xserver: Branch 'transform-proposal' - 243 commits

Keith Packard keithp at kemper.freedesktop.org
Sun May 4 22:26:21 PDT 2008


 .gitignore                                                |    6 
 GL/Makefile.am                                            |    7 
 GL/apple/Makefile.am                                      |   24 
 GL/apple/aglGlx.c                                         | 1354 --------
 GL/apple/indirect.c                                       | 1938 ------------
 GL/glx/Makefile.am                                        |    7 
 GL/glx/glxcmds.c                                          |   58 
 GL/glx/glxcontext.h                                       |    6 
 GL/glx/glxdrawable.h                                      |    2 
 GL/glx/glxdri.c                                           |  259 -
 GL/glx/glxdri2.c                                          |  423 +-
 GL/glx/glxext.c                                           |    2 
 GL/glx/glxglcore.c                                        |  138 
 GL/glx/glxscreens.c                                       |   66 
 GL/glx/glxscreens.h                                       |   88 
 GL/glx/glxutil.c                                          |   63 
 GL/glx/glxutil.h                                          |    2 
 GL/mesa/.gitignore                                        |   32 
 GL/mesa/Makefile.am                                       |   18 
 GL/mesa/X/Makefile.am                                     |   27 
 GL/mesa/glapi/Makefile.am                                 |   20 
 GL/mesa/main/Makefile.am                                  |   86 
 GL/mesa/math/Makefile.am                                  |   27 
 GL/mesa/shader/Makefile.am                                |   39 
 GL/mesa/shader/grammar/Makefile.am                        |   20 
 GL/mesa/shader/slang/Makefile.am                          |   41 
 GL/mesa/swrast/Makefile.am                                |   50 
 GL/mesa/swrast_setup/Makefile.am                          |   20 
 GL/mesa/tnl/Makefile.am                                   |   37 
 GL/mesa/vbo/Makefile.am                                   |   35 
 GL/symlink-mesa.sh                                        |  164 -
 Makefile.am                                               |   15 
 Xext/EVI.c                                                |  200 -
 Xext/EVIstruct.h                                          |   58 
 Xext/Makefile.am                                          |   23 
 Xext/appgroup.c                                           |  775 ----
 Xext/appgroup.h                                           |   67 
 Xext/cup.c                                                |  342 --
 Xext/dpms.c                                               |    7 
 Xext/mitmisc.c                                            |  155 
 Xext/sampleEVI.c                                          |  123 
 Xext/security.c                                           |    8 
 Xext/xevie.c                                              |  122 
 Xext/xres.c                                               |    2 
 Xext/xselinux.c                                           |   96 
 Xext/xselinux.h                                           |    1 
 Xi/exevents.c                                             |    2 
 acinclude.m4                                              |  172 -
 cfb/Makefile.am                                           |   21 
 cfb/Makefile.am.inc                                       |  153 
 cfb/cfb.h                                                 | 1268 -------
 cfb/cfb16.h                                               |   93 
 cfb/cfb24.h                                               |   97 
 cfb/cfb32.h                                               |   93 
 cfb/cfb8bit.c                                             |  469 --
 cfb/cfb8bit.h                                             | 1570 ---------
 cfb/cfb8line.c                                            | 1503 ---------
 cfb/cfballpriv.c                                          |   70 
 cfb/cfbbitblt.c                                           | 1455 ---------
 cfb/cfbblt.c                                              |  933 -----
 cfb/cfbbres.c                                             |  340 --
 cfb/cfbbresd.c                                            |  404 --
 cfb/cfbcmap.c                                             |  119 
 cfb/cfbcppl.c                                             |  486 ---
 cfb/cfbfillarc.c                                          |  374 --
 cfb/cfbfillrct.c                                          |  305 -
 cfb/cfbfillsp.c                                           | 1004 ------
 cfb/cfbgc.c                                               |  799 ----
 cfb/cfbgetsp.c                                            |  213 -
 cfb/cfbglblt8.c                                           |  477 --
 cfb/cfbhrzvert.c                                          |  554 ---
 cfb/cfbigblt8.c                                           |  106 
 cfb/cfbimage.c                                            |  206 -
 cfb/cfbline.c                                             |  756 ----
 cfb/cfbmap.h                                              |  210 -
 cfb/cfbmskbits.c                                          | 1400 --------
 cfb/cfbmskbits.h                                          |  854 -----
 cfb/cfbpixmap.c                                           |  375 --
 cfb/cfbply1rct.c                                          |  363 --
 cfb/cfbpolypnt.c                                          |  202 -
 cfb/cfbpush8.c                                            |  184 -
 cfb/cfbrctstp8.c                                          |  593 ---
 cfb/cfbrrop.c                                             |  227 -
 cfb/cfbrrop.h                                             |  343 --
 cfb/cfbscrinit.c                                          |  223 -
 cfb/cfbsetsp.c                                            |  316 -
 cfb/cfbsolid.c                                            | 1365 --------
 cfb/cfbteblt8.c                                           |  589 ---
 cfb/cfbtegblt.c                                           |  218 -
 cfb/cfbtile32.c                                           |  517 ---
 cfb/cfbtileodd.c                                          | 1245 -------
 cfb/cfbunmap.h                                            |  161 -
 cfb/cfbwindow.c                                           |  160 
 cfb/cfbzerarc.c                                           |  322 --
 cfb/stip68kgnu.h                                          |  121 
 cfb/stipmips.s                                            |  281 -
 cfb/stipsparc.s                                           |  290 -
 cfb/stipsprc32.s                                          |  291 -
 cfb32/Makefile.am                                         |    9 
 composite/Makefile.am                                     |    1 
 composite/compext.c                                       |  193 -
 composite/compinit.c                                      |   13 
 composite/compint.h                                       |   24 
 composite/compoverlay.c                                   |  159 
 config/hal.c                                              |  194 -
 config/x11-input.fdi                                      |   62 
 configure.ac                                              |  225 -
 dix/Makefile.am                                           |   14 
 dix/devices.c                                             |    6 
 dix/dispatch.c                                            |    9 
 dix/dixutils.c                                            |    3 
 dix/events.c                                              |    7 
 dix/getevents.c                                           |   14 
 dix/main.c                                                |   19 
 dix/window.c                                              |   70 
 exa/Makefile.am                                           |    1 
 exa/exa.c                                                 |  133 
 exa/exa.h                                                 |    4 
 exa/exa_accel.c                                           |   32 
 exa/exa_glyphs.c                                          |  897 +++++
 exa/exa_offscreen.c                                       |  161 -
 exa/exa_priv.h                                            |   60 
 exa/exa_render.c                                          |  238 +
 fb/Makefile.am                                            |    6 
 fb/fb.h                                                   |    2 
 fb/fbpseudocolor.c                                        | 2248 --------------
 fb/fbpseudocolor.h                                        |   20 
 fb/wfbrename.h                                            |    8 
 hw/dmx/dmx-config.h                                       |    2 
 hw/dmx/dmxextension.c                                     |    1 
 hw/kdrive/Makefile.am                                     |    4 
 hw/kdrive/ati/Makefile.am                                 |    4 
 hw/kdrive/chips/Makefile.am                               |    4 
 hw/kdrive/ephyr/GL/internal/dri_interface.h               |  517 ---
 hw/kdrive/ephyr/Makefile.am                               |  107 
 hw/kdrive/ephyr/XF86dri.c                                 |    7 
 hw/kdrive/ephyr/ephyr.c                                   |   31 
 hw/kdrive/ephyr/ephyr.h                                   |    1 
 hw/kdrive/ephyr/ephyr_draw.c                              |    1 
 hw/kdrive/ephyr/ephyrdri.c                                |    7 
 hw/kdrive/ephyr/ephyrdriext.c                             |    4 
 hw/kdrive/ephyr/ephyrglxext.c                             |    5 
 hw/kdrive/ephyr/ephyrhostglx.c                            |    4 
 hw/kdrive/ephyr/ephyrinit.c                               |   19 
 hw/kdrive/ephyr/ephyrlog.h                                |    4 
 hw/kdrive/ephyr/hostx.c                                   |   39 
 hw/kdrive/ephyr/hostx.h                                   |    7 
 hw/kdrive/ephyr/xf86dri.h                                 |  120 
 hw/kdrive/epson/Makefile.am                               |    4 
 hw/kdrive/fake/Makefile.am                                |    4 
 hw/kdrive/fbdev/Makefile.am                               |    4 
 hw/kdrive/fbdev/fbdev.c                                   |   26 
 hw/kdrive/i810/Makefile.am                                |    4 
 hw/kdrive/linux/keyboard.c                                |   26 
 hw/kdrive/linux/tslib.c                                   |    4 
 hw/kdrive/mach64/Makefile.am                              |    4 
 hw/kdrive/mga/Makefile.am                                 |    4 
 hw/kdrive/neomagic/Makefile.am                            |    4 
 hw/kdrive/nvidia/Makefile.am                              |    4 
 hw/kdrive/pm2/Makefile.am                                 |    4 
 hw/kdrive/r128/Makefile.am                                |    4 
 hw/kdrive/sdl/Makefile.am                                 |    4 
 hw/kdrive/sis300/Makefile.am                              |    4 
 hw/kdrive/smi/Makefile.am                                 |    4 
 hw/kdrive/src/kinput.c                                    |    4 
 hw/kdrive/vesa/Makefile.am                                |    4 
 hw/kdrive/via/Makefile.am                                 |    4 
 hw/xfree86/Makefile.am                                    |    8 
 hw/xfree86/common/compiler.h                              |    6 
 hw/xfree86/common/xf86.h                                  |    1 
 hw/xfree86/common/xf86AutoConfig.c                        |  154 
 hw/xfree86/common/xf86Bus.c                               |    4 
 hw/xfree86/common/xf86Config.c                            |   40 
 hw/xfree86/common/xf86Init.c                              |   60 
 hw/xfree86/common/xf86Privstr.h                           |    3 
 hw/xfree86/common/xf86Xinput.c                            |   30 
 hw/xfree86/ddc/xf86DDC.c                                  |  241 -
 hw/xfree86/ddc/xf86DDC.h                                  |    2 
 hw/xfree86/dixmods/GLcoremodule.c                         |   63 
 hw/xfree86/dixmods/Makefile.am                            |   25 
 hw/xfree86/dixmods/cfb32module.c                          |   57 
 hw/xfree86/dixmods/cfbmodule.c                            |   57 
 hw/xfree86/dixmods/extmod/Makefile.am                     |    1 
 hw/xfree86/dixmods/extmod/modinit.c                       |   50 
 hw/xfree86/dixmods/extmod/modinit.h                       |   26 
 hw/xfree86/dixmods/glxmodule.c                            |   37 
 hw/xfree86/doc/man/xorg.conf.man.pre                      |    8 
 hw/xfree86/dri/Makefile.am                                |    2 
 hw/xfree86/dri/dri.c                                      |    2 
 hw/xfree86/dri2/Makefile.am                               |    5 
 hw/xfree86/dri2/dri2.c                                    |  107 
 hw/xfree86/dri2/dri2.h                                    |   16 
 hw/xfree86/dri2/dri2ext.c                                 |  361 ++
 hw/xfree86/exa/examodule.c                                |   13 
 hw/xfree86/int10/helper_exec.c                            |    2 
 hw/xfree86/loader/dixsym.c                                |   15 
 hw/xfree86/loader/loader.c                                |    2 
 hw/xfree86/loader/xf86sym.c                               |    3 
 hw/xfree86/modes/xf86Crtc.h                               |    6 
 hw/xfree86/modes/xf86Cursors.c                            |    3 
 hw/xfree86/modes/xf86EdidModes.c                          |   25 
 hw/xfree86/modes/xf86Rotate.c                             |   33 
 hw/xfree86/os-support/bsd/Makefile.am                     |    1 
 hw/xfree86/os-support/bsd/bsdResource.c                   |    2 
 hw/xfree86/os-support/bsd/bsd_jstk.c                      |  183 -
 hw/xfree86/os-support/bsd/i386_video.c                    |    8 
 hw/xfree86/os-support/bus/Pci.h                           |    8 
 hw/xfree86/os-support/linux/Makefile.am                   |    1 
 hw/xfree86/os-support/linux/lnxResource.c                 |    1 
 hw/xfree86/os-support/linux/lnx_jstk.c                    |  180 -
 hw/xfree86/os-support/linux/lnx_video.c                   |    4 
 hw/xfree86/utils/xorgcfg/expert.c                         |   50 
 hw/xfree86/utils/xorgcfg/loadmod.c                        |    4 
 hw/xfree86/x86emu/prim_ops.c                              |    2 
 hw/xfree86/x86emu/x86emu/prim_x86_gcc.h                   |    2 
 hw/xfree86/x86emu/x86emu/types.h                          |    2 
 hw/xfree86/xaa/xaaInitAccel.c                             |   57 
 hw/xfree86/xf8_32bpp/Makefile.am                          |   37 
 hw/xfree86/xf8_32bpp/cfb8_32.h                            |  191 -
 hw/xfree86/xf8_32bpp/cfb8_32module.c                      |   39 
 hw/xfree86/xf8_32bpp/cfbcpyarea.c                         |  549 ---
 hw/xfree86/xf8_32bpp/cfbcpyplane.c                        |   41 
 hw/xfree86/xf8_32bpp/cfbgc.c                              |  646 ----
 hw/xfree86/xf8_32bpp/cfbgcmisc.c                          |  150 
 hw/xfree86/xf8_32bpp/cfbgcunder.c                         |  620 ---
 hw/xfree86/xf8_32bpp/cfbimage.c                           |  174 -
 hw/xfree86/xf8_32bpp/cfbpntwin.c                          |   51 
 hw/xfree86/xf8_32bpp/cfbscrinit.c                         |  311 -
 hw/xfree86/xf8_32bpp/cfbwindow.c                          |  116 
 hw/xfree86/xf8_32bpp/xf86overlay.c                        | 1179 -------
 hw/xgl/egl/kinput.c                                       |    4 
 hw/xnest/Args.c                                           |    5 
 hw/xprint/Makefile.am                                     |    3 
 hw/xprint/ps/psout.h                                      |    2 
 hw/xquartz/GL/Makefile.am                                 |   13 
 hw/xquartz/GL/indirect.c                                  | 1940 ++++++++++++
 hw/xquartz/Makefile.am                                    |   17 
 hw/xquartz/X11Application.h                               |    9 
 hw/xquartz/X11Application.m                               |  567 +--
 hw/xquartz/X11Controller.h                                |   12 
 hw/xquartz/X11Controller.m                                |  173 -
 hw/xquartz/applewm.c                                      |    2 
 hw/xquartz/bundle/English.lproj/Localizable.strings       |binary
 hw/xquartz/bundle/English.lproj/main.nib/designable.nib   |  502 ++-
 hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib |binary
 hw/xquartz/darwin.c                                       |  117 
 hw/xquartz/darwin.h                                       |   44 
 hw/xquartz/darwinEvents.c                                 |  619 ++-
 hw/xquartz/darwinEvents.h                                 |   43 
 hw/xquartz/darwinKeyboard.c                               | 1009 ------
 hw/xquartz/darwinKeyboard.h                               |   45 
 hw/xquartz/darwinXinput.c                                 |  200 -
 hw/xquartz/pseudoramiX.c                                  |   37 
 hw/xquartz/quartz.c                                       |  162 -
 hw/xquartz/quartz.h                                       |    6 
 hw/xquartz/quartzAudio.c                                  |    2 
 hw/xquartz/quartzCocoa.m                                  |    9 
 hw/xquartz/quartzCommon.h                                 |   25 
 hw/xquartz/quartzCursor.c                                 |  646 ----
 hw/xquartz/quartzCursor.h                                 |   42 
 hw/xquartz/quartzForeground.c                             |    2 
 hw/xquartz/quartzKeyboard.c                               | 1010 ++++++
 hw/xquartz/quartzKeyboard.h                               |   16 
 hw/xquartz/quartzPasteboard.c                             |   10 
 hw/xquartz/quartzPasteboard.h                             |    4 
 hw/xquartz/quartzStartup.c                                |   99 
 hw/xquartz/sanitizedCarbon.h                              |   32 
 hw/xquartz/sanitizedCocoa.h                               |   27 
 hw/xquartz/threadSafety.c                                 |   70 
 hw/xquartz/threadSafety.h                                 |   56 
 hw/xquartz/xpr/Makefile.am                                |   29 
 hw/xquartz/xpr/dri.h                                      |    2 
 hw/xquartz/xpr/xpr.h                                      |    3 
 hw/xquartz/xpr/xprAppleWM.c                               |    2 
 hw/xquartz/xpr/xprCursor.c                                |    8 
 hw/xquartz/xpr/xprEvent.c                                 |   91 
 hw/xquartz/xpr/xprEvent.h                                 |   34 
 hw/xquartz/xpr/xprFrame.c                                 |   43 
 hw/xquartz/xpr/xprScreen.c                                |   85 
 include/dix-config.h.in                                   |   20 
 include/dixstruct.h                                       |    4 
 include/globals.h                                         |   26 
 include/servermd.h                                        |   32 
 include/windowstr.h                                       |    3 
 include/xkbsrv.h                                          |   16 
 include/xorg-server.h.in                                  |    6 
 mi/micoord.h                                              |    2 
 mi/miinitext.c                                            |   63 
 mi/mivaltree.c                                            |    4 
 miext/rootless/Makefile.am                                |    2 
 miext/rootless/README.txt                                 |    4 
 miext/rootless/accel/Makefile.am                          |   15 
 miext/rootless/accel/rlAccel.c                            |  147 
 miext/rootless/accel/rlAccel.h                            |  140 
 miext/rootless/accel/rlBlt.c                              |  408 --
 miext/rootless/accel/rlCopy.c                             |  106 
 miext/rootless/accel/rlFill.c                             |  220 -
 miext/rootless/accel/rlFillRect.c                         |  117 
 miext/rootless/accel/rlFillSpans.c                        |  105 
 miext/rootless/accel/rlGlyph.c                            |  169 -
 miext/rootless/accel/rlSolid.c                            |  111 
 miext/rootless/rootlessConfig.h                           |    3 
 miext/rootless/rootlessGC.c                               |    8 
 miext/rootless/rootlessWindow.c                           |   72 
 miext/rootless/rootlessWindow.h                           |    4 
 miext/rootless/safeAlpha/Makefile.am                      |    7 
 miext/rootless/safeAlpha/safeAlpha.h                      |   42 
 miext/rootless/safeAlpha/safeAlphaPicture.c               |  211 -
 os/WaitFor.c                                              |    6 
 os/connection.c                                           |    3 
 os/utils.c                                                |   19 
 render/matrix.c                                           |    7 
 render/picturestr.h                                       |    2 
 xkb/ddxLoad.c                                             |    6 
 xkb/xkbActions.c                                          |   11 
 xorg-server.pc.in                                         |    2 
 316 files changed, 9288 insertions(+), 44575 deletions(-)

New commits:
commit 33e5a176e62a0114cb8cca9447798c6d6b6665ed
Merge: e48f6bc... efa65a0...
Author: Keith Packard <keithp at keithp.com>
Date:   Sun May 4 22:24:56 2008 -0700

    Merge commit 'origin/master' into transform-proposal-old
    
    Conflicts:
    
    	configure.ac
    	exa/exa.c

diff --cc configure.ac
index 07a334c,f695551..8abebfe
--- a/configure.ac
+++ b/configure.ac
@@@ -1971,13 -1938,10 +1938,10 @@@ if test "$KDRIVE" = yes; the
  	    ;;
      esac
      KDRIVE_STUB_LIB='$(top_builddir)/hw/kdrive/src/libkdrivestubs.a'
-     KDRIVE_LOCAL_LIBS="$TSLIB_LIBS $DIX_LIB $KDRIVE_LIB $KDRIVE_STUB_LIB $CONFIG_LIB"
+     KDRIVE_LOCAL_LIBS="$DIX_LIB $KDRIVE_LIB $KDRIVE_STUB_LIB $CONFIG_LIB"
      KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $FB_LIB $MI_LIB $KDRIVE_PURE_LIBS"
 -    KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB"
 +    KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB $XEXT_LIB"
-     KDRIVE_LIBS="$KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS"
- 
-     # check if we can build Xephyr
-     PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS, [xephyr="yes"], [xephyr="no"])
+     KDRIVE_LIBS="$TSLIB_LIBS $KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS $GLX_SYS_LIBS"
  
      AC_SUBST([XEPHYR_LIBS])
      AC_SUBST([XEPHYR_INCS])
diff --cc exa/exa.c
index baa9e94,809fb4b..0852334
--- a/exa/exa.c
+++ b/exa/exa.c
@@@ -699,8 -754,9 +754,10 @@@ exaCloseScreen(int i, ScreenPtr pScreen
  #ifdef RENDER
      if (ps) {
  	ps->Composite = pExaScr->SavedComposite;
+ 	ps->Glyphs = pExaScr->SavedGlyphs;
  	ps->Trapezoids = pExaScr->SavedTrapezoids;
 +	ps->AddTraps = pExaScr->SavedAddTraps;
+ 	ps->Triangles = pExaScr->SavedTriangles;
      }
  #endif
  
diff --cc hw/xfree86/modes/xf86Crtc.h
index 6d7a9b1,83b1f13..4d4d967
--- a/hw/xfree86/modes/xf86Crtc.h
+++ b/hw/xfree86/modes/xf86Crtc.h
@@@ -677,9 -662,15 +677,15 @@@ xf86CrtcSetMode (xf86CrtcPtr crtc, Disp
   * Assign crtc rotation during mode set
   */
  Bool
 -xf86CrtcRotate (xf86CrtcPtr crtc, DisplayModePtr mode, Rotation rotation);
 +xf86CrtcRotate (xf86CrtcPtr crtc);
  
  /*
+  * free shadow memory allocated for all crtcs
+  */
+ void
+ xf86RotateFreeShadow(ScrnInfoPtr pScrn);
+ 
+ /*
   * Clean up rotation during CloseScreen
   */
  void
commit efa65a0317e12c9ad34fa00fe90bf5eae9fa2670
Author: Keith Packard <keithp at keithp.com>
Date:   Sun May 4 21:52:58 2008 -0700

    Rework composite overlay window code to fix several resource management bugs.
    
    The composite overlay window code had several misunderstandings of the
    workings of the X server, in particular error handling paths would often
    double-free objects. Clean all of this up by using resource destruction as
    the sole mechanism for freeing resource-based objects.

diff --git a/composite/Makefile.am b/composite/Makefile.am
index 21504e6..d7bead1 100644
--- a/composite/Makefile.am
+++ b/composite/Makefile.am
@@ -7,4 +7,5 @@ libcomposite_la_SOURCES = 	\
 	compext.c		\
 	compint.h		\
 	compinit.c		\
+	compoverlay.c		\
 	compwindow.c		
diff --git a/composite/compext.c b/composite/compext.c
index b3433f7..e720f6c 100644
--- a/composite/compext.c
+++ b/composite/compext.c
@@ -54,10 +54,7 @@ static CARD8	CompositeReqCode;
 static DevPrivateKey CompositeClientPrivateKey = &CompositeClientPrivateKey;
 RESTYPE		CompositeClientWindowType;
 RESTYPE		CompositeClientSubwindowsType;
-static RESTYPE	CompositeClientOverlayType;
-
-static void deleteCompOverlayClient (CompOverlayClientPtr pOcToDel, 
-				     ScreenPtr pScreen);
+RESTYPE		CompositeClientOverlayType;
 
 typedef struct _CompositeClient {
     int	    major_version;
@@ -107,19 +104,8 @@ static int
 FreeCompositeClientOverlay (pointer value, XID ccwid)
 {
     CompOverlayClientPtr pOc = (CompOverlayClientPtr) value;
-    ScreenPtr pScreen = pOc->pScreen;
-    CompScreenPtr cs;
-
-    deleteCompOverlayClient(pOc, pScreen);
-
-    /* Unmap overlay window when there are no more clients using it */
-    cs = GetCompScreen(pScreen);
-    if (cs->pOverlayClients == NULL) {
-	if (cs->pOverlayWin != NULL) {
-	    UnmapWindow(cs->pOverlayWin, FALSE);
-	}
-    }
 
+    compFreeOverlayClient (pOc);
     return Success;
 }
 
@@ -304,137 +290,6 @@ ProcCompositeNameWindowPixmap (ClientPtr client)
 }
 
 
-/*
- * Routines for manipulating the per-screen overlay clients list.
- * This list indicates which clients have called GetOverlayWindow
- * for this screen.
- */
-
-/* Return the screen's overlay client list element for the given client */
-static CompOverlayClientPtr
-findCompOverlayClient (ClientPtr pClient, ScreenPtr pScreen) 
-{
-    CompScreenPtr    cs = GetCompScreen(pScreen);
-    CompOverlayClientPtr pOc;
-
-    for (pOc = cs->pOverlayClients; pOc != NULL; pOc = pOc->pNext) {
-	if (pOc->pClient == pClient) {
-	    return pOc;
-	}
-    }
-
-    return NULL;           
-}
-
-static int
-createCompOverlayClient (ClientPtr pClient, ScreenPtr pScreen)
-{
-    CompScreenPtr    cs = GetCompScreen(pScreen);
-    CompOverlayClientPtr pOc;
-
-    pOc = (CompOverlayClientPtr) xalloc(sizeof(CompOverlayClientRec));
-    if (pOc == NULL) {
-	return BadAlloc;
-    }
-    pOc->pClient = pClient;
-    pOc->pScreen = pScreen;
-    pOc->resource = FakeClientID(pClient->index);
-    pOc->pNext = cs->pOverlayClients;
-    cs->pOverlayClients = pOc;
-
-    /* 
-     * Create a resource for this element so it can be deleted
-     * when the client goes away.
-     */
-    if (!AddResource (pOc->resource, CompositeClientOverlayType, 
-		      (pointer) pOc)) {
-	xfree(pOc);
-	return BadAlloc;
-    }
-
-    return Success;
-}
-
-/* 
- * Delete the given overlay client list element from its screen list.
- */
-static void
-deleteCompOverlayClient (CompOverlayClientPtr pOcToDel, ScreenPtr pScreen)
-{
-    CompScreenPtr    cs = GetCompScreen(pScreen);
-    CompOverlayClientPtr pOc, pNext;
-    CompOverlayClientPtr pOcLast = NULL;
-
-    pOc = cs->pOverlayClients;
-    while (pOc != NULL) {
-	pNext = pOc->pNext;
-	if (pOc == pOcToDel) {
-	    xfree(pOc);
-	    if (pOcLast == NULL) {
-		cs->pOverlayClients = pNext;
-	    } else {
-		pOcLast->pNext = pNext;
-	    }
-	    break;
-	}
-	pOcLast = pOc;
-	pOc = pNext;
-    }
-}
-
-/* 
- * Delete all the hide-counts list elements for this screen.
- */
-void
-deleteCompOverlayClientsForScreen (ScreenPtr pScreen)
-{
-    CompScreenPtr    cs = GetCompScreen(pScreen);
-    CompOverlayClientPtr pOc, pTmp;
-
-    pOc = cs->pOverlayClients;
-    while (pOc != NULL) {
-	pTmp = pOc->pNext;
-	FreeResource(pOc->resource, 0);
-	pOc = pTmp;
-    }
-    cs->pOverlayClients = NULL;
-}
-
-/* 
-** If necessary, create the overlay window. And map it 
-** Note: I found it excessively difficult to destroy this window
-** during compCloseScreen; DeleteWindow can't be called because
-** the input devices are already shut down. So we are going to 
-** just allocate an overlay window once per screen per X server
-** invocation.
-*/
-
-static WindowPtr
-createOverlayWindow (ScreenPtr pScreen)
-{
-    int wid = FakeClientID(0);
-    WindowPtr pWin;
-    XID overrideRedirect = TRUE;
-    int result;
-
-    pWin = CreateWindow (
-	        wid, WindowTable[pScreen->myNum],
-    	        0, 0, pScreen->width, pScreen->height, 0, 
-	        InputOutput, CWOverrideRedirect, &overrideRedirect,
-	        WindowTable[pScreen->myNum]->drawable.depth, 
-	        serverClient, pScreen->rootVisual, &result);
-    if (pWin == NULL) {
-	return NULL;
-    }
-
-    if (!AddResource(wid, RT_WINDOW, (pointer)pWin)) {
-	DeleteWindow(pWin, None);
-	return NULL;
-    }
-
-    return pWin;
-}
-
 static int
 ProcCompositeGetOverlayWindow (ClientPtr client)
 {
@@ -456,28 +311,31 @@ ProcCompositeGetOverlayWindow (ClientPtr client)
     }
     pScreen = pWin->drawable.pScreen;
 
+    /* 
+     * Create an OverlayClient structure to mark this client's
+     * interest in the overlay window
+     */
+    pOc = compCreateOverlayClient(pScreen, client);
+    if (pOc == NULL)
+	return BadAlloc;
+
+    /*
+     * Make sure the overlay window exists
+     */
     cs = GetCompScreen(pScreen);
-    if (cs->pOverlayWin == NULL) {
-	cs->pOverlayWin = createOverlayWindow(pScreen);
-	if (cs->pOverlayWin == NULL) {
+    if (cs->pOverlayWin == NULL)
+	if (!compCreateOverlayWindow(pScreen))
+	{
+	    FreeResource (pOc->resource, RT_NONE);
 	    return BadAlloc;
 	}
-    }
 
     rc = XaceHook(XACE_RESOURCE_ACCESS, client, cs->pOverlayWin->drawable.id,
 		  RT_WINDOW, cs->pOverlayWin, RT_NONE, NULL, DixGetAttrAccess);
     if (rc != Success)
+    {
+	FreeResource (pOc->resource, RT_NONE);
 	return rc;
-
-    MapWindow(cs->pOverlayWin, serverClient);
-
-    /* Record that client is using this overlay window */
-    pOc = findCompOverlayClient(client, pScreen);
-    if (pOc == NULL) {
-	int ret = createCompOverlayClient(client, pScreen);
-	if (ret != Success) {
-	    return ret;
-	}
     }
 
     rep.type = X_Reply;
@@ -504,7 +362,6 @@ ProcCompositeReleaseOverlayWindow (ClientPtr client)
     WindowPtr pWin;
     ScreenPtr pScreen;
     CompOverlayClientPtr pOc;
-    CompScreenPtr cs;
 
     REQUEST_SIZE_MATCH(xCompositeReleaseOverlayWindowReq);
     pWin = (WindowPtr) LookupIDByType (stuff->window, RT_WINDOW);
@@ -519,18 +376,12 @@ ProcCompositeReleaseOverlayWindow (ClientPtr client)
      * Has client queried a reference to the overlay window
      * on this screen? If not, generate an error.
      */
-    pOc = findCompOverlayClient(client, pWin->drawable.pScreen);
-    if (pOc == NULL) {
+    pOc = compFindOverlayClient (pWin->drawable.pScreen, client);
+    if (pOc == NULL)
 	return BadMatch;
-    }
 
     /* The delete function will free the client structure */
-    FreeResource (pOc->resource, 0);
-
-    cs = GetCompScreen(pScreen);
-    if (cs->pOverlayClients == NULL) {
-	UnmapWindow(cs->pOverlayWin, FALSE);
-    }
+    FreeResource (pOc->resource, RT_NONE);
 
     return client->noClientException;
 }
diff --git a/composite/compinit.c b/composite/compinit.c
index 49b2044..7914a8d 100644
--- a/composite/compinit.c
+++ b/composite/compinit.c
@@ -76,14 +76,6 @@ compCloseScreen (int index, ScreenPtr pScreen)
     pScreen->CopyWindow = cs->CopyWindow;
     pScreen->PositionWindow = cs->PositionWindow;
 
-    deleteCompOverlayClientsForScreen(pScreen);
-
-    /* 
-    ** Note: no need to call DeleteWindow; the server has
-    ** already destroyed it.
-    */
-    cs->pOverlayWin = NULL;
-
     xfree (cs);
     dixSetPrivate(&pScreen->devPrivates, CompScreenPrivateKey, NULL);
     ret = (*pScreen->CloseScreen) (index, pScreen);
@@ -122,11 +114,11 @@ compChangeWindowAttributes(WindowPtr pWin, unsigned long mask)
     if (ret && (mask & CWBackingStore)) {
 	if (pWin->backingStore != NotUseful) {
 	    compRedirectWindow(serverClient, pWin, CompositeRedirectAutomatic);
-	    pWin->backStorage = TRUE;
+	    pWin->backStorage = (pointer) (intptr_t) 1;
 	} else {
 	    compUnredirectWindow(serverClient, pWin,
 				 CompositeRedirectAutomatic);
-	    pWin->backStorage = FALSE;
+	    pWin->backStorage = NULL;
 	}
     }
 
@@ -380,6 +372,7 @@ compScreenInit (ScreenPtr pScreen)
 	return FALSE;
 
     cs->damaged = FALSE;
+    cs->overlayWid = FakeClientID(0);
     cs->pOverlayWin = NULL;
     cs->pOverlayClients = NULL;
 
diff --git a/composite/compint.h b/composite/compint.h
index 4b0fe08..1c19ccd 100644
--- a/composite/compint.h
+++ b/composite/compint.h
@@ -155,6 +155,7 @@ typedef struct _CompScreen {
     VisualID			*alternateVisuals;
 
     WindowPtr                   pOverlayWin;
+    Window			overlayWid;
     CompOverlayClientPtr        pOverlayClients;
     
 } CompScreenRec, *CompScreenPtr;
@@ -172,6 +173,7 @@ extern DevPrivateKey CompSubwindowsPrivateKey;
 
 extern RESTYPE		CompositeClientWindowType;
 extern RESTYPE		CompositeClientSubwindowsType;
+extern RESTYPE		CompositeClientOverlayType;
 
 /*
  * compalloc.c
@@ -230,6 +232,25 @@ Bool
 compScreenInit (ScreenPtr pScreen);
 
 /*
+ * compoverlay.c
+ */
+
+void
+compFreeOverlayClient (CompOverlayClientPtr pOcToDel);
+
+CompOverlayClientPtr
+compFindOverlayClient (ScreenPtr pScreen, ClientPtr pClient);
+    
+CompOverlayClientPtr
+compCreateOverlayClient (ScreenPtr pScreen, ClientPtr pClient);
+
+Bool
+compCreateOverlayWindow (ScreenPtr pScreen);
+
+void
+compDestroyOverlayWindow (ScreenPtr pScreen);
+
+/*
  * compwindow.c
  */
 
@@ -292,9 +313,6 @@ compCopyWindow (WindowPtr pWin, DDXPointRec ptOldOrg, RegionPtr prgnSrc);
 void
 compWindowUpdate (WindowPtr pWin);
 
-void
-deleteCompOverlayClientsForScreen (ScreenPtr pScreen);
-
 WindowPtr
 CompositeRealChildHead (WindowPtr pWin);
 
diff --git a/composite/compoverlay.c b/composite/compoverlay.c
new file mode 100644
index 0000000..94e5b03
--- /dev/null
+++ b/composite/compoverlay.c
@@ -0,0 +1,159 @@
+/*
+ * Copyright © 2006 Sun Microsystems
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and its
+ * documentation for any purpose is hereby granted without fee, provided that
+ * the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of Sun Microsystems not be used in
+ * advertising or publicity pertaining to distribution of the software without
+ * specific, written prior permission.  Sun Microsystems makes no
+ * representations about the suitability of this software for any purpose.  It
+ * is provided "as is" without express or implied warranty.
+ *
+ * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+ * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Copyright © 2003 Keith Packard
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and its
+ * documentation for any purpose is hereby granted without fee, provided that
+ * the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of Keith Packard not be used in
+ * advertising or publicity pertaining to distribution of the software without
+ * specific, written prior permission.  Keith Packard makes no
+ * representations about the suitability of this software for any purpose.  It
+ * is provided "as is" without express or implied warranty.
+ *
+ * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+ * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include "compint.h"
+#include "xace.h"
+
+/* 
+ * Delete the given overlay client list element from its screen list.
+ */
+void
+compFreeOverlayClient (CompOverlayClientPtr pOcToDel)
+{
+    ScreenPtr		    pScreen = pOcToDel->pScreen;
+    CompScreenPtr	    cs = GetCompScreen (pScreen);
+    CompOverlayClientPtr    *pPrev, pOc;
+
+    for (pPrev = &cs->pOverlayClients; (pOc = *pPrev); pPrev = &pOc->pNext)
+    {
+	if (pOc == pOcToDel) {
+	    *pPrev = pOc->pNext;
+	    xfree (pOc);
+	    break;
+	}
+    }
+    
+    /* Destroy overlay window when there are no more clients using it */
+    if (cs->pOverlayClients == NULL)
+	compDestroyOverlayWindow (pScreen);
+}
+
+/*
+ * Return the client's first overlay client rec from the given screen
+ */
+CompOverlayClientPtr
+compFindOverlayClient (ScreenPtr pScreen, ClientPtr pClient)
+{
+    CompScreenPtr	    cs = GetCompScreen(pScreen);
+    CompOverlayClientPtr    pOc;
+
+    for (pOc = cs->pOverlayClients; pOc != NULL; pOc = pOc->pNext)
+	if (pOc->pClient == pClient)
+	    return pOc;
+
+    return NULL;           
+}
+
+/*
+ * Create an overlay client object for the given client
+ */
+CompOverlayClientPtr
+compCreateOverlayClient (ScreenPtr pScreen, ClientPtr pClient)
+{
+    CompScreenPtr    cs = GetCompScreen(pScreen);
+    CompOverlayClientPtr pOc;
+
+    pOc = (CompOverlayClientPtr) xalloc(sizeof(CompOverlayClientRec));
+    if (pOc == NULL)
+	return NULL;
+
+    pOc->pClient = pClient;
+    pOc->pScreen = pScreen;
+    pOc->resource = FakeClientID(pClient->index);
+    pOc->pNext = cs->pOverlayClients;
+    cs->pOverlayClients = pOc;
+
+    /* 
+     * Create a resource for this element so it can be deleted
+     * when the client goes away.
+     */
+    if (!AddResource (pOc->resource, CompositeClientOverlayType, (pointer) pOc))
+	return NULL;
+
+    return pOc;
+}
+
+/*
+ * Create the overlay window and map it
+ */
+Bool
+compCreateOverlayWindow (ScreenPtr pScreen)
+{
+    CompScreenPtr   cs = GetCompScreen(pScreen);
+    WindowPtr	    pRoot = WindowTable[pScreen->myNum];
+    WindowPtr	    pWin;
+    XID		    overrideRedirect = TRUE;
+    int		    result;
+
+    pWin = cs->pOverlayWin = 
+	CreateWindow (cs->overlayWid, pRoot,
+		      0, 0, pScreen->width, pScreen->height, 0, 
+		      InputOutput, CWOverrideRedirect, &overrideRedirect,
+		      pRoot->drawable.depth, 
+		      serverClient, pScreen->rootVisual, &result);
+    if (pWin == NULL)
+	return FALSE;
+
+    if (!AddResource(pWin->drawable.id, RT_WINDOW, (pointer)pWin))
+	return FALSE;
+
+    MapWindow(pWin, serverClient);
+
+    return TRUE;
+}
+
+/*
+ * Destroy the overlay window
+ */
+void
+compDestroyOverlayWindow (ScreenPtr pScreen)
+{
+    CompScreenPtr cs = GetCompScreen(pScreen);
+
+    cs->pOverlayWin = NullWindow;
+    FreeResource (cs->overlayWid, RT_NONE);
+}
+
commit 6c1accce87c9bd640c1b4bbc49bae7d44b1cc97b
Author: Keith Packard <keithp at keithp.com>
Date:   Sun May 4 21:51:08 2008 -0700

    Empty the borderClip of manual redirect windows. (bug 15823)
    
    Thanks to Owen Taylor for root-causing this one.
    
    If a TreatAsTransparent window has any area in the borderClip, that will be
    added to the totalClip region for use by other windows. That's wrong.
    Instead, simply empty the borderClip for TreatAsTransparent windows right up
    front.

diff --git a/mi/mivaltree.c b/mi/mivaltree.c
index 74483e3..d9d07ca 100644
--- a/mi/mivaltree.c
+++ b/mi/mivaltree.c
@@ -255,7 +255,11 @@ miComputeClips (
     if (pParent->redirectDraw != RedirectDrawNone)
     {
 	if (miSetRedirectBorderClipProc)
+	{
+	    if (TreatAsTransparent (pParent))
+		REGION_EMPTY (pScreen, universe);
 	    (*miSetRedirectBorderClipProc) (pParent, universe);
+	}
 	REGION_COPY(pScreen, universe, &pParent->borderSize);
     }
 #endif
commit d500eeb9458336780d77baf8b7db96e1f7ff4f0d
Author: Aaron Plattner <aplattner at nvidia.com>
Date:   Sun May 4 10:26:25 2008 -0700

    Xephyr: Handle depth 30 and reject higher depths rather than crashing.

diff --git a/hw/kdrive/ephyr/ephyr.c b/hw/kdrive/ephyr/ephyr.c
index d69e148..3989d0d 100644
--- a/hw/kdrive/ephyr/ephyr.c
+++ b/hw/kdrive/ephyr/ephyr.c
@@ -150,11 +150,22 @@ ephyrScreenInitialize (KdScreenInfo *screen, EphyrScrPriv *scrpriv)
 	  screen->fb[0].depth = 16;
 	  screen->fb[0].bitsPerPixel = 16;
 	}
-      else
+      else if (screen->fb[0].depth <= 24)
 	{
 	  screen->fb[0].depth = 24;
 	  screen->fb[0].bitsPerPixel = 32;
 	}
+      else if (screen->fb[0].depth <= 30)
+	{
+	  screen->fb[0].depth = 30;
+	  screen->fb[0].bitsPerPixel = 32;
+	}
+      else
+	{
+	  ErrorF("\nXephyr: Unsupported screen depth %d\n",
+	         screen->fb[0].depth);
+	  return FALSE;
+	}
 
       hostx_get_visual_masks (screen, &redMask, &greenMask, &blueMask);
 
commit f4a68f3701889950d3b98842d021f357f3913fea
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri May 2 17:35:57 2008 -0700

    XQuartz: Fix mouse input offsets earlier since GetPointerEvents does not like negative (x,y) values
    (cherry picked from commit 8d9eab3a2ec5955cc2698fdcb1fa6ed12b2aadb7)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 646b9ef..691725d 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -839,7 +839,7 @@ static void send_nsevent (NSEventType type, NSEvent *e) {
 	int pointer_x, pointer_y, ev_button, ev_type;
 	float pressure, tilt_x, tilt_y;
 
-	/* convert location to global top-left coordinates */
+	/* convert location to be relative to top-left of primary display */
 	location = [e locationInWindow];
 	window = [e window];
 	screen = [[[NSScreen screens] objectAtIndex:0] frame];
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 2c95ed7..1547094 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -359,6 +359,28 @@ static void DarwinPokeEQ(void) {
 	write(darwinEventWriteFD, &nullbyte, 1);
 }
 
+/* Convert from Appkit pointer input values to X input values:
+ * Note: pointer_x and pointer_y are relative to the upper-left of primary
+ *       display.
+ */
+static void DarwinPrepareValuators(int *valuators, ScreenPtr screen,
+                                   int pointer_x, int pointer_y, 
+                                   float pressure, float tilt_x, float tilt_y) {
+    /* Fix offset between darwin and X screens */
+    pointer_x -= darwinMainScreenX + dixScreenOrigins[screen->myNum].x;
+    pointer_y -= darwinMainScreenY + dixScreenOrigins[screen->myNum].y;
+    
+    /* Setup our array of values */
+    valuators[0] = pointer_x;
+    valuators[1] = pointer_y;
+    valuators[2] = pressure * SCALEFACTOR_PRESSURE;
+    valuators[3] = tilt_x * SCALEFACTOR_TILT;
+    valuators[4] = tilt_y * SCALEFACTOR_TILT;
+    
+    DEBUG_LOG("Valuators: {%d,%d,%d,%d,%d}\n", 
+              valuators[0], valuators[1], valuators[2], valuators[3], valuators[4]);
+}
+
 void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int pointer_y, 
 			     float pressure, float tilt_x, float tilt_y) {
 	static int darwinFakeMouseButtonDown = 0;
@@ -366,22 +388,26 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	int i, num_events;
 	DeviceIntPtr dev;
     ScreenPtr screen;
+    int valuators[5];
 	
-//    DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
+    DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
     
 	if(!darwinEvents) {
-		ErrorF("DarwinSendPointerEvents called before darwinEvents was initialized\n");
+		DEBUG_LOG("DarwinSendPointerEvents called before darwinEvents was initialized\n");
 		return;
 	}
 
-	int valuators[5] = {pointer_x, pointer_y, pressure * SCALEFACTOR_PRESSURE, 
-		      tilt_x * SCALEFACTOR_TILT, tilt_y * SCALEFACTOR_TILT};
-	
-	if (pressure == 0 && tilt_x == 0 && tilt_y == 0) dev = darwinPointer;
-	else dev = darwinTablet;
+	if (pressure == 0 && tilt_x == 0 && tilt_y == 0)
+        dev = darwinPointer;
+	else
+        dev = darwinTablet;
+
+    screen = miPointerGetScreen(dev);
+    if(!screen) {
+        DEBUG_LOG("DarwinSendPointerEvents called before screen was initialized\n");
+        return;
+    }
 
-	DEBUG_LOG("Valuators: {%d,%d,%d,%d,%d}\n", 
-			valuators[0], valuators[1], valuators[2], valuators[3], valuators[4]);
 	if (ev_type == ButtonPress && darwinFakeButtons && ev_button == 1) {
 		// Mimic multi-button mouse with modifier-clicks
 		// If both sets of modifiers are pressed,
@@ -411,19 +437,13 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 		DarwinUpdateModifiers(KeyPress, darwinFakeMouseButtonMask & old_flags);
 		darwinFakeMouseButtonMask = 0;
 		return;
-	} 
+	}
 
+    DarwinPrepareValuators(valuators, screen, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
     darwinEvents_lock(); {
         num_events = GetPointerEvents(darwinEvents, dev, ev_type, ev_button, 
                                       POINTER_ABSOLUTE, 0, dev==darwinTablet?5:2, valuators);
-        screen = miPointerGetScreen(dev);
-        for(i=0; i<num_events && screen; i++) {
-            darwinEvents[i].u.keyButtonPointer.rootX -= darwinMainScreenX +
-                dixScreenOrigins[screen->myNum].x;
-            darwinEvents[i].u.keyButtonPointer.rootY -= darwinMainScreenY +
-                dixScreenOrigins[screen->myNum].y;
-            mieqEnqueue (dev, &darwinEvents[i]);
-        }
+        for(i=0; i<num_events; i++) mieqEnqueue (dev, &darwinEvents[i]);
         DarwinPokeEQ();
 
     } darwinEvents_unlock();
@@ -433,7 +453,7 @@ void DarwinSendKeyboardEvents(int ev_type, int keycode) {
 	int i, num_events;
 
 	if(!darwinEvents) {
-		ErrorF("DarwinSendKeyboardEvents called before darwinEvents was initialized\n");
+		DEBUG_LOG("DarwinSendKeyboardEvents called before darwinEvents was initialized\n");
 		return;
 	}
 
@@ -459,21 +479,28 @@ void DarwinSendKeyboardEvents(int ev_type, int keycode) {
 
 void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y) {
 	int i, num_events;
-
-	// tilt and pressure have no meaning for a Prox event
-	int valuators[5] = {pointer_x, pointer_y, 0, 0, 0};  
+    ScreenPtr screen;
+    DeviceIntPtr dev = darwinTablet;
+    int valuators[5];
 
 	DEBUG_LOG("DarwinSendProximityEvents(%d, %d, %d)\n", ev_type, pointer_x, pointer_y);
-	
+
 	if(!darwinEvents) {
-		ErrorF("DarwinSendProximityEvents called before darwinEvents was initialized\n");
+		DEBUG_LOG("DarwinSendProximityEvents called before darwinEvents was initialized\n");
 		return;
 	}
+    
+    screen = miPointerGetScreen(dev);
+    if(!screen) {
+        DEBUG_LOG("DarwinSendPointerEvents called before screen was initialized\n");
+        return;
+    }    
 
+    DarwinPrepareValuators(valuators, screen, pointer_x, pointer_y, 0.0f, 0.0f, 0.0f);
     darwinEvents_lock(); {
-        num_events = GetProximityEvents(darwinEvents, darwinTablet, ev_type,
+        num_events = GetProximityEvents(darwinEvents, dev, ev_type,
                                         0, 5, valuators);
-        for(i=0; i<num_events; i++) mieqEnqueue (darwinTablet,&darwinEvents[i]);
+        for(i=0; i<num_events; i++) mieqEnqueue (dev,&darwinEvents[i]);
         DarwinPokeEQ();
     } darwinEvents_unlock();
 }
@@ -484,7 +511,7 @@ void DarwinSendScrollEvents(float count_x, float count_y,
 							int pointer_x, int pointer_y, 
 			    			float pressure, float tilt_x, float tilt_y) {
 	if(!darwinEvents) {
-		ErrorF("DarwinSendScrollEvents called before darwinEvents was initialized\n");
+		DEBUG_LOG("DarwinSendScrollEvents called before darwinEvents was initialized\n");
 		return;
 	}
 
commit 96fa7da3b87e2f9187ec13dad259beefdc17cd94
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri May 2 16:53:45 2008 -0700

    XQuartz: Avoid a possible crash at startup due to unfavorable context switching.
    (cherry picked from commit ff10c37bdd09656cf2f7ee9577f5552caa1ffdb8)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 161fd9d..2c95ed7 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -365,6 +365,7 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	static int darwinFakeMouseButtonMask = 0;
 	int i, num_events;
 	DeviceIntPtr dev;
+    ScreenPtr screen;
 	
 //    DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
     
@@ -415,11 +416,12 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
     darwinEvents_lock(); {
         num_events = GetPointerEvents(darwinEvents, dev, ev_type, ev_button, 
                                       POINTER_ABSOLUTE, 0, dev==darwinTablet?5:2, valuators);
-        for(i=0; i<num_events; i++) {
+        screen = miPointerGetScreen(dev);
+        for(i=0; i<num_events && screen; i++) {
             darwinEvents[i].u.keyButtonPointer.rootX -= darwinMainScreenX +
-                dixScreenOrigins[miPointerCurrentScreen()->myNum].x;
+                dixScreenOrigins[screen->myNum].x;
             darwinEvents[i].u.keyButtonPointer.rootY -= darwinMainScreenY +
-                dixScreenOrigins[miPointerCurrentScreen()->myNum].y;
+                dixScreenOrigins[screen->myNum].y;
             mieqEnqueue (dev, &darwinEvents[i]);
         }
         DarwinPokeEQ();
commit a338007be6fd4302af012109d959f43ac7eab2b1
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu May 1 18:02:59 2008 -0700

    XQuartz: Adjust the screen origin offset properly for multimonitor setups
    (cherry picked from commit f2020b9836bacd0593ac0b4c8541e32714ab02a9)

diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index df328f3..107d8ee 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -42,6 +42,7 @@
 
 #include "opaque.h"
 #include "darwin.h"
+#include "darwinEvents.h"
 #include "quartz.h"
 #define _APPLEWM_SERVER_
 #include "X11/extensions/applewm.h"
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 7b3091d..161fd9d 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -81,22 +81,21 @@ int input_check_zero, input_check_flag;
 static int old_flags = 0;  // last known modifier state
 
 xEvent *darwinEvents = NULL;
+pthread_mutex_t darwinEvents_mutex = PTHREAD_MUTEX_INITIALIZER;
 
-pthread_mutex_t mieqEnqueue_mutex = PTHREAD_MUTEX_INITIALIZER;
-
-static inline void mieqEnqueue_lock(void) {
+static inline void darwinEvents_lock(void) {
     int err;
-    if((err = pthread_mutex_lock(&mieqEnqueue_mutex))) {
-        ErrorF("%s:%s:%d: Failed to lock mieqEnqueue_mutex: %d\n",
+    if((err = pthread_mutex_lock(&darwinEvents_mutex))) {
+        ErrorF("%s:%s:%d: Failed to lock darwinEvents_mutex: %d\n",
                __FILE__, __FUNCTION__, __LINE__, err);
         spewCallStack();
     }
 }
 
-static inline void mieqEnqueue_unlock(void) {
+static inline void darwinEvents_unlock(void) {
     int err;
-    if((err = pthread_mutex_unlock(&mieqEnqueue_mutex))) {
-        ErrorF("%s:%s:%d: Failed to unlock mieqEnqueue_mutex: %d\n",
+    if((err = pthread_mutex_unlock(&darwinEvents_mutex))) {
+        ErrorF("%s:%s:%d: Failed to unlock darwinEvents_mutex: %d\n",
                __FILE__, __FUNCTION__, __LINE__, err);
         spewCallStack();
     }
@@ -413,13 +412,19 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 		return;
 	} 
 
-    mieqEnqueue_lock(); {
+    darwinEvents_lock(); {
         num_events = GetPointerEvents(darwinEvents, dev, ev_type, ev_button, 
                                       POINTER_ABSOLUTE, 0, dev==darwinTablet?5:2, valuators);
-        for(i=0; i<num_events; i++) mieqEnqueue (dev,&darwinEvents[i]);
+        for(i=0; i<num_events; i++) {
+            darwinEvents[i].u.keyButtonPointer.rootX -= darwinMainScreenX +
+                dixScreenOrigins[miPointerCurrentScreen()->myNum].x;
+            darwinEvents[i].u.keyButtonPointer.rootY -= darwinMainScreenY +
+                dixScreenOrigins[miPointerCurrentScreen()->myNum].y;
+            mieqEnqueue (dev, &darwinEvents[i]);
+        }
         DarwinPokeEQ();
 
-    } mieqEnqueue_unlock();
+    } darwinEvents_unlock();
 }
 
 void DarwinSendKeyboardEvents(int ev_type, int keycode) {
@@ -443,11 +448,11 @@ void DarwinSendKeyboardEvents(int ev_type, int keycode) {
 		}
 	}
 
-    mieqEnqueue_lock(); {
+    darwinEvents_lock(); {
         num_events = GetKeyboardEvents(darwinEvents, darwinKeyboard, ev_type, keycode + MIN_KEYCODE);
         for(i=0; i<num_events; i++) mieqEnqueue(darwinKeyboard,&darwinEvents[i]);
         DarwinPokeEQ();
-    } mieqEnqueue_unlock();
+    } darwinEvents_unlock();
 }
 
 void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y) {
@@ -463,12 +468,12 @@ void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y) {
 		return;
 	}
 
-    mieqEnqueue_lock(); {
+    darwinEvents_lock(); {
         num_events = GetProximityEvents(darwinEvents, darwinTablet, ev_type,
                                         0, 5, valuators);
         for(i=0; i<num_events; i++) mieqEnqueue (darwinTablet,&darwinEvents[i]);
         DarwinPokeEQ();
-    } mieqEnqueue_unlock();
+    } darwinEvents_unlock();
 }
 
 
@@ -533,8 +538,8 @@ void DarwinSendDDXEvent(int type, int argc, ...) {
         va_end (args);
     }
 
-    mieqEnqueue_lock();
+    darwinEvents_lock();
     mieqEnqueue(darwinPointer, &xe);
     DarwinPokeEQ();
-    mieqEnqueue_unlock();
+    darwinEvents_unlock();
 }
diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index 7312226..d8eb72a 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -40,6 +40,7 @@
 #include "xprEvent.h"
 #include "pseudoramiX.h"
 #include "darwin.h"
+#include "darwinEvents.h"
 #include "rootless.h"
 #include "dri.h"
 #include "globals.h"
commit 3b8d53452cd6c74d32d7759964a7cd9ee775f161
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Thu May 1 15:10:52 2008 +0200

    EXA: Fall back in CompositeRects if the driver can't accelerate Composite.
    
    Fixes http://bugs.freedesktop.org/show_bug.cgi?id=15780 .

diff --git a/exa/exa_render.c b/exa/exa_render.c
index 43b0029..b480c6d 100644
--- a/exa/exa_render.c
+++ b/exa/exa_render.c
@@ -345,6 +345,9 @@ exaTryDriverCompositeRects(CARD8	       op,
     struct _Pixmap scratch;
     ExaMigrationRec pixmaps[2];
 
+    if (!pExaScr->info->PrepareComposite)
+	return -1;
+
     pSrcPix = exaGetDrawablePixmap(pSrc->pDrawable);
     pSrcExaPix = ExaGetPixmapPriv(pSrcPix);
 
commit 01c61f3d972fc2f4e5bb536dd00d8b6bbeb0fb3d
Author: Paulo Cesar Pereira de Andrade <pcpa at mandriva.com.br>
Date:   Thu May 1 01:02:39 2008 -0300

    xorgcfg: Fix a crash if xorg.conf doesn't have a Files section.
    
    This patch only creates a Files section if required, so if no entries are
    added, an empty Files section will not be created.
    
    Signed-off-by: Peter Hutterer <peter at cs.unisa.edu.au>

diff --git a/hw/xfree86/utils/xorgcfg/expert.c b/hw/xfree86/utils/xorgcfg/expert.c
index bb6960c..484c2ec 100644
--- a/hw/xfree86/utils/xorgcfg/expert.c
+++ b/hw/xfree86/utils/xorgcfg/expert.c
@@ -465,7 +465,7 @@ CreateFiles(TreeNode *files)
     Widget w;
     char *value;
 
-    value = file->file_logfile ? file->file_logfile : "";
+    value = (file && file->file_logfile) ? file->file_logfile : "";
     node = NewNode(files, NULL, NULL, files->node, 
 		   (TreeData*)XtCalloc(1, sizeof(TreeData)));
     CreateFilesField(node, "LogFile", value);
@@ -509,10 +509,14 @@ UpdateFiles(TreeNode *files)
     /* LogFile */
     files = files->child;
     XtVaGetValues(files->data->files.text, XtNstring, &str, NULL);
-    XtFree(XF86Config->conf_files->file_logfile);
-    if (*str)
+    if (XF86Config->conf_files && XF86Config->conf_files->file_logfile)
+	XtFree(XF86Config->conf_files->file_logfile);
+    if (*str) {
+	if (XF86Config->conf_files == NULL)
+	    XF86Config->conf_files = XtCalloc(1, sizeof(XF86ConfFilesRec));
 	XF86Config->conf_files->file_logfile = XtNewString(str);
-    else
+    }
+    else if (XF86Config->conf_files)
 	XF86Config->conf_files->file_logfile = NULL;
 }
 
@@ -527,10 +531,11 @@ CreateFontPath(TreeNode *fontpath, char *path)
     if (path == NULL) {
 	if (XF86Font_path) {
 	    path = XtNewString(XF86Font_path);
-	    if (XF86Config->conf_files && XF86Config->conf_files->file_fontpath) {
+	    if (XF86Config->conf_files && XF86Config->conf_files->file_fontpath)
 		XtFree(XF86Config->conf_files->file_fontpath);
-		XF86Config->conf_files->file_fontpath = XtNewString(path);
-	    }
+	    if (XF86Config->conf_files == NULL)
+		XF86Config->conf_files = XtCalloc(1, sizeof(XF86ConfFilesRec));
+	    XF86Config->conf_files->file_fontpath = XtNewString(path);
 	}
 	else if (XF86Config->conf_files && XF86Config->conf_files->file_fontpath)
 	    path = XtNewString(XF86Config->conf_files->file_fontpath);
@@ -629,9 +634,14 @@ FontPathChanged(TreeNode *node)
 	pos += len - 2;
     }
 
-    if (XF86Config->conf_files->file_fontpath)
-	XtFree(XF86Config->conf_files->file_fontpath);
-    XF86Config->conf_files->file_fontpath = fontpath;
+    if (XF86Config->conf_files) {
+	if (XF86Config->conf_files->file_fontpath)
+	    XtFree(XF86Config->conf_files->file_fontpath);
+    }
+    else if (fontpath)
+	XF86Config->conf_files = XtCalloc(1, sizeof(XF86ConfFilesRec));
+    if (XF86Config->conf_files)
+	XF86Config->conf_files->file_fontpath = fontpath;
 }
 
 static void
@@ -703,10 +713,11 @@ CreateModulePath(TreeNode *modulepath, char *path)
     if (path == NULL) {
 	if (XF86Module_path) {
 	    path = XtNewString(XF86Module_path);
-	    if (XF86Config->conf_files && XF86Config->conf_files->file_modulepath) {
+	    if (XF86Config->conf_files == NULL)
+		XF86Config->conf_files = XtCalloc(1, sizeof(XF86ConfFilesRec));
+	    else if (XF86Config->conf_files->file_modulepath)
 		XtFree(XF86Config->conf_files->file_modulepath);
-		XF86Config->conf_files->file_modulepath = XtNewString(path);
-	    }
+	    XF86Config->conf_files->file_modulepath = XtNewString(path);
 	}
 	else if (XF86Config->conf_files && XF86Config->conf_files->file_modulepath)
 	    path = XtNewString(XF86Config->conf_files->file_modulepath);
@@ -799,9 +810,14 @@ ModulePathChanged(TreeNode *node)
 	pos += len - 2;
     }
 
-    if (XF86Config->conf_files->file_modulepath)
-	XtFree(XF86Config->conf_files->file_modulepath);
-    XF86Config->conf_files->file_modulepath = modulepath;
+    if (XF86Config->conf_files) {
+	if (XF86Config->conf_files->file_modulepath)
+	    XtFree(XF86Config->conf_files->file_modulepath);
+    }
+    else if (modulepath)
+	XF86Config->conf_files = XtCalloc(1, sizeof(XF86ConfFilesRec));
+    if (XF86Config->conf_files)
+	XF86Config->conf_files->file_modulepath = modulepath;
 }
 
 static void
@@ -921,6 +937,8 @@ NewModuleCallback(Widget unused, XtPointer user_data, XtPointer call_data)
     DeleteNode(node);
     load = (XF86LoadPtr)XtCalloc(1, sizeof(XF86LoadRec));
     load->load_name = XtNewString(label);
+    if (XF86Config->conf_modules == NULL)
+	XF86Config->conf_modules = XtCalloc(1, sizeof(XF86ConfModuleRec));
     XF86Config->conf_modules->mod_load_lst =
 	xf86addModule(XF86Config->conf_modules->mod_load_lst, load);
 
commit 6899ff81e8f668382e3e2f9afdd9cdf51d0e0f7d
Author: Paulo Cesar Pereira de Andrade <pcpa at mandriva.com.br>
Date:   Wed Apr 30 16:38:42 2008 -0300

    Fix an off by one read error in drmSIGIOHandler().
    
    Signed-off-by: Peter Hutterer <peter at cs.unisa.edu.au>

diff --git a/hw/xfree86/dri/dri.c b/hw/xfree86/dri/dri.c
index b736c6a..ef1a6ea 100644
--- a/hw/xfree86/dri/dri.c
+++ b/hw/xfree86/dri/dri.c
@@ -2436,7 +2436,7 @@ static void drmSIGIOHandler(int interrupt, void *closure)
 #if 0
 	    fprintf(stderr, "Trying %d\n", entry->fd);
 #endif
-	    if ((count = read(entry->fd, buf, sizeof(buf))) > 0) {
+	    if ((count = read(entry->fd, buf, sizeof(buf) - 1)) > 0) {
 		buf[count] = '\0';
 #if 0
 		fprintf(stderr, "Got %s\n", buf);
commit ec0419b50534006a272278b79ee51538193661cb
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 30 17:30:57 2008 -0700

    XQuartz: Moved some relevant stuff from darwin.h to darwinEvents.h
    (cherry picked from commit 1fcf74a436f2e19cceb3f285b89859025d94c040)

diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index 4300b9f..bdf0046 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -89,38 +89,6 @@ extern int              darwinDesiredRefresh;
 extern int              darwinMainScreenX;
 extern int              darwinMainScreenY;
 
-
-/*
- * Special ddx events understood by the X server
- */
-enum {
-    kXquartzReloadKeymap      // Reload system keymap
-            = LASTEvent+1,    // (from X.h list of event names)
-    kXquartzActivate,         // restore X drawing and cursor
-    kXquartzDeactivate,       // clip X drawing and switch to Aqua cursor
-    kXquartzSetRootClip,      // enable or disable drawing to the X screen
-    kXquartzQuit,             // kill the X server and release the display
-    kXquartzReadPasteboard,   // copy Mac OS X pasteboard into X cut buffer
-    kXquartzWritePasteboard,  // copy X cut buffer onto Mac OS X pasteboard
-    kXquartzBringAllToFront,  // bring all X windows to front
-    kXquartzToggleFullscreen, // Enable/Disable fullscreen mode
-    kXquartzSetRootless,      // Set rootless mode
-    kXquartzSpaceChanged,     // Spaces changed
-    /*
-     * AppleWM events
-     */
-    kXquartzControllerNotify, // send an AppleWMControllerNotify event
-    kXquartzPasteboardNotify, // notify the WM to copy or paste
-    /*
-     * Xplugin notification events
-     */
-    kXquartzDisplayChanged,   // display configuration has changed
-    kXquartzWindowState,      // window visibility state has changed
-    kXquartzWindowMoved,      // window has moved on screen
-};
-
-void DarwinSendDDXEvent(int type, int argc, ...);
-
 #define ENABLE_DEBUG_LOG 1
 
 #ifdef ENABLE_DEBUG_LOG
diff --git a/hw/xquartz/darwinEvents.h b/hw/xquartz/darwinEvents.h
index ef8bf39..a676aeb 100644
--- a/hw/xquartz/darwinEvents.h
+++ b/hw/xquartz/darwinEvents.h
@@ -40,4 +40,36 @@ void DarwinSendScrollEvents(float count_x, float count_y, int pointer_x, int poi
 			    float pressure, float tilt_x, float tilt_y);
 void DarwinUpdateModKeys(int flags);
 
+/*
+ * Special ddx events understood by the X server
+ */
+enum {
+    kXquartzReloadKeymap      // Reload system keymap
+    = LASTEvent+1,    // (from X.h list of event names)
+    kXquartzActivate,         // restore X drawing and cursor
+    kXquartzDeactivate,       // clip X drawing and switch to Aqua cursor
+    kXquartzSetRootClip,      // enable or disable drawing to the X screen
+    kXquartzQuit,             // kill the X server and release the display
+    kXquartzReadPasteboard,   // copy Mac OS X pasteboard into X cut buffer
+    kXquartzWritePasteboard,  // copy X cut buffer onto Mac OS X pasteboard
+    kXquartzBringAllToFront,  // bring all X windows to front
+    kXquartzToggleFullscreen, // Enable/Disable fullscreen mode
+    kXquartzSetRootless,      // Set rootless mode
+    kXquartzSpaceChanged,     // Spaces changed
+    /*
+     * AppleWM events
+     */
+    kXquartzControllerNotify, // send an AppleWMControllerNotify event
+    kXquartzPasteboardNotify, // notify the WM to copy or paste
+    /*
+     * Xplugin notification events
+     */
+    kXquartzDisplayChanged,   // display configuration has changed
+    kXquartzWindowState,      // window visibility state has changed
+    kXquartzWindowMoved,      // window has moved on screen
+};
+
+/* Send one of the above events to the server thread. */
+void DarwinSendDDXEvent(int type, int argc, ...);
+
 #endif  /* _DARWIN_EVENTS_H */
commit 28d1e21f1523d475cb757d3cfa33737ed62c534d
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 30 17:30:32 2008 -0700

    Dix: Cleaned up sanity checking in Get{Pointer,Keyboard}Events
    
    XQuartz was crashing because the Appkit thread was trying to GetXXXEvents while the Xserver thread was exiting.
    This adds some more sanity checks and avoids that crash
    (cherry picked from commit 34ec4bd6acb834c0e3f9a5042a0cc3f52c6f3a68)

diff --git a/dix/getevents.c b/dix/getevents.c
index bf9331e..0229c0a 100644
--- a/dix/getevents.c
+++ b/dix/getevents.c
@@ -407,8 +407,8 @@ GetKeyboardValuatorEvents(xEvent *events, DeviceIntPtr pDev, int type,
                           int num_valuators, int *valuators) {
     int numEvents = 0;
     CARD32 ms = 0;
-    KeySym *map = pDev->key->curKeySyms.map;
-    KeySym sym = map[key_code * pDev->key->curKeySyms.mapWidth];
+    KeySym *map;
+    KeySym sym;
     deviceKeyButtonPointer *kbp = NULL;
 
     if (!events)
@@ -419,11 +419,14 @@ GetKeyboardValuatorEvents(xEvent *events, DeviceIntPtr pDev, int type,
         return 0;
 
     if (!pDev->key || !pDev->focus || !pDev->kbdfeed ||
-        (pDev->coreEvents && !inputInfo.keyboard->key))
+        (pDev->coreEvents && !(inputInfo.keyboard && inputInfo.keyboard->key)))
         return 0;
 
     if (key_code < 8 || key_code > 255)
         return 0;
+    
+    map = pDev->key->curKeySyms.map;
+    sym = map[key_code * pDev->key->curKeySyms.mapWidth];
 
     if (pDev->coreEvents)
         numEvents = 2;
@@ -539,6 +542,9 @@ GetPointerEvents(xEvent *events, DeviceIntPtr pDev, int type, int buttons,
 
     if ((type == ButtonPress || type == ButtonRelease) && !pDev->button)
         return 0;
+    
+    if(pDev->coreEvents && !cp)
+        return 0;
 
     /* FIXME: I guess it should, in theory, be possible to post button events
      *        from devices without valuators. */
commit ce36ae526d88d20ff67cd6cb429fb06f48d231f6
Author: Kazuhiro Inaoka <inaoka.kazuhiro at renesas.com>
Date:   Wed Apr 30 11:58:32 2008 +0300

    Add M32R architecture support (bug #10020)
    
    Still needs autotools support, so this won't actually _build_: it's just
    a starting point.

diff --git a/hw/xfree86/common/compiler.h b/hw/xfree86/common/compiler.h
index 7b65da8..9e7f821 100644
--- a/hw/xfree86/common/compiler.h
+++ b/hw/xfree86/common/compiler.h
@@ -1363,7 +1363,7 @@ do {									\
 #    define write_mem_barrier()   /* NOP */
 
 #    if !defined(__SUNPRO_C)
-#    if !defined(FAKEIT) && !defined(__mc68000__) && !defined(__arm__) && !defined(__sh__) && !defined(__hppa__) && !defined(__s390__)
+#    if !defined(FAKEIT) && !defined(__mc68000__) && !defined(__arm__) && !defined(__sh__) && !defined(__hppa__) && !defined(__s390__) && !defined(__m32r__)
 #     ifdef GCCUSESGAS
 
 /*
@@ -1472,7 +1472,7 @@ inl(unsigned short port)
 
 #     endif /* GCCUSESGAS */
 
-#    else /* !defined(FAKEIT) && !defined(__mc68000__)  && !defined(__arm__) && !defined(__sh__) && !defined(__hppa__)*/
+#    else /* !defined(FAKEIT) && !defined(__mc68000__)  && !defined(__arm__) && !defined(__sh__) && !defined(__hppa__) && !defined(__m32r__) */
 
 static __inline__ void
 outb(unsigned short port, unsigned char val)
diff --git a/hw/xfree86/common/xf86Bus.c b/hw/xfree86/common/xf86Bus.c
index f7ffac8..7e6b93a 100644
--- a/hw/xfree86/common/xf86Bus.c
+++ b/hw/xfree86/common/xf86Bus.c
@@ -2773,7 +2773,7 @@ xf86FindPrimaryDevice()
     }
 }
 
-#if !defined(__sparc) && !defined(__sparc__) && !defined(__powerpc__) && !defined(__mips__) && !defined(__arm__)
+#if !defined(__sparc) && !defined(__sparc__) && !defined(__powerpc__) && !defined(__mips__) && !defined(__arm__) && !defined(__m32r__)
 #include "vgaHW.h"
 #include "compiler.h"
 #endif
@@ -2785,7 +2785,7 @@ static void
 CheckGenericGA()
 {
 /* This needs to be changed for multiple domains */
-#if !defined(__sparc__) && !defined(__sparc) && !defined(__powerpc__) && !defined(__mips__) && !defined(__ia64__) && !defined(__arm__) && !defined(__s390__)
+#if !defined(__sparc__) && !defined(__sparc) && !defined(__powerpc__) && !defined(__mips__) && !defined(__ia64__) && !defined(__arm__) && !defined(__s390__) && !defined(__m32r__)
     IOADDRESS GenericIOBase = VGAHW_GET_IOBASE();
     CARD8 CurrentValue, TestValue;
 
diff --git a/hw/xfree86/os-support/bus/Pci.h b/hw/xfree86/os-support/bus/Pci.h
index b78d307..1385eee 100644
--- a/hw/xfree86/os-support/bus/Pci.h
+++ b/hw/xfree86/os-support/bus/Pci.h
@@ -237,6 +237,12 @@
 # if defined(linux)
 #  define ARCH_PCI_INIT linuxPciInit
 # endif
+#elif defined(__m32r__)
+# if defined(linux)
+#  define ARCH_PCI_INIT linuxPciInit
+#  define INCLUDE_XF86_MAP_PCI_MEM
+#  define INCLUDE_XF86_NO_DOMAIN
+# endif
 #elif defined(__sparc__) || defined(sparc)
 # if defined(linux)
 #  define ARCH_PCI_INIT linuxPciInit
diff --git a/hw/xfree86/os-support/linux/lnxResource.c b/hw/xfree86/os-support/linux/lnxResource.c
index 67af9db..734f4d6 100644
--- a/hw/xfree86/os-support/linux/lnxResource.c
+++ b/hw/xfree86/os-support/linux/lnxResource.c
@@ -65,6 +65,7 @@ xf86AccResFromOS(resPtr ret)
       defined(__sparc__) || \
       defined(__mips__) || \
       defined(__sh__) || \
+      defined(__m32r__) || \
       defined(__mc68000__) || \
       defined(__arm__) || \
       defined(__s390__) || \
diff --git a/hw/xfree86/os-support/linux/lnx_video.c b/hw/xfree86/os-support/linux/lnx_video.c
index 1bd2d57..4295937 100644
--- a/hw/xfree86/os-support/linux/lnx_video.c
+++ b/hw/xfree86/os-support/linux/lnx_video.c
@@ -558,7 +558,7 @@ xf86EnableIO(void)
 #endif
 	}
 	close(fd);
-#elif !defined(__mc68000__) && !defined(__sparc__) && !defined(__mips__) && !defined(__sh__) && !defined(__hppa__) && !defined(__s390__) && !defined(__arm__)
+#elif !defined(__mc68000__) && !defined(__sparc__) && !defined(__mips__) && !defined(__sh__) && !defined(__hppa__) && !defined(__s390__) && !defined(__arm__) && !defined(__m32r__)
         if (ioperm(0, 1024, 1) || iopl(3)) {
                 if (errno == ENODEV)
                         ErrorF("xf86EnableIOPorts: no I/O ports found\n");
@@ -585,7 +585,7 @@ xf86DisableIO(void)
 #if defined(__powerpc__)
 	munmap(ioBase, 0x20000);
 	ioBase = NULL;
-#elif !defined(__mc68000__) && !defined(__sparc__) && !defined(__mips__) && !defined(__sh__) && !defined(__hppa__) && !defined(__arm__) && !defined(__s390__)
+#elif !defined(__mc68000__) && !defined(__sparc__) && !defined(__mips__) && !defined(__sh__) && !defined(__hppa__) && !defined(__arm__) && !defined(__s390__) && !defined(__m32r__)
 	iopl(0);
 	ioperm(0, 1024, 0);
 #endif
diff --git a/include/servermd.h b/include/servermd.h
index 7b0a328..8e6de09 100644
--- a/include/servermd.h
+++ b/include/servermd.h
@@ -217,6 +217,26 @@ SOFTWARE.
 
 #endif /* SuperH */
 
+#if defined(__m32r__)
+
+#if defined(__BIG_ENDIAN__)
+# define IMAGE_BYTE_ORDER      MSBFirst
+# define BITMAP_BIT_ORDER      MSBFirst
+# define GLYPHPADBYTES         4
+# define GETLEFTBITS_ALIGNMENT 1
+#else
+# define IMAGE_BYTE_ORDER      LSBFirst
+# define BITMAP_BIT_ORDER      LSBFirst
+# define GLYPHPADBYTES         4
+# define GETLEFTBITS_ALIGNMENT 1
+#endif
+
+#define AVOID_MEMORY_READ
+#define FAST_CONSTANT_OFFSET_MODE
+#define LARGE_INSTRUCTION_CACHE
+#define PLENTIFUL_REGISTERS
+
+#endif /* __m32r__ */
 
 #if (defined(sun) && (defined(__sparc) || defined(sparc))) || \
     (defined(__uxp__) && (defined(sparc) || defined(mc68000))) || \
commit b71b51c982706501b6229532ce342752207426bb
Author: Ben Byer <bbyer at bushing.apple.com>
Date:   Tue Apr 29 23:37:58 2008 -0700

    xquartz: created darwinTablet, to represent tablet events
    (cherry picked from commit 50641bce730ee03738fa0c4beb8125b34fda556f)

diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index 6f47194..f20cce1 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -1,10 +1,9 @@
 /**************************************************************
  *
- * Shared code for the Darwin X Server
- * running with Quartz or IOKit display mode
+ * Xquartz initialization code
  *
+ * Copyright (c) 2007-2008 Apple Inc.
  * Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
- * Copyright (c) 2007 Apple Inc.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
@@ -112,6 +111,7 @@ int                     darwinFakeMouse3Mask = NX_COMMANDMASK;
 
 // devices
 DeviceIntPtr            darwinPointer = NULL;
+DeviceIntPtr            darwinTablet = NULL;
 DeviceIntPtr            darwinKeyboard = NULL;
 
 // Common pixmap formats
@@ -332,14 +332,13 @@ static void DarwinChangePointerControl(
 #endif
 
 /*
- * DarwinMouseProc
- *  Handle the initialization, etc. of a mouse
+ * DarwinMouseProc: Handle the initialization, etc. of a mouse
  */
 static int DarwinMouseProc(DeviceIntPtr pPointer, int what) {
+	// 7 buttons: left, right, middle, then four scroll wheel "buttons"
     CARD8 map[8] = {0, 1, 2, 3, 4, 5, 6, 7};
     
     switch (what) {
-            
         case DEVICE_INIT:
             pPointer->public.on = FALSE;
             
@@ -347,15 +346,13 @@ static int DarwinMouseProc(DeviceIntPtr pPointer, int what) {
             InitPointerDeviceStruct((DevicePtr)pPointer, map, 7,
                                     GetMotionHistory,
                                     (PtrCtrlProcPtr)NoopDDA,
-                                    GetMotionHistorySize(), 7);
-            InitProximityClassDeviceStruct(pPointer);
+                                    GetMotionHistorySize(), 2);
+								pPointer->name = strdup("Quartz Pointing Device");
             break;
-            
         case DEVICE_ON:
             pPointer->public.on = TRUE;
             AddEnabledDevice( darwinEventReadFD );
             return Success;
-            
         case DEVICE_CLOSE:
         case DEVICE_OFF:
             pPointer->public.on = FALSE;
@@ -366,6 +363,34 @@ static int DarwinMouseProc(DeviceIntPtr pPointer, int what) {
     return Success;
 }
 
+static int DarwinTabletProc(DeviceIntPtr pPointer, int what) {
+    CARD8 map[4] = {0, 1, 2, 3};
+    
+    switch (what) {
+        case DEVICE_INIT:
+            pPointer->public.on = FALSE;
+            
+            // Set button map.
+            InitPointerDeviceStruct((DevicePtr)pPointer, map, 3,
+                                    GetMotionHistory,
+                                    (PtrCtrlProcPtr)NoopDDA,
+                                    GetMotionHistorySize(), 7);
+            InitProximityClassDeviceStruct(pPointer);
+//			InitAbsoluteClassDeviceStruct(pPointer);
+			pPointer->name = strdup("pen");			
+            break;
+        case DEVICE_ON:
+            pPointer->public.on = TRUE;
+            AddEnabledDevice( darwinEventReadFD );
+            return Success;
+        case DEVICE_CLOSE:
+        case DEVICE_OFF:
+            pPointer->public.on = FALSE;
+            RemoveEnabledDevice(darwinEventReadFD);
+            return Success;
+    }
+    return Success;
+}
 
 /*
  * DarwinKeybdProc
@@ -376,6 +401,7 @@ static int DarwinKeybdProc( DeviceIntPtr pDev, int onoff )
     switch ( onoff ) {
         case DEVICE_INIT:
             DarwinKeyboardInit( pDev );
+			pDev->name = strdup("Quartz Keyboard");
             break;
         case DEVICE_ON:
             pDev->public.on = TRUE;
@@ -499,9 +525,11 @@ int DarwinParseModifierList(
 void InitInput( int argc, char **argv )
 {
     darwinPointer = AddInputDevice(DarwinMouseProc, TRUE);
-	darwinPointer->name = strdup("tablet");
     RegisterPointerDevice( darwinPointer );
 
+    darwinTablet = AddInputDevice(DarwinTabletProc, TRUE);
+    RegisterPointerDevice( darwinTablet );
+
     darwinKeyboard = AddInputDevice(DarwinKeybdProc, TRUE);
     RegisterKeyboardDevice( darwinKeyboard );
 
diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index 6d2fbd0..4300b9f 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -71,6 +71,7 @@ extern io_connect_t     darwinParamConnect;
 extern int              darwinEventReadFD;
 extern int              darwinEventWriteFD;
 extern DeviceIntPtr     darwinPointer;
+extern DeviceIntPtr     darwinTablet;
 extern DeviceIntPtr     darwinKeyboard;
 
 // User preferences
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index e25ae84..7b3091d 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -365,7 +365,8 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	static int darwinFakeMouseButtonDown = 0;
 	static int darwinFakeMouseButtonMask = 0;
 	int i, num_events;
-
+	DeviceIntPtr dev;
+	
 //    DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
     
 	if(!darwinEvents) {
@@ -376,7 +377,10 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	int valuators[5] = {pointer_x, pointer_y, pressure * SCALEFACTOR_PRESSURE, 
 		      tilt_x * SCALEFACTOR_TILT, tilt_y * SCALEFACTOR_TILT};
 	
-		DEBUG_LOG("Valuators: {%d,%d,%d,%d,%d}\n", 
+	if (pressure == 0 && tilt_x == 0 && tilt_y == 0) dev = darwinPointer;
+	else dev = darwinTablet;
+
+	DEBUG_LOG("Valuators: {%d,%d,%d,%d,%d}\n", 
 			valuators[0], valuators[1], valuators[2], valuators[3], valuators[4]);
 	if (ev_type == ButtonPress && darwinFakeButtons && ev_button == 1) {
 		// Mimic multi-button mouse with modifier-clicks
@@ -410,9 +414,9 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	} 
 
     mieqEnqueue_lock(); {
-        num_events = GetPointerEvents(darwinEvents, darwinPointer, ev_type, ev_button, 
-                                      POINTER_ABSOLUTE, 0, 5, valuators);
-        for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
+        num_events = GetPointerEvents(darwinEvents, dev, ev_type, ev_button, 
+                                      POINTER_ABSOLUTE, 0, dev==darwinTablet?5:2, valuators);
+        for(i=0; i<num_events; i++) mieqEnqueue (dev,&darwinEvents[i]);
         DarwinPokeEQ();
 
     } mieqEnqueue_unlock();
@@ -460,9 +464,9 @@ void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y) {
 	}
 
     mieqEnqueue_lock(); {
-        num_events = GetProximityEvents(darwinEvents, darwinPointer, ev_type,
+        num_events = GetProximityEvents(darwinEvents, darwinTablet, ev_type,
                                         0, 5, valuators);
-        for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
+        for(i=0; i<num_events; i++) mieqEnqueue (darwinTablet,&darwinEvents[i]);
         DarwinPokeEQ();
     } mieqEnqueue_unlock();
 }
commit 519581b0bab5cc6dac397877da485745f18c2120
Author: Ben Byer <bbyer at bushing.apple.com>
Date:   Tue Apr 29 23:00:09 2008 -0700

    xquartz: remove unused params from DarwinEQInit
    (cherry picked from commit 299a056737168ca1faefd675dce6d6ab13176be9)

diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index c18b575..6f47194 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -499,12 +499,13 @@ int DarwinParseModifierList(
 void InitInput( int argc, char **argv )
 {
     darwinPointer = AddInputDevice(DarwinMouseProc, TRUE);
+	darwinPointer->name = strdup("tablet");
     RegisterPointerDevice( darwinPointer );
 
     darwinKeyboard = AddInputDevice(DarwinKeybdProc, TRUE);
     RegisterKeyboardDevice( darwinKeyboard );
 
-    DarwinEQInit( (DevicePtr)darwinKeyboard, (DevicePtr)darwinPointer );
+    DarwinEQInit();
 
     QuartzInitInput(argc, argv);
 }
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index cd2b49a..e25ae84 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -307,7 +307,7 @@ static void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, in
     }
 }
 
-Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) { 
+Bool DarwinEQInit(void) { 
     if (!darwinEvents)
         darwinEvents = (xEvent *)xcalloc(sizeof(xEvent), GetMaximumEventsNum());
     if (!darwinEvents)
diff --git a/hw/xquartz/darwinEvents.h b/hw/xquartz/darwinEvents.h
index 4a619c9..ef8bf39 100644
--- a/hw/xquartz/darwinEvents.h
+++ b/hw/xquartz/darwinEvents.h
@@ -28,7 +28,7 @@
 #ifndef _DARWIN_EVENTS_H
 #define _DARWIN_EVENTS_H
 
-Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr);
+Bool DarwinEQInit(void);
 void DarwinEQEnqueue(const xEventPtr e);
 void DarwinEQPointerPost(DeviceIntPtr pDev, xEventPtr e);
 void DarwinEQSwitchScreen(ScreenPtr pScreen, Bool fromDIX);
commit d70487a4c09cfeb90d996ab40a23a74b2c15be6f
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Tue Apr 29 23:59:26 2008 -0700

    XQuartz: Fix to tablet-event handling code; we now scale
    more conservatively (to match Linux's Wacom driver) and
    we now receive all tablet-related events.
    (cherry picked from commit 588683cecca2cfc65a28de035cd6ee3d64ff59d2)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index e10e71e..646b9ef 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -49,6 +49,13 @@
 
 #define DEFAULTS_FILE "/usr/X11/lib/X11/xserver/Xquartz.plist"
 
+#ifndef XSERVER_VERSION
+#define XSERVER_VERSION "?"
+#endif
+
+#define ProximityIn    0
+#define ProximityOut   1
+
 int X11EnableKeyEquivalents = TRUE;
 int quartzHasRoot = FALSE, quartzEnableRootless = TRUE;
 
@@ -852,27 +859,37 @@ static void send_nsevent (NSEventType type, NSEvent *e) {
 	tilt_y = 0;
 
 	switch (type) {
-		case NSLeftMouseDown:    ev_button=1; ev_type=ButtonPress; goto handle_mouse;
-		case NSOtherMouseDown:   ev_button=2; ev_type=ButtonPress; goto handle_mouse;
-		case NSRightMouseDown:   ev_button=3; ev_type=ButtonPress; goto handle_mouse;
-		case NSLeftMouseUp:      ev_button=1; ev_type=ButtonRelease; goto handle_mouse;
-		case NSOtherMouseUp:     ev_button=2; ev_type=ButtonRelease; goto handle_mouse;
-		case NSRightMouseUp:     ev_button=3; ev_type=ButtonRelease; goto handle_mouse;
-		case NSLeftMouseDragged:  ev_button=1; ev_type=MotionNotify; goto handle_mouse;
-		case NSOtherMouseDragged: ev_button=2; ev_type=MotionNotify; goto handle_mouse;
-		case NSRightMouseDragged: ev_button=3; ev_type=MotionNotify; goto handle_mouse;
+		case NSLeftMouseDown:    ev_button=1; ev_type=ButtonPress; goto check_subtype;
+		case NSOtherMouseDown:   ev_button=2; ev_type=ButtonPress; goto check_subtype;
+		case NSRightMouseDown:   ev_button=3; ev_type=ButtonPress; goto check_subtype;
+		case NSLeftMouseUp:      ev_button=1; ev_type=ButtonRelease; goto check_subtype;
+		case NSOtherMouseUp:     ev_button=2; ev_type=ButtonRelease; goto check_subtype;
+		case NSRightMouseUp:     ev_button=3; ev_type=ButtonRelease; goto check_subtype;
+		case NSLeftMouseDragged:  ev_button=1; ev_type=MotionNotify; goto check_subtype;
+		case NSOtherMouseDragged: ev_button=2; ev_type=MotionNotify; goto check_subtype;
+		case NSRightMouseDragged: ev_button=3; ev_type=MotionNotify; goto check_subtype;
+		
+check_subtype:
+			if ([e subtype] != NSTabletPointEventSubtype) goto handle_mouse;
+			// fall through to get tablet data
 		case NSTabletPoint:
 			pressure = [e pressure];
 			tilt_x = [e tilt].x;
-			tilt_y = [e tilt].y; // fall through
+			tilt_y = [e tilt].y; 
+			// fall through to normal mouse handling
+
 		case NSMouseMoved: ev_button=0; ev_type=MotionNotify; goto handle_mouse;
-		handle_mouse:
 
-//      if ([e subtype] == NSTabletPointEventSubtype) pressure = [e pressure];
+handle_mouse:
 		DarwinSendPointerEvents(ev_type, ev_button, pointer_x, pointer_y,
 			pressure, tilt_x, tilt_y);
 		break;
 
+		case NSTabletProximity:
+			DarwinSendProximityEvents([e isEnteringProximity]?ProximityIn:ProximityOut,
+				pointer_x, pointer_y);
+		break;
+
 		case NSScrollWheel:
 			DarwinSendScrollEvents([e deltaX], [e deltaY], pointer_x, pointer_y,
 				pressure, tilt_x, tilt_y);
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 86e7704..cd2b49a 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -65,6 +65,10 @@ in this Software without prior written authorization from The Open Group.
 #define SCROLLWHEELLEFTFAKE  6
 #define SCROLLWHEELRIGHTFAKE 7
 
+/* These values were chosen to match the output of xinput under Linux */
+#define SCALEFACTOR_TILT        64.0
+#define SCALEFACTOR_PRESSURE    1000.0
+
 #define _APPLEWM_SERVER_
 #include "applewmExt.h"
 #include <X11/extensions/applewm.h>
@@ -362,26 +366,18 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	static int darwinFakeMouseButtonMask = 0;
 	int i, num_events;
 
-    //DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
+//    DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
     
 	if(!darwinEvents) {
 		ErrorF("DarwinSendPointerEvents called before darwinEvents was initialized\n");
 		return;
 	}
-	/* I can't find a spec for this, but at least GTK expects that tablets are
-     just like mice, except they have either one or three extra valuators, in this
-     order:
-     
-     X coord, Y coord, pressure, X tilt, Y tilt
-     Pressure and tilt should be represented natively as floats; unfortunately,
-     we can't do that.  Again, GTK seems to record the min/max of each valuator,
-     and then perform scaling back to float itself using that info. Soo.... */
-
-	int valuators[5] = {pointer_x, pointer_y, 
-		      pressure * INT32_MAX * 1.0f, 
-		      tilt_x * INT32_MAX * 1.0f, 
-		      tilt_y * INT32_MAX * 1.0f};
 
+	int valuators[5] = {pointer_x, pointer_y, pressure * SCALEFACTOR_PRESSURE, 
+		      tilt_x * SCALEFACTOR_TILT, tilt_y * SCALEFACTOR_TILT};
+	
+		DEBUG_LOG("Valuators: {%d,%d,%d,%d,%d}\n", 
+			valuators[0], valuators[1], valuators[2], valuators[3], valuators[4]);
 	if (ev_type == ButtonPress && darwinFakeButtons && ev_button == 1) {
 		// Mimic multi-button mouse with modifier-clicks
 		// If both sets of modifiers are pressed,
@@ -450,16 +446,16 @@ void DarwinSendKeyboardEvents(int ev_type, int keycode) {
     } mieqEnqueue_unlock();
 }
 
-void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y, 
-			       float pressure, float tilt_x, float tilt_y) {
+void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y) {
 	int i, num_events;
-	int valuators[5] = {pointer_x, pointer_y, 
-		      pressure * INT32_MAX * 1.0f, 
-		      tilt_x * INT32_MAX * 1.0f, 
-		      tilt_y * INT32_MAX * 1.0f};
 
+	// tilt and pressure have no meaning for a Prox event
+	int valuators[5] = {pointer_x, pointer_y, 0, 0, 0};  
+
+	DEBUG_LOG("DarwinSendProximityEvents(%d, %d, %d)\n", ev_type, pointer_x, pointer_y);
+	
 	if(!darwinEvents) {
-		ErrorF("DarwinSendProximityvents called before darwinEvents was initialized\n");
+		ErrorF("DarwinSendProximityEvents called before darwinEvents was initialized\n");
 		return;
 	}
 
diff --git a/hw/xquartz/darwinEvents.h b/hw/xquartz/darwinEvents.h
index dd3f81c..4a619c9 100644
--- a/hw/xquartz/darwinEvents.h
+++ b/hw/xquartz/darwinEvents.h
@@ -34,8 +34,7 @@ void DarwinEQPointerPost(DeviceIntPtr pDev, xEventPtr e);
 void DarwinEQSwitchScreen(ScreenPtr pScreen, Bool fromDIX);
 void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int pointer_y,
 			     float pressure, float tilt_x, float tilt_y);
-void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y, 
-			       float pressure, float tilt_x, float tilt_y);
+void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y);
 void DarwinSendKeyboardEvents(int ev_type, int keycode);
 void DarwinSendScrollEvents(float count_x, float count_y, int pointer_x, int pointer_y,
 			    float pressure, float tilt_x, float tilt_y);
commit f65a1a62f9eac2f6620d5d469dbf6c79b2eadab7
Author: Hong Liu <hong.liu at intel.com>
Date:   Tue Apr 29 09:00:11 2008 -0700

    Keep rotation wrappers in place while transforms are in use
    
    LeaveVT/EnterVT cycles will free/realloc shadow frame buffers. Because of
    this, the presense/absence of that data is insufficient to know whether
    the screen function wrappers are necessary. Instead, the 'transform_in_use'
    flag should be used.
    
    This patch also adds 'xf86RotateFreeShadow' for drivers to use at LeaveVT
    time to free the rotation data; it will be reallocated on EnterVT.

diff --git a/hw/xfree86/loader/xf86sym.c b/hw/xfree86/loader/xf86sym.c
index 24fc44c..9833d34 100644
--- a/hw/xfree86/loader/xf86sym.c
+++ b/hw/xfree86/loader/xf86sym.c
@@ -942,6 +942,7 @@ _X_HIDDEN void *xfree86LookupTab[] = {
     SYMFUNC(xf86CrtcDestroy)
     SYMFUNC(xf86CrtcInUse)
     SYMFUNC(xf86CrtcSetScreenSubpixelOrder)
+    SYMFUNC(xf86RotateFreeShadow)
     SYMFUNC(xf86RotateCloseScreen)
     SYMFUNC(xf86CrtcRotate)
     SYMFUNC(xf86CrtcSetMode)
diff --git a/hw/xfree86/modes/xf86Crtc.h b/hw/xfree86/modes/xf86Crtc.h
index 2d723a5..83b1f13 100644
--- a/hw/xfree86/modes/xf86Crtc.h
+++ b/hw/xfree86/modes/xf86Crtc.h
@@ -665,6 +665,12 @@ Bool
 xf86CrtcRotate (xf86CrtcPtr crtc, DisplayModePtr mode, Rotation rotation);
 
 /*
+ * free shadow memory allocated for all crtcs
+ */
+void
+xf86RotateFreeShadow(ScrnInfoPtr pScrn);
+
+/*
  * Clean up rotation during CloseScreen
  */
 void
diff --git a/hw/xfree86/modes/xf86Rotate.c b/hw/xfree86/modes/xf86Rotate.c
index e2d6295..8f34032 100644
--- a/hw/xfree86/modes/xf86Rotate.c
+++ b/hw/xfree86/modes/xf86Rotate.c
@@ -457,8 +457,7 @@ xf86RotateDestroy (xf86CrtcPtr crtc)
     }
 
     for (c = 0; c < xf86_config->num_crtc; c++)
-	if (xf86_config->crtc[c]->rotatedPixmap ||
-	    xf86_config->crtc[c]->rotatedData)
+	if (xf86_config->crtc[c]->transform_in_use)
 	    return;
 
     /*
@@ -479,6 +478,24 @@ xf86RotateDestroy (xf86CrtcPtr crtc)
 }
 
 _X_EXPORT void
+xf86RotateFreeShadow(ScrnInfoPtr pScrn)
+{
+    xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);
+    int c;
+
+   for (c = 0; c < config->num_crtc; c++) {
+       xf86CrtcPtr crtc = config->crtc[c];
+
+       if (crtc->rotatedPixmap || crtc->rotatedData) {
+	   crtc->funcs->shadow_destroy(crtc, crtc->rotatedPixmap,
+				crtc->rotatedData);
+	   crtc->rotatedPixmap = NULL;
+	   crtc->rotatedData = NULL;
+       }
+   }
+}
+
+_X_EXPORT void
 xf86RotateCloseScreen (ScreenPtr screen)
 {
     ScrnInfoPtr		scrn = xf86Screens[screen->myNum];
commit e48f6bcd94b310e5c79939bdb1703f9555a3cdd1
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Apr 29 08:30:51 2008 -0700

    Debug XKB bits

diff --git a/xkb/ddxLoad.c b/xkb/ddxLoad.c
index d80ce62..c95ef4d 100644
--- a/xkb/ddxLoad.c
+++ b/xkb/ddxLoad.c
@@ -75,6 +75,9 @@ THE USE OR PERFORMANCE OF THIS SOFTWARE.
 #define PATHSEPARATOR "/"
 #endif
 
+#define DEBUG
+#define xkbDebugFlags	65535
+
 #ifdef WIN32
 
 #include <X11/Xwindows.h>
@@ -350,11 +353,12 @@ unsigned	missing;
     if ((names->keycodes==NULL)&&(names->types==NULL)&&
 	(names->compat==NULL)&&(names->symbols==NULL)&&
 	(names->geometry==NULL)) {
+	LogMessage (X_ERROR, "XKB: missing XKB definition\n");
         return 0;
     }
     else if (!XkbDDXCompileKeymapByNames(xkb,names,want,need,
                                          nameRtrn,nameRtrnLen)){
-	DebugF("Couldn't compile keymap file\n");
+	LogMessage (X_ERROR, "Couldn't compile keymap file\n");
 	return 0;
     }
     file= XkbDDXOpenConfigFile(nameRtrn,fileName,PATH_MAX);
commit 4c7ca04362ca74cd54d76f6a05978b64c7598ead
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Apr 29 08:30:17 2008 -0700

    kludge around glx crashes during server exit

diff --git a/GL/glx/glxext.c b/GL/glx/glxext.c
index 85d8deb..4519555 100644
--- a/GL/glx/glxext.c
+++ b/GL/glx/glxext.c
@@ -378,7 +378,7 @@ void glxSuspendClients(void)
     int i;
 
     for (i = 1; i < currentMaxClients; i++) {
-	if (clients[i] && glxGetClient(clients[i])->inUse)
+	if (clients[i] && clients[i]->osPrivate && glxGetClient(clients[i])->inUse)
 	    IgnoreClient(clients[i]);
     }
 
commit 15cd90455813f67b8e98e5164c6ae85bf42739a7
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Apr 29 08:29:42 2008 -0700

    Handle transform failure when computing shadow damage area.
    
    PictureTransformBounds can fail, when this happens, damage the entire screen
    so that the shadow gets repainted correctly.

diff --git a/hw/xfree86/modes/xf86Rotate.c b/hw/xfree86/modes/xf86Rotate.c
index 8925fad..0090658 100644
--- a/hw/xfree86/modes/xf86Rotate.c
+++ b/hw/xfree86/modes/xf86Rotate.c
@@ -177,7 +177,17 @@ xf86CrtcDamageShadow (xf86CrtcPtr crtc)
     damage_box.x2 = crtc->mode.HDisplay;
     damage_box.y1 = 0;
     damage_box.y2 = crtc->mode.VDisplay;
-    PictureTransformBounds (&damage_box, &crtc->crtc_to_framebuffer);
+    if (1 || !PictureTransformBounds (&damage_box, &crtc->crtc_to_framebuffer))
+    {
+	damage_box.x1 = 0;
+	damage_box.y1 = 0;
+	damage_box.x2 = pScreen->width;
+	damage_box.y2 = pScreen->height;
+    }
+    if (damage_box.x1 < 0) damage_box.x1 = 0;
+    if (damage_box.y1 < 0) damage_box.y1 = 0;
+    if (damage_box.x2 > pScreen->width) damage_box.x2 = pScreen->width;
+    if (damage_box.y2 > pScreen->height) damage_box.y2 = pScreen->height;
     REGION_INIT (pScreen, &damage_region, &damage_box, 1);
     DamageDamageRegion (&(*pScreen->GetScreenPixmap)(pScreen)->drawable,
 			&damage_region);
diff --git a/render/matrix.c b/render/matrix.c
index 603281e..560ee94 100644
--- a/render/matrix.c
+++ b/render/matrix.c
@@ -84,7 +84,6 @@ _X_EXPORT Bool
 PictureTransformPoint (PictTransformPtr transform,
 		       PictVectorPtr	vector)
 {
-    PictVector	    result;
     int		    i, j;
     xFixed_32_32    partial;
     xFixed_34_30    v[3];
@@ -227,7 +226,7 @@ PictureTransformTranslate (PictTransformPtr forward,
     return TRUE;
 }
 
-_X_EXPORT void
+_X_EXPORT Bool
 PictureTransformBounds (BoxPtr b, PictTransformPtr matrix)
 {
     PictVector	v[4];
@@ -240,7 +239,8 @@ PictureTransformBounds (BoxPtr b, PictTransformPtr matrix)
     v[3].vector[0] = F (b->x1);    v[3].vector[1] = F (b->y2);	v[3].vector[2] = F(1);
     for (i = 0; i < 4; i++)
     {
-	PictureTransformPoint (matrix, &v[i]);
+	if (!PictureTransformPoint (matrix, &v[i]))
+	    return FALSE;
 	x1 = xFixedToInt (v[i].vector[0]);
 	y1 = xFixedToInt (v[i].vector[1]);
 	x2 = xFixedToInt (xFixedCeil (v[i].vector[0]));
@@ -258,6 +258,7 @@ PictureTransformBounds (BoxPtr b, PictTransformPtr matrix)
 	    if (y2 > b->y2) b->y2 = y2;
 	}
     }
+    return TRUE;
 }
 
 _X_EXPORT Bool
diff --git a/render/picturestr.h b/render/picturestr.h
index c993e93..ed77fe3 100644
--- a/render/picturestr.h
+++ b/render/picturestr.h
@@ -727,7 +727,7 @@ PictureTransformTranslate (PictTransformPtr forward,
 			   PictTransformPtr reverse,
 			   xFixed tx, xFixed ty);
 
-void
+Bool
 PictureTransformBounds (BoxPtr b, PictTransformPtr matrix);
 
 Bool
commit b93c9a1553f981e6b38dd0a33db8f766847ce232
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Apr 29 08:27:57 2008 -0700

    Fix up kdrive build (again)

diff --git a/configure.ac b/configure.ac
index 8e890f6..07a334c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1962,7 +1962,7 @@ if test "$KDRIVE" = yes; then
     
     KDRIVE_CFLAGS="$XSERVER_CFLAGS -DHAVE_KDRIVE_CONFIG_H $TSLIB_CFLAGS"
 
-    KDRIVE_PURE_LIBS="$FB_LIB $MI_LIB $FIXES_LIB $XEXT_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $GLX_LIBS $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB $OS_LIB"
+    KDRIVE_PURE_LIBS="$FB_LIB $MI_LIB $FIXES_LIB $XEXT_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $GLX_LIBS $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_SHADOW_LIB $MIEXT_DAMAGE_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB $OS_LIB"
     KDRIVE_LIB='$(top_builddir)/hw/kdrive/src/libkdrive.a'
     case $host_os in
 	*linux*)
@@ -1973,7 +1973,7 @@ if test "$KDRIVE" = yes; then
     KDRIVE_STUB_LIB='$(top_builddir)/hw/kdrive/src/libkdrivestubs.a'
     KDRIVE_LOCAL_LIBS="$TSLIB_LIBS $DIX_LIB $KDRIVE_LIB $KDRIVE_STUB_LIB $CONFIG_LIB"
     KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $FB_LIB $MI_LIB $KDRIVE_PURE_LIBS"
-    KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB"
+    KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB $XEXT_LIB"
     KDRIVE_LIBS="$KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS"
 
     # check if we can build Xephyr
commit d5ab89f4f1acbe2614036e8934122185ac0f81ee
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 28 15:52:24 2008 -0700

    XQuartz: Unset CFProcessPath... blech
    (cherry picked from commit ce4fbfbc75c62a092214d140c7550279aebe69ef)

diff --git a/hw/xquartz/quartzStartup.c b/hw/xquartz/quartzStartup.c
index 7b6a1a6..a4472e6 100644
--- a/hw/xquartz/quartzStartup.c
+++ b/hw/xquartz/quartzStartup.c
@@ -98,6 +98,12 @@ int main(int argc, char **argv, char **envp) {
     int         i;
     int         fd[2];
 
+    /* Unset CFProcessPath, so our children don't inherit this kludge we need
+     * to load our nib.  If an xterm gets this set, then it fails to
+     * 'open hi.txt' properly.
+     */
+    unsetenv("CFProcessPath");
+    
     // Make a pipe to pass events
     assert( pipe(fd) == 0 );
     darwinEventReadFD = fd[0];
commit 0c2312b21b6700c1425baccaf9c26150b4f0fd6a
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 28 15:28:21 2008 -0700

    XQuartz: xprIsX11Window can be called from the Appkit thread (see X11Application.m)
    (cherry picked from commit 22cf72437601c07b8a6c744b4f2f1f4cd6713e60)

diff --git a/hw/xquartz/xpr/xprFrame.c b/hw/xquartz/xpr/xprFrame.c
index edb4128..9fa9424 100644
--- a/hw/xquartz/xpr/xprFrame.c
+++ b/hw/xquartz/xpr/xprFrame.c
@@ -453,8 +453,6 @@ xprGetXWindow(xp_window_id wid)
 {
     RootlessWindowRec *winRec;
 
-    TA_SERVER();
-    
     if (window_hash == NULL)
         return NULL;
 
@@ -474,8 +472,6 @@ xprGetXWindowFromAppKit(int windowNumber)
     Bool ret;
     xp_window_id wid;
 
-    TA_SERVER();
-    
     if (window_hash == NULL)
         return FALSE;
 
@@ -507,8 +503,6 @@ xprIsX11Window(void *nsWindow, int windowNumber)
     Bool ret;
     xp_window_id wid;
 
-    TA_SERVER();
-    
     if (window_hash == NULL)
         return FALSE;
 
commit c3dc4bdbb018c0606d561e2dfb9a36e9297fa312
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 28 15:42:02 2008 -0700

    XQuartz: Disabled DPMS extension
    (cherry picked from commit 1448fed9b6d484f471b9b2982c76ca921a9273b9)

diff --git a/configure.ac b/configure.ac
index 67606c7..f695551 100644
--- a/configure.ac
+++ b/configure.ac
@@ -524,11 +524,11 @@ AC_ARG_ENABLE(glx-tls,        AS_HELP_STRING([--enable-glx-tls], [Build GLX with
 
 dnl Extensions.
 AC_ARG_ENABLE(registry,       AS_HELP_STRING([--disable-registry], [Build string registry module (default: enabled)]), [XREGISTRY=$enableval], [XREGISTRY=yes])
-AC_ARG_ENABLE(composite,      AS_HELP_STRING([--disable-composite], [Build Composite extension (default: enabled)]), [COMPOSITE=$enableval], [COMPOSITE=auto])
+AC_ARG_ENABLE(composite,      AS_HELP_STRING([--disable-composite], [Build Composite extension (default: enabled)]), [COMPOSITE=$enableval], [COMPOSITE=yes])
 AC_ARG_ENABLE(mitshm,         AS_HELP_STRING([--disable-shm], [Build SHM extension (default: enabled)]), [MITSHM=$enableval], [MITSHM=yes])
 AC_ARG_ENABLE(xres,           AS_HELP_STRING([--disable-xres], [Build XRes extension (default: enabled)]), [RES=$enableval], [RES=yes])
 AC_ARG_ENABLE(xtrap,          AS_HELP_STRING([--disable-xtrap], [Build XTrap extension (default: enabled)]), [XTRAP=$enableval], [XTRAP=yes])
-AC_ARG_ENABLE(record,         AS_HELP_STRING([--disable-record], [Build Record extension (default: disabled)]), [RECORD=$enableval], [RECORD=no])
+AC_ARG_ENABLE(record,         AS_HELP_STRING([--enable-record], [Build Record extension (default: disabled)]), [RECORD=$enableval], [RECORD=no])
 AC_ARG_ENABLE(xv,             AS_HELP_STRING([--disable-xv], [Build Xv extension (default: enabled)]), [XV=$enableval], [XV=yes])
 AC_ARG_ENABLE(xvmc,           AS_HELP_STRING([--disable-xvmc], [Build XvMC extension (default: enabled)]), [XVMC=$enableval], [XVMC=yes])
 AC_ARG_ENABLE(dga,            AS_HELP_STRING([--disable-dga], [Build DGA extension (default: auto)]), [DGA=$enableval], [DGA=auto])
@@ -644,6 +644,40 @@ XORG_CHECK_LINUXDOC
 dnl Handle installing libxf86config
 AM_CONDITIONAL(INSTALL_LIBXF86CONFIG, [test "x$INSTALL_LIBXF86CONFIG" = xyes])
 
+dnl XQuartz DDX Detection... Yes, it's ugly to have it here... but we need to handle this early on
+case $host_os in
+	darwin*)
+		if test x$XQUARTZ = xauto; then
+			AC_CACHE_CHECK([whether to build Xquartz],xorg_cv_Carbon_framework,[
+		 		save_LDFLAGS=$LDFLAGS
+				LDFLAGS="$LDFLAGS -framework Carbon"
+				AC_LINK_IFELSE([char FSFindFolder(); int main() { FSFindFolder(); return 0;}],
+				[xorg_cv_Carbon_framework=yes],
+				[xorg_cv_Carbon_framework=no])
+			LDFLAGS=$save_LDFLAGS])
+                
+			if test "X$xorg_cv_Carbon_framework" = Xyes; then
+				XQUARTZ=yes
+			else
+				XQUARTZ=no
+			fi
+		fi
+
+		if test "x$XQUARTZ" = xyes ; then
+			XQUARTZ=yes
+			XVFB=no
+			XNEST=no
+
+			COMPOSITE=no
+			DGA=no
+			DPMSExtension=no
+			XF86BIGFONT=no
+			XF86MISC=no
+			XF86VIDMODE=no
+		fi
+		;;
+esac
+
 dnl ---------------------------------------------------------------------------
 dnl Extension section
 dnl ---------------------------------------------------------------------------
@@ -780,18 +814,6 @@ if test "x$XREGISTRY" = xyes; then
 	AC_DEFINE(XREGISTRY, 1, [Build registry module])
 fi
 
-dnl XQuartz DDX Detection... Yes, it's ugly to have it here... but we need to disable COMPOSITE for 
-if test "x$COMPOSITE" = xauto; then
-	case $host_os in
-		darwin*)
-			test "x$XQUARTZ" = xyes -o "x$XQUARTZ" = xauto && COMPOSITE=no
-			;;
-		*)
-			COMPOSITE=yes
-			;;
-	esac
-fi
-
 AM_CONDITIONAL(COMPOSITE, [test "x$COMPOSITE" = xyes])
 if test "x$COMPOSITE" = xyes; then
 	AC_DEFINE(COMPOSITE, 1, [Support Composite Extension])
@@ -1706,22 +1728,6 @@ AM_CONDITIONAL(XWIN_RANDR, [test "x$XWIN" = xyes])
 AM_CONDITIONAL(XWIN_XV, [test "x$XWIN" = xyes && test "x$XV" = xyes])
 
 dnl Darwin / OS X DDX
-if test "X$XQUARTZ" = Xauto; then
-	AC_CACHE_CHECK([whether to build Xquartz],xorg_cv_Carbon_framework,[
-	 	save_LDFLAGS=$LDFLAGS
-		LDFLAGS="$LDFLAGS -framework Carbon"
-		AC_LINK_IFELSE([char FSFindFolder(); int main() { FSFindFolder(); return 0;}],
-			[xorg_cv_Carbon_framework=yes],
-			[xorg_cv_Carbon_framework=no])
-		LDFLAGS=$save_LDFLAGS])
-                
-	if test "X$xorg_cv_Carbon_framework" = Xyes; then
-		XQUARTZ=yes
-	else
-		XQUARTZ=no
-	fi
-fi
-
 if test "x$XQUARTZ" = xyes; then
 	AC_DEFINE(XQUARTZ,1,[Have Quartz])
 	AC_DEFINE(ROOTLESS,1,[Build Rootless code])
@@ -1733,23 +1739,6 @@ if test "x$XQUARTZ" = xyes; then
 	AC_CHECK_LIB([Xplugin],[xp_init],[:])
 
 	CFLAGS="${CFLAGS} -DROOTLESS_WORKAROUND -DNO_ALLOCA"
-
-	if test "x$XF86MISC" = xyes || test "x$XF86MISC" = xauto; then
-		AC_MSG_NOTICE([Disabling XF86Misc extension])
-		XF86MISC=no
-	fi
-	if test "x$XF86VIDMODE" = xyes || test "x$XF86VIDMODE" = xauto; then
-		AC_MSG_NOTICE([Disabling XF86VidMode extension])
-		XF86VIDMODE=no
-	fi
-	if test "x$XF86BIGFONT" = xyes || test "x$XF86BIGFONT" = xauto; then
-		AC_MSG_NOTICE([Disabling XF86BigFont extension])
-		XF86BIGFONT=no
-	fi
-	if test "x$DGA" = xyes || test "x$DGA" = xauto; then
-		AC_MSG_NOTICE([Disabling DGA extension])
-		DGA=no
-	fi
 fi
 
 # Support for objc in autotools is minimal and not documented.
diff --git a/hw/xquartz/Makefile.am b/hw/xquartz/Makefile.am
index 1465a52..b2674be 100644
--- a/hw/xquartz/Makefile.am
+++ b/hw/xquartz/Makefile.am
@@ -19,7 +19,6 @@ DIST_SUBDIRS = GL xpr bundle
 libXquartz_la_SOURCES = \
 	$(top_srcdir)/fb/fbcmap_mi.c \
 	$(top_srcdir)/mi/miinitext.c \
-	$(top_srcdir)/Xext/dpmsstubs.c \
 	X11Application.m \
 	X11Controller.m \
 	applewm.c \
commit 07382a70c7ac9807dfb31821a4763bea2309bde6
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 28 12:36:54 2008 -0700

    XQuartz: Added thread debugging to xprFrame.c
    (cherry picked from commit 41542502b321c697271c1752525b600872b6df96)

diff --git a/hw/xquartz/xpr/xprFrame.c b/hw/xquartz/xpr/xprFrame.c
index 901efca..edb4128 100644
--- a/hw/xquartz/xpr/xprFrame.c
+++ b/hw/xquartz/xpr/xprFrame.c
@@ -43,6 +43,8 @@
 #include <X11/Xatom.h>
 #include "windowstr.h"
 
+#include "threadSafety.h"
+
 #include <pthread.h>
 
 #define DEFINE_ATOM_HELPER(func,atom_name)                      \
@@ -69,7 +71,8 @@ static inline xp_error
 xprConfigureWindow(xp_window_id id, unsigned int mask,
                    const xp_window_changes *values)
 {
-  //  ErrorF("xprConfigureWindow()\n");
+    TA_SERVER();
+
     if (!no_configure_window)
         return xp_configure_window(id, mask, values);
     else
@@ -84,6 +87,8 @@ xprSetNativeProperty(RootlessWindowPtr pFrame)
     unsigned int native_id;
     long data;
 
+    TA_SERVER();
+    
     err = xp_get_native_window((xp_window_id) pFrame->wid, &native_id);
     if (err == Success)
     {
@@ -108,6 +113,8 @@ xprCreateFrame(RootlessWindowPtr pFrame, ScreenPtr pScreen,
     unsigned int mask = 0;
     xp_error err;
 
+    TA_SERVER();
+    
     wc.x = newX;
     wc.y = newY;
     wc.width = pFrame->width;
@@ -169,6 +176,8 @@ xprCreateFrame(RootlessWindowPtr pFrame, ScreenPtr pScreen,
 void
 xprDestroyFrame(RootlessFrameID wid)
 {
+    TA_SERVER();
+    
     pthread_mutex_lock(&window_hash_mutex);
     x_hash_table_remove(window_hash, wid);
     pthread_mutex_unlock(&window_hash_mutex);
@@ -183,6 +192,8 @@ xprDestroyFrame(RootlessFrameID wid)
 void
 xprMoveFrame(RootlessFrameID wid, ScreenPtr pScreen, int newX, int newY)
 {
+    TA_SERVER();
+    
     xp_window_changes wc;
 
     wc.x = newX;
@@ -202,6 +213,8 @@ xprResizeFrame(RootlessFrameID wid, ScreenPtr pScreen,
 {
     xp_window_changes wc;
 
+    TA_SERVER();
+    
     wc.x = newX;
     wc.y = newY;
     wc.width = newW;
@@ -223,7 +236,9 @@ xprRestackFrame(RootlessFrameID wid, RootlessFrameID nextWid)
 {
     xp_window_changes wc;
 
-    /* Stack frame below nextWid it if it exists, or raise
+    TA_SERVER();
+    
+   /* Stack frame below nextWid it if it exists, or raise
        frame above everything otherwise. */
 
     if (nextWid == NULL)
@@ -249,6 +264,8 @@ xprReshapeFrame(RootlessFrameID wid, RegionPtr pShape)
 {
     xp_window_changes wc;
 
+    TA_SERVER();
+    
     if (pShape != NULL)
     {
         wc.shape_nrects = REGION_NUM_RECTS(pShape);
@@ -274,6 +291,8 @@ xprUnmapFrame(RootlessFrameID wid)
 {
     xp_window_changes wc;
 
+    TA_SERVER();
+    
     wc.stack_mode = XP_UNMAPPED;
     wc.sibling = 0;
 
@@ -292,6 +311,8 @@ xprStartDrawing(RootlessFrameID wid, char **pixelData, int *bytesPerRow)
     unsigned int rowbytes[2];
     xp_error err;
 
+    TA_SERVER();
+    
     err = xp_lock_window((xp_window_id) wid, NULL, NULL, data, rowbytes, NULL);
     if (err != Success)
         FatalError("Could not lock window %i for drawing.", (int) wid);
@@ -307,6 +328,8 @@ xprStartDrawing(RootlessFrameID wid, char **pixelData, int *bytesPerRow)
 void
 xprStopDrawing(RootlessFrameID wid, Bool flush)
 {
+    TA_SERVER();
+    
     xp_unlock_window((xp_window_id) wid, flush);
 }
 
@@ -317,6 +340,8 @@ xprStopDrawing(RootlessFrameID wid, Bool flush)
 void
 xprUpdateRegion(RootlessFrameID wid, RegionPtr pDamage)
 {
+    TA_SERVER();
+    
     xp_flush_window((xp_window_id) wid);
 }
 
@@ -328,6 +353,8 @@ void
 xprDamageRects(RootlessFrameID wid, int nrects, const BoxRec *rects,
                int shift_x, int shift_y)
 {
+    TA_SERVER();
+    
     xp_mark_window((xp_window_id) wid, nrects, rects, shift_x, shift_y);
 }
 
@@ -341,6 +368,8 @@ xprSwitchWindow(RootlessWindowPtr pFrame, WindowPtr oldWin)
 {
     DeleteProperty(serverClient, oldWin, xa_native_window_id());
 
+    TA_SERVER();
+    
     xprSetNativeProperty(pFrame);
 }
 
@@ -352,6 +381,8 @@ Bool xprDoReorderWindow(RootlessWindowPtr pFrame)
 {
     WindowPtr pWin = pFrame->win;
 
+    TA_SERVER();
+    
     return AppleWMDoReorderWindow(pWin);
 }
 
@@ -364,6 +395,8 @@ void
 xprCopyWindow(RootlessFrameID wid, int dstNrects, const BoxRec *dstRects,
               int dx, int dy)
 {
+    TA_SERVER();
+    
     xp_copy_window((xp_window_id) wid, (xp_window_id) wid,
                    dstNrects, dstRects, dx, dy);
 }
@@ -398,6 +431,8 @@ xprInit(ScreenPtr pScreen)
 {
     RootlessInit(pScreen, &xprRootlessProcs);
 
+    TA_SERVER();
+    
     rootless_CopyBytes_threshold = xp_copy_bytes_threshold;
     rootless_FillBytes_threshold = xp_fill_bytes_threshold;
     rootless_CompositePixels_threshold = xp_composite_area_threshold;
@@ -418,6 +453,8 @@ xprGetXWindow(xp_window_id wid)
 {
     RootlessWindowRec *winRec;
 
+    TA_SERVER();
+    
     if (window_hash == NULL)
         return NULL;
 
@@ -437,6 +474,8 @@ xprGetXWindowFromAppKit(int windowNumber)
     Bool ret;
     xp_window_id wid;
 
+    TA_SERVER();
+    
     if (window_hash == NULL)
         return FALSE;
 
@@ -468,6 +507,8 @@ xprIsX11Window(void *nsWindow, int windowNumber)
     Bool ret;
     xp_window_id wid;
 
+    TA_SERVER();
+    
     if (window_hash == NULL)
         return FALSE;
 
@@ -498,6 +539,8 @@ xprHideWindows(Bool hide)
     int screen;
     WindowPtr pRoot, pWin;
 
+    TA_SERVER();
+    
     for (screen = 0; screen < screenInfo.numScreens; screen++) {
         pRoot = WindowTable[screenInfo.screens[screen]->myNum];
         RootlessFrameID prevWid = NULL;
commit 8349732a6720652bfbad7874a952be73a0e8e77b
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Mon Apr 28 21:09:35 2008 +0200

    EXA: Try to accelerate non-antialiased text via the glyph cache as well.
    
    Treat 1 bit glyphs and masks as PICT_a8 in the glyph cache. We're not able to
    accelerate them otherwise.

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index 08ec097..ff665d5 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -374,6 +374,10 @@ exaGlyphCacheUploadGlyph(ScreenPtr         pScreen,
     if (exaPixmapIsOffscreen(pGlyphPixmap))
 	return FALSE;
 
+    /* UploadToScreen only works if bpp match */
+    if (pGlyphPixmap->drawable.bitsPerPixel != pCachePixmap->drawable.bitsPerPixel)
+	return FALSE;
+
     /* cache pixmap must be offscreen. */
     pixmaps[0].as_dst = TRUE;
     pixmaps[0].as_src = FALSE;
@@ -524,6 +528,9 @@ exaBufferGlyph(ScreenPtr         pScreen,
 
     if (buffer->count == GLYPH_BUFFER_SIZE)
 	return ExaGlyphNeedFlush;
+
+    if (PICT_FORMAT_BPP(format) == 1)
+	format = PICT_a8;
     
     for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
 	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
@@ -796,6 +803,14 @@ exaGlyphs (CARD8 	 op,
 	    return;
 	width = extents.x2 - extents.x1;
 	height = extents.y2 - extents.y1;
+
+	if (maskFormat->depth == 1) {
+	    PictFormatPtr a8Format = PictureMatchFormat (pScreen, 8, PICT_a8);
+
+	    if (a8Format)
+		maskFormat = a8Format;
+	}
+
 	pMaskPixmap = (*pScreen->CreatePixmap) (pScreen, width, height,
 						maskFormat->depth,
 						CREATE_PIXMAP_USAGE_SCRATCH);
commit a65d530040bb561ba88c5d8c71633a7c0bf11e89
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Mon Apr 28 21:03:12 2008 +0200

    EXA: Accumulate glyphs whenever possible, for full benefits of the glyph cache.

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index b618365..08ec097 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -662,6 +662,79 @@ GlyphExtents (int		nlist,
     }
 }
 
+/**
+ * Returns TRUE if the glyphs in the lists intersect.  Only checks based on
+ * bounding box, which appears to be good enough to catch most cases at least.
+ */
+static Bool
+exaGlyphsIntersect(int nlist, GlyphListPtr list, GlyphPtr *glyphs)
+{
+    int x1, x2, y1, y2;
+    int n;
+    GlyphPtr glyph;
+    int x, y;
+    BoxRec extents;
+    Bool first = TRUE;
+
+    x = 0;
+    y = 0;
+    while (nlist--) {
+       x += list->xOff;
+       y += list->yOff;
+       n = list->len;
+       list++;
+       while (n--) {
+           glyph = *glyphs++;
+
+           if (glyph->info.width == 0 || glyph->info.height == 0) {
+               x += glyph->info.xOff;
+               y += glyph->info.yOff;
+               continue;
+           }
+
+           x1 = x - glyph->info.x;
+           if (x1 < MINSHORT)
+               x1 = MINSHORT;
+           y1 = y - glyph->info.y;
+           if (y1 < MINSHORT)
+               y1 = MINSHORT;
+           x2 = x1 + glyph->info.width;
+           if (x2 > MAXSHORT)
+               x2 = MAXSHORT;
+           y2 = y1 + glyph->info.height;
+           if (y2 > MAXSHORT)
+               y2 = MAXSHORT;
+
+           if (first) {
+               extents.x1 = x1;
+               extents.y1 = y1;
+               extents.x2 = x2;
+               extents.y2 = y2;
+               first = FALSE;
+           } else {
+               if (x1 < extents.x2 && x2 > extents.x1 &&
+                   y1 < extents.y2 && y2 > extents.y1)
+               {
+                   return TRUE;
+               }
+
+               if (x1 < extents.x1)
+                  extents.x1 = x1;
+               if (x2 > extents.x2)
+                   extents.x2 = x2;
+               if (y1 < extents.y1)
+                   extents.y1 = y1;
+               if (y2 > extents.y2)
+                   extents.y2 = y2;
+           }
+           x += glyph->info.xOff;
+           y += glyph->info.yOff;
+       }
+    }
+
+    return FALSE;
+}
+
 #define NeedsComponent(f) (PICT_FORMAT_A(f) != 0 && PICT_FORMAT_RGB(f) != 0)
 
 void
@@ -689,6 +762,29 @@ exaGlyphs (CARD8 	 op,
     CARD32	component_alpha;
     ExaGlyphBuffer buffer;
 
+    /* If we don't have a mask format but all the glyphs have the same format
+     * and don't intersect, use the glyph format as mask format for the full
+     * benefits of the glyph cache.
+     */
+    if (!maskFormat) {
+       Bool sameFormat = TRUE;
+       int i;
+
+       maskFormat = list[0].format;
+
+       for (i = 0; i < nlist; i++) {
+           if (maskFormat->format != list[i].format->format) {
+               sameFormat = FALSE;
+               break;
+           }
+       }
+
+       if (!sameFormat || (maskFormat->depth != 1 &&
+			   exaGlyphsIntersect(nlist, list, glyphs))) {
+	   maskFormat = NULL;
+       }
+    }
+
     if (maskFormat)
     {
 	GCPtr	    pGC;
commit e7eaac59c424a205dd106fc7d70734ff4b390f28
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Mon Apr 28 21:00:55 2008 +0200

    EXA: Glyph cache upload tweaks.
    
    Track damage after using UploadToScreen directly.
    
    Don't waste any effort on empty glyphs.

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index 95ff4d8..b618365 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -394,6 +394,12 @@ exaGlyphCacheUploadGlyph(ScreenPtr         pScreen,
 				       pExaPixmap->sys_pitch))
 	return FALSE;
 
+    exaPixmapDirty (pCachePixmap,
+		    CACHE_X(pos) + cacheXoff,
+		    CACHE_Y(pos) + cacheYoff,
+		    CACHE_X(pos) + cacheXoff + pGlyph->info.width,
+		    CACHE_Y(pos) + cacheYoff + pGlyph->info.height);
+
     return TRUE;
 }
 
@@ -737,7 +743,8 @@ exaGlyphs (CARD8 	 op,
 	    glyph = *glyphs++;
 	    pPicture = GlyphPicture (glyph)[pScreen->myNum];
 
-	    if (exaBufferGlyph(pScreen, &buffer, glyph, x, y) == ExaGlyphNeedFlush)
+	    if (glyph->info.width > 0 && glyph->info.height > 0 &&
+		exaBufferGlyph(pScreen, &buffer, glyph, x, y) == ExaGlyphNeedFlush)
 	    {
 		if (maskFormat)
 		    exaGlyphsToMask(pMask, &buffer);
commit cc08c06665ffe29ad44d023d75d0f86e5338875d
Author: Owen Taylor <otaylor at huygens.home.fishsoup.net>
Date:   Mon Apr 28 21:00:55 2008 +0200

    EXA: Use UploadToScreen() for uploads to glyph cache
    
    When possible, use UploadToScreen() rather than CompositePicture()
    to upload glyphs onto the glyph cache pixmap. This avoids allocating
    offscreen memory for each glyph making management of offscreen
    areas much more efficient.

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index 27ecd4a..95ff4d8 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -347,6 +347,56 @@ exaGlyphCacheHashRemove(ExaGlyphCachePtr cache,
 #define CACHE_X(pos) (((pos) % cache->columns) * cache->glyphWidth)
 #define CACHE_Y(pos) (cache->yOffset + ((pos) / cache->columns) * cache->glyphHeight)
 
+/* The most efficient thing to way to upload the glyph to the screen
+ * is to use the UploadToScreen() driver hook; this allows us to
+ * pipeline glyph uploads and to avoid creating offscreen pixmaps for
+ * glyphs that we'll never use again.
+ */
+static Bool
+exaGlyphCacheUploadGlyph(ScreenPtr         pScreen,
+			 ExaGlyphCachePtr  cache,
+			 int               pos,
+			 GlyphPtr          pGlyph)
+{
+    ExaScreenPriv(pScreen);
+    PicturePtr pGlyphPicture = GlyphPicture(pGlyph)[pScreen->myNum];
+    PixmapPtr pGlyphPixmap = (PixmapPtr)pGlyphPicture->pDrawable;
+    ExaPixmapPriv(pGlyphPixmap);
+    PixmapPtr pCachePixmap = (PixmapPtr)cache->picture->pDrawable;
+    ExaMigrationRec pixmaps[1];
+    int cacheXoff, cacheYoff;
+
+    if (!pExaScr->info->UploadToScreen || pExaScr->swappedOut || pExaPixmap->accel_blocked)
+	return FALSE;
+
+    /* If the glyph pixmap is already uploaded, no point in doing
+     * things this way */
+    if (exaPixmapIsOffscreen(pGlyphPixmap))
+	return FALSE;
+
+    /* cache pixmap must be offscreen. */
+    pixmaps[0].as_dst = TRUE;
+    pixmaps[0].as_src = FALSE;
+    pixmaps[0].pPix = pCachePixmap;
+    pixmaps[0].pReg = NULL;
+    exaDoMigration (pixmaps, 1, TRUE);
+
+    pCachePixmap = exaGetOffscreenPixmap ((DrawablePtr)pCachePixmap, &cacheXoff, &cacheYoff);
+    if (!pCachePixmap)
+	return FALSE;
+
+    if (!pExaScr->info->UploadToScreen(pCachePixmap,
+				       CACHE_X(pos) + cacheXoff,
+				       CACHE_Y(pos) + cacheYoff,
+				       pGlyph->info.width,
+				       pGlyph->info.height,
+				       (char *)pExaPixmap->sys_ptr,
+				       pExaPixmap->sys_pitch))
+	return FALSE;
+
+    return TRUE;
+}
+
 static ExaGlyphCacheResult
 exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 			 ExaGlyphCachePtr  cache,
@@ -413,18 +463,23 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 	    cache->evictionPosition = rand() % cache->size;
 	}
 
-	/* Now actually upload the glyph into the cache picture */
+	/* Now actually upload the glyph into the cache picture; if
+	 * we can't do it with UploadToScreen (because the glyph is
+	 * offscreen, etc), we fall back to CompositePicture.
+	 */
+	if (!exaGlyphCacheUploadGlyph(pScreen, cache, pos, pGlyph)) {
+	    CompositePicture (PictOpSrc,
+			      GlyphPicture(pGlyph)[pScreen->myNum],
+			      None,
+			      cache->picture,
+			      0, 0,
+			      0, 0,
+			      CACHE_X(pos),
+			      CACHE_Y(pos),
+			      pGlyph->info.width,
+			      pGlyph->info.height);
+	}
 
-	CompositePicture (PictOpSrc,
-			  GlyphPicture(pGlyph)[pScreen->myNum],
-			  None,
-			  cache->picture,
-			  0, 0,
-			  0, 0,
-			  CACHE_X(pos),
-			  CACHE_Y(pos),
-			  pGlyph->info.width,
-			  pGlyph->info.height);
     }
     
 
commit 13fd2256300b61d88b840952d838f834523f5dd7
Author: Owen Taylor <otaylor at huygens.home.fishsoup.net>
Date:   Mon Apr 28 21:00:55 2008 +0200

    EXA: Clean up debug messages

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index 851e439..27ecd4a 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -260,11 +260,9 @@ exaGlyphCacheHashLookup(ExaGlyphCachePtr cache,
 	    return -1;
 
 	if (memcmp(pGlyph->sha1, cache->glyphs[entryPos].sha1, sizeof(pGlyph->sha1)) == 0){
-	    DBG_GLYPH_CACHE((" found entry at %d\n", slot));
 	    return entryPos;
 	}
 	    
-	DBG_GLYPH_CACHE((" lookup linear probe bumpalong\n"));
 	slot--;
 	if (slot < 0)
 	    slot = cache->hashSize - 1;
@@ -284,7 +282,6 @@ exaGlyphCacheHashInsert(ExaGlyphCachePtr cache,
     
     while (TRUE) { /* hash table can never be full */
 	if (cache->hashEntries[slot] == -1) {
-	    DBG_GLYPH_CACHE((" inserting entry at %d\n", slot));
 	    cache->hashEntries[slot] = pos;
 	    return;
 	}
diff --git a/exa/exa_priv.h b/exa/exa_priv.h
index 8a17f65..f3b72ae 100644
--- a/exa/exa_priv.h
+++ b/exa/exa_priv.h
@@ -61,7 +61,7 @@
 #define DEBUG_MIGRATE		0
 #define DEBUG_PIXMAP		0
 #define DEBUG_OFFSCREEN		0
-#define DEBUG_GLYPH_CACHE	1
+#define DEBUG_GLYPH_CACHE	0
 
 #if DEBUG_TRACE_FALL
 #define EXA_FALLBACK(x)     					\
commit fcb5949928f1c27f67f40c094c3c673786574422
Author: Owen Taylor <otaylor at huygens.home.fishsoup.net>
Date:   Mon Apr 28 21:00:54 2008 +0200

    EXA: Fix overlapping glyphs in glyph cache
    
    Allocate each cache at a different vertical position in the
    per-format pixmap. Fix width/height confusion when choosing
    the cache for a glyph.

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index 55fdb01..851e439 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -173,12 +173,13 @@ exaRealizeGlyphCaches(ScreenPtr    pScreen,
     for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
 	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
 	int rows;
-	
+
 	if (cache->format != format)
 	    continue;
 
-	rows = (cache->size + cache->columns - 1) / cache->columns;
+	cache->yOffset = height;
 
+	rows = (cache->size + cache->columns - 1) / cache->columns;
 	height += rows * cache->glyphHeight;
     }
 
@@ -346,6 +347,9 @@ exaGlyphCacheHashRemove(ExaGlyphCachePtr cache,
     }
 }
 
+#define CACHE_X(pos) (((pos) % cache->columns) * cache->glyphWidth)
+#define CACHE_Y(pos) (cache->yOffset + ((pos) / cache->columns) * cache->glyphHeight)
+
 static ExaGlyphCacheResult
 exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 			 ExaGlyphCachePtr  cache,
@@ -393,8 +397,8 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 		int x, y;
 		int i;
 		
-		x = (pos % cache->columns) * cache->glyphWidth;
-		y = (pos / cache->columns) * cache->glyphHeight;
+		x = CACHE_X(pos);
+		y = CACHE_Y(pos);
 
 		for (i = 0; i < buffer->count; i++) {
 		    if (buffer->rects[i].xSrc == x && buffer->rects[i].ySrc == y) {
@@ -420,8 +424,8 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 			  cache->picture,
 			  0, 0,
 			  0, 0,
-			  (pos % cache->columns) * cache->glyphWidth,
-			  (pos / cache->columns) * cache->glyphHeight,
+			  CACHE_X(pos),
+			  CACHE_Y(pos),
 			  pGlyph->info.width,
 			  pGlyph->info.height);
     }
@@ -430,8 +434,8 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
     buffer->source = cache->picture;
 	    
     rect = &buffer->rects[buffer->count];
-    rect->xSrc = (pos % cache->columns) * cache->glyphWidth;
-    rect->ySrc = (pos / cache->columns) * cache->glyphHeight;
+    rect->xSrc = CACHE_X(pos);
+    rect->ySrc = CACHE_Y(pos);
     rect->xDst = xGlyph - pGlyph->info.x;
     rect->yDst = yGlyph - pGlyph->info.y;
     rect->width = pGlyph->info.width;
@@ -442,6 +446,9 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
     return ExaGlyphSuccess;
 }
 
+#undef CACHE_X
+#undef CACHE_Y
+
 static ExaGlyphCacheResult
 exaBufferGlyph(ScreenPtr         pScreen,
 	       ExaGlyphBufferPtr buffer,
@@ -452,7 +459,7 @@ exaBufferGlyph(ScreenPtr         pScreen,
     ExaScreenPriv(pScreen);
     unsigned int format = (GlyphPicture(pGlyph)[pScreen->myNum])->format;
     int width = pGlyph->info.width;
-    int height = pGlyph->info.width;
+    int height = pGlyph->info.height;
     ExaCompositeRectPtr rect;
     PicturePtr source;
     int i;
diff --git a/exa/exa_priv.h b/exa/exa_priv.h
index 0d5d0f5..8a17f65 100644
--- a/exa/exa_priv.h
+++ b/exa/exa_priv.h
@@ -61,7 +61,7 @@
 #define DEBUG_MIGRATE		0
 #define DEBUG_PIXMAP		0
 #define DEBUG_OFFSCREEN		0
-#define DEBUG_GLYPH_CACHE	0
+#define DEBUG_GLYPH_CACHE	1
 
 #if DEBUG_TRACE_FALL
 #define EXA_FALLBACK(x)     					\
@@ -121,6 +121,7 @@ typedef struct {
     int glyphCount; /* Current number of glyphs */
     
     PicturePtr picture;   /* Where the glyphs of the cache are stored */
+    int yOffset;          /* y location within the picture where the cache starts */
     int columns;          /* Number of columns the glyphs are layed out in */
     int evictionPosition; /* Next random position to evict a glyph */
 } ExaGlyphCacheRec, *ExaGlyphCachePtr;
commit 40eb14c9482457969e0bde97c49edad536285e02
Author: Owen Taylor <otaylor at huygens.home.fishsoup.net>
Date:   Mon Apr 28 21:00:54 2008 +0200

    EXA: Add exaCompositeRects()
    
    Add a function to composite multiple independent rectangles
    from the same source to the same destination in a single
    operation: this is useful for building a glyph mask.

diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
index 3fe433a..55fdb01 100644
--- a/exa/exa_glyphs.c
+++ b/exa/exa_glyphs.c
@@ -56,16 +56,6 @@
 #define DBG_GLYPH_CACHE(a)
 #endif
 
-/* Instructions for rendering a single glyph */
-typedef struct {
-    INT16 xSrc;
-    INT16 ySrc;
-    INT16 xDst;
-    INT16 yDst;
-    INT16 width;
-    INT16 height;
-} ExaGlyphRenderRec, *ExaGlyphRenderPtr;
-
 /* Width of the pixmaps we use for the caches; this should be less than
  * max texture size of the driver; this may need to actually come from
  * the driver.
@@ -79,7 +69,7 @@ typedef struct {
 
 typedef struct {
     PicturePtr source;
-    ExaGlyphRenderRec glyphs[GLYPH_BUFFER_SIZE];
+    ExaCompositeRectRec rects[GLYPH_BUFFER_SIZE];
     int count;
 } ExaGlyphBuffer, *ExaGlyphBufferPtr;
 
@@ -364,7 +354,7 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 			 int               xGlyph,
 			 int               yGlyph)
 {
-    ExaGlyphRenderPtr glyphRec;
+    ExaCompositeRectPtr rect;
     int pos;
     
     if (buffer->source && buffer->source != cache->picture)
@@ -407,7 +397,7 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 		y = (pos / cache->columns) * cache->glyphHeight;
 
 		for (i = 0; i < buffer->count; i++) {
-		    if (buffer->glyphs[i].xSrc == x && buffer->glyphs[i].ySrc == y) {
+		    if (buffer->rects[i].xSrc == x && buffer->rects[i].ySrc == y) {
 			DBG_GLYPH_CACHE(("  must flush buffer\n"));
 			return ExaGlyphNeedFlush;
 		    }
@@ -439,13 +429,13 @@ exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
 
     buffer->source = cache->picture;
 	    
-    glyphRec = &buffer->glyphs[buffer->count];
-    glyphRec->xSrc = (pos % cache->columns) * cache->glyphWidth;
-    glyphRec->ySrc = (pos / cache->columns) * cache->glyphHeight;
-    glyphRec->xDst = xGlyph - pGlyph->info.x;
-    glyphRec->yDst = yGlyph - pGlyph->info.y;
-    glyphRec->width = pGlyph->info.width;
-    glyphRec->height = pGlyph->info.height;
+    rect = &buffer->rects[buffer->count];
+    rect->xSrc = (pos % cache->columns) * cache->glyphWidth;
+    rect->ySrc = (pos / cache->columns) * cache->glyphHeight;
+    rect->xDst = xGlyph - pGlyph->info.x;
+    rect->yDst = yGlyph - pGlyph->info.y;
+    rect->width = pGlyph->info.width;
+    rect->height = pGlyph->info.height;
 	    
     buffer->count++;
 
@@ -463,7 +453,7 @@ exaBufferGlyph(ScreenPtr         pScreen,
     unsigned int format = (GlyphPicture(pGlyph)[pScreen->myNum])->format;
     int width = pGlyph->info.width;
     int height = pGlyph->info.width;
-    ExaGlyphRenderPtr glyphRec;
+    ExaCompositeRectPtr rect;
     PicturePtr source;
     int i;
 
@@ -497,13 +487,13 @@ exaBufferGlyph(ScreenPtr         pScreen,
 
     buffer->source = source;
     
-    glyphRec = &buffer->glyphs[buffer->count];
-    glyphRec->xSrc = 0;
-    glyphRec->ySrc = 0;
-    glyphRec->xDst = xGlyph - pGlyph->info.x;
-    glyphRec->yDst = yGlyph - pGlyph->info.y;
-    glyphRec->width = pGlyph->info.width;
-    glyphRec->height = pGlyph->info.height;
+    rect = &buffer->rects[buffer->count];
+    rect->xSrc = 0;
+    rect->ySrc = 0;
+    rect->xDst = xGlyph - pGlyph->info.x;
+    rect->yDst = yGlyph - pGlyph->info.y;
+    rect->width = pGlyph->info.width;
+    rect->height = pGlyph->info.height;
 
     buffer->count++;
 
@@ -514,23 +504,8 @@ static void
 exaGlyphsToMask(PicturePtr        pMask,
 		ExaGlyphBufferPtr buffer)
 {
-    int i;
-
-    for (i = 0; i < buffer->count; i++) {
-	ExaGlyphRenderPtr glyphRec = &buffer->glyphs[i];
-	
-	CompositePicture (PictOpAdd,
-			  buffer->source,
-			  None,
-			  pMask,
-			  glyphRec->xSrc,
-			  glyphRec->ySrc,
-			  0, 0,
-			  glyphRec->xDst,
-			  glyphRec->yDst,
-			  glyphRec->width,
-			  glyphRec->height);
-    }
+    exaCompositeRects(PictOpAdd, buffer->source, pMask,
+		      buffer->count, buffer->rects);
     
     buffer->count = 0;
     buffer->source = NULL;
@@ -549,20 +524,20 @@ exaGlyphsToDst(CARD8		 op,
     int i;
 
     for (i = 0; i < buffer->count; i++) {
-	ExaGlyphRenderPtr glyphRec = &buffer->glyphs[i];
+	ExaCompositeRectPtr rect = &buffer->rects[i];
 	
 	CompositePicture (op,
 			  pSrc,
 			  buffer->source,
 			  pDst,
-			  xSrc + glyphRec->xDst - xDst,
-			  ySrc + glyphRec->yDst - yDst,
-			  glyphRec->xSrc,
-			  glyphRec->ySrc,
-			  glyphRec->xDst,
-			  glyphRec->yDst,
-			  glyphRec->width,
-			  glyphRec->height);
+			  xSrc + rect->xDst - xDst,
+			  ySrc + rect->yDst - yDst,
+			  rect->xSrc,
+			  rect->ySrc,
+			  rect->xDst,
+			  rect->yDst,
+			  rect->width,
+			  rect->height);
     }
     
     buffer->count = 0;
diff --git a/exa/exa_priv.h b/exa/exa_priv.h
index aaceeb8..0d5d0f5 100644
--- a/exa/exa_priv.h
+++ b/exa/exa_priv.h
@@ -243,6 +243,15 @@ typedef struct _ExaMigrationRec {
     RegionPtr pReg;
 } ExaMigrationRec, *ExaMigrationPtr;
 
+typedef struct {
+    INT16 xSrc;
+    INT16 ySrc;
+    INT16 xDst;
+    INT16 yDst;
+    INT16 width;
+    INT16 height;
+} ExaCompositeRectRec, *ExaCompositeRectPtr;
+
 /**
  * exaDDXDriverInit must be implemented by the DDX using EXA, and is the place
  * to set EXA options or hook in screen functions to handle using EXA as the AA.
@@ -457,6 +466,13 @@ exaComposite(CARD8	op,
 	     CARD16	height);
 
 void
+exaCompositeRects(CARD8	              op,
+		  PicturePtr	      Src,
+		  PicturePtr	      pDst,
+		  int                 nrect,
+		  ExaCompositeRectPtr rects);
+
+void
 exaTrapezoids (CARD8 op, PicturePtr pSrc, PicturePtr pDst,
                PictFormatPtr maskFormat, INT16 xSrc, INT16 ySrc,
                int ntrap, xTrapezoid *traps);
diff --git a/exa/exa_render.c b/exa/exa_render.c
index 1d7b897..43b0029 100644
--- a/exa/exa_render.c
+++ b/exa/exa_render.c
@@ -332,6 +332,228 @@ exaTryDriverSolidFill(PicturePtr	pSrc,
 }
 
 static int
+exaTryDriverCompositeRects(CARD8	       op,
+			   PicturePtr	       pSrc,
+			   PicturePtr	       pDst,
+			   int                 nrect,
+			   ExaCompositeRectPtr rects)
+{
+    ExaScreenPriv (pDst->pDrawable->pScreen);
+    int src_off_x, src_off_y, dst_off_x, dst_off_y;
+    PixmapPtr pSrcPix, pDstPix;
+    ExaPixmapPrivPtr pSrcExaPix, pDstExaPix;
+    struct _Pixmap scratch;
+    ExaMigrationRec pixmaps[2];
+
+    pSrcPix = exaGetDrawablePixmap(pSrc->pDrawable);
+    pSrcExaPix = ExaGetPixmapPriv(pSrcPix);
+
+    pDstPix = exaGetDrawablePixmap(pDst->pDrawable);
+    pDstExaPix = ExaGetPixmapPriv(pDstPix);
+
+    /* Check whether the accelerator can use these pixmaps.
+     * FIXME: If it cannot, use temporary pixmaps so that the drawing
+     * happens within limits.
+     */
+    if (pSrcExaPix->accel_blocked ||
+	pDstExaPix->accel_blocked)
+    {
+	return -1;
+    }
+
+    if (pExaScr->info->CheckComposite &&
+	!(*pExaScr->info->CheckComposite) (op, pSrc, NULL, pDst))
+    {
+	return -1;
+    }
+    
+    exaGetDrawableDeltas (pDst->pDrawable, pDstPix, &dst_off_x, &dst_off_y);
+	
+    pixmaps[0].as_dst = TRUE;
+    pixmaps[0].as_src = exaOpReadsDestination(op);
+    pixmaps[0].pPix = pDstPix;
+    pixmaps[0].pReg = NULL;
+    pixmaps[1].as_dst = FALSE;
+    pixmaps[1].as_src = TRUE;
+    pixmaps[1].pPix = pSrcPix;
+    pixmaps[1].pReg = NULL;
+    exaDoMigration(pixmaps, 2, TRUE);
+
+    pSrcPix = exaGetOffscreenPixmap (pSrc->pDrawable, &src_off_x, &src_off_y);
+    if (!exaPixmapIsOffscreen(pDstPix))
+	return 0;
+    
+    if (!pSrcPix && pExaScr->info->UploadToScratch)
+    {
+	pSrcPix = exaGetDrawablePixmap (pSrc->pDrawable);
+	if ((*pExaScr->info->UploadToScratch) (pSrcPix, &scratch))
+	    pSrcPix = &scratch;
+    }
+
+    if (!pSrcPix)
+	return 0;
+
+    if (!(*pExaScr->info->PrepareComposite) (op, pSrc, NULL, pDst, pSrcPix,
+					     NULL, pDstPix))
+	return -1;
+
+    while (nrect--)
+    {
+	INT16 xDst = rects->xDst + pDst->pDrawable->x;
+	INT16 yDst = rects->yDst + pDst->pDrawable->y;
+	INT16 xSrc = rects->xSrc + pSrc->pDrawable->x;
+	INT16 ySrc = rects->ySrc + pSrc->pDrawable->y;
+	
+	RegionRec region;
+	BoxPtr pbox;
+	int nbox;
+	
+	if (!miComputeCompositeRegion (&region, pSrc, NULL, pDst,
+				       xSrc, ySrc, 0, 0, xDst, yDst,
+				       rects->width, rects->height))
+	    goto next_rect;
+	
+	REGION_TRANSLATE(pScreen, &region, dst_off_x, dst_off_y);
+	
+	nbox = REGION_NUM_RECTS(&region);
+	pbox = REGION_RECTS(&region);
+
+	xSrc = xSrc + src_off_x - xDst - dst_off_x;
+	ySrc = ySrc + src_off_y - yDst - dst_off_y;
+	
+	while (nbox--)
+	{
+	    (*pExaScr->info->Composite) (pDstPix,
+					 pbox->x1 + xSrc,
+					 pbox->y1 + ySrc,
+					 0, 0,
+					 pbox->x1,
+					 pbox->y1,
+					 pbox->x2 - pbox->x1,
+					 pbox->y2 - pbox->y1);
+	    pbox++;
+	}
+
+    next_rect:
+	REGION_UNINIT(pDst->pDrawable->pScreen, &region);
+
+	rects++;
+    }
+    
+    (*pExaScr->info->DoneComposite) (pDstPix);
+    exaMarkSync(pDst->pDrawable->pScreen);
+	
+    return 1;
+}
+
+/**
+ * Copy a number of rectangles from source to destination in a single
+ * operation. This is specialized for building a glyph mask: we don'y
+ * have a mask argument because we don't need it for that, and we
+ * don't have he special-case fallbacks found in exaComposite() - if the
+ * driver can support it, we use the driver functionality, otherwise we
+ * fallback straight to software.
+ */
+void
+exaCompositeRects(CARD8	              op,
+		  PicturePtr	      pSrc,
+		  PicturePtr	      pDst,
+		  int                 nrect,
+		  ExaCompositeRectPtr rects)
+{
+    PixmapPtr pPixmap = exaGetDrawablePixmap(pDst->pDrawable);
+    ExaPixmapPriv(pPixmap);
+    
+    int xoff, yoff;
+    int x1 = MAXSHORT;
+    int y1 = MAXSHORT;
+    int x2 = MINSHORT;
+    int y2 = MINSHORT;
+    RegionRec region;
+    RegionPtr pending_damage;
+    BoxRec box;
+    int n;
+    ExaCompositeRectPtr r;
+    
+    /* We have to manage the damage ourselves, since CompositeRects isn't
+     * something in the screen that can be managed by the damage extension,
+     * and EXA depends on damage to track what needs to be migrated between
+     * offscreen and onscreen.
+     */
+
+    /* Compute the overall extents of the composited region - we're making
+     * the assumption here that we are compositing a bunch of glyphs that
+     * cluster closely together and damaging each glyph individually would
+     * be a loss compared to damaging the bounding box.
+     */
+    n = nrect;
+    r = rects;
+    while (n--) {
+	int rect_x2 = r->xDst + r->width;
+	int rect_y2 = r->yDst + r->width;
+
+	if (r->xDst < x1) x1 = r->xDst;
+	if (r->xDst < y1) y1 = r->xDst;
+	if (rect_x2 > x2) x2 = rect_x2;
+	if (rect_y2 > y2) y2 = rect_y2;
+	
+	r++;
+    }
+
+    if (x2 <= x1 && y2 <= y1)
+	return;
+
+    box.x1 = x1;
+    box.x2 = x2 < MAXSHORT ? x2 : MAXSHORT;
+    box.y1 = y1;
+    box.y2 = y2 < MAXSHORT ? y2 : MAXSHORT;
+    
+    /* The pixmap migration code relies on pendingDamage indicating
+     * the bounds of the current rendering, so we need to force 
+     * the actual damage into that region before we do anything, and
+     * (see use of DamagePendingRegion in exaCopyDirty)
+     */
+    
+    REGION_INIT(pScreen, &region, &box, 1);
+    
+    exaGetDrawableDeltas(pDst->pDrawable, pPixmap, &xoff, &yoff);
+
+    REGION_TRANSLATE(pScreen, &region, xoff, yoff);
+    pending_damage = DamagePendingRegion(pExaPixmap->pDamage);
+    REGION_UNION(pScreen, pending_damage, pending_damage, &region);
+    REGION_TRANSLATE(pScreen, &region, -xoff, -yoff);
+    
+    /************************************************************/
+    
+    ValidatePicture (pSrc);
+    ValidatePicture (pDst);
+    
+    if (exaTryDriverCompositeRects(op, pSrc, pDst, nrect, rects) != 1) {
+	n = nrect;
+	r = rects;
+	while (n--) {
+	    ExaCheckComposite (op, pSrc, NULL, pDst,
+			       r->xSrc, r->ySrc,
+			       0, 0,
+			       r->xDst, r->yDst,
+			       r->width, r->height);
+	    r++;
+	}
+    }
+    
+    /************************************************************/
+
+    /* Now we have to flush the damage out from pendingDamage => damage 
+     * Calling DamageDamageRegion has that effect. (We could pass
+     * in an empty region here, but we pass in the same region we
+     * use above; the effect is the same.)
+     */
+
+    DamageDamageRegion(pDst->pDrawable, &region);
+    REGION_UNINIT(pScreen, &region);
+}
+
+static int
 exaTryDriverComposite(CARD8		op,
 		      PicturePtr	pSrc,
 		      PicturePtr	pMask,
commit 54184110f6f3e5d7276d5431e739a4fcf0c3523e
Author: Owen Taylor <otaylor at huygens.home.fishsoup.net>
Date:   Mon Apr 28 21:00:54 2008 +0200

    EXA: Use a single large glyph cache pixmap
    
    Add back exaGlyphs(); the new version copies the glyph images
    onto a single large glyph pixmap and draws from their to the
    destination surface. This reduces the management of small
    offscreen areas and will allow us to avoid texture unit setup
    between each glyph.

diff --git a/exa/Makefile.am b/exa/Makefile.am
index e2f7ed3..2b3f1e4 100644
--- a/exa/Makefile.am
+++ b/exa/Makefile.am
@@ -18,6 +18,7 @@ libexa_la_SOURCES = \
 	exa.c \
 	exa.h \
 	exa_accel.c \
+	exa_glyphs.c \
 	exa_migration.c \
 	exa_offscreen.c \
 	exa_render.c \
diff --git a/exa/exa.c b/exa/exa.c
index 3a6ad98..809fb4b 100644
--- a/exa/exa.c
+++ b/exa/exa.c
@@ -739,6 +739,8 @@ exaCloseScreen(int i, ScreenPtr pScreen)
     PictureScreenPtr	ps = GetPictureScreenIfSet(pScreen);
 #endif
 
+    exaGlyphsFini(pScreen);
+
     pScreen->CreateGC = pExaScr->SavedCreateGC;
     pScreen->CloseScreen = pExaScr->SavedCloseScreen;
     pScreen->GetImage = pExaScr->SavedGetImage;
@@ -752,7 +754,9 @@ exaCloseScreen(int i, ScreenPtr pScreen)
 #ifdef RENDER
     if (ps) {
 	ps->Composite = pExaScr->SavedComposite;
+	ps->Glyphs = pExaScr->SavedGlyphs;
 	ps->Trapezoids = pExaScr->SavedTrapezoids;
+	ps->Triangles = pExaScr->SavedTriangles;
     }
 #endif
 
@@ -914,6 +918,9 @@ exaDriverInit (ScreenPtr		pScreen,
         pExaScr->SavedComposite = ps->Composite;
 	ps->Composite = exaComposite;
 
+	pExaScr->SavedGlyphs = ps->Glyphs;
+	ps->Glyphs = exaGlyphs;
+	
 	pExaScr->SavedTriangles = ps->Triangles;
 	ps->Triangles = exaTriangles;
 
@@ -973,6 +980,8 @@ exaDriverInit (ScreenPtr		pScreen,
 	}
     }
 
+    exaGlyphsInit(pScreen);
+
     LogMessage(X_INFO, "EXA(%d): Driver registered support for the following"
 	       " operations:\n", pScreen->myNum);
     assert(pScreenInfo->PrepareSolid != NULL);
diff --git a/exa/exa_glyphs.c b/exa/exa_glyphs.c
new file mode 100644
index 0000000..3fe433a
--- /dev/null
+++ b/exa/exa_glyphs.c
@@ -0,0 +1,745 @@
+/*
+ * Copyright © 2008 Red Hat, Inc.
+ * Partly based on code Copyright © 2000 SuSE, Inc.
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and its
+ * documentation for any purpose is hereby granted without fee, provided that
+ * the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of Red Hat not be used in advertising or
+ * publicity pertaining to distribution of the software without specific,
+ * written prior permission.  Red Hat makes no representations about the
+ * suitability of this software for any purpose.  It is provided "as is"
+ * without express or implied warranty.
+ *
+ * Red Hat DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL Red Hat
+ * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
+ * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 
+ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and its
+ * documentation for any purpose is hereby granted without fee, provided that
+ * the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of SuSE not be used in advertising or
+ * publicity pertaining to distribution of the software without specific,
+ * written prior permission.  SuSE makes no representations about the
+ * suitability of this software for any purpose.  It is provided "as is"
+ * without express or implied warranty.
+ *
+ * SuSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL SuSE
+ * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
+ * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 
+ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Author: Owen Taylor <otaylor at fishsoup.net>
+ * Based on code by: Keith Packard
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <stdlib.h>
+
+#include "exa_priv.h"
+
+#include "mipict.h"
+
+#if DEBUG_GLYPH_CACHE
+#define DBG_GLYPH_CACHE(a) ErrorF a
+#else
+#define DBG_GLYPH_CACHE(a)
+#endif
+
+/* Instructions for rendering a single glyph */
+typedef struct {
+    INT16 xSrc;
+    INT16 ySrc;
+    INT16 xDst;
+    INT16 yDst;
+    INT16 width;
+    INT16 height;
+} ExaGlyphRenderRec, *ExaGlyphRenderPtr;
+
+/* Width of the pixmaps we use for the caches; this should be less than
+ * max texture size of the driver; this may need to actually come from
+ * the driver.
+ */
+#define CACHE_PICTURE_WIDTH 1024
+
+/* Maximum number of glyphs we buffer on the stack before flushing
+ * rendering to the mask or destination surface.
+ */
+#define GLYPH_BUFFER_SIZE 256
+
+typedef struct {
+    PicturePtr source;
+    ExaGlyphRenderRec glyphs[GLYPH_BUFFER_SIZE];
+    int count;
+} ExaGlyphBuffer, *ExaGlyphBufferPtr;
+
+typedef enum {
+    ExaGlyphSuccess,    /* Glyph added to render buffer */
+    ExaGlyphFail,       /* out of memory, etc */
+    ExaGlyphNeedFlush,  /* would evict a glyph already in the buffer */
+} ExaGlyphCacheResult;
+
+void
+exaGlyphsInit(ScreenPtr pScreen)
+{
+    ExaScreenPriv(pScreen);
+    int i = 0;
+
+    memset(pExaScr->glyphCaches, 0, sizeof(pExaScr->glyphCaches));
+
+    pExaScr->glyphCaches[i].format = PICT_a8;
+    pExaScr->glyphCaches[i].glyphWidth = pExaScr->glyphCaches[i].glyphHeight = 16;
+    i++;
+    pExaScr->glyphCaches[i].format = PICT_a8;
+    pExaScr->glyphCaches[i].glyphWidth = pExaScr->glyphCaches[i].glyphHeight = 32;
+    i++;
+    pExaScr->glyphCaches[i].format = PICT_a8r8g8b8;
+    pExaScr->glyphCaches[i].glyphWidth = pExaScr->glyphCaches[i].glyphHeight = 16;
+    i++;
+    pExaScr->glyphCaches[i].format = PICT_a8r8g8b8;
+    pExaScr->glyphCaches[i].glyphWidth = pExaScr->glyphCaches[i].glyphHeight = 32;
+    i++;
+
+    assert(i == EXA_NUM_GLYPH_CACHES);
+    
+    for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
+	pExaScr->glyphCaches[i].columns = CACHE_PICTURE_WIDTH / pExaScr->glyphCaches[i].glyphWidth;
+	pExaScr->glyphCaches[i].size = 256;
+	pExaScr->glyphCaches[i].hashSize = 557;
+    }
+}
+
+static void
+exaUnrealizeGlyphCaches(ScreenPtr    pScreen,
+			unsigned int format)
+{
+    ExaScreenPriv(pScreen);
+    int i;
+
+    for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
+	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
+	
+	if (cache->format != format)
+	    continue;
+
+	if (cache->picture) {
+	    FreePicture ((pointer) cache->picture, (XID) 0);
+	    cache->picture = NULL;
+	}
+
+	if (cache->hashEntries) {
+	    xfree(cache->hashEntries);
+	    cache->hashEntries = NULL;
+	}
+	
+	if (cache->glyphs) {
+	    xfree(cache->glyphs);
+	    cache->glyphs = NULL;
+	}
+	cache->glyphCount = 0;
+    }
+}
+
+/* All caches for a single format share a single pixmap for glyph storage,
+ * allowing mixing glyphs of different sizes without paying a penalty
+ * for switching between source pixmaps. (Note that for a size of font
+ * right at the border between two sizes, we might be switching for almost
+ * every glyph.)
+ *
+ * This function allocates the storage pixmap, and then fills in the
+ * rest of the allocated structures for all caches with the given format.
+ */
+static Bool
+exaRealizeGlyphCaches(ScreenPtr    pScreen,
+		      unsigned int format)
+{
+    ExaScreenPriv(pScreen);
+
+    int depth = PIXMAN_FORMAT_DEPTH(format);
+    PictFormatPtr pPictFormat;
+    PixmapPtr pPixmap;
+    PicturePtr pPicture;
+    int height;
+    int i;
+    int	error;
+
+    pPictFormat = PictureMatchFormat(pScreen, depth, format);
+    if (!pPictFormat)
+	return FALSE;
+    
+    /* Compute the total vertical size needed for the format */
+
+    height = 0;
+    for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
+	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
+	int rows;
+	
+	if (cache->format != format)
+	    continue;
+
+	rows = (cache->size + cache->columns - 1) / cache->columns;
+
+	height += rows * cache->glyphHeight;
+    }
+
+    /* Now allocate the pixmap and picture */
+       
+    pPixmap = (*pScreen->CreatePixmap) (pScreen,
+					CACHE_PICTURE_WIDTH,
+					height, depth, 0);
+    if (!pPixmap)
+	return FALSE;
+
+    pPicture = CreatePicture(0, &pPixmap->drawable, pPictFormat,
+			     0, 0, serverClient, &error);
+
+    (*pScreen->DestroyPixmap) (pPixmap); /* picture holds a refcount */
+
+    if (!pPicture)
+	return FALSE;
+
+    /* And store the picture in all the caches for the format */
+    
+    for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
+	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
+	int j;
+
+	if (cache->format != format)
+	    continue;
+
+	cache->picture = pPicture;
+	cache->picture->refcnt++;
+	cache->hashEntries = xalloc(sizeof(int) * cache->hashSize);
+	cache->glyphs = xalloc(sizeof(ExaCachedGlyphRec) * cache->size);
+	cache->glyphCount = 0;
+
+	if (!cache->hashEntries || !cache->glyphs)
+	    goto bail;
+
+	for (j = 0; j < cache->hashSize; j++)
+	    cache->hashEntries[j] = -1;
+	
+	cache->evictionPosition = rand() % cache->size;
+    }
+
+    /* Each cache references the picture individually */
+    FreePicture ((pointer) pPicture, (XID) 0);
+    return TRUE;
+
+bail:
+    exaUnrealizeGlyphCaches(pScreen, format);
+    return FALSE;
+}
+
+void
+exaGlyphsFini (ScreenPtr pScreen)
+{
+    ExaScreenPriv(pScreen);
+    int i;
+
+    for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
+	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
+
+	if (cache->picture)
+	    exaUnrealizeGlyphCaches(pScreen, cache->format);
+    }
+}
+
+static int
+exaGlyphCacheHashLookup(ExaGlyphCachePtr cache,
+			GlyphPtr         pGlyph)
+{
+    int slot;
+
+    slot = (*(CARD32 *) pGlyph->sha1) % cache->hashSize;
+    
+    while (TRUE) { /* hash table can never be full */
+	int entryPos = cache->hashEntries[slot];
+	if (entryPos == -1)
+	    return -1;
+
+	if (memcmp(pGlyph->sha1, cache->glyphs[entryPos].sha1, sizeof(pGlyph->sha1)) == 0){
+	    DBG_GLYPH_CACHE((" found entry at %d\n", slot));
+	    return entryPos;
+	}
+	    
+	DBG_GLYPH_CACHE((" lookup linear probe bumpalong\n"));
+	slot--;
+	if (slot < 0)
+	    slot = cache->hashSize - 1;
+    }
+}
+
+static void
+exaGlyphCacheHashInsert(ExaGlyphCachePtr cache,
+			GlyphPtr         pGlyph,
+			int              pos)
+{
+    int slot;
+
+    memcpy(cache->glyphs[pos].sha1, pGlyph->sha1, sizeof(pGlyph->sha1));
+    
+    slot = (*(CARD32 *) pGlyph->sha1) % cache->hashSize;
+    
+    while (TRUE) { /* hash table can never be full */
+	if (cache->hashEntries[slot] == -1) {
+	    DBG_GLYPH_CACHE((" inserting entry at %d\n", slot));
+	    cache->hashEntries[slot] = pos;
+	    return;
+	}
+	    
+	slot--;
+	if (slot < 0)
+	    slot = cache->hashSize - 1;
+    }
+}
+
+static void
+exaGlyphCacheHashRemove(ExaGlyphCachePtr cache,
+			int              pos)
+{
+    int slot;
+    int emptiedSlot = -1;
+
+    slot = (*(CARD32 *) cache->glyphs[pos].sha1) % cache->hashSize;
+
+    while (TRUE) { /* hash table can never be full */
+	int entryPos = cache->hashEntries[slot];
+	
+	if (entryPos == -1)
+	    return;
+
+	if (entryPos == pos) {
+	    cache->hashEntries[slot] = -1;
+	    emptiedSlot = slot;
+	} else if (emptiedSlot != -1) {
+	    /* See if we can move this entry into the emptied slot, we can't
+	     * do that if if entry would have hashed between the current position
+	     * and the emptied slot. (taking wrapping into account). Bad positions
+	     * are:
+	     *
+	     * |   XXXXXXXXXX             |
+	     *     i         j            
+	     *                            
+	     * |XXX                   XXXX|
+	     *     j                  i
+	     *
+	     * i - slot, j - emptiedSlot
+	     *
+	     * (Knuth 6.4R)
+	     */
+	    
+	    int entrySlot = (*(CARD32 *) cache->glyphs[entryPos].sha1) % cache->hashSize;
+
+	    if (!((entrySlot >= slot && entrySlot < emptiedSlot) ||
+		  (emptiedSlot < slot && (entrySlot < emptiedSlot || entrySlot >= slot)))) 
+	    {
+		cache->hashEntries[emptiedSlot] = entryPos;
+		cache->hashEntries[slot] = -1;
+		emptiedSlot = slot;
+	    }
+	}
+	
+	slot--;
+	if (slot < 0)
+	    slot = cache->hashSize - 1;
+    }
+}
+
+static ExaGlyphCacheResult
+exaGlyphCacheBufferGlyph(ScreenPtr         pScreen,
+			 ExaGlyphCachePtr  cache,
+			 ExaGlyphBufferPtr buffer,
+			 GlyphPtr          pGlyph,
+			 int               xGlyph,
+			 int               yGlyph)
+{
+    ExaGlyphRenderPtr glyphRec;
+    int pos;
+    
+    if (buffer->source && buffer->source != cache->picture)
+	return ExaGlyphNeedFlush;
+
+    if (!cache->picture) {
+	if (!exaRealizeGlyphCaches(pScreen, cache->format))
+	    return ExaGlyphFail;
+    }
+
+    DBG_GLYPH_CACHE(("(%d,%d,%s): buffering glyph %lx\n",
+		     cache->glyphWidth, cache->glyphHeight, cache->format == PICT_a8 ? "A" : "ARGB",
+		     (long)*(CARD32 *) pGlyph->sha1));
+   
+    pos = exaGlyphCacheHashLookup(cache, pGlyph);
+    if (pos != -1) {
+	DBG_GLYPH_CACHE(("  found existing glyph at %d\n", pos));
+    } else {
+	if (cache->glyphCount < cache->size) {
+	    /* Space remaining; we fill from the start */
+	    pos = cache->glyphCount;
+	    cache->glyphCount++;
+	    DBG_GLYPH_CACHE(("  storing glyph in free space at %d\n", pos));
+
+	    exaGlyphCacheHashInsert(cache, pGlyph, pos);
+
+	} else {
+	    /* Need to evict an entry. We have to see if any glyphs
+	     * already in the output buffer were at this position in
+	     * the cache
+	     */
+	    
+	    pos = cache->evictionPosition;
+	    DBG_GLYPH_CACHE(("  evicting glyph at %d\n", pos));
+	    if (buffer->count) {
+		int x, y;
+		int i;
+		
+		x = (pos % cache->columns) * cache->glyphWidth;
+		y = (pos / cache->columns) * cache->glyphHeight;
+
+		for (i = 0; i < buffer->count; i++) {
+		    if (buffer->glyphs[i].xSrc == x && buffer->glyphs[i].ySrc == y) {
+			DBG_GLYPH_CACHE(("  must flush buffer\n"));
+			return ExaGlyphNeedFlush;
+		    }
+		}
+	    }
+
+	    /* OK, we're all set, swap in the new glyph */
+	    exaGlyphCacheHashRemove(cache, pos);
+	    exaGlyphCacheHashInsert(cache, pGlyph, pos);
+
+	    /* And pick a new eviction position */
+	    cache->evictionPosition = rand() % cache->size;
+	}
+
+	/* Now actually upload the glyph into the cache picture */
+
+	CompositePicture (PictOpSrc,
+			  GlyphPicture(pGlyph)[pScreen->myNum],
+			  None,
+			  cache->picture,
+			  0, 0,
+			  0, 0,
+			  (pos % cache->columns) * cache->glyphWidth,
+			  (pos / cache->columns) * cache->glyphHeight,
+			  pGlyph->info.width,
+			  pGlyph->info.height);
+    }
+    
+
+    buffer->source = cache->picture;
+	    
+    glyphRec = &buffer->glyphs[buffer->count];
+    glyphRec->xSrc = (pos % cache->columns) * cache->glyphWidth;
+    glyphRec->ySrc = (pos / cache->columns) * cache->glyphHeight;
+    glyphRec->xDst = xGlyph - pGlyph->info.x;
+    glyphRec->yDst = yGlyph - pGlyph->info.y;
+    glyphRec->width = pGlyph->info.width;
+    glyphRec->height = pGlyph->info.height;
+	    
+    buffer->count++;
+
+    return ExaGlyphSuccess;
+}
+
+static ExaGlyphCacheResult
+exaBufferGlyph(ScreenPtr         pScreen,
+	       ExaGlyphBufferPtr buffer,
+	       GlyphPtr          pGlyph,
+	       int               xGlyph,
+	       int               yGlyph)
+{
+    ExaScreenPriv(pScreen);
+    unsigned int format = (GlyphPicture(pGlyph)[pScreen->myNum])->format;
+    int width = pGlyph->info.width;
+    int height = pGlyph->info.width;
+    ExaGlyphRenderPtr glyphRec;
+    PicturePtr source;
+    int i;
+
+    if (buffer->count == GLYPH_BUFFER_SIZE)
+	return ExaGlyphNeedFlush;
+    
+    for (i = 0; i < EXA_NUM_GLYPH_CACHES; i++) {
+	ExaGlyphCachePtr cache = &pExaScr->glyphCaches[i];
+
+	if (format == cache->format &&
+	    width <= cache->glyphWidth &&
+	    height <= cache->glyphHeight) {
+	    ExaGlyphCacheResult result = exaGlyphCacheBufferGlyph(pScreen, &pExaScr->glyphCaches[i],
+								  buffer,
+								  pGlyph, xGlyph, yGlyph);
+	    switch (result) {
+	    case ExaGlyphFail:
+		break;
+	    case ExaGlyphSuccess:
+	    case ExaGlyphNeedFlush:
+		return result;
+	    }
+	}
+    }
+
+    /* Couldn't find the glyph in the cache, use the glyph picture directly */
+
+    source = GlyphPicture(pGlyph)[pScreen->myNum];
+    if (buffer->source && buffer->source != source)
+	return ExaGlyphNeedFlush;
+
+    buffer->source = source;
+    
+    glyphRec = &buffer->glyphs[buffer->count];
+    glyphRec->xSrc = 0;
+    glyphRec->ySrc = 0;
+    glyphRec->xDst = xGlyph - pGlyph->info.x;
+    glyphRec->yDst = yGlyph - pGlyph->info.y;
+    glyphRec->width = pGlyph->info.width;
+    glyphRec->height = pGlyph->info.height;
+
+    buffer->count++;
+
+    return ExaGlyphSuccess;
+}
+
+static void
+exaGlyphsToMask(PicturePtr        pMask,
+		ExaGlyphBufferPtr buffer)
+{
+    int i;
+
+    for (i = 0; i < buffer->count; i++) {
+	ExaGlyphRenderPtr glyphRec = &buffer->glyphs[i];
+	
+	CompositePicture (PictOpAdd,
+			  buffer->source,
+			  None,
+			  pMask,
+			  glyphRec->xSrc,
+			  glyphRec->ySrc,
+			  0, 0,
+			  glyphRec->xDst,
+			  glyphRec->yDst,
+			  glyphRec->width,
+			  glyphRec->height);
+    }
+    
+    buffer->count = 0;
+    buffer->source = NULL;
+}
+
+static void
+exaGlyphsToDst(CARD8		 op,
+	       PicturePtr	 pSrc,
+	       PicturePtr	 pDst,
+	       ExaGlyphBufferPtr buffer,
+	       INT16		 xSrc,
+	       INT16		 ySrc,
+	       INT16		 xDst,
+	       INT16		 yDst)
+{
+    int i;
+
+    for (i = 0; i < buffer->count; i++) {
+	ExaGlyphRenderPtr glyphRec = &buffer->glyphs[i];
+	
+	CompositePicture (op,
+			  pSrc,
+			  buffer->source,
+			  pDst,
+			  xSrc + glyphRec->xDst - xDst,
+			  ySrc + glyphRec->yDst - yDst,
+			  glyphRec->xSrc,
+			  glyphRec->ySrc,
+			  glyphRec->xDst,
+			  glyphRec->yDst,
+			  glyphRec->width,
+			  glyphRec->height);
+    }
+    
+    buffer->count = 0;
+    buffer->source = NULL;
+}
+
+/* Cut and paste from render/glyph.c - probably should export it instead */
+static void
+GlyphExtents (int		nlist,
+	      GlyphListPtr	list,
+	      GlyphPtr	       *glyphs,
+	      BoxPtr		extents)
+{
+    int		x1, x2, y1, y2;
+    int		n;
+    GlyphPtr	glyph;
+    int		x, y;
+    
+    x = 0;
+    y = 0;
+    extents->x1 = MAXSHORT;
+    extents->x2 = MINSHORT;
+    extents->y1 = MAXSHORT;
+    extents->y2 = MINSHORT;
+    while (nlist--)
+    {
+	x += list->xOff;
+	y += list->yOff;
+	n = list->len;
+	list++;
+	while (n--)
+	{
+	    glyph = *glyphs++;
+	    x1 = x - glyph->info.x;
+	    if (x1 < MINSHORT)
+		x1 = MINSHORT;
+	    y1 = y - glyph->info.y;
+	    if (y1 < MINSHORT)
+		y1 = MINSHORT;
+	    x2 = x1 + glyph->info.width;
+	    if (x2 > MAXSHORT)
+		x2 = MAXSHORT;
+	    y2 = y1 + glyph->info.height;
+	    if (y2 > MAXSHORT)
+		y2 = MAXSHORT;
+	    if (x1 < extents->x1)
+		extents->x1 = x1;
+	    if (x2 > extents->x2)
+		extents->x2 = x2;
+	    if (y1 < extents->y1)
+		extents->y1 = y1;
+	    if (y2 > extents->y2)
+		extents->y2 = y2;
+	    x += glyph->info.xOff;
+	    y += glyph->info.yOff;
+	}
+    }
+}
+
+#define NeedsComponent(f) (PICT_FORMAT_A(f) != 0 && PICT_FORMAT_RGB(f) != 0)
+
+void
+exaGlyphs (CARD8 	 op,
+	   PicturePtr	 pSrc,
+	   PicturePtr	 pDst,
+	   PictFormatPtr maskFormat,
+	   INT16	 xSrc,
+	   INT16	 ySrc,
+	   int		 nlist,
+	   GlyphListPtr	 list,
+	   GlyphPtr	*glyphs)
+{
+    PicturePtr	pPicture;
+    PixmapPtr   pMaskPixmap = 0;
+    PicturePtr  pMask;
+    ScreenPtr   pScreen = pDst->pDrawable->pScreen;
+    int		width = 0, height = 0;
+    int		x, y;
+    int		xDst = list->xOff, yDst = list->yOff;
+    int		n;
+    GlyphPtr	glyph;
+    int		error;
+    BoxRec	extents = {0, 0, 0, 0};
+    CARD32	component_alpha;
+    ExaGlyphBuffer buffer;
+
+    if (maskFormat)
+    {
+	GCPtr	    pGC;
+	xRectangle  rect;
+
+	GlyphExtents (nlist, list, glyphs, &extents);
+
+	if (extents.x2 <= extents.x1 || extents.y2 <= extents.y1)
+	    return;
+	width = extents.x2 - extents.x1;
+	height = extents.y2 - extents.y1;
+	pMaskPixmap = (*pScreen->CreatePixmap) (pScreen, width, height,
+						maskFormat->depth,
+						CREATE_PIXMAP_USAGE_SCRATCH);
+	if (!pMaskPixmap)
+	    return;
+	component_alpha = NeedsComponent(maskFormat->format);
+	pMask = CreatePicture (0, &pMaskPixmap->drawable,
+			       maskFormat, CPComponentAlpha, &component_alpha,
+			       serverClient, &error);
+	if (!pMask)
+	{
+	    (*pScreen->DestroyPixmap) (pMaskPixmap);
+	    return;
+	}
+	pGC = GetScratchGC (pMaskPixmap->drawable.depth, pScreen);
+	ValidateGC (&pMaskPixmap->drawable, pGC);
+	rect.x = 0;
+	rect.y = 0;
+	rect.width = width;
+	rect.height = height;
+	(*pGC->ops->PolyFillRect) (&pMaskPixmap->drawable, pGC, 1, &rect);
+	FreeScratchGC (pGC);
+	x = -extents.x1;
+	y = -extents.y1;
+    }
+    else
+    {
+	pMask = pDst;
+	x = 0;
+	y = 0;
+    }
+    buffer.count = 0;
+    buffer.source = NULL;
+    while (nlist--)
+    {
+	x += list->xOff;
+	y += list->yOff;
+	n = list->len;
+	while (n--)
+	{
+	    glyph = *glyphs++;
+	    pPicture = GlyphPicture (glyph)[pScreen->myNum];
+
+	    if (exaBufferGlyph(pScreen, &buffer, glyph, x, y) == ExaGlyphNeedFlush)
+	    {
+		if (maskFormat)
+		    exaGlyphsToMask(pMask, &buffer);
+		else
+		    exaGlyphsToDst(op, pSrc, pDst, &buffer,
+				   xSrc, ySrc, xDst, yDst);
+
+		exaBufferGlyph(pScreen, &buffer, glyph, x, y);
+	    }
+
+	    x += glyph->info.xOff;
+	    y += glyph->info.yOff;
+	}
+	list++;
+    }
+    
+    if (maskFormat)
+	exaGlyphsToMask(pMask, &buffer);
+    else
+	exaGlyphsToDst(op, pSrc, pDst, &buffer,
+		       xSrc, ySrc, xDst, yDst);
+    
+    if (maskFormat)
+    {
+	x = extents.x1;
+	y = extents.y1;
+	CompositePicture (op,
+			  pSrc,
+			  pMask,
+			  pDst,
+			  xSrc + x - xDst,
+			  ySrc + y - yDst,
+			  0, 0,
+			  x, y,
+			  width, height);
+	FreePicture ((pointer) pMask, (XID) 0);
+	(*pScreen->DestroyPixmap) (pMaskPixmap);
+    }
+}
diff --git a/exa/exa_priv.h b/exa/exa_priv.h
index 0138e4a..aaceeb8 100644
--- a/exa/exa_priv.h
+++ b/exa/exa_priv.h
@@ -61,6 +61,7 @@
 #define DEBUG_MIGRATE		0
 #define DEBUG_PIXMAP		0
 #define DEBUG_OFFSCREEN		0
+#define DEBUG_GLYPH_CACHE	0
 
 #if DEBUG_TRACE_FALL
 #define EXA_FALLBACK(x)     					\
@@ -95,6 +96,37 @@ enum ExaMigrationHeuristic {
     ExaMigrationSmart
 };
 
+typedef struct {
+    unsigned char sha1[20];
+} ExaCachedGlyphRec, *ExaCachedGlyphPtr;
+
+typedef struct {
+    /* The identity of the cache, statically configured at initialization */
+    unsigned int format;
+    int glyphWidth;
+    int glyphHeight;
+
+    int size; /* Size of cache; eventually this should be dynamically determined */
+
+    /* Hash table mapping from glyph sha1 to position in the glyph; we use
+     * open addressing with a hash table size determined based on size and large
+     * enough so that we always have a good amount of free space, so we can
+     * use linear probing. (Linear probing is preferrable to double hashing
+     * here because it allows us to easily remove entries.)
+     */
+    int *hashEntries;
+    int hashSize;
+    
+    ExaCachedGlyphPtr glyphs;
+    int glyphCount; /* Current number of glyphs */
+    
+    PicturePtr picture;   /* Where the glyphs of the cache are stored */
+    int columns;          /* Number of columns the glyphs are layed out in */
+    int evictionPosition; /* Next random position to evict a glyph */
+} ExaGlyphCacheRec, *ExaGlyphCachePtr;
+
+#define EXA_NUM_GLYPH_CACHES 4
+
 typedef void (*EnableDisableFBAccessProcPtr)(int, Bool);
 typedef struct {
     ExaDriverPtr info;
@@ -122,6 +154,8 @@ typedef struct {
     unsigned			 disableFbCount;
     Bool			 optimize_migration;
     unsigned			 offScreenCounter;
+
+    ExaGlyphCacheRec             glyphCaches[EXA_NUM_GLYPH_CACHES];
 } ExaScreenPrivRec, *ExaScreenPrivPtr;
 
 /*
@@ -432,6 +466,13 @@ exaTriangles (CARD8 op, PicturePtr pSrc, PicturePtr pDst,
 	      PictFormatPtr maskFormat, INT16 xSrc, INT16 ySrc,
 	      int ntri, xTriangle *tris);
 
+/* exa_glyph.c */
+void
+exaGlyphsInit(ScreenPtr pScreen);
+
+void
+exaGlyphsFini (ScreenPtr pScreen);
+
 void
 exaGlyphs (CARD8	op,
 	  PicturePtr	pSrc,
commit e9734306088e12f2cd68bf347ecf8415be4f0268
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 28 11:47:49 2008 -0700

    XQuartz: More startup / threading house cleaning.
    (cherry picked from commit 72653c24c00dfba64ce35a3d400598bcd77defc1)

diff --git a/hw/xquartz/X11Application.h b/hw/xquartz/X11Application.h
index 3869df9..8e7fed2 100644
--- a/hw/xquartz/X11Application.h
+++ b/hw/xquartz/X11Application.h
@@ -71,7 +71,7 @@ void X11ApplicationSetCanQuit (int state);
 void X11ApplicationServerReady (void);
 void X11ApplicationShowHideMenubar (int state);
 
-void X11ApplicationMain(int argc, const char **argv);
+void X11ApplicationMain(int argc, char **argv, char **envp);
 
 extern int X11EnableKeyEquivalents;
 extern int quartzHasRoot, quartzEnableRootless;
diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 7680437..e10e71e 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -47,9 +47,6 @@
 #include <mach/mach.h>
 #include <unistd.h>
 
-#include <pthread.h>
-extern pthread_cond_t server_can_start_cond;
-
 #define DEFAULTS_FILE "/usr/X11/lib/X11/xserver/Xquartz.plist"
 
 int X11EnableKeyEquivalents = TRUE;
@@ -776,7 +773,7 @@ environment?", @"Startup xinitrc dialog");
     [X11App prefs_synchronize];
 }
 
-void X11ApplicationMain (int argc, const char **argv) {
+void X11ApplicationMain (int argc, char **argv, char **envp) {
     NSAutoreleasePool *pool;
 
 #ifdef DEBUG
@@ -804,7 +801,7 @@ void X11ApplicationMain (int argc, const char **argv) {
     NSMaxY([[NSScreen mainScreen] visibleFrame]);
 
     /* Tell the server thread that it can proceed */
-    pthread_cond_broadcast(&server_can_start_cond);
+    QuartzInitServer(argc, argv, envp);
 
     [NSApp run];
     /* not reached */
diff --git a/hw/xquartz/X11Controller.h b/hw/xquartz/X11Controller.h
index d33752e..7942bc4 100644
--- a/hw/xquartz/X11Controller.h
+++ b/hw/xquartz/X11Controller.h
@@ -100,6 +100,6 @@
 
 #endif /* __OBJC__ */
 
-void X11ControllerMain(int argc, const char **argv);
+void X11ControllerMain(int argc, char **argv, char **envp);
 
 #endif /* X11CONTROLLER_H */
diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index 01470e5..df328f3 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -756,6 +756,6 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 
 @end
 
-void X11ControllerMain(int argc, const char **argv) {
-    X11ApplicationMain (argc, argv);
+void X11ControllerMain(int argc, char **argv, char **envp) {
+    X11ApplicationMain (argc, argv, envp);
 }
diff --git a/hw/xquartz/quartz.h b/hw/xquartz/quartz.h
index e116023..1b6d71f 100644
--- a/hw/xquartz/quartz.h
+++ b/hw/xquartz/quartz.h
@@ -128,6 +128,7 @@ Bool QuartzAddScreen(int index, ScreenPtr pScreen);
 Bool QuartzSetupScreen(int index, ScreenPtr pScreen);
 void QuartzInitOutput(int argc,char **argv);
 void QuartzInitInput(int argc, char **argv);
+void QuartzInitServer(int argc, char **argv, char **envp);
 void QuartzGiveUp(void);
 void QuartzProcessEvent(xEvent *xe);
 void QuartzDisplayChangedHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents);
diff --git a/hw/xquartz/quartzStartup.c b/hw/xquartz/quartzStartup.c
index 34eaf8a..7b6a1a6 100644
--- a/hw/xquartz/quartzStartup.c
+++ b/hw/xquartz/quartzStartup.c
@@ -58,19 +58,10 @@ struct arg {
     char **envp;
 };
 
-pthread_cond_t server_can_start_cond = PTHREAD_COND_INITIALIZER;
-
 static void server_thread (void *arg) {
-    struct arg *args = (struct arg *)arg;
-
-    /* Wait to be told we can continue */
-    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
-    pthread_mutex_lock(&mutex);
-    pthread_cond_wait(&server_can_start_cond, &mutex);
-    pthread_mutex_unlock(&mutex);
-    pthread_mutex_destroy(&mutex);
-
-    exit (dix_main(args->argc, args->argv, args->envp));
+    struct arg args = *((struct arg *)arg);
+    free(arg);
+    exit (dix_main(args.argc, args.argv, args.envp));
 }
 
 static pthread_t create_thread (void *func, void *arg) {
@@ -86,16 +77,27 @@ static pthread_t create_thread (void *func, void *arg) {
     return tid;
 }
 
+void QuartzInitServer(int argc, char **argv, char **envp) {
+    struct arg *args = (struct arg*)malloc(sizeof(struct arg));
+    if(!args)
+        FatalError("Could not allocate memory.\n");
+    
+    args->argc = argc;
+    args->argv = argv;
+    args->envp = envp;
+    
+    APPKIT_THREAD_ID = pthread_self();
+    SERVER_THREAD_ID = create_thread(server_thread, args);
+
+    if (!SERVER_THREAD_ID) {
+        FatalError("can't create secondary thread\n");
+    }
+}
+
 int main(int argc, char **argv, char **envp) {
     int         i;
     int         fd[2];
 
-    /* Store the args to pass to dix_main() */
-    struct arg  args;
-    args.argc = argc;
-    args.argv = argv;
-    args.envp = envp;
-
     // Make a pipe to pass events
     assert( pipe(fd) == 0 );
     darwinEventReadFD = fd[0];
@@ -112,18 +114,8 @@ int main(int argc, char **argv, char **envp) {
 
     /* Create the audio mutex */
     QuartzAudioInit();
-    
-    pthread_cond_init(&server_can_start_cond, NULL); 
-    
-    APPKIT_THREAD_ID = pthread_self();
-    SERVER_THREAD_ID = create_thread(server_thread, &args);
-
-    if (!SERVER_THREAD_ID) {
-        ErrorF("can't create secondary thread\n");
-        exit (1);
-    }
 
     QuartzMoveToForeground();
-    X11ControllerMain(argc, (const char **)argv);
+    X11ControllerMain(argc, argv, envp);
     exit(0);
 }
commit 4b46fc931e61bec0abd6a86062e46dd7a408e745
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 28 10:50:51 2008 -0700

    XQuartz: Updated Localizable.strings
    (cherry picked from commit d8d9c866b90fb24c93bd6e25fa90f8f2bf58ad34)

diff --git a/hw/xquartz/bundle/English.lproj/Localizable.strings b/hw/xquartz/bundle/English.lproj/Localizable.strings
index c83b085..63a1352 100644
Binary files a/hw/xquartz/bundle/English.lproj/Localizable.strings and b/hw/xquartz/bundle/English.lproj/Localizable.strings differ
commit 4017ebe5bfa7a261cd1135801756c44e9fe93ca1
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sun Apr 27 00:01:14 2008 -0700

    XQuartz: Added missing Xquartz.man.pre to EXTRA_DIST
    (cherry picked from commit 03e707987f7f32e47dd0355c6d16bfb9169a379b)

diff --git a/hw/xquartz/xpr/Makefile.am b/hw/xquartz/xpr/Makefile.am
index 12009fb..41f2b86 100644
--- a/hw/xquartz/xpr/Makefile.am
+++ b/hw/xquartz/xpr/Makefile.am
@@ -47,6 +47,7 @@ include $(top_srcdir)/cpprules.in
 	cp $< $@
 
 EXTRA_DIST = \
+	Xquartz.man.pre \
 	dri.h \
 	dristruct.h \
 	appledri.h \
commit 0bd28315afc3b7223f8ff9f17597db09500a9388
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sat Apr 26 23:00:42 2008 -0700

    Xquartz: Added missing to EXTRA_DIST
    (cherry picked from commit f4b963256feb03e9e6b5521bdefeb390e9a49688)

diff --git a/hw/xquartz/Makefile.am b/hw/xquartz/Makefile.am
index ccef5f6..1465a52 100644
--- a/hw/xquartz/Makefile.am
+++ b/hw/xquartz/Makefile.am
@@ -52,4 +52,6 @@ EXTRA_DIST = \
 	quartzForeground.h \
 	quartzKeyboard.h \
 	quartzPasteboard.h \
+	sanitizedCarbon.h \
+	sanitizedCocoa.h \
 	threadSafety.h
commit ef1c52053755fa14b4ca98b22c506f73f5f4a4b7
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sat Apr 26 19:21:05 2008 -0700

    XQuartz: Cleaned up startup and thread creation a tad.
    (cherry picked from commit c861fe00e112b21ee0156d09a6cd5281642a1dcc)

diff --git a/dix/main.c b/dix/main.c
index 6d9dd33..fbd6413 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -237,12 +237,11 @@ static int indexForScanlinePad[ 65 ] = {
 #define MIN(a,b) (((a) < (b)) ? (a) : (b))
 #endif
 
-#ifdef __APPLE__
-void DarwinHandleGUI(int argc, char **argv, char **envp);
+#ifdef XQUARTZ
+int dix_main(int argc, char *argv[], char *envp[])
+#else
+int main(int argc, char *argv[], char *envp[])
 #endif
-
-int
-main(int argc, char *argv[], char *envp[])
 {
     int		i, j, k, error;
     char	*xauthfile;
@@ -256,13 +255,6 @@ main(int argc, char *argv[], char *envp[])
     PrinterInitGlobals();
 #endif
 
-#ifdef XQUARTZ
-    /* Quartz support on Mac OS X requires that the Cocoa event loop be in
-     * the main thread. This allows the X server main to be called again
-     * from another thread. */
-    DarwinHandleGUI(argc, argv, envp);
-#endif
-
     CheckUserParameters(argc, argv, envp);
 
     CheckUserAuthorization();
diff --git a/hw/xquartz/X11Application.h b/hw/xquartz/X11Application.h
index 47c605c..3869df9 100644
--- a/hw/xquartz/X11Application.h
+++ b/hw/xquartz/X11Application.h
@@ -71,7 +71,7 @@ void X11ApplicationSetCanQuit (int state);
 void X11ApplicationServerReady (void);
 void X11ApplicationShowHideMenubar (int state);
 
-void X11ApplicationMain(int argc, const char **argv, void (*server_thread) (void *), void *server_arg);
+void X11ApplicationMain(int argc, const char **argv);
 
 extern int X11EnableKeyEquivalents;
 extern int quartzHasRoot, quartzEnableRootless;
diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index eefa45f..7680437 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -35,6 +35,7 @@
 
 #include "quartzForeground.h"
 #include "quartzCommon.h"
+
 #import "X11Application.h"
 
 # include "darwin.h"
@@ -45,7 +46,9 @@
 # include "micmap.h"
 #include <mach/mach.h>
 #include <unistd.h>
+
 #include <pthread.h>
+extern pthread_cond_t server_can_start_cond;
 
 #define DEFAULTS_FILE "/usr/X11/lib/X11/xserver/Xquartz.plist"
 
@@ -732,19 +735,6 @@ void X11ApplicationShowHideMenubar (int state) {
     [n release];
 }
 
-static pthread_t create_thread (void *func, void *arg) {
-    pthread_attr_t attr;
-    pthread_t tid;
-	
-    pthread_attr_init (&attr);
-    pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
-    pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
-    pthread_create (&tid, &attr, func, arg);
-    pthread_attr_destroy (&attr);
-	
-    return tid;
-}
-
 static void check_xinitrc (void) {
     char *tem, buf[1024];
     NSString *msg;
@@ -786,7 +776,7 @@ environment?", @"Startup xinitrc dialog");
     [X11App prefs_synchronize];
 }
 
-void X11ApplicationMain (int argc, const char **argv, void (*server_thread) (void *), void *server_arg) {
+void X11ApplicationMain (int argc, const char **argv) {
     NSAutoreleasePool *pool;
 
 #ifdef DEBUG
@@ -812,16 +802,9 @@ void X11ApplicationMain (int argc, const char **argv, void (*server_thread) (voi
     /* Calculate the height of the menubar so we can avoid it. */
     aquaMenuBarHeight = NSHeight([[NSScreen mainScreen] frame]) -
     NSMaxY([[NSScreen mainScreen] visibleFrame]);
-  
-    APPKIT_THREAD = pthread_self();
-    SERVER_THREAD = create_thread (server_thread, server_arg);
-
-    if (!SERVER_THREAD) {
-        ErrorF("can't create secondary thread\n");
-        exit (1);
-    }
 
-    QuartzMoveToForeground();
+    /* Tell the server thread that it can proceed */
+    pthread_cond_broadcast(&server_can_start_cond);
 
     [NSApp run];
     /* not reached */
diff --git a/hw/xquartz/X11Controller.h b/hw/xquartz/X11Controller.h
index c5994bd..d33752e 100644
--- a/hw/xquartz/X11Controller.h
+++ b/hw/xquartz/X11Controller.h
@@ -100,6 +100,6 @@
 
 #endif /* __OBJC__ */
 
-void X11ControllerMain(int argc, const char **argv, void (*server_thread) (void *), void *server_arg);
+void X11ControllerMain(int argc, const char **argv);
 
 #endif /* X11CONTROLLER_H */
diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index 8dfe4b3..01470e5 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -756,6 +756,6 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 
 @end
 
-void X11ControllerMain(int argc, const char **argv, void (*server_thread) (void *), void *server_arg) {
-    X11ApplicationMain (argc, argv, server_thread, server_arg);
+void X11ControllerMain(int argc, const char **argv) {
+    X11ApplicationMain (argc, argv);
 }
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 0643e53..86e7704 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -78,7 +78,8 @@ static int old_flags = 0;  // last known modifier state
 
 xEvent *darwinEvents = NULL;
 
-pthread_mutex_t mieqEnqueue_mutex;
+pthread_mutex_t mieqEnqueue_mutex = PTHREAD_MUTEX_INITIALIZER;
+
 static inline void mieqEnqueue_lock(void) {
     int err;
     if((err = pthread_mutex_lock(&mieqEnqueue_mutex))) {
@@ -303,17 +304,11 @@ static void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, in
 }
 
 Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) { 
-    int err;
-
     if (!darwinEvents)
         darwinEvents = (xEvent *)xcalloc(sizeof(xEvent), GetMaximumEventsNum());
     if (!darwinEvents)
         FatalError("Couldn't allocate event buffer\n");
 
-    if((err = pthread_mutex_init(&mieqEnqueue_mutex, NULL))) {
-        FatalError("Couldn't allocate mieqEnqueue mutex: %d.\n", err);
-    }
-    
     mieqInit();
     mieqSetHandler(kXquartzReloadKeymap, DarwinKeyboardReloadHandler);
     mieqSetHandler(kXquartzActivate, DarwinEventHandler);
diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index 2cba5df..0635b48 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -39,7 +39,6 @@
 #include "quartz.h"
 #include "darwin.h"
 #include "darwinEvents.h"
-#include "quartzAudio.h"
 #include "pseudoramiX.h"
 #define _APPLEWM_SERVER_
 #include "applewmExt.h"
@@ -156,10 +155,6 @@ void QuartzInitOutput(
     int argc,
     char **argv )
 {
-    if (serverGeneration == 1) {
-        QuartzAudioInit();
-    }
-
     if (!RegisterBlockAndWakeupHandlers(QuartzBlockHandler,
                                         QuartzWakeupHandler,
                                         NULL))
diff --git a/hw/xquartz/quartzStartup.c b/hw/xquartz/quartzStartup.c
index 233e6e6..34eaf8a 100644
--- a/hw/xquartz/quartzStartup.c
+++ b/hw/xquartz/quartzStartup.c
@@ -37,54 +37,71 @@
 #include <unistd.h>
 #include <CoreFoundation/CoreFoundation.h>
 #include "quartzCommon.h"
+#include "quartzForeground.h"
 #include "X11Controller.h"
 #include "darwin.h"
+#include "darwinEvents.h"
+#include "quartzAudio.h"
 #include "quartz.h"
 #include "opaque.h"
 #include "micmap.h"
 
 #include <assert.h>
 
-char **envpGlobal;      // argcGlobal and argvGlobal
-                        // are from dix/globals.c
+#include <pthread.h>
 
-int main(int argc, char **argv, char **envp);
-void _InitHLTB(void);
-void DarwinHandleGUI(int argc, char **argv, char **envp);
+int dix_main(int argc, char **argv, char **envp);
+
+struct arg {
+    int argc;
+    char **argv;
+    char **envp;
+};
+
+pthread_cond_t server_can_start_cond = PTHREAD_COND_INITIALIZER;
 
 static void server_thread (void *arg) {
-  exit (main (argcGlobal, argvGlobal, envpGlobal));
+    struct arg *args = (struct arg *)arg;
+
+    /* Wait to be told we can continue */
+    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+    pthread_mutex_lock(&mutex);
+    pthread_cond_wait(&server_can_start_cond, &mutex);
+    pthread_mutex_unlock(&mutex);
+    pthread_mutex_destroy(&mutex);
+
+    exit (dix_main(args->argc, args->argv, args->envp));
 }
 
-/*
- * DarwinHandleGUI
- *  This function is called first from main(). The first time
- *  it is called we start the Mac OS X front end. The front end
- *  will call main() again from another thread to run the X
- *  server. On the second call this function loads the user
- *  preferences set by the Mac OS X front end.
- */
-void DarwinHandleGUI(int argc, char **argv, char **envp) {
-    static Bool been_here = FALSE;
+static pthread_t create_thread (void *func, void *arg) {
+    pthread_attr_t attr;
+    pthread_t tid;
+	
+    pthread_attr_init (&attr);
+    pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
+    pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
+    pthread_create (&tid, &attr, func, arg);
+    pthread_attr_destroy (&attr);
+	
+    return tid;
+}
+
+int main(int argc, char **argv, char **envp) {
     int         i;
     int         fd[2];
 
-    if (been_here) {
-        return;
-    }
-    been_here = TRUE;
-    
+    /* Store the args to pass to dix_main() */
+    struct arg  args;
+    args.argc = argc;
+    args.argv = argv;
+    args.envp = envp;
+
     // Make a pipe to pass events
     assert( pipe(fd) == 0 );
     darwinEventReadFD = fd[0];
     darwinEventWriteFD = fd[1];
     fcntl(darwinEventReadFD, F_SETFL, O_NONBLOCK);
 
-    // Store command line arguments to pass back to main()
-    argcGlobal = argc;
-    argvGlobal = argv;
-    envpGlobal = envp;
-
     for (i = 1; i < argc; i++) {
         // Display version info without starting Mac OS X UI if requested
         if (!strcmp( argv[i], "-showconfig" ) || !strcmp( argv[i], "-version" )) {
@@ -93,16 +110,20 @@ void DarwinHandleGUI(int argc, char **argv, char **envp) {
         }
     }
 
-    /* Initially I ran the X server on the main thread, and received
-       events on the second thread. But now we may be using Carbon,
-       that needs to run on the main thread. (Otherwise, when it's
-       prebound, it will initialize itself on the wrong thread)
-       
-       grr.. but doing that means that if the X thread gets scheduled
-       before the main thread when we're _not_ prebound, things fail,
-       so initialize by hand. */
-
-    _InitHLTB();    
-    X11ControllerMain(argc, (const char **)argv, server_thread, NULL);
+    /* Create the audio mutex */
+    QuartzAudioInit();
+    
+    pthread_cond_init(&server_can_start_cond, NULL); 
+    
+    APPKIT_THREAD_ID = pthread_self();
+    SERVER_THREAD_ID = create_thread(server_thread, &args);
+
+    if (!SERVER_THREAD_ID) {
+        ErrorF("can't create secondary thread\n");
+        exit (1);
+    }
+
+    QuartzMoveToForeground();
+    X11ControllerMain(argc, (const char **)argv);
     exit(0);
 }
diff --git a/hw/xquartz/threadSafety.c b/hw/xquartz/threadSafety.c
index 7835de6..b5a4ecf 100644
--- a/hw/xquartz/threadSafety.c
+++ b/hw/xquartz/threadSafety.c
@@ -33,8 +33,8 @@
 
 #include <execinfo.h>
 
-pthread_t SERVER_THREAD;
-pthread_t APPKIT_THREAD;
+pthread_t APPKIT_THREAD_ID;
+pthread_t SERVER_THREAD_ID;
 
 void spewCallStack(void) {
     void* callstack[128];
@@ -48,7 +48,7 @@ void spewCallStack(void) {
     free(strs);
 }
 
-void _threadAssert(pthread_t tid, const char *file, const char *fun, int line) {
+void _threadSafetyAssert(pthread_t tid, const char *file, const char *fun, int line) {
     if(pthread_equal(pthread_self(), tid))
         return;
     
@@ -58,3 +58,13 @@ void _threadAssert(pthread_t tid, const char *file, const char *fun, int line) {
            file, fun, line);
     spewCallStack();
 }
+
+const char *threadSafetyID(pthread_t tid) {
+    if(pthread_equal(tid, APPKIT_THREAD_ID)) {
+        return "Appkit Thread";
+    } else if(pthread_equal(tid, SERVER_THREAD_ID)) {
+        return "Xserver Thread";
+    } else {        
+        return "Unknown Thread";
+    }
+}
diff --git a/hw/xquartz/threadSafety.h b/hw/xquartz/threadSafety.h
index ed2ad9f..7b00910 100644
--- a/hw/xquartz/threadSafety.h
+++ b/hw/xquartz/threadSafety.h
@@ -31,22 +31,23 @@
 
 #include <pthread.h>
 
-extern pthread_t SERVER_THREAD;
-extern pthread_t APPKIT_THREAD;
-
-#define threadSafetyID(tid) (pthread_equal((tid), SERVER_THREAD) ? "X Server Thread" : "Appkit Thread")
+extern pthread_t APPKIT_THREAD_ID;
+extern pthread_t SERVER_THREAD_ID;
 
 /* Dump the call stack */
 void spewCallStack(void);
 
 /* Print message to ErrorF if we're in the wrong thread */
-void _threadAssert(pthread_t tid, const char *file, const char *fun, int line);
+void _threadSafetyAssert(pthread_t tid, const char *file, const char *fun, int line);
+
+/* Get a string that identifies our thread nicely */
+const char *threadSafetyID(pthread_t tid);
 
-#define threadAssert(tid) _threadAssert(tid, __FILE__, __FUNCTION__, __LINE__)
+#define threadSafetyAssert(tid) _threadSafetyAssert(tid, __FILE__, __FUNCTION__, __LINE__)
 
 #ifdef DEBUG_THREADS
-#define TA_SERVER() threadAssert(SERVER_THREAD)
-#define TA_APPKIT() threadAssert(APPKIT_THREAD)
+#define TA_APPKIT() threadSafetyAssert(APPKIT_THREAD_ID)
+#define TA_SERVER() threadSafetyAssert(SERVER_THREAD_ID)
 #else
 #define TA_SERVER() 
 #define TA_APPKIT() 
commit b114d4e861885cc5b49cd81b33ad825461811b3e
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sat Apr 26 17:04:49 2008 -0700

    XQuartz: Don't subtract the titlebar off of the pointer_y
    (cherry picked from commit 00a9567acce2b27a649cbebd4790e3043688a7d8)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 265819a..eefa45f 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -867,8 +867,6 @@ static void send_nsevent (NSEventType type, NSEvent *e) {
 		pointer_y = (screen.origin.y + screen.size.height) - location.y;
 	}
 
-	pointer_y -= aquaMenuBarHeight;
-
 	pressure = 0;  // for tablets
 	tilt_x = 0;
 	tilt_y = 0;
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index afa292f..0643e53 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -367,6 +367,8 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 	static int darwinFakeMouseButtonMask = 0;
 	int i, num_events;
 
+    //DEBUG_LOG("x=%d, y=%d, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
+    
 	if(!darwinEvents) {
 		ErrorF("DarwinSendPointerEvents called before darwinEvents was initialized\n");
 		return;
commit b9ca7896356f79ee27be5d5aa62052f6984282b0
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri Apr 25 17:54:36 2008 -0700

    XQuartz: Added some pseudoramiX debug traces
    (cherry picked from commit 5bee1585a399eab0a7b6fc80ad476d81b5d227d3)

diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index 3231077..6d2fbd0 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -130,4 +130,6 @@ extern FILE *debug_log_fp;
 #define DEBUG_LOG(msg, args...) 
 #endif
 
+#define TRACE() DEBUG_LOG("\n")
+
 #endif  /* _DARWIN_H */
diff --git a/hw/xquartz/pseudoramiX.c b/hw/xquartz/pseudoramiX.c
index 49d5eb6..aafaa26 100644
--- a/hw/xquartz/pseudoramiX.c
+++ b/hw/xquartz/pseudoramiX.c
@@ -37,6 +37,7 @@ Equipment Corporation.
 #include <dix-config.h>
 #endif
 
+#include "darwin.h"
 #include "pseudoramiX.h"
 #include "extnsionst.h"
 #include "dixstruct.h"
@@ -99,6 +100,8 @@ PseudoramiXAddScreen(int x, int y, int w, int h)
                                       sizeof(PseudoramiXScreenRec));
     }
 
+    DEBUG_LOG("x: %d, y: %d, w: %d, h: %d\n", x, y, w, h);
+
     s = &pseudoramiXScreens[pseudoramiXNumScreens++];
     s->x = x;
     s->y = y;
@@ -116,6 +119,8 @@ void PseudoramiXExtensionInit(int argc, char *argv[])
 
     if (noPseudoramiXExtension) return;
 
+    TRACE();
+
     /* Even with only one screen we need to enable PseudoramiX to allow
        dynamic screen configuration changes. */
 #if 0
@@ -153,12 +158,16 @@ void PseudoramiXExtensionInit(int argc, char *argv[])
 
 void PseudoramiXResetScreens(void)
 {
+    TRACE();
+
     pseudoramiXNumScreens = 0;
 }
 
 
 static void PseudoramiXResetProc(ExtensionEntry *extEntry)
 {
+    TRACE();
+
     PseudoramiXResetScreens();
 }
 
@@ -166,6 +175,8 @@ static void PseudoramiXResetProc(ExtensionEntry *extEntry)
 // was PanoramiX
 static int ProcPseudoramiXQueryVersion(ClientPtr client)
 {
+    TRACE();
+
     return ProcPanoramiXQueryVersion(client);
 }
 
@@ -178,6 +189,8 @@ static int ProcPseudoramiXGetState(ClientPtr client)
     xPanoramiXGetStateReply rep;
     register int n, rc;
 
+    TRACE();
+    
     REQUEST_SIZE_MATCH(xPanoramiXGetStateReq);
     rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
     if (rc != Success)
@@ -205,6 +218,8 @@ static int ProcPseudoramiXGetScreenCount(ClientPtr client)
     xPanoramiXGetScreenCountReply rep;
     register int n, rc;
 
+    TRACE();
+    
     REQUEST_SIZE_MATCH(xPanoramiXGetScreenCountReq);
     rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
     if (rc != Success)
@@ -232,6 +247,8 @@ static int ProcPseudoramiXGetScreenSize(ClientPtr client)
     xPanoramiXGetScreenSizeReply	rep;
     register int			n, rc;
 
+    TRACE();
+    
     REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
     rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
     if (rc != Success)
@@ -262,6 +279,8 @@ static int ProcPseudoramiXIsActive(ClientPtr client)
     /* REQUEST(xXineramaIsActiveReq); */
     xXineramaIsActiveReply	rep;
 
+    TRACE();
+    
     REQUEST_SIZE_MATCH(xXineramaIsActiveReq);
 
     rep.type = X_Reply;
@@ -285,6 +304,8 @@ static int ProcPseudoramiXQueryScreens(ClientPtr client)
     /* REQUEST(xXineramaQueryScreensReq); */
     xXineramaQueryScreensReply	rep;
 
+    DEBUG_LOG("noPseudoramiXExtension=%d, pseudoramiXNumScreens=%d\n", noPseudoramiXExtension, pseudoramiXNumScreens);
+    
     REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
 
     rep.type = X_Reply;
@@ -327,6 +348,7 @@ static int ProcPseudoramiXQueryScreens(ClientPtr client)
 // was PanoramiX
 static int ProcPseudoramiXDispatch (ClientPtr client)
 {   REQUEST(xReq);
+    TRACE();
     switch (stuff->data)
     {
 	case X_PanoramiXQueryVersion:
@@ -353,6 +375,8 @@ SProcPseudoramiXQueryVersion (ClientPtr client)
 	REQUEST(xPanoramiXQueryVersionReq);
 	register int n;
 
+    TRACE();
+
 	swaps(&stuff->length,n);
 	REQUEST_SIZE_MATCH (xPanoramiXQueryVersionReq);
 	return ProcPseudoramiXQueryVersion(client);
@@ -364,6 +388,8 @@ SProcPseudoramiXGetState(ClientPtr client)
 	REQUEST(xPanoramiXGetStateReq);
 	register int n;
 
+    TRACE();
+
  	swaps (&stuff->length, n);
 	REQUEST_SIZE_MATCH(xPanoramiXGetStateReq);
 	return ProcPseudoramiXGetState(client);
@@ -375,6 +401,8 @@ SProcPseudoramiXGetScreenCount(ClientPtr client)
 	REQUEST(xPanoramiXGetScreenCountReq);
 	register int n;
 
+    TRACE();
+
 	swaps (&stuff->length, n);
 	REQUEST_SIZE_MATCH(xPanoramiXGetScreenCountReq);
 	return ProcPseudoramiXGetScreenCount(client);
@@ -386,6 +414,8 @@ SProcPseudoramiXGetScreenSize(ClientPtr client)
 	REQUEST(xPanoramiXGetScreenSizeReq);
 	register int n;
 
+    TRACE();
+
 	swaps (&stuff->length, n);
 	REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
 	return ProcPseudoramiXGetScreenSize(client);
@@ -398,6 +428,8 @@ SProcPseudoramiXIsActive(ClientPtr client)
 	REQUEST(xXineramaIsActiveReq);
 	register int n;
 
+    TRACE();
+
 	swaps (&stuff->length, n);
 	REQUEST_SIZE_MATCH(xXineramaIsActiveReq);
 	return ProcPseudoramiXIsActive(client);
@@ -410,6 +442,8 @@ SProcPseudoramiXQueryScreens(ClientPtr client)
 	REQUEST(xXineramaQueryScreensReq);
 	register int n;
 
+    TRACE();
+
 	swaps (&stuff->length, n);
 	REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
 	return ProcPseudoramiXQueryScreens(client);
@@ -419,6 +453,9 @@ SProcPseudoramiXQueryScreens(ClientPtr client)
 static int
 SProcPseudoramiXDispatch (ClientPtr client)
 {   REQUEST(xReq);
+
+    TRACE();
+
     switch (stuff->data)
     {
 	case X_PanoramiXQueryVersion:
diff --git a/hw/xquartz/quartzCocoa.m b/hw/xquartz/quartzCocoa.m
index aa4b9fb..2890d34 100644
--- a/hw/xquartz/quartzCocoa.m
+++ b/hw/xquartz/quartzCocoa.m
@@ -44,8 +44,6 @@
 
 #include "darwin.h"
 
-#include "pseudoramiX.h"
-
 extern void FatalError(const char *, ...);
 extern char *display;
 extern int noPanoramiXExtension;
commit 0209e46249b61974a6e3ed54a51cc36dfaf0064f
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 24 23:48:11 2008 -0700

    XQuartz: More multi-monitor work... reverted Ben's workaround (worked for side-by-side only) and added more debugging.
    (cherry picked from commit 515b8b855ac5d2d5aef881053f73b2ad07a6dd2e)

diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index aad55fc..c18b575 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -535,8 +535,7 @@ DarwinAdjustScreenOrigins(ScreenInfo *pScreenInfo)
     /* Find leftmost screen. If there's a tie, take the topmost of the two. */
     for (i = 1; i < pScreenInfo->numScreens; i++) {
         if (dixScreenOrigins[i].x < left  ||
-            (dixScreenOrigins[i].x == left &&
-             dixScreenOrigins[i].y < top))
+            (dixScreenOrigins[i].x == left && dixScreenOrigins[i].y < top))
         {
             left = dixScreenOrigins[i].x;
             top = dixScreenOrigins[i].y;
@@ -545,17 +544,20 @@ DarwinAdjustScreenOrigins(ScreenInfo *pScreenInfo)
 
     darwinMainScreenX = left;
     darwinMainScreenY = top;
+    
+    DEBUG_LOG("top = %d, left=%d\n", top, left);
 
     /* Shift all screens so that there is a screen whose top left
-       is at X11 (0,0) and at global screen coordinate
-       (darwinMainScreenX, darwinMainScreenY). */
+     * is at X11 (0,0) and at global screen coordinate
+     * (darwinMainScreenX, darwinMainScreenY).
+     */
 
     if (darwinMainScreenX != 0 || darwinMainScreenY != 0) {
         for (i = 0; i < pScreenInfo->numScreens; i++) {
             dixScreenOrigins[i].x -= darwinMainScreenX;
             dixScreenOrigins[i].y -= darwinMainScreenY;
-    /*            ErrorF("Screen %d placed at X11 coordinate (%d,%d).\n",
-		  i, dixScreenOrigins[i].x, dixScreenOrigins[i].y); */
+            DEBUG_LOG("Screen %d placed at X11 coordinate (%d,%d).\n",
+                      i, dixScreenOrigins[i].x, dixScreenOrigins[i].y);
         }
     }
 }
diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index 583d7ef..7312226 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -153,7 +153,8 @@ displayScreenBounds(CGDirectDisplayID id, Bool remove_menubar)
               (int)frame.origin.x, (int)frame.origin.y);
     
     /* Remove menubar to help standard X11 window managers. */
-    if (remove_menubar && !quartzHasRoot && id == 0) {
+    if (remove_menubar && !quartzHasRoot && 
+        frame.origin.x == 0 && frame.origin.y == 0) {
         frame.origin.y += aquaMenuBarHeight;
         frame.size.height -= aquaMenuBarHeight;
     }
@@ -201,6 +202,9 @@ xprAddPseudoramiXScreens(int *x, int *y, int *width, int *height)
     *width = unionRect.size.width;
     *height = unionRect.size.height;
 
+    DEBUG_LOG("  screen union origin: (%d,%d) size: (%d,%d).\n",
+              *x, *y, *width, *height);
+
     /* Tell PseudoramiX about the real screens. */
     for (i = 0; i < displayCount; i++)
     {
@@ -229,7 +233,7 @@ xprDisplayInit(void)
 {
     CGDisplayCount displayCount;
 
-    //    ErrorF("Display mode: Rootless Quartz -- Xplugin implementation\n");
+    DEBUG_LOG("");
 
     CGGetActiveDisplayList(0, NULL, &displayCount);
 
@@ -265,6 +269,8 @@ xprAddScreen(int index, ScreenPtr pScreen)
 {
     DarwinFramebufferPtr dfb = SCREEN_PRIV(pScreen);
     int depth = darwinDesiredDepth;
+
+    DEBUG_LOG("index=%d depth=%d\n", index, depth);
     
     if(depth == -1) {
         depth = CGDisplaySamplesPerPixel(kCGDirectMainDisplay) * CGDisplayBitsPerSample(kCGDirectMainDisplay);
commit b65dbd350b8518bb90bed9cdc64dd900bc75d20c
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 24 21:14:04 2008 -0700

    XQuartz: Cleaned up multi-monitor support.
    (cherry picked from commit c05abf0a19b0ef0fc4ace9400a095ce2521456bc)
    (cherry picked from commit 9112f290434c246d3e797551aaaf3a89d2006b23)

diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index 6f7598f..583d7ef 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -142,20 +142,26 @@ displayAtIndex(int index)
  *  Return the bounds of a particular display.
  */
 static CGRect
-displayScreenBounds(CGDirectDisplayID id)
+displayScreenBounds(CGDirectDisplayID id, Bool remove_menubar)
 {
     CGRect frame;
 
     frame = CGDisplayBounds(id);
 
+    DEBUG_LOG("    %dx%d @ (%d,%d).\n",
+              (int)frame.size.width, (int)frame.size.height,
+              (int)frame.origin.x, (int)frame.origin.y);
+    
     /* Remove menubar to help standard X11 window managers. */
-
-    if (frame.origin.y == 0)
-    {
+    if (remove_menubar && !quartzHasRoot && id == 0) {
         frame.origin.y += aquaMenuBarHeight;
         frame.size.height -= aquaMenuBarHeight;
     }
 
+    DEBUG_LOG("    %dx%d @ (%d,%d).\n",
+              (int)frame.size.width, (int)frame.size.height,
+              (int)frame.origin.x, (int)frame.origin.y);
+
     return frame;
 }
 
@@ -179,8 +185,13 @@ xprAddPseudoramiXScreens(int *x, int *y, int *width, int *height)
     /* Get the union of all screens */
     for (i = 0; i < displayCount; i++)
     {
+
+        /* we can't remove the menubar from the screen - doing so
+         * would constrain the pointer to the screen, not allowing it
+         * to reach the menubar..
+         */
         CGDirectDisplayID dpy = displayList[i];
-        frame = displayScreenBounds(dpy);
+        frame = displayScreenBounds(dpy, FALSE);
         unionRect = CGRectUnion(unionRect, frame);
     }
 
@@ -195,17 +206,12 @@ xprAddPseudoramiXScreens(int *x, int *y, int *width, int *height)
     {
         CGDirectDisplayID dpy = displayList[i];
 
-        frame = displayScreenBounds(dpy);
-
-	/*        ErrorF("PseudoramiX screen %d added: %dx%d @ (%d,%d).\n", i,
-               (int)frame.size.width, (int)frame.size.height,
-               (int)frame.origin.x, (int)frame.origin.y); */
-
+        frame = displayScreenBounds(dpy, TRUE);
         frame.origin.x -= unionRect.origin.x;
         frame.origin.y -= unionRect.origin.y;
 
-	/*        ErrorF("PseudoramiX screen %d placed at X11 coordinate (%d,%d).\n",
-		  i, (int)frame.origin.x, (int)frame.origin.y); */
+        DEBUG_LOG("    placed at X11 coordinate (%d,%d).\n",
+                  (int)frame.origin.x, (int)frame.origin.y);
 
         PseudoramiXAddScreen(frame.origin.x, frame.origin.y,
                              frame.size.width, frame.size.height);
@@ -315,12 +321,14 @@ xprAddScreen(int index, ScreenPtr pScreen)
 
     if (noPseudoramiXExtension)
     {
+        ErrorF("Warning: noPseudoramiXExtension!\n");
+        
         CGDirectDisplayID dpy;
         CGRect frame;
 
         dpy = displayAtIndex(index);
 
-        frame = displayScreenBounds(dpy);
+        frame = displayScreenBounds(dpy, TRUE);
 
         dfb->x = frame.origin.x;
         dfb->y = frame.origin.y;
commit 5869e3f5551e7e2d18e06a2f220b77d8c4161db1
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 24 19:39:27 2008 -0700

    darwin gots /dev/urandom, too yo!
    (cherry picked from commit bf0144f38034bc59f108bb2c5270ff37fbe70e10)

diff --git a/configure.ac b/configure.ac
index b42b120..67606c7 100644
--- a/configure.ac
+++ b/configure.ac
@@ -177,7 +177,7 @@ AC_CHECK_FUNC([dlopen], [],
 	AC_CHECK_LIB([dl], [dlopen], DLOPEN_LIBS="-ldl"))
 
 case $host_os in
-    linux*)
+    linux*|darwin*)
 	AC_DEFINE(HAVE_URANDOM, 1, [Has /dev/urandom]) ;;
     solaris*)
 	# Solaris 8 with patches, or Solaris 9 or later have /dev/urandom
commit b1ae7c79db78cc3b789701f81328669f9f8ed80f
Author: Alan Coopersmith <alan.coopersmith at sun.com>
Date:   Thu Apr 24 19:02:43 2008 -0700

    Bug 14247: If pkg-config can't find openssl.pc, just link with -lcrypto
    
    X.Org bugzilla #14247 <http://bugs.freedesktop.org/show_bug.cgi?id=14247>

diff --git a/configure.ac b/configure.ac
index b2a07a6..b42b120 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1118,7 +1118,9 @@ PKG_CHECK_MODULES([XSERVERLIBS], [$REQUIRED_LIBS])
 
 # OpenSSL used for SHA1 hashing in render/glyph.c, but we don't need all of
 # the OpenSSL libraries, just libcrypto
-PKG_CHECK_MODULES([OPENSSL], [openssl], [OPENSSL_LIB_FLAGS=`$PKG_CONFIG --libs-only-L --libs-only-other openssl`])
+PKG_CHECK_EXISTS([openssl],
+ [PKG_CHECK_MODULES([OPENSSL], [openssl],
+   [OPENSSL_LIB_FLAGS=`$PKG_CONFIG --libs-only-L --libs-only-other openssl`])])
 LIBCRYPTO="$OPENSSL_LIB_FLAGS -lcrypto"
 
 # Autotools has some unfortunate issues with library handling.  In order to
commit 1daae4574c19a122baf73b6f9457b0d383b1bc66
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 24 18:22:05 2008 -0700

    Added missing HAVE_LAUNCHD to dix-config.h.in
    (cherry picked from commit 1b4b73cefbc2f3e3f6d0cb84ea202f84fb60abb5)

diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index 135d3d8..fc1caa3 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -148,6 +148,9 @@
 /* Define to 1 if you have version 2.2 (or newer) of the drm library */
 #undef HAVE_LIBDRM_2_2
 
+/* Define to 1 if launchd is available. */
+#undef HAVE_LAUNCHD
+
 /* Have Quartz */
 #undef XQUARTZ
 
commit 63853e4ad211945ed25541223207a78f83766ced
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 24 18:21:42 2008 -0700

    XQuartz: Compile in missing glx source that we still need
    (cherry picked from commit c611335dee267e41dcd1733a6bb5206b102f804e)

diff --git a/GL/glx/Makefile.am b/GL/glx/Makefile.am
index 1d4719c..9bf296c 100644
--- a/GL/glx/Makefile.am
+++ b/GL/glx/Makefile.am
@@ -47,7 +47,12 @@ libglxdri_la_SOURCES = \
         extension_string.c \
         extension_string.h
 
+#if XQUARTZ
+XQUARTZ_libglx_la_SOURCES = glcontextmodes.c
+#endif
+
 libglx_la_SOURCES = \
+	$(XQUARTZ_libglx_la_SOURCES) \
         g_disptab.h \
         glxbyteorder.h \
         glxcmds.c \
commit ae982a27e4059fecd4048d245e6aa02f8dcc97d0
Author: Dave Airlie <airlied at redhat.com>
Date:   Thu Apr 24 16:37:29 2008 +1000

    glx: test for valid read and draw privates before using them
    
    this should fix a bug where f-spot exiting blows up the X server

diff --git a/GL/glx/glxutil.c b/GL/glx/glxutil.c
index 11e9f89..aa23a95 100644
--- a/GL/glx/glxutil.c
+++ b/GL/glx/glxutil.c
@@ -81,38 +81,40 @@ __glXDeassociateContext(__GLXcontext *glxc)
     __GLXcontext *curr, *prev;
 
     prev = NULL;
-    for ( curr = glxc->drawPriv->drawGlxc
-	  ; curr != NULL
-	  ; prev = curr, curr = curr->nextDrawPriv ) {
-	if (curr == glxc) {
-	    /* found context.  Deassociate. */
-	    if (prev == NULL) {
-		glxc->drawPriv->drawGlxc = curr->nextDrawPriv;
-	    } else {
-		prev->nextDrawPriv = curr->nextDrawPriv;
+    if (glxc->drawPriv) {
+        for ( curr = glxc->drawPriv->drawGlxc; curr != NULL
+	      ; prev = curr, curr = curr->nextDrawPriv ) {
+	    if (curr == glxc) {
+	        /* found context.  Deassociate. */
+	        if (prev == NULL) {
+		    glxc->drawPriv->drawGlxc = curr->nextDrawPriv;
+	        } else {
+		    prev->nextDrawPriv = curr->nextDrawPriv;
+	        }
+	        curr->nextDrawPriv = NULL;
+	        __glXUnrefDrawable(glxc->drawPriv);
+	        break;
 	    }
-	    curr->nextDrawPriv = NULL;
-	    __glXUnrefDrawable(glxc->drawPriv);
-	    break;
-	}
+        }
     }
 
-
     prev = NULL;
-    for ( curr = glxc->readPriv->readGlxc
-	  ; curr != NULL 
-	  ; prev = curr, curr = curr->nextReadPriv ) {
-	if (curr == glxc) {
-	    /* found context.  Deassociate. */
-	    if (prev == NULL) {
-		glxc->readPriv->readGlxc = curr->nextReadPriv;
-	    } else {
-		prev->nextReadPriv = curr->nextReadPriv;
-	    }
-	    curr->nextReadPriv = NULL;
-	    __glXUnrefDrawable(glxc->readPriv);
-	    break;
-	}
+    if (glxc->readPriv) {
+        for ( curr = glxc->readPriv->readGlxc
+	      ; curr != NULL 
+	      ; prev = curr, curr = curr->nextReadPriv ) {
+	    if (curr == glxc) {
+	        /* found context.  Deassociate. */
+	        if (prev == NULL) {
+		    glxc->readPriv->readGlxc = curr->nextReadPriv;
+	        } else {
+		    prev->nextReadPriv = curr->nextReadPriv;
+	        }
+	        curr->nextReadPriv = NULL;
+	        __glXUnrefDrawable(glxc->readPriv);
+	       break;
+	   }
+       }
     }
 }
 
commit f377141912594f87144d6d7f7fdd279a101d8e6c
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Thu Apr 24 13:30:28 2008 +0930

    Xi: don't attempt to send to a NULL window.
    
    Only applicable when the server comes down/restarts. In this case,
    WindowTable[i] may be NULL. Let's not try to send an event then.

diff --git a/Xi/exevents.c b/Xi/exevents.c
index fb84bef..641bead 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1279,6 +1279,8 @@ SendEventToAllWindows(DeviceIntPtr dev, Mask mask, xEvent * ev, int count)
 
     for (i = 0; i < screenInfo.numScreens; i++) {
         pWin = WindowTable[i];
+        if (!pWin)
+            continue;
         (void)DeliverEventsToWindow(pWin, ev, count, mask, NullGrab, dev->id);
         p1 = pWin->firstChild;
         FindInterestedChildren(dev, p1, mask, ev, count);
commit aec485f2dcc87b340759d67b60e7dee7931aaec5
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Thu Apr 24 13:29:46 2008 +0930

    dix: NULL out WindowTable after freeing all the windows.
    
    CloseDownDevices() tries to send PresenceNotify events. If the windows are
    already freed, then we are accessing dangling pointers.

diff --git a/dix/main.c b/dix/main.c
index db43473..6d9dd33 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -458,7 +458,10 @@ main(int argc, char *argv[], char *envp[])
 #endif
 
         config_fini();
+
+        memset(WindowTable, 0, MAXSCREENS * sizeof(WindowPtr));
 	CloseDownDevices();
+
 	for (i = screenInfo.numScreens - 1; i >= 0; i--)
 	{
 	    FreeScratchPixmapsForScreen(i);
commit 9ab4e2fd8eaa87dbd16835affb1aa54dcb1a619e
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Wed Apr 23 11:38:08 2008 +0930

    xfree86: don't free the config-file related information in DIDR. #15645
    
    In DeleteInputDeviceRequest, leave the conf_idev (which is shared with
    xf86ConfigLayout.input) alone for devices that were specified in the
    ServerLayout section of the config file. This way, in the next server
    generation we are left with what was the original config and can thus re-init
    the devices.
    
    This is an addon to 6d22a9615a0e6ab3d00b0bcb22ff001b6ece02ae, an attempt to
    fix Bug 14418.
    
    X.Org Bug 15645 <https://bugs.freedesktop.org/show_bug.cgi?id=15645>
    X.Org Bug 14418 <https://bugs.freedesktop.org/show_bug.cgi?id=15645>

diff --git a/hw/xfree86/common/xf86Init.c b/hw/xfree86/common/xf86Init.c
index 6d5eaad..68dc387 100644
--- a/hw/xfree86/common/xf86Init.c
+++ b/hw/xfree86/common/xf86Init.c
@@ -1123,37 +1123,35 @@ InitInput(argc, argv)
     xf86Info.vtRequestsPending = FALSE;
     xf86Info.inputPending = FALSE;
 
-    if (serverGeneration == 1) {
-	/* Call the PreInit function for each input device instance. */
-	for (pDev = xf86ConfigLayout.inputs; pDev && *pDev; pDev++) {
-	    /* Replace obsolete keyboard driver with kbd */
-	    if (!xf86NameCmp((*pDev)->driver, "keyboard")) {
-		strcpy((*pDev)->driver, "kbd");
-            }
-
-	    if ((pDrv = xf86LookupInputDriver((*pDev)->driver)) == NULL) {
-		xf86Msg(X_ERROR, "No Input driver matching `%s'\n", (*pDev)->driver);
-		/* XXX For now, just continue. */
-		continue;
-	    }
-	    if (!pDrv->PreInit) {
-		xf86MsgVerb(X_WARNING, 0,
-		    "Input driver `%s' has no PreInit function (ignoring)\n",
-		    pDrv->driverName);
-		continue;
-	    }
-	    pInfo = pDrv->PreInit(pDrv, *pDev, 0);
-	    if (!pInfo) {
-		xf86Msg(X_ERROR, "PreInit returned NULL for \"%s\"\n",
-			(*pDev)->identifier);
-		continue;
-	    } else if (!(pInfo->flags & XI86_CONFIGURED)) {
-		xf86Msg(X_ERROR, "PreInit failed for input device \"%s\"\n",
-			(*pDev)->identifier);
-		xf86DeleteInput(pInfo, 0);
-		continue;
-	    }
-	}
+    /* Call the PreInit function for each input device instance. */
+    for (pDev = xf86ConfigLayout.inputs; pDev && *pDev; pDev++) {
+        /* Replace obsolete keyboard driver with kbd */
+        if (!xf86NameCmp((*pDev)->driver, "keyboard")) {
+            strcpy((*pDev)->driver, "kbd");
+        }
+
+        if ((pDrv = xf86LookupInputDriver((*pDev)->driver)) == NULL) {
+            xf86Msg(X_ERROR, "No Input driver matching `%s'\n", (*pDev)->driver);
+            /* XXX For now, just continue. */
+            continue;
+        }
+        if (!pDrv->PreInit) {
+            xf86MsgVerb(X_WARNING, 0,
+                    "Input driver `%s' has no PreInit function (ignoring)\n",
+                    pDrv->driverName);
+            continue;
+        }
+        pInfo = pDrv->PreInit(pDrv, *pDev, 0);
+        if (!pInfo) {
+            xf86Msg(X_ERROR, "PreInit returned NULL for \"%s\"\n",
+                    (*pDev)->identifier);
+            continue;
+        } else if (!(pInfo->flags & XI86_CONFIGURED)) {
+            xf86Msg(X_ERROR, "PreInit failed for input device \"%s\"\n",
+                    (*pDev)->identifier);
+            xf86DeleteInput(pInfo, 0);
+            continue;
+        }
     }
 
     /* Initialise all input devices. */
diff --git a/hw/xfree86/common/xf86Xinput.c b/hw/xfree86/common/xf86Xinput.c
index d34238e..710e787 100644
--- a/hw/xfree86/common/xf86Xinput.c
+++ b/hw/xfree86/common/xf86Xinput.c
@@ -448,6 +448,8 @@ DeleteInputDeviceRequest(DeviceIntPtr pDev)
     LocalDevicePtr pInfo = (LocalDevicePtr) pDev->public.devicePrivate;
     InputDriverPtr drv;
     IDevRec *idev;
+    BOOL found;
+    IDevPtr *it;
 
     if (pInfo) /* need to get these before RemoveDevice */
     {
@@ -464,10 +466,18 @@ DeleteInputDeviceRequest(DeviceIntPtr pDev)
     else
         xf86DeleteInput(pInfo, 0);
 
-    xfree(idev->driver);
-    xfree(idev->identifier);
-    xf86optionListFree(idev->commonOptions);
-    xfree(idev);
+    /* devices added through HAL aren't in the config layout */
+    it = xf86ConfigLayout.inputs;
+    while(*it && *it != idev)
+        it++;
+
+    if (!(*it)) /* end of list, not in the layout */
+    {
+        xfree(idev->driver);
+        xfree(idev->identifier);
+        xf86optionListFree(idev->commonOptions);
+        xfree(idev);
+    }
 }
 
 /* 
commit d09c520b322ba5c5f4d6b630a7c0c62e56732f82
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 23 10:22:34 2008 -0700

    Moved Apple GL bits into our DDX subtree
    (cherry picked from commit c9356f32892978faecb30f7b7af7488820ce37ff)

diff --git a/GL/Makefile.am b/GL/Makefile.am
index 44fca18..c3ac155 100644
--- a/GL/Makefile.am
+++ b/GL/Makefile.am
@@ -1,9 +1,4 @@
-if XQUARTZ
-XQUARTZ_SUBDIRS = apple
-endif
-
-SUBDIRS = glx $(XQUARTZ_SUBDIRS)
-DIST_SUBDIRS = glx apple
+SUBDIRS = glx
 
 WINDOWS_EXTRAS = \
 	windows/ChangeLog \
diff --git a/GL/apple/Makefile.am b/GL/apple/Makefile.am
deleted file mode 100644
index 7ad9140..0000000
--- a/GL/apple/Makefile.am
+++ /dev/null
@@ -1,14 +0,0 @@
-AM_CFLAGS = $(DIX_CFLAGS)
-AM_CPPFLAGS = \
-	-I$(top_srcdir) \
-	-I$(top_srcdir)/GL/glx \
-	-I$(top_srcdir)/GL/include \
-	-I$(top_srcdir)/GL/mesa/glapi \
-	-I$(top_srcdir)/hw/xquartz \
-	-I$(top_srcdir)/hw/xquartz/xpr \
-	-I$(top_srcdir)/miext/damage
-
-noinst_LIBRARIES = libCGLcore.a 
-libCGLcore_a_SOURCES = \
-	indirect.c \
-	$(top_srcdir)/hw/dmx/glxProxy/compsize.c
diff --git a/GL/apple/indirect.c b/GL/apple/indirect.c
deleted file mode 100644
index a0884d4..0000000
--- a/GL/apple/indirect.c
+++ /dev/null
@@ -1,1940 +0,0 @@
-/*
- * GLX implementation that uses Apple's OpenGL.framework
- * (Indirect rendering path)
- *
- * Copyright (c) 2007 Apple Inc.
- * Copyright (c) 2004 Torrey T. Lyons. All Rights Reserved.
- * Copyright (c) 2002 Greg Parker. All Rights Reserved.
- *
- * Portions of this file are copied from Mesa's xf86glx.c,
- * which contains the following copyright:
- *
- * Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
- * All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "dri.h"
-
-#define GL_EXT_histogram 1
-#define GL_EXT_polygon_offset 1
-#define GL_SGIS_pixel_texture 1
-#define GL_SGIX_pixel_texture 1
-#define GL_EXT_multisample 1
-#define GL_SGIS_multisample 1
-#define GL_EXT_vertex_array 1
-#define GL_ARB_point_parameters 1
-#define GL_NV_vertex_array_range 1
-#define GL_MESA_resize_buffers 1
-#define GL_ARB_window_pos 1
-#define GL_EXT_cull_vertex 1
-#define GL_NV_vertex_program 1
-#define GL_APPLE_fence 1
-#define GL_IBM_multimode_draw_arrays 1
-#define GL_EXT_fragment_shader 1
-
-#include <OpenGL/OpenGL.h>
-#include <OpenGL/CGLContext.h>
-
-// X11 and X11's glx
-#include <GL/gl.h>
-#include <GL/glxproto.h>
-#include <windowstr.h>
-#include <resource.h>
-#include <GL/glxint.h>
-#include <GL/glxtokens.h>
-#include <scrnintstr.h>
-#include <glxserver.h>
-#include <glxscreens.h>
-#include <glxdrawable.h>
-#include <glxcontext.h>
-#include <glxext.h>
-#include <glxutil.h>
-#include <glxscreens.h>
-#include <GL/internal/glcore.h>
-#include "x-hash.h"
-#include "x-list.h"
-
-#include <dispatch.h>
-#define GLAPIENTRYP *
-typedef unsigned long long GLuint64EXT;
-typedef long long GLint64EXT;
-#include <Xplugin.h>
-#include "glcontextmodes.h"
-#include <glapi.h>
-#include <glapitable.h>
-
-// ggs: needed to call back to glx with visual configs
-extern void GlxSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs, void **configprivs);
-__GLXprovider * GlxGetMesaProvider (void);
-
-// Write debugging output, or not
-#ifdef GLAQUA_DEBUG
-#define GLAQUA_DEBUG_MSG ErrorF
-#else
-#define GLAQUA_DEBUG_MSG(a, ...)
-#endif
-
-static void setup_dispatch_table(void);
-GLuint __glFloorLog2(GLuint val);
-void warn_func(void * p1, char *format, ...);
-
-// some prototypes
-static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen);
-static __GLXdrawable * __glXAquaScreenCreateDrawable(__GLXscreen *screen, DrawablePtr pDraw, XID drawId, __GLXconfig *modes);
-
-static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
-                              int *nvisualp, int *ndepthp,
-                              int *rootDepthp, VisualID *defaultVisp,
-                              unsigned long sizes, int bitsPerRGB);
-static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
-                                   void **privates);
-
-static void glAquaResetExtension(void);
-static void __glXAquaContextDestroy(__GLXcontext *baseContext);
-static int __glXAquaContextMakeCurrent(__GLXcontext *baseContext);
-static int __glXAquaContextLoseCurrent(__GLXcontext *baseContext);
-static int __glXAquaContextForceCurrent(__GLXcontext *baseContext);
-static int __glXAquaContextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, unsigned long mask);
-
-static CGLPixelFormatObj makeFormat(__GLXconfig *mode);
-
-__GLXprovider __glXMesaProvider = {
-  __glXAquaScreenProbe,
-  "Core OpenGL",
-    NULL
-};
-
-__GLXprovider *
-GlxGetMesaProvider (void)
-{
-  GLAQUA_DEBUG_MSG("GlxGetMesaProvider\n");
-  return &__glXMesaProvider;
-}
-
-typedef struct __GLXAquaScreen   __GLXAquaScreen;
-typedef struct __GLXAquaContext  __GLXAquaContext;
-typedef struct __GLXAquaDrawable __GLXAquaDrawable;
-
-struct __GLXAquaScreen {
-  __GLXscreen   base;
-  int           index;
-    int num_vis;
-    __GLXconfig *modes;
-};
-
-static __GLXAquaScreen glAquaScreens[MAXSCREENS];
-
-struct __GLXAquaContext {
-  __GLXcontext base;
-  CGLContextObj ctx;
-  CGLPixelFormatObj pixelFormat;
-  xp_surface_id sid;
-  unsigned isAttached :1;
-};
-
-struct __GLXAquaDrawable {
-  __GLXdrawable base;
-    DrawablePtr pDraw;
-    xp_surface_id sid;
-};
-
-static __GLXcontext *
-__glXAquaScreenCreateContext(__GLXscreen *screen,
-			     __GLXconfig *config,
-			     __GLXcontext *baseShareContext)
-{
-  __GLXAquaContext *context;
-  __GLXAquaContext *shareContext = (__GLXAquaContext *) baseShareContext;
-  CGLError gl_err;
-  
-  GLAQUA_DEBUG_MSG("glXAquaScreenCreateContext\n");
-
-  context = malloc (sizeof (__GLXAquaContext));
-  if (context == NULL) return NULL;
-
-  memset(context, 0, sizeof *context);
-
-  context->base.pGlxScreen = screen;
-  context->base.config      = config;
-
-  context->base.destroy        = __glXAquaContextDestroy;
-  context->base.makeCurrent    = __glXAquaContextMakeCurrent;
-  context->base.loseCurrent    = __glXAquaContextLoseCurrent;
-  context->base.copy           = __glXAquaContextCopy;
-  context->base.forceCurrent   = __glXAquaContextForceCurrent;
-  //  context->base.createDrawable = __glXAquaContextCreateDrawable;
-
-  context->pixelFormat = makeFormat(config);
-  if (!context->pixelFormat) {
-        free(context);
-        return NULL;
-  }
-
-  context->ctx = NULL;
-  gl_err = CGLCreateContext(context->pixelFormat,
-                            shareContext ? shareContext->ctx : NULL,
-                            &context->ctx);
-
-  if (gl_err != 0) {
-      ErrorF("CGLCreateContext error: %s\n", CGLErrorString(gl_err));
-      CGLDestroyPixelFormat(context->pixelFormat);
-      free(context);
-      return NULL;
-    }
-	setup_dispatch_table();
-    GLAQUA_DEBUG_MSG("glAquaCreateContext done\n");
-  return &context->base;
-}
-
-static __GLXextensionInfo __glDDXExtensionInfo = {
-    GL_CORE_APPLE,
-    glAquaResetExtension,
-    glAquaInitVisuals,
-    glAquaSetVisualConfigs
-};
-
-void *__glXglDDXExtensionInfo(void) {
-  GLAQUA_DEBUG_MSG("glXAglDDXExtensionInfo\n");
-    return &__glDDXExtensionInfo;
-}
-
-/* maps from surface id -> list of __GLcontext */
-static x_hash_table *surface_hash;
-
-static void __glXAquaContextDestroy(__GLXcontext *baseContext) {
-    x_list *lst;
-
-    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
-
-    GLAQUA_DEBUG_MSG("glAquaContextDestroy (ctx 0x%x)\n",
-                     (unsigned int) baseContext);
-    if (context != NULL) {
-      if (context->sid != 0 && surface_hash != NULL) {
-		lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
-		lst = x_list_remove(lst, context);
-		x_hash_table_insert(surface_hash, (void *) context->sid, lst);
-      }
-
-      if (context->ctx != NULL) CGLDestroyContext(context->ctx);
-
-      if (context->pixelFormat != NULL)	CGLDestroyPixelFormat(context->pixelFormat);
-      
-      free(context);
-    }
-}
-
-static int __glXAquaContextLoseCurrent(__GLXcontext *baseContext) {
-    CGLError gl_err;
-
-    GLAQUA_DEBUG_MSG("glAquaLoseCurrent (ctx 0x%p)\n", baseContext);
-
-    gl_err = CGLSetCurrentContext(NULL);
-    if (gl_err != 0)
-      ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
-
-    __glXLastContext = NULL; // Mesa does this; why?
-
-    return GL_TRUE;
-}
-
-/* Called when a surface is destroyed as a side effect of destroying
-   the window it's attached to. */
-static void surface_notify(void *_arg, void *data) {
-    DRISurfaceNotifyArg *arg = (DRISurfaceNotifyArg *)_arg;
-    __GLXAquaDrawable *draw = (__GLXAquaDrawable *)data;
-    __GLXAquaContext *context;
-    x_list *lst;
-	if(_arg == NULL || data == NULL) {
-		ErrorF("surface_notify called with bad params");
-		return;
-	}
-	
-    GLAQUA_DEBUG_MSG("surface_notify(%p, %p)\n", _arg, data);
-    switch (arg->kind) {
-    case AppleDRISurfaceNotifyDestroyed:
-        if (surface_hash != NULL)
-            x_hash_table_remove(surface_hash, (void *) arg->id);
-	        draw->base.pDraw = NULL;
-			draw->sid = 0;
-        break;
-
-    case AppleDRISurfaceNotifyChanged:
-        if (surface_hash != NULL) {
-            lst = x_hash_table_lookup(surface_hash, (void *) arg->id, NULL);
-            for (; lst != NULL; lst = lst->next)
-            {
-                context = lst->data;
-                xp_update_gl_context(context->ctx);
-            }
-        }
-        break;
-	default:
-		ErrorF("surface_notify: unknown kind %d\n", arg->kind);
-		break;
-    }
-}
-
-static void attach(__GLXAquaContext *context, __GLXAquaDrawable *draw) {
-    DrawablePtr pDraw;
-	GLAQUA_DEBUG_MSG("attach(%p, %p)\n", context, draw);
-    pDraw = draw->base.pDraw;
-
-    if (draw->sid == 0) {
-//        if (!quartzProcs->CreateSurface(pDraw->pScreen, pDraw->id, pDraw,
-        if (!DRICreateSurface(pDraw->pScreen, pDraw->id, pDraw,
-                                        0, &draw->sid, NULL,
-                                        surface_notify, draw))
-            return;
-        draw->pDraw = pDraw;
-	} 
-
-    if (!context->isAttached || context->sid != draw->sid) {
-        x_list *lst;
-
-        if (xp_attach_gl_context(context->ctx, draw->sid) != Success) {
-//            quartzProcs->DestroySurface(pDraw->pScreen, pDraw->id, pDraw,
-            DRIDestroySurface(pDraw->pScreen, pDraw->id, pDraw,
-								surface_notify, draw);
-            if (surface_hash != NULL)
-                x_hash_table_remove(surface_hash, (void *) draw->sid);
-
-            draw->sid = 0;
-            return;
-        }
-
-        context->isAttached = TRUE;
-        context->sid = draw->sid;
-
-        if (surface_hash == NULL)
-            surface_hash = x_hash_table_new(NULL, NULL, NULL, NULL);
-
-        lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
-        if (x_list_find(lst, context) == NULL) {
-            lst = x_list_prepend(lst, context);
-            x_hash_table_insert(surface_hash, (void *) context->sid, lst);
-        }
-
-        GLAQUA_DEBUG_MSG("attached 0x%x to 0x%x\n", (unsigned int) pDraw->id,
-                         (unsigned int) draw->sid);
-    } 
-}
-
-#if 0     // unused
-static void unattach(__GLXAquaContext *context) {
-	x_list *lst;
-	GLAQUA_DEBUG_MSG("unattach\n");
-	if (context == NULL) {
-		ErrorF("Tried to unattach a null context\n");
-		return;
-	}
-    if (context->isAttached) {
-        GLAQUA_DEBUG_MSG("unattaching\n");
-
-        if (surface_hash != NULL) {
-            lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
-            lst = x_list_remove(lst, context);
-            x_hash_table_insert(surface_hash, (void *) context->sid, lst);
-        }
-
-        CGLClearDrawable(context->ctx);
-        context->isAttached = FALSE;
-        context->sid = 0;
-    }
-}
-#endif
-
-static int __glXAquaContextMakeCurrent(__GLXcontext *baseContext) {
-    CGLError gl_err;
-    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
-	__GLXAquaDrawable *drawPriv = (__GLXAquaDrawable *) context->base.drawPriv;
-
-    GLAQUA_DEBUG_MSG("glAquaMakeCurrent (ctx 0x%p)\n", baseContext);
-    
-    attach(context, drawPriv);
-
-    gl_err = CGLSetCurrentContext(context->ctx);
-    if (gl_err != 0)
-        ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
-    
-    return gl_err == 0;
-}
-
-static int __glXAquaContextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, unsigned long mask)
-{
-    CGLError gl_err;
-
-    __GLXAquaContext *dst = (__GLXAquaContext *) baseDst;
-    __GLXAquaContext *src = (__GLXAquaContext *) baseSrc;
-
-    GLAQUA_DEBUG_MSG("GLXAquaContextCopy\n");
-
-    gl_err = CGLCopyContext(src->ctx, dst->ctx, mask);
-    if (gl_err != 0)
-        ErrorF("CGLCopyContext error: %s\n", CGLErrorString(gl_err));
-
-    return gl_err == 0;
-}
-
-static int __glXAquaContextForceCurrent(__GLXcontext *baseContext)
-{
-    CGLError gl_err;
-    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
-    GLAQUA_DEBUG_MSG("glAquaForceCurrent (ctx %p)\n", context->ctx);
-
-    gl_err = CGLSetCurrentContext(context->ctx);
-    if (gl_err != 0)
-        ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
-
-    return gl_err == 0;
-}
-
-/* Drawing surface notification callbacks */
-
-static GLboolean __glXAquaDrawableResize(__GLXdrawable *base)  {
-    GLAQUA_DEBUG_MSG("unimplemented glAquaDrawableResize\n");
-    return GL_TRUE;
-}
-
-static GLboolean __glXAquaDrawableSwapBuffers(__GLXdrawable *base) {
-    CGLError gl_err;
-	__GLXAquaContext * drawableCtx;
-//    GLAQUA_DEBUG_MSG("glAquaDrawableSwapBuffers(%p)\n",base);
-	
-	if(!base) {
-		ErrorF("glXAquaDrawbleSwapBuffers passed NULL\n");
-	    return GL_FALSE;
-	}
-
-    drawableCtx = (__GLXAquaContext *)base->drawGlxc;
-
-    if (drawableCtx != NULL && drawableCtx->ctx != NULL) {
-        gl_err = CGLFlushDrawable(drawableCtx->ctx);
-        if (gl_err != 0)
-            ErrorF("CGLFlushDrawable error: %s\n", CGLErrorString(gl_err));
-    }
-    return GL_TRUE;
-}
-
-static CGLPixelFormatObj makeFormat(__GLXconfig *config) {
-    int i;
-    CGLPixelFormatAttribute attr[64]; // currently uses max of 30
-    CGLPixelFormatObj result;
-    GLint n_formats;
-    CGLError gl_err;
-    
-    GLAQUA_DEBUG_MSG("makeFormat\n");
-
-    if (!config->rgbMode)
-        return NULL;
-
-    i = 0;
-
-    // attr [i++] = kCGLPFAAcelerated; // require hwaccel - BAD for multiscreen
-    // attr [i++] = kCGLPFANoRecovery; // disable fallback renderers - BAD
-
-    if (config->stereoMode) {
-        attr[i++] = kCGLPFAStereo;
-    }
-
-    if (config->doubleBufferMode) {
-        attr[i++] = kCGLPFADoubleBuffer;
-    }
-
-    if (config->colorIndexMode) {
-        /* ignored */
-    }
-
-    if (config->rgbMode) {
-        attr[i++] = kCGLPFAColorSize;
-        attr[i++] = config->redBits + config->greenBits + config->blueBits;
-        attr[i++] = kCGLPFAAlphaSize;
-        attr[i++] = 1; /* FIXME: ignoring config->alphaBits which is always 0 */
-    }
-
-    if (config->haveAccumBuffer) {
-        attr[i++] = kCGLPFAAccumSize;
-        attr[i++] = config->accumRedBits + config->accumGreenBits
-                    + config->accumBlueBits + config->accumAlphaBits;
-    }
-	
-    if (config->haveDepthBuffer) {
-        attr[i++] = kCGLPFADepthSize;
-        attr[i++] = config->depthBits;
-    }
-	
-    if (config->haveStencilBuffer) {
-        attr[i++] = kCGLPFAStencilSize;
-        attr[i++] = config->stencilBits;
-    }
-
-    attr[i++] = kCGLPFAAuxBuffers;
-    attr[i++] = config->numAuxBuffers;
-
-    /* mode->level ignored */
-
-    /* mode->pixmapMode ? */
-
-    attr[i++] = 0;
-
-    GLAQUA_DEBUG_MSG("makeFormat almost done\n");
-
-    result = NULL;
-    gl_err = CGLChoosePixelFormat(attr, &result, &n_formats);
-    if (gl_err != 0)
-        ErrorF("CGLChoosePixelFormat error: %s\n", CGLErrorString(gl_err));
-
-    GLAQUA_DEBUG_MSG("makeFormat done (0x%x)\n", (unsigned int) result);
-
-    return result;
-}
-
-// Originally copied from Mesa
-
-static int                 numConfigs     = 0;
-static __GLXvisualConfig  *visualConfigs  = NULL;
-static void              **visualPrivates = NULL;
-
-/*
- * In the case the driver defines no GLX visuals we'll use these.
- * Note that for TrueColor and DirectColor visuals, bufferSize is the 
- * sum of redSize, greenSize, blueSize and alphaSize, which may be larger 
- * than the nplanes/rootDepth of the server's X11 visuals
- */
-#define NUM_FALLBACK_CONFIGS 5
-static __GLXvisualConfig FallbackConfigs[NUM_FALLBACK_CONFIGS] = {
-  /* [0] = RGB, double buffered, Z */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-     0,  0,  0, 0,      /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    0,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [1] = RGB, double buffered, Z, stencil, accum */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-    16, 16, 16, 0,      /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    8,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [2] = RGB+Alpha, double buffered, Z, stencil, accum */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 8,      /* rgba sizes */
-    -1, -1, -1, -1,     /* rgba masks */
-    16, 16, 16, 16,     /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    8,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [3] = RGB+Alpha, single buffered, Z, stencil, accum */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 8,      /* rgba sizes */
-    -1, -1, -1, -1,     /* rgba masks */
-    16, 16, 16, 16,     /* rgba accum sizes */
-    False,              /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    8,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [4] = CI, double buffered, Z */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    False,              /* rgba? (false = color index) */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-     0,  0,  0, 0,      /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    0,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-};
-
-static __GLXvisualConfig NullConfig = {
-    -1,                 /* vid */
-    -1,                 /* class */
-    False,              /* rgba */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-     0,  0,  0, 0,      /* rgba accum sizes */
-    False,              /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    0,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE_EXT,       /* visualRating */
-    0,                  /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-};
-
-
-static inline int count_bits(uint32_t x)
-{
-    x = x - ((x >> 1) & 0x55555555);
-    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
-    x = (x + (x >> 4)) & 0x0f0f0f0f;
-    x = x + (x >> 8);
-    x = x + (x >> 16);
-    return x & 63;
-}
-
-
-static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
-                         VisualID *defaultVisp,
-                         int ndepth, DepthPtr pdepth,
-                         int rootDepth)
-{
-    int numRGBconfigs;
-    int numCIconfigs;
-    int numVisuals = *nvisualp;
-    int numNewVisuals;
-    int numNewConfigs;
-    VisualPtr pVisual = *visualp;
-    VisualPtr pVisualNew = NULL;
-    VisualID *orig_vid = NULL;
-    __GLXconfig *modes;
-    __GLXvisualConfig *pNewVisualConfigs = NULL;
-    void **glXVisualPriv;
-    void **pNewVisualPriv;
-    int found_default;
-    int i, j, k;
-
-    GLAQUA_DEBUG_MSG("init_visuals\n");
-
-    if (numConfigs > 0)
-        numNewConfigs = numConfigs;
-    else
-        numNewConfigs = NUM_FALLBACK_CONFIGS;
-
-    /* Alloc space for the list of new GLX visuals */
-    pNewVisualConfigs = (__GLXvisualConfig *)
-                     malloc(numNewConfigs * sizeof(__GLXvisualConfig));
-    if (!pNewVisualConfigs) {
-        return FALSE;
-    }
-
-    /* Alloc space for the list of new GLX visual privates */
-    pNewVisualPriv = (void **) malloc(numNewConfigs * sizeof(void *));
-    if (!pNewVisualPriv) {
-        free(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /*
-    ** If SetVisualConfigs was not called, then use default GLX
-    ** visual configs.
-    */
-    if (numConfigs == 0) {
-        memcpy(pNewVisualConfigs, FallbackConfigs,
-               NUM_FALLBACK_CONFIGS * sizeof(__GLXvisualConfig));
-        memset(pNewVisualPriv, 0, NUM_FALLBACK_CONFIGS * sizeof(void *));
-    }
-    else {
-        /* copy driver's visual config info */
-        for (i = 0; i < numConfigs; i++) {
-            pNewVisualConfigs[i] = visualConfigs[i];
-            pNewVisualPriv[i] = visualPrivates[i];
-        }
-    }
-
-    /* Count the number of RGB and CI visual configs */
-    numRGBconfigs = 0;
-    numCIconfigs = 0;
-    for (i = 0; i < numNewConfigs; i++) {
-        if (pNewVisualConfigs[i].rgba)
-            numRGBconfigs++;
-        else
-            numCIconfigs++;
-    }
-
-    /* Count the total number of visuals to compute */
-    numNewVisuals = 0;
-    for (i = 0; i < numVisuals; i++) {
-        int count;
-
-        count = ((pVisual[i].class == TrueColor ||
-                  pVisual[i].class == DirectColor)
-                ? numRGBconfigs : numCIconfigs);
-        if (count == 0)
-            count = 1;          /* preserve the existing visual */
-
-        numNewVisuals += count;
-    }
-
-    /* Reset variables for use with the next screen/driver's visual configs */
-    visualConfigs = NULL;
-    numConfigs = 0;
-
-    /* Alloc temp space for the list of orig VisualIDs for each new visual */
-    orig_vid = (VisualID *)malloc(numNewVisuals * sizeof(VisualID));
-    if (!orig_vid) {
-        free(pNewVisualPriv);
-        free(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Alloc space for the list of glXVisuals */
-    modes = _gl_context_modes_create(numNewVisuals, sizeof(__GLXconfig));
-    if (modes == NULL) {
-        free(orig_vid);
-        free(pNewVisualPriv);
-        free(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Alloc space for the list of glXVisualPrivates */
-    glXVisualPriv = (void **)malloc(numNewVisuals * sizeof(void *));
-    if (!glXVisualPriv) {
-        _gl_context_modes_destroy( modes );
-        free(orig_vid);
-        free(pNewVisualPriv);
-        free(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Alloc space for the new list of the X server's visuals */
-    pVisualNew = (VisualPtr)malloc(numNewVisuals * sizeof(VisualRec));
-    if (!pVisualNew) {
-        free(glXVisualPriv);
-        _gl_context_modes_destroy( modes );
-        free(orig_vid);
-        free(pNewVisualPriv);
-        free(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Initialize the new visuals */
-    found_default = FALSE;
-    glAquaScreens[screenInfo.numScreens-1].modes = modes;
-    for (i = j = 0; i < numVisuals; i++) {
-        int is_rgb = (pVisual[i].class == TrueColor ||
-                      pVisual[i].class == DirectColor);
-
-        if (!is_rgb)
-        {
-            /* We don't support non-rgb visuals for GL. But we don't
-               want to remove them either, so just pass them through
-               with null glX configs */
-
-            pVisualNew[j] = pVisual[i];
-            pVisualNew[j].vid = FakeClientID(0);
-
-            /* Check for the default visual */
-            if (!found_default && pVisual[i].vid == *defaultVisp) {
-                *defaultVisp = pVisualNew[j].vid;
-                found_default = TRUE;
-            }
-
-            /* Save the old VisualID */
-            orig_vid[j] = pVisual[i].vid;
-
-            /* Initialize the glXVisual */
-            _gl_copy_visual_to_context_mode( modes, & NullConfig );
-            modes->visualID = pVisualNew[j].vid;
-
-            j++;
-
-            continue;
-        }
-
-        for (k = 0; k < numNewConfigs; k++) {
-            if (pNewVisualConfigs[k].rgba != is_rgb)
-                continue;
-
-            assert( modes != NULL );
-
-            /* Initialize the new visual */
-            pVisualNew[j] = pVisual[i];
-            pVisualNew[j].vid = FakeClientID(0);
-
-            /* Check for the default visual */
-            if (!found_default && pVisual[i].vid == *defaultVisp) {
-                *defaultVisp = pVisualNew[j].vid;
-                found_default = TRUE;
-            }
-
-            /* Save the old VisualID */
-            orig_vid[j] = pVisual[i].vid;
-
-            /* Initialize the glXVisual */
-            _gl_copy_visual_to_context_mode( modes, & pNewVisualConfigs[k] );
-            modes->visualID = pVisualNew[j].vid;
-
-            /*
-             * If the class is -1, then assume the X visual information
-             * is identical to what GLX needs, and take them from the X
-             * visual.  NOTE: if class != -1, then all other fields MUST
-             * be initialized.
-             */
-            if (modes->visualType == GLX_NONE) {
-                modes->visualType = _gl_convert_from_x_visual_type( pVisual[i].class );
-                modes->redBits    = count_bits(pVisual[i].redMask);
-                modes->greenBits  = count_bits(pVisual[i].greenMask);
-                modes->blueBits   = count_bits(pVisual[i].blueMask);
-                modes->alphaBits  = modes->alphaBits;
-                modes->redMask    = pVisual[i].redMask;
-                modes->greenMask  = pVisual[i].greenMask;
-                modes->blueMask   = pVisual[i].blueMask;
-                modes->alphaMask  = modes->alphaMask;
-                modes->rgbBits = (is_rgb)
-                    ? (modes->redBits + modes->greenBits +
-                       modes->blueBits + modes->alphaBits)
-                    : rootDepth;
-            }
-
-            /* Save the device-dependent private for this visual */
-            glXVisualPriv[j] = pNewVisualPriv[k];
-
-            j++;
-            modes = modes->next;
-        }
-    }
-
-    assert(j <= numNewVisuals);
-
-    /* Save the GLX visuals in the screen structure */
-    glAquaScreens[screenInfo.numScreens-1].num_vis = numNewVisuals;
-    //    glAquaScreens[screenInfo.numScreens-1].priv = glXVisualPriv;
-
-    /* set up depth's VisualIDs */
-    for (i = 0; i < ndepth; i++) {
-        int numVids = 0;
-        VisualID *pVids = NULL;
-        int k, n = 0;
-
-        /* Count the new number of VisualIDs at this depth */
-        for (j = 0; j < pdepth[i].numVids; j++)
-            for (k = 0; k < numNewVisuals; k++)
-            if (pdepth[i].vids[j] == orig_vid[k])
-                numVids++;
-
-        /* Allocate a new list of VisualIDs for this depth */
-        pVids = (VisualID *)malloc(numVids * sizeof(VisualID));
-
-        /* Initialize the new list of VisualIDs for this depth */
-        for (j = 0; j < pdepth[i].numVids; j++)
-            for (k = 0; k < numNewVisuals; k++)
-            if (pdepth[i].vids[j] == orig_vid[k])
-                pVids[n++] = pVisualNew[k].vid;
-
-        /* Update this depth's list of VisualIDs */
-        free(pdepth[i].vids);
-        pdepth[i].vids = pVids;
-        pdepth[i].numVids = numVids;
-    }
-
-    /* Update the X server's visuals */
-    *nvisualp = numNewVisuals;
-    *visualp = pVisualNew;
-
-    /* Free the old list of the X server's visuals */
-    free(pVisual);
-
-    /* Clean up temporary allocations */
-    free(orig_vid);
-    free(pNewVisualPriv);
-    free(pNewVisualConfigs);
-
-    /* Free the private list created by DDX HW driver */
-    if (visualPrivates)
-        free(visualPrivates);
-    visualPrivates = NULL;
-
-    return TRUE;
-}
-
-Bool enable_stereo = FALSE;
-/* based on code in i830_dri.c
-   This ends calling glAquaSetVisualConfigs to set the static
-   numconfigs, etc. */
-// see also glxglcore.c -- bhb
-static void
-glAquaInitVisualConfigs(void)
-{
-    int                 lclNumConfigs     = 0;
-    __GLXvisualConfig  *lclVisualConfigs  = NULL;
-    void              **lclVisualPrivates = NULL;
-
-    int stereo, depth, aux, buffers, stencil, accum;
-    int i = 0;
-
-    GLAQUA_DEBUG_MSG("glAquaInitVisualConfigs ");
-        
-    /* count num configs:
-        2 stereo (on, off) (optional)
-        2 Z buffer (0, 24 bit)
-        2 AUX buffer (0, 2)
-        2 buffers (single, double)
-        2 stencil (0, 8 bit)
-        2 accum (0, 64 bit)
-        = 64 configs with stereo, or 32 without */
-
-    if (enable_stereo) lclNumConfigs = 2 * 2 * 2 * 2 * 2 * 2; /* 64 */
-    else               lclNumConfigs = 2 * 2 * 2 * 2 * 2; /* 32 */
-
-    /* alloc */
-    lclVisualConfigs = xcalloc(sizeof(__GLXvisualConfig), lclNumConfigs);
-    lclVisualPrivates = xcalloc(sizeof(void *), lclNumConfigs);
-
-    /* fill in configs */
-    if (NULL != lclVisualConfigs) {
-        i = 0; /* current buffer */
-        for (stereo = 0; stereo < (enable_stereo ? 2 : 1); stereo++) {
-	  for (depth = 0; depth < 2; depth++) {
-            for (aux = 0; aux < 2; aux++) {
-	      for (buffers = 0; buffers < 2; buffers++) {
-		for (stencil = 0; stencil < 2; stencil++) {
-		  for (accum = 0; accum < 2; accum++) {
-		    lclVisualConfigs[i].vid = -1;
-		    lclVisualConfigs[i].class = -1;
-		    lclVisualConfigs[i].rgba = TRUE;
-		    lclVisualConfigs[i].redSize = -1;
-		    lclVisualConfigs[i].greenSize = -1;
-		    lclVisualConfigs[i].blueSize = -1;
-		    lclVisualConfigs[i].redMask = -1;
-		    lclVisualConfigs[i].greenMask = -1;
-		    lclVisualConfigs[i].blueMask = -1;
-		    lclVisualConfigs[i].alphaMask = 0;
-		    if (accum) {
-		      lclVisualConfigs[i].accumRedSize = 16;
-		      lclVisualConfigs[i].accumGreenSize = 16;
-		      lclVisualConfigs[i].accumBlueSize = 16;
-		      lclVisualConfigs[i].accumAlphaSize = 16;
-		    } else {
-		      lclVisualConfigs[i].accumRedSize = 0;
-		      lclVisualConfigs[i].accumGreenSize = 0;
-		      lclVisualConfigs[i].accumBlueSize = 0;
-		      lclVisualConfigs[i].accumAlphaSize = 0;
-		    }
-		    lclVisualConfigs[i].doubleBuffer = buffers ? TRUE : FALSE;
-		    lclVisualConfigs[i].stereo = stereo ? TRUE : FALSE;
-		    lclVisualConfigs[i].bufferSize = -1;
-		    
-		    lclVisualConfigs[i].depthSize = depth? 24 : 0;
-		    lclVisualConfigs[i].stencilSize = stencil ? 8 : 0;
-		    lclVisualConfigs[i].auxBuffers = aux ? 2 : 0;
-		    lclVisualConfigs[i].level = 0;
-		    lclVisualConfigs[i].visualRating = GLX_NONE_EXT;
-		    lclVisualConfigs[i].transparentPixel = 0;
-		    lclVisualConfigs[i].transparentRed = 0;
-		    lclVisualConfigs[i].transparentGreen = 0;
-		    lclVisualConfigs[i].transparentBlue = 0;
-		    lclVisualConfigs[i].transparentAlpha = 0;
-		    lclVisualConfigs[i].transparentIndex = 0;
-		    i++;
-		  }
-		}
-	      }
-            }
-	  }
-	}
-    }
-    if (i != lclNumConfigs)
-        GLAQUA_DEBUG_MSG("glAquaInitVisualConfigs failed to alloc visual configs");
-
-    GlxSetVisualConfigs(lclNumConfigs, lclVisualConfigs, lclVisualPrivates);
-}
-
-
-static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
-                                   void **privates)
-{
-    GLAQUA_DEBUG_MSG("glAquaSetVisualConfigs\n");
-
-    numConfigs = nconfigs;
-    visualConfigs = configs;
-    visualPrivates = privates;
-}
-
-static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
-                              int *nvisualp, int *ndepthp,
-                              int *rootDepthp, VisualID *defaultVisp,
-                              unsigned long sizes, int bitsPerRGB)
-{
-    GLAQUA_DEBUG_MSG("glAquaInitVisuals\n");
-    
-    if (numConfigs == 0) /* if no configs */
-        glAquaInitVisualConfigs(); /* ensure the visual configs are setup */
-
-    /*
-     * setup the visuals supported by this particular screen.
-     */
-    return init_visuals(nvisualp, visualp, defaultVisp,
-                        *ndepthp, *depthp, *rootDepthp);
-}
-
-#if 0
-static void fixup_visuals(int screen)
-{
-    ScreenPtr pScreen = screenInfo.screens[screen];
-    glAquaScreenRec *pScr = &glAquaScreens[screen];
-    int j;
-    __GLcontextModes *modes;
-
-    GLAQUA_DEBUG_MSG("fixup_visuals\n");
-
-    for ( modes = pScr->modes ; modes != NULL ; modes = modes->next ) {
-        const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
-        const int nplanes = (modes->rgbBits - modes->alphaBits);
-        const VisualPtr pVis = pScreen->visuals;
-
-        /* Find a visual that matches the GLX visual's class and size */
-        for (j = 0; j < pScreen->numVisuals; j++) {
-            if (pVis[j].class == vis_class &&
-            pVis[j].nplanes == nplanes) {
-
-            /* Fixup the masks */
-            modes->redMask   = pVis[j].redMask;
-            modes->greenMask = pVis[j].greenMask;
-            modes->blueMask  = pVis[j].blueMask;
-
-            /* Recalc the sizes */
-            modes->redBits   = count_bits(modes->redMask);
-            modes->greenBits = count_bits(modes->greenMask);
-            modes->blueBits  = count_bits(modes->blueMask);
-            }
-        }
-    }
-}
-#endif
-static void __glXAquaScreenDestroy(__GLXscreen *screen) {
-
-	GLAQUA_DEBUG_MSG("glXAquaScreenDestroy(%p)\n", screen);
-  __glXScreenDestroy(screen);
-
-  free(screen);
-}
-
-static void init_screen_visuals(__GLXAquaScreen *screen) {
-  ScreenPtr pScreen = screen->base.pScreen;
-  
-  __GLXconfig *modes;
-  int *used;
-  int i, j;
-  
-    GLAQUA_DEBUG_MSG("init_screen_visuals\n");
-
-    /* FIXME: Change 'used' to be a array of bits (rather than of ints),
-     * FIXME: create a stack array of 8 or 16 bytes.  If 'numVisuals' is less
-     * FIXME: than 64 or 128 the stack array can be used instead of calling
-     * FIXME: malloc / free.  If nothing else, convert 'used' to
-     * FIXME: array of bytes instead of ints!
-     */
-    used = (int *)malloc(pScreen->numVisuals * sizeof(int));
-    memset(used, 0, pScreen->numVisuals * sizeof(int));
-
-    i = 0;
-    for ( modes = screen -> base.visuals
-          ; modes != NULL
-          ; modes = modes->next ) {
-        const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
-        const int nplanes = (modes->rgbBits - modes->alphaBits);
-        const VisualPtr pVis = pScreen->visuals;
-
-        for (j = 0; j < pScreen->numVisuals; j++) {
-            if (pVis[j].class     == vis_class &&
-                pVis[j].nplanes   == nplanes &&
-                pVis[j].redMask   == modes->redMask &&
-                pVis[j].greenMask == modes->greenMask &&
-                pVis[j].blueMask  == modes->blueMask &&
-                !used[j]) {
-
-                    /* set the VisualID */
-                    modes->visualID = pVis[j].vid;
-
-                    /* Mark this visual used */
-                    used[j] = 1;
-                    break;
-            }
-        }
-        if ( j == pScreen->numVisuals ) {
-            ErrorF("No matching visual for __GLcontextMode with "
-                   "visual class = %d (%d), nplanes = %u\n",
-                   vis_class, 
-                   (int)modes->visualType,
-                   (unsigned int)(modes->rgbBits - modes->alphaBits) );
-        }
-        else if ( modes->visualID == -1 ) {
-            FatalError( "Matching visual found, but visualID still -1!\n" );
-        }
-
-        i++;
-    }
-
-    free(used);
-}
-
-static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen) {
-  __GLXAquaScreen *screen;
-  GLAQUA_DEBUG_MSG("glXAquaScreenProbe\n");
-  if (screen == NULL) return NULL;
-
-  screen = malloc(sizeof *screen);
-
-  __glXScreenInit(&screen->base, pScreen);
-
-  screen->base.destroy        = __glXAquaScreenDestroy;
-  screen->base.createContext  = __glXAquaScreenCreateContext;
-  screen->base.createDrawable = __glXAquaScreenCreateDrawable;
-  screen->base.pScreen       = pScreen;
-
-  init_screen_visuals(screen);
-
-  return &screen->base;
-}
-
-static void __glXAquaDrawableDestroy(__GLXdrawable *base) {
-    GLAQUA_DEBUG_MSG("glAquaDestroyDrawablePrivate\n");
-
-    /* It doesn't work to call DRIDestroySurface here, the drawable's
-       already gone.. But dri.c notices the window destruction and
-       frees the surface itself. */
-
-    free(base);
-}
-
-static __GLXdrawable *
-__glXAquaScreenCreateDrawable(__GLXscreen *screen,
-			      DrawablePtr pDraw,
-			      XID drawId,
-			      __GLXconfig *modes) {
-  __GLXAquaDrawable *glxPriv;
-
-  GLAQUA_DEBUG_MSG("glAquaScreenCreateDrawable(%p,%p,%d,%p)\n", context, pDraw, drawId, modes);
-
-  glxPriv = xalloc(sizeof *glxPriv);
-  if (glxPriv == NULL) return NULL;
-
-  memset(glxPriv, 0, sizeof *glxPriv);
-
-  if (!__glXDrawableInit(&glxPriv->base, screen, pDraw, GLX_DRAWABLE_PIXMAP /*?*/, drawId, modes)) {
-    xfree(glxPriv);
-    return NULL;
-  }
-
-  glxPriv->base.destroy       = __glXAquaDrawableDestroy;
-  glxPriv->base.resize        = __glXAquaDrawableResize;
-  glxPriv->base.swapBuffers   = __glXAquaDrawableSwapBuffers;
-  //  glxPriv->base.copySubBuffer = __glXAquaDrawableCopySubBuffer;
-
-  return &glxPriv->base;
-}
-
-static void glAquaResetExtension(void)
-{
-    GLAQUA_DEBUG_MSG("glAquaResetExtension\n");
-    CGLSetOption(kCGLGOResetLibrary, GL_TRUE);
-}
-
-// Extra goodies for glx
-
-GLuint __glFloorLog2(GLuint val)
-{
-    int c = 0;
-
-    while (val > 1) {
-        c++;
-        val >>= 1;
-    }
-    return c;
-}
-
-void warn_func(void * p1, char *format, ...) {
-  va_list v;
-  va_start(v, format);
-  vfprintf(stderr, format, v);
-  va_end(v);
-}
-
-static void setup_dispatch_table(void) {
-  struct _glapi_table *disp=_glapi_get_dispatch();
-  _glapi_set_warning_func((_glapi_warning_func)warn_func);
-  _glapi_noop_enable_warnings(TRUE);
-
-  SET_Accum(disp, glAccum);
-  SET_ActiveStencilFaceEXT(disp, glActiveStencilFaceEXT);
-  SET_ActiveTextureARB(disp, glActiveTextureARB);
-//SET_AlphaFragmentOp1ATI(disp, glAlphaFragmentOp1EXT);   // <-- EXT -> ATI
-//SET_AlphaFragmentOp2ATI(disp, glAlphaFragmentOp2EXT);
-//SET_AlphaFragmentOp3ATI(disp, glAlphaFragmentOp3EXT);
-  SET_AlphaFunc(disp, glAlphaFunc);
-//SET_AreProgramsResidentNV(disp, glAreProgramsResidentNV);
-  SET_AreTexturesResident(disp, glAreTexturesResident); 
-  SET_ArrayElement(disp, glArrayElement);
-  SET_AttachObjectARB(disp, glAttachObjectARB);
-  SET_Begin(disp, glBegin);
-//SET_BeginFragmentShaderATI(disp, glBeginFragmentShaderEXT);   // <-- EXT -> ATI
-  SET_BeginQueryARB(disp, glBeginQueryARB);
-  SET_BindAttribLocationARB(disp, glBindAttribLocationARB);
-  SET_BindBufferARB(disp, glBindBufferARB);
-//SET_BindFragmentShaderATI(disp, glBindFragmentShaderEXT);     // <-- EXT -> ATI
-  SET_BindFramebufferEXT(disp, glBindFramebufferEXT);
-//SET_BindProgramNV(disp, glBindProgramNV);
-  SET_BindRenderbufferEXT(disp, glBindRenderbufferEXT);
-  SET_BindTexture(disp, glBindTexture);
-  SET_Bitmap(disp, glBitmap);
-  SET_BlendColor(disp, glBlendColor);
-  SET_BlendEquation(disp, glBlendEquation);
-  SET_BlendEquationSeparateEXT(disp, glBlendEquationSeparateEXT);
-  SET_BlendFunc(disp, glBlendFunc);
-  SET_BlendFuncSeparateEXT(disp, glBlendFuncSeparateEXT);
-  SET_BlitFramebufferEXT(disp, glBlitFramebufferEXT);
-  SET_BufferDataARB(disp, glBufferDataARB);
-  SET_BufferSubDataARB(disp, glBufferSubDataARB);
-  SET_CallList(disp, glCallList);
-  SET_CallLists(disp, glCallLists);
-  SET_CheckFramebufferStatusEXT(disp, glCheckFramebufferStatusEXT);
-  SET_Clear(disp, glClear);
-  SET_ClearAccum(disp, glClearAccum);
-  SET_ClearColor(disp, glClearColor);
-  SET_ClearDepth(disp, glClearDepth);
-  SET_ClearIndex(disp, glClearIndex);
-  SET_ClearStencil(disp, glClearStencil);
-  SET_ClientActiveTextureARB(disp, glClientActiveTextureARB);
-  SET_ClipPlane(disp, glClipPlane);
-  SET_Color3b(disp, glColor3b);
-  SET_Color3bv(disp, glColor3bv);
-  SET_Color3d(disp, glColor3d);
-  SET_Color3dv(disp, glColor3dv);
-  SET_Color3f(disp, glColor3f);
-  SET_Color3fv(disp, glColor3fv);
-  SET_Color3i(disp, glColor3i);
-  SET_Color3iv(disp, glColor3iv);
-  SET_Color3s(disp, glColor3s);
-  SET_Color3sv(disp, glColor3sv);
-  SET_Color3ub(disp, glColor3ub);
-  SET_Color3ubv(disp, glColor3ubv);
-  SET_Color3ui(disp, glColor3ui);
-  SET_Color3uiv(disp, glColor3uiv);
-  SET_Color3us(disp, glColor3us);
-  SET_Color3usv(disp, glColor3usv);
-  SET_Color4b(disp, glColor4b);
-  SET_Color4bv(disp, glColor4bv);
-  SET_Color4d(disp, glColor4d);
-  SET_Color4dv(disp, glColor4dv);
-  SET_Color4f(disp, glColor4f);
-  SET_Color4fv(disp, glColor4fv);
-  SET_Color4i(disp, glColor4i);
-  SET_Color4iv(disp, glColor4iv);
-  SET_Color4s(disp, glColor4s);
-  SET_Color4sv(disp, glColor4sv);
-  SET_Color4ub(disp, glColor4ub);
-  SET_Color4ubv(disp, glColor4ubv);
-  SET_Color4ui(disp, glColor4ui);
-  SET_Color4uiv(disp, glColor4uiv);
-  SET_Color4us(disp, glColor4us);
-  SET_Color4usv(disp, glColor4usv);
-//SET_ColorFragmentOp1ATI(disp, glColorFragmentOp1EXT);    // <-- EXT -> ATI
-//SET_ColorFragmentOp2ATI(disp, glColorFragmentOp2EXT);
-//SET_ColorFragmentOp3ATI(disp, glColorFragmentOp3EXT);
-  SET_ColorMask(disp, glColorMask);
-  SET_ColorMaterial(disp, glColorMaterial);
-  SET_ColorPointer(disp, glColorPointer);
-//SET_ColorPointerEXT(disp, glColorPointerEXT);
-  SET_ColorSubTable(disp, glColorSubTable);
-  SET_ColorTable(disp, glColorTable);
-  SET_ColorTableParameterfv(disp, glColorTableParameterfv);
-  SET_ColorTableParameteriv(disp, glColorTableParameteriv);
-  SET_CombinerInputNV(disp, glCombinerInputNV);
-  SET_CombinerOutputNV(disp, glCombinerOutputNV);
-  SET_CombinerParameterfNV(disp, glCombinerParameterfNV);
-  SET_CombinerParameterfvNV(disp, glCombinerParameterfvNV);
-  SET_CombinerParameteriNV(disp, glCombinerParameteriNV);
-  SET_CombinerParameterivNV(disp, glCombinerParameterivNV);
-  SET_CompileShaderARB(disp, glCompileShaderARB);
-  SET_CompressedTexImage1DARB(disp, glCompressedTexImage1DARB);
-  SET_CompressedTexImage2DARB(disp, glCompressedTexImage2DARB);
-  SET_CompressedTexImage3DARB(disp, glCompressedTexImage3DARB);
-  SET_CompressedTexSubImage1DARB(disp, glCompressedTexSubImage1DARB);
-  SET_CompressedTexSubImage2DARB(disp, glCompressedTexSubImage2DARB);
-  SET_CompressedTexSubImage3DARB(disp, glCompressedTexSubImage3DARB);
-  SET_ConvolutionFilter1D(disp, glConvolutionFilter1D);
-  SET_ConvolutionFilter2D(disp, glConvolutionFilter2D);
-  SET_ConvolutionParameterf(disp, glConvolutionParameterf);
-  SET_ConvolutionParameterfv(disp, glConvolutionParameterfv);
-  SET_ConvolutionParameteri(disp, glConvolutionParameteri);
-  SET_ConvolutionParameteriv(disp, glConvolutionParameteriv);
-  SET_CopyColorSubTable(disp, glCopyColorSubTable);
-  SET_CopyColorTable(disp, glCopyColorTable);
-  SET_CopyConvolutionFilter1D(disp, glCopyConvolutionFilter1D);
-  SET_CopyConvolutionFilter2D(disp, glCopyConvolutionFilter2D);
-  SET_CopyPixels(disp, glCopyPixels);
-  SET_CopyTexImage1D(disp, glCopyTexImage1D);
-  SET_CopyTexImage2D(disp, glCopyTexImage2D);
-  SET_CopyTexSubImage1D(disp, glCopyTexSubImage1D);
-  SET_CopyTexSubImage2D(disp, glCopyTexSubImage2D);
-  SET_CopyTexSubImage3D(disp, glCopyTexSubImage3D);
-  SET_CreateProgramObjectARB(disp, glCreateProgramObjectARB);
-  SET_CreateShaderObjectARB(disp, glCreateShaderObjectARB);
-  SET_CullFace(disp, glCullFace);
-//SET_CullParameterdvEXT(disp, glCullParameterdvEXT);
-//SET_CullParameterfvEXT(disp, glCullParameterfvEXT);
-  SET_DeleteBuffersARB(disp, glDeleteBuffersARB);
-  SET_DeleteFencesNV(disp, glDeleteFencesAPPLE);
-//SET_DeleteFragmentShaderATI(disp, glDeleteFragmentShaderEXT);      // <-- EXT -> ATI
-  SET_DeleteFramebuffersEXT(disp, glDeleteFramebuffersEXT);
-  SET_DeleteLists(disp, glDeleteLists);
-  SET_DeleteObjectARB(disp, glDeleteObjectARB);
-//SET_DeleteProgramsNV(disp, glDeleteProgramsNV);
-  SET_DeleteQueriesARB(disp, glDeleteQueriesARB);
-  SET_DeleteRenderbuffersEXT(disp, glDeleteRenderbuffersEXT);
-  SET_DeleteTextures(disp, glDeleteTextures);
-  SET_DepthBoundsEXT(disp, glDepthBoundsEXT);
-  SET_DepthFunc(disp, glDepthFunc);
-  SET_DepthMask(disp, glDepthMask);
-  SET_DepthRange(disp, glDepthRange);
-  SET_DetachObjectARB(disp, glDetachObjectARB);
-  SET_Disable(disp, glDisable);
-  SET_DisableClientState(disp, glDisableClientState);
-  SET_DisableVertexAttribArrayARB(disp, glDisableVertexAttribArrayARB);
-  SET_DrawArrays(disp, glDrawArrays);
-  SET_DrawBuffer(disp, glDrawBuffer);
-  SET_DrawBuffersARB(disp, glDrawBuffersARB);
-  SET_DrawElements(disp, glDrawElements);
-  SET_DrawPixels(disp, glDrawPixels);
-  SET_DrawRangeElements(disp, glDrawRangeElements);
-  SET_EdgeFlag(disp, glEdgeFlag);
-  SET_EdgeFlagPointer(disp, glEdgeFlagPointer);
-//SET_EdgeFlagPointerEXT(disp, glEdgeFlagPointerEXT);
-  SET_EdgeFlagv(disp, glEdgeFlagv);
-  SET_Enable(disp, glEnable);
-  SET_EnableClientState(disp, glEnableClientState);
-  SET_EnableVertexAttribArrayARB(disp, glEnableVertexAttribArrayARB);
-  SET_End(disp, glEnd);
-//SET_EndFragmentShaderATI(disp, glEndFragmentShaderEXT);        // <-- EXT -> ATI
-  SET_EndList(disp, glEndList);
-  SET_EndQueryARB(disp, glEndQueryARB);
-  SET_EvalCoord1d(disp, glEvalCoord1d);
-  SET_EvalCoord1dv(disp, glEvalCoord1dv);
-  SET_EvalCoord1f(disp, glEvalCoord1f);
-  SET_EvalCoord1fv(disp, glEvalCoord1fv);
-  SET_EvalCoord2d(disp, glEvalCoord2d);
-  SET_EvalCoord2dv(disp, glEvalCoord2dv);
-  SET_EvalCoord2f(disp, glEvalCoord2f);
-  SET_EvalCoord2fv(disp, glEvalCoord2fv);
-  SET_EvalMesh1(disp, glEvalMesh1);
-  SET_EvalMesh2(disp, glEvalMesh2);
-  SET_EvalPoint1(disp, glEvalPoint1);
-  SET_EvalPoint2(disp, glEvalPoint2);
-//SET_ExecuteProgramNV(disp, glExecuteProgramNV);
-  SET_FeedbackBuffer(disp, glFeedbackBuffer);
-  SET_FinalCombinerInputNV(disp, glFinalCombinerInputNV);
-  SET_Finish(disp, glFinish);
-  SET_FinishFenceNV(disp, glFinishFenceAPPLE);       // <-- APPLE -> NV
-  SET_Flush(disp, glFlush);
-//SET_FlushVertexArrayRangeNV(disp, glFlushVertexArrayRangeNV);
-  SET_FogCoordPointerEXT(disp, glFogCoordPointerEXT);
-  SET_FogCoorddEXT(disp, glFogCoorddEXT);
-  SET_FogCoorddvEXT(disp, glFogCoorddvEXT);
-  SET_FogCoordfEXT(disp, glFogCoordfEXT);
-  SET_FogCoordfvEXT(disp, glFogCoordfvEXT);
-  SET_Fogf(disp, glFogf);
-  SET_Fogfv(disp, glFogfv);
-  SET_Fogi(disp, glFogi);
-  SET_Fogiv(disp, glFogiv);
-  SET_FramebufferRenderbufferEXT(disp, glFramebufferRenderbufferEXT);
-  SET_FramebufferTexture1DEXT(disp, glFramebufferTexture1DEXT);
-  SET_FramebufferTexture2DEXT(disp, glFramebufferTexture2DEXT);
-  SET_FramebufferTexture3DEXT(disp, glFramebufferTexture3DEXT);
-  SET_FrontFace(disp, glFrontFace);
-  SET_Frustum(disp, glFrustum);
-  SET_GenBuffersARB(disp, glGenBuffersARB);
-  SET_GenFencesNV(disp, glGenFencesAPPLE);            // <-- APPLE -> NV
-//SET_GenFragmentShadersATI(disp, glGenFragmentShadersEXT);         // <-- EXT -> ATI
-  SET_GenFramebuffersEXT(disp, glGenFramebuffersEXT);
-  SET_GenLists(disp, glGenLists);
-//SET_GenProgramsNV(disp, glGenProgramsNV);
-  SET_GenQueriesARB(disp, glGenQueriesARB);
-  SET_GenRenderbuffersEXT(disp, glGenRenderbuffersEXT);
-  SET_GenTextures(disp, glGenTextures);
-  SET_GenerateMipmapEXT(disp, glGenerateMipmapEXT);
-  SET_GetActiveAttribARB(disp, glGetActiveAttribARB);
-  SET_GetActiveUniformARB(disp, glGetActiveUniformARB);
-  SET_GetAttachedObjectsARB(disp, glGetAttachedObjectsARB);
-  SET_GetAttribLocationARB(disp, glGetAttribLocationARB);
-  SET_GetBooleanv(disp, glGetBooleanv);
-  SET_GetBufferParameterivARB(disp, glGetBufferParameterivARB);
-  SET_GetBufferPointervARB(disp, glGetBufferPointervARB);
-  SET_GetBufferSubDataARB(disp, glGetBufferSubDataARB);
-  SET_GetClipPlane(disp, glGetClipPlane);
-  SET_GetColorTable(disp, glGetColorTable);
-  SET_GetColorTableParameterfv(disp, glGetColorTableParameterfv);
-  SET_GetColorTableParameteriv(disp, glGetColorTableParameteriv);
-  SET_GetCombinerInputParameterfvNV(disp, glGetCombinerInputParameterfvNV);
-  SET_GetCombinerInputParameterivNV(disp, glGetCombinerInputParameterivNV);
-  SET_GetCombinerOutputParameterfvNV(disp, glGetCombinerOutputParameterfvNV);
-  SET_GetCombinerOutputParameterivNV(disp, glGetCombinerOutputParameterivNV);
-  SET_GetCompressedTexImageARB(disp, glGetCompressedTexImageARB);
-  SET_GetConvolutionFilter(disp, glGetConvolutionFilter);
-  SET_GetConvolutionParameterfv(disp, glGetConvolutionParameterfv);
-  SET_GetConvolutionParameteriv(disp, glGetConvolutionParameteriv);
-  SET_GetDoublev(disp, glGetDoublev);
-  SET_GetError(disp, glGetError);
-//SET_GetFenceivNV(disp, glGetFenceivNV);
-  SET_GetFinalCombinerInputParameterfvNV(disp, glGetFinalCombinerInputParameterfvNV);
-  SET_GetFinalCombinerInputParameterivNV(disp, glGetFinalCombinerInputParameterivNV);
-  SET_GetFloatv(disp, glGetFloatv);
-  SET_GetFramebufferAttachmentParameterivEXT(disp, glGetFramebufferAttachmentParameterivEXT);
-  SET_GetHandleARB(disp, glGetHandleARB);
-  SET_GetHistogram(disp, glGetHistogram);
-  SET_GetHistogramParameterfv(disp, glGetHistogramParameterfv);
-  SET_GetHistogramParameteriv(disp, glGetHistogramParameteriv);
-  SET_GetInfoLogARB(disp, glGetInfoLogARB);
-  SET_GetIntegerv(disp, glGetIntegerv);
-  SET_GetLightfv(disp, glGetLightfv);
-  SET_GetLightiv(disp, glGetLightiv);
-  SET_GetMapdv(disp, glGetMapdv);
-  SET_GetMapfv(disp, glGetMapfv);
-  SET_GetMapiv(disp, glGetMapiv);
-  SET_GetMaterialfv(disp, glGetMaterialfv);
-  SET_GetMaterialiv(disp, glGetMaterialiv);
-  SET_GetMinmax(disp, glGetMinmax);
-  SET_GetMinmaxParameterfv(disp, glGetMinmaxParameterfv);
-  SET_GetMinmaxParameteriv(disp, glGetMinmaxParameteriv);
-  SET_GetObjectParameterfvARB(disp, glGetObjectParameterfvARB);
-  SET_GetObjectParameterivARB(disp, glGetObjectParameterivARB);
-  SET_GetPixelMapfv(disp, glGetPixelMapfv);
-  SET_GetPixelMapuiv(disp, glGetPixelMapuiv);
-  SET_GetPixelMapusv(disp, glGetPixelMapusv);
-//SET_GetPixelTexGenParameterfvSGIS(disp, glGetPixelTexGenParameterfvSGIS);
-//SET_GetPixelTexGenParameterivSGIS(disp, glGetPixelTexGenParameterivSGIS);
-  SET_GetPointerv(disp, glGetPointerv);
-  SET_GetPolygonStipple(disp, glGetPolygonStipple);
-  SET_GetProgramEnvParameterdvARB(disp, glGetProgramEnvParameterdvARB);
-  SET_GetProgramEnvParameterfvARB(disp, glGetProgramEnvParameterfvARB);
-  SET_GetProgramLocalParameterdvARB(disp, glGetProgramLocalParameterdvARB);
-  SET_GetProgramLocalParameterfvARB(disp, glGetProgramLocalParameterfvARB);
-//SET_GetProgramNamedParameterdvNV(disp, glGetProgramNamedParameterdvNV);
-//SET_GetProgramNamedParameterfvNV(disp, glGetProgramNamedParameterfvNV);
-//SET_GetProgramParameterdvNV(disp, glGetProgramParameterdvNV);
-//SET_GetProgramParameterfvNV(disp, glGetProgramParameterfvNV);
-  SET_GetProgramStringARB(disp, glGetProgramStringARB);
-//SET_GetProgramStringNV(disp, glGetProgramStringNV);
-  SET_GetProgramivARB(disp, glGetProgramivARB);
-//SET_GetProgramivNV(disp, glGetProgramivNV);
-//SET_GetQueryObjecti64vEXT(disp, glGetQueryObjecti64vEXT);
-  SET_GetQueryObjectivARB(disp, glGetQueryObjectivARB);
-//SET_GetQueryObjectui64vEXT(disp, glGetQueryObjectui64vEXT);
-  SET_GetQueryObjectuivARB(disp, glGetQueryObjectuivARB);
-  SET_GetQueryivARB(disp, glGetQueryivARB);
-  SET_GetRenderbufferParameterivEXT(disp, glGetRenderbufferParameterivEXT);
-  SET_GetSeparableFilter(disp, glGetSeparableFilter);
-  SET_GetShaderSourceARB(disp, glGetShaderSourceARB);
-  SET_GetString(disp, glGetString);
-  SET_GetTexEnvfv(disp, glGetTexEnvfv);
-  SET_GetTexEnviv(disp, glGetTexEnviv);
-  SET_GetTexGendv(disp, glGetTexGendv);
-  SET_GetTexGenfv(disp, glGetTexGenfv);
-  SET_GetTexGeniv(disp, glGetTexGeniv);
-  SET_GetTexImage(disp, glGetTexImage);
-  SET_GetTexLevelParameterfv(disp, glGetTexLevelParameterfv);
-  SET_GetTexLevelParameteriv(disp, glGetTexLevelParameteriv);
-  SET_GetTexParameterfv(disp, glGetTexParameterfv);
-  SET_GetTexParameteriv(disp, glGetTexParameteriv);
-//SET_GetTrackMatrixivNV(disp, glGetTrackMatrixivNV);
-  SET_GetUniformLocationARB(disp, glGetUniformLocationARB);
-  SET_GetUniformfvARB(disp, glGetUniformfvARB);
-  SET_GetUniformivARB(disp, glGetUniformivARB);
-//SET_GetVertexAttribPointervNV(disp, glGetVertexAttribPointervNV);
-  SET_GetVertexAttribdvARB(disp, glGetVertexAttribdvARB);
-//SET_GetVertexAttribdvNV(disp, glGetVertexAttribdvNV);
-  SET_GetVertexAttribfvARB(disp, glGetVertexAttribfvARB);
-//SET_GetVertexAttribfvNV(disp, glGetVertexAttribfvNV);
-  SET_GetVertexAttribivARB(disp, glGetVertexAttribivARB);
-//SET_GetVertexAttribivNV(disp, glGetVertexAttribivNV);
-  SET_Hint(disp, glHint);
-  SET_Histogram(disp, glHistogram);
-  SET_IndexMask(disp, glIndexMask);
-  SET_IndexPointer(disp, glIndexPointer);
-//SET_IndexPointerEXT(disp, glIndexPointerEXT);
-  SET_Indexd(disp, glIndexd);
-  SET_Indexdv(disp, glIndexdv);
-  SET_Indexf(disp, glIndexf);
-  SET_Indexfv(disp, glIndexfv);
-  SET_Indexi(disp, glIndexi);
-  SET_Indexiv(disp, glIndexiv);
-  SET_Indexs(disp, glIndexs);
-  SET_Indexsv(disp, glIndexsv);
-  SET_Indexub(disp, glIndexub);
-  SET_Indexubv(disp, glIndexubv);
-  SET_InitNames(disp, glInitNames);
-  SET_InterleavedArrays(disp, glInterleavedArrays);
-  SET_IsBufferARB(disp, glIsBufferARB);
-  SET_IsEnabled(disp, glIsEnabled);
-  SET_IsFenceNV(disp, glIsFenceAPPLE);           // <-- APPLE -> NV
-  SET_IsFramebufferEXT(disp, glIsFramebufferEXT);
-  SET_IsList(disp, glIsList);
-//SET_IsProgramNV(disp, glIsProgramNV);
-  SET_IsQueryARB(disp, glIsQueryARB);
-  SET_IsRenderbufferEXT(disp, glIsRenderbufferEXT);
-  SET_IsTexture(disp, glIsTexture);
-  SET_LightModelf(disp, glLightModelf);
-  SET_LightModelfv(disp, glLightModelfv);
-  SET_LightModeli(disp, glLightModeli);
-  SET_LightModeliv(disp, glLightModeliv);
-  SET_Lightf(disp, glLightf);
-  SET_Lightfv(disp, glLightfv);
-  SET_Lighti(disp, glLighti);
-  SET_Lightiv(disp, glLightiv);
-  SET_LineStipple(disp, glLineStipple);
-  SET_LineWidth(disp, glLineWidth);
-  SET_LinkProgramARB(disp, glLinkProgramARB);
-  SET_ListBase(disp, glListBase);
-  SET_LoadIdentity(disp, glLoadIdentity);
-  SET_LoadMatrixd(disp, glLoadMatrixd);
-  SET_LoadMatrixf(disp, glLoadMatrixf);
-  SET_LoadName(disp, glLoadName);
-//SET_LoadProgramNV(disp, glLoadProgramNV);
-  SET_LoadTransposeMatrixdARB(disp, glLoadTransposeMatrixdARB);
-  SET_LoadTransposeMatrixfARB(disp, glLoadTransposeMatrixfARB);
-  SET_LockArraysEXT(disp, glLockArraysEXT);
-  SET_LogicOp(disp, glLogicOp);
-  SET_Map1d(disp, glMap1d);
-  SET_Map1f(disp, glMap1f);
-  SET_Map2d(disp, glMap2d);
-  SET_Map2f(disp, glMap2f);
-  SET_MapBufferARB(disp, glMapBufferARB);
-  SET_MapGrid1d(disp, glMapGrid1d);
-  SET_MapGrid1f(disp, glMapGrid1f);
-  SET_MapGrid2d(disp, glMapGrid2d);
-  SET_MapGrid2f(disp, glMapGrid2f);
-  SET_Materialf(disp, glMaterialf);
-  SET_Materialfv(disp, glMaterialfv);
-  SET_Materiali(disp, glMateriali);
-  SET_Materialiv(disp, glMaterialiv);
-  SET_MatrixMode(disp, glMatrixMode);
-  SET_Minmax(disp, glMinmax);
-  SET_MultMatrixd(disp, glMultMatrixd);
-  SET_MultMatrixf(disp, glMultMatrixf);
-  SET_MultTransposeMatrixdARB(disp, glMultTransposeMatrixdARB);
-  SET_MultTransposeMatrixfARB(disp, glMultTransposeMatrixfARB);
-  SET_MultiDrawArraysEXT(disp, glMultiDrawArraysEXT);
-  SET_MultiDrawElementsEXT(disp, glMultiDrawElementsEXT);
-//SET_MultiModeDrawArraysIBM(disp, glMultiModeDrawArraysIBM);
-//SET_MultiModeDrawElementsIBM(disp, glMultiModeDrawElementsIBM);
-  SET_MultiTexCoord1dARB(disp, glMultiTexCoord1dARB);
-  SET_MultiTexCoord1dvARB(disp, glMultiTexCoord1dvARB);
-  SET_MultiTexCoord1fARB(disp, glMultiTexCoord1fARB);
-  SET_MultiTexCoord1fvARB(disp, glMultiTexCoord1fvARB);
-  SET_MultiTexCoord1iARB(disp, glMultiTexCoord1iARB);
-  SET_MultiTexCoord1ivARB(disp, glMultiTexCoord1ivARB);
-  SET_MultiTexCoord1sARB(disp, glMultiTexCoord1sARB);
-  SET_MultiTexCoord1svARB(disp, glMultiTexCoord1svARB);
-  SET_MultiTexCoord2dARB(disp, glMultiTexCoord2dARB);
-  SET_MultiTexCoord2dvARB(disp, glMultiTexCoord2dvARB);
-  SET_MultiTexCoord2fARB(disp, glMultiTexCoord2fARB);
-  SET_MultiTexCoord2fvARB(disp, glMultiTexCoord2fvARB);
-  SET_MultiTexCoord2iARB(disp, glMultiTexCoord2iARB);
-  SET_MultiTexCoord2ivARB(disp, glMultiTexCoord2ivARB);
-  SET_MultiTexCoord2sARB(disp, glMultiTexCoord2sARB);
-  SET_MultiTexCoord2svARB(disp, glMultiTexCoord2svARB);
-  SET_MultiTexCoord3dARB(disp, glMultiTexCoord3dARB);
-  SET_MultiTexCoord3dvARB(disp, glMultiTexCoord3dvARB);
-  SET_MultiTexCoord3fARB(disp, glMultiTexCoord3fARB);
-  SET_MultiTexCoord3fvARB(disp, glMultiTexCoord3fvARB);
-  SET_MultiTexCoord3iARB(disp, glMultiTexCoord3iARB);
-  SET_MultiTexCoord3ivARB(disp, glMultiTexCoord3ivARB);
-  SET_MultiTexCoord3sARB(disp, glMultiTexCoord3sARB);
-  SET_MultiTexCoord3svARB(disp, glMultiTexCoord3svARB);
-  SET_MultiTexCoord4dARB(disp, glMultiTexCoord4dARB);
-  SET_MultiTexCoord4dvARB(disp, glMultiTexCoord4dvARB);
-  SET_MultiTexCoord4fARB(disp, glMultiTexCoord4fARB);
-  SET_MultiTexCoord4fvARB(disp, glMultiTexCoord4fvARB);
-  SET_MultiTexCoord4iARB(disp, glMultiTexCoord4iARB);
-  SET_MultiTexCoord4ivARB(disp, glMultiTexCoord4ivARB);
-  SET_MultiTexCoord4sARB(disp, glMultiTexCoord4sARB);
-  SET_MultiTexCoord4svARB(disp, glMultiTexCoord4svARB);
-  SET_NewList(disp, glNewList);
-  SET_Normal3b(disp, glNormal3b);
-  SET_Normal3bv(disp, glNormal3bv);
-  SET_Normal3d(disp, glNormal3d);
-  SET_Normal3dv(disp, glNormal3dv);
-  SET_Normal3f(disp, glNormal3f);
-  SET_Normal3fv(disp, glNormal3fv);
-  SET_Normal3i(disp, glNormal3i);
-  SET_Normal3iv(disp, glNormal3iv);
-  SET_Normal3s(disp, glNormal3s);
-  SET_Normal3sv(disp, glNormal3sv);
-  SET_NormalPointer(disp, glNormalPointer);
-//SET_NormalPointerEXT(disp, glNormalPointerEXT);
-  SET_Ortho(disp, glOrtho);
-//SET_PassTexCoordATI(disp, glPassTexCoordEXT);         // <-- EXT -> ATI
-  SET_PassThrough(disp, glPassThrough);
-  SET_PixelMapfv(disp, glPixelMapfv);
-  SET_PixelMapuiv(disp, glPixelMapuiv);
-  SET_PixelMapusv(disp, glPixelMapusv);
-  SET_PixelStoref(disp, glPixelStoref);
-  SET_PixelStorei(disp, glPixelStorei);
-//SET_PixelTexGenParameterfSGIS(disp, glPixelTexGenParameterfSGIS);
-//SET_PixelTexGenParameterfvSGIS(disp, glPixelTexGenParameterfvSGIS);
-//SET_PixelTexGenParameteriSGIS(disp, glPixelTexGenParameteriSGIS);
-//SET_PixelTexGenParameterivSGIS(disp, glPixelTexGenParameterivSGIS);
-//  SET_PixelTexGenSGIX(disp, glPixelTexGenSGIX);
-  SET_PixelTransferf(disp, glPixelTransferf);
-  SET_PixelTransferi(disp, glPixelTransferi);
-  SET_PixelZoom(disp, glPixelZoom);
-  SET_PointParameterfEXT(disp, glPointParameterfARB);      // <-- ARB -> EXT
-  SET_PointParameterfvEXT(disp, glPointParameterfvARB);    // <-- ARB -> EXT
-  SET_PointParameteriNV(disp, glPointParameteriNV);
-  SET_PointParameterivNV(disp, glPointParameterivNV);
-  SET_PointSize(disp, glPointSize);
-  SET_PolygonMode(disp, glPolygonMode);
-  SET_PolygonOffset(disp, glPolygonOffset);
-//SET_PolygonOffsetEXT(disp, glPolygonOffsetEXT);
-  SET_PolygonStipple(disp, glPolygonStipple);
-  SET_PopAttrib(disp, glPopAttrib);
-  SET_PopClientAttrib(disp, glPopClientAttrib);
-  SET_PopMatrix(disp, glPopMatrix);
-  SET_PopName(disp, glPopName);
-  SET_PrioritizeTextures(disp, glPrioritizeTextures);
-  SET_ProgramEnvParameter4dARB(disp, glProgramEnvParameter4dARB);
-  SET_ProgramEnvParameter4dvARB(disp, glProgramEnvParameter4dvARB);
-  SET_ProgramEnvParameter4fARB(disp, glProgramEnvParameter4fARB);
-  SET_ProgramEnvParameter4fvARB(disp, glProgramEnvParameter4fvARB);
-  SET_ProgramLocalParameter4dARB(disp, glProgramLocalParameter4dARB);
-  SET_ProgramLocalParameter4dvARB(disp, glProgramLocalParameter4dvARB);
-  SET_ProgramLocalParameter4fARB(disp, glProgramLocalParameter4fARB);
-  SET_ProgramLocalParameter4fvARB(disp, glProgramLocalParameter4fvARB);
-//SET_ProgramNamedParameter4dNV(disp, glProgramNamedParameter4dNV);
-//SET_ProgramNamedParameter4dvNV(disp, glProgramNamedParameter4dvNV);
-//SET_ProgramNamedParameter4fNV(disp, glProgramNamedParameter4fNV);
-//SET_ProgramNamedParameter4fvNV(disp, glProgramNamedParameter4fvNV);
-//SET_ProgramParameter4dNV(disp, glProgramParameter4dNV);
-//SET_ProgramParameter4dvNV(disp, glProgramParameter4dvNV);
-//SET_ProgramParameter4fNV(disp, glProgramParameter4fNV);
-//SET_ProgramParameter4fvNV(disp, glProgramParameter4fvNV);
-//SET_ProgramParameters4dvNV(disp, glProgramParameters4dvNV);
-//SET_ProgramParameters4fvNV(disp, glProgramParameters4fvNV);
-  SET_ProgramStringARB(disp, glProgramStringARB);
-  SET_PushAttrib(disp, glPushAttrib);
-  SET_PushClientAttrib(disp, glPushClientAttrib);
-  SET_PushMatrix(disp, glPushMatrix);
-  SET_PushName(disp, glPushName);
-  SET_RasterPos2d(disp, glRasterPos2d);
-  SET_RasterPos2dv(disp, glRasterPos2dv);
-  SET_RasterPos2f(disp, glRasterPos2f);
-  SET_RasterPos2fv(disp, glRasterPos2fv);
-  SET_RasterPos2i(disp, glRasterPos2i);
-  SET_RasterPos2iv(disp, glRasterPos2iv);
-  SET_RasterPos2s(disp, glRasterPos2s);
-  SET_RasterPos2sv(disp, glRasterPos2sv);
-  SET_RasterPos3d(disp, glRasterPos3d);
-  SET_RasterPos3dv(disp, glRasterPos3dv);
-  SET_RasterPos3f(disp, glRasterPos3f);
-  SET_RasterPos3fv(disp, glRasterPos3fv);
-  SET_RasterPos3i(disp, glRasterPos3i);
-  SET_RasterPos3iv(disp, glRasterPos3iv);
-  SET_RasterPos3s(disp, glRasterPos3s);
-  SET_RasterPos3sv(disp, glRasterPos3sv);
-  SET_RasterPos4d(disp, glRasterPos4d);
-  SET_RasterPos4dv(disp, glRasterPos4dv);
-  SET_RasterPos4f(disp, glRasterPos4f);
-  SET_RasterPos4fv(disp, glRasterPos4fv);
-  SET_RasterPos4i(disp, glRasterPos4i);
-  SET_RasterPos4iv(disp, glRasterPos4iv);
-  SET_RasterPos4s(disp, glRasterPos4s);
-  SET_RasterPos4sv(disp, glRasterPos4sv);
-  SET_ReadBuffer(disp, glReadBuffer);
-  SET_ReadPixels(disp, glReadPixels);
-  SET_Rectd(disp, glRectd);
-  SET_Rectdv(disp, glRectdv);
-  SET_Rectf(disp, glRectf);
-  SET_Rectfv(disp, glRectfv);
-  SET_Recti(disp, glRecti);
-  SET_Rectiv(disp, glRectiv);
-  SET_Rects(disp, glRects);
-  SET_Rectsv(disp, glRectsv);
-  SET_RenderMode(disp, glRenderMode);
-  SET_RenderbufferStorageEXT(disp, glRenderbufferStorageEXT);
-//SET_RequestResidentProgramsNV(disp, glRequestResidentProgramsNV);
-  SET_ResetHistogram(disp, glResetHistogram);
-  SET_ResetMinmax(disp, glResetMinmax);
-//SET_ResizeBuffersMESA(disp, glResizeBuffersMESA);
-  SET_Rotated(disp, glRotated);
-  SET_Rotatef(disp, glRotatef);
-  SET_SampleCoverageARB(disp, glSampleCoverageARB);
-//SET_SampleMapATI(disp, glSampleMapEXT);       // <-- EXT -> ATI
-//SET_SampleMaskSGIS(disp, glSampleMaskSGIS);
-//SET_SamplePatternSGIS(disp, glSamplePatternSGIS);
-  SET_Scaled(disp, glScaled);
-  SET_Scalef(disp, glScalef);
-  SET_Scissor(disp, glScissor);
-  SET_SecondaryColor3bEXT(disp, glSecondaryColor3bEXT);
-  SET_SecondaryColor3bvEXT(disp, glSecondaryColor3bvEXT);
-  SET_SecondaryColor3dEXT(disp, glSecondaryColor3dEXT);
-  SET_SecondaryColor3dvEXT(disp, glSecondaryColor3dvEXT);
-  SET_SecondaryColor3fEXT(disp, glSecondaryColor3fEXT);
-  SET_SecondaryColor3fvEXT(disp, glSecondaryColor3fvEXT);
-  SET_SecondaryColor3iEXT(disp, glSecondaryColor3iEXT);
-  SET_SecondaryColor3ivEXT(disp, glSecondaryColor3ivEXT);
-  SET_SecondaryColor3sEXT(disp, glSecondaryColor3sEXT);
-  SET_SecondaryColor3svEXT(disp, glSecondaryColor3svEXT);
-  SET_SecondaryColor3ubEXT(disp, glSecondaryColor3ubEXT);
-  SET_SecondaryColor3ubvEXT(disp, glSecondaryColor3ubvEXT);
-  SET_SecondaryColor3uiEXT(disp, glSecondaryColor3uiEXT);
-  SET_SecondaryColor3uivEXT(disp, glSecondaryColor3uivEXT);
-  SET_SecondaryColor3usEXT(disp, glSecondaryColor3usEXT);
-  SET_SecondaryColor3usvEXT(disp, glSecondaryColor3usvEXT);
-  SET_SecondaryColorPointerEXT(disp, glSecondaryColorPointerEXT);
-  SET_SelectBuffer(disp, glSelectBuffer);
-  SET_SeparableFilter2D(disp, glSeparableFilter2D);
-  SET_SetFenceNV(disp, glSetFenceAPPLE);  // <-- APPLE -> NV
-//SET_SetFragmentShaderConstantATI(disp, glSetFragmentShaderConstantEXT);   // <-- EXT -> ATI
-  SET_ShadeModel(disp, glShadeModel);
-  SET_ShaderSourceARB(disp, glShaderSourceARB);
-  SET_StencilFunc(disp, glStencilFunc);
-  SET_StencilFuncSeparate(disp, glStencilFuncSeparate);
-  SET_StencilMask(disp, glStencilMask);
-  SET_StencilMaskSeparate(disp, glStencilMaskSeparate);
-  SET_StencilOp(disp, glStencilOp);
-  SET_StencilOpSeparate(disp, glStencilOpSeparate);
-  SET_TestFenceNV(disp, glTestFenceAPPLE); // <-- APPLE -> NV
-  SET_TexCoord1d(disp, glTexCoord1d);
-  SET_TexCoord1dv(disp, glTexCoord1dv);
-  SET_TexCoord1f(disp, glTexCoord1f);
-  SET_TexCoord1fv(disp, glTexCoord1fv);
-  SET_TexCoord1i(disp, glTexCoord1i);
-  SET_TexCoord1iv(disp, glTexCoord1iv);
-  SET_TexCoord1s(disp, glTexCoord1s);
-  SET_TexCoord1sv(disp, glTexCoord1sv);
-  SET_TexCoord2d(disp, glTexCoord2d);
-  SET_TexCoord2dv(disp, glTexCoord2dv);
-  SET_TexCoord2f(disp, glTexCoord2f);
-  SET_TexCoord2fv(disp, glTexCoord2fv);
-  SET_TexCoord2i(disp, glTexCoord2i);
-  SET_TexCoord2iv(disp, glTexCoord2iv);
-  SET_TexCoord2s(disp, glTexCoord2s);
-  SET_TexCoord2sv(disp, glTexCoord2sv);
-  SET_TexCoord3d(disp, glTexCoord3d);
-  SET_TexCoord3dv(disp, glTexCoord3dv);
-  SET_TexCoord3f(disp, glTexCoord3f);
-  SET_TexCoord3fv(disp, glTexCoord3fv);
-  SET_TexCoord3i(disp, glTexCoord3i);
-  SET_TexCoord3iv(disp, glTexCoord3iv);
-  SET_TexCoord3s(disp, glTexCoord3s);
-  SET_TexCoord3sv(disp, glTexCoord3sv);
-  SET_TexCoord4d(disp, glTexCoord4d);
-  SET_TexCoord4dv(disp, glTexCoord4dv);
-  SET_TexCoord4f(disp, glTexCoord4f);
-  SET_TexCoord4fv(disp, glTexCoord4fv);
-  SET_TexCoord4i(disp, glTexCoord4i);
-  SET_TexCoord4iv(disp, glTexCoord4iv);
-  SET_TexCoord4s(disp, glTexCoord4s);
-  SET_TexCoord4sv(disp, glTexCoord4sv);
-  SET_TexCoordPointer(disp, glTexCoordPointer);
-//SET_TexCoordPointerEXT(disp, glTexCoordPointerEXT);
-  SET_TexEnvf(disp, glTexEnvf);
-  SET_TexEnvfv(disp, glTexEnvfv);
-  SET_TexEnvi(disp, glTexEnvi);
-  SET_TexEnviv(disp, glTexEnviv);
-  SET_TexGend(disp, glTexGend);
-  SET_TexGendv(disp, glTexGendv);
-  SET_TexGenf(disp, glTexGenf);
-  SET_TexGenfv(disp, glTexGenfv);
-  SET_TexGeni(disp, glTexGeni);
-  SET_TexGeniv(disp, glTexGeniv);
-  SET_TexImage1D(disp, glTexImage1D);
-  SET_TexImage2D(disp, glTexImage2D);
-  SET_TexImage3D(disp, glTexImage3D);
-  SET_TexParameterf(disp, glTexParameterf);
-  SET_TexParameterfv(disp, glTexParameterfv);
-  SET_TexParameteri(disp, glTexParameteri);
-  SET_TexParameteriv(disp, glTexParameteriv);
-  SET_TexSubImage1D(disp, glTexSubImage1D);
-  SET_TexSubImage2D(disp, glTexSubImage2D);
-  SET_TexSubImage3D(disp, glTexSubImage3D);
-//SET_TrackMatrixNV(disp, glTrackMatrixNV);
-  SET_Translated(disp, glTranslated);
-  SET_Translatef(disp, glTranslatef);
-  SET_Uniform1fARB(disp, glUniform1fARB);
-  SET_Uniform1fvARB(disp, glUniform1fvARB);
-  SET_Uniform1iARB(disp, glUniform1iARB);
-  SET_Uniform1ivARB(disp, glUniform1ivARB);
-  SET_Uniform2fARB(disp, glUniform2fARB);
-  SET_Uniform2fvARB(disp, glUniform2fvARB);
-  SET_Uniform2iARB(disp, glUniform2iARB);
-  SET_Uniform2ivARB(disp, glUniform2ivARB);
-  SET_Uniform3fARB(disp, glUniform3fARB);
-  SET_Uniform3fvARB(disp, glUniform3fvARB);
-  SET_Uniform3iARB(disp, glUniform3iARB);
-  SET_Uniform3ivARB(disp, glUniform3ivARB);
-  SET_Uniform4fARB(disp, glUniform4fARB);
-  SET_Uniform4fvARB(disp, glUniform4fvARB);
-  SET_Uniform4iARB(disp, glUniform4iARB);
-  SET_Uniform4ivARB(disp, glUniform4ivARB);
-  SET_UniformMatrix2fvARB(disp, glUniformMatrix2fvARB);
-  SET_UniformMatrix3fvARB(disp, glUniformMatrix3fvARB);
-  SET_UniformMatrix4fvARB(disp, glUniformMatrix4fvARB);
-  SET_UnlockArraysEXT(disp, glUnlockArraysEXT);
-  SET_UnmapBufferARB(disp, glUnmapBufferARB);
-  SET_UseProgramObjectARB(disp, glUseProgramObjectARB);
-  SET_ValidateProgramARB(disp, glValidateProgramARB);
-  SET_Vertex2d(disp, glVertex2d);
-  SET_Vertex2dv(disp, glVertex2dv);
-  SET_Vertex2f(disp, glVertex2f);
-  SET_Vertex2fv(disp, glVertex2fv);
-  SET_Vertex2i(disp, glVertex2i);
-  SET_Vertex2iv(disp, glVertex2iv);
-  SET_Vertex2s(disp, glVertex2s);
-  SET_Vertex2sv(disp, glVertex2sv);
-  SET_Vertex3d(disp, glVertex3d);
-  SET_Vertex3dv(disp, glVertex3dv);
-  SET_Vertex3f(disp, glVertex3f);
-  SET_Vertex3fv(disp, glVertex3fv);
-  SET_Vertex3i(disp, glVertex3i);
-  SET_Vertex3iv(disp, glVertex3iv);
-  SET_Vertex3s(disp, glVertex3s);
-  SET_Vertex3sv(disp, glVertex3sv);
-  SET_Vertex4d(disp, glVertex4d);
-  SET_Vertex4dv(disp, glVertex4dv);
-  SET_Vertex4f(disp, glVertex4f);
-  SET_Vertex4fv(disp, glVertex4fv);
-  SET_Vertex4i(disp, glVertex4i);
-  SET_Vertex4iv(disp, glVertex4iv);
-  SET_Vertex4s(disp, glVertex4s);
-  SET_Vertex4sv(disp, glVertex4sv);
-//SET_VertexArrayRangeNV(disp, glVertexArrayRangeNV);
-  SET_VertexAttrib1dARB(disp, glVertexAttrib1dARB);
-  SET_VertexAttrib1dvARB(disp, glVertexAttrib1dvARB);
-  SET_VertexAttrib1fARB(disp, glVertexAttrib1fARB);
-  SET_VertexAttrib1fvARB(disp, glVertexAttrib1fvARB);
-  SET_VertexAttrib1sARB(disp, glVertexAttrib1sARB);
-  SET_VertexAttrib1svARB(disp, glVertexAttrib1svARB);
-  SET_VertexAttrib2dARB(disp, glVertexAttrib2dARB);
-  SET_VertexAttrib2dvARB(disp, glVertexAttrib2dvARB);
-  SET_VertexAttrib2fARB(disp, glVertexAttrib2fARB);
-  SET_VertexAttrib2fvARB(disp, glVertexAttrib2fvARB);
-  SET_VertexAttrib2sARB(disp, glVertexAttrib2sARB);
-  SET_VertexAttrib2svARB(disp, glVertexAttrib2svARB);
-  SET_VertexAttrib3dARB(disp, glVertexAttrib3dARB);
-  SET_VertexAttrib3dvARB(disp, glVertexAttrib3dvARB);
-  SET_VertexAttrib3fARB(disp, glVertexAttrib3fARB);
-  SET_VertexAttrib3fvARB(disp, glVertexAttrib3fvARB);
-  SET_VertexAttrib3sARB(disp, glVertexAttrib3sARB);
-  SET_VertexAttrib3svARB(disp, glVertexAttrib3svARB);
-  SET_VertexAttrib4NbvARB(disp, glVertexAttrib4NbvARB);
-  SET_VertexAttrib4NivARB(disp, glVertexAttrib4NivARB);
-  SET_VertexAttrib4NsvARB(disp, glVertexAttrib4NsvARB);
-  SET_VertexAttrib4NubARB(disp, glVertexAttrib4NubARB);
-  SET_VertexAttrib4NubvARB(disp, glVertexAttrib4NubvARB);
-  SET_VertexAttrib4NuivARB(disp, glVertexAttrib4NuivARB);
-  SET_VertexAttrib4NusvARB(disp, glVertexAttrib4NusvARB);
-  SET_VertexAttrib4bvARB(disp, glVertexAttrib4bvARB);
-  SET_VertexAttrib4dARB(disp, glVertexAttrib4dARB);
-  SET_VertexAttrib4dvARB(disp, glVertexAttrib4dvARB);
-  SET_VertexAttrib4fARB(disp, glVertexAttrib4fARB);
-  SET_VertexAttrib4fvARB(disp, glVertexAttrib4fvARB);
-  SET_VertexAttrib4ivARB(disp, glVertexAttrib4ivARB);
-  SET_VertexAttrib4sARB(disp, glVertexAttrib4sARB);
-  SET_VertexAttrib4svARB(disp, glVertexAttrib4svARB);
-  SET_VertexAttrib4ubvARB(disp, glVertexAttrib4ubvARB);
-  SET_VertexAttrib4uivARB(disp, glVertexAttrib4uivARB);
-  SET_VertexAttrib4usvARB(disp, glVertexAttrib4usvARB);
-  SET_VertexAttribPointerARB(disp, glVertexAttribPointerARB);
-  SET_VertexPointer(disp, glVertexPointer);
-//  SET_VertexPointerEXT(disp, glVertexPointerEXT);
-  SET_Viewport(disp, glViewport);
-  SET_WindowPos2dMESA(disp, glWindowPos2dARB);
-  SET_WindowPos2dvMESA(disp, glWindowPos2dvARB);
-  SET_WindowPos2fMESA(disp, glWindowPos2fARB);
-  SET_WindowPos2fvMESA(disp, glWindowPos2fvARB);
-  SET_WindowPos2iMESA(disp, glWindowPos2iARB);
-  SET_WindowPos2ivMESA(disp, glWindowPos2ivARB);
-  SET_WindowPos2sMESA(disp, glWindowPos2sARB);
-  SET_WindowPos2svMESA(disp, glWindowPos2svARB);
-  SET_WindowPos3dMESA(disp, glWindowPos3dARB);
-  SET_WindowPos3dvMESA(disp, glWindowPos3dvARB);
-  SET_WindowPos3fMESA(disp, glWindowPos3fARB);
-  SET_WindowPos3fvMESA(disp, glWindowPos3fvARB);
-  SET_WindowPos3iMESA(disp, glWindowPos3iARB);
-  SET_WindowPos3ivMESA(disp, glWindowPos3ivARB);
-  SET_WindowPos3sMESA(disp, glWindowPos3sARB);
-  SET_WindowPos3svMESA(disp, glWindowPos3svARB);
-//SET_WindowPos4dMESA(disp, glWindowPos4dMESA);
-//SET_WindowPos4dvMESA(disp, glWindowPos4dvMESA);
-//SET_WindowPos4fMESA(disp, glWindowPos4fMESA);
-//SET_WindowPos4fvMESA(disp, glWindowPos4fvMESA);
-//SET_WindowPos4iMESA(disp, glWindowPos4iMESA);
-//SET_WindowPos4ivMESA(disp, glWindowPos4ivMESA);
-//SET_WindowPos4sMESA(disp, glWindowPos4sMESA);
-//SET_WindowPos4svMESA(disp, glWindowPos4svMESA);
-}
diff --git a/configure.ac b/configure.ac
index 51ab4c6..b2a07a6 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1724,22 +1724,14 @@ if test "x$XQUARTZ" = xyes; then
 	AC_DEFINE(XQUARTZ,1,[Have Quartz])
 	AC_DEFINE(ROOTLESS,1,[Build Rootless code])
 
-#glxAGL / glxCGL don't work yet
-#	AC_CACHE_CHECK([for AGL framework],xorg_cv_AGL_framework,[
-#		save_LDFLAGS=$LDFLAGS
-#		LDFLAGS="$LDFLAGS -framework AGL"
-#		AC_LINK_IFELSE(
-#			[char aglEnable(); int main() { aglEnable(); return 0;}],
-#			[xorg_cv_AGL_framework=yes],
-#			[xorg_cv_AGL_framework=no])
-#		LDFLAGS=$save_LDFLAGS
-#	])
-	xorg_cv_AGL_framework=no
-	DARWIN_GLX_LIBS='$(top_builddir)/GL/apple/indirect.o $(top_builddir)/GL/glx/libglx.la'
-	DARWIN_LIBS="$MI_LIB $OS_LIB $DIX_LIB $FB_LIB $FIXES_LIB $XEXT_LIB $CONFIG_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB $DARWIN_GLX_LIBS"
+	DARWIN_GLX_LIBS='$(top_builddir)/hw/xquartz/GL/libCGLCore.la $(top_builddir)/GL/glx/libglx.la'
+	DARWIN_LIBS="$MI_LIB $OS_LIB $DIX_LIB $FB_LIB $FIXES_LIB $XEXT_LIB $CONFIG_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $XPSTUBS_LIB $DARWIN_GLX_LIBS"
 	AC_SUBST([DARWIN_LIBS])
+
 	AC_CHECK_LIB([Xplugin],[xp_init],[:])
+
 	CFLAGS="${CFLAGS} -DROOTLESS_WORKAROUND -DNO_ALLOCA"
+
 	if test "x$XF86MISC" = xyes || test "x$XF86MISC" = xauto; then
 		AC_MSG_NOTICE([Disabling XF86Misc extension])
 		XF86MISC=no
@@ -2087,7 +2079,6 @@ XORG_MANPAGE_SECTIONS
 AC_OUTPUT([
 Makefile
 GL/Makefile
-GL/apple/Makefile
 GL/glx/Makefile
 include/Makefile
 afb/Makefile
@@ -2181,6 +2172,7 @@ hw/xgl/glxext/module/Makefile
 hw/xnest/Makefile
 hw/xwin/Makefile
 hw/xquartz/Makefile
+hw/xquartz/GL/Makefile
 hw/xquartz/bundle/Makefile
 hw/xquartz/xpr/Makefile
 hw/kdrive/Makefile
diff --git a/hw/xquartz/GL/Makefile.am b/hw/xquartz/GL/Makefile.am
new file mode 100644
index 0000000..41d4566
--- /dev/null
+++ b/hw/xquartz/GL/Makefile.am
@@ -0,0 +1,13 @@
+noinst_LTLIBRARIES = libCGLCore.la
+AM_CFLAGS = $(XSERVER_CFLAGS) $(DIX_CFLAGS)
+AM_CPPFLAGS = \
+	-I$(top_srcdir) \
+	-I$(top_srcdir)/GL/glx \
+	-I$(top_srcdir)/GL/include \
+	-I$(top_srcdir)/GL/mesa/glapi \
+	-I$(top_srcdir)/hw/xquartz \
+	-I$(top_srcdir)/hw/xquartz/xpr \
+	-I$(top_srcdir)/miext/damage
+
+libCGLCore_la_SOURCES = \
+	indirect.c
diff --git a/hw/xquartz/GL/indirect.c b/hw/xquartz/GL/indirect.c
new file mode 100644
index 0000000..a0884d4
--- /dev/null
+++ b/hw/xquartz/GL/indirect.c
@@ -0,0 +1,1940 @@
+/*
+ * GLX implementation that uses Apple's OpenGL.framework
+ * (Indirect rendering path)
+ *
+ * Copyright (c) 2007 Apple Inc.
+ * Copyright (c) 2004 Torrey T. Lyons. All Rights Reserved.
+ * Copyright (c) 2002 Greg Parker. All Rights Reserved.
+ *
+ * Portions of this file are copied from Mesa's xf86glx.c,
+ * which contains the following copyright:
+ *
+ * Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
+ * All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include "dri.h"
+
+#define GL_EXT_histogram 1
+#define GL_EXT_polygon_offset 1
+#define GL_SGIS_pixel_texture 1
+#define GL_SGIX_pixel_texture 1
+#define GL_EXT_multisample 1
+#define GL_SGIS_multisample 1
+#define GL_EXT_vertex_array 1
+#define GL_ARB_point_parameters 1
+#define GL_NV_vertex_array_range 1
+#define GL_MESA_resize_buffers 1
+#define GL_ARB_window_pos 1
+#define GL_EXT_cull_vertex 1
+#define GL_NV_vertex_program 1
+#define GL_APPLE_fence 1
+#define GL_IBM_multimode_draw_arrays 1
+#define GL_EXT_fragment_shader 1
+
+#include <OpenGL/OpenGL.h>
+#include <OpenGL/CGLContext.h>
+
+// X11 and X11's glx
+#include <GL/gl.h>
+#include <GL/glxproto.h>
+#include <windowstr.h>
+#include <resource.h>
+#include <GL/glxint.h>
+#include <GL/glxtokens.h>
+#include <scrnintstr.h>
+#include <glxserver.h>
+#include <glxscreens.h>
+#include <glxdrawable.h>
+#include <glxcontext.h>
+#include <glxext.h>
+#include <glxutil.h>
+#include <glxscreens.h>
+#include <GL/internal/glcore.h>
+#include "x-hash.h"
+#include "x-list.h"
+
+#include <dispatch.h>
+#define GLAPIENTRYP *
+typedef unsigned long long GLuint64EXT;
+typedef long long GLint64EXT;
+#include <Xplugin.h>
+#include "glcontextmodes.h"
+#include <glapi.h>
+#include <glapitable.h>
+
+// ggs: needed to call back to glx with visual configs
+extern void GlxSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs, void **configprivs);
+__GLXprovider * GlxGetMesaProvider (void);
+
+// Write debugging output, or not
+#ifdef GLAQUA_DEBUG
+#define GLAQUA_DEBUG_MSG ErrorF
+#else
+#define GLAQUA_DEBUG_MSG(a, ...)
+#endif
+
+static void setup_dispatch_table(void);
+GLuint __glFloorLog2(GLuint val);
+void warn_func(void * p1, char *format, ...);
+
+// some prototypes
+static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen);
+static __GLXdrawable * __glXAquaScreenCreateDrawable(__GLXscreen *screen, DrawablePtr pDraw, XID drawId, __GLXconfig *modes);
+
+static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
+                              int *nvisualp, int *ndepthp,
+                              int *rootDepthp, VisualID *defaultVisp,
+                              unsigned long sizes, int bitsPerRGB);
+static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
+                                   void **privates);
+
+static void glAquaResetExtension(void);
+static void __glXAquaContextDestroy(__GLXcontext *baseContext);
+static int __glXAquaContextMakeCurrent(__GLXcontext *baseContext);
+static int __glXAquaContextLoseCurrent(__GLXcontext *baseContext);
+static int __glXAquaContextForceCurrent(__GLXcontext *baseContext);
+static int __glXAquaContextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, unsigned long mask);
+
+static CGLPixelFormatObj makeFormat(__GLXconfig *mode);
+
+__GLXprovider __glXMesaProvider = {
+  __glXAquaScreenProbe,
+  "Core OpenGL",
+    NULL
+};
+
+__GLXprovider *
+GlxGetMesaProvider (void)
+{
+  GLAQUA_DEBUG_MSG("GlxGetMesaProvider\n");
+  return &__glXMesaProvider;
+}
+
+typedef struct __GLXAquaScreen   __GLXAquaScreen;
+typedef struct __GLXAquaContext  __GLXAquaContext;
+typedef struct __GLXAquaDrawable __GLXAquaDrawable;
+
+struct __GLXAquaScreen {
+  __GLXscreen   base;
+  int           index;
+    int num_vis;
+    __GLXconfig *modes;
+};
+
+static __GLXAquaScreen glAquaScreens[MAXSCREENS];
+
+struct __GLXAquaContext {
+  __GLXcontext base;
+  CGLContextObj ctx;
+  CGLPixelFormatObj pixelFormat;
+  xp_surface_id sid;
+  unsigned isAttached :1;
+};
+
+struct __GLXAquaDrawable {
+  __GLXdrawable base;
+    DrawablePtr pDraw;
+    xp_surface_id sid;
+};
+
+static __GLXcontext *
+__glXAquaScreenCreateContext(__GLXscreen *screen,
+			     __GLXconfig *config,
+			     __GLXcontext *baseShareContext)
+{
+  __GLXAquaContext *context;
+  __GLXAquaContext *shareContext = (__GLXAquaContext *) baseShareContext;
+  CGLError gl_err;
+  
+  GLAQUA_DEBUG_MSG("glXAquaScreenCreateContext\n");
+
+  context = malloc (sizeof (__GLXAquaContext));
+  if (context == NULL) return NULL;
+
+  memset(context, 0, sizeof *context);
+
+  context->base.pGlxScreen = screen;
+  context->base.config      = config;
+
+  context->base.destroy        = __glXAquaContextDestroy;
+  context->base.makeCurrent    = __glXAquaContextMakeCurrent;
+  context->base.loseCurrent    = __glXAquaContextLoseCurrent;
+  context->base.copy           = __glXAquaContextCopy;
+  context->base.forceCurrent   = __glXAquaContextForceCurrent;
+  //  context->base.createDrawable = __glXAquaContextCreateDrawable;
+
+  context->pixelFormat = makeFormat(config);
+  if (!context->pixelFormat) {
+        free(context);
+        return NULL;
+  }
+
+  context->ctx = NULL;
+  gl_err = CGLCreateContext(context->pixelFormat,
+                            shareContext ? shareContext->ctx : NULL,
+                            &context->ctx);
+
+  if (gl_err != 0) {
+      ErrorF("CGLCreateContext error: %s\n", CGLErrorString(gl_err));
+      CGLDestroyPixelFormat(context->pixelFormat);
+      free(context);
+      return NULL;
+    }
+	setup_dispatch_table();
+    GLAQUA_DEBUG_MSG("glAquaCreateContext done\n");
+  return &context->base;
+}
+
+static __GLXextensionInfo __glDDXExtensionInfo = {
+    GL_CORE_APPLE,
+    glAquaResetExtension,
+    glAquaInitVisuals,
+    glAquaSetVisualConfigs
+};
+
+void *__glXglDDXExtensionInfo(void) {
+  GLAQUA_DEBUG_MSG("glXAglDDXExtensionInfo\n");
+    return &__glDDXExtensionInfo;
+}
+
+/* maps from surface id -> list of __GLcontext */
+static x_hash_table *surface_hash;
+
+static void __glXAquaContextDestroy(__GLXcontext *baseContext) {
+    x_list *lst;
+
+    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
+
+    GLAQUA_DEBUG_MSG("glAquaContextDestroy (ctx 0x%x)\n",
+                     (unsigned int) baseContext);
+    if (context != NULL) {
+      if (context->sid != 0 && surface_hash != NULL) {
+		lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
+		lst = x_list_remove(lst, context);
+		x_hash_table_insert(surface_hash, (void *) context->sid, lst);
+      }
+
+      if (context->ctx != NULL) CGLDestroyContext(context->ctx);
+
+      if (context->pixelFormat != NULL)	CGLDestroyPixelFormat(context->pixelFormat);
+      
+      free(context);
+    }
+}
+
+static int __glXAquaContextLoseCurrent(__GLXcontext *baseContext) {
+    CGLError gl_err;
+
+    GLAQUA_DEBUG_MSG("glAquaLoseCurrent (ctx 0x%p)\n", baseContext);
+
+    gl_err = CGLSetCurrentContext(NULL);
+    if (gl_err != 0)
+      ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
+
+    __glXLastContext = NULL; // Mesa does this; why?
+
+    return GL_TRUE;
+}
+
+/* Called when a surface is destroyed as a side effect of destroying
+   the window it's attached to. */
+static void surface_notify(void *_arg, void *data) {
+    DRISurfaceNotifyArg *arg = (DRISurfaceNotifyArg *)_arg;
+    __GLXAquaDrawable *draw = (__GLXAquaDrawable *)data;
+    __GLXAquaContext *context;
+    x_list *lst;
+	if(_arg == NULL || data == NULL) {
+		ErrorF("surface_notify called with bad params");
+		return;
+	}
+	
+    GLAQUA_DEBUG_MSG("surface_notify(%p, %p)\n", _arg, data);
+    switch (arg->kind) {
+    case AppleDRISurfaceNotifyDestroyed:
+        if (surface_hash != NULL)
+            x_hash_table_remove(surface_hash, (void *) arg->id);
+	        draw->base.pDraw = NULL;
+			draw->sid = 0;
+        break;
+
+    case AppleDRISurfaceNotifyChanged:
+        if (surface_hash != NULL) {
+            lst = x_hash_table_lookup(surface_hash, (void *) arg->id, NULL);
+            for (; lst != NULL; lst = lst->next)
+            {
+                context = lst->data;
+                xp_update_gl_context(context->ctx);
+            }
+        }
+        break;
+	default:
+		ErrorF("surface_notify: unknown kind %d\n", arg->kind);
+		break;
+    }
+}
+
+static void attach(__GLXAquaContext *context, __GLXAquaDrawable *draw) {
+    DrawablePtr pDraw;
+	GLAQUA_DEBUG_MSG("attach(%p, %p)\n", context, draw);
+    pDraw = draw->base.pDraw;
+
+    if (draw->sid == 0) {
+//        if (!quartzProcs->CreateSurface(pDraw->pScreen, pDraw->id, pDraw,
+        if (!DRICreateSurface(pDraw->pScreen, pDraw->id, pDraw,
+                                        0, &draw->sid, NULL,
+                                        surface_notify, draw))
+            return;
+        draw->pDraw = pDraw;
+	} 
+
+    if (!context->isAttached || context->sid != draw->sid) {
+        x_list *lst;
+
+        if (xp_attach_gl_context(context->ctx, draw->sid) != Success) {
+//            quartzProcs->DestroySurface(pDraw->pScreen, pDraw->id, pDraw,
+            DRIDestroySurface(pDraw->pScreen, pDraw->id, pDraw,
+								surface_notify, draw);
+            if (surface_hash != NULL)
+                x_hash_table_remove(surface_hash, (void *) draw->sid);
+
+            draw->sid = 0;
+            return;
+        }
+
+        context->isAttached = TRUE;
+        context->sid = draw->sid;
+
+        if (surface_hash == NULL)
+            surface_hash = x_hash_table_new(NULL, NULL, NULL, NULL);
+
+        lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
+        if (x_list_find(lst, context) == NULL) {
+            lst = x_list_prepend(lst, context);
+            x_hash_table_insert(surface_hash, (void *) context->sid, lst);
+        }
+
+        GLAQUA_DEBUG_MSG("attached 0x%x to 0x%x\n", (unsigned int) pDraw->id,
+                         (unsigned int) draw->sid);
+    } 
+}
+
+#if 0     // unused
+static void unattach(__GLXAquaContext *context) {
+	x_list *lst;
+	GLAQUA_DEBUG_MSG("unattach\n");
+	if (context == NULL) {
+		ErrorF("Tried to unattach a null context\n");
+		return;
+	}
+    if (context->isAttached) {
+        GLAQUA_DEBUG_MSG("unattaching\n");
+
+        if (surface_hash != NULL) {
+            lst = x_hash_table_lookup(surface_hash, (void *) context->sid, NULL);
+            lst = x_list_remove(lst, context);
+            x_hash_table_insert(surface_hash, (void *) context->sid, lst);
+        }
+
+        CGLClearDrawable(context->ctx);
+        context->isAttached = FALSE;
+        context->sid = 0;
+    }
+}
+#endif
+
+static int __glXAquaContextMakeCurrent(__GLXcontext *baseContext) {
+    CGLError gl_err;
+    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
+	__GLXAquaDrawable *drawPriv = (__GLXAquaDrawable *) context->base.drawPriv;
+
+    GLAQUA_DEBUG_MSG("glAquaMakeCurrent (ctx 0x%p)\n", baseContext);
+    
+    attach(context, drawPriv);
+
+    gl_err = CGLSetCurrentContext(context->ctx);
+    if (gl_err != 0)
+        ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
+    
+    return gl_err == 0;
+}
+
+static int __glXAquaContextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, unsigned long mask)
+{
+    CGLError gl_err;
+
+    __GLXAquaContext *dst = (__GLXAquaContext *) baseDst;
+    __GLXAquaContext *src = (__GLXAquaContext *) baseSrc;
+
+    GLAQUA_DEBUG_MSG("GLXAquaContextCopy\n");
+
+    gl_err = CGLCopyContext(src->ctx, dst->ctx, mask);
+    if (gl_err != 0)
+        ErrorF("CGLCopyContext error: %s\n", CGLErrorString(gl_err));
+
+    return gl_err == 0;
+}
+
+static int __glXAquaContextForceCurrent(__GLXcontext *baseContext)
+{
+    CGLError gl_err;
+    __GLXAquaContext *context = (__GLXAquaContext *) baseContext;
+    GLAQUA_DEBUG_MSG("glAquaForceCurrent (ctx %p)\n", context->ctx);
+
+    gl_err = CGLSetCurrentContext(context->ctx);
+    if (gl_err != 0)
+        ErrorF("CGLSetCurrentContext error: %s\n", CGLErrorString(gl_err));
+
+    return gl_err == 0;
+}
+
+/* Drawing surface notification callbacks */
+
+static GLboolean __glXAquaDrawableResize(__GLXdrawable *base)  {
+    GLAQUA_DEBUG_MSG("unimplemented glAquaDrawableResize\n");
+    return GL_TRUE;
+}
+
+static GLboolean __glXAquaDrawableSwapBuffers(__GLXdrawable *base) {
+    CGLError gl_err;
+	__GLXAquaContext * drawableCtx;
+//    GLAQUA_DEBUG_MSG("glAquaDrawableSwapBuffers(%p)\n",base);
+	
+	if(!base) {
+		ErrorF("glXAquaDrawbleSwapBuffers passed NULL\n");
+	    return GL_FALSE;
+	}
+
+    drawableCtx = (__GLXAquaContext *)base->drawGlxc;
+
+    if (drawableCtx != NULL && drawableCtx->ctx != NULL) {
+        gl_err = CGLFlushDrawable(drawableCtx->ctx);
+        if (gl_err != 0)
+            ErrorF("CGLFlushDrawable error: %s\n", CGLErrorString(gl_err));
+    }
+    return GL_TRUE;
+}
+
+static CGLPixelFormatObj makeFormat(__GLXconfig *config) {
+    int i;
+    CGLPixelFormatAttribute attr[64]; // currently uses max of 30
+    CGLPixelFormatObj result;
+    GLint n_formats;
+    CGLError gl_err;
+    
+    GLAQUA_DEBUG_MSG("makeFormat\n");
+
+    if (!config->rgbMode)
+        return NULL;
+
+    i = 0;
+
+    // attr [i++] = kCGLPFAAcelerated; // require hwaccel - BAD for multiscreen
+    // attr [i++] = kCGLPFANoRecovery; // disable fallback renderers - BAD
+
+    if (config->stereoMode) {
+        attr[i++] = kCGLPFAStereo;
+    }
+
+    if (config->doubleBufferMode) {
+        attr[i++] = kCGLPFADoubleBuffer;
+    }
+
+    if (config->colorIndexMode) {
+        /* ignored */
+    }
+
+    if (config->rgbMode) {
+        attr[i++] = kCGLPFAColorSize;
+        attr[i++] = config->redBits + config->greenBits + config->blueBits;
+        attr[i++] = kCGLPFAAlphaSize;
+        attr[i++] = 1; /* FIXME: ignoring config->alphaBits which is always 0 */
+    }
+
+    if (config->haveAccumBuffer) {
+        attr[i++] = kCGLPFAAccumSize;
+        attr[i++] = config->accumRedBits + config->accumGreenBits
+                    + config->accumBlueBits + config->accumAlphaBits;
+    }
+	
+    if (config->haveDepthBuffer) {
+        attr[i++] = kCGLPFADepthSize;
+        attr[i++] = config->depthBits;
+    }
+	
+    if (config->haveStencilBuffer) {
+        attr[i++] = kCGLPFAStencilSize;
+        attr[i++] = config->stencilBits;
+    }
+
+    attr[i++] = kCGLPFAAuxBuffers;
+    attr[i++] = config->numAuxBuffers;
+
+    /* mode->level ignored */
+
+    /* mode->pixmapMode ? */
+
+    attr[i++] = 0;
+
+    GLAQUA_DEBUG_MSG("makeFormat almost done\n");
+
+    result = NULL;
+    gl_err = CGLChoosePixelFormat(attr, &result, &n_formats);
+    if (gl_err != 0)
+        ErrorF("CGLChoosePixelFormat error: %s\n", CGLErrorString(gl_err));
+
+    GLAQUA_DEBUG_MSG("makeFormat done (0x%x)\n", (unsigned int) result);
+
+    return result;
+}
+
+// Originally copied from Mesa
+
+static int                 numConfigs     = 0;
+static __GLXvisualConfig  *visualConfigs  = NULL;
+static void              **visualPrivates = NULL;
+
+/*
+ * In the case the driver defines no GLX visuals we'll use these.
+ * Note that for TrueColor and DirectColor visuals, bufferSize is the 
+ * sum of redSize, greenSize, blueSize and alphaSize, which may be larger 
+ * than the nplanes/rootDepth of the server's X11 visuals
+ */
+#define NUM_FALLBACK_CONFIGS 5
+static __GLXvisualConfig FallbackConfigs[NUM_FALLBACK_CONFIGS] = {
+  /* [0] = RGB, double buffered, Z */
+  {
+    -1,                 /* vid */
+    -1,                 /* class */
+    True,               /* rgba */
+    -1, -1, -1, 0,      /* rgba sizes */
+    -1, -1, -1, 0,      /* rgba masks */
+     0,  0,  0, 0,      /* rgba accum sizes */
+    True,               /* doubleBuffer */
+    False,              /* stereo */
+    -1,                 /* bufferSize */
+    16,                 /* depthSize */
+    0,                  /* stencilSize */
+    0,                  /* auxBuffers */
+    0,                  /* level */
+    GLX_NONE,           /* visualRating */
+    GLX_NONE,           /* transparentPixel */
+    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
+    0                   /* transparentIndex */
+  },
+  /* [1] = RGB, double buffered, Z, stencil, accum */
+  {
+    -1,                 /* vid */
+    -1,                 /* class */
+    True,               /* rgba */
+    -1, -1, -1, 0,      /* rgba sizes */
+    -1, -1, -1, 0,      /* rgba masks */
+    16, 16, 16, 0,      /* rgba accum sizes */
+    True,               /* doubleBuffer */
+    False,              /* stereo */
+    -1,                 /* bufferSize */
+    16,                 /* depthSize */
+    8,                  /* stencilSize */
+    0,                  /* auxBuffers */
+    0,                  /* level */
+    GLX_NONE,           /* visualRating */
+    GLX_NONE,           /* transparentPixel */
+    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
+    0                   /* transparentIndex */
+  },
+  /* [2] = RGB+Alpha, double buffered, Z, stencil, accum */
+  {
+    -1,                 /* vid */
+    -1,                 /* class */
+    True,               /* rgba */
+    -1, -1, -1, 8,      /* rgba sizes */
+    -1, -1, -1, -1,     /* rgba masks */
+    16, 16, 16, 16,     /* rgba accum sizes */
+    True,               /* doubleBuffer */
+    False,              /* stereo */
+    -1,                 /* bufferSize */
+    16,                 /* depthSize */
+    8,                  /* stencilSize */
+    0,                  /* auxBuffers */
+    0,                  /* level */
+    GLX_NONE,           /* visualRating */
+    GLX_NONE,           /* transparentPixel */
+    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
+    0                   /* transparentIndex */
+  },
+  /* [3] = RGB+Alpha, single buffered, Z, stencil, accum */
+  {
+    -1,                 /* vid */
+    -1,                 /* class */
+    True,               /* rgba */
+    -1, -1, -1, 8,      /* rgba sizes */
+    -1, -1, -1, -1,     /* rgba masks */
+    16, 16, 16, 16,     /* rgba accum sizes */
+    False,              /* doubleBuffer */
+    False,              /* stereo */
+    -1,                 /* bufferSize */
+    16,                 /* depthSize */
+    8,                  /* stencilSize */
+    0,                  /* auxBuffers */
+    0,                  /* level */
+    GLX_NONE,           /* visualRating */
+    GLX_NONE,           /* transparentPixel */
+    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
+    0                   /* transparentIndex */
+  },
+  /* [4] = CI, double buffered, Z */
+  {
+    -1,                 /* vid */
+    -1,                 /* class */
+    False,              /* rgba? (false = color index) */
+    -1, -1, -1, 0,      /* rgba sizes */
+    -1, -1, -1, 0,      /* rgba masks */
+     0,  0,  0, 0,      /* rgba accum sizes */
+    True,               /* doubleBuffer */
+    False,              /* stereo */
+    -1,                 /* bufferSize */
+    16,                 /* depthSize */
+    0,                  /* stencilSize */
+    0,                  /* auxBuffers */
+    0,                  /* level */
+    GLX_NONE,           /* visualRating */
+    GLX_NONE,           /* transparentPixel */
+    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
+    0                   /* transparentIndex */
+  },
+};
+
+static __GLXvisualConfig NullConfig = {
+    -1,                 /* vid */
+    -1,                 /* class */
+    False,              /* rgba */
+    -1, -1, -1, 0,      /* rgba sizes */
+    -1, -1, -1, 0,      /* rgba masks */
+     0,  0,  0, 0,      /* rgba accum sizes */
+    False,              /* doubleBuffer */
+    False,              /* stereo */
+    -1,                 /* bufferSize */
+    16,                 /* depthSize */
+    0,                  /* stencilSize */
+    0,                  /* auxBuffers */
+    0,                  /* level */
+    GLX_NONE_EXT,       /* visualRating */
+    0,                  /* transparentPixel */
+    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
+    0                   /* transparentIndex */
+};
+
+
+static inline int count_bits(uint32_t x)
+{
+    x = x - ((x >> 1) & 0x55555555);
+    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
+    x = (x + (x >> 4)) & 0x0f0f0f0f;
+    x = x + (x >> 8);
+    x = x + (x >> 16);
+    return x & 63;
+}
+
+
+static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
+                         VisualID *defaultVisp,
+                         int ndepth, DepthPtr pdepth,
+                         int rootDepth)
+{
+    int numRGBconfigs;
+    int numCIconfigs;
+    int numVisuals = *nvisualp;
+    int numNewVisuals;
+    int numNewConfigs;
+    VisualPtr pVisual = *visualp;
+    VisualPtr pVisualNew = NULL;
+    VisualID *orig_vid = NULL;
+    __GLXconfig *modes;
+    __GLXvisualConfig *pNewVisualConfigs = NULL;
+    void **glXVisualPriv;
+    void **pNewVisualPriv;
+    int found_default;
+    int i, j, k;
+
+    GLAQUA_DEBUG_MSG("init_visuals\n");
+
+    if (numConfigs > 0)
+        numNewConfigs = numConfigs;
+    else
+        numNewConfigs = NUM_FALLBACK_CONFIGS;
+
+    /* Alloc space for the list of new GLX visuals */
+    pNewVisualConfigs = (__GLXvisualConfig *)
+                     malloc(numNewConfigs * sizeof(__GLXvisualConfig));
+    if (!pNewVisualConfigs) {
+        return FALSE;
+    }
+
+    /* Alloc space for the list of new GLX visual privates */
+    pNewVisualPriv = (void **) malloc(numNewConfigs * sizeof(void *));
+    if (!pNewVisualPriv) {
+        free(pNewVisualConfigs);
+        return FALSE;
+    }
+
+    /*
+    ** If SetVisualConfigs was not called, then use default GLX
+    ** visual configs.
+    */
+    if (numConfigs == 0) {
+        memcpy(pNewVisualConfigs, FallbackConfigs,
+               NUM_FALLBACK_CONFIGS * sizeof(__GLXvisualConfig));
+        memset(pNewVisualPriv, 0, NUM_FALLBACK_CONFIGS * sizeof(void *));
+    }
+    else {
+        /* copy driver's visual config info */
+        for (i = 0; i < numConfigs; i++) {
+            pNewVisualConfigs[i] = visualConfigs[i];
+            pNewVisualPriv[i] = visualPrivates[i];
+        }
+    }
+
+    /* Count the number of RGB and CI visual configs */
+    numRGBconfigs = 0;
+    numCIconfigs = 0;
+    for (i = 0; i < numNewConfigs; i++) {
+        if (pNewVisualConfigs[i].rgba)
+            numRGBconfigs++;
+        else
+            numCIconfigs++;
+    }
+
+    /* Count the total number of visuals to compute */
+    numNewVisuals = 0;
+    for (i = 0; i < numVisuals; i++) {
+        int count;
+
+        count = ((pVisual[i].class == TrueColor ||
+                  pVisual[i].class == DirectColor)
+                ? numRGBconfigs : numCIconfigs);
+        if (count == 0)
+            count = 1;          /* preserve the existing visual */
+
+        numNewVisuals += count;
+    }
+
+    /* Reset variables for use with the next screen/driver's visual configs */
+    visualConfigs = NULL;
+    numConfigs = 0;
+
+    /* Alloc temp space for the list of orig VisualIDs for each new visual */
+    orig_vid = (VisualID *)malloc(numNewVisuals * sizeof(VisualID));
+    if (!orig_vid) {
+        free(pNewVisualPriv);
+        free(pNewVisualConfigs);
+        return FALSE;
+    }
+
+    /* Alloc space for the list of glXVisuals */
+    modes = _gl_context_modes_create(numNewVisuals, sizeof(__GLXconfig));
+    if (modes == NULL) {
+        free(orig_vid);
+        free(pNewVisualPriv);
+        free(pNewVisualConfigs);
+        return FALSE;
+    }
+
+    /* Alloc space for the list of glXVisualPrivates */
+    glXVisualPriv = (void **)malloc(numNewVisuals * sizeof(void *));
+    if (!glXVisualPriv) {
+        _gl_context_modes_destroy( modes );
+        free(orig_vid);
+        free(pNewVisualPriv);
+        free(pNewVisualConfigs);
+        return FALSE;
+    }
+
+    /* Alloc space for the new list of the X server's visuals */
+    pVisualNew = (VisualPtr)malloc(numNewVisuals * sizeof(VisualRec));
+    if (!pVisualNew) {
+        free(glXVisualPriv);
+        _gl_context_modes_destroy( modes );
+        free(orig_vid);
+        free(pNewVisualPriv);
+        free(pNewVisualConfigs);
+        return FALSE;
+    }
+
+    /* Initialize the new visuals */
+    found_default = FALSE;
+    glAquaScreens[screenInfo.numScreens-1].modes = modes;
+    for (i = j = 0; i < numVisuals; i++) {
+        int is_rgb = (pVisual[i].class == TrueColor ||
+                      pVisual[i].class == DirectColor);
+
+        if (!is_rgb)
+        {
+            /* We don't support non-rgb visuals for GL. But we don't
+               want to remove them either, so just pass them through
+               with null glX configs */
+
+            pVisualNew[j] = pVisual[i];
+            pVisualNew[j].vid = FakeClientID(0);
+
+            /* Check for the default visual */
+            if (!found_default && pVisual[i].vid == *defaultVisp) {
+                *defaultVisp = pVisualNew[j].vid;
+                found_default = TRUE;
+            }
+
+            /* Save the old VisualID */
+            orig_vid[j] = pVisual[i].vid;
+
+            /* Initialize the glXVisual */
+            _gl_copy_visual_to_context_mode( modes, & NullConfig );
+            modes->visualID = pVisualNew[j].vid;
+
+            j++;
+
+            continue;
+        }
+
+        for (k = 0; k < numNewConfigs; k++) {
+            if (pNewVisualConfigs[k].rgba != is_rgb)
+                continue;
+
+            assert( modes != NULL );
+
+            /* Initialize the new visual */
+            pVisualNew[j] = pVisual[i];
+            pVisualNew[j].vid = FakeClientID(0);
+
+            /* Check for the default visual */
+            if (!found_default && pVisual[i].vid == *defaultVisp) {
+                *defaultVisp = pVisualNew[j].vid;
+                found_default = TRUE;
+            }
+
+            /* Save the old VisualID */
+            orig_vid[j] = pVisual[i].vid;
+
+            /* Initialize the glXVisual */
+            _gl_copy_visual_to_context_mode( modes, & pNewVisualConfigs[k] );
+            modes->visualID = pVisualNew[j].vid;
+
+            /*
+             * If the class is -1, then assume the X visual information
+             * is identical to what GLX needs, and take them from the X
+             * visual.  NOTE: if class != -1, then all other fields MUST
+             * be initialized.
+             */
+            if (modes->visualType == GLX_NONE) {
+                modes->visualType = _gl_convert_from_x_visual_type( pVisual[i].class );
+                modes->redBits    = count_bits(pVisual[i].redMask);
+                modes->greenBits  = count_bits(pVisual[i].greenMask);
+                modes->blueBits   = count_bits(pVisual[i].blueMask);
+                modes->alphaBits  = modes->alphaBits;
+                modes->redMask    = pVisual[i].redMask;
+                modes->greenMask  = pVisual[i].greenMask;
+                modes->blueMask   = pVisual[i].blueMask;
+                modes->alphaMask  = modes->alphaMask;
+                modes->rgbBits = (is_rgb)
+                    ? (modes->redBits + modes->greenBits +
+                       modes->blueBits + modes->alphaBits)
+                    : rootDepth;
+            }
+
+            /* Save the device-dependent private for this visual */
+            glXVisualPriv[j] = pNewVisualPriv[k];
+
+            j++;
+            modes = modes->next;
+        }
+    }
+
+    assert(j <= numNewVisuals);
+
+    /* Save the GLX visuals in the screen structure */
+    glAquaScreens[screenInfo.numScreens-1].num_vis = numNewVisuals;
+    //    glAquaScreens[screenInfo.numScreens-1].priv = glXVisualPriv;
+
+    /* set up depth's VisualIDs */
+    for (i = 0; i < ndepth; i++) {
+        int numVids = 0;
+        VisualID *pVids = NULL;
+        int k, n = 0;
+
+        /* Count the new number of VisualIDs at this depth */
+        for (j = 0; j < pdepth[i].numVids; j++)
+            for (k = 0; k < numNewVisuals; k++)
+            if (pdepth[i].vids[j] == orig_vid[k])
+                numVids++;
+
+        /* Allocate a new list of VisualIDs for this depth */
+        pVids = (VisualID *)malloc(numVids * sizeof(VisualID));
+
+        /* Initialize the new list of VisualIDs for this depth */
+        for (j = 0; j < pdepth[i].numVids; j++)
+            for (k = 0; k < numNewVisuals; k++)
+            if (pdepth[i].vids[j] == orig_vid[k])
+                pVids[n++] = pVisualNew[k].vid;
+
+        /* Update this depth's list of VisualIDs */
+        free(pdepth[i].vids);
+        pdepth[i].vids = pVids;
+        pdepth[i].numVids = numVids;
+    }
+
+    /* Update the X server's visuals */
+    *nvisualp = numNewVisuals;
+    *visualp = pVisualNew;
+
+    /* Free the old list of the X server's visuals */
+    free(pVisual);
+
+    /* Clean up temporary allocations */
+    free(orig_vid);
+    free(pNewVisualPriv);
+    free(pNewVisualConfigs);
+
+    /* Free the private list created by DDX HW driver */
+    if (visualPrivates)
+        free(visualPrivates);
+    visualPrivates = NULL;
+
+    return TRUE;
+}
+
+Bool enable_stereo = FALSE;
+/* based on code in i830_dri.c
+   This ends calling glAquaSetVisualConfigs to set the static
+   numconfigs, etc. */
+// see also glxglcore.c -- bhb
+static void
+glAquaInitVisualConfigs(void)
+{
+    int                 lclNumConfigs     = 0;
+    __GLXvisualConfig  *lclVisualConfigs  = NULL;
+    void              **lclVisualPrivates = NULL;
+
+    int stereo, depth, aux, buffers, stencil, accum;
+    int i = 0;
+
+    GLAQUA_DEBUG_MSG("glAquaInitVisualConfigs ");
+        
+    /* count num configs:
+        2 stereo (on, off) (optional)
+        2 Z buffer (0, 24 bit)
+        2 AUX buffer (0, 2)
+        2 buffers (single, double)
+        2 stencil (0, 8 bit)
+        2 accum (0, 64 bit)
+        = 64 configs with stereo, or 32 without */
+
+    if (enable_stereo) lclNumConfigs = 2 * 2 * 2 * 2 * 2 * 2; /* 64 */
+    else               lclNumConfigs = 2 * 2 * 2 * 2 * 2; /* 32 */
+
+    /* alloc */
+    lclVisualConfigs = xcalloc(sizeof(__GLXvisualConfig), lclNumConfigs);
+    lclVisualPrivates = xcalloc(sizeof(void *), lclNumConfigs);
+
+    /* fill in configs */
+    if (NULL != lclVisualConfigs) {
+        i = 0; /* current buffer */
+        for (stereo = 0; stereo < (enable_stereo ? 2 : 1); stereo++) {
+	  for (depth = 0; depth < 2; depth++) {
+            for (aux = 0; aux < 2; aux++) {
+	      for (buffers = 0; buffers < 2; buffers++) {
+		for (stencil = 0; stencil < 2; stencil++) {
+		  for (accum = 0; accum < 2; accum++) {
+		    lclVisualConfigs[i].vid = -1;
+		    lclVisualConfigs[i].class = -1;
+		    lclVisualConfigs[i].rgba = TRUE;
+		    lclVisualConfigs[i].redSize = -1;
+		    lclVisualConfigs[i].greenSize = -1;
+		    lclVisualConfigs[i].blueSize = -1;
+		    lclVisualConfigs[i].redMask = -1;
+		    lclVisualConfigs[i].greenMask = -1;
+		    lclVisualConfigs[i].blueMask = -1;
+		    lclVisualConfigs[i].alphaMask = 0;
+		    if (accum) {
+		      lclVisualConfigs[i].accumRedSize = 16;
+		      lclVisualConfigs[i].accumGreenSize = 16;
+		      lclVisualConfigs[i].accumBlueSize = 16;
+		      lclVisualConfigs[i].accumAlphaSize = 16;
+		    } else {
+		      lclVisualConfigs[i].accumRedSize = 0;
+		      lclVisualConfigs[i].accumGreenSize = 0;
+		      lclVisualConfigs[i].accumBlueSize = 0;
+		      lclVisualConfigs[i].accumAlphaSize = 0;
+		    }
+		    lclVisualConfigs[i].doubleBuffer = buffers ? TRUE : FALSE;
+		    lclVisualConfigs[i].stereo = stereo ? TRUE : FALSE;
+		    lclVisualConfigs[i].bufferSize = -1;
+		    
+		    lclVisualConfigs[i].depthSize = depth? 24 : 0;
+		    lclVisualConfigs[i].stencilSize = stencil ? 8 : 0;
+		    lclVisualConfigs[i].auxBuffers = aux ? 2 : 0;
+		    lclVisualConfigs[i].level = 0;
+		    lclVisualConfigs[i].visualRating = GLX_NONE_EXT;
+		    lclVisualConfigs[i].transparentPixel = 0;
+		    lclVisualConfigs[i].transparentRed = 0;
+		    lclVisualConfigs[i].transparentGreen = 0;
+		    lclVisualConfigs[i].transparentBlue = 0;
+		    lclVisualConfigs[i].transparentAlpha = 0;
+		    lclVisualConfigs[i].transparentIndex = 0;
+		    i++;
+		  }
+		}
+	      }
+            }
+	  }
+	}
+    }
+    if (i != lclNumConfigs)
+        GLAQUA_DEBUG_MSG("glAquaInitVisualConfigs failed to alloc visual configs");
+
+    GlxSetVisualConfigs(lclNumConfigs, lclVisualConfigs, lclVisualPrivates);
+}
+
+
+static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
+                                   void **privates)
+{
+    GLAQUA_DEBUG_MSG("glAquaSetVisualConfigs\n");
+
+    numConfigs = nconfigs;
+    visualConfigs = configs;
+    visualPrivates = privates;
+}
+
+static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
+                              int *nvisualp, int *ndepthp,
+                              int *rootDepthp, VisualID *defaultVisp,
+                              unsigned long sizes, int bitsPerRGB)
+{
+    GLAQUA_DEBUG_MSG("glAquaInitVisuals\n");
+    
+    if (numConfigs == 0) /* if no configs */
+        glAquaInitVisualConfigs(); /* ensure the visual configs are setup */
+
+    /*
+     * setup the visuals supported by this particular screen.
+     */
+    return init_visuals(nvisualp, visualp, defaultVisp,
+                        *ndepthp, *depthp, *rootDepthp);
+}
+
+#if 0
+static void fixup_visuals(int screen)
+{
+    ScreenPtr pScreen = screenInfo.screens[screen];
+    glAquaScreenRec *pScr = &glAquaScreens[screen];
+    int j;
+    __GLcontextModes *modes;
+
+    GLAQUA_DEBUG_MSG("fixup_visuals\n");
+
+    for ( modes = pScr->modes ; modes != NULL ; modes = modes->next ) {
+        const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
+        const int nplanes = (modes->rgbBits - modes->alphaBits);
+        const VisualPtr pVis = pScreen->visuals;
+
+        /* Find a visual that matches the GLX visual's class and size */
+        for (j = 0; j < pScreen->numVisuals; j++) {
+            if (pVis[j].class == vis_class &&
+            pVis[j].nplanes == nplanes) {
+
+            /* Fixup the masks */
+            modes->redMask   = pVis[j].redMask;
+            modes->greenMask = pVis[j].greenMask;
+            modes->blueMask  = pVis[j].blueMask;
+
+            /* Recalc the sizes */
+            modes->redBits   = count_bits(modes->redMask);
+            modes->greenBits = count_bits(modes->greenMask);
+            modes->blueBits  = count_bits(modes->blueMask);
+            }
+        }
+    }
+}
+#endif
+static void __glXAquaScreenDestroy(__GLXscreen *screen) {
+
+	GLAQUA_DEBUG_MSG("glXAquaScreenDestroy(%p)\n", screen);
+  __glXScreenDestroy(screen);
+
+  free(screen);
+}
+
+static void init_screen_visuals(__GLXAquaScreen *screen) {
+  ScreenPtr pScreen = screen->base.pScreen;
+  
+  __GLXconfig *modes;
+  int *used;
+  int i, j;
+  
+    GLAQUA_DEBUG_MSG("init_screen_visuals\n");
+
+    /* FIXME: Change 'used' to be a array of bits (rather than of ints),
+     * FIXME: create a stack array of 8 or 16 bytes.  If 'numVisuals' is less
+     * FIXME: than 64 or 128 the stack array can be used instead of calling
+     * FIXME: malloc / free.  If nothing else, convert 'used' to
+     * FIXME: array of bytes instead of ints!
+     */
+    used = (int *)malloc(pScreen->numVisuals * sizeof(int));
+    memset(used, 0, pScreen->numVisuals * sizeof(int));
+
+    i = 0;
+    for ( modes = screen -> base.visuals
+          ; modes != NULL
+          ; modes = modes->next ) {
+        const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
+        const int nplanes = (modes->rgbBits - modes->alphaBits);
+        const VisualPtr pVis = pScreen->visuals;
+
+        for (j = 0; j < pScreen->numVisuals; j++) {
+            if (pVis[j].class     == vis_class &&
+                pVis[j].nplanes   == nplanes &&
+                pVis[j].redMask   == modes->redMask &&
+                pVis[j].greenMask == modes->greenMask &&
+                pVis[j].blueMask  == modes->blueMask &&
+                !used[j]) {
+
+                    /* set the VisualID */
+                    modes->visualID = pVis[j].vid;
+
+                    /* Mark this visual used */
+                    used[j] = 1;
+                    break;
+            }
+        }
+        if ( j == pScreen->numVisuals ) {
+            ErrorF("No matching visual for __GLcontextMode with "
+                   "visual class = %d (%d), nplanes = %u\n",
+                   vis_class, 
+                   (int)modes->visualType,
+                   (unsigned int)(modes->rgbBits - modes->alphaBits) );
+        }
+        else if ( modes->visualID == -1 ) {
+            FatalError( "Matching visual found, but visualID still -1!\n" );
+        }
+
+        i++;
+    }
+
+    free(used);
+}
+
+static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen) {
+  __GLXAquaScreen *screen;
+  GLAQUA_DEBUG_MSG("glXAquaScreenProbe\n");
+  if (screen == NULL) return NULL;
+
+  screen = malloc(sizeof *screen);
+
+  __glXScreenInit(&screen->base, pScreen);
+
+  screen->base.destroy        = __glXAquaScreenDestroy;
+  screen->base.createContext  = __glXAquaScreenCreateContext;
+  screen->base.createDrawable = __glXAquaScreenCreateDrawable;
+  screen->base.pScreen       = pScreen;
+
+  init_screen_visuals(screen);
+
+  return &screen->base;
+}
+
+static void __glXAquaDrawableDestroy(__GLXdrawable *base) {
+    GLAQUA_DEBUG_MSG("glAquaDestroyDrawablePrivate\n");
+
+    /* It doesn't work to call DRIDestroySurface here, the drawable's
+       already gone.. But dri.c notices the window destruction and
+       frees the surface itself. */
+
+    free(base);
+}
+
+static __GLXdrawable *
+__glXAquaScreenCreateDrawable(__GLXscreen *screen,
+			      DrawablePtr pDraw,
+			      XID drawId,
+			      __GLXconfig *modes) {
+  __GLXAquaDrawable *glxPriv;
+
+  GLAQUA_DEBUG_MSG("glAquaScreenCreateDrawable(%p,%p,%d,%p)\n", context, pDraw, drawId, modes);
+
+  glxPriv = xalloc(sizeof *glxPriv);
+  if (glxPriv == NULL) return NULL;
+
+  memset(glxPriv, 0, sizeof *glxPriv);
+
+  if (!__glXDrawableInit(&glxPriv->base, screen, pDraw, GLX_DRAWABLE_PIXMAP /*?*/, drawId, modes)) {
+    xfree(glxPriv);
+    return NULL;
+  }
+
+  glxPriv->base.destroy       = __glXAquaDrawableDestroy;
+  glxPriv->base.resize        = __glXAquaDrawableResize;
+  glxPriv->base.swapBuffers   = __glXAquaDrawableSwapBuffers;
+  //  glxPriv->base.copySubBuffer = __glXAquaDrawableCopySubBuffer;
+
+  return &glxPriv->base;
+}
+
+static void glAquaResetExtension(void)
+{
+    GLAQUA_DEBUG_MSG("glAquaResetExtension\n");
+    CGLSetOption(kCGLGOResetLibrary, GL_TRUE);
+}
+
+// Extra goodies for glx
+
+GLuint __glFloorLog2(GLuint val)
+{
+    int c = 0;
+
+    while (val > 1) {
+        c++;
+        val >>= 1;
+    }
+    return c;
+}
+
+void warn_func(void * p1, char *format, ...) {
+  va_list v;
+  va_start(v, format);
+  vfprintf(stderr, format, v);
+  va_end(v);
+}
+
+static void setup_dispatch_table(void) {
+  struct _glapi_table *disp=_glapi_get_dispatch();
+  _glapi_set_warning_func((_glapi_warning_func)warn_func);
+  _glapi_noop_enable_warnings(TRUE);
+
+  SET_Accum(disp, glAccum);
+  SET_ActiveStencilFaceEXT(disp, glActiveStencilFaceEXT);
+  SET_ActiveTextureARB(disp, glActiveTextureARB);
+//SET_AlphaFragmentOp1ATI(disp, glAlphaFragmentOp1EXT);   // <-- EXT -> ATI
+//SET_AlphaFragmentOp2ATI(disp, glAlphaFragmentOp2EXT);
+//SET_AlphaFragmentOp3ATI(disp, glAlphaFragmentOp3EXT);
+  SET_AlphaFunc(disp, glAlphaFunc);
+//SET_AreProgramsResidentNV(disp, glAreProgramsResidentNV);
+  SET_AreTexturesResident(disp, glAreTexturesResident); 
+  SET_ArrayElement(disp, glArrayElement);
+  SET_AttachObjectARB(disp, glAttachObjectARB);
+  SET_Begin(disp, glBegin);
+//SET_BeginFragmentShaderATI(disp, glBeginFragmentShaderEXT);   // <-- EXT -> ATI
+  SET_BeginQueryARB(disp, glBeginQueryARB);
+  SET_BindAttribLocationARB(disp, glBindAttribLocationARB);
+  SET_BindBufferARB(disp, glBindBufferARB);
+//SET_BindFragmentShaderATI(disp, glBindFragmentShaderEXT);     // <-- EXT -> ATI
+  SET_BindFramebufferEXT(disp, glBindFramebufferEXT);
+//SET_BindProgramNV(disp, glBindProgramNV);
+  SET_BindRenderbufferEXT(disp, glBindRenderbufferEXT);
+  SET_BindTexture(disp, glBindTexture);
+  SET_Bitmap(disp, glBitmap);
+  SET_BlendColor(disp, glBlendColor);
+  SET_BlendEquation(disp, glBlendEquation);
+  SET_BlendEquationSeparateEXT(disp, glBlendEquationSeparateEXT);
+  SET_BlendFunc(disp, glBlendFunc);
+  SET_BlendFuncSeparateEXT(disp, glBlendFuncSeparateEXT);
+  SET_BlitFramebufferEXT(disp, glBlitFramebufferEXT);
+  SET_BufferDataARB(disp, glBufferDataARB);
+  SET_BufferSubDataARB(disp, glBufferSubDataARB);
+  SET_CallList(disp, glCallList);
+  SET_CallLists(disp, glCallLists);
+  SET_CheckFramebufferStatusEXT(disp, glCheckFramebufferStatusEXT);
+  SET_Clear(disp, glClear);
+  SET_ClearAccum(disp, glClearAccum);
+  SET_ClearColor(disp, glClearColor);
+  SET_ClearDepth(disp, glClearDepth);
+  SET_ClearIndex(disp, glClearIndex);
+  SET_ClearStencil(disp, glClearStencil);
+  SET_ClientActiveTextureARB(disp, glClientActiveTextureARB);
+  SET_ClipPlane(disp, glClipPlane);
+  SET_Color3b(disp, glColor3b);
+  SET_Color3bv(disp, glColor3bv);
+  SET_Color3d(disp, glColor3d);
+  SET_Color3dv(disp, glColor3dv);
+  SET_Color3f(disp, glColor3f);
+  SET_Color3fv(disp, glColor3fv);
+  SET_Color3i(disp, glColor3i);
+  SET_Color3iv(disp, glColor3iv);
+  SET_Color3s(disp, glColor3s);
+  SET_Color3sv(disp, glColor3sv);
+  SET_Color3ub(disp, glColor3ub);
+  SET_Color3ubv(disp, glColor3ubv);
+  SET_Color3ui(disp, glColor3ui);
+  SET_Color3uiv(disp, glColor3uiv);
+  SET_Color3us(disp, glColor3us);
+  SET_Color3usv(disp, glColor3usv);
+  SET_Color4b(disp, glColor4b);
+  SET_Color4bv(disp, glColor4bv);
+  SET_Color4d(disp, glColor4d);
+  SET_Color4dv(disp, glColor4dv);
+  SET_Color4f(disp, glColor4f);
+  SET_Color4fv(disp, glColor4fv);
+  SET_Color4i(disp, glColor4i);
+  SET_Color4iv(disp, glColor4iv);
+  SET_Color4s(disp, glColor4s);
+  SET_Color4sv(disp, glColor4sv);
+  SET_Color4ub(disp, glColor4ub);
+  SET_Color4ubv(disp, glColor4ubv);
+  SET_Color4ui(disp, glColor4ui);
+  SET_Color4uiv(disp, glColor4uiv);
+  SET_Color4us(disp, glColor4us);
+  SET_Color4usv(disp, glColor4usv);
+//SET_ColorFragmentOp1ATI(disp, glColorFragmentOp1EXT);    // <-- EXT -> ATI
+//SET_ColorFragmentOp2ATI(disp, glColorFragmentOp2EXT);
+//SET_ColorFragmentOp3ATI(disp, glColorFragmentOp3EXT);
+  SET_ColorMask(disp, glColorMask);
+  SET_ColorMaterial(disp, glColorMaterial);
+  SET_ColorPointer(disp, glColorPointer);
+//SET_ColorPointerEXT(disp, glColorPointerEXT);
+  SET_ColorSubTable(disp, glColorSubTable);
+  SET_ColorTable(disp, glColorTable);
+  SET_ColorTableParameterfv(disp, glColorTableParameterfv);
+  SET_ColorTableParameteriv(disp, glColorTableParameteriv);
+  SET_CombinerInputNV(disp, glCombinerInputNV);
+  SET_CombinerOutputNV(disp, glCombinerOutputNV);
+  SET_CombinerParameterfNV(disp, glCombinerParameterfNV);
+  SET_CombinerParameterfvNV(disp, glCombinerParameterfvNV);
+  SET_CombinerParameteriNV(disp, glCombinerParameteriNV);
+  SET_CombinerParameterivNV(disp, glCombinerParameterivNV);
+  SET_CompileShaderARB(disp, glCompileShaderARB);
+  SET_CompressedTexImage1DARB(disp, glCompressedTexImage1DARB);
+  SET_CompressedTexImage2DARB(disp, glCompressedTexImage2DARB);
+  SET_CompressedTexImage3DARB(disp, glCompressedTexImage3DARB);
+  SET_CompressedTexSubImage1DARB(disp, glCompressedTexSubImage1DARB);
+  SET_CompressedTexSubImage2DARB(disp, glCompressedTexSubImage2DARB);
+  SET_CompressedTexSubImage3DARB(disp, glCompressedTexSubImage3DARB);
+  SET_ConvolutionFilter1D(disp, glConvolutionFilter1D);
+  SET_ConvolutionFilter2D(disp, glConvolutionFilter2D);
+  SET_ConvolutionParameterf(disp, glConvolutionParameterf);
+  SET_ConvolutionParameterfv(disp, glConvolutionParameterfv);
+  SET_ConvolutionParameteri(disp, glConvolutionParameteri);
+  SET_ConvolutionParameteriv(disp, glConvolutionParameteriv);
+  SET_CopyColorSubTable(disp, glCopyColorSubTable);
+  SET_CopyColorTable(disp, glCopyColorTable);
+  SET_CopyConvolutionFilter1D(disp, glCopyConvolutionFilter1D);
+  SET_CopyConvolutionFilter2D(disp, glCopyConvolutionFilter2D);
+  SET_CopyPixels(disp, glCopyPixels);
+  SET_CopyTexImage1D(disp, glCopyTexImage1D);
+  SET_CopyTexImage2D(disp, glCopyTexImage2D);
+  SET_CopyTexSubImage1D(disp, glCopyTexSubImage1D);
+  SET_CopyTexSubImage2D(disp, glCopyTexSubImage2D);
+  SET_CopyTexSubImage3D(disp, glCopyTexSubImage3D);
+  SET_CreateProgramObjectARB(disp, glCreateProgramObjectARB);
+  SET_CreateShaderObjectARB(disp, glCreateShaderObjectARB);
+  SET_CullFace(disp, glCullFace);
+//SET_CullParameterdvEXT(disp, glCullParameterdvEXT);
+//SET_CullParameterfvEXT(disp, glCullParameterfvEXT);
+  SET_DeleteBuffersARB(disp, glDeleteBuffersARB);
+  SET_DeleteFencesNV(disp, glDeleteFencesAPPLE);
+//SET_DeleteFragmentShaderATI(disp, glDeleteFragmentShaderEXT);      // <-- EXT -> ATI
+  SET_DeleteFramebuffersEXT(disp, glDeleteFramebuffersEXT);
+  SET_DeleteLists(disp, glDeleteLists);
+  SET_DeleteObjectARB(disp, glDeleteObjectARB);
+//SET_DeleteProgramsNV(disp, glDeleteProgramsNV);
+  SET_DeleteQueriesARB(disp, glDeleteQueriesARB);
+  SET_DeleteRenderbuffersEXT(disp, glDeleteRenderbuffersEXT);
+  SET_DeleteTextures(disp, glDeleteTextures);
+  SET_DepthBoundsEXT(disp, glDepthBoundsEXT);
+  SET_DepthFunc(disp, glDepthFunc);
+  SET_DepthMask(disp, glDepthMask);
+  SET_DepthRange(disp, glDepthRange);
+  SET_DetachObjectARB(disp, glDetachObjectARB);
+  SET_Disable(disp, glDisable);
+  SET_DisableClientState(disp, glDisableClientState);
+  SET_DisableVertexAttribArrayARB(disp, glDisableVertexAttribArrayARB);
+  SET_DrawArrays(disp, glDrawArrays);
+  SET_DrawBuffer(disp, glDrawBuffer);
+  SET_DrawBuffersARB(disp, glDrawBuffersARB);
+  SET_DrawElements(disp, glDrawElements);
+  SET_DrawPixels(disp, glDrawPixels);
+  SET_DrawRangeElements(disp, glDrawRangeElements);
+  SET_EdgeFlag(disp, glEdgeFlag);
+  SET_EdgeFlagPointer(disp, glEdgeFlagPointer);
+//SET_EdgeFlagPointerEXT(disp, glEdgeFlagPointerEXT);
+  SET_EdgeFlagv(disp, glEdgeFlagv);
+  SET_Enable(disp, glEnable);
+  SET_EnableClientState(disp, glEnableClientState);
+  SET_EnableVertexAttribArrayARB(disp, glEnableVertexAttribArrayARB);
+  SET_End(disp, glEnd);
+//SET_EndFragmentShaderATI(disp, glEndFragmentShaderEXT);        // <-- EXT -> ATI
+  SET_EndList(disp, glEndList);
+  SET_EndQueryARB(disp, glEndQueryARB);
+  SET_EvalCoord1d(disp, glEvalCoord1d);
+  SET_EvalCoord1dv(disp, glEvalCoord1dv);
+  SET_EvalCoord1f(disp, glEvalCoord1f);
+  SET_EvalCoord1fv(disp, glEvalCoord1fv);
+  SET_EvalCoord2d(disp, glEvalCoord2d);
+  SET_EvalCoord2dv(disp, glEvalCoord2dv);
+  SET_EvalCoord2f(disp, glEvalCoord2f);
+  SET_EvalCoord2fv(disp, glEvalCoord2fv);
+  SET_EvalMesh1(disp, glEvalMesh1);
+  SET_EvalMesh2(disp, glEvalMesh2);
+  SET_EvalPoint1(disp, glEvalPoint1);
+  SET_EvalPoint2(disp, glEvalPoint2);
+//SET_ExecuteProgramNV(disp, glExecuteProgramNV);
+  SET_FeedbackBuffer(disp, glFeedbackBuffer);
+  SET_FinalCombinerInputNV(disp, glFinalCombinerInputNV);
+  SET_Finish(disp, glFinish);
+  SET_FinishFenceNV(disp, glFinishFenceAPPLE);       // <-- APPLE -> NV
+  SET_Flush(disp, glFlush);
+//SET_FlushVertexArrayRangeNV(disp, glFlushVertexArrayRangeNV);
+  SET_FogCoordPointerEXT(disp, glFogCoordPointerEXT);
+  SET_FogCoorddEXT(disp, glFogCoorddEXT);
+  SET_FogCoorddvEXT(disp, glFogCoorddvEXT);
+  SET_FogCoordfEXT(disp, glFogCoordfEXT);
+  SET_FogCoordfvEXT(disp, glFogCoordfvEXT);
+  SET_Fogf(disp, glFogf);
+  SET_Fogfv(disp, glFogfv);
+  SET_Fogi(disp, glFogi);
+  SET_Fogiv(disp, glFogiv);
+  SET_FramebufferRenderbufferEXT(disp, glFramebufferRenderbufferEXT);
+  SET_FramebufferTexture1DEXT(disp, glFramebufferTexture1DEXT);
+  SET_FramebufferTexture2DEXT(disp, glFramebufferTexture2DEXT);
+  SET_FramebufferTexture3DEXT(disp, glFramebufferTexture3DEXT);
+  SET_FrontFace(disp, glFrontFace);
+  SET_Frustum(disp, glFrustum);
+  SET_GenBuffersARB(disp, glGenBuffersARB);
+  SET_GenFencesNV(disp, glGenFencesAPPLE);            // <-- APPLE -> NV
+//SET_GenFragmentShadersATI(disp, glGenFragmentShadersEXT);         // <-- EXT -> ATI
+  SET_GenFramebuffersEXT(disp, glGenFramebuffersEXT);
+  SET_GenLists(disp, glGenLists);
+//SET_GenProgramsNV(disp, glGenProgramsNV);
+  SET_GenQueriesARB(disp, glGenQueriesARB);
+  SET_GenRenderbuffersEXT(disp, glGenRenderbuffersEXT);
+  SET_GenTextures(disp, glGenTextures);
+  SET_GenerateMipmapEXT(disp, glGenerateMipmapEXT);
+  SET_GetActiveAttribARB(disp, glGetActiveAttribARB);
+  SET_GetActiveUniformARB(disp, glGetActiveUniformARB);
+  SET_GetAttachedObjectsARB(disp, glGetAttachedObjectsARB);
+  SET_GetAttribLocationARB(disp, glGetAttribLocationARB);
+  SET_GetBooleanv(disp, glGetBooleanv);
+  SET_GetBufferParameterivARB(disp, glGetBufferParameterivARB);
+  SET_GetBufferPointervARB(disp, glGetBufferPointervARB);
+  SET_GetBufferSubDataARB(disp, glGetBufferSubDataARB);
+  SET_GetClipPlane(disp, glGetClipPlane);
+  SET_GetColorTable(disp, glGetColorTable);
+  SET_GetColorTableParameterfv(disp, glGetColorTableParameterfv);
+  SET_GetColorTableParameteriv(disp, glGetColorTableParameteriv);
+  SET_GetCombinerInputParameterfvNV(disp, glGetCombinerInputParameterfvNV);
+  SET_GetCombinerInputParameterivNV(disp, glGetCombinerInputParameterivNV);
+  SET_GetCombinerOutputParameterfvNV(disp, glGetCombinerOutputParameterfvNV);
+  SET_GetCombinerOutputParameterivNV(disp, glGetCombinerOutputParameterivNV);
+  SET_GetCompressedTexImageARB(disp, glGetCompressedTexImageARB);
+  SET_GetConvolutionFilter(disp, glGetConvolutionFilter);
+  SET_GetConvolutionParameterfv(disp, glGetConvolutionParameterfv);
+  SET_GetConvolutionParameteriv(disp, glGetConvolutionParameteriv);
+  SET_GetDoublev(disp, glGetDoublev);
+  SET_GetError(disp, glGetError);
+//SET_GetFenceivNV(disp, glGetFenceivNV);
+  SET_GetFinalCombinerInputParameterfvNV(disp, glGetFinalCombinerInputParameterfvNV);
+  SET_GetFinalCombinerInputParameterivNV(disp, glGetFinalCombinerInputParameterivNV);
+  SET_GetFloatv(disp, glGetFloatv);
+  SET_GetFramebufferAttachmentParameterivEXT(disp, glGetFramebufferAttachmentParameterivEXT);
+  SET_GetHandleARB(disp, glGetHandleARB);
+  SET_GetHistogram(disp, glGetHistogram);
+  SET_GetHistogramParameterfv(disp, glGetHistogramParameterfv);
+  SET_GetHistogramParameteriv(disp, glGetHistogramParameteriv);
+  SET_GetInfoLogARB(disp, glGetInfoLogARB);
+  SET_GetIntegerv(disp, glGetIntegerv);
+  SET_GetLightfv(disp, glGetLightfv);
+  SET_GetLightiv(disp, glGetLightiv);
+  SET_GetMapdv(disp, glGetMapdv);
+  SET_GetMapfv(disp, glGetMapfv);
+  SET_GetMapiv(disp, glGetMapiv);
+  SET_GetMaterialfv(disp, glGetMaterialfv);
+  SET_GetMaterialiv(disp, glGetMaterialiv);
+  SET_GetMinmax(disp, glGetMinmax);
+  SET_GetMinmaxParameterfv(disp, glGetMinmaxParameterfv);
+  SET_GetMinmaxParameteriv(disp, glGetMinmaxParameteriv);
+  SET_GetObjectParameterfvARB(disp, glGetObjectParameterfvARB);
+  SET_GetObjectParameterivARB(disp, glGetObjectParameterivARB);
+  SET_GetPixelMapfv(disp, glGetPixelMapfv);
+  SET_GetPixelMapuiv(disp, glGetPixelMapuiv);
+  SET_GetPixelMapusv(disp, glGetPixelMapusv);
+//SET_GetPixelTexGenParameterfvSGIS(disp, glGetPixelTexGenParameterfvSGIS);
+//SET_GetPixelTexGenParameterivSGIS(disp, glGetPixelTexGenParameterivSGIS);
+  SET_GetPointerv(disp, glGetPointerv);
+  SET_GetPolygonStipple(disp, glGetPolygonStipple);
+  SET_GetProgramEnvParameterdvARB(disp, glGetProgramEnvParameterdvARB);
+  SET_GetProgramEnvParameterfvARB(disp, glGetProgramEnvParameterfvARB);
+  SET_GetProgramLocalParameterdvARB(disp, glGetProgramLocalParameterdvARB);
+  SET_GetProgramLocalParameterfvARB(disp, glGetProgramLocalParameterfvARB);
+//SET_GetProgramNamedParameterdvNV(disp, glGetProgramNamedParameterdvNV);
+//SET_GetProgramNamedParameterfvNV(disp, glGetProgramNamedParameterfvNV);
+//SET_GetProgramParameterdvNV(disp, glGetProgramParameterdvNV);
+//SET_GetProgramParameterfvNV(disp, glGetProgramParameterfvNV);
+  SET_GetProgramStringARB(disp, glGetProgramStringARB);
+//SET_GetProgramStringNV(disp, glGetProgramStringNV);
+  SET_GetProgramivARB(disp, glGetProgramivARB);
+//SET_GetProgramivNV(disp, glGetProgramivNV);
+//SET_GetQueryObjecti64vEXT(disp, glGetQueryObjecti64vEXT);
+  SET_GetQueryObjectivARB(disp, glGetQueryObjectivARB);
+//SET_GetQueryObjectui64vEXT(disp, glGetQueryObjectui64vEXT);
+  SET_GetQueryObjectuivARB(disp, glGetQueryObjectuivARB);
+  SET_GetQueryivARB(disp, glGetQueryivARB);
+  SET_GetRenderbufferParameterivEXT(disp, glGetRenderbufferParameterivEXT);
+  SET_GetSeparableFilter(disp, glGetSeparableFilter);
+  SET_GetShaderSourceARB(disp, glGetShaderSourceARB);
+  SET_GetString(disp, glGetString);
+  SET_GetTexEnvfv(disp, glGetTexEnvfv);
+  SET_GetTexEnviv(disp, glGetTexEnviv);
+  SET_GetTexGendv(disp, glGetTexGendv);
+  SET_GetTexGenfv(disp, glGetTexGenfv);
+  SET_GetTexGeniv(disp, glGetTexGeniv);
+  SET_GetTexImage(disp, glGetTexImage);
+  SET_GetTexLevelParameterfv(disp, glGetTexLevelParameterfv);
+  SET_GetTexLevelParameteriv(disp, glGetTexLevelParameteriv);
+  SET_GetTexParameterfv(disp, glGetTexParameterfv);
+  SET_GetTexParameteriv(disp, glGetTexParameteriv);
+//SET_GetTrackMatrixivNV(disp, glGetTrackMatrixivNV);
+  SET_GetUniformLocationARB(disp, glGetUniformLocationARB);
+  SET_GetUniformfvARB(disp, glGetUniformfvARB);
+  SET_GetUniformivARB(disp, glGetUniformivARB);
+//SET_GetVertexAttribPointervNV(disp, glGetVertexAttribPointervNV);
+  SET_GetVertexAttribdvARB(disp, glGetVertexAttribdvARB);
+//SET_GetVertexAttribdvNV(disp, glGetVertexAttribdvNV);
+  SET_GetVertexAttribfvARB(disp, glGetVertexAttribfvARB);
+//SET_GetVertexAttribfvNV(disp, glGetVertexAttribfvNV);
+  SET_GetVertexAttribivARB(disp, glGetVertexAttribivARB);
+//SET_GetVertexAttribivNV(disp, glGetVertexAttribivNV);
+  SET_Hint(disp, glHint);
+  SET_Histogram(disp, glHistogram);
+  SET_IndexMask(disp, glIndexMask);
+  SET_IndexPointer(disp, glIndexPointer);
+//SET_IndexPointerEXT(disp, glIndexPointerEXT);
+  SET_Indexd(disp, glIndexd);
+  SET_Indexdv(disp, glIndexdv);
+  SET_Indexf(disp, glIndexf);
+  SET_Indexfv(disp, glIndexfv);
+  SET_Indexi(disp, glIndexi);
+  SET_Indexiv(disp, glIndexiv);
+  SET_Indexs(disp, glIndexs);
+  SET_Indexsv(disp, glIndexsv);
+  SET_Indexub(disp, glIndexub);
+  SET_Indexubv(disp, glIndexubv);
+  SET_InitNames(disp, glInitNames);
+  SET_InterleavedArrays(disp, glInterleavedArrays);
+  SET_IsBufferARB(disp, glIsBufferARB);
+  SET_IsEnabled(disp, glIsEnabled);
+  SET_IsFenceNV(disp, glIsFenceAPPLE);           // <-- APPLE -> NV
+  SET_IsFramebufferEXT(disp, glIsFramebufferEXT);
+  SET_IsList(disp, glIsList);
+//SET_IsProgramNV(disp, glIsProgramNV);
+  SET_IsQueryARB(disp, glIsQueryARB);
+  SET_IsRenderbufferEXT(disp, glIsRenderbufferEXT);
+  SET_IsTexture(disp, glIsTexture);
+  SET_LightModelf(disp, glLightModelf);
+  SET_LightModelfv(disp, glLightModelfv);
+  SET_LightModeli(disp, glLightModeli);
+  SET_LightModeliv(disp, glLightModeliv);
+  SET_Lightf(disp, glLightf);
+  SET_Lightfv(disp, glLightfv);
+  SET_Lighti(disp, glLighti);
+  SET_Lightiv(disp, glLightiv);
+  SET_LineStipple(disp, glLineStipple);
+  SET_LineWidth(disp, glLineWidth);
+  SET_LinkProgramARB(disp, glLinkProgramARB);
+  SET_ListBase(disp, glListBase);
+  SET_LoadIdentity(disp, glLoadIdentity);
+  SET_LoadMatrixd(disp, glLoadMatrixd);
+  SET_LoadMatrixf(disp, glLoadMatrixf);
+  SET_LoadName(disp, glLoadName);
+//SET_LoadProgramNV(disp, glLoadProgramNV);
+  SET_LoadTransposeMatrixdARB(disp, glLoadTransposeMatrixdARB);
+  SET_LoadTransposeMatrixfARB(disp, glLoadTransposeMatrixfARB);
+  SET_LockArraysEXT(disp, glLockArraysEXT);
+  SET_LogicOp(disp, glLogicOp);
+  SET_Map1d(disp, glMap1d);
+  SET_Map1f(disp, glMap1f);
+  SET_Map2d(disp, glMap2d);
+  SET_Map2f(disp, glMap2f);
+  SET_MapBufferARB(disp, glMapBufferARB);
+  SET_MapGrid1d(disp, glMapGrid1d);
+  SET_MapGrid1f(disp, glMapGrid1f);
+  SET_MapGrid2d(disp, glMapGrid2d);
+  SET_MapGrid2f(disp, glMapGrid2f);
+  SET_Materialf(disp, glMaterialf);
+  SET_Materialfv(disp, glMaterialfv);
+  SET_Materiali(disp, glMateriali);
+  SET_Materialiv(disp, glMaterialiv);
+  SET_MatrixMode(disp, glMatrixMode);
+  SET_Minmax(disp, glMinmax);
+  SET_MultMatrixd(disp, glMultMatrixd);
+  SET_MultMatrixf(disp, glMultMatrixf);
+  SET_MultTransposeMatrixdARB(disp, glMultTransposeMatrixdARB);
+  SET_MultTransposeMatrixfARB(disp, glMultTransposeMatrixfARB);
+  SET_MultiDrawArraysEXT(disp, glMultiDrawArraysEXT);
+  SET_MultiDrawElementsEXT(disp, glMultiDrawElementsEXT);
+//SET_MultiModeDrawArraysIBM(disp, glMultiModeDrawArraysIBM);
+//SET_MultiModeDrawElementsIBM(disp, glMultiModeDrawElementsIBM);
+  SET_MultiTexCoord1dARB(disp, glMultiTexCoord1dARB);
+  SET_MultiTexCoord1dvARB(disp, glMultiTexCoord1dvARB);
+  SET_MultiTexCoord1fARB(disp, glMultiTexCoord1fARB);
+  SET_MultiTexCoord1fvARB(disp, glMultiTexCoord1fvARB);
+  SET_MultiTexCoord1iARB(disp, glMultiTexCoord1iARB);
+  SET_MultiTexCoord1ivARB(disp, glMultiTexCoord1ivARB);
+  SET_MultiTexCoord1sARB(disp, glMultiTexCoord1sARB);
+  SET_MultiTexCoord1svARB(disp, glMultiTexCoord1svARB);
+  SET_MultiTexCoord2dARB(disp, glMultiTexCoord2dARB);
+  SET_MultiTexCoord2dvARB(disp, glMultiTexCoord2dvARB);
+  SET_MultiTexCoord2fARB(disp, glMultiTexCoord2fARB);
+  SET_MultiTexCoord2fvARB(disp, glMultiTexCoord2fvARB);
+  SET_MultiTexCoord2iARB(disp, glMultiTexCoord2iARB);
+  SET_MultiTexCoord2ivARB(disp, glMultiTexCoord2ivARB);
+  SET_MultiTexCoord2sARB(disp, glMultiTexCoord2sARB);
+  SET_MultiTexCoord2svARB(disp, glMultiTexCoord2svARB);
+  SET_MultiTexCoord3dARB(disp, glMultiTexCoord3dARB);
+  SET_MultiTexCoord3dvARB(disp, glMultiTexCoord3dvARB);
+  SET_MultiTexCoord3fARB(disp, glMultiTexCoord3fARB);
+  SET_MultiTexCoord3fvARB(disp, glMultiTexCoord3fvARB);
+  SET_MultiTexCoord3iARB(disp, glMultiTexCoord3iARB);
+  SET_MultiTexCoord3ivARB(disp, glMultiTexCoord3ivARB);
+  SET_MultiTexCoord3sARB(disp, glMultiTexCoord3sARB);
+  SET_MultiTexCoord3svARB(disp, glMultiTexCoord3svARB);
+  SET_MultiTexCoord4dARB(disp, glMultiTexCoord4dARB);
+  SET_MultiTexCoord4dvARB(disp, glMultiTexCoord4dvARB);
+  SET_MultiTexCoord4fARB(disp, glMultiTexCoord4fARB);
+  SET_MultiTexCoord4fvARB(disp, glMultiTexCoord4fvARB);
+  SET_MultiTexCoord4iARB(disp, glMultiTexCoord4iARB);
+  SET_MultiTexCoord4ivARB(disp, glMultiTexCoord4ivARB);
+  SET_MultiTexCoord4sARB(disp, glMultiTexCoord4sARB);
+  SET_MultiTexCoord4svARB(disp, glMultiTexCoord4svARB);
+  SET_NewList(disp, glNewList);
+  SET_Normal3b(disp, glNormal3b);
+  SET_Normal3bv(disp, glNormal3bv);
+  SET_Normal3d(disp, glNormal3d);
+  SET_Normal3dv(disp, glNormal3dv);
+  SET_Normal3f(disp, glNormal3f);
+  SET_Normal3fv(disp, glNormal3fv);
+  SET_Normal3i(disp, glNormal3i);
+  SET_Normal3iv(disp, glNormal3iv);
+  SET_Normal3s(disp, glNormal3s);
+  SET_Normal3sv(disp, glNormal3sv);
+  SET_NormalPointer(disp, glNormalPointer);
+//SET_NormalPointerEXT(disp, glNormalPointerEXT);
+  SET_Ortho(disp, glOrtho);
+//SET_PassTexCoordATI(disp, glPassTexCoordEXT);         // <-- EXT -> ATI
+  SET_PassThrough(disp, glPassThrough);
+  SET_PixelMapfv(disp, glPixelMapfv);
+  SET_PixelMapuiv(disp, glPixelMapuiv);
+  SET_PixelMapusv(disp, glPixelMapusv);
+  SET_PixelStoref(disp, glPixelStoref);
+  SET_PixelStorei(disp, glPixelStorei);
+//SET_PixelTexGenParameterfSGIS(disp, glPixelTexGenParameterfSGIS);
+//SET_PixelTexGenParameterfvSGIS(disp, glPixelTexGenParameterfvSGIS);
+//SET_PixelTexGenParameteriSGIS(disp, glPixelTexGenParameteriSGIS);
+//SET_PixelTexGenParameterivSGIS(disp, glPixelTexGenParameterivSGIS);
+//  SET_PixelTexGenSGIX(disp, glPixelTexGenSGIX);
+  SET_PixelTransferf(disp, glPixelTransferf);
+  SET_PixelTransferi(disp, glPixelTransferi);
+  SET_PixelZoom(disp, glPixelZoom);
+  SET_PointParameterfEXT(disp, glPointParameterfARB);      // <-- ARB -> EXT
+  SET_PointParameterfvEXT(disp, glPointParameterfvARB);    // <-- ARB -> EXT
+  SET_PointParameteriNV(disp, glPointParameteriNV);
+  SET_PointParameterivNV(disp, glPointParameterivNV);
+  SET_PointSize(disp, glPointSize);
+  SET_PolygonMode(disp, glPolygonMode);
+  SET_PolygonOffset(disp, glPolygonOffset);
+//SET_PolygonOffsetEXT(disp, glPolygonOffsetEXT);
+  SET_PolygonStipple(disp, glPolygonStipple);
+  SET_PopAttrib(disp, glPopAttrib);
+  SET_PopClientAttrib(disp, glPopClientAttrib);
+  SET_PopMatrix(disp, glPopMatrix);
+  SET_PopName(disp, glPopName);
+  SET_PrioritizeTextures(disp, glPrioritizeTextures);
+  SET_ProgramEnvParameter4dARB(disp, glProgramEnvParameter4dARB);
+  SET_ProgramEnvParameter4dvARB(disp, glProgramEnvParameter4dvARB);
+  SET_ProgramEnvParameter4fARB(disp, glProgramEnvParameter4fARB);
+  SET_ProgramEnvParameter4fvARB(disp, glProgramEnvParameter4fvARB);
+  SET_ProgramLocalParameter4dARB(disp, glProgramLocalParameter4dARB);
+  SET_ProgramLocalParameter4dvARB(disp, glProgramLocalParameter4dvARB);
+  SET_ProgramLocalParameter4fARB(disp, glProgramLocalParameter4fARB);
+  SET_ProgramLocalParameter4fvARB(disp, glProgramLocalParameter4fvARB);
+//SET_ProgramNamedParameter4dNV(disp, glProgramNamedParameter4dNV);
+//SET_ProgramNamedParameter4dvNV(disp, glProgramNamedParameter4dvNV);
+//SET_ProgramNamedParameter4fNV(disp, glProgramNamedParameter4fNV);
+//SET_ProgramNamedParameter4fvNV(disp, glProgramNamedParameter4fvNV);
+//SET_ProgramParameter4dNV(disp, glProgramParameter4dNV);
+//SET_ProgramParameter4dvNV(disp, glProgramParameter4dvNV);
+//SET_ProgramParameter4fNV(disp, glProgramParameter4fNV);
+//SET_ProgramParameter4fvNV(disp, glProgramParameter4fvNV);
+//SET_ProgramParameters4dvNV(disp, glProgramParameters4dvNV);
+//SET_ProgramParameters4fvNV(disp, glProgramParameters4fvNV);
+  SET_ProgramStringARB(disp, glProgramStringARB);
+  SET_PushAttrib(disp, glPushAttrib);
+  SET_PushClientAttrib(disp, glPushClientAttrib);
+  SET_PushMatrix(disp, glPushMatrix);
+  SET_PushName(disp, glPushName);
+  SET_RasterPos2d(disp, glRasterPos2d);
+  SET_RasterPos2dv(disp, glRasterPos2dv);
+  SET_RasterPos2f(disp, glRasterPos2f);
+  SET_RasterPos2fv(disp, glRasterPos2fv);
+  SET_RasterPos2i(disp, glRasterPos2i);
+  SET_RasterPos2iv(disp, glRasterPos2iv);
+  SET_RasterPos2s(disp, glRasterPos2s);
+  SET_RasterPos2sv(disp, glRasterPos2sv);
+  SET_RasterPos3d(disp, glRasterPos3d);
+  SET_RasterPos3dv(disp, glRasterPos3dv);
+  SET_RasterPos3f(disp, glRasterPos3f);
+  SET_RasterPos3fv(disp, glRasterPos3fv);
+  SET_RasterPos3i(disp, glRasterPos3i);
+  SET_RasterPos3iv(disp, glRasterPos3iv);
+  SET_RasterPos3s(disp, glRasterPos3s);
+  SET_RasterPos3sv(disp, glRasterPos3sv);
+  SET_RasterPos4d(disp, glRasterPos4d);
+  SET_RasterPos4dv(disp, glRasterPos4dv);
+  SET_RasterPos4f(disp, glRasterPos4f);
+  SET_RasterPos4fv(disp, glRasterPos4fv);
+  SET_RasterPos4i(disp, glRasterPos4i);
+  SET_RasterPos4iv(disp, glRasterPos4iv);
+  SET_RasterPos4s(disp, glRasterPos4s);
+  SET_RasterPos4sv(disp, glRasterPos4sv);
+  SET_ReadBuffer(disp, glReadBuffer);
+  SET_ReadPixels(disp, glReadPixels);
+  SET_Rectd(disp, glRectd);
+  SET_Rectdv(disp, glRectdv);
+  SET_Rectf(disp, glRectf);
+  SET_Rectfv(disp, glRectfv);
+  SET_Recti(disp, glRecti);
+  SET_Rectiv(disp, glRectiv);
+  SET_Rects(disp, glRects);
+  SET_Rectsv(disp, glRectsv);
+  SET_RenderMode(disp, glRenderMode);
+  SET_RenderbufferStorageEXT(disp, glRenderbufferStorageEXT);
+//SET_RequestResidentProgramsNV(disp, glRequestResidentProgramsNV);
+  SET_ResetHistogram(disp, glResetHistogram);
+  SET_ResetMinmax(disp, glResetMinmax);
+//SET_ResizeBuffersMESA(disp, glResizeBuffersMESA);
+  SET_Rotated(disp, glRotated);
+  SET_Rotatef(disp, glRotatef);
+  SET_SampleCoverageARB(disp, glSampleCoverageARB);
+//SET_SampleMapATI(disp, glSampleMapEXT);       // <-- EXT -> ATI
+//SET_SampleMaskSGIS(disp, glSampleMaskSGIS);
+//SET_SamplePatternSGIS(disp, glSamplePatternSGIS);
+  SET_Scaled(disp, glScaled);
+  SET_Scalef(disp, glScalef);
+  SET_Scissor(disp, glScissor);
+  SET_SecondaryColor3bEXT(disp, glSecondaryColor3bEXT);
+  SET_SecondaryColor3bvEXT(disp, glSecondaryColor3bvEXT);
+  SET_SecondaryColor3dEXT(disp, glSecondaryColor3dEXT);
+  SET_SecondaryColor3dvEXT(disp, glSecondaryColor3dvEXT);
+  SET_SecondaryColor3fEXT(disp, glSecondaryColor3fEXT);
+  SET_SecondaryColor3fvEXT(disp, glSecondaryColor3fvEXT);
+  SET_SecondaryColor3iEXT(disp, glSecondaryColor3iEXT);
+  SET_SecondaryColor3ivEXT(disp, glSecondaryColor3ivEXT);
+  SET_SecondaryColor3sEXT(disp, glSecondaryColor3sEXT);
+  SET_SecondaryColor3svEXT(disp, glSecondaryColor3svEXT);
+  SET_SecondaryColor3ubEXT(disp, glSecondaryColor3ubEXT);
+  SET_SecondaryColor3ubvEXT(disp, glSecondaryColor3ubvEXT);
+  SET_SecondaryColor3uiEXT(disp, glSecondaryColor3uiEXT);
+  SET_SecondaryColor3uivEXT(disp, glSecondaryColor3uivEXT);
+  SET_SecondaryColor3usEXT(disp, glSecondaryColor3usEXT);
+  SET_SecondaryColor3usvEXT(disp, glSecondaryColor3usvEXT);
+  SET_SecondaryColorPointerEXT(disp, glSecondaryColorPointerEXT);
+  SET_SelectBuffer(disp, glSelectBuffer);
+  SET_SeparableFilter2D(disp, glSeparableFilter2D);
+  SET_SetFenceNV(disp, glSetFenceAPPLE);  // <-- APPLE -> NV
+//SET_SetFragmentShaderConstantATI(disp, glSetFragmentShaderConstantEXT);   // <-- EXT -> ATI
+  SET_ShadeModel(disp, glShadeModel);
+  SET_ShaderSourceARB(disp, glShaderSourceARB);
+  SET_StencilFunc(disp, glStencilFunc);
+  SET_StencilFuncSeparate(disp, glStencilFuncSeparate);
+  SET_StencilMask(disp, glStencilMask);
+  SET_StencilMaskSeparate(disp, glStencilMaskSeparate);
+  SET_StencilOp(disp, glStencilOp);
+  SET_StencilOpSeparate(disp, glStencilOpSeparate);
+  SET_TestFenceNV(disp, glTestFenceAPPLE); // <-- APPLE -> NV
+  SET_TexCoord1d(disp, glTexCoord1d);
+  SET_TexCoord1dv(disp, glTexCoord1dv);
+  SET_TexCoord1f(disp, glTexCoord1f);
+  SET_TexCoord1fv(disp, glTexCoord1fv);
+  SET_TexCoord1i(disp, glTexCoord1i);
+  SET_TexCoord1iv(disp, glTexCoord1iv);
+  SET_TexCoord1s(disp, glTexCoord1s);
+  SET_TexCoord1sv(disp, glTexCoord1sv);
+  SET_TexCoord2d(disp, glTexCoord2d);
+  SET_TexCoord2dv(disp, glTexCoord2dv);
+  SET_TexCoord2f(disp, glTexCoord2f);
+  SET_TexCoord2fv(disp, glTexCoord2fv);
+  SET_TexCoord2i(disp, glTexCoord2i);
+  SET_TexCoord2iv(disp, glTexCoord2iv);
+  SET_TexCoord2s(disp, glTexCoord2s);
+  SET_TexCoord2sv(disp, glTexCoord2sv);
+  SET_TexCoord3d(disp, glTexCoord3d);
+  SET_TexCoord3dv(disp, glTexCoord3dv);
+  SET_TexCoord3f(disp, glTexCoord3f);
+  SET_TexCoord3fv(disp, glTexCoord3fv);
+  SET_TexCoord3i(disp, glTexCoord3i);
+  SET_TexCoord3iv(disp, glTexCoord3iv);
+  SET_TexCoord3s(disp, glTexCoord3s);
+  SET_TexCoord3sv(disp, glTexCoord3sv);
+  SET_TexCoord4d(disp, glTexCoord4d);
+  SET_TexCoord4dv(disp, glTexCoord4dv);
+  SET_TexCoord4f(disp, glTexCoord4f);
+  SET_TexCoord4fv(disp, glTexCoord4fv);
+  SET_TexCoord4i(disp, glTexCoord4i);
+  SET_TexCoord4iv(disp, glTexCoord4iv);
+  SET_TexCoord4s(disp, glTexCoord4s);
+  SET_TexCoord4sv(disp, glTexCoord4sv);
+  SET_TexCoordPointer(disp, glTexCoordPointer);
+//SET_TexCoordPointerEXT(disp, glTexCoordPointerEXT);
+  SET_TexEnvf(disp, glTexEnvf);
+  SET_TexEnvfv(disp, glTexEnvfv);
+  SET_TexEnvi(disp, glTexEnvi);
+  SET_TexEnviv(disp, glTexEnviv);
+  SET_TexGend(disp, glTexGend);
+  SET_TexGendv(disp, glTexGendv);
+  SET_TexGenf(disp, glTexGenf);
+  SET_TexGenfv(disp, glTexGenfv);
+  SET_TexGeni(disp, glTexGeni);
+  SET_TexGeniv(disp, glTexGeniv);
+  SET_TexImage1D(disp, glTexImage1D);
+  SET_TexImage2D(disp, glTexImage2D);
+  SET_TexImage3D(disp, glTexImage3D);
+  SET_TexParameterf(disp, glTexParameterf);
+  SET_TexParameterfv(disp, glTexParameterfv);
+  SET_TexParameteri(disp, glTexParameteri);
+  SET_TexParameteriv(disp, glTexParameteriv);
+  SET_TexSubImage1D(disp, glTexSubImage1D);
+  SET_TexSubImage2D(disp, glTexSubImage2D);
+  SET_TexSubImage3D(disp, glTexSubImage3D);
+//SET_TrackMatrixNV(disp, glTrackMatrixNV);
+  SET_Translated(disp, glTranslated);
+  SET_Translatef(disp, glTranslatef);
+  SET_Uniform1fARB(disp, glUniform1fARB);
+  SET_Uniform1fvARB(disp, glUniform1fvARB);
+  SET_Uniform1iARB(disp, glUniform1iARB);
+  SET_Uniform1ivARB(disp, glUniform1ivARB);
+  SET_Uniform2fARB(disp, glUniform2fARB);
+  SET_Uniform2fvARB(disp, glUniform2fvARB);
+  SET_Uniform2iARB(disp, glUniform2iARB);
+  SET_Uniform2ivARB(disp, glUniform2ivARB);
+  SET_Uniform3fARB(disp, glUniform3fARB);
+  SET_Uniform3fvARB(disp, glUniform3fvARB);
+  SET_Uniform3iARB(disp, glUniform3iARB);
+  SET_Uniform3ivARB(disp, glUniform3ivARB);
+  SET_Uniform4fARB(disp, glUniform4fARB);
+  SET_Uniform4fvARB(disp, glUniform4fvARB);
+  SET_Uniform4iARB(disp, glUniform4iARB);
+  SET_Uniform4ivARB(disp, glUniform4ivARB);
+  SET_UniformMatrix2fvARB(disp, glUniformMatrix2fvARB);
+  SET_UniformMatrix3fvARB(disp, glUniformMatrix3fvARB);
+  SET_UniformMatrix4fvARB(disp, glUniformMatrix4fvARB);
+  SET_UnlockArraysEXT(disp, glUnlockArraysEXT);
+  SET_UnmapBufferARB(disp, glUnmapBufferARB);
+  SET_UseProgramObjectARB(disp, glUseProgramObjectARB);
+  SET_ValidateProgramARB(disp, glValidateProgramARB);
+  SET_Vertex2d(disp, glVertex2d);
+  SET_Vertex2dv(disp, glVertex2dv);
+  SET_Vertex2f(disp, glVertex2f);
+  SET_Vertex2fv(disp, glVertex2fv);
+  SET_Vertex2i(disp, glVertex2i);
+  SET_Vertex2iv(disp, glVertex2iv);
+  SET_Vertex2s(disp, glVertex2s);
+  SET_Vertex2sv(disp, glVertex2sv);
+  SET_Vertex3d(disp, glVertex3d);
+  SET_Vertex3dv(disp, glVertex3dv);
+  SET_Vertex3f(disp, glVertex3f);
+  SET_Vertex3fv(disp, glVertex3fv);
+  SET_Vertex3i(disp, glVertex3i);
+  SET_Vertex3iv(disp, glVertex3iv);
+  SET_Vertex3s(disp, glVertex3s);
+  SET_Vertex3sv(disp, glVertex3sv);
+  SET_Vertex4d(disp, glVertex4d);
+  SET_Vertex4dv(disp, glVertex4dv);
+  SET_Vertex4f(disp, glVertex4f);
+  SET_Vertex4fv(disp, glVertex4fv);
+  SET_Vertex4i(disp, glVertex4i);
+  SET_Vertex4iv(disp, glVertex4iv);
+  SET_Vertex4s(disp, glVertex4s);
+  SET_Vertex4sv(disp, glVertex4sv);
+//SET_VertexArrayRangeNV(disp, glVertexArrayRangeNV);
+  SET_VertexAttrib1dARB(disp, glVertexAttrib1dARB);
+  SET_VertexAttrib1dvARB(disp, glVertexAttrib1dvARB);
+  SET_VertexAttrib1fARB(disp, glVertexAttrib1fARB);
+  SET_VertexAttrib1fvARB(disp, glVertexAttrib1fvARB);
+  SET_VertexAttrib1sARB(disp, glVertexAttrib1sARB);
+  SET_VertexAttrib1svARB(disp, glVertexAttrib1svARB);
+  SET_VertexAttrib2dARB(disp, glVertexAttrib2dARB);
+  SET_VertexAttrib2dvARB(disp, glVertexAttrib2dvARB);
+  SET_VertexAttrib2fARB(disp, glVertexAttrib2fARB);
+  SET_VertexAttrib2fvARB(disp, glVertexAttrib2fvARB);
+  SET_VertexAttrib2sARB(disp, glVertexAttrib2sARB);
+  SET_VertexAttrib2svARB(disp, glVertexAttrib2svARB);
+  SET_VertexAttrib3dARB(disp, glVertexAttrib3dARB);
+  SET_VertexAttrib3dvARB(disp, glVertexAttrib3dvARB);
+  SET_VertexAttrib3fARB(disp, glVertexAttrib3fARB);
+  SET_VertexAttrib3fvARB(disp, glVertexAttrib3fvARB);
+  SET_VertexAttrib3sARB(disp, glVertexAttrib3sARB);
+  SET_VertexAttrib3svARB(disp, glVertexAttrib3svARB);
+  SET_VertexAttrib4NbvARB(disp, glVertexAttrib4NbvARB);
+  SET_VertexAttrib4NivARB(disp, glVertexAttrib4NivARB);
+  SET_VertexAttrib4NsvARB(disp, glVertexAttrib4NsvARB);
+  SET_VertexAttrib4NubARB(disp, glVertexAttrib4NubARB);
+  SET_VertexAttrib4NubvARB(disp, glVertexAttrib4NubvARB);
+  SET_VertexAttrib4NuivARB(disp, glVertexAttrib4NuivARB);
+  SET_VertexAttrib4NusvARB(disp, glVertexAttrib4NusvARB);
+  SET_VertexAttrib4bvARB(disp, glVertexAttrib4bvARB);
+  SET_VertexAttrib4dARB(disp, glVertexAttrib4dARB);
+  SET_VertexAttrib4dvARB(disp, glVertexAttrib4dvARB);
+  SET_VertexAttrib4fARB(disp, glVertexAttrib4fARB);
+  SET_VertexAttrib4fvARB(disp, glVertexAttrib4fvARB);
+  SET_VertexAttrib4ivARB(disp, glVertexAttrib4ivARB);
+  SET_VertexAttrib4sARB(disp, glVertexAttrib4sARB);
+  SET_VertexAttrib4svARB(disp, glVertexAttrib4svARB);
+  SET_VertexAttrib4ubvARB(disp, glVertexAttrib4ubvARB);
+  SET_VertexAttrib4uivARB(disp, glVertexAttrib4uivARB);
+  SET_VertexAttrib4usvARB(disp, glVertexAttrib4usvARB);
+  SET_VertexAttribPointerARB(disp, glVertexAttribPointerARB);
+  SET_VertexPointer(disp, glVertexPointer);
+//  SET_VertexPointerEXT(disp, glVertexPointerEXT);
+  SET_Viewport(disp, glViewport);
+  SET_WindowPos2dMESA(disp, glWindowPos2dARB);
+  SET_WindowPos2dvMESA(disp, glWindowPos2dvARB);
+  SET_WindowPos2fMESA(disp, glWindowPos2fARB);
+  SET_WindowPos2fvMESA(disp, glWindowPos2fvARB);
+  SET_WindowPos2iMESA(disp, glWindowPos2iARB);
+  SET_WindowPos2ivMESA(disp, glWindowPos2ivARB);
+  SET_WindowPos2sMESA(disp, glWindowPos2sARB);
+  SET_WindowPos2svMESA(disp, glWindowPos2svARB);
+  SET_WindowPos3dMESA(disp, glWindowPos3dARB);
+  SET_WindowPos3dvMESA(disp, glWindowPos3dvARB);
+  SET_WindowPos3fMESA(disp, glWindowPos3fARB);
+  SET_WindowPos3fvMESA(disp, glWindowPos3fvARB);
+  SET_WindowPos3iMESA(disp, glWindowPos3iARB);
+  SET_WindowPos3ivMESA(disp, glWindowPos3ivARB);
+  SET_WindowPos3sMESA(disp, glWindowPos3sARB);
+  SET_WindowPos3svMESA(disp, glWindowPos3svARB);
+//SET_WindowPos4dMESA(disp, glWindowPos4dMESA);
+//SET_WindowPos4dvMESA(disp, glWindowPos4dvMESA);
+//SET_WindowPos4fMESA(disp, glWindowPos4fMESA);
+//SET_WindowPos4fvMESA(disp, glWindowPos4fvMESA);
+//SET_WindowPos4iMESA(disp, glWindowPos4iMESA);
+//SET_WindowPos4ivMESA(disp, glWindowPos4ivMESA);
+//SET_WindowPos4sMESA(disp, glWindowPos4sMESA);
+//SET_WindowPos4svMESA(disp, glWindowPos4svMESA);
+}
diff --git a/hw/xquartz/Makefile.am b/hw/xquartz/Makefile.am
index 1c97ac8..ccef5f6 100644
--- a/hw/xquartz/Makefile.am
+++ b/hw/xquartz/Makefile.am
@@ -13,8 +13,8 @@ if X11APP
 X11APP_SUBDIRS = bundle
 endif
 
-SUBDIRS = . xpr $(X11APP_SUBDIRS)
-DIST_SUBDIRS = xpr bundle
+SUBDIRS = . GL xpr $(X11APP_SUBDIRS)
+DIST_SUBDIRS = GL xpr bundle
 
 libXquartz_la_SOURCES = \
 	$(top_srcdir)/fb/fbcmap_mi.c \
commit b05b416c622063b84747702a54ffd9a802d6fc11
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 23 09:59:48 2008 -0700

    XQuartz: No need to include indirect.c a second time
    (cherry picked from commit 41ed532525da85d1bd2c20af5ffa28ac6d1f4996)

diff --git a/hw/xquartz/xpr/Makefile.am b/hw/xquartz/xpr/Makefile.am
index d74cf7d..12009fb 100644
--- a/hw/xquartz/xpr/Makefile.am
+++ b/hw/xquartz/xpr/Makefile.am
@@ -14,7 +14,6 @@ Xquartz_SOURCES = \
 	xprEvent.c \
 	xprFrame.c \
 	xprScreen.c \
-	../../../GL/apple/indirect.c \
 	x-hash.c \
 	x-hook.c \
 	x-list.c
commit 565492c70a280d7e749500c5c0073bdcaf175c86
Author: Ben Byer <bbyer at apple.com>
Date:   Wed Apr 23 06:00:57 2008 -0700

    xquartz: build fixes for GLX/DRI2 fallout (note: not guaranteed)
    (cherry picked from commit 85a5796b667461bf1fafc68c07b3a704cd8efd5b)

diff --git a/GL/apple/indirect.c b/GL/apple/indirect.c
index 2729ab0..a0884d4 100644
--- a/GL/apple/indirect.c
+++ b/GL/apple/indirect.c
@@ -102,7 +102,7 @@ void warn_func(void * p1, char *format, ...);
 
 // some prototypes
 static __GLXscreen * __glXAquaScreenProbe(ScreenPtr pScreen);
-static __GLXdrawable * __glXAquaScreenCreateDrawable(__GLXscreen *screen, DrawablePtr pDraw, XID drawId, __GLcontextModes *modes);
+static __GLXdrawable * __glXAquaScreenCreateDrawable(__GLXscreen *screen, DrawablePtr pDraw, XID drawId, __GLXconfig *modes);
 
 static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
                               int *nvisualp, int *ndepthp,
@@ -118,7 +118,7 @@ static int __glXAquaContextLoseCurrent(__GLXcontext *baseContext);
 static int __glXAquaContextForceCurrent(__GLXcontext *baseContext);
 static int __glXAquaContextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, unsigned long mask);
 
-static CGLPixelFormatObj makeFormat(__GLcontextModes *mode);
+static CGLPixelFormatObj makeFormat(__GLXconfig *mode);
 
 __GLXprovider __glXMesaProvider = {
   __glXAquaScreenProbe,
@@ -141,7 +141,7 @@ struct __GLXAquaScreen {
   __GLXscreen   base;
   int           index;
     int num_vis;
-    __GLcontextModes *modes;
+    __GLXconfig *modes;
 };
 
 static __GLXAquaScreen glAquaScreens[MAXSCREENS];
@@ -162,7 +162,7 @@ struct __GLXAquaDrawable {
 
 static __GLXcontext *
 __glXAquaScreenCreateContext(__GLXscreen *screen,
-			     __GLcontextModes *modes,
+			     __GLXconfig *config,
 			     __GLXcontext *baseShareContext)
 {
   __GLXAquaContext *context;
@@ -177,7 +177,7 @@ __glXAquaScreenCreateContext(__GLXscreen *screen,
   memset(context, 0, sizeof *context);
 
   context->base.pGlxScreen = screen;
-  context->base.modes      = modes;
+  context->base.config      = config;
 
   context->base.destroy        = __glXAquaContextDestroy;
   context->base.makeCurrent    = __glXAquaContextMakeCurrent;
@@ -186,7 +186,7 @@ __glXAquaScreenCreateContext(__GLXscreen *screen,
   context->base.forceCurrent   = __glXAquaContextForceCurrent;
   //  context->base.createDrawable = __glXAquaContextCreateDrawable;
 
-  context->pixelFormat = makeFormat(modes);
+  context->pixelFormat = makeFormat(config);
   if (!context->pixelFormat) {
         free(context);
         return NULL;
@@ -437,7 +437,7 @@ static GLboolean __glXAquaDrawableSwapBuffers(__GLXdrawable *base) {
     return GL_TRUE;
 }
 
-static CGLPixelFormatObj makeFormat(__GLcontextModes *mode) {
+static CGLPixelFormatObj makeFormat(__GLXconfig *config) {
     int i;
     CGLPixelFormatAttribute attr[64]; // currently uses max of 30
     CGLPixelFormatObj result;
@@ -446,7 +446,7 @@ static CGLPixelFormatObj makeFormat(__GLcontextModes *mode) {
     
     GLAQUA_DEBUG_MSG("makeFormat\n");
 
-    if (!mode->rgbMode)
+    if (!config->rgbMode)
         return NULL;
 
     i = 0;
@@ -454,42 +454,43 @@ static CGLPixelFormatObj makeFormat(__GLcontextModes *mode) {
     // attr [i++] = kCGLPFAAcelerated; // require hwaccel - BAD for multiscreen
     // attr [i++] = kCGLPFANoRecovery; // disable fallback renderers - BAD
 
-    if (mode->stereoMode) {
+    if (config->stereoMode) {
         attr[i++] = kCGLPFAStereo;
     }
-    if (mode->doubleBufferMode) {
+
+    if (config->doubleBufferMode) {
         attr[i++] = kCGLPFADoubleBuffer;
     }
 
-    if (mode->colorIndexMode) {
+    if (config->colorIndexMode) {
         /* ignored */
     }
 
-    if (mode->rgbMode) {
+    if (config->rgbMode) {
         attr[i++] = kCGLPFAColorSize;
-        attr[i++] = mode->redBits + mode->greenBits + mode->blueBits;
+        attr[i++] = config->redBits + config->greenBits + config->blueBits;
         attr[i++] = kCGLPFAAlphaSize;
-        attr[i++] = 1; /* FIXME: ignoring mode->alphaBits which is always 0 */
+        attr[i++] = 1; /* FIXME: ignoring config->alphaBits which is always 0 */
     }
 
-    if (mode->haveAccumBuffer) {
+    if (config->haveAccumBuffer) {
         attr[i++] = kCGLPFAAccumSize;
-        attr[i++] = mode->accumRedBits + mode->accumGreenBits
-                    + mode->accumBlueBits + mode->accumAlphaBits;
+        attr[i++] = config->accumRedBits + config->accumGreenBits
+                    + config->accumBlueBits + config->accumAlphaBits;
     }
 	
-    if (mode->haveDepthBuffer) {
+    if (config->haveDepthBuffer) {
         attr[i++] = kCGLPFADepthSize;
-        attr[i++] = mode->depthBits;
+        attr[i++] = config->depthBits;
     }
 	
-    if (mode->haveStencilBuffer) {
+    if (config->haveStencilBuffer) {
         attr[i++] = kCGLPFAStencilSize;
-        attr[i++] = mode->stencilBits;
+        attr[i++] = config->stencilBits;
     }
 
     attr[i++] = kCGLPFAAuxBuffers;
-    attr[i++] = mode->numAuxBuffers;
+    attr[i++] = config->numAuxBuffers;
 
     /* mode->level ignored */
 
@@ -670,7 +671,7 @@ static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
     VisualPtr pVisual = *visualp;
     VisualPtr pVisualNew = NULL;
     VisualID *orig_vid = NULL;
-    __GLcontextModes *modes;
+    __GLXconfig *modes;
     __GLXvisualConfig *pNewVisualConfigs = NULL;
     void **glXVisualPriv;
     void **pNewVisualPriv;
@@ -752,7 +753,7 @@ static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
     }
 
     /* Alloc space for the list of glXVisuals */
-    modes = _gl_context_modes_create(numNewVisuals, sizeof(__GLcontextModes));
+    modes = _gl_context_modes_create(numNewVisuals, sizeof(__GLXconfig));
     if (modes == NULL) {
         free(orig_vid);
         free(pNewVisualPriv);
@@ -925,6 +926,7 @@ Bool enable_stereo = FALSE;
 /* based on code in i830_dri.c
    This ends calling glAquaSetVisualConfigs to set the static
    numconfigs, etc. */
+// see also glxglcore.c -- bhb
 static void
 glAquaInitVisualConfigs(void)
 {
@@ -1085,7 +1087,7 @@ static void __glXAquaScreenDestroy(__GLXscreen *screen) {
 static void init_screen_visuals(__GLXAquaScreen *screen) {
   ScreenPtr pScreen = screen->base.pScreen;
   
-  __GLcontextModes *modes;
+  __GLXconfig *modes;
   int *used;
   int i, j;
   
@@ -1101,7 +1103,7 @@ static void init_screen_visuals(__GLXAquaScreen *screen) {
     memset(used, 0, pScreen->numVisuals * sizeof(int));
 
     i = 0;
-    for ( modes = screen -> base.modes
+    for ( modes = screen -> base.visuals
           ; modes != NULL
           ; modes = modes->next ) {
         const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
@@ -1174,7 +1176,7 @@ static __GLXdrawable *
 __glXAquaScreenCreateDrawable(__GLXscreen *screen,
 			      DrawablePtr pDraw,
 			      XID drawId,
-			      __GLcontextModes *modes) {
+			      __GLXconfig *modes) {
   __GLXAquaDrawable *glxPriv;
 
   GLAQUA_DEBUG_MSG("glAquaScreenCreateDrawable(%p,%p,%d,%p)\n", context, pDraw, drawId, modes);
@@ -1184,7 +1186,7 @@ __glXAquaScreenCreateDrawable(__GLXscreen *screen,
 
   memset(glxPriv, 0, sizeof *glxPriv);
 
-  if (!__glXDrawableInit(&glxPriv->base, screen, pDraw, drawId, modes)) {
+  if (!__glXDrawableInit(&glxPriv->base, screen, pDraw, GLX_DRAWABLE_PIXMAP /*?*/, drawId, modes)) {
     xfree(glxPriv);
     return NULL;
   }
commit 6f6505db51763d902142a8161e71cad44f52560c
Author: Ben Byer <bbyer at apple.com>
Date:   Wed Apr 23 03:43:51 2008 -0700

    glx / xquartz:  we still need glxcontentmodes.[ch] kthx
    (cherry picked from commit 27545fd37f8c703b72f7cfc329778abc1ceabfa0)

diff --git a/GL/symlink-mesa.sh b/GL/symlink-mesa.sh
index 8deaa43..def4f63 100755
--- a/GL/symlink-mesa.sh
+++ b/GL/symlink-mesa.sh
@@ -64,6 +64,8 @@ symlink_glx() {
     dst_dir glx
 
     action indirect_size.h
+    action glcontextmodes.c
+    action glcontextmodes.h
     action indirect_dispatch.c
     action indirect_dispatch.h
     action indirect_dispatch_swap.c
commit 4e3a8af5751ff88c0cadd612821b0ef349d250c5
Author: Ben Byer <bbyer at apple.com>
Date:   Wed Apr 23 03:39:41 2008 -0700

    xquartz: clean up linker line for main binary
    (cherry picked from commit 821d7400f2ff917497b2ee58ceef2b69c2d47ec7)

diff --git a/hw/xquartz/xpr/Makefile.am b/hw/xquartz/xpr/Makefile.am
index 6007423..d74cf7d 100644
--- a/hw/xquartz/xpr/Makefile.am
+++ b/hw/xquartz/xpr/Makefile.am
@@ -14,6 +14,7 @@ Xquartz_SOURCES = \
 	xprEvent.c \
 	xprFrame.c \
 	xprScreen.c \
+	../../../GL/apple/indirect.c \
 	x-hash.c \
 	x-hook.c \
 	x-list.c
@@ -21,23 +22,6 @@ Xquartz_SOURCES = \
 Xquartz_LDADD = \
 	$(top_builddir)/hw/xquartz/libXquartz.la \
 	$(top_builddir)/dix/dixfonts.lo \
-	$(top_builddir)/config/libconfig.a \
-	$(top_builddir)/dix/libdix.la \
-	$(top_builddir)/os/libos.la \
-	$(top_builddir)/dix/libxpstubs.la \
-	$(top_builddir)/miext/shadow/libshadow.la \
-	$(top_builddir)/fb/libfb.la \
-	$(top_builddir)/mi/libmi.la \
-	$(top_builddir)/damageext/libdamageext.la \
-	$(top_builddir)/miext/damage/libdamage.la \
-	$(top_builddir)/xfixes/libxfixes.la \
-	$(top_builddir)/Xext/libXext.la \
-	$(top_builddir)/xkb/libxkb.la \
-	$(top_builddir)/xkb/libxkbstubs.la \
-	$(top_builddir)/Xi/libXi.la \
-	$(top_builddir)/dbe/libdbe.la \
-	$(top_builddir)/record/librecord.la \
-	$(top_builddir)/XTrap/libxtrap.la \
 	$(top_builddir)/miext/rootless/librootless.la \
 	$(DARWIN_LIBS) $(XSERVER_LIBS) $(XSERVER_SYS_LIBS) -lXplugin
 
commit 3685b171da51f853bfdb312d36622dfa03ee75be
Author: Ben Byer <bbyer at apple.com>
Date:   Tue Apr 22 23:53:23 2008 -0700

    xquartz: remove vestigial aglGlx.c
    (cherry picked from commit 40bd041e4255f26fcbdf0831e68619ae0f46ab39)

diff --git a/GL/apple/Makefile.am b/GL/apple/Makefile.am
index c064c03..7ad9140 100644
--- a/GL/apple/Makefile.am
+++ b/GL/apple/Makefile.am
@@ -8,17 +8,7 @@ AM_CPPFLAGS = \
 	-I$(top_srcdir)/hw/xquartz/xpr \
 	-I$(top_srcdir)/miext/damage
 
-if HAVE_AGL_FRAMEWORK
-noinst_LIBRARIES = libAGLcore.a 
-libAGLcore_a_SOURCES = aglGlx.c \
-		       $(top_srcdir)/hw/xquartz/xpr/x-list.c \
-		       $(top_srcdir)/hw/xquartz/xpr/x-list.h \
-		       $(top_srcdir)/hw/xquartz/xpr/x-hash.c \
-		       $(top_srcdir)/hw/xquartz/xpr/x-hash.h \
-		       $(top_srcdir)/hw/dmx/glxProxy/compsize.c
-endif
-
-#noinst_LIBRARIES = libCGLcore.a 
-#libCGLcore_a_SOURCES = \
-#	indirect.c \
-#	$(top_srcdir)/hw/dmx/glxProxy/compsize.c
+noinst_LIBRARIES = libCGLcore.a 
+libCGLcore_a_SOURCES = \
+	indirect.c \
+	$(top_srcdir)/hw/dmx/glxProxy/compsize.c
diff --git a/GL/apple/aglGlx.c b/GL/apple/aglGlx.c
deleted file mode 100644
index 900a9a9..0000000
--- a/GL/apple/aglGlx.c
+++ /dev/null
@@ -1,1354 +0,0 @@
-/*
- * GLX implementation that uses Apple's AGL.framework for OpenGL
- *
- * FIXME: This file and indirect.c are very similar. The two should be
- * merged by introducing suitable abstractions.
- */
-/*
- * Copyright (c) 2002 Greg Parker. All Rights Reserved.
- * Copyright (c) 2004 Torrey T. Lyons. All Rights Reserved.
- *
- * Large portions of this file are copied from Mesa's xf86glx.c,
- * which contains the following copyright:
- *
- * Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
- * All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "quartzCommon.h"
-#include <AGL/agl.h>
-#include "cr.h"
-
-// X11 and X11's glx
-#undef BOOL
-#define BOOL xBOOL
-#include "quartz.h"
-#include <miscstruct.h>
-#include <windowstr.h>
-#include <resource.h>
-#include <GL/glxint.h>
-#include <GL/glxtokens.h>
-#include <scrnintstr.h>
-#include <glxserver.h>
-#include <glxscreens.h>
-#include <glxdrawable.h>
-#include <glxcontext.h>
-#include <glxext.h>
-#include <glxutil.h>
-#include <glxscreens.h>
-#include <GL/internal/glcore.h>
-#undef BOOL
-
-#include "glcontextmodes.h"
-
-// ggs: needed to call back to glx with visual configs
-extern void GlxSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs, void **configprivs);
-
-// Write debugging output, or not
-#ifdef GLAQUA_DEBUG
-#define GLAQUA_DEBUG_MSG ErrorF
-#else
-#define GLAQUA_DEBUG_MSG(a, ...)
-#endif
-
-
-// The following GL functions don't have an EXT suffix in OpenGL.framework.
-GLboolean glAreTexturesResidentEXT (GLsizei a, const GLuint *b, GLboolean *c) {
-    return glAreTexturesResident(a, b, c);
-}
-void glDeleteTexturesEXT (GLsizei d, const GLuint *e) {
-    glDeleteTextures(d, e);
-}
-void glGenTexturesEXT (GLsizei f, GLuint *g) {
-    glGenTextures(f, g);
-}
-GLboolean glIsTextureEXT (GLuint h) {
-    return glIsTexture(h);
-}
-
-
-// some prototypes
-static Bool glAquaScreenProbe(int screen);
-static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
-                              int *nvisualp, int *ndepthp,
-                              int *rootDepthp, VisualID *defaultVisp,
-                              unsigned long sizes, int bitsPerRGB);
-static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
-                                   void **privates);
-static __GLinterface *glAquaCreateContext(__GLimports *imports,
-                                          __GLcontextModes *mode,
-                                          __GLinterface *shareGC);
-static void glAquaCreateBuffer(__GLXdrawablePrivate *glxPriv);
-static void glAquaResetExtension(void);
-
-
-/*
- * This structure is statically allocated in the __glXScreens[]
- * structure.  This struct is not used anywhere other than in
- * __glXScreenInit to initialize each of the active screens
- * (__glXActiveScreens[]).  Several of the fields must be initialized by
- * the screenProbe routine before they are copied to the active screens
- * struct.  In particular, the contextCreate, modes, numVisuals,
- * and numUsableVisuals fields must be initialized.
- */
-static __GLXscreenInfo __glDDXScreenInfo = {
-    glAquaScreenProbe,   /* Must be generic and handle all screens */
-    glAquaCreateContext, /* Substitute screen's createContext routine */
-    glAquaCreateBuffer,  /* Substitute screen's createBuffer routine */
-    NULL,                 /* Set up modes in probe */
-    NULL,                 /* Set up pVisualPriv in probe */
-    0,                    /* Set up numVisuals in probe */
-    0,                    /* Set up numUsableVisuals in probe */
-    "Vendor String",      /* GLXvendor is overwritten by __glXScreenInit */
-    "Version String",     /* GLXversion is overwritten by __glXScreenInit */
-    "Extensions String",  /* GLXextensions is overwritten by __glXScreenInit */
-    NULL                  /* WrappedPositionWindow is overwritten */
-};
-
-void *__glXglDDXScreenInfo(void) {
-    return &__glDDXScreenInfo;
-}
-
-static __GLXextensionInfo __glDDXExtensionInfo = {
-    GL_CORE_APPLE,
-    glAquaResetExtension,
-    glAquaInitVisuals,
-    glAquaSetVisualConfigs
-};
-
-void *__glXglDDXExtensionInfo(void) {
-    return &__glDDXExtensionInfo;
-}
-
-// prototypes
-
-static GLboolean glAquaDestroyContext(__GLcontext *gc);
-static GLboolean glAquaLoseCurrent(__GLcontext *gc);
-static GLboolean glAquaMakeCurrent(__GLcontext *gc);
-static GLboolean glAquaShareContext(__GLcontext *gc, __GLcontext *gcShare);
-static GLboolean glAquaCopyContext(__GLcontext *dst, const __GLcontext *src,
-                                    GLuint mask);
-static GLboolean glAquaForceCurrent(__GLcontext *gc);
-
-/* Drawing surface notification callbacks */
-static GLboolean glAquaNotifyResize(__GLcontext *gc);
-static void glAquaNotifyDestroy(__GLcontext *gc);
-static void glAquaNotifySwapBuffers(__GLcontext *gc);
-
-/* Dispatch table override control for external agents like libGLS */
-static struct __GLdispatchStateRec* glAquaDispatchExec(__GLcontext *gc);
-static void glAquaBeginDispatchOverride(__GLcontext *gc);
-static void glAquaEndDispatchOverride(__GLcontext *gc);
-
-
-static __GLexports glAquaExports = {
-    glAquaDestroyContext,
-    glAquaLoseCurrent,
-    glAquaMakeCurrent,
-    glAquaShareContext,
-    glAquaCopyContext,
-    glAquaForceCurrent,
-
-    glAquaNotifyResize,
-    glAquaNotifyDestroy,
-    glAquaNotifySwapBuffers,
-
-    glAquaDispatchExec,
-    glAquaBeginDispatchOverride,
-    glAquaEndDispatchOverride
-};
-
-
-typedef struct {
-    int num_vis;
-    __GLcontextModes *modes;
-    void **priv;
-
-    // wrapped screen functions
-    RealizeWindowProcPtr RealizeWindow;
-    UnrealizeWindowProcPtr UnrealizeWindow;
-} glAquaScreenRec;
-
-static glAquaScreenRec glAquaScreens[MAXSCREENS];
-
-
-// __GLdrawablePrivate->private
-typedef struct {
-    GLboolean (*resize)(__GLdrawableBuffer *buf, GLint x, GLint y,
-                        GLuint width, GLuint height,
-                        __GLdrawablePrivate *glPriv,
-                        GLuint bufferMask);
-} GLAquaDrawableRec;
-
-struct __GLcontextRec {
-  struct __GLinterfaceRec interface; // required to be first
-
-  AGLContext ctx;
-  AGLPixelFormat pixelFormat;
-
-  Bool isAttached; // TRUE if ctx is really attached to a window
-};
-
-
-// Context manipulation; return GL_FALSE on failure
-static GLboolean glAquaDestroyContext(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("glAquaDestroyContext (ctx 0x%x)\n", gc->ctx);
-
-    if (gc) {
-        if (gc->ctx) aglDestroyContext(gc->ctx);
-        if (gc->pixelFormat) aglDestroyPixelFormat(gc->pixelFormat);
-        free(gc);
-    }
-
-    return GL_TRUE;
-}
-
-
-static GLboolean glAquaLoseCurrent(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("glAquaLoseCurrent (ctx 0x%x)\n", gc->ctx);
-
-    aglSetCurrentContext(NULL);
-    __glXLastContext = NULL; // Mesa does this; why?
-    gc->isAttached = FALSE;
-
-    return GL_TRUE;
-}
-
-
-/*
- * Attach a GL context to a GL drawable
- * If glPriv is NULL, the context is detached.
- */
-static void attach(__GLcontext *gc, __GLdrawablePrivate *glPriv)
-{
-    __GLXdrawablePrivate *glxPriv;
-
-    if (glPriv == NULL) {
-        // attaching to nothing
-        GLAQUA_DEBUG_MSG("unattaching\n");
-        aglSetDrawable(gc->ctx, NULL);
-        gc->isAttached = FALSE;
-        return;
-    }
-
-    // Note that when resizing, the X11 WindowPtr already has its
-    // new size and position, but the Aqua window does not.
-
-    glxPriv = (__GLXdrawablePrivate *)glPriv->other;
-
-    if (glxPriv->type == DRAWABLE_WINDOW) {
-        WindowPtr pWin = (WindowPtr) glxPriv->pDraw;
-        WindowPtr topWin = quartzProcs->TopLevelParent(pWin);
-        CRWindowPtr crWinPtr;
-        AGLDrawable newPort;
-
-        if (glPriv->width <= 0 || glPriv->height <= 0) {
-            // attach to zero size drawable - will really attach later
-            GLAQUA_DEBUG_MSG("couldn't attach to zero size drawable\n");
-            aglSetDrawable(gc->ctx, NULL);
-            gc->isAttached = FALSE;
-            return;
-        }
-
-        crWinPtr = (CRWindowPtr) quartzProcs->FrameForWindow(pWin, FALSE);
-
-        if (crWinPtr) {
-            newPort = (AGLDrawable) crWinPtr->port;
-        } else {
-            newPort = NULL;
-        }
-
-        if (newPort) {
-            // FIXME: won't be a CGrafPtr if currently offscreen or fullscreen
-            AGLDrawable oldPort = aglGetDrawable(gc->ctx);
-            // AGLDrawable newPort = GetWindowPort(window);
-
-            // Frame is GLdrawable in X11 global coordinates
-            // FIXME: Does this work for multiple screens?
-            GLint frame[4] = {glPriv->xOrigin, glPriv->yOrigin, glPriv->width, glPriv->height};
-            GLAQUA_DEBUG_MSG("global size %d %d %d %d\n",
-                             frame[0], frame[1], frame[2], frame[3]);
-
-            // Convert to window-local coordinates
-            frame[0] -= topWin->drawable.x - topWin->borderWidth;
-            frame[1] -= topWin->drawable.y - topWin->borderWidth;
-
-            // AGL uses flipped coordinates
-            frame[1] = topWin->drawable.height + 2*topWin->borderWidth -
-                       frame[1] - frame[3];
-
-            GLAQUA_DEBUG_MSG("local size %d %d %d %d\n",
-                             frame[0], frame[1], frame[2], frame[3]);
-
-            if (oldPort != newPort) {
-                // FIXME: retain/release windows
-                if (!aglSetDrawable(gc->ctx, newPort)) return;
-            }
-            if (!aglSetInteger(gc->ctx, AGL_BUFFER_RECT, frame)) return;
-            if (!aglEnable(gc->ctx, AGL_BUFFER_RECT)) return;
-            if (!aglSetInteger(gc->ctx, AGL_SWAP_RECT, frame)) return;
-            if (!aglEnable(gc->ctx, AGL_SWAP_RECT)) return;
-            if (!aglUpdateContext(gc->ctx)) return;
-
-            gc->isAttached = TRUE;
-            GLAQUA_DEBUG_MSG("attached context 0x%x to window 0x%x\n", gc->ctx,
-                             pWin->drawable.id);
-        } else {
-            // attach to not-yet-realized window - will really attach later
-            GLAQUA_DEBUG_MSG("couldn't attach to unrealized window\n");
-            aglSetDrawable(gc->ctx, NULL);
-            gc->isAttached = FALSE;
-        }
-    } else {
-        GLAQUA_DEBUG_MSG("attach: attach to non-window unimplemented\n");
-        aglSetDrawable(gc->ctx, NULL);
-        gc->isAttached = FALSE;
-    }
-}
-
-static GLboolean glAquaMakeCurrent(__GLcontext *gc)
-{
-    __GLdrawablePrivate *glPriv = gc->interface.imports.getDrawablePrivate(gc);
-
-    GLAQUA_DEBUG_MSG("glAquaMakeCurrent (ctx 0x%x)\n", gc->ctx);
-
-    if (!gc->isAttached) {
-        attach(gc, glPriv);
-    }
-
-    return aglSetCurrentContext(gc->ctx);
-}
-
-static GLboolean glAquaShareContext(__GLcontext *gc, __GLcontext *gcShare)
-{
-  GLAQUA_DEBUG_MSG("glAquaShareContext unimplemented\n");
-
-  return GL_TRUE;
-}
-
-
-static GLboolean glAquaCopyContext(__GLcontext *dst, const __GLcontext *src,
-                                   GLuint mask)
-{
-  GLAQUA_DEBUG_MSG("glAquaCopyContext\n");
-
-    return aglCopyContext(src->ctx, dst->ctx, mask);
-}
-
-static GLboolean glAquaForceCurrent(__GLcontext *gc)
-{
-    //     GLAQUA_DEBUG_MSG("glAquaForceCurrent (ctx 0x%x)\n", gc->ctx);
-    return aglSetCurrentContext(gc->ctx);
-}
-
-/* Drawing surface notification callbacks */
-
-static GLboolean glAquaNotifyResize(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaNotifyResize");
-    return GL_TRUE;
-}
-
-static void glAquaNotifyDestroy(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaNotifyDestroy");
-}
-
-static void glAquaNotifySwapBuffers(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaNotifySwapBuffers");
-}
-
-/* Dispatch table override control for external agents like libGLS */
-static struct __GLdispatchStateRec* glAquaDispatchExec(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaDispatchExec");
-    return NULL;
-}
-
-static void glAquaBeginDispatchOverride(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaBeginDispatchOverride");
-}
-
-static void glAquaEndDispatchOverride(__GLcontext *gc)
-{
-    GLAQUA_DEBUG_MSG("unimplemented glAquaEndDispatchOverride");
-}
-
-
-static AGLPixelFormat makeFormat(__GLcontextModes *mode)
-{
-    int i;
-    GLint attr[64]; // currently uses max of 30
-    AGLPixelFormat result;
-
-    GLAQUA_DEBUG_MSG("makeFormat\n");
-
-    i = 0;
-
-    // attr [i++] = AGL_ACCELERATED; // require hwaccel - BAD for multiscreen
-    // attr [i++] = AGL_NO_RECOVERY; // disable fallback renderers - BAD
-
-    if (mode->stereoMode) {
-        attr[i++] = AGL_STEREO;
-    }
-    if (mode->doubleBufferMode) {
-        attr[i++] = AGL_DOUBLEBUFFER;
-    }
-
-    if (mode->colorIndexMode) {
-        attr[i++] = AGL_BUFFER_SIZE;
-        attr[i++] = mode->indexBits;
-    }
-
-    if (mode->rgbMode) {
-        attr[i++] = AGL_RGBA;
-        attr[i++] = AGL_RED_SIZE;
-        attr[i++] = mode->redBits;
-        attr[i++] = AGL_GREEN_SIZE;
-        attr[i++] = mode->greenBits;
-        attr[i++] = AGL_BLUE_SIZE;
-        attr[i++] = mode->blueBits;
-        attr[i++] = AGL_ALPHA_SIZE;
-        attr[i++] = mode->alphaBits;
-    }
-
-    if (mode->haveAccumBuffer) {
-        attr[i++] = AGL_ACCUM_RED_SIZE;
-        attr[i++] = mode->accumRedBits;
-        attr[i++] = AGL_ACCUM_GREEN_SIZE;
-        attr[i++] = mode->accumGreenBits;
-        attr[i++] = AGL_ACCUM_BLUE_SIZE;
-        attr[i++] = mode->accumBlueBits;
-        attr[i++] = AGL_ACCUM_ALPHA_SIZE;
-        attr[i++] = mode->accumAlphaBits;
-    }
-    if (mode->haveDepthBuffer) {
-        attr[i++] = AGL_DEPTH_SIZE;
-        attr[i++] = mode->depthBits;
-    }
-    if (mode->haveStencilBuffer) {
-        attr[i++] = AGL_STENCIL_SIZE;
-        attr[i++] = mode->stencilBits;
-    }
-
-    attr[i++] = AGL_AUX_BUFFERS;
-    attr[i++] = mode->numAuxBuffers;
-
-    attr[i++] = AGL_LEVEL;
-    attr[i++] = mode->level;
-
-    // mode->pixmapMode ?
-
-    attr[i++] = AGL_NONE; // end of option list
-
-    GLAQUA_DEBUG_MSG("makeFormat almost done\n");
-    result = aglChoosePixelFormat(NULL, 0, attr);
-    GLAQUA_DEBUG_MSG("makeFormat done (0x%x)\n", result);
-    return result;
-}
-
-static __GLinterface *glAquaCreateContext(__GLimports *imports,
-                                          __GLcontextModes *mode,
-                                          __GLinterface *shareGC)
-{
-    __GLcontext *result;
-    __GLcontext *sharectx = (__GLcontext *)shareGC;
-
-    GLAQUA_DEBUG_MSG("glAquaCreateContext\n");
-
-    result = (__GLcontext *)calloc(1, sizeof(__GLcontext));
-    if (!result) return NULL;
-
-    result->interface.imports = *imports;
-    result->interface.exports = glAquaExports;
-
-    result->pixelFormat = makeFormat(mode);
-    if (!result->pixelFormat) {
-        free(result);
-        return NULL;
-    }
-
-    result->ctx = aglCreateContext(result->pixelFormat,
-                        (sharectx && sharectx->ctx) ? sharectx->ctx : NULL);
-
-    if (!result->ctx) {
-        aglDestroyPixelFormat(result->pixelFormat);
-        free(result);
-        return NULL;
-    }
-
-    result->isAttached = FALSE;
-
-    GLAQUA_DEBUG_MSG("glAquaCreateContext done\n");
-    return (__GLinterface *)result;
-}
-
-
-Bool
-glAquaRealizeWindow(WindowPtr pWin)
-{
-    // If this window has GL contexts, tell them to reattach
-    Bool result;
-    ScreenPtr pScreen = pWin->drawable.pScreen;
-    glAquaScreenRec *screenPriv = &glAquaScreens[pScreen->myNum];
-    __GLXdrawablePrivate *glxPriv;
-
-    GLAQUA_DEBUG_MSG("glAquaRealizeWindow\n");
-
-    // Allow the window to be created (RootlessRealizeWindow is inside our wrap)
-    pScreen->RealizeWindow = screenPriv->RealizeWindow;
-    result = pScreen->RealizeWindow(pWin);
-    pScreen->RealizeWindow = glAquaRealizeWindow;
-
-    // The Aqua window will already have been created (windows are
-    // realized from top down)
-
-    // Re-attach this window's GL contexts, if any.
-    glxPriv = __glXFindDrawablePrivate(pWin->drawable.id);
-    if (glxPriv) {
-        __GLXcontext *gx;
-        __GLcontext *gc;
-        __GLdrawablePrivate *glPriv = &glxPriv->glPriv;
-        GLAQUA_DEBUG_MSG("glAquaRealizeWindow is GL drawable!\n");
-
-        // GL contexts bound to this window for drawing
-        for (gx = glxPriv->drawGlxc; gx != NULL; gx = gx->nextDrawPriv) {
-            gc = (__GLcontext *)gx->gc;
-            attach(gc, glPriv);
-        }
-
-        // GL contexts bound to this window for reading
-        for (gx = glxPriv->readGlxc; gx != NULL; gx = gx->nextReadPriv) {
-            gc = (__GLcontext *)gx->gc;
-            attach(gc, glPriv);
-        }
-    }
-
-    return result;
-}
-
-Bool
-glAquaUnrealizeWindow(WindowPtr pWin)
-{
-    // If this window has GL contexts, tell them to unattach
-    Bool result;
-    ScreenPtr pScreen = pWin->drawable.pScreen;
-    glAquaScreenRec *screenPriv = &glAquaScreens[pScreen->myNum];
-    __GLXdrawablePrivate *glxPriv;
-
-    GLAQUA_DEBUG_MSG("glAquaUnrealizeWindow\n");
-
-    // The Aqua window may have already been destroyed (windows
-    // are unrealized from top down)
-
-    // Unattach this window's GL contexts, if any.
-    glxPriv = __glXFindDrawablePrivate(pWin->drawable.id);
-    if (glxPriv) {
-        __GLXcontext *gx;
-        __GLcontext *gc;
-        GLAQUA_DEBUG_MSG("glAquaUnealizeWindow is GL drawable!\n");
-
-        // GL contexts bound to this window for drawing
-        for (gx = glxPriv->drawGlxc; gx != NULL; gx = gx->nextDrawPriv) {
-            gc = (__GLcontext *)gx->gc;
-            attach(gc, NULL);
-        }
-
-        // GL contexts bound to this window for reading
-        for (gx = glxPriv->readGlxc; gx != NULL; gx = gx->nextReadPriv) {
-            gc = (__GLcontext *)gx->gc;
-            attach(gc, NULL);
-        }
-    }
-
-    pScreen->UnrealizeWindow = screenPriv->UnrealizeWindow;
-    result = pScreen->UnrealizeWindow(pWin);
-    pScreen->UnrealizeWindow = glAquaUnrealizeWindow;
-
-    return result;
-}
-
-
-// Originally copied from Mesa
-
-static int                 numConfigs     = 0;
-static __GLXvisualConfig  *visualConfigs  = NULL;
-static void              **visualPrivates = NULL;
-
-/*
- * In the case the driver defines no GLX visuals we'll use these.
- * Note that for TrueColor and DirectColor visuals, bufferSize is the 
- * sum of redSize, greenSize, blueSize and alphaSize, which may be larger 
- * than the nplanes/rootDepth of the server's X11 visuals
- */
-#define NUM_FALLBACK_CONFIGS 5
-static __GLXvisualConfig FallbackConfigs[NUM_FALLBACK_CONFIGS] = {
-  /* [0] = RGB, double buffered, Z */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-     0,  0,  0, 0,      /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    0,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [1] = RGB, double buffered, Z, stencil, accum */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-    16, 16, 16, 0,      /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    8,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [2] = RGB+Alpha, double buffered, Z, stencil, accum */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 8,      /* rgba sizes */
-    -1, -1, -1, -1,     /* rgba masks */
-    16, 16, 16, 16,     /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    8,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [3] = RGB+Alpha, single buffered, Z, stencil, accum */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    True,               /* rgba */
-    -1, -1, -1, 8,      /* rgba sizes */
-    -1, -1, -1, -1,     /* rgba masks */
-    16, 16, 16, 16,     /* rgba accum sizes */
-    False,              /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    8,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-  /* [4] = CI, double buffered, Z */
-  {
-    -1,                 /* vid */
-    -1,                 /* class */
-    False,              /* rgba? (false = color index) */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-     0,  0,  0, 0,      /* rgba accum sizes */
-    True,               /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    0,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE,           /* visualRating */
-    GLX_NONE,           /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-  },
-};
-
-static __GLXvisualConfig NullConfig = {
-    -1,                 /* vid */
-    -1,                 /* class */
-    False,              /* rgba */
-    -1, -1, -1, 0,      /* rgba sizes */
-    -1, -1, -1, 0,      /* rgba masks */
-     0,  0,  0, 0,      /* rgba accum sizes */
-    False,              /* doubleBuffer */
-    False,              /* stereo */
-    -1,                 /* bufferSize */
-    16,                 /* depthSize */
-    0,                  /* stencilSize */
-    0,                  /* auxBuffers */
-    0,                  /* level */
-    GLX_NONE_EXT,       /* visualRating */
-    0,                  /* transparentPixel */
-    0, 0, 0, 0,         /* transparent rgba color (floats scaled to ints) */
-    0                   /* transparentIndex */
-};
-
-
-static int count_bits(unsigned int n)
-{
-   int bits = 0;
-
-   while (n > 0) {
-      if (n & 1) bits++;
-      n >>= 1;
-   }
-   return bits;
-}
-
-
-static Bool init_visuals(int *nvisualp, VisualPtr *visualp,
-                         VisualID *defaultVisp,
-                         int ndepth, DepthPtr pdepth,
-                         int rootDepth)
-{
-    int numRGBconfigs;
-    int numCIconfigs;
-    int numVisuals = *nvisualp;
-    int numNewVisuals;
-    int numNewConfigs;
-    VisualPtr pVisual = *visualp;
-    VisualPtr pVisualNew = NULL;
-    VisualID *orig_vid = NULL;
-    __GLcontextModes *modes;
-    __GLXvisualConfig *pNewVisualConfigs = NULL;
-    void **glXVisualPriv;
-    void **pNewVisualPriv;
-    int found_default;
-    int i, j, k;
-
-    GLAQUA_DEBUG_MSG("init_visuals\n");
-
-    if (numConfigs > 0)
-        numNewConfigs = numConfigs;
-    else
-        numNewConfigs = NUM_FALLBACK_CONFIGS;
-
-    /* Alloc space for the list of new GLX visuals */
-    pNewVisualConfigs = (__GLXvisualConfig *)
-                     __glXMalloc(numNewConfigs * sizeof(__GLXvisualConfig));
-    if (!pNewVisualConfigs) {
-        return FALSE;
-    }
-
-    /* Alloc space for the list of new GLX visual privates */
-    pNewVisualPriv = (void **) __glXMalloc(numNewConfigs * sizeof(void *));
-    if (!pNewVisualPriv) {
-        __glXFree(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /*
-    ** If SetVisualConfigs was not called, then use default GLX
-    ** visual configs.
-    */
-    if (numConfigs == 0) {
-        memcpy(pNewVisualConfigs, FallbackConfigs,
-               NUM_FALLBACK_CONFIGS * sizeof(__GLXvisualConfig));
-        memset(pNewVisualPriv, 0, NUM_FALLBACK_CONFIGS * sizeof(void *));
-    }
-    else {
-        /* copy driver's visual config info */
-        for (i = 0; i < numConfigs; i++) {
-            pNewVisualConfigs[i] = visualConfigs[i];
-            pNewVisualPriv[i] = visualPrivates[i];
-        }
-    }
-
-    /* Count the number of RGB and CI visual configs */
-    numRGBconfigs = 0;
-    numCIconfigs = 0;
-    for (i = 0; i < numNewConfigs; i++) {
-        if (pNewVisualConfigs[i].rgba)
-            numRGBconfigs++;
-        else
-            numCIconfigs++;
-    }
-
-    /* Count the total number of visuals to compute */
-    numNewVisuals = 0;
-    for (i = 0; i < numVisuals; i++) {
-        int count;
-
-        count = ((pVisual[i].class == TrueColor ||
-                  pVisual[i].class == DirectColor)
-                ? numRGBconfigs : numCIconfigs);
-        if (count == 0)
-            count = 1;          /* preserve the existing visual */
-
-        numNewVisuals += count;
-    }
-
-    /* Reset variables for use with the next screen/driver's visual configs */
-    visualConfigs = NULL;
-    numConfigs = 0;
-
-    /* Alloc temp space for the list of orig VisualIDs for each new visual */
-    orig_vid = (VisualID *)__glXMalloc(numNewVisuals * sizeof(VisualID));
-    if (!orig_vid) {
-        __glXFree(pNewVisualPriv);
-        __glXFree(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Alloc space for the list of glXVisuals */
-    modes = _gl_context_modes_create(numNewVisuals, sizeof(__GLcontextModes));
-    if (modes == NULL) {
-        __glXFree(orig_vid);
-        __glXFree(pNewVisualPriv);
-        __glXFree(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Alloc space for the list of glXVisualPrivates */
-    glXVisualPriv = (void **)__glXMalloc(numNewVisuals * sizeof(void *));
-    if (!glXVisualPriv) {
-        _gl_context_modes_destroy( modes );
-        __glXFree(orig_vid);
-        __glXFree(pNewVisualPriv);
-        __glXFree(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Alloc space for the new list of the X server's visuals */
-    pVisualNew = (VisualPtr)__glXMalloc(numNewVisuals * sizeof(VisualRec));
-    if (!pVisualNew) {
-        __glXFree(glXVisualPriv);
-        _gl_context_modes_destroy( modes );
-        __glXFree(orig_vid);
-        __glXFree(pNewVisualPriv);
-        __glXFree(pNewVisualConfigs);
-        return FALSE;
-    }
-
-    /* Initialize the new visuals */
-    found_default = FALSE;
-    glAquaScreens[screenInfo.numScreens-1].modes = modes;
-    for (i = j = 0; i < numVisuals; i++) {
-        int is_rgb = (pVisual[i].class == TrueColor ||
-                  pVisual[i].class == DirectColor);
-
-        if (!is_rgb)
-        {
-            /* We don't support non-rgb visuals for GL. But we don't
-               want to remove them either, so just pass them through
-               with null glX configs */
-
-            pVisualNew[j] = pVisual[i];
-            pVisualNew[j].vid = FakeClientID(0);
-
-            /* Check for the default visual */
-            if (!found_default && pVisual[i].vid == *defaultVisp) {
-                *defaultVisp = pVisualNew[j].vid;
-                found_default = TRUE;
-            }
-
-            /* Save the old VisualID */
-            orig_vid[j] = pVisual[i].vid;
-
-            /* Initialize the glXVisual */
-            _gl_copy_visual_to_context_mode( modes, & NullConfig );
-            modes->visualID = pVisualNew[j].vid;
-
-            j++;
-
-            continue;
-        }
-
-        for (k = 0; k < numNewConfigs; k++) {
-            if (pNewVisualConfigs[k].rgba != is_rgb)
-                continue;
-
-            assert( modes != NULL );
-
-            /* Initialize the new visual */
-            pVisualNew[j] = pVisual[i];
-            pVisualNew[j].vid = FakeClientID(0);
-
-            /* Check for the default visual */
-            if (!found_default && pVisual[i].vid == *defaultVisp) {
-                *defaultVisp = pVisualNew[j].vid;
-                found_default = TRUE;
-            }
-
-            /* Save the old VisualID */
-            orig_vid[j] = pVisual[i].vid;
-
-            /* Initialize the glXVisual */
-            _gl_copy_visual_to_context_mode( modes, & pNewVisualConfigs[k] );
-            modes->visualID = pVisualNew[j].vid;
-
-            /*
-             * If the class is -1, then assume the X visual information
-             * is identical to what GLX needs, and take them from the X
-             * visual.  NOTE: if class != -1, then all other fields MUST
-             * be initialized.
-             */
-            if (modes->visualType == GLX_NONE) {
-                modes->visualType = _gl_convert_from_x_visual_type( pVisual[i].class );
-                modes->redBits    = count_bits(pVisual[i].redMask);
-                modes->greenBits  = count_bits(pVisual[i].greenMask);
-                modes->blueBits   = count_bits(pVisual[i].blueMask);
-                modes->alphaBits  = modes->alphaBits;
-                modes->redMask    = pVisual[i].redMask;
-                modes->greenMask  = pVisual[i].greenMask;
-                modes->blueMask   = pVisual[i].blueMask;
-                modes->alphaMask  = modes->alphaMask;
-                modes->rgbBits = (is_rgb)
-                    ? (modes->redBits + modes->greenBits +
-                       modes->blueBits + modes->alphaBits)
-                    : rootDepth;
-            }
-
-            /* Save the device-dependent private for this visual */
-            glXVisualPriv[j] = pNewVisualPriv[k];
-
-            j++;
-            modes = modes->next;
-        }
-    }
-
-    assert(j <= numNewVisuals);
-
-    /* Save the GLX visuals in the screen structure */
-    glAquaScreens[screenInfo.numScreens-1].num_vis = numNewVisuals;
-    glAquaScreens[screenInfo.numScreens-1].priv = glXVisualPriv;
-
-    /* Set up depth's VisualIDs */
-    for (i = 0; i < ndepth; i++) {
-        int numVids = 0;
-        VisualID *pVids = NULL;
-        int k, n = 0;
-
-        /* Count the new number of VisualIDs at this depth */
-        for (j = 0; j < pdepth[i].numVids; j++)
-            for (k = 0; k < numNewVisuals; k++)
-            if (pdepth[i].vids[j] == orig_vid[k])
-                numVids++;
-
-        /* Allocate a new list of VisualIDs for this depth */
-        pVids = (VisualID *)__glXMalloc(numVids * sizeof(VisualID));
-
-        /* Initialize the new list of VisualIDs for this depth */
-        for (j = 0; j < pdepth[i].numVids; j++)
-            for (k = 0; k < numNewVisuals; k++)
-            if (pdepth[i].vids[j] == orig_vid[k])
-                pVids[n++] = pVisualNew[k].vid;
-
-        /* Update this depth's list of VisualIDs */
-        __glXFree(pdepth[i].vids);
-        pdepth[i].vids = pVids;
-        pdepth[i].numVids = numVids;
-    }
-
-    /* Update the X server's visuals */
-    *nvisualp = numNewVisuals;
-    *visualp = pVisualNew;
-
-    /* Free the old list of the X server's visuals */
-    __glXFree(pVisual);
-
-    /* Clean up temporary allocations */
-    __glXFree(orig_vid);
-    __glXFree(pNewVisualPriv);
-    __glXFree(pNewVisualConfigs);
-
-    /* Free the private list created by DDX HW driver */
-    if (visualPrivates)
-        xfree(visualPrivates);
-    visualPrivates = NULL;
-
-    return TRUE;
-}
-
-/* based on code in i830_dri.c
-   This ends calling glAquaSetVisualConfigs to set the static
-   numconfigs, etc. */
-static void
-glAquaInitVisualConfigs(void)
-{
-    int                 lclNumConfigs     = 0;
-    __GLXvisualConfig  *lclVisualConfigs  = NULL;
-    void              **lclVisualPrivates = NULL;
-
-    int depth, aux, buffers, stencil, accum;
-    int i = 0;
-
-    GLAQUA_DEBUG_MSG("glAquaInitVisualConfigs ");
-
-    /* count num configs:
-        2 Z buffer (0, 24 bit)
-        2 AUX buffer (0, 2)
-        2 buffers (single, double)
-        2 stencil (0, 8 bit)
-        2 accum (0, 64 bit)
-        = 32 configs */
-
-    lclNumConfigs = 2 * 2 * 2 * 2 * 2; /* 32 */
-
-    /* alloc */
-    lclVisualConfigs = xcalloc(sizeof(__GLXvisualConfig), lclNumConfigs);
-    lclVisualPrivates = xcalloc(sizeof(void *), lclNumConfigs);
-
-    /* fill in configs */
-    if (NULL != lclVisualConfigs) {
-        i = 0; /* current buffer */
-        for (depth = 0; depth < 2; depth++) {
-            for (aux = 0; aux < 2; aux++) {
-                for (buffers = 0; buffers < 2; buffers++) {
-                    for (stencil = 0; stencil < 2; stencil++) {
-                        for (accum = 0; accum < 2; accum++) {
-                            lclVisualConfigs[i].vid = -1;
-                            lclVisualConfigs[i].class = -1;
-                            lclVisualConfigs[i].rgba = TRUE;
-                            lclVisualConfigs[i].redSize = -1;
-                            lclVisualConfigs[i].greenSize = -1;
-                            lclVisualConfigs[i].blueSize = -1;
-                            lclVisualConfigs[i].redMask = -1;
-                            lclVisualConfigs[i].greenMask = -1;
-                            lclVisualConfigs[i].blueMask = -1;
-                            lclVisualConfigs[i].alphaMask = 0;
-                            if (accum) {
-                                lclVisualConfigs[i].accumRedSize = 16;
-                                lclVisualConfigs[i].accumGreenSize = 16;
-                                lclVisualConfigs[i].accumBlueSize = 16;
-                                lclVisualConfigs[i].accumAlphaSize = 16;
-                            }
-                            else {
-                                lclVisualConfigs[i].accumRedSize = 0;
-                                lclVisualConfigs[i].accumGreenSize = 0;
-                                lclVisualConfigs[i].accumBlueSize = 0;
-                                lclVisualConfigs[i].accumAlphaSize = 0;
-                            }
-                            lclVisualConfigs[i].doubleBuffer = buffers ? TRUE : FALSE;
-                            lclVisualConfigs[i].stereo = FALSE;
-                            lclVisualConfigs[i].bufferSize = -1;
-
-                            lclVisualConfigs[i].depthSize = depth? 24 : 0;
-                            lclVisualConfigs[i].stencilSize = stencil ? 8 : 0;
-                            lclVisualConfigs[i].auxBuffers = aux ? 2 : 0;
-                            lclVisualConfigs[i].level = 0;
-                            lclVisualConfigs[i].visualRating = GLX_NONE_EXT;
-                            lclVisualConfigs[i].transparentPixel = 0;
-                            lclVisualConfigs[i].transparentRed = 0;
-                            lclVisualConfigs[i].transparentGreen = 0;
-                            lclVisualConfigs[i].transparentBlue = 0;
-                            lclVisualConfigs[i].transparentAlpha = 0;
-                            lclVisualConfigs[i].transparentIndex = 0;
-                            i++;
-                        }
-                    }
-                }
-            }
-        }
-    }
-    if (i != lclNumConfigs)
-        GLAQUA_DEBUG_MSG("glAquaInitVisualConfigs failed to alloc visual configs");
-
-    GlxSetVisualConfigs(lclNumConfigs, lclVisualConfigs, lclVisualPrivates);
-}
-
-
-static void glAquaSetVisualConfigs(int nconfigs, __GLXvisualConfig *configs,
-                                   void **privates)
-{
-    GLAQUA_DEBUG_MSG("glAquaSetVisualConfigs\n");
-
-    numConfigs = nconfigs;
-    visualConfigs = configs;
-    visualPrivates = privates;
-}
-
-static Bool glAquaInitVisuals(VisualPtr *visualp, DepthPtr *depthp,
-                              int *nvisualp, int *ndepthp,
-                              int *rootDepthp, VisualID *defaultVisp,
-                              unsigned long sizes, int bitsPerRGB)
-{
-    GLAQUA_DEBUG_MSG("glAquaInitVisuals\n");
-
-    if (numConfigs == 0) /* if no configs */
-        glAquaInitVisualConfigs(); /* ensure the visual configs are setup */
-
-    /*
-     * Setup the visuals supported by this particular screen.
-     */
-    return init_visuals(nvisualp, visualp, defaultVisp,
-                        *ndepthp, *depthp, *rootDepthp);
-}
-
-
-static void fixup_visuals(int screen)
-{
-    ScreenPtr pScreen = screenInfo.screens[screen];
-    glAquaScreenRec *pScr = &glAquaScreens[screen];
-    int j;
-    __GLcontextModes *modes;
-
-    GLAQUA_DEBUG_MSG("fixup_visuals\n");
-
-    for ( modes = pScr->modes ; modes != NULL ; modes = modes->next ) {
-        const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
-        const int nplanes = (modes->rgbBits - modes->alphaBits);
-        const VisualPtr pVis = pScreen->visuals;
-
-        /* Find a visual that matches the GLX visual's class and size */
-        for (j = 0; j < pScreen->numVisuals; j++) {
-            if (pVis[j].class == vis_class &&
-            pVis[j].nplanes == nplanes) {
-
-            /* Fixup the masks */
-            modes->redMask   = pVis[j].redMask;
-            modes->greenMask = pVis[j].greenMask;
-            modes->blueMask  = pVis[j].blueMask;
-
-            /* Recalc the sizes */
-            modes->redBits   = count_bits(modes->redMask);
-            modes->greenBits = count_bits(modes->greenMask);
-            modes->blueBits  = count_bits(modes->blueMask);
-            }
-        }
-    }
-}
-
-static void init_screen_visuals(int screen)
-{
-    ScreenPtr pScreen = screenInfo.screens[screen];
-    __GLcontextModes *modes;
-    int *used;
-    int i, j;
-
-    GLAQUA_DEBUG_MSG("init_screen_visuals\n");
-
-    /* FIXME: Change 'used' to be a array of bits (rather than of ints),
-     * FIXME: create a stack array of 8 or 16 bytes.  If 'numVisuals' is less
-     * FIXME: than 64 or 128 the stack array can be used instead of calling
-     * FIXME: __glXMalloc / __glXFree.  If nothing else, convert 'used' to
-     * FIXME: array of bytes instead of ints!
-     */
-    used = (int *)__glXMalloc(pScreen->numVisuals * sizeof(int));
-    __glXMemset(used, 0, pScreen->numVisuals * sizeof(int));
-
-    i = 0;
-    for ( modes = glAquaScreens[screen].modes 
-          ; modes != NULL
-          ; modes = modes->next ) {
-        const int vis_class = _gl_convert_to_x_visual_type( modes->visualType );
-        const int nplanes = (modes->rgbBits - modes->alphaBits);
-        const VisualPtr pVis = pScreen->visuals;
-
-        for (j = 0; j < pScreen->numVisuals; j++) {
-            if (pVis[j].class     == vis_class &&
-                pVis[j].nplanes   == nplanes &&
-                pVis[j].redMask   == modes->redMask &&
-                pVis[j].greenMask == modes->greenMask &&
-                pVis[j].blueMask  == modes->blueMask &&
-                !used[j]) {
-
-                    /* Set the VisualID */
-                    modes->visualID = pVis[j].vid;
-
-                    /* Mark this visual used */
-                    used[j] = 1;
-                    break;
-            }
-        }
-        if ( j == pScreen->numVisuals ) {
-            ErrorF("No matching visual for __GLcontextMode with "
-                   "visual class = %d (%d), nplanes = %u\n",
-                   vis_class, 
-                   (int)modes->visualType,
-                   (unsigned int)(modes->rgbBits - modes->alphaBits) );
-        }
-        else if ( modes->visualID == -1 ) {
-            FatalError( "Matching visual found, but visualID still -1!\n" );
-        }
-
-        i++;
-    }
-
-    __glXFree(used);
-}
-
-static Bool glAquaScreenProbe(int screen)
-{
-    ScreenPtr pScreen;
-    glAquaScreenRec *screenPriv;
-
-    GLAQUA_DEBUG_MSG("glAquaScreenProbe\n");
-
-    /*
-     * Set up the current screen's visuals.
-     */
-    __glDDXScreenInfo.modes = glAquaScreens[screen].modes;
-    __glDDXScreenInfo.pVisualPriv = glAquaScreens[screen].priv;
-    __glDDXScreenInfo.numVisuals =
-        __glDDXScreenInfo.numUsableVisuals = glAquaScreens[screen].num_vis;
-
-    /*
-     * Set the current screen's createContext routine.  This could be
-     * wrapped by a DDX GLX context creation routine.
-     */
-    __glDDXScreenInfo.createContext = glAquaCreateContext;
-
-    /*
-     * The ordering of the rgb compenents might have been changed by the
-     * driver after mi initialized them.
-     */
-    fixup_visuals(screen);
-
-    /*
-     * Find the GLX visuals that are supported by this screen and create
-     * XMesa's visuals.
-     */
-    init_screen_visuals(screen);
-
-    /*
-     * Wrap RealizeWindow and UnrealizeWindow on this screen
-     */
-    pScreen = screenInfo.screens[screen];
-    screenPriv = &glAquaScreens[screen];
-    screenPriv->RealizeWindow = pScreen->RealizeWindow;
-    pScreen->RealizeWindow = glAquaRealizeWindow;
-    screenPriv->UnrealizeWindow = pScreen->UnrealizeWindow;
-    pScreen->UnrealizeWindow = glAquaUnrealizeWindow;
-
-    return TRUE;
-}
-
-
-static GLboolean glAquaResizeBuffers(__GLdrawableBuffer *buffer,
-                                     GLint x, GLint y,
-                                     GLuint width, GLuint height,
-                                     __GLdrawablePrivate *glPriv,
-                                     GLuint bufferMask)
-{
-    GLAquaDrawableRec *aquaPriv = (GLAquaDrawableRec *)glPriv->private;
-    __GLXdrawablePrivate *glxPriv = (__GLXdrawablePrivate *)glPriv->other;
-    __GLXcontext *gx;
-    __GLcontext *gc;
-
-    GLAQUA_DEBUG_MSG("glAquaResizeBuffers to (%d %d %d %d)\n", x, y, width, height);
-
-    // update all contexts that point at this drawable for drawing (hack?)
-    for (gx = glxPriv->drawGlxc; gx != NULL; gx = gx->nextDrawPriv) {
-        gc = (__GLcontext *)gx->gc;
-        attach(gc, glPriv);
-    }
-
-    // update all contexts that point at this drawable for reading (hack?)
-    for (gx = glxPriv->readGlxc; gx != NULL; gx = gx->nextReadPriv) {
-        gc = (__GLcontext *)gx->gc;
-        attach(gc, glPriv);
-    }
-
-    return aquaPriv->resize(buffer, x, y, width, height, glPriv, bufferMask);
-}
-
-
-static GLboolean glAquaSwapBuffers(__GLXdrawablePrivate *glxPriv)
-{
-    // fixme AGL software renderer will use properties of current QD port (bad)
-
-    // swap buffers on only *one* of the contexts
-    // (e.g. the last one for drawing)
-    __GLcontext *gc = (__GLcontext *)glxPriv->drawGlxc->gc;
-    if (gc && gc->ctx) aglSwapBuffers(gc->ctx);
-
-    return GL_TRUE;
-}
-
-static void glAquaDestroyDrawablePrivate(__GLdrawablePrivate *glPriv)
-{
-    GLAQUA_DEBUG_MSG("glAquaDestroyDrawablePrivate\n");
-
-    free(glPriv->private);
-    glPriv->private = NULL;
-}
-
-static void glAquaCreateBuffer(__GLXdrawablePrivate *glxPriv)
-{
-    GLAquaDrawableRec *aquaPriv = malloc(sizeof(GLAquaDrawableRec));
-    __GLdrawablePrivate *glPriv = &glxPriv->glPriv;
-
-    GLAQUA_DEBUG_MSG("glAquaCreateBuffer\n");
-
-    // replace swapBuffers (original is never called)
-    glxPriv->swapBuffers = glAquaSwapBuffers;
-
-    // wrap front buffer resize
-    aquaPriv->resize = glPriv->frontBuffer.resize;
-    glPriv->frontBuffer.resize = glAquaResizeBuffers;
-
-    // stash private data
-    glPriv->private = aquaPriv;
-    glPriv->freePrivate = glAquaDestroyDrawablePrivate;
-}
-
-
-static void glAquaResetExtension(void)
-{
-    GLAQUA_DEBUG_MSG("glAquaResetExtension\n");
-    aglResetLibrary();
-}
-
-
-
-// Extra goodies for glx
-
-GLuint __glFloorLog2(GLuint val)
-{
-    int c = 0;
-
-    while (val > 1) {
-        c++;
-        val >>= 1;
-    }
-    return c;
-}
commit f6e22d69af6bc8f63c3a46535a09e217696a679f
Author: Hans de Goede <j.w.r.degoede at hhs.nl>
Date:   Wed Apr 23 12:28:30 2008 -0400

    Prefer glxvisuals with stencil buffer for default visuals
    
    The first fbconfig which has a depthbuffer > 0  and doublebuf is choosen
    when associating fbconfigs with the visuals, indepenent of stencil bits.
    This happens to work ok on intel as there all fbconfigs with a
    depthbuffer > 0 also have stencil bits.
    
    This patch fixes this by first trying to get a fbconfig for default X visuals
    with both stencilbuf, depthbuf and doublebuffering, and if that fails fallback
    to trying to get one with only a depthbuf and doublebuffering.

diff --git a/GL/glx/glxscreens.c b/GL/glx/glxscreens.c
index 41ee029..5859de0 100644
--- a/GL/glx/glxscreens.c
+++ b/GL/glx/glxscreens.c
@@ -437,6 +437,7 @@ initGlxVisual(VisualPtr visual, __GLXconfig *config)
 typedef struct {
     GLboolean doubleBuffer;
     GLboolean depthBuffer;
+    GLboolean stencilBuffer;
 } FBConfigTemplateRec, *FBConfigTemplatePtr;
 
 static __GLXconfig *
@@ -453,6 +454,8 @@ pickFBConfig(__GLXscreen *pGlxScreen, FBConfigTemplatePtr template, int class)
 	    continue;
 	if ((config->depthBits > 0) != template->depthBuffer)
 	    continue;
+	if ((config->stencilBits > 0) != template->stencilBuffer)
+	    continue;
 
 	return config;
     }
@@ -466,8 +469,9 @@ addMinimalSet(__GLXscreen *pGlxScreen)
     __GLXconfig *config;
     VisualPtr visuals;
     int i, j;
-    FBConfigTemplateRec best = { GL_TRUE, GL_TRUE };
-    FBConfigTemplateRec minimal = { GL_FALSE, GL_FALSE };
+    FBConfigTemplateRec best = { GL_TRUE, GL_TRUE, GL_TRUE };
+    FBConfigTemplateRec good = { GL_TRUE, GL_TRUE, GL_FALSE };
+    FBConfigTemplateRec minimal = { GL_FALSE, GL_FALSE, GL_FALSE };
 
     pGlxScreen->visuals = xcalloc(pGlxScreen->pScreen->numVisuals,
 				  sizeof (__GLXconfig *));
@@ -480,8 +484,11 @@ addMinimalSet(__GLXscreen *pGlxScreen)
     for (i = 0, j = 0; i < pGlxScreen->pScreen->numVisuals; i++) {
 	if (visuals[i].nplanes == 32)
 	    config = pickFBConfig(pGlxScreen, &minimal, visuals[i].class);
-	else
+	else {
 	    config = pickFBConfig(pGlxScreen, &best, visuals[i].class);
+	    if (config == NULL)
+		config = pickFBConfig(pGlxScreen, &good, visuals[i].class);
+        }
 	if (config == NULL)
 	    config = pGlxScreen->fbconfigs;
 	if (config == NULL)
commit 00effad583713e882c3f2518bcd3da51bf4db716
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Wed Apr 23 17:46:30 2008 +0300

    xephyr: XEPHYR_DRI is identical to XF86DRI

diff --git a/configure.ac b/configure.ac
index 21c1d91..51ab4c6 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1925,11 +1925,6 @@ if test "$KDRIVE" = yes; then
     if test "x$XEPHYR" = xauto; then
         XEPHYR=$xephyr
     fi
-    XEPHYR_DRI=no
-    if test x$XEPHYR = xyes -a x$DRI = xyes && test "x$GLX" = xyes; then
-        XEPHYR_DRI=yes
-        AC_DEFINE(XEPHYR_DRI,1,[enable DRI extension in xephyr])
-    fi
 
     # Xephyr needs nanosleep() which is in librt on Solaris
     AC_CHECK_FUNC([nanosleep], [],
@@ -1984,7 +1979,6 @@ AM_CONDITIONAL(KDRIVEFBDEV, [test "x$XFBDEV" = xyes])
 AM_CONDITIONAL(XSDLSERVER, [test x"$XSDL" = xyes])
 AM_CONDITIONAL(XEPHYR, [test "x$KDRIVE" = xyes && test "x$XEPHYR" = xyes])
 AM_CONDITIONAL(BUILD_KDRIVEFBDEVLIB, [test "x$KDRIVE" = xyes && test "x$KDRIVEFBDEVLIB" = xyes])
-AM_CONDITIONAL(XEPHYR_HAS_DRI, [test x$XEPHYR_DRI = xyes])
 AM_CONDITIONAL(XFAKESERVER, [test "x$KDRIVE" = xyes && test "x$XFAKE" = xyes])
 
 dnl these only go in xkb-config.h (which is shared by the Xorg and Xnest servers)
diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index 90fd4d8..5269876 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -11,7 +11,7 @@ if XV
 LIBXEPHYR_HOSTXV=libxephyr-hostxv.a
 endif
 
-if XEPHYR_HAS_DRI
+if DRI
 LIBXEPHYR_HOSTDRI=libxephyr-hostdri.a
 endif
 
@@ -53,7 +53,7 @@ if XV
 libxephyr_hostxv_a_SOURCES = $(HOSTVIDEO_SRCS)
 endif
 
-if XEPHYR_HAS_DRI
+if DRI
 libxephyr_hostdri_a_SOURCES = $(HOSTDRI_SRCS)
 endif
 
diff --git a/hw/kdrive/ephyr/XF86dri.c b/hw/kdrive/ephyr/XF86dri.c
index a5fc9bd..be65edf 100644
--- a/hw/kdrive/ephyr/XF86dri.c
+++ b/hw/kdrive/ephyr/XF86dri.c
@@ -46,8 +46,6 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #include <kdrive-config.h>
 #endif
 
-#ifdef XEPHYR_DRI
-
 /* THIS IS NOT AN X CONSORTIUM STANDARD */
 
 #define NEED_REPLIES
@@ -639,5 +637,3 @@ XF86DRICloseFullScreen(Display *dpy, int screen, Drawable drawable)
     (void) drawable;
     return True;
 }
-#endif /*EPHYR_DRI*/
-
diff --git a/hw/kdrive/ephyr/ephyr.c b/hw/kdrive/ephyr/ephyr.c
index b02f990..d69e148 100644
--- a/hw/kdrive/ephyr/ephyr.c
+++ b/hw/kdrive/ephyr/ephyr.c
@@ -32,11 +32,11 @@
 #include "scrnintstr.h"
 #include "ephyrlog.h"
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 #include "ephyrdri.h"
 #include "ephyrdriext.h"
 #include "ephyrglxext.h"
-#endif /*XEPHYR_DRI*/
+#endif /* XF86DRI */
 
 extern int KdTsPhyScreen;
 #ifdef GLXEXT
@@ -631,7 +631,7 @@ ephyrInitScreen (ScreenPtr pScreen)
   }
 #endif /*XV*/
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
   if (!ephyrNoDRI && !hostx_has_dri ()) {
       EPHYR_LOG ("host x does not support DRI. Disabling DRI forwarding\n") ;
       ephyrNoDRI = TRUE ;
@@ -841,7 +841,7 @@ miPointerScreenFuncRec ephyrPointerScreenFuncs =
   ephyrWarpCursor
 };
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 /**
  * find if the remote window denoted by a_remote
  * is paired with an internal Window within the Xephyr server.
@@ -873,7 +873,7 @@ ephyrExposePairedWindow (int a_remote)
     screen->WindowExposures (pair->local, &reg, NullRegion);
     REGION_UNINIT (screen, &reg);
 }
-#endif /*XEPHYR_DRI*/
+#endif /* XF86DRI */
 
 void
 ephyrPoll(void)
@@ -908,14 +908,14 @@ ephyrPoll(void)
             else
               {
                   int x=0, y=0;
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
                   EphyrWindowPair *pair = NULL;
 #endif
                   EPHYR_LOG ("enqueuing mouse motion:%d\n", ephyrCurScreen) ;
                   x = ev.data.mouse_motion.x;
                   y = ev.data.mouse_motion.y;
                   EPHYR_LOG ("initial (x,y):(%d,%d)\n", x, y) ;
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
                   EPHYR_LOG ("is this window peered by a gl drawable ?\n") ;
                   if (findWindowPairFromRemote (ev.data.mouse_motion.window,
                                                 &pair))
@@ -972,7 +972,7 @@ ephyrPoll(void)
 	  KdEnqueueKeyboardEvent (ephyrKbd, ev.data.key_up.scancode, TRUE);
 	  break;
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 	case EPHYR_EV_EXPOSE:
 	  /*
 	   * We only receive expose events when the expose event have
@@ -982,7 +982,7 @@ ephyrPoll(void)
 	   */
 	  ephyrExposePairedWindow (ev.data.expose.window);
 	  break;
-#endif /*XEPHYR_DRI*/
+#endif /* XF86DRI */
 
 	default:
 	  break;
diff --git a/hw/kdrive/ephyr/ephyrdri.c b/hw/kdrive/ephyr/ephyrdri.c
index bb4f6a1..9aa68b1 100644
--- a/hw/kdrive/ephyr/ephyrdri.c
+++ b/hw/kdrive/ephyr/ephyrdri.c
@@ -29,11 +29,8 @@
 #include <kdrive-config.h>
 #endif
 
-#ifdef XEPHYR_DRI
-
 #include <X11/Xutil.h>
 #include <X11/Xlibint.h>
-/*#define _XF86DRI_SERVER_*/
 #include <GL/glx.h>
 #include "xf86dri.h"
 #include "hostx.h"
@@ -287,5 +284,3 @@ ephyrDRIGetDeviceInfo (int a_screen,
     EPHYR_LOG ("leave:%d\n", is_ok) ;
     return is_ok ;
 }
-#endif /*EPHYR_DRI*/
-
diff --git a/hw/kdrive/ephyr/ephyrdriext.c b/hw/kdrive/ephyr/ephyrdriext.c
index fafe56d..883e330 100644
--- a/hw/kdrive/ephyr/ephyrdriext.c
+++ b/hw/kdrive/ephyr/ephyrdriext.c
@@ -32,8 +32,6 @@
 #include <kdrive-config.h>
 #endif
 
-#ifdef XEPHYR_DRI
-
 #include <string.h>
 
 #define NEED_REPLIES
@@ -1439,5 +1437,3 @@ SProcXF86DRIDispatch (register ClientPtr client)
         }
     }
 }
-
-#endif /*XEPHYR_DRI*/
diff --git a/hw/kdrive/ephyr/ephyrglxext.c b/hw/kdrive/ephyr/ephyrglxext.c
index 43a634d..2e08e39 100644
--- a/hw/kdrive/ephyr/ephyrglxext.c
+++ b/hw/kdrive/ephyr/ephyrglxext.c
@@ -42,8 +42,6 @@
 #include "hostx.h"
 
 
-#ifdef XEPHYR_DRI
-
 #ifndef TRUE
 #define TRUE 1
 #endif
@@ -727,6 +725,3 @@ ephyrGLXIsDirectSwap (__GLXclientState *a_cl, GLbyte *a_pc)
 {
     return ephyrGLXIsDirectReal (a_cl, a_pc, TRUE) ;
 }
-
-#endif /*XEPHYR_DRI*/
-
diff --git a/hw/kdrive/ephyr/ephyrhostglx.c b/hw/kdrive/ephyr/ephyrhostglx.c
index f5db5be..6d783d2 100644
--- a/hw/kdrive/ephyr/ephyrhostglx.c
+++ b/hw/kdrive/ephyr/ephyrhostglx.c
@@ -41,7 +41,6 @@
 #include "ephyrlog.h"
 #include "hostx.h"
 
-#ifdef XEPHYR_DRI
 enum VisualConfRequestType {
     EPHYR_GET_FB_CONFIG,
     EPHYR_VENDOR_PRIV_GET_FB_CONFIG_SGIX,
@@ -687,6 +686,3 @@ out:
     EPHYR_LOG ("leave\n") ;
     return is_ok ;
 }
-
-#endif /*XEPHYR_DRI*/
-
diff --git a/hw/kdrive/ephyr/hostx.c b/hw/kdrive/ephyr/hostx.c
index 1a71d06..74f9f16 100644
--- a/hw/kdrive/ephyr/hostx.c
+++ b/hw/kdrive/ephyr/hostx.c
@@ -45,12 +45,12 @@
 #include <X11/keysym.h>
 #include <X11/extensions/XShm.h>
 #include <X11/extensions/shape.h>
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 #include <GL/glx.h>
-#endif /*XEPHYR_DRI*/
+#endif /* XF86DRI */
 #include "ephyrlog.h"
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 extern Bool XF86DRIQueryExtension (Display *dpy,
                                    int *event_basep,
                                    int *error_basep);
@@ -1315,7 +1315,7 @@ hostx_has_xshape (void)
     return TRUE;
 }
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 typedef struct {
     int is_valid ;
     int local_id ;
@@ -1418,5 +1418,4 @@ hostx_has_glx (void)
     return TRUE ;
 }
 
-#endif /*XEPHYR_DRI*/
-
+#endif /* XF86DRI */
diff --git a/hw/kdrive/ephyr/hostx.h b/hw/kdrive/ephyr/hostx.h
index 47ba61b..c1b1958 100644
--- a/hw/kdrive/ephyr/hostx.h
+++ b/hw/kdrive/ephyr/hostx.h
@@ -244,7 +244,7 @@ int hostx_set_window_clipping_rectangles (int a_window,
                                           int a_num_rects) ;
 int hostx_has_xshape (void) ;
 
-#ifdef XEPHYR_DRI
+#ifdef XF86DRI
 int hostx_lookup_peer_window (void *a_local_window,
                               int *a_host_peer /*out parameter*/) ;
 int
@@ -256,6 +256,6 @@ hostx_get_resource_id_peer (int a_local_resource_id,
 int hostx_has_dri (void) ;
 
 int hostx_has_glx (void) ;
-#endif /*XEPHYR_DRI*/
+#endif /* XF86DRI */
 
 #endif /*_XLIBS_STUFF_H_*/
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index 1779082..135d3d8 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -419,8 +419,6 @@
 /* Support DRI extension */
 #undef XF86DRI
 
-#undef XEPHYR_DRI
-
 /* Build DRI2 extension */
 #undef DRI2
 
commit 6a9f7f28ec455d2879ca1a315ce77c48af49e7f4
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Wed Apr 23 17:46:15 2008 +0300

    xephyr: sync with mesa

diff --git a/hw/kdrive/ephyr/GL/internal/dri_interface.h b/hw/kdrive/ephyr/GL/internal/dri_interface.h
deleted file mode 100644
index 8d24e31..0000000
--- a/hw/kdrive/ephyr/GL/internal/dri_interface.h
+++ /dev/null
@@ -1,517 +0,0 @@
-/*
- * Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
- * (C) Copyright IBM Corporation 2004
- * All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * on the rights to use, copy, modify, merge, publish, distribute, sub
- * license, and/or sell copies of the Software, and to permit persons to whom
- * the Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice (including the next
- * paragraph) shall be included in all copies or substantial portions of the
- * Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.  IN NO EVENT SHALL
- * THE COPYRIGHT HOLDERS AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
- * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- * USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/**
- * \file dri_interface.h
- *
- * This file contains all the types and functions that define the interface
- * between a DRI driver and driver loader.  Currently, the most common driver
- * loader is the XFree86 libGL.so.  However, other loaders do exist, and in
- * the future the server-side libglx.a will also be a loader.
- * 
- * \author Kevin E. Martin <kevin at precisioninsight.com>
- * \author Ian Romanick <idr at us.ibm.com>
- */
-
-#ifndef DRI_INTERFACE_H
-#define DRI_INTERFACE_H
-
-#include <GL/internal/glcore.h>
-#include <drm.h>
-
-/**
- * \name DRI interface structures
- *
- * The following structures define the interface between the GLX client
- * side library and the DRI (direct rendering infrastructure).
- */
-/*@{*/
-typedef struct __DRIdisplayRec  __DRIdisplay;
-typedef struct __DRIscreenRec   __DRIscreen;
-typedef struct __DRIcontextRec  __DRIcontext;
-typedef struct __DRIdrawableRec __DRIdrawable;
-typedef struct __DRIdriverRec   __DRIdriver;
-typedef struct __DRIframebufferRec __DRIframebuffer;
-typedef struct __DRIversionRec     __DRIversion;
-typedef struct __DRIinterfaceMethodsRec  __DRIinterfaceMethods;
-typedef unsigned long __DRIid;
-typedef void __DRInativeDisplay;
-/*@}*/
-
-
-/**
- * \name Functions provided by the driver loader.
- */
-/*@{*/
-/**
- * Type of a pointer to \c glXGetScreenDriver, as returned by
- * \c glXGetProcAddress.  This function is used to get the name of the DRI
- * driver for the specified screen of the specified display.  The driver
- * name is typically used with \c glXGetDriverConfig.
- *
- * \sa glXGetScreenDriver, glXGetProcAddress, glXGetDriverConfig
- */
-typedef const char * (* PFNGLXGETSCREENDRIVERPROC) (__DRInativeDisplay *dpy, int scrNum);
-
-/**
- * Type of a pointer to \c glXGetDriverConfig, as returned by
- * \c glXGetProcAddress.  This function is used to get the XML document
- * describing the configuration options available for the specified driver.
- *
- * \sa glXGetDriverConfig, glXGetProcAddress, glXGetScreenDriver
- */
-typedef const char * (* PFNGLXGETDRIVERCONFIGPROC) (const char *driverName);
-
-/**
- * Type of a pointer to \c glxEnableExtension, as returned by
- * \c __DRIinterfaceMethods::getProcAddress.  This function is used to enable
- * a GLX extension on the specified screen.
- */
-typedef void (* PFNGLXSCRENABLEEXTENSIONPROC) ( void *psc, const char * name );
-/*@}*/
-
-
-/**
- * \name Functions and data provided by the driver.
- */
-/*@{*/
-
-typedef void *(CREATENEWSCREENFUNC)(__DRInativeDisplay *dpy, int scrn,
-    __DRIscreen *psc, const __GLcontextModes * modes,
-    const __DRIversion * ddx_version, const __DRIversion * dri_version,
-    const __DRIversion * drm_version, const __DRIframebuffer * frame_buffer,
-    void * pSAREA, int fd, int internal_api_version,
-    const __DRIinterfaceMethods * interface,
-    __GLcontextModes ** driver_modes);
-typedef CREATENEWSCREENFUNC* PFNCREATENEWSCREENFUNC;
-extern CREATENEWSCREENFUNC __driCreateNewScreen_20050727;
-
-
-/**
- * XML document describing the configuration options supported by the
- * driver.
- */
-extern const char __driConfigOptions[];
-
-/*@}*/
-
-
-/**
- * Stored version of some component (i.e., server-side DRI module, kernel-side
- * DRM, etc.).
- * 
- * \todo
- * There are several data structures that explicitly store a major version,
- * minor version, and patch level.  These structures should be modified to
- * have a \c __DRIversionRec instead.
- */
-struct __DRIversionRec {
-    int    major;        /**< Major version number. */
-    int    minor;        /**< Minor version number. */
-    int    patch;        /**< Patch-level. */
-};
-
-
-typedef void (*__DRIfuncPtr)(void);
-
-struct __DRIinterfaceMethodsRec {
-    /**
-     * Get pointer to named function.
-     */
-    __DRIfuncPtr (*getProcAddress)( const char * proc_name );
-
-    /**
-     * Create a list of \c __GLcontextModes structures.
-     */
-    __GLcontextModes * (*createContextModes)(unsigned count,
-        size_t minimum_bytes_per_struct);
-
-    /**
-     * Destroy a list of \c __GLcontextModes structures.
-     *
-     * \todo
-     * Determine if the drivers actually need to call this.
-     */
-    void (*destroyContextModes)( __GLcontextModes * modes );
-
-    /**
-     * Get the \c __DRIscreen for a given display and screen number.
-     */
-    __DRIscreen *(*getScreen)(__DRInativeDisplay *dpy, int screenNum);
-
-
-    /**
-     * \name Client/server protocol functions.
-     *
-     * These functions implement the DRI client/server protocol for
-     * context and drawable operations.  Platforms that do not implement
-     * the wire protocol (e.g., EGL) will implement glorified no-op functions.
-     */
-    /*@{*/
-    /**
-     * Determine if the specified window ID still exists.
-     * 
-     * \note
-     * Implementations may assume that the driver will only pass an ID into
-     * this function that actually corresponds to a window.  On
-     * implementations where windows can only be destroyed by the DRI driver
-     * (e.g., EGL), this function is allowed to always return \c GL_TRUE.
-     */
-    GLboolean (*windowExists)(__DRInativeDisplay *dpy, __DRIid draw);
-
-    /**
-     * Create the server-side portion of the GL context.
-     */
-    GLboolean (* createContext)( __DRInativeDisplay *dpy, int screenNum,
-        int configID, void * contextID, drm_context_t * hw_context );
-
-    /**
-     * Destroy the server-side portion of the GL context.
-     */
-    GLboolean (* destroyContext)( __DRInativeDisplay *dpy, int screenNum,
-        __DRIid context );
-
-    /**
-     * Create the server-side portion of the drawable.
-     */
-    GLboolean (*createDrawable)( __DRInativeDisplay * ndpy, int screen,
-        __DRIid drawable, drm_drawable_t * hHWDrawable );
-
-    /**
-     * Destroy the server-side portion of the drawable.
-     */
-    GLboolean (*destroyDrawable)( __DRInativeDisplay * ndpy, int screen,
-        __DRIid drawable );
-
-    /**
-     * This function is used to get information about the position, size, and
-     * clip rects of a drawable.
-     */
-    GLboolean (* getDrawableInfo) ( __DRInativeDisplay *dpy, int scrn,
-        __DRIid draw, unsigned int * index, unsigned int * stamp,
-        int * x, int * y, int * width, int * height,
-        int * numClipRects, drm_clip_rect_t ** pClipRects,
-        int * backX, int * backY,
-        int * numBackClipRects, drm_clip_rect_t ** pBackClipRects );
-    /*@}*/
-
-
-    /**
-     * \name Timing related functions.
-     */
-    /*@{*/
-    /**
-     * Get the 64-bit unadjusted system time (UST).
-     */
-    int (*getUST)(int64_t * ust);
-
-    /**
-     * Get the media stream counter (MSC) rate.
-     * 
-     * Matching the definition in GLX_OML_sync_control, this function returns
-     * the rate of the "media stream counter".  In practical terms, this is
-     * the frame refresh rate of the display.
-     */
-    GLboolean (*getMSCRate)(__DRInativeDisplay * dpy, __DRIid drawable,
-        int32_t * numerator, int32_t * denominator);
-    /*@}*/
-
-    /**
-     * Reports areas of the given drawable which have been modified by the
-     * driver.
-     *
-     * \param drawable which the drawing was done to.
-     * \param rects rectangles affected, with the drawable origin as the
-     *	      origin.
-     * \param x X offset of the drawable within the screen (used in the
-     *	      front_buffer case)
-     * \param y Y offset of the drawable within the screen.
-     * \param front_buffer boolean flag for whether the drawing to the
-     * 	      drawable was actually done directly to the front buffer (instead
-     *	      of backing storage, for example)
-     */
-    void (*reportDamage)(__DRInativeDisplay * dpy, int screen,
-			 __DRIid drawable,
-			 int x, int y,
-			 drm_clip_rect_t *rects, int num_rects,
-			 int front_buffer);
-};
-
-   
-/**
- * Framebuffer information record.  Used by libGL to communicate information
- * about the framebuffer to the driver's \c __driCreateNewScreen function.
- * 
- * In XFree86, most of this information is derrived from data returned by
- * calling \c XF86DRIGetDeviceInfo.
- *
- * \sa XF86DRIGetDeviceInfo __DRIdisplayRec::createNewScreen
- *     __driUtilCreateNewScreen CallCreateNewScreen
- *
- * \bug This structure could be better named.
- */
-struct __DRIframebufferRec {
-    unsigned char *base;    /**< Framebuffer base address in the CPU's
-			     * address space.  This value is calculated by
-			     * calling \c drmMap on the framebuffer handle
-			     * returned by \c XF86DRIGetDeviceInfo (or a
-			     * similar function).
-			     */
-    int size;               /**< Framebuffer size, in bytes. */
-    int stride;             /**< Number of bytes from one line to the next. */
-    int width;              /**< Pixel width of the framebuffer. */
-    int height;             /**< Pixel height of the framebuffer. */
-    int dev_priv_size;      /**< Size of the driver's dev-priv structure. */
-    void *dev_priv;         /**< Pointer to the driver's dev-priv structure. */
-};
-
-
-/**
- * Screen dependent methods.  This structure is initialized during the
- * \c __DRIdisplayRec::createScreen call.
- */
-struct __DRIscreenRec {
-    /**
-     * Method to destroy the private DRI screen data.
-     */
-    void (*destroyScreen)(__DRInativeDisplay *dpy, int scrn, void *screenPrivate);
-
-    /**
-     * Method to create the private DRI drawable data and initialize the
-     * drawable dependent methods.
-     */
-    void *(*createNewDrawable)(__DRInativeDisplay *dpy, const __GLcontextModes *modes,
-			       __DRIid draw, __DRIdrawable *pdraw,
-			       int renderType, const int *attrs);
-
-    /**
-     * Method to return a pointer to the DRI drawable data.
-     */
-    __DRIdrawable *(*getDrawable)(__DRInativeDisplay *dpy, __DRIid draw,
-				  void *drawablePrivate);
-
-    /**
-     * Opaque pointer to private per screen direct rendering data.  \c NULL
-     * if direct rendering is not supported on this screen.  Never
-     * dereferenced in libGL.
-     */
-    void *private;
-
-    /**
-     * Get the number of vertical refreshes since some point in time before
-     * this function was first called (i.e., system start up).
-     * 
-     * \since Internal API version 20030317.
-     */
-    int (*getMSC)( void *screenPrivate, int64_t *msc );
-
-    /**
-     * Opaque pointer that points back to the containing 
-     * \c __GLXscreenConfigs.  This data structure is shared with DRI drivers
-     * but \c __GLXscreenConfigs is not. However, they are needed by some GLX
-     * functions called by DRI drivers.
-     *
-     * \since Internal API version 20030813.
-     */
-    void *screenConfigs;
-
-    /**
-     * Functions associated with MESA_allocate_memory.
-     *
-     * \since Internal API version 20030815.
-     */
-    /*@{*/
-    void *(*allocateMemory)(__DRInativeDisplay *dpy, int scrn, GLsizei size,
-			    GLfloat readfreq, GLfloat writefreq,
-			    GLfloat priority);
-   
-    void (*freeMemory)(__DRInativeDisplay *dpy, int scrn, GLvoid *pointer);
-   
-    GLuint (*memoryOffset)(__DRInativeDisplay *dpy, int scrn, const GLvoid *pointer);
-    /*@}*/
-
-    /**
-     * Method to create the private DRI context data and initialize the
-     * context dependent methods.
-     *
-     * \since Internal API version 20031201.
-     */
-    void * (*createNewContext)(__DRInativeDisplay *dpy, const __GLcontextModes *modes,
-			       int render_type,
-			       void *sharedPrivate, __DRIcontext *pctx);
-
-    /**
-     * Method to override base texture image with a driver specific 'offset'.
-     * The depth passed in allows e.g. to ignore the alpha channel of texture
-     * images where the non-alpha components don't occupy a whole texel.
-     *
-     * For GLX_EXT_texture_from_pixmap with AIGLX.
-     *
-     * \since Internal API version 20070121.
-     */
-    void (*setTexOffset)(__DRIcontext *pDRICtx, GLint texname,
-			 unsigned long long offset, GLint depth, GLuint pitch);
-};
-
-/**
- * Context dependent methods.  This structure is initialized during the
- * \c __DRIscreenRec::createContext call.
- */
-struct __DRIcontextRec {
-    /**
-     * Method to destroy the private DRI context data.
-     */
-    void (*destroyContext)(__DRInativeDisplay *dpy, int scrn, void *contextPrivate);
-
-    /**
-     * Opaque pointer to private per context direct rendering data.
-     * \c NULL if direct rendering is not supported on the display or
-     * screen used to create this context.  Never dereferenced in libGL.
-     */
-    void *private;
-
-    /**
-     * Pointer to the mode used to create this context.
-     *
-     * \since Internal API version 20040317.
-     */
-    const __GLcontextModes * mode;
-
-    /**
-     * Method to bind a DRI drawable to a DRI graphics context.
-     *
-     * \since Internal API version 20050727.
-     */
-    GLboolean (*bindContext)(__DRInativeDisplay *dpy, int scrn, __DRIid draw,
-			 __DRIid read, __DRIcontext *ctx);
-
-    /**
-     * Method to unbind a DRI drawable from a DRI graphics context.
-     *
-     * \since Internal API version 20050727.
-     */
-    GLboolean (*unbindContext)(__DRInativeDisplay *dpy, int scrn, __DRIid draw,
-			   __DRIid read, __DRIcontext *ctx);
-};
-
-/**
- * Drawable dependent methods.  This structure is initialized during the
- * \c __DRIscreenRec::createDrawable call.  \c createDrawable is not called
- * by libGL at this time.  It's currently used via the dri_util.c utility code
- * instead.
- */
-struct __DRIdrawableRec {
-    /**
-     * Method to destroy the private DRI drawable data.
-     */
-    void (*destroyDrawable)(__DRInativeDisplay *dpy, void *drawablePrivate);
-
-    /**
-     * Method to swap the front and back buffers.
-     */
-    void (*swapBuffers)(__DRInativeDisplay *dpy, void *drawablePrivate);
-
-    /**
-     * Opaque pointer to private per drawable direct rendering data.
-     * \c NULL if direct rendering is not supported on the display or
-     * screen used to create this drawable.  Never dereferenced in libGL.
-     */
-    void *private;
-
-    /**
-     * Get the number of completed swap buffers for this drawable.
-     *
-     * \since Internal API version 20030317.
-     */
-    int (*getSBC)(__DRInativeDisplay *dpy, void *drawablePrivate, int64_t *sbc );
-
-    /**
-     * Wait for the SBC to be greater than or equal target_sbc.
-     *
-     * \since Internal API version 20030317.
-     */
-    int (*waitForSBC)( __DRInativeDisplay * dpy, void *drawablePriv,
-		       int64_t target_sbc,
-		       int64_t * msc, int64_t * sbc );
-
-    /**
-     * Wait for the MSC to equal target_msc, or, if that has already passed,
-     * the next time (MSC % divisor) is equal to remainder.  If divisor is
-     * zero, the function will return as soon as MSC is greater than or equal
-     * to target_msc.
-     * 
-     * \since Internal API version 20030317.
-     */
-    int (*waitForMSC)( __DRInativeDisplay * dpy, void *drawablePriv,
-		       int64_t target_msc, int64_t divisor, int64_t remainder,
-		       int64_t * msc, int64_t * sbc );
-
-    /**
-     * Like \c swapBuffers, but does NOT have an implicit \c glFlush.  Once
-     * rendering is complete, waits until MSC is equal to target_msc, or
-     * if that has already passed, waits until (MSC % divisor) is equal
-     * to remainder.  If divisor is zero, the swap will happen as soon as
-     * MSC is greater than or equal to target_msc.
-     * 
-     * \since Internal API version 20030317.
-     */
-    int64_t (*swapBuffersMSC)(__DRInativeDisplay *dpy, void *drawablePrivate,
-			      int64_t target_msc,
-			      int64_t divisor, int64_t remainder);
-
-    /**
-     * Enable or disable frame usage tracking.
-     * 
-     * \since Internal API version 20030317.
-     */
-    int (*frameTracking)(__DRInativeDisplay *dpy, void *drawablePrivate, GLboolean enable);
-
-    /**
-     * Retrieve frame usage information.
-     * 
-     * \since Internal API version 20030317.
-     */
-    int (*queryFrameTracking)(__DRInativeDisplay *dpy, void *drawablePrivate,
-			      int64_t * sbc, int64_t * missedFrames,
-			      float * lastMissedUsage, float * usage );
-
-    /**
-     * Used by drivers that implement the GLX_SGI_swap_control or
-     * GLX_MESA_swap_control extension.
-     *
-     * \since Internal API version 20030317.
-     */
-    unsigned swap_interval;
-
-    /**
-     * Used by drivers that implement the GLX_MESA_copy_sub_buffer extension.
-     *
-     * \since Internal API version 20060314.
-     */
-    void (*copySubBuffer)(__DRInativeDisplay *dpy, void *drawablePrivate,
-			  int x, int y, int w, int h);
-};
-
-#endif
diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index d13bbae..90fd4d8 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -34,6 +34,7 @@ HOSTDRI_SRCS =			\
 	ephyrdri.c		\
 	ephyrdri.h		\
 	XF86dri.c		\
+	xf86dri.h		\
 	ephyrglxext.c		\
 	ephyrglxext.h		\
 	ephyrhostglx.c		\
diff --git a/hw/kdrive/ephyr/XF86dri.c b/hw/kdrive/ephyr/XF86dri.c
index e656ff5..a5fc9bd 100644
--- a/hw/kdrive/ephyr/XF86dri.c
+++ b/hw/kdrive/ephyr/XF86dri.c
@@ -55,9 +55,8 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #include <X11/extensions/Xext.h>
 #include <X11/extensions/extutil.h>
 #include <GL/glx.h>
-#include <X11/dri/xf86dri.h>
+#include "xf86dri.h"
 #include <X11/dri/xf86dristr.h>
-#include "GL/internal/dri_interface.h"
 
 static XExtensionInfo _xf86dri_info_data;
 static XExtensionInfo *xf86dri_info = &_xf86dri_info_data;
diff --git a/hw/kdrive/ephyr/ephyrdri.c b/hw/kdrive/ephyr/ephyrdri.c
index 53a96ba..bb4f6a1 100644
--- a/hw/kdrive/ephyr/ephyrdri.c
+++ b/hw/kdrive/ephyr/ephyrdri.c
@@ -35,7 +35,7 @@
 #include <X11/Xlibint.h>
 /*#define _XF86DRI_SERVER_*/
 #include <GL/glx.h>
-#include <X11/dri/xf86dri.h>
+#include "xf86dri.h"
 #include "hostx.h"
 #include "ephyrdri.h"
 #define _HAVE_XALLOC_DECLS
diff --git a/hw/kdrive/ephyr/xf86dri.h b/hw/kdrive/ephyr/xf86dri.h
new file mode 100644
index 0000000..cd650b5
--- /dev/null
+++ b/hw/kdrive/ephyr/xf86dri.h
@@ -0,0 +1,120 @@
+/* $XFree86: xc/lib/GL/dri/xf86dri.h,v 1.8 2002/10/30 12:51:25 alanh Exp $ */
+/**************************************************************************
+
+Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
+Copyright 2000 VA Linux Systems, Inc.
+All Rights Reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sub license, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice (including the
+next paragraph) shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
+IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
+ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+**************************************************************************/
+
+/**
+ * \file xf86dri.h
+ * Protocol numbers and function prototypes for DRI X protocol.
+ *
+ * \author Kevin E. Martin <martin at valinux.com>
+ * \author Jens Owen <jens at tungstengraphics.com>
+ * \author Rickard E. (Rik) Faith <faith at valinux.com>
+ */
+
+#ifndef _XF86DRI_H_
+#define _XF86DRI_H_
+
+#include <X11/Xfuncproto.h>
+#include <xf86drm.h>
+
+#define X_XF86DRIQueryVersion			0
+#define X_XF86DRIQueryDirectRenderingCapable	1
+#define X_XF86DRIOpenConnection			2
+#define X_XF86DRICloseConnection		3
+#define X_XF86DRIGetClientDriverName		4
+#define X_XF86DRICreateContext			5
+#define X_XF86DRIDestroyContext			6
+#define X_XF86DRICreateDrawable			7
+#define X_XF86DRIDestroyDrawable		8
+#define X_XF86DRIGetDrawableInfo		9
+#define X_XF86DRIGetDeviceInfo			10
+#define X_XF86DRIAuthConnection                 11
+#define X_XF86DRIOpenFullScreen                 12   /* Deprecated */
+#define X_XF86DRICloseFullScreen                13   /* Deprecated */
+
+#define XF86DRINumberEvents		0
+
+#define XF86DRIClientNotLocal		0
+#define XF86DRIOperationNotSupported	1
+#define XF86DRINumberErrors		(XF86DRIOperationNotSupported + 1)
+
+#ifndef _XF86DRI_SERVER_
+
+_XFUNCPROTOBEGIN
+
+Bool XF86DRIQueryExtension( Display *dpy, int *event_base, int *error_base );
+
+Bool XF86DRIQueryVersion( Display *dpy, int *majorVersion, int *minorVersion,
+    int *patchVersion );
+
+Bool XF86DRIQueryDirectRenderingCapable( Display *dpy, int screen,
+    Bool *isCapable );
+
+Bool XF86DRIOpenConnection( Display *dpy, int screen, drm_handle_t *hSAREA,
+    char **busIDString );
+
+Bool XF86DRIAuthConnection( Display *dpy, int screen, drm_magic_t magic );
+
+Bool XF86DRICloseConnection( Display *dpy, int screen );
+
+Bool XF86DRIGetClientDriverName( Display *dpy, int screen,
+    int *ddxDriverMajorVersion, int *ddxDriverMinorVersion,
+    int *ddxDriverPatchVersion, char **clientDriverName );
+
+Bool XF86DRICreateContext( Display *dpy, int screen, Visual *visual,
+    XID *ptr_to_returned_context_id, drm_context_t *hHWContext );
+
+Bool XF86DRICreateContextWithConfig( Display *dpy, int screen, int configID,
+    XID *ptr_to_returned_context_id, drm_context_t *hHWContext );
+
+extern GLboolean XF86DRIDestroyContext( Display *dpy, int screen,
+    XID context_id );
+
+extern GLboolean XF86DRICreateDrawable( Display *dpy, int screen,
+    XID drawable, drm_drawable_t *hHWDrawable );
+
+extern GLboolean XF86DRIDestroyDrawable( Display *dpy, int screen, 
+    XID drawable);
+
+Bool XF86DRIGetDrawableInfo( Display *dpy, int screen, Drawable drawable,
+    unsigned int *index, unsigned int *stamp, 
+    int *X, int *Y, int *W, int *H,
+    int *numClipRects, drm_clip_rect_t ** pClipRects,
+    int *backX, int *backY,
+    int *numBackClipRects, drm_clip_rect_t **pBackClipRects );
+
+Bool XF86DRIGetDeviceInfo( Display *dpy, int screen,
+    drm_handle_t *hFrameBuffer, int *fbOrigin, int *fbSize,
+    int *fbStride, int *devPrivateSize, void **pDevPrivate );
+
+_XFUNCPROTOEND
+
+#endif /* _XF86DRI_SERVER_ */
+
+#endif /* _XF86DRI_H_ */
+
commit 7ffc68c5cc7108c9e56af25f9f9b4398f5b027df
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Wed Apr 23 17:45:54 2008 +0300

    xephyr: libGL is client lib

diff --git a/configure.ac b/configure.ac
index c1c10f7..21c1d91 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1917,6 +1917,10 @@ if test "$KDRIVE" = yes; then
     if test "x$XV" = xyes; then
         XEPHYR_REQUIRED_LIBS="$XEPHYR_REQUIRED_LIBS xv"
     fi
+    if test "x$DRI" = xyes && test "x$GLX" = xyes; then
+        XEPHYR_REQUIRED_LIBS="$XEPHYR_REQUIRED_LIBS gl libdrm"
+    fi
+
     PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS, [xephyr="yes"], [xephyr="no"])
     if test "x$XEPHYR" = xauto; then
         XEPHYR=$xephyr
@@ -1924,10 +1928,6 @@ if test "$KDRIVE" = yes; then
     XEPHYR_DRI=no
     if test x$XEPHYR = xyes -a x$DRI = xyes && test "x$GLX" = xyes; then
         XEPHYR_DRI=yes
-        XEPHYR_DRI_LIBS=-lGL
-        AC_SUBST(XEPHYR_DRI_LIBS)
-    fi
-    if test x$XEPHYR_DRI = xyes ; then
         AC_DEFINE(XEPHYR_DRI,1,[enable DRI extension in xephyr])
     fi
 
@@ -1965,9 +1965,6 @@ if test "$KDRIVE" = yes; then
     KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB"
     KDRIVE_LIBS="$TSLIB_LIBS $KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS $GLX_SYS_LIBS"
 
-    # check if we can build Xephyr
-    PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS, [xephyr="yes"], [xephyr="no"])
-
     AC_SUBST([XEPHYR_LIBS])
     AC_SUBST([XEPHYR_INCS])
     AC_SUBST([XSDL_LIBS])
diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index dc0144a..d13bbae 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -2,15 +2,11 @@ INCLUDES = 			\
 	@KDRIVE_INCS@		\
 	@KDRIVE_CFLAGS@		\
 	@XEPHYR_INCS@		\
+	@XEPHYR_CFLAGS@		\
+	@DRIPROTO_CFLAGS@	\
 	-I$(top_srcdir)		\
 	-I$(top_srcdir)/exa
 
-if XEPHYR_HAS_DRI
-INCLUDES +=			\
-	@LIBDRM_CFLAGS@		\
-	@DRIPROTO_CFLAGS@
-endif
-
 if XV
 LIBXEPHYR_HOSTXV=libxephyr-hostxv.a
 endif
@@ -76,9 +72,7 @@ Xephyr_LDADD = 						\
 	$(LIBXEPHYR_HOSTDRI)				\
 	$(top_builddir)/exa/libexa.la			\
 	@KDRIVE_LIBS@					\
-	@XEPHYR_LIBS@ 					\
-	@LIBDRM_LIBS@					\
-	@XEPHYR_DRI_LIBS@
+	@XEPHYR_LIBS@
 
 Xephyr_DEPENDENCIES =	\
 	libxephyr.a					\
commit a27c244d72603e27766ff3900ab28fe094f7397e
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Wed Apr 23 17:45:37 2008 +0300

    xephyr: Makefile cleanup 2

diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index f0182d5..dc0144a 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -23,19 +23,16 @@ noinst_LIBRARIES = libxephyr-hostx.a $(LIBXEPHYR_HOSTXV) $(LIBXEPHYR_HOSTDRI) li
 
 bin_PROGRAMS = Xephyr
 
-libxephyr_hostx_a_SOURCES =	\
+HOSTX_SRCS =			\
 	hostx.c			\
 	hostx.h
 
-if XV
-libxephyr_hostxv_a_SOURCES=	\
+HOSTVIDEO_SRCS =		\
 	ephyrvideo.c		\
 	ephyrhostvideo.c	\
 	ephyrhostvideo.h
-endif
 
-if XEPHYR_HAS_DRI
-libxephyr_hostdri_a_SOURCES=	\
+HOSTDRI_SRCS =			\
 	ephyrdriext.c		\
 	ephyrdriext.h		\
 	ephyrdri.c		\
@@ -45,15 +42,26 @@ libxephyr_hostdri_a_SOURCES=	\
 	ephyrglxext.h		\
 	ephyrhostglx.c		\
 	ephyrhostglx.h
-endif
 
-libxephyr_a_SOURCES =		\
+XEPHYR_SRCS =			\
 	ephyr.c			\
 	ephyr.h			\
 	ephyrlog.h		\
 	ephyr_draw.c		\
 	os.c
 
+libxephyr_hostx_a_SOURCES = $(HOSTX_SRCS)
+
+if XV
+libxephyr_hostxv_a_SOURCES = $(HOSTVIDEO_SRCS)
+endif
+
+if XEPHYR_HAS_DRI
+libxephyr_hostdri_a_SOURCES = $(HOSTDRI_SRCS)
+endif
+
+libxephyr_a_SOURCES = $(XEPHYR_SRCS)
+
 Xephyr_SOURCES = \
 	ephyrinit.c
 
@@ -81,3 +89,7 @@ Xephyr_DEPENDENCIES =	\
 
 relink:
 	rm -f $(bin_PROGRAMS) && make $(bin_PROGRAMS)
+
+EXTRA_DIST = \
+	$(HOSTVIDEO_SRCS) \
+	$(HOSTDRI_SRCS)
commit d4d19b2f22002b1579438cb9cf08dd580c7ec005
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Wed Apr 23 17:45:19 2008 +0300

    xephyr: Makefile cleanup 1

diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index 7ef22a3..f0182d5 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -1,68 +1,58 @@
-INCLUDES = 					\
-	@KDRIVE_INCS@				\
-	@KDRIVE_CFLAGS@				\
-	-I$(srcdir)/../../../exa
+INCLUDES = 			\
+	@KDRIVE_INCS@		\
+	@KDRIVE_CFLAGS@		\
+	@XEPHYR_INCS@		\
+	-I$(top_srcdir)		\
+	-I$(top_srcdir)/exa
+
+if XEPHYR_HAS_DRI
+INCLUDES +=			\
+	@LIBDRM_CFLAGS@		\
+	@DRIPROTO_CFLAGS@
+endif
 
 if XV
-    LIBXEPHYR_HOSTXV=libxephyr-hostxv.a
-else
-    LIBXEPHYR_HOSTXV=
+LIBXEPHYR_HOSTXV=libxephyr-hostxv.a
 endif
 
 if XEPHYR_HAS_DRI
-    LIBXEPHYR_HOSTDRI=libxephyr-hostdri.a
-else
-    LIBXEPHYR_HOSTDRI=
+LIBXEPHYR_HOSTDRI=libxephyr-hostdri.a
 endif
 
 noinst_LIBRARIES = libxephyr-hostx.a $(LIBXEPHYR_HOSTXV) $(LIBXEPHYR_HOSTDRI) libxephyr.a
 
 bin_PROGRAMS = Xephyr
 
-libxephyr_hostx_a_SOURCES =                             \
-	hostx.c                                         \
+libxephyr_hostx_a_SOURCES =	\
+	hostx.c			\
 	hostx.h
 
-libxephyr_hostxv_a_INCLUDES = @XEPHYR_INCS@
-
 if XV
-libxephyr_hostxv_a_SOURCES=				\
-	ephyrhostvideo.c \
+libxephyr_hostxv_a_SOURCES=	\
+	ephyrvideo.c		\
+	ephyrhostvideo.c	\
 	ephyrhostvideo.h
 endif
 
 if XEPHYR_HAS_DRI
-
-libxephyr_hostdri_a_SOURCES= \
-ephyrdriext.c	\
-ephyrdriext.h	\
-ephyrdri.c	\
-ephyrdri.h	\
-XF86dri.c	\
-ephyrglxext.c	\
-ephyrglxext.h	\
-ephyrhostglx.c	\
-ephyrhostglx.h	
-
-libxephyr_hostdri_a_CFLAGS= \
--I$(top_srcdir)		\
- at LIBDRM_CFLAGS@ 	\
- at DRIPROTO_CFLAGS@
-
+libxephyr_hostdri_a_SOURCES=	\
+	ephyrdriext.c		\
+	ephyrdriext.h		\
+	ephyrdri.c		\
+	ephyrdri.h		\
+	XF86dri.c		\
+	ephyrglxext.c		\
+	ephyrglxext.h		\
+	ephyrhostglx.c		\
+	ephyrhostglx.h
 endif
 
-libxephyr_a_SOURCES =	\
-	ephyr.c		\
-	ephyr_draw.c	\
-	ephyrvideo.c	\
-	os.c		\
-	hostx.h         \
-	ephyr.h		\
-	ephyrlog.h
-
-libxephyr_a_CFLAGS = \
--I$(top_srcdir) \
- at LIBDRM_CFLAGS@
+libxephyr_a_SOURCES =		\
+	ephyr.c			\
+	ephyr.h			\
+	ephyrlog.h		\
+	ephyr_draw.c		\
+	os.c
 
 Xephyr_SOURCES = \
 	ephyrinit.c
@@ -73,18 +63,18 @@ endif
 
 Xephyr_LDADD = 						\
 	libxephyr.a					\
-	libxephyr-hostx.a			        \
+	libxephyr-hostx.a				\
 	$(LIBXEPHYR_HOSTXV)				\
 	$(LIBXEPHYR_HOSTDRI)				\
-	../../../exa/libexa.la				\
+	$(top_builddir)/exa/libexa.la			\
 	@KDRIVE_LIBS@					\
-        @XEPHYR_LIBS@ 					\
+	@XEPHYR_LIBS@ 					\
 	@LIBDRM_LIBS@					\
 	@XEPHYR_DRI_LIBS@
 
 Xephyr_DEPENDENCIES =	\
 	libxephyr.a					\
-	libxephyr-hostx.a			        \
+	libxephyr-hostx.a				\
 	$(LIBXEPHYR_HOSTXV)				\
 	$(LIBXEPHYR_HOSTDRI)				\
 	@KDRIVE_LOCAL_LIBS@
commit cdc4571b580a8f4fd279404215bff0fb9a5b4816
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Sun Apr 20 17:06:26 2008 +0300

    drop TOGCUP remnants

diff --git a/configure.ac b/configure.ac
index aba4619..c1c10f7 100644
--- a/configure.ac
+++ b/configure.ac
@@ -547,7 +547,6 @@ AC_ARG_ENABLE(xcsecurity,     AS_HELP_STRING([--disable-xcsecurity], [Build Secu
 AC_ARG_ENABLE(xcalibrate,     AS_HELP_STRING([--enable-xcalibrate], [Build XCalibrate extension (default: disabled)]), [XCALIBRATE=$enableval], [XCALIBRATE=no])
 AC_ARG_ENABLE(tslib,          AS_HELP_STRING([--enable-tslib], [Build kdrive tslib touchscreen support (default: disabled)]), [TSLIB=$enableval], [TSLIB=no])
 AC_ARG_ENABLE(xevie,          AS_HELP_STRING([--disable-xevie], [Build XEvIE extension (default: enabled)]), [XEVIE=$enableval], [XEVIE=yes])
-AC_ARG_ENABLE(cup,            AS_HELP_STRING([--disable-cup], [Build TOG-CUP extension (default: enabled)]), [CUP=$enableval], [CUP=yes])
 AC_ARG_ENABLE(multibuffer,    AS_HELP_STRING([--enable-multibuffer], [Build Multibuffer extension (default: disabled)]), [MULTIBUFFER=$enableval], [MULTIBUFFER=no])
 AC_ARG_ENABLE(fontcache,      AS_HELP_STRING([--enable-fontcache], [Build FontCache extension (default: disabled)]), [FONTCACHE=$enableval], [FONTCACHE=no])
 AC_ARG_ENABLE(dbe,            AS_HELP_STRING([--disable-dbe], [Build DBE extension (default: enabled)]), [DBE=$enableval], [DBE=yes])
@@ -930,12 +929,6 @@ if test "x$XEVIE" = xyes; then
 	REQUIRED_MODULES="$REQUIRED_MODULES evieproto"
 fi
 
-AM_CONDITIONAL(CUP, [test "x$CUP" = xyes])
-if test "x$CUP" = xyes; then
-	AC_DEFINE(TOGCUP, 1, [Build TOG-CUP extension])
-	# Requires xextproto which is always required
-fi
-
 AM_CONDITIONAL(MULTIBUFFER, [test "x$MULTIBUFFER" = xyes])
 if test "x$MULTIBUFFER" = xyes; then
 	AC_DEFINE(MULTIBUFFER, 1, [Build Multibuffer extension])
commit 6cd9287aed3c128d9c10b9b042ba7b864143d522
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Sun Apr 20 16:58:51 2008 +0300

    drop EVI remnants

diff --git a/Xext/EVIstruct.h b/Xext/EVIstruct.h
deleted file mode 100644
index e658190..0000000
--- a/Xext/EVIstruct.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/************************************************************
-Copyright (c) 1997 by Silicon Graphics Computer Systems, Inc.
-Permission to use, copy, modify, and distribute this
-software and its documentation for any purpose and without
-fee is hereby granted, provided that the above copyright
-notice appear in all copies and that both that copyright
-notice and this permission notice appear in supporting
-documentation, and that the name of Silicon Graphics not be
-used in advertising or publicity pertaining to distribution
-of the software without specific prior written permission.
-Silicon Graphics makes no representation about the suitability
-of this software for any purpose. It is provided "as is"
-without any express or implied warranty.
-SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
-SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
-GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
-DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
-DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
-THE USE OR PERFORMANCE OF THIS SOFTWARE.
-********************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifndef EVI_STRUCT_H
-#define EVI_STRUCT_H
-
-/*
- ******************************************************************************
- ** Per-ddx data
- ******************************************************************************
- */
-
-typedef int (*GetVisualInfoProc)(
-	VisualID32*,
-	int,
-	xExtendedVisualInfo**,
-	int*,
-	VisualID32**,
-	int*
-);
-
-typedef void (*FreeVisualInfoProc)(
-    xExtendedVisualInfo*,
-    VisualID32*
-);
-typedef struct _EviPrivRec {
-    GetVisualInfoProc getVisualInfo;
-    FreeVisualInfoProc freeVisualInfo;
-} EviPrivRec, *EviPrivPtr;
-
-extern EviPrivPtr eviDDXInit(void);
-extern void eviDDXReset(void);
-
-#endif /* EVI_STRUCT_H */
commit a88c6b66465c039bf92a54a496516fee4d900784
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Fri Apr 18 17:47:16 2008 +0300

    glcore: drop GLcore (files)

diff --git a/GL/mesa/.gitignore b/GL/mesa/.gitignore
deleted file mode 100644
index 6b92b24..0000000
--- a/GL/mesa/.gitignore
+++ /dev/null
@@ -1,32 +0,0 @@
-X/drivers
-X/glxheader.h
-X/xm*.h
-X/xm*.c
-mesa/drivers
-mesa/glxheader.h
-mesa/xm*.c
-glapi/*.c
-glapi/*.h
-main/*.c
-main/*.h
-math/*.c
-math/*.h
-ppc
-shader/*.c
-shader/*.h
-shader/slang/*.c
-shader/slang/*.h
-shader/slang/library
-shader/grammar/*.c
-shader/grammar/*.h
-sparc
-swrast/*.c
-swrast/*.h
-swrast_setup/*.c
-swrast_setup/*.h
-tnl/*.c
-tnl/*.h
-x86
-x86-64
-vbo/*.c
-vbo/*.h
diff --git a/GL/mesa/Makefile.am b/GL/mesa/Makefile.am
deleted file mode 100644
index 7f27c58..0000000
--- a/GL/mesa/Makefile.am
+++ /dev/null
@@ -1,18 +0,0 @@
-SUBDIRS = X
-SUBDIRS += main math swrast swrast_setup tnl shader glapi vbo
-
-noinst_LTLIBRARIES = libGLcore.la
-
-libGLcore_la_SOURCES = dummy.c
-MESA_LIBS           = main/libmain.la \
-                      math/libmath.la \
-                      swrast/libswrast.la \
-                      swrast_setup/libss.la \
-                      tnl/libtnl.la \
-                      shader/libshader.la \
-		      shader/grammar/libgrammar.la \
-		      shader/slang/libslang.la \
-                      vbo/libvbo.la
-
-libGLcore_la_LIBADD = $(MESA_LIBS) \
-                      X/libX.la
diff --git a/GL/mesa/X/Makefile.am b/GL/mesa/X/Makefile.am
deleted file mode 100644
index d8abbc6..0000000
--- a/GL/mesa/X/Makefile.am
+++ /dev/null
@@ -1,27 +0,0 @@
-noinst_LTLIBRARIES = libX.la
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I. \
-           -I at MESA_SOURCE@/src/mesa/glapi \
-           -I at MESA_SOURCE@/src/mesa/main \
-           -I at MESA_SOURCE@/src/mesa
-
-# -DXFree86Server is required because the X11 driver in Mesa thinks that
-# symbol means "being built in the server"
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-XM_SOURCES = \
-	xm_api.c \
-	xm_buffer.c \
-	xm_dd.c \
-	xm_image.c \
-	xm_line.c \
-	xm_span.c \
-	xm_tri.c
-
-XM_SOURCES += drivers/common/driverfuncs.c
-
-nodist_libX_la_SOURCES = $(XM_SOURCES)
diff --git a/GL/mesa/dummy.c b/GL/mesa/dummy.c
deleted file mode 100644
index e69de29..0000000
diff --git a/GL/mesa/glapi/Makefile.am b/GL/mesa/glapi/Makefile.am
deleted file mode 100644
index db79114..0000000
--- a/GL/mesa/glapi/Makefile.am
+++ /dev/null
@@ -1,20 +0,0 @@
-noinst_LTLIBRARIES = libglapi.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libglapi_la_SOURCES = glapi.c glthread.c
diff --git a/GL/mesa/main/Makefile.am b/GL/mesa/main/Makefile.am
deleted file mode 100644
index f8ce137..0000000
--- a/GL/mesa/main/Makefile.am
+++ /dev/null
@@ -1,86 +0,0 @@
-noinst_LTLIBRARIES = libmain.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-if NEED_VSNPRINTF
-VSNPRINTF_SOURCES = vsnprintf.c
-endif
-
-nodist_libmain_la_SOURCES = accum.c \
-                    api_arrayelt.c \
-                    api_loopback.c \
-                    api_noop.c \
-                    api_validate.c \
-                    arrayobj.c \
-                    attrib.c \
-                    blend.c \
-                    bufferobj.c \
-                    buffers.c \
-                    clip.c \
-                    colortab.c \
-                    context.c \
-                    convolve.c \
-                    debug.c \
-                    depth.c \
-		    depthstencil.c \
-                    dlist.c \
-                    drawpix.c \
-                    enable.c \
-                    enums.c \
-                    eval.c \
-                    execmem.c \
-                    extensions.c \
-                    fbobject.c \
-                    feedback.c \
-                    fog.c \
-                    framebuffer.c \
-                    get.c \
-                    getstring.c \
-                    hash.c \
-                    hint.c \
-                    histogram.c \
-                    image.c \
-                    imports.c \
-                    light.c \
-                    lines.c \
-                    matrix.c \
-                    mipmap.c \
-                    mm.c \
-                    pixel.c \
-                    points.c \
-                    polygon.c \
-		    queryobj.c \
-                    rastpos.c \
-                    rbadaptors.c \
-                    renderbuffer.c \
-                    shaders.c \
-                    state.c \
-                    stencil.c \
-                    texcompress.c \
-                    texcompress_fxt1.c \
-                    texcompress_s3tc.c \
-                    texenvprogram.c \
-                    texformat.c \
-                    teximage.c \
-                    texobj.c \
-                    texrender.c \
-                    texstate.c \
-                    texstore.c \
-                    varray.c \
-                    $(VSNPRINTF_SOURCES) \
-                    vtxfmt.c
diff --git a/GL/mesa/math/Makefile.am b/GL/mesa/math/Makefile.am
deleted file mode 100644
index c7c5642..0000000
--- a/GL/mesa/math/Makefile.am
+++ /dev/null
@@ -1,27 +0,0 @@
-noinst_LTLIBRARIES = libmath.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libmath_la_SOURCES = m_debug_clip.c \
-                       m_debug_norm.c \
-                       m_debug_xform.c \
-                       m_eval.c \
-                       m_matrix.c \
-                       m_translate.c \
-                       m_vector.c \
-                       m_xform.c
diff --git a/GL/mesa/shader/Makefile.am b/GL/mesa/shader/Makefile.am
deleted file mode 100644
index abde275..0000000
--- a/GL/mesa/shader/Makefile.am
+++ /dev/null
@@ -1,39 +0,0 @@
-SUBDIRS = grammar slang
-
-noinst_LTLIBRARIES = libshader.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-	   -I../shader/grammar \
-	   -I../shader/slang \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libshader_la_SOURCES = \
-                      arbprogparse.c \
-                      arbprogram.c \
-                      atifragshader.c \
-                      nvfragparse.c \
-                      nvprogram.c \
-                      nvvertparse.c \
-                      prog_debug.c \
-                      prog_execute.c \
-                      prog_instruction.c \
-                      prog_parameter.c \
-                      prog_print.c \
-                      program.c \
-                      programopt.c \
-                      prog_statevars.c \
-                      shader_api.c
diff --git a/GL/mesa/shader/grammar/Makefile.am b/GL/mesa/shader/grammar/Makefile.am
deleted file mode 100644
index 332c8e9..0000000
--- a/GL/mesa/shader/grammar/Makefile.am
+++ /dev/null
@@ -1,20 +0,0 @@
-noinst_LTLIBRARIES = libgrammar.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../../X \
-           -I../../glapi \
-           -I../../main \
-           -I../../math \
-           -I../../shader \
-           -I../../swrast \
-           -I../../swrast_setup \
-           -I../../tnl \
-           -I../.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libgrammar_la_SOURCES = grammar_mesa.c
diff --git a/GL/mesa/shader/slang/Makefile.am b/GL/mesa/shader/slang/Makefile.am
deleted file mode 100644
index 71498ee..0000000
--- a/GL/mesa/shader/slang/Makefile.am
+++ /dev/null
@@ -1,41 +0,0 @@
-noinst_LTLIBRARIES = libslang.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../grammar \
-           -I../../X \
-           -I../../glapi \
-           -I../../main \
-           -I../../math \
-           -I../../shader \
-           -I../../swrast \
-           -I../../swrast_setup \
-           -I../../tnl \
-           -I../.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libslang_la_SOURCES = slang_builtin.c \
-		      slang_codegen.c \
-		      slang_compile.c \
-		      slang_compile_function.c \
-		      slang_compile_operation.c \
-		      slang_compile_struct.c \
-		      slang_compile_variable.c \
-		      slang_emit.c \
-		      slang_ir.c \
-		      slang_label.c \
-		      slang_library_noise.c \
-		      slang_link.c \
-		      slang_log.c \
-		      slang_mem.c \
-		      slang_preprocess.c \
-		      slang_print.c \
-		      slang_simplify.c \
-		      slang_storage.c \
-		      slang_typeinfo.c \
-		      slang_utility.c \
-		      slang_vartable.c
diff --git a/GL/mesa/swrast/Makefile.am b/GL/mesa/swrast/Makefile.am
deleted file mode 100644
index bffb1e7..0000000
--- a/GL/mesa/swrast/Makefile.am
+++ /dev/null
@@ -1,50 +0,0 @@
-noinst_LTLIBRARIES = libswrast.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../shader/slang \
-	   -I../shader/slang \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libswrast_la_SOURCES = s_aaline.c \
-                      s_aatriangle.c \
-                      s_accum.c \
-                      s_alpha.c \
-                      s_atifragshader.c \
-                      s_bitmap.c \
-                      s_blend.c \
-                      s_blit.c \
-                      s_buffers.c \
-                      s_context.c \
-                      s_copypix.c \
-                      s_depth.c \
-                      s_drawpix.c \
-                      s_feedback.c \
-                      s_fog.c \
-		      s_fragprog.c \
-                      s_imaging.c \
-                      s_lines.c \
-                      s_logic.c \
-                      s_masking.c \
-                      s_points.c \
-                      s_readpix.c \
-                      s_span.c \
-                      s_stencil.c \
-		      s_texcombine.c \
-		      s_texfilter.c \
-                      s_texstore.c \
-                      s_triangle.c \
-                      s_zoom.c
diff --git a/GL/mesa/swrast_setup/Makefile.am b/GL/mesa/swrast_setup/Makefile.am
deleted file mode 100644
index 1f3c031..0000000
--- a/GL/mesa/swrast_setup/Makefile.am
+++ /dev/null
@@ -1,20 +0,0 @@
-noinst_LTLIBRARIES = libss.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libss_la_SOURCES = ss_context.c ss_triangle.c
diff --git a/GL/mesa/tnl/Makefile.am b/GL/mesa/tnl/Makefile.am
deleted file mode 100644
index b3c8206..0000000
--- a/GL/mesa/tnl/Makefile.am
+++ /dev/null
@@ -1,37 +0,0 @@
-noinst_LTLIBRARIES = libtnl.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../shader/slang \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libtnl_la_SOURCES = t_context.c \
-                      t_draw.c \
-                      t_pipeline.c \
-                      t_vb_cull.c \
-                      t_vb_fog.c \
-                      t_vb_light.c \
-                      t_vb_normals.c \
-                      t_vb_points.c \
-                      t_vb_program.c \
-                      t_vb_render.c \
-                      t_vb_texgen.c \
-                      t_vb_texmat.c \
-                      t_vb_vertex.c \
-                      t_vertex.c \
-                      t_vertex_generic.c \
-                      t_vertex_sse.c \
-                      t_vp_build.c
diff --git a/GL/mesa/vbo/Makefile.am b/GL/mesa/vbo/Makefile.am
deleted file mode 100644
index 9943f2a..0000000
--- a/GL/mesa/vbo/Makefile.am
+++ /dev/null
@@ -1,35 +0,0 @@
-noinst_LTLIBRARIES = libvbo.la
-
-AM_CFLAGS = \
-	$(DIX_CFLAGS) \
-	-DXFree86Server \
-	@GLX_DEFINES@
-
-INCLUDES = -I at MESA_SOURCE@/include \
-           -I../X \
-           -I../glapi \
-           -I../main \
-           -I../math \
-           -I../shader \
-           -I../shader/slang \
-	   -I../shader/slang \
-           -I../swrast \
-           -I../swrast_setup \
-           -I../tnl \
-           -I.. \
-           -I$(top_srcdir)/hw/xfree86/os-support
-
-nodist_libvbo_la_SOURCES = vbo_context.c \
-			vbo_exec_api.c \
-			vbo_exec_array.c \
-			vbo_exec.c \
-			vbo_exec_draw.c \
-			vbo_exec_eval.c \
-			vbo_rebase.c \
-			vbo_save_api.c \
-			vbo_save.c \
-			vbo_save_draw.c \
-			vbo_save_loopback.c \
-			vbo_split.c \
-			vbo_split_copy.c \
-			vbo_split_inplace.c
diff --git a/GL/symlink-mesa.sh b/GL/symlink-mesa.sh
index d611fcf..8deaa43 100755
--- a/GL/symlink-mesa.sh
+++ b/GL/symlink-mesa.sh
@@ -58,169 +58,6 @@ main() {
 
 ## actual symlinking
 
-symlink_mesa_glapi() {
-    src_dir src/mesa/glapi
-    dst_dir mesa/glapi
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_main() {
-    src_dir src/mesa/main
-    dst_dir mesa/main
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_math() {
-    src_dir src/mesa/math
-    dst_dir mesa/math
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_swrast() {
-    src_dir src/mesa/swrast
-    dst_dir mesa/swrast
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_ss() {
-    src_dir src/mesa/swrast_setup
-    dst_dir mesa/swrast_setup
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_tnl() {
-    src_dir src/mesa/tnl
-    dst_dir mesa/tnl
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_shader() {
-    src_dir src/mesa/shader
-    dst_dir mesa/shader
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_shader_grammar() {
-    src_dir src/mesa/shader/grammar
-    dst_dir mesa/shader/grammar
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_shader_slang() {
-    src_dir src/mesa/shader/slang
-    dst_dir mesa/shader/slang
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_shader_slang_library() {
-    src_dir src/mesa/shader/slang/library
-    dst_dir mesa/shader/slang/library
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}        
-
-symlink_mesa_vbo() {
-    src_dir src/mesa/vbo
-    dst_dir mesa/vbo
-
-    for src in $REAL_SRC_DIR/*.c $REAL_SRC_DIR/*.h; do
-        action `basename $src`
-    done
-}
-
-symlink_mesa_x() {
-    src_dir src/mesa/drivers/x11
-    dst_dir mesa/X
-
-    # action glxapi.h
-    action glxheader.h
-    # action realglx.h
-    # action xfonts.h
-    action xm_api.c
-    action xm_buffer.c
-    action xm_dd.c
-    action xm_image.c
-    action xm_image.h
-    action xm_line.c
-    action xm_span.c
-    action xm_tri.c
-    action xmesaP.h
-
-    # another hack
-    src_dir src/mesa/drivers/common
-    dst_dir mesa/X/drivers/common
-    action driverfuncs.c
-    action driverfuncs.h
-}
-
-symlink_mesa_ppc() {
-    src_dir src/mesa/ppc
-    dst_dir mesa/ppc
-}
-
-symlink_mesa_sparc() {
-    src_dir src/mesa/sparc
-    dst_dir mesa/sparc
-}
-
-symlink_mesa_x86() {
-    src_dir src/mesa/x86
-    dst_dir mesa/x86
-}
-
-symlink_mesa_x8664() {
-    src_dir src/mesa/x86-64
-    dst_dir mesa/x86-64
-}
-
-symlink_mesa() {
-    symlink_mesa_main
-    symlink_mesa_math
-    symlink_mesa_swrast
-    symlink_mesa_ss
-    symlink_mesa_tnl
-    symlink_mesa_shader
-    symlink_mesa_shader_grammar
-    symlink_mesa_shader_slang
-    symlink_mesa_shader_slang_library
-    symlink_mesa_x
-    symlink_mesa_glapi
-    symlink_mesa_ppc
-    symlink_mesa_sparc
-    symlink_mesa_vbo
-    symlink_mesa_x86
-    symlink_mesa_x8664
-}
-
 symlink_glx() {
     # this is... unpleasant
     src_dir src/glx/x11
diff --git a/hw/xfree86/dixmods/GLcoremodule.c b/hw/xfree86/dixmods/GLcoremodule.c
deleted file mode 100644
index d55cb78..0000000
--- a/hw/xfree86/dixmods/GLcoremodule.c
+++ /dev/null
@@ -1,63 +0,0 @@
-/**************************************************************************
-
-Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
-All Rights Reserved.
-
-Permission is hereby granted, free of charge, to any person obtaining a
-copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sub license, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice (including the
-next paragraph) shall be included in all copies or substantial portions
-of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
-IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
-ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-**************************************************************************/
-
-/*
- * Authors:
- *   Kevin E. Martin <kevin at precisioninsight.com>
- *
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include "xf86Module.h"
-
-static MODULESETUPPROTO(GLcoreSetup);
-
-static XF86ModuleVersionInfo VersRec =
-{
-        "GLcore",
-        MODULEVENDORSTRING,
-        MODINFOSTRING1,
-        MODINFOSTRING2,
-        XORG_VERSION_CURRENT,
-        1, 0, 0,
-        ABI_CLASS_EXTENSION,
-        ABI_EXTENSION_VERSION,
-        MOD_CLASS_NONE,
-        {0,0,0,0}
-};
-
-_X_EXPORT XF86ModuleData GLcoreModuleData = { &VersRec, GLcoreSetup, NULL };
-
-static pointer
-GLcoreSetup(pointer module, pointer opts, int *errmaj, int *errmin)
-{
-    /* Need a non-NULL return value to indicate success */
-    return (pointer)1;
-}
commit dd7a53f8f21e41e1ab43f7e684ba586abc97ef7e
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Fri Apr 18 17:47:01 2008 +0300

    glcore: drop GLcore (build system)

diff --git a/GL/Makefile.am b/GL/Makefile.am
index 29d03f2..44fca18 100644
--- a/GL/Makefile.am
+++ b/GL/Makefile.am
@@ -2,8 +2,8 @@ if XQUARTZ
 XQUARTZ_SUBDIRS = apple
 endif
 
-SUBDIRS = glx mesa $(XQUARTZ_SUBDIRS)
-DIST_SUBDIRS = glx mesa apple
+SUBDIRS = glx $(XQUARTZ_SUBDIRS)
+DIST_SUBDIRS = glx apple
 
 WINDOWS_EXTRAS = \
 	windows/ChangeLog \
diff --git a/GL/symlink-mesa.sh b/GL/symlink-mesa.sh
index 47afdcd..d611fcf 100755
--- a/GL/symlink-mesa.sh
+++ b/GL/symlink-mesa.sh
@@ -267,7 +267,6 @@ run() {
     # $1 what to do
     # $2 explanation
 
-    ACTION=$1 EXPLANATION=$2 run_module mesa
     ACTION=$1 EXPLANATION=$2 run_module glx
 }
 
diff --git a/configure.ac b/configure.ac
index 5da56b5..aba4619 100644
--- a/configure.ac
+++ b/configure.ac
@@ -837,7 +837,7 @@ if test "x$GLX" = xyes && ! test "x$MESA_SOURCE" = x; then
 	PKG_CHECK_MODULES([GL], [glproto >= 1.4.9])
 	AC_SUBST(XLIB_CFLAGS)
 	AC_DEFINE(GLXEXT, 1, [Build GLX extension])
-	GLX_LIBS='$(top_builddir)/GL/glx/libglx.la $(top_builddir)/GL/mesa/libGLcore.la'
+	GLX_LIBS='$(top_builddir)/GL/glx/libglx.la'
 	test -d GL || mkdir GL
 	case $host_os in
 	  solaris*) 	
@@ -2105,18 +2105,6 @@ Makefile
 GL/Makefile
 GL/apple/Makefile
 GL/glx/Makefile
-GL/mesa/Makefile
-GL/mesa/glapi/Makefile
-GL/mesa/main/Makefile
-GL/mesa/math/Makefile
-GL/mesa/shader/Makefile
-GL/mesa/shader/grammar/Makefile
-GL/mesa/shader/slang/Makefile
-GL/mesa/swrast/Makefile
-GL/mesa/swrast_setup/Makefile
-GL/mesa/tnl/Makefile
-GL/mesa/vbo/Makefile
-GL/mesa/X/Makefile
 include/Makefile
 afb/Makefile
 composite/Makefile
diff --git a/hw/xfree86/dixmods/Makefile.am b/hw/xfree86/dixmods/Makefile.am
index 67967c5..beff9b1 100644
--- a/hw/xfree86/dixmods/Makefile.am
+++ b/hw/xfree86/dixmods/Makefile.am
@@ -3,7 +3,7 @@ noinst_LTLIBRARIES = libdixmods.la libxorgxkb.la
 SUBDIRS = extmod
 
 if GLX
-GLXMODS = libglx.la libGLcore.la
+GLXMODS = libglx.la
 endif
 
 if XTRAP
@@ -48,10 +48,6 @@ INCLUDES = @XORG_INCS@ \
            -I$(top_srcdir)/miext/shadow \
            -I$(top_srcdir)/GL/glx
 
-libGLcore_la_LDFLAGS = -avoid-version
-libGLcore_la_LIBADD = $(top_builddir)/GL/mesa/libGLcore.la
-libGLcore_la_SOURCES = GLcoremodule.c
-
 libafb_la_LDFLAGS = -avoid-version
 libafb_la_LIBADD = $(top_builddir)/afb/libafb.la
 libafb_la_SOURCES = afbmodule.c
commit 567d389d47dee233a973b101e04ce41c47a68f34
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Fri Apr 18 17:46:18 2008 +0300

    glcore: build from mesa, dlopen from xorg
    
    * The GLcore interface is disposable
    * GLcore is installed in DRI_DRIVER_INSTALL_DIR which is overloaded for
      GLX_PROVIDER_INSTALL_DIR

diff --git a/GL/glx/glxglcore.c b/GL/glx/glxglcore.c
index c8a2514..dafa9bc 100644
--- a/GL/glx/glxglcore.c
+++ b/GL/glx/glxglcore.c
@@ -37,7 +37,9 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #endif
 
 #include <string.h>
+#include <dlfcn.h>
 
+#define _NEED_GL_CORE_IF
 #include <GL/xmesa.h>
 #include <GL/internal/glcore.h>
 #include <glxserver.h>
@@ -48,6 +50,22 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 #include "os.h"
 
+#define XMesaCreateVisual       (*glcore->XMesaCreateVisual)
+#define XMesaDestroyVisual      (*glcore->XMesaDestroyVisual)
+
+#define XMesaCreateWindowBuffer (*glcore->XMesaCreateWindowBuffer)
+#define XMesaCreatePixmapBuffer (*glcore->XMesaCreatePixmapBuffer)
+#define XMesaDestroyBuffer      (*glcore->XMesaDestroyBuffer)
+#define XMesaSwapBuffers        (*glcore->XMesaSwapBuffers)
+#define XMesaResizeBuffers      (*glcore->XMesaResizeBuffers)
+
+#define XMesaCreateContext      (*glcore->XMesaCreateContext)
+#define XMesaDestroyContext     (*glcore->XMesaDestroyContext)
+#define XMesaCopyContext        (*glcore->XMesaCopyContext)
+#define XMesaMakeCurrent2       (*glcore->XMesaMakeCurrent2)
+#define XMesaForceCurrent       (*glcore->XMesaForceCurrent)
+#define XMesaLoseCurrent        (*glcore->XMesaLoseCurrent)
+
 typedef struct __GLXMESAscreen   __GLXMESAscreen;
 typedef struct __GLXMESAcontext  __GLXMESAcontext;
 typedef struct __GLXMESAdrawable __GLXMESAdrawable;
@@ -55,8 +73,11 @@ typedef struct __GLXMESAdrawable __GLXMESAdrawable;
 struct __GLXMESAscreen {
     __GLXscreen   base;
     int           index;
-    int		  num_vis;
+    int           num_vis;
     XMesaVisual  *xm_vis;
+    void         *driver;
+
+    const __GLcoreModule *glcore;
 };
 
 struct __GLXMESAcontext {
@@ -65,8 +86,9 @@ struct __GLXMESAcontext {
 };
 
 struct __GLXMESAdrawable {
-    __GLXdrawable base;
-    XMesaBuffer   xm_buf;
+    __GLXdrawable    base;
+    XMesaBuffer      xm_buf;
+    __GLXMESAscreen *screen;
 };
 
 static XMesaVisual find_mesa_visual(__GLXscreen *screen, XID fbconfigID);
@@ -76,6 +98,7 @@ static void
 __glXMesaDrawableDestroy(__GLXdrawable *base)
 {
     __GLXMESAdrawable *glxPriv = (__GLXMESAdrawable *) base;
+    const __GLcoreModule *glcore = glxPriv->screen->glcore;
 
     if (glxPriv->xm_buf != NULL)
       XMesaDestroyBuffer(glxPriv->xm_buf);
@@ -86,6 +109,7 @@ static GLboolean
 __glXMesaDrawableResize(__GLXdrawable *base)
 {
     __GLXMESAdrawable *glxPriv = (__GLXMESAdrawable *) base;
+    const __GLcoreModule *glcore = glxPriv->screen->glcore;
 
     XMesaResizeBuffers(glxPriv->xm_buf);
 
@@ -96,6 +120,7 @@ static GLboolean
 __glXMesaDrawableSwapBuffers(__GLXdrawable *base)
 {
     __GLXMESAdrawable *glxPriv = (__GLXMESAdrawable *) base;
+    const __GLcoreModule *glcore = glxPriv->screen->glcore;
 
     /* This is terrifying: XMesaSwapBuffers() ends up calling CopyArea
      * to do the buffer swap, but this assumes that the server holds
@@ -121,6 +146,8 @@ __glXMesaScreenCreateDrawable(__GLXscreen *screen,
 			      XID drawId,
 			      __GLXconfig *modes)
 {
+    __GLXMESAscreen *mesaScreen = (__GLXMESAscreen *) screen;
+    const __GLcoreModule *glcore = mesaScreen->glcore;
     __GLXMESAdrawable *glxPriv;
     XMesaVisual xm_vis;
 
@@ -130,6 +157,7 @@ __glXMesaScreenCreateDrawable(__GLXscreen *screen,
 
     memset(glxPriv, 0, sizeof *glxPriv);
 
+    glxPriv->screen = mesaScreen;
     if (!__glXDrawableInit(&glxPriv->base, screen,
 			   pDraw, type, drawId, modes)) {
         xfree(glxPriv);
@@ -166,6 +194,8 @@ static void
 __glXMesaContextDestroy(__GLXcontext *baseContext)
 {
     __GLXMESAcontext *context = (__GLXMESAcontext *) baseContext;
+    __GLXMESAscreen *screen = (__GLXMESAscreen *) context->base.pGlxScreen;
+    const __GLcoreModule *glcore = screen->glcore;
 
     XMesaDestroyContext(context->xmesa);
     __glXContextDestroy(&context->base);
@@ -179,6 +209,8 @@ __glXMesaContextMakeCurrent(__GLXcontext *baseContext)
     __GLXMESAcontext *context = (__GLXMESAcontext *) baseContext;
     __GLXMESAdrawable *drawPriv = (__GLXMESAdrawable *) context->base.drawPriv;
     __GLXMESAdrawable *readPriv = (__GLXMESAdrawable *) context->base.readPriv;
+    __GLXMESAscreen *screen = (__GLXMESAscreen *) context->base.pGlxScreen;
+    const __GLcoreModule *glcore = screen->glcore;
 
     return XMesaMakeCurrent2(context->xmesa,
 			     drawPriv->xm_buf,
@@ -189,6 +221,8 @@ static int
 __glXMesaContextLoseCurrent(__GLXcontext *baseContext)
 {
     __GLXMESAcontext *context = (__GLXMESAcontext *) baseContext;
+    __GLXMESAscreen *screen = (__GLXMESAscreen *) context->base.pGlxScreen;
+    const __GLcoreModule *glcore = screen->glcore;
 
     return XMesaLoseCurrent(context->xmesa);
 }
@@ -200,6 +234,8 @@ __glXMesaContextCopy(__GLXcontext *baseDst,
 {
     __GLXMESAcontext *dst = (__GLXMESAcontext *) baseDst;
     __GLXMESAcontext *src = (__GLXMESAcontext *) baseSrc;
+    __GLXMESAscreen *screen = (__GLXMESAscreen *) dst->base.pGlxScreen;
+    const __GLcoreModule *glcore = screen->glcore;
 
     return XMesaCopyContext(src->xmesa, dst->xmesa, mask);
 }
@@ -208,6 +244,8 @@ static int
 __glXMesaContextForceCurrent(__GLXcontext *baseContext)
 {
     __GLXMESAcontext *context = (__GLXMESAcontext *) baseContext;
+    __GLXMESAscreen *screen = (__GLXMESAscreen *) context->base.pGlxScreen;
+    const __GLcoreModule *glcore = screen->glcore;
 
     /* GlxSetRenderTables() call for XGL moved in XMesaForceCurrent() */
 
@@ -219,6 +257,8 @@ __glXMesaScreenCreateContext(__GLXscreen *screen,
 			     __GLXconfig *config,
 			     __GLXcontext *baseShareContext)
 {
+    __GLXMESAscreen *mesaScreen = (__GLXMESAscreen *) screen;
+    const __GLcoreModule *glcore = mesaScreen->glcore;
     __GLXMESAcontext *context;
     __GLXMESAcontext *shareContext = (__GLXMESAcontext *) baseShareContext;
     XMesaVisual xm_vis;
@@ -261,6 +301,7 @@ static void
 __glXMesaScreenDestroy(__GLXscreen *screen)
 {
     __GLXMESAscreen *mesaScreen = (__GLXMESAscreen *) screen;
+    const __GLcoreModule *glcore = mesaScreen->glcore;
     int i;
 
     if (mesaScreen->xm_vis) {
@@ -272,6 +313,8 @@ __glXMesaScreenDestroy(__GLXscreen *screen)
 	xfree(mesaScreen->xm_vis);
     }
 
+    dlclose(mesaScreen->driver);
+
     __glXScreenDestroy(screen);
 
     xfree(screen);
@@ -373,6 +416,7 @@ createFBConfigs(__GLXscreen *pGlxScreen, ScreenPtr pScreen)
 static void
 createMesaVisuals(__GLXMESAscreen *pMesaScreen)
 {
+    const __GLcoreModule *glcore = pMesaScreen->glcore;
     __GLXconfig *config;
     ScreenPtr pScreen;
     VisualPtr visual = NULL;
@@ -409,15 +453,35 @@ createMesaVisuals(__GLXMESAscreen *pMesaScreen)
     }
 }
 
+static const char dri_driver_path[] = DRI_DRIVER_PATH;
+
 static __GLXscreen *
 __glXMesaScreenProbe(ScreenPtr pScreen)
 {
     __GLXMESAscreen *screen;
+    char filename[128];
 
     screen = xalloc(sizeof *screen);
     if (screen == NULL)
 	return NULL;
 
+    snprintf(filename, sizeof filename, "%s/%s.so",
+             dri_driver_path, "libGLcore");
+
+    screen->driver = dlopen(filename, RTLD_LAZY | RTLD_LOCAL);
+    if (screen->driver == NULL) {
+        LogMessage(X_ERROR, "GLX error: dlopen of %s failed (%s)\n",
+                   filename, dlerror());
+        goto handle_error;
+    }
+
+    screen->glcore = dlsym(screen->driver, __GL_CORE);
+    if (screen->glcore == NULL) {
+        LogMessage(X_ERROR, "GLX error: dlsym for %s failed (%s)\n",
+                   __GL_CORE, dlerror());
+        goto handle_error;
+    }
+
     /*
      * Find the GLX visuals that are supported by this screen and create
      * XMesa's visuals.
@@ -435,7 +499,20 @@ __glXMesaScreenProbe(ScreenPtr pScreen)
     screen->base.swapInterval  = NULL;
     screen->base.pScreen       = pScreen;
 
+    LogMessage(X_INFO, "GLX: Loaded and initialized %s\n", filename);
+
     return &screen->base;
+
+handle_error:
+
+    if (screen->driver)
+        dlclose(screen->driver);
+
+    xfree(screen);
+
+    FatalError("GLX: could not load software renderer\n");
+
+    return NULL;
 }
 
 __GLXprovider __glXMesaProvider = {
diff --git a/hw/xfree86/dixmods/glxmodule.c b/hw/xfree86/dixmods/glxmodule.c
index a1a0886..88091cd 100644
--- a/hw/xfree86/dixmods/glxmodule.c
+++ b/hw/xfree86/dixmods/glxmodule.c
@@ -72,37 +72,6 @@ static XF86ModuleVersionInfo VersRec =
 
 _X_EXPORT XF86ModuleData glxModuleData = { &VersRec, glxSetup, NULL };
 
-/* We do a little proxy dance here, so we can avoid loading GLcore
- * unless we really need to.*/
-
-static pointer glxModule;
-
-static __GLXscreen *
-__glXMesaProxyScreenProbe(ScreenPtr pScreen)
-{
-  pointer GLcore;
-  static __GLXprovider *provider;
-
-  if (provider == NULL) {
-    GLcore = LoadSubModule(glxModule, "GLcore", NULL, NULL, NULL, NULL, 
-			   NULL, NULL);
-    if (GLcore == NULL)
-      return NULL;
-
-    provider = LoaderSymbol("__glXMesaProvider");
-    if (provider == NULL)
-      return NULL;
-  }
-
-  return provider->screenProbe(pScreen);
-}
-
-static __GLXprovider __glXMesaProxyProvider = {
-    __glXMesaProxyScreenProbe,
-    "MESA-PROXY",
-    NULL
-};
-
 static pointer
 glxSetup(pointer module, pointer opts, int *errmaj, int *errmin)
 {
@@ -116,8 +85,10 @@ glxSetup(pointer module, pointer opts, int *errmaj, int *errmin)
 
     setupDone = TRUE;
 
-    glxModule = module;
-    GlxPushProvider(&__glXMesaProxyProvider);
+    provider = LoaderSymbol("__glXMesaProvider");
+    if (provider == NULL)
+	return NULL;
+    GlxPushProvider(provider);
 
     xf86Msg(xf86Info.aiglxFrom, "AIGLX %s\n", 
 	    xf86Info.aiglx ? "enabled" : "disabled");
commit efb723e166e5fa89e90c7b400fb4c7979b1f50c0
Author: George Sapountzis <gsap7 at yahoo.gr>
Date:   Fri Apr 18 17:45:53 2008 +0300

    glcore: prepare for dynamic loading
    
    glcore gets linked with -ldl, -lpthread for s3tc and glapi
    xserver needs
            DLOPEN_LIBS - to dlopen the glcore dso
            LD_EXPORT_SYMBOLS_FLAG - to export symbols for glcore to use
    
    the ld flag is added to kdrive only when GLX is enabled, the net overhead for
    Xephyr is ~155KB, could be reduced with --dynamic-list.

diff --git a/configure.ac b/configure.ac
index 995a652..5da56b5 100644
--- a/configure.ac
+++ b/configure.ac
@@ -848,6 +848,7 @@ if test "x$GLX" = xyes && ! test "x$MESA_SOURCE" = x; then
 	if test $? -ne 0; then
 		AC_MSG_ERROR([Failed to link Mesa source tree.  Please specify a proper path to Mesa sources, or disable GLX.])
 	fi
+	GLX_SYS_LIBS="$GLX_SYS_LIBS $DLOPEN_LIBS"
 else
         GLX=no
 fi
@@ -1969,7 +1970,7 @@ if test "$KDRIVE" = yes; then
     KDRIVE_LOCAL_LIBS="$DIX_LIB $KDRIVE_LIB $KDRIVE_STUB_LIB $CONFIG_LIB"
     KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $FB_LIB $MI_LIB $KDRIVE_PURE_LIBS"
     KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB"
-    KDRIVE_LIBS="$TSLIB_LIBS $KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS"
+    KDRIVE_LIBS="$TSLIB_LIBS $KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS $GLX_SYS_LIBS"
 
     # check if we can build Xephyr
     PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS, [xephyr="yes"], [xephyr="no"])
diff --git a/hw/kdrive/ati/Makefile.am b/hw/kdrive/ati/Makefile.am
index 8429250..31462bb 100644
--- a/hw/kdrive/ati/Makefile.am
+++ b/hw/kdrive/ati/Makefile.am
@@ -58,6 +58,10 @@ ATI_LIBS =				\
 	$(DRI_LIBS)			\
 	@KDRIVE_LIBS@
 
+if GLX
+Xati_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xati_LDADD = \
 	$(ATI_LIBS)			\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/chips/Makefile.am b/hw/kdrive/chips/Makefile.am
index 51b0edf..46e1760 100644
--- a/hw/kdrive/chips/Makefile.am
+++ b/hw/kdrive/chips/Makefile.am
@@ -20,6 +20,10 @@ CHIPS_LIBS =					 \
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a \
 	@KDRIVE_LIBS@
 
+if GLX
+Xchips_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xchips_LDADD = \
 	$(CHIPS_LIBS)				\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index 81d3d69..7ef22a3 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -67,6 +67,10 @@ libxephyr_a_CFLAGS = \
 Xephyr_SOURCES = \
 	ephyrinit.c
 
+if GLX
+Xephyr_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xephyr_LDADD = 						\
 	libxephyr.a					\
 	libxephyr-hostx.a			        \
diff --git a/hw/kdrive/epson/Makefile.am b/hw/kdrive/epson/Makefile.am
index 2a44014..14bb049 100644
--- a/hw/kdrive/epson/Makefile.am
+++ b/hw/kdrive/epson/Makefile.am
@@ -20,6 +20,10 @@ EPSON_LIBS =					\
 	libepson.a 				\
 	@KDRIVE_LIBS@
 
+if GLX
+Xepson_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xepson_LDADD = \
 	$(EPSON_LIBS)			       \
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/fake/Makefile.am b/hw/kdrive/fake/Makefile.am
index 09d179e..0f88656 100644
--- a/hw/kdrive/fake/Makefile.am
+++ b/hw/kdrive/fake/Makefile.am
@@ -16,6 +16,10 @@ libfake_a_SOURCES =	\
 Xfake_SOURCES = \
 	fakeinit.c
 
+if GLX
+Xfake_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xfake_LDADD = 						\
 	libfake.a					\
 	@KDRIVE_LIBS@					\
diff --git a/hw/kdrive/fbdev/Makefile.am b/hw/kdrive/fbdev/Makefile.am
index 420855b..c77f146 100644
--- a/hw/kdrive/fbdev/Makefile.am
+++ b/hw/kdrive/fbdev/Makefile.am
@@ -14,6 +14,10 @@ bin_PROGRAMS = Xfbdev
 Xfbdev_SOURCES = \
 	fbinit.c
 
+if GLX
+Xfbdev_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xfbdev_LDADD = 						\
 	libfbdev.a					\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/i810/Makefile.am b/hw/kdrive/i810/Makefile.am
index ea02cb6..30919fa 100644
--- a/hw/kdrive/i810/Makefile.am
+++ b/hw/kdrive/i810/Makefile.am
@@ -23,6 +23,10 @@ I810_LIBS =						\
 	libi810.a 					\
 	@KDRIVE_LIBS@
 
+if GLX
+Xi810_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xi810_LDADD = \
 	$(I810_LIBS)					\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/mach64/Makefile.am b/hw/kdrive/mach64/Makefile.am
index 746ffff..6ca376a 100644
--- a/hw/kdrive/mach64/Makefile.am
+++ b/hw/kdrive/mach64/Makefile.am
@@ -27,6 +27,10 @@ MACH64_LIBS =						\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a        
 
 
+if GLX
+Xmach64_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xmach64_LDADD = 					\
 	$(MACH64_LIBS)					\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/mga/Makefile.am b/hw/kdrive/mga/Makefile.am
index 37bc50c..a7dd2cb 100644
--- a/hw/kdrive/mga/Makefile.am
+++ b/hw/kdrive/mga/Makefile.am
@@ -22,6 +22,10 @@ MGA_LIBS =						\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a	\
 	@KDRIVE_LIBS@
 
+if GLX
+Xmga_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xmga_LDADD = \
 	$(MGA_LIBS)					\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/neomagic/Makefile.am b/hw/kdrive/neomagic/Makefile.am
index 95f0e1e..b449c37 100644
--- a/hw/kdrive/neomagic/Makefile.am
+++ b/hw/kdrive/neomagic/Makefile.am
@@ -32,6 +32,10 @@ NEOMAGIC_LIBS =                 \
 	${VESA_LIBS}                \
 	@KDRIVE_LIBS@
 
+if GLX
+Xneomagic_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xneomagic_LDADD = \
 	$(NEOMAGIC_LIBS)            \
 	@KDRIVE_LIBS@               \
diff --git a/hw/kdrive/nvidia/Makefile.am b/hw/kdrive/nvidia/Makefile.am
index b380e44..81736c3 100644
--- a/hw/kdrive/nvidia/Makefile.am
+++ b/hw/kdrive/nvidia/Makefile.am
@@ -23,6 +23,10 @@ NVIDIA_LIBS =					\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a \
 	@KDRIVE_LIBS@
 
+if GLX
+Xnvidia_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xnvidia_LDADD = \
 	$(NVIDIA_LIBS)				\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/pm2/Makefile.am b/hw/kdrive/pm2/Makefile.am
index 208d031..cb28de6 100644
--- a/hw/kdrive/pm2/Makefile.am
+++ b/hw/kdrive/pm2/Makefile.am
@@ -21,6 +21,10 @@ PM2_LIBS =					\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a \
 	@KDRIVE_LIBS@
 
+if GLX
+Xpm2_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xpm2_LDADD = \
 	$(PM2_LIBS)				\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/r128/Makefile.am b/hw/kdrive/r128/Makefile.am
index 62c1fcf..344fbeb 100644
--- a/hw/kdrive/r128/Makefile.am
+++ b/hw/kdrive/r128/Makefile.am
@@ -20,6 +20,10 @@ R128_LIBS =					\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a \
 	@KDRIVE_LIBS@
 
+if GLX
+Xr128_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xr128_LDADD = \
 	$(R128_LIBS)				\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/sdl/Makefile.am b/hw/kdrive/sdl/Makefile.am
index fe9309e..a70d147 100644
--- a/hw/kdrive/sdl/Makefile.am
+++ b/hw/kdrive/sdl/Makefile.am
@@ -7,6 +7,10 @@ bin_PROGRAMS = Xsdl
 
 Xsdl_SOURCES = sdl.c
 
+if GLX
+Xsdl_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xsdl_LDADD = \
 	@KDRIVE_LIBS@                                  \
 	@XSDL_LIBS@
diff --git a/hw/kdrive/sis300/Makefile.am b/hw/kdrive/sis300/Makefile.am
index 3e8ce90..af2500a 100644
--- a/hw/kdrive/sis300/Makefile.am
+++ b/hw/kdrive/sis300/Makefile.am
@@ -34,6 +34,10 @@ SIS_LIBS =				\
 	$(VESA_LIBS)			\
 	@KDRIVE_LIBS@
 
+if GLX
+Xsis_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xsis_LDADD = \
 	$(SIS_LIBS)				\
 	@KDRIVE_LIBS@                          \
diff --git a/hw/kdrive/smi/Makefile.am b/hw/kdrive/smi/Makefile.am
index a4d6624..bd7077c 100644
--- a/hw/kdrive/smi/Makefile.am
+++ b/hw/kdrive/smi/Makefile.am
@@ -25,6 +25,10 @@ SMI_LIBS =					\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a \
 	@KDRIVE_LIBS@
 
+if GLX
+Xsmi_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xsmi_LDADD = \
 	$(SMI_LIBS)				\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/vesa/Makefile.am b/hw/kdrive/vesa/Makefile.am
index ac50d2b..ec35c1e 100644
--- a/hw/kdrive/vesa/Makefile.am
+++ b/hw/kdrive/vesa/Makefile.am
@@ -19,6 +19,10 @@ libvesa_a_SOURCES = \
 Xvesa_SOURCES = \
 	vesainit.c
 
+if GLX
+Xvesa_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xvesa_LDADD = \
 	libvesa.a 				\
 	@KDRIVE_LIBS@
diff --git a/hw/kdrive/via/Makefile.am b/hw/kdrive/via/Makefile.am
index 249b3f3..c659379 100644
--- a/hw/kdrive/via/Makefile.am
+++ b/hw/kdrive/via/Makefile.am
@@ -21,6 +21,10 @@ VIA_LIBS =	\
 	libvia.a	\
 	$(top_builddir)/hw/kdrive/vesa/libvesa.a
 
+if GLX
+Xvia_LDFLAGS = $(LD_EXPORT_SYMBOLS_FLAG)
+endif
+
 Xvia_LDADD =						\
 	$(VIA_LIBS)					\
 	@KDRIVE_LIBS@
commit fbad87f2ae9f97fcb43546b0fa35f1100415dfec
Author: Julien Cristau <jcristau at debian.org>
Date:   Tue Apr 22 23:50:11 2008 +0200

    autoconfig: don't call closedir() when opendir() failed
    
    If opendir() fails, return from matchDriverFromFiles() immediately.
    Ubuntu bug 217647.

diff --git a/hw/xfree86/common/xf86AutoConfig.c b/hw/xfree86/common/xf86AutoConfig.c
index 5ffd847..7e5fab4 100644
--- a/hw/xfree86/common/xf86AutoConfig.c
+++ b/hw/xfree86/common/xf86AutoConfig.c
@@ -330,86 +330,87 @@ matchDriverFromFiles (char** matches, uint16_t match_vendor, uint16_t match_chip
     int i, j;
 
     idsdir = opendir(PCI_TXT_IDS_PATH);
-    if (idsdir) {
-         xf86Msg(X_INFO, "Scanning %s directory for additional PCI ID's supported by the drivers\n", PCI_TXT_IDS_PATH);
-        direntry = readdir(idsdir);
-        /* Read the directory */
-        while (direntry) {
-            if (direntry->d_name[0] == '.') {
-                direntry = readdir(idsdir);
-                continue;
+    if (!idsdir)
+        return;
+
+    xf86Msg(X_INFO, "Scanning %s directory for additional PCI ID's supported by the drivers\n", PCI_TXT_IDS_PATH);
+    direntry = readdir(idsdir);
+    /* Read the directory */
+    while (direntry) {
+        if (direntry->d_name[0] == '.') {
+            direntry = readdir(idsdir);
+            continue;
+        }
+        len = strlen(direntry->d_name);
+        /* A tiny bit of sanity checking. We should probably do better */
+        if (strncmp(&(direntry->d_name[len-4]), ".ids", 4) == 0) {
+            /* We need the full path name to open the file */
+            strncpy(path_name, PCI_TXT_IDS_PATH, 256);
+            strncat(path_name, "/", 1);
+            strncat(path_name, direntry->d_name, (256 - strlen(path_name) - 1));
+            fp = fopen(path_name, "r");
+            if (fp == NULL) {
+                xf86Msg(X_ERROR, "Could not open %s for reading. Exiting.\n", path_name);
+                goto end;
             }
-            len = strlen(direntry->d_name);
-            /* A tiny bit of sanity checking. We should probably do better */
-            if (strncmp(&(direntry->d_name[len-4]), ".ids", 4) == 0) {
-                /* We need the full path name to open the file */
-                strncpy(path_name, PCI_TXT_IDS_PATH, 256);
-                strncat(path_name, "/", 1);
-                strncat(path_name, direntry->d_name, (256 - strlen(path_name) - 1));
-                fp = fopen(path_name, "r");
-                if (fp == NULL) {
-                    xf86Msg(X_ERROR, "Could not open %s for reading. Exiting.\n", path_name);
-                    goto end;
-                }
-                /* Read the file */
-                #ifdef __GLIBC__
-                while ((read = getline(&line, &len, fp)) != -1) {
-                #else
-                while ((line = fgetln(fp, &len)) != (char *)NULL) {
-                #endif /* __GLIBC __ */
-                    xchomp(line);
-                    if (isdigit(line[0])) {
-                        strncpy(vendor_str, line, 4);
-                        vendor_str[4] = '\0';
-                        vendor = (int)strtol(vendor_str, NULL, 16);
-                        if ((strlen(&line[4])) == 0) {
-                                chip_str[0] = '\0';
-                                chip = -1;
+            /* Read the file */
+#ifdef __GLIBC__
+            while ((read = getline(&line, &len, fp)) != -1) {
+#else
+            while ((line = fgetln(fp, &len)) != (char *)NULL) {
+#endif /* __GLIBC __ */
+                xchomp(line);
+                if (isdigit(line[0])) {
+                    strncpy(vendor_str, line, 4);
+                    vendor_str[4] = '\0';
+                    vendor = (int)strtol(vendor_str, NULL, 16);
+                    if ((strlen(&line[4])) == 0) {
+                        chip_str[0] = '\0';
+                        chip = -1;
+                    } else {
+                        /* Handle trailing whitespace */
+                        if (isspace(line[4])) {
+                            chip_str[0] = '\0';
+                            chip = -1;
                         } else {
-                                /* Handle trailing whitespace */
-                                if (isspace(line[4])) {
-                                    chip_str[0] = '\0';
-                                    chip = -1;
-                                } else {
-                                /* Ok, it's a real ID */
-                                    strncpy(chip_str, &line[4], 4);
-                                    chip_str[4] = '\0';
-                                    chip = (int)strtol(chip_str, NULL, 16);
-                                }
+                            /* Ok, it's a real ID */
+                            strncpy(chip_str, &line[4], 4);
+                            chip_str[4] = '\0';
+                            chip = (int)strtol(chip_str, NULL, 16);
                         }
-                        if (vendor == match_vendor && chip == match_chip ) {
-                            i = 0;
-                            while (matches[i]) {
-                                i++;
-                            }
-                            matches[i] = (char*)xalloc(sizeof(char) * strlen(direntry->d_name) -  3);
-                            if (!matches[i]) {
-                                xf86Msg(X_ERROR, "Could not allocate space for the module name. Exiting.\n");
-                                goto end;
-                            }
-                            /* hack off the .ids suffix. This should guard
-                             * against other problems, but it will end up
-                             * taking off anything after the first '.' */
-                            for (j = 0; j < (strlen(direntry->d_name) - 3) ; j++) {
-                                if (direntry->d_name[j] == '.') {
-                                    matches[i][j] = '\0';
-                                    break;
-                                } else {
-                                    matches[i][j] = direntry->d_name[j];
-                                }
+                    }
+                    if (vendor == match_vendor && chip == match_chip ) {
+                        i = 0;
+                        while (matches[i]) {
+                            i++;
+                        }
+                        matches[i] = (char*)xalloc(sizeof(char) * strlen(direntry->d_name) -  3);
+                        if (!matches[i]) {
+                            xf86Msg(X_ERROR, "Could not allocate space for the module name. Exiting.\n");
+                            goto end;
+                        }
+                        /* hack off the .ids suffix. This should guard
+                         * against other problems, but it will end up
+                         * taking off anything after the first '.' */
+                        for (j = 0; j < (strlen(direntry->d_name) - 3) ; j++) {
+                            if (direntry->d_name[j] == '.') {
+                                matches[i][j] = '\0';
+                                break;
+                            } else {
+                                matches[i][j] = direntry->d_name[j];
                             }
-                            xf86Msg(X_INFO, "Matched %s from file name %s\n", matches[i], direntry->d_name);
                         }
-                    } else {
-                        /* TODO Handle driver overrides here */
+                        xf86Msg(X_INFO, "Matched %s from file name %s\n", matches[i], direntry->d_name);
                     }
+                } else {
+                    /* TODO Handle driver overrides here */
                 }
-                fclose(fp);
             }
-            direntry = readdir(idsdir);
+            fclose(fp);
         }
+        direntry = readdir(idsdir);
     }
-    end:
+ end:
     xfree(line);
     closedir(idsdir);
 }
commit 76381092e8f650ec7d1f058fa4c8a7348893f775
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 23 02:22:14 2008 -0700

    XQuartz: Make sure QuartzAudioInit() gets run.
    (cherry picked from commit bb3d034675b70e22e78df5554cab0ec2a3d913d0)
    (cherry picked from commit 824b31c7f8144a67a320442abd3d854e99d2bfe2)

diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index 4d03d02..2cba5df 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -156,7 +156,7 @@ void QuartzInitOutput(
     int argc,
     char **argv )
 {
-    if (serverGeneration == 0) {
+    if (serverGeneration == 1) {
         QuartzAudioInit();
     }
 
@@ -244,7 +244,7 @@ void QuartzDisplayChangedHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev,
     int x, y, width, height, sx, sy;
     xEvent e;
 
-    DEBUG_LOG("QuartzDisplayChangedHandler()\n");
+    DEBUG_LOG("QuartzDisplayChangedHandler(): noPseudoramiXExtension=%d, screenInfo.numScreens=%d\n", noPseudoramiXExtension, screenInfo.numScreens);
     if (noPseudoramiXExtension || screenInfo.numScreens != 1)
     {
         /* FIXME: if not using Xinerama, we have multiple screens, and
commit 00815b3e5223e822f306db45cd4884a22ac9f7ed
Author: Julien Cristau <jcristau at debian.org>
Date:   Mon Apr 21 14:34:39 2008 +0200

    Don't set DRI2=yes if we can't find dri2proto or libdrm

diff --git a/configure.ac b/configure.ac
index 04d976c..995a652 100644
--- a/configure.ac
+++ b/configure.ac
@@ -379,7 +379,7 @@ case $host_os in
 	AC_DEFINE(PCVT_SUPPORT, 1, [System has PCVT console])
 	AC_DEFINE(SYSCONS_SUPPORT, 1, [System has syscons console])
 	DRI=yes
-	DRI2=yes
+	PKG_CHECK_EXISTS([dri2proto >= 1.1 libdrm >= 2.3.1], DRI2=yes, DRI2=no)
 	;;
   *netbsd*)
 	AC_DEFINE(CSRG_BASED, 1, [System is BSD-like])
@@ -387,7 +387,7 @@ case $host_os in
 	AC_DEFINE(PCVT_SUPPORT, 1, [System has PCVT console])
 	AC_DEFINE(WSCONS_SUPPORT, 1, [System has wscons console])
 	DRI=yes
-	DRI2=yes
+	PKG_CHECK_EXISTS([dri2proto >= 1.1 libdrm >= 2.3.1], DRI2=yes, DRI2=no)
 	;;
   *openbsd*)
 	AC_DEFINE(CSRG_BASED, 1, [System is BSD-like])
@@ -396,7 +396,7 @@ case $host_os in
 	;;
   *linux*)
 	DRI=yes
-	DRI2=yes
+	PKG_CHECK_EXISTS([dri2proto >= 1.1 libdrm >= 2.3.1], DRI2=yes, DRI2=no)
 	KDRIVE_HW=yes
 	;;
   *solaris*)
commit e77f65768efbf05cdf363a2f41f036f74eaa45de
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 18:07:46 2008 +0100

    Reuse the existing framebuffer mode in kdrive/fbdev
    
    When starting up kdrive/fbdev, if the current framebuffer mode is sensible use
    that unless told otherwise.
    
    Signed-off-by: Daniel Stone <daniel at fooishbar.org>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index 177be0b..7721e60 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -179,16 +179,24 @@ fbdevScreenInitialize (KdScreenInfo *screen, FbdevScrPriv *scrpriv)
 	screen->rate = 103; /* FIXME: should get proper value from fb driver */
     }
     if (!screen->fb[0].depth)
-	screen->fb[0].depth = 16;
-
-    t = KdFindMode (screen, fbdevModeSupported);
-    screen->rate = t->rate;
-    screen->width = t->horizontal;
-    screen->height = t->vertical;
+    {
+	if (k >= 0) 
+	    screen->fb[0].depth = var.bits_per_pixel;
+	else
+	    screen->fb[0].depth = 16;
+    }
 
-    /* Now try setting the mode */
-    if (k < 0 || (t->horizontal != var.xres || t->vertical != var.yres))
-        fbdevConvertMonitorTiming (t, &var);
+    if ((screen->width != var.xres) || (screen->height != var.yres))
+    {
+      t = KdFindMode (screen, fbdevModeSupported);
+      screen->rate = t->rate;
+      screen->width = t->horizontal;
+      screen->height = t->vertical;
+
+      /* Now try setting the mode */
+      if (k < 0 || (t->horizontal != var.xres || t->vertical != var.yres))
+          fbdevConvertMonitorTiming (t, &var);
+    }
 
     var.activate = FB_ACTIVATE_NOW;
     var.bits_per_pixel = screen->fb[0].depth;
commit c4fd1121531b0cba1a3e90fa747871d784365c7e
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 18:05:53 2008 +0100

    Add mediumraw support to the linux kdrive driver
    
    Signed-off-by: Daniel Stone <daniel at fooishbar.org>

diff --git a/hw/kdrive/linux/keyboard.c b/hw/kdrive/linux/keyboard.c
index 3193ab7..ae981b7 100644
--- a/hw/kdrive/linux/keyboard.c
+++ b/hw/kdrive/linux/keyboard.c
@@ -42,6 +42,8 @@
 #include <sys/ioctl.h>
 
 extern int LinuxConsoleFd;
+static unsigned char mediumraw_data, mediumraw_up;
+static enum { DEFAULT, EXTBYTE1, EXTBYTE2 } mediumraw_state = DEFAULT;
 
 static const KeySym linux_to_x[256] = {
 	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
@@ -701,7 +703,29 @@ LinuxKeyboardRead (int fd, void *closure)
             else
 #endif
                 scancode = b[0] & 0x7f;
-	    KdEnqueueKeyboardEvent (closure, scancode, b[0] & 0x80);
+	    /* This is extended medium raw mode interpreter
+	       see linux/drivers/keyboard.c (kbd->kbdmode == VC_MEDIUMRAW) */
+	    switch (mediumraw_state)
+	    {
+	    case DEFAULT:
+		if (scancode == 0)
+		{
+		    mediumraw_state = EXTBYTE1;
+		    mediumraw_up = b[0] & 0x80;
+		}
+		else
+		    KdEnqueueKeyboardEvent (closure, scancode, b[0] & 0x80);
+		break;
+	    case EXTBYTE1:
+		mediumraw_data = scancode;
+		mediumraw_state = EXTBYTE2;
+		break;
+	    case EXTBYTE2:
+		/* Note: Only codes < 256 will pass correctly through KdEnqueueKeyboardEvent() */
+	      KdEnqueueKeyboardEvent (closure, (int)mediumraw_data << 7 | scancode, mediumraw_up);
+		mediumraw_state = DEFAULT;
+		break;
+	    }
 	    b++;
 	}
     }
commit 455383db95618a05ebdbeae78423e08065f0e14e
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 18:04:31 2008 +0100

    Enable the epson kdrive driver
    
    Signed-off-by: Daniel Stone <daniel at fooishbar.org>

diff --git a/hw/kdrive/Makefile.am b/hw/kdrive/Makefile.am
index 5803644..767e1c4 100644
--- a/hw/kdrive/Makefile.am
+++ b/hw/kdrive/Makefile.am
@@ -1,10 +1,10 @@
 if KDRIVEVESA
-VESA_SUBDIRS = vesa ati chips epson i810 mach64 mga nvidia pm2 r128 \
+VESA_SUBDIRS = vesa ati chips i810 mach64 mga nvidia pm2 r128 \
                smi via
 endif
 
 if BUILD_KDRIVEFBDEVLIB
-FBDEV_SUBDIRS = fbdev
+FBDEV_SUBDIRS = fbdev epson
 endif
 
 if XFAKESERVER
commit 82b37d35af13a9f402755e167493ab256b664b9c
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 16:38:14 2008 +0100

    Add support for AVR32

diff --git a/include/servermd.h b/include/servermd.h
index 6168410..7b0a328 100644
--- a/include/servermd.h
+++ b/include/servermd.h
@@ -130,6 +130,16 @@ SOFTWARE.
 
 #endif /* vax */
 
+#ifdef __avr32__
+
+#define IMAGE_BYTE_ORDER        MSBFirst
+#define BITMAP_BIT_ORDER        MSBFirst
+#define GLYPHPADBYTES           4
+#define GETLEFTBITS_ALIGNMENT   1
+#define AVOID_MEMORY_READ
+
+#endif /* __avr32__ */ 
+
 #ifdef __arm32__
 
 #define IMAGE_BYTE_ORDER        LSBFirst
commit 20a90bef8b4993f06cf76ad05e3d4c974e1614f6
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 16:37:02 2008 +0100

    Add a default touchscreen path
    
    When enabling the touchscreen, open /dev/input/touchscreen0 if no path was
    specified.

diff --git a/hw/kdrive/linux/tslib.c b/hw/kdrive/linux/tslib.c
index 371aece..50cd7cb 100644
--- a/hw/kdrive/linux/tslib.c
+++ b/hw/kdrive/linux/tslib.c
@@ -114,6 +114,10 @@ TslibEnable (KdPointerInfo *pi)
 
     private->raw_event_hook = NULL;
     private->raw_event_closure = NULL;
+    if (!pi->path) {
+        pi->path = "/dev/input/touchscreen0";
+        ErrorF("[tslib/TslibEnable] no device path given, trying %s\n", pi->path);
+    }
     private->tsDev = ts_open(pi->path, 0);
     private->fd = ts_fd(private->tsDev);
     if (!private->tsDev || ts_config(private->tsDev) || private->fd < 0) {
commit b44e89f4683ffcfd75eaf39f1f37d7461db44689
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 16:28:39 2008 +0100

    Update to tslib 1.0
    
    Update the pkgconfig checks to tslib 1.0, and fix the LIBS definitions.

diff --git a/configure.ac b/configure.ac
index efb6e66..04d976c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1942,7 +1942,7 @@ if test "$KDRIVE" = yes; then
         AC_CHECK_LIB([rt], [nanosleep], XEPHYR_LIBS="$XEPHYR_LIBS -lrt"))
     
     if test "x$TSLIB" = xyes; then
-        PKG_CHECK_MODULES([TSLIB], [tslib-0.0], [HAVE_TSLIB="yes"], [HAVE_TSLIB="no"])
+        PKG_CHECK_MODULES([TSLIB], [tslib-1.0], [HAVE_TSLIB="yes"], [HAVE_TSLIB="no"])
         if test "x$HAVE_TSLIB" = xno; then
             AC_MSG_ERROR([tslib must be installed to build the tslib driver. See http://tslib.berlios.de/])
         fi
@@ -1966,10 +1966,10 @@ if test "$KDRIVE" = yes; then
 	    ;;
     esac
     KDRIVE_STUB_LIB='$(top_builddir)/hw/kdrive/src/libkdrivestubs.a'
-    KDRIVE_LOCAL_LIBS="$TSLIB_LIBS $DIX_LIB $KDRIVE_LIB $KDRIVE_STUB_LIB $CONFIG_LIB"
+    KDRIVE_LOCAL_LIBS="$DIX_LIB $KDRIVE_LIB $KDRIVE_STUB_LIB $CONFIG_LIB"
     KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $FB_LIB $MI_LIB $KDRIVE_PURE_LIBS"
     KDRIVE_LOCAL_LIBS="$KDRIVE_LOCAL_LIBS $KDRIVE_OS_LIB $OS_LIB"
-    KDRIVE_LIBS="$KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS"
+    KDRIVE_LIBS="$TSLIB_LIBS $KDRIVE_LOCAL_LIBS $XSERVER_SYS_LIBS"
 
     # check if we can build Xephyr
     PKG_CHECK_MODULES(XEPHYR, $XEPHYR_REQUIRED_LIBS, [xephyr="yes"], [xephyr="no"])
commit 3848422d2354b7a5302fda92b05b0d728190e050
Author: Ross Burton <ross at burtonini.com>
Date:   Tue Apr 22 16:25:23 2008 +0100

    Fix build when XKB is disabled.

diff --git a/dix/devices.c b/dix/devices.c
index 5a726af..2c9a329 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -524,8 +524,8 @@ CloseDevice(DeviceIntPtr dev)
 #ifdef XKB
 	if (dev->key->xkbInfo)
 	    XkbFreeInfo(dev->key->xkbInfo);
-#endif
         dev->key->xkbInfo = NULL;
+#endif
 	xfree(dev->key->curKeySyms.map);
 	xfree(dev->key->modifierKeyMap);
 	xfree(dev->key);
commit 744d0cfda74f8283801cc2d6c5eda48402455bc3
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Apr 21 22:06:38 2008 -0700

    add missing DARWIN_GLX_LIBS in configure.ac
    (cherry picked from commit a033c0b3dbb3b963261faa39f0236457cb00ff44)

diff --git a/configure.ac b/configure.ac
index d3a2317..efb6e66 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1742,7 +1742,7 @@ if test "x$XQUARTZ" = xyes; then
 #	])
 	xorg_cv_AGL_framework=no
 	DARWIN_GLX_LIBS='$(top_builddir)/GL/apple/indirect.o $(top_builddir)/GL/glx/libglx.la'
-	DARWIN_LIBS="$MI_LIB $OS_LIB $DIX_LIB $FB_LIB $FIXES_LIB $XEXT_LIB $CONFIG_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB"
+	DARWIN_LIBS="$MI_LIB $OS_LIB $DIX_LIB $FB_LIB $FIXES_LIB $XEXT_LIB $CONFIG_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $RENDER_LIB $RANDR_LIB $DAMAGE_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $XPSTUBS_LIB $DARWIN_GLX_LIBS"
 	AC_SUBST([DARWIN_LIBS])
 	AC_CHECK_LIB([Xplugin],[xp_init],[:])
 	CFLAGS="${CFLAGS} -DROOTLESS_WORKAROUND -DNO_ALLOCA"
commit 2ddbfd345786aa39b6ccaed82a1ca5c145284ee3
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Tue Apr 22 16:31:44 2008 +0930

    xnest: re-enable XKB support. #10015
    
    XKB was disabled in 08928afb0500d46b0caa0a1d1244dee2ed80e6a0, with the comment
    "Disable XKB, as we can't yet use it". Seems like "yet" is over, running GNOME
    and changing XKB settings seems to work in Xnest now.
    
    X.Org Bug 10015 <https://bugs.freedesktop.org/show_bug.cgi?id=10015>

diff --git a/hw/xnest/Args.c b/hw/xnest/Args.c
index f061f9e..209f175 100644
--- a/hw/xnest/Args.c
+++ b/hw/xnest/Args.c
@@ -57,11 +57,6 @@ void ddxInitGlobals(void)
     extern Bool noCompositeExtension;
     noCompositeExtension = TRUE;
 #endif
-
-#ifdef XKB
-    extern Bool noXkbExtension;
-    noXkbExtension = TRUE;
-#endif
 }
 
 int
commit a8b8700c7345b89953c8b63cb5c347a95e6ab988
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 21 23:44:37 2008 -0700

    XQuartz: Fixed cmd-tab to bring all windows forward.
    (cherry picked from commit e48e2ce931228f4dfa36c39b8ec8c72a58025b1b)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 3df19de..265819a 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -264,7 +264,8 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 				_appFlags._active = YES;
 
 				[self activateX:YES];
-				if ([e data2] & 0x10) X11ApplicationSetFrontProcess();
+				if ([e data2] & 0x10) 
+                    DarwinSendDDXEvent(kXquartzBringAllToFront, 0);
 			}
 			break;
 
diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index 98cb395..8dfe4b3 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -754,12 +754,6 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
     return YES;
 }
 
-- (OSX_BOOL) applicationShouldHandleReopen:(NSApplication *)app
-                     hasVisibleWindows:(OSX_BOOL)hasVis {
-    DarwinSendDDXEvent(kXquartzBringAllToFront, 0);
-    return YES;
-}
-
 @end
 
 void X11ControllerMain(int argc, const char **argv, void (*server_thread) (void *), void *server_arg) {
commit a368ab757edf36ed7bbda023673d28883ce11231
Author: Dave Airlie <airlied at linux.ie>
Date:   Tue Apr 22 15:13:57 2008 +1000

    GLcore: make googleearth not crash the server on sw-rendering.
    
    I don't think this is the 100% correct answer as I get log spam saying
    (EE) DoSwapInterval: cx = 0x98b8998, GLX screen = 0x96dd780
    (EE) AIGLX: cx->pGlxScreen->swapInterval == NULL
    
    but thats better than X exiting in my book.

diff --git a/GL/glx/glxglcore.c b/GL/glx/glxglcore.c
index 1eac0eb..c8a2514 100644
--- a/GL/glx/glxglcore.c
+++ b/GL/glx/glxglcore.c
@@ -432,6 +432,7 @@ __glXMesaScreenProbe(ScreenPtr pScreen)
     screen->base.destroy        = __glXMesaScreenDestroy;
     screen->base.createContext  = __glXMesaScreenCreateContext;
     screen->base.createDrawable = __glXMesaScreenCreateDrawable;
+    screen->base.swapInterval  = NULL;
     screen->base.pScreen       = pScreen;
 
     return &screen->base;
commit 449723510a1f9d024e23d9eb33795cac27f9443e
Author: Egbert Eich <eich at pdx.freedesktop.org>
Date:   Tue Apr 22 13:30:03 2008 +0930

    xkb: use the correct device instead of an uninitialised "dev". #15614
    
    X.Org Bug 15614 <http://bugs.freedesktop.org/show_bug.cgi?id=15614>
    
    Signed-off-by: Peter Hutterer <peter at cs.unisa.edu.au>

diff --git a/xkb/xkbActions.c b/xkb/xkbActions.c
index 8c72874..f226b6b 100644
--- a/xkb/xkbActions.c
+++ b/xkb/xkbActions.c
@@ -1031,7 +1031,7 @@ _XkbFilterDeviceBtn(	XkbSrvInfoPtr	xkbi,
 DeviceIntPtr	dev;
 int		button;
 
-    if (dev == inputInfo.keyboard)
+    if (xkbi->device == inputInfo.keyboard)
         return 0;
 
     if (filter->keycode==0) {		/* initial press */
commit ba87c25321c3378fd1ad0c55dcb0af0a6e82a540
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 21 20:03:08 2008 -0700

    Make rootless use dixLookupClient rather than deprecated LookupClient.
    (cherry picked from commit 582b5b01f9697b66489ea906a2ecb8bfc5915571)

diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index fa395a8..df1d3a8 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -131,32 +131,38 @@ RootlessNativeWindowStateChanged (WindowPtr pWin, unsigned int state)
   pWin->rootlessUnhittable = winRec->is_offscreen;
 }
 
-void
-RootlessNativeWindowMoved (WindowPtr pWin)
-{
-  xp_box bounds;
-  int sx, sy;
-  XID vlist[2];
-  Mask mask;
-  RootlessWindowRec *winRec = WINREC(pWin);
-
-  if (xp_get_window_bounds ((xp_window_id)winRec->wid, &bounds) != Success) return;
-
-  sx = dixScreenOrigins[pWin->drawable.pScreen->myNum].x + darwinMainScreenX;
-  sy = dixScreenOrigins[pWin->drawable.pScreen->myNum].y + darwinMainScreenY;
-
-  /* Fake up a ConfigureWindow packet to resize the window to the current bounds. */
-
-  vlist[0] = (INT16) bounds.x1 - sx;
-  vlist[1] = (INT16) bounds.y1 - sy;
-  mask = CWX | CWY;
-
-  /* Don't want to do anything to the physical window (avoids 
+void RootlessNativeWindowMoved (WindowPtr pWin) {
+    xp_box bounds;
+    int sx, sy, err;
+    XID vlist[2];
+    Mask mask;
+    ClientPtr client, pClient;
+    RootlessWindowRec *winRec = WINREC(pWin);
+    
+    if (xp_get_window_bounds ((xp_window_id)winRec->wid, &bounds) != Success) return;
+    
+    sx = dixScreenOrigins[pWin->drawable.pScreen->myNum].x + darwinMainScreenX;
+    sy = dixScreenOrigins[pWin->drawable.pScreen->myNum].y + darwinMainScreenY;
+    
+    /* Fake up a ConfigureWindow packet to resize the window to the current bounds. */
+    
+    vlist[0] = (INT16) bounds.x1 - sx;
+    vlist[1] = (INT16) bounds.y1 - sy;
+    mask = CWX | CWY;
+    
+    /* pretend we're the owner of the window! */
+    err = dixLookupClient(&pClient, pWin->drawable.id, NullClient, DixUnknownAccess);
+    if(err != Success) {
+        ErrorF("RootlessNativeWindowMoved(): Failed to lookup window: 0x%x\n", pWin->drawable.id);
+        return;
+    }
+    
+    /* Don't want to do anything to the physical window (avoids 
      notification-response feedback loops) */
-
-  no_configure_window = TRUE;
-  ConfigureWindow (pWin, mask, vlist, serverClient);
-  no_configure_window = FALSE;
+    
+    no_configure_window = TRUE;
+    ConfigureWindow (pWin, mask, vlist, client);
+    no_configure_window = FALSE;
 }
 
 /* Updates the _NATIVE_SCREEN_ORIGIN property on the given root window. */
commit 8822110d7d6b684f373fc883aeb7cab9734e9ddb
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Mon Apr 21 20:08:05 2008 -0700

    Fixed dixLookupClient to work with client=NullClient as it did in the 1.3 branch
    (cherry picked from commit e41ccc64702f856e5e09dfa652fe73c14b8a0225)
    (cherry picked from commit ce5a5f93990647de85e535734ee6bb430ad591cb)

diff --git a/dix/dixutils.c b/dix/dixutils.c
index aaf5106..22935ce 100644
--- a/dix/dixutils.c
+++ b/dix/dixutils.c
@@ -270,7 +270,8 @@ dixLookupClient(ClientPtr *pClient, XID rid, ClientPtr client, Mask access)
     *pClient = clients[clientIndex];
     return Success;
 bad:
-    client->errorValue = rid;
+    if(client)
+        client->errorValue = rid;
     *pClient = NULL;
     return rc;
 }
commit 5ffb6a2fe8db5871eaf26b8535af1588c43f33d3
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Apr 21 19:55:54 2008 -0700

    Nuke a call to deprecated LookupClient, and hopefully prevent a
    null-pointer dereference, too!
    (cherry picked from commit 3d28e9f953709914e18807bc74c241333671cb30)

diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index a6002bb..fa395a8 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -138,7 +138,6 @@ RootlessNativeWindowMoved (WindowPtr pWin)
   int sx, sy;
   XID vlist[2];
   Mask mask;
-  ClientPtr client;
   RootlessWindowRec *winRec = WINREC(pWin);
 
   if (xp_get_window_bounds ((xp_window_id)winRec->wid, &bounds) != Success) return;
@@ -152,14 +151,11 @@ RootlessNativeWindowMoved (WindowPtr pWin)
   vlist[1] = (INT16) bounds.y1 - sy;
   mask = CWX | CWY;
 
-  /* pretend we're the owner of the window! */
-  client = LookupClient (pWin->drawable.id, NullClient);
-
   /* Don't want to do anything to the physical window (avoids 
      notification-response feedback loops) */
 
   no_configure_window = TRUE;
-  ConfigureWindow (pWin, mask, vlist, client);
+  ConfigureWindow (pWin, mask, vlist, serverClient);
   no_configure_window = FALSE;
 }
 
commit 590688131d89595bdc78ca562ee88df86c9012a6
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sun Apr 20 22:18:45 2008 -0700

    XQuartz: Fixed quit dialog to be more conforming with HIG.
    (cherry picked from commit 14c6b837bb03bd0956f90882f550847f13d0ca09)

diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index f2dee2c..98cb395 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -690,24 +690,26 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
   DarwinSendDDXEvent(kXquartzControllerNotify, 1, AppleWMShowAll);
 }
 
-- (NSApplicationTerminateReply) applicationShouldTerminate:sender
-{
-  NSString *msg;
-	
-  if (can_quit || [X11App prefs_get_boolean:@PREFS_NO_QUIT_ALERT default:NO])
-    return NSTerminateNow;
+- (NSApplicationTerminateReply) applicationShouldTerminate:sender {
+    NSString *msg;
+    NSString *title;
 	
-  /* Make sure we're frontmost. */
-  [NSApp activateIgnoringOtherApps:YES];
+    if (can_quit || [X11App prefs_get_boolean:@PREFS_NO_QUIT_ALERT default:NO])
+        return NSTerminateNow;
 	
-  msg = NSLocalizedString (@"Are you sure you want to quit X11?\n\nIf you quit X11, any X11 applications you are running will stop immediately and you will lose any changes you have not saved.", @"Dialog when quitting");
+    /* Make sure we're frontmost. */
+    [NSApp activateIgnoringOtherApps:YES];
 	
-  /* FIXME: safe to run the alert in here? Or should we return Later
-     and then run the alert on a timer? It seems to work here, so.. */
+    title = NSLocalizedString(@"Do you really want to quit X11?", @"Dialog title when quitting");
+    msg = NSLocalizedString(@"Any open X11 applications will stop immediately, and you will lose any unsaved changes.", @"Dialog when quitting");
+
+    /* FIXME: safe to run the alert in here? Or should we return Later
+     *        and then run the alert on a timer? It seems to work here, so..
+     */
 	
-  return (NSRunAlertPanel (nil, msg, NSLocalizedString (@"Quit", @""),
-			   NSLocalizedString (@"Cancel", @""), nil)
-	  == NSAlertDefaultReturn) ? NSTerminateNow : NSTerminateCancel;
+    return (NSRunAlertPanel (title, msg, NSLocalizedString (@"Quit", @""),
+                             NSLocalizedString (@"Cancel", @""), nil)
+            == NSAlertDefaultReturn) ? NSTerminateNow : NSTerminateCancel;
 }
 
 - (void) applicationWillTerminate:(NSNotification *)aNotification
commit d20b3ac22d960fa44632cc4a14be079daa2d5a33
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sun Apr 20 22:18:19 2008 -0700

    .gitignore: Added Xquartz stuff
    (cherry picked from commit 0a9a3bec2de8d1f442493e13cf9f039902a4928f)

diff --git a/.gitignore b/.gitignore
index 548e784..a6925d9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -278,6 +278,8 @@ hw/xprint/doc/Xprt.1x
 hw/xprint/doc/Xprt.man
 hw/xprint/dpmsstubs-wrapper.c
 hw/xprint/miinitext-wrapper.c
+hw/xquartz/xpr/Xquartz
+hw/xquartz/xpr/Xquartz.1
 include/dix-config.h
 include/kdrive-config.h
 include/xgl-config.h
commit 570b0dca261920c9b01b4eb11fe9b9987b1c636a
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Apr 21 17:52:10 2008 -0700

    Fix for pointer-offset issue when using a multi-display environment on X11.app.
    (cherry picked from commit 9a7e14286ced55c5e2a4512e2629e03836443009)

diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index f685d4a..6f7598f 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -150,7 +150,7 @@ displayScreenBounds(CGDirectDisplayID id)
 
     /* Remove menubar to help standard X11 window managers. */
 
-    if (frame.origin.x == 0 && frame.origin.y == 0)
+    if (frame.origin.y == 0)
     {
         frame.origin.y += aquaMenuBarHeight;
         frame.size.height -= aquaMenuBarHeight;
commit 3f081b4de55e1378728a24d069bf06575ffca2d8
Author: Tilman Sauerbeck <tilman at code-monkey.de>
Date:   Mon Apr 21 11:22:07 2008 +0200

    EXA: Set pixmap->accel_blocked on the screen pixmap, too.

diff --git a/exa/exa.c b/exa/exa.c
index 0e3ea70..3a6ad98 100644
--- a/exa/exa.c
+++ b/exa/exa.c
@@ -699,6 +699,34 @@ exaBitmapToRegion(PixmapPtr pPix)
   return ret;
 }
 
+static Bool
+exaCreateScreenResources(ScreenPtr pScreen)
+{
+    ExaScreenPriv(pScreen);
+    PixmapPtr pScreenPixmap;
+    Bool b;
+
+    pScreen->CreateScreenResources = pExaScr->SavedCreateScreenResources;
+    b = pScreen->CreateScreenResources(pScreen);
+    pScreen->CreateScreenResources = exaCreateScreenResources;
+
+    if (!b)
+        return FALSE;
+
+    pScreenPixmap = pScreen->GetScreenPixmap(pScreen);
+
+    if (pScreenPixmap) {
+        ExaPixmapPriv(pScreenPixmap);
+
+        exaSetAccelBlock(pExaScr, pExaPixmap,
+                         pScreenPixmap->drawable.width,
+                         pScreenPixmap->drawable.height,
+                         pScreenPixmap->drawable.bitsPerPixel);
+    }
+
+    return TRUE;
+}
+
 /**
  * exaCloseScreen() unwraps its wrapped screen functions and tears down EXA's
  * screen private, before calling down to the next CloseSccreen.
@@ -720,6 +748,7 @@ exaCloseScreen(int i, ScreenPtr pScreen)
     pScreen->CopyWindow = pExaScr->SavedCopyWindow;
     pScreen->ChangeWindowAttributes = pExaScr->SavedChangeWindowAttributes;
     pScreen->BitmapToRegion = pExaScr->SavedBitmapToRegion;
+    pScreen->CreateScreenResources = pExaScr->SavedCreateScreenResources;
 #ifdef RENDER
     if (ps) {
 	ps->Composite = pExaScr->SavedComposite;
@@ -877,6 +906,9 @@ exaDriverInit (ScreenPtr		pScreen,
     pExaScr->SavedBitmapToRegion = pScreen->BitmapToRegion;
     pScreen->BitmapToRegion = exaBitmapToRegion;
 
+    pExaScr->SavedCreateScreenResources = pScreen->CreateScreenResources;
+    pScreen->CreateScreenResources = exaCreateScreenResources;
+
 #ifdef RENDER
     if (ps) {
         pExaScr->SavedComposite = ps->Composite;
diff --git a/exa/exa_priv.h b/exa/exa_priv.h
index e41f46a..0138e4a 100644
--- a/exa/exa_priv.h
+++ b/exa/exa_priv.h
@@ -107,6 +107,7 @@ typedef struct {
     CopyWindowProcPtr 		 SavedCopyWindow;
     ChangeWindowAttributesProcPtr SavedChangeWindowAttributes;
     BitmapToRegionProcPtr        SavedBitmapToRegion;
+    CreateScreenResourcesProcPtr SavedCreateScreenResources;
     ModifyPixmapHeaderProcPtr    SavedModifyPixmapHeader;
 #ifdef RENDER
     CompositeProcPtr             SavedComposite;
commit 26c1801a27b81fdd988d5bd210ba0e76ecc274ae
Author: Tilman Sauerbeck <tilman at code-monkey.de>
Date:   Mon Apr 21 11:03:27 2008 +0200

    EXA: Update sys_pitch/fb_pitch in exaModifyPixmapHeader.
    
    exaModifyPixmapHeader now also only evaluates arguments that have a
    meaningful value.

diff --git a/exa/exa.c b/exa/exa.c
index 81dc3e2..0e3ea70 100644
--- a/exa/exa.c
+++ b/exa/exa.c
@@ -248,6 +248,19 @@ exaSetAccelBlock(ExaScreenPrivPtr pExaScr, ExaPixmapPrivPtr pExaPixmap,
         pExaPixmap->accel_blocked |= EXA_RANGE_HEIGHT;
 }
 
+static void
+exaSetFbPitch(ExaScreenPrivPtr pExaScr, ExaPixmapPrivPtr pExaPixmap,
+              int w, int h, int bpp)
+{
+    if (pExaScr->info->flags & EXA_OFFSCREEN_ALIGN_POT && w != 1)
+        pExaPixmap->fb_pitch = (1 << (exaLog2(w - 1) + 1)) * bpp / 8;
+    else
+        pExaPixmap->fb_pitch = w * bpp / 8;
+
+    pExaPixmap->fb_pitch = EXA_ALIGN(pExaPixmap->fb_pitch,
+                                     pExaScr->info->pixmapPitchAlign);
+}
+
 /**
  * exaCreatePixmap() creates a new pixmap.
  *
@@ -292,12 +305,8 @@ exaCreatePixmap(ScreenPtr pScreen, int w, int h, int depth,
         if (paddedWidth / 4 > 32767 || h > 32767)
             return NullPixmap;
 
-        if (pExaScr->info->flags & EXA_OFFSCREEN_ALIGN_POT && w != 1)
-            pExaPixmap->fb_pitch = (1 << (exaLog2(w - 1) + 1)) * bpp / 8;
-        else
-            pExaPixmap->fb_pitch = w * bpp / 8;
-        pExaPixmap->fb_pitch = EXA_ALIGN(pExaPixmap->fb_pitch,
-                                         pExaScr->info->pixmapPitchAlign);
+        exaSetFbPitch(pExaScr, pExaPixmap, w, h, bpp);
+
         if (paddedWidth < pExaPixmap->fb_pitch)
             paddedWidth = pExaPixmap->fb_pitch;
 
@@ -331,12 +340,7 @@ exaCreatePixmap(ScreenPtr pScreen, int w, int h, int depth,
         pExaPixmap->offscreen = FALSE;
 
         pExaPixmap->fb_ptr = NULL;
-        if (pExaScr->info->flags & EXA_OFFSCREEN_ALIGN_POT && w != 1)
-            pExaPixmap->fb_pitch = (1 << (exaLog2(w - 1) + 1)) * bpp / 8;
-        else
-            pExaPixmap->fb_pitch = w * bpp / 8;
-        pExaPixmap->fb_pitch = EXA_ALIGN(pExaPixmap->fb_pitch,
-				         pExaScr->info->pixmapPitchAlign);
+        exaSetFbPitch(pExaScr, pExaPixmap, w, h, bpp);
         pExaPixmap->fb_size = pExaPixmap->fb_pitch * h;
 
         if (pExaPixmap->fb_pitch > 131071) {
@@ -384,10 +388,19 @@ exaModifyPixmapHeader(PixmapPtr pPixmap, int width, int height, int depth,
     pExaPixmap = ExaGetPixmapPriv(pPixmap);
 
     if (pExaPixmap) {
-	pExaPixmap->sys_ptr = pPixData;
+        if (pPixData)
+            pExaPixmap->sys_ptr = pPixData;
 
-        exaSetAccelBlock(pExaScr, pExaPixmap,
-                         width, height, bitsPerPixel);
+        if (devKind > 0)
+            pExaPixmap->sys_pitch = devKind;
+
+        if (width > 0 && height > 0 && bitsPerPixel > 0) {
+            exaSetFbPitch(pExaScr, pExaPixmap,
+                          width, height, bitsPerPixel);
+
+            exaSetAccelBlock(pExaScr, pExaPixmap,
+                             width, height, bitsPerPixel);
+        }
     }
 
 
commit 4fa89fbe18c929e0d36305ab47e7e17841309ffd
Author: Jordan Crouse <jordan.crouse at amd.com>
Date:   Mon Apr 21 12:09:00 2008 -0600

    xf86: Change AutoConfig driver for PCI ID 022:2091 to 'geode'

diff --git a/hw/xfree86/common/xf86AutoConfig.c b/hw/xfree86/common/xf86AutoConfig.c
index 92b204b..5ffd847 100644
--- a/hw/xfree86/common/xf86AutoConfig.c
+++ b/hw/xfree86/common/xf86AutoConfig.c
@@ -146,7 +146,11 @@ videoPtrToDriverName(struct pci_device *dev)
 
     switch (dev->vendor_id)
     {
-	case 0x1022:		    return "amd";
+	case 0x1022:
+		if (dev->device_id == 0x2081)
+			return "geode";
+		else
+			return NULL;
 	case 0x1142:		    return "apm";
 	case 0xedd8:		    return "ark";
 	case 0x1a03:		    return "ast";
commit 6c95fae1e9d6b0eb64bc78eced05a6e9f5faf02e
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Mon Apr 21 10:45:11 2008 +0200

    EXA: Offscreen memory eviction improvements.
    
    * Make sure available areas are considered to have no eviction cost. This seems
      to help for https://bugs.freedesktop.org/show_bug.cgi?id=15513 but I'm afraid
      that may just be coincidence.
    * Only calculate eviction cost of each area once for each eviction pass.
      Safeguard against potential (though unlikely) division by zero.
    * Cosmetic enhancements: Name eviction cost related variables 'cost' instead of
      'score' to emphasize that smaller values are better, update Doxygen file
      comment to the way eviction works now.

diff --git a/exa/exa.h b/exa/exa.h
index 97ae6c0..2562094 100644
--- a/exa/exa.h
+++ b/exa/exa.h
@@ -64,6 +64,8 @@ struct _ExaOffscreenArea {
     ExaOffscreenState   state;
 
     ExaOffscreenArea    *next;
+
+    unsigned            eviction_cost;
 };
 
 /**
diff --git a/exa/exa_offscreen.c b/exa/exa_offscreen.c
index 85b5388..4aaa2c1 100644
--- a/exa/exa_offscreen.c
+++ b/exa/exa_offscreen.c
@@ -21,11 +21,9 @@
  */
 
 /** @file
- * This allocator allocates blocks of memory by maintaining a list of areas
- * and a score for each area.  As an area is marked used, its score is
- * incremented, and periodically all of the areas have their scores decayed by
- * a fraction.  When allocating, the contiguous block of areas with the minimum
- * score is found and evicted in order to make room for the new allocation.
+ * This allocator allocates blocks of memory by maintaining a list of areas.
+ * When allocating, the contiguous block of areas with the minimum eviction
+ * cost is found and evicted in order to make room for the new allocation.
  */
 
 #include "exa_priv.h"
@@ -71,19 +69,36 @@ ExaOffscreenKickOut (ScreenPtr pScreen, ExaOffscreenArea *area)
     return exaOffscreenFree (pScreen, area);
 }
 
-#define AREA_SCORE(area) (area->size / (double)(pExaScr->offScreenCounter - area->last_use))
+static void
+exaUpdateEvictionCost(ExaOffscreenArea *area, unsigned offScreenCounter)
+{
+    unsigned age;
+
+    if (area->state == ExaOffscreenAvail)
+	return;
+
+    age = offScreenCounter - area->last_use;
+
+    /* This is unlikely to happen, but could result in a division by zero... */
+    if (age > (UINT_MAX / 2)) {
+	age = UINT_MAX / 2;
+	area->last_use = offScreenCounter - age;
+    }
+
+    area->eviction_cost = area->size / age;
+}
 
 static ExaOffscreenArea *
 exaFindAreaToEvict(ExaScreenPrivPtr pExaScr, int size, int align)
 {
     ExaOffscreenArea *begin, *end, *best;
-    double score, best_score;
+    unsigned cost, best_cost;
     int avail, real_size, tmp;
 
-    best_score = UINT_MAX;
+    best_cost = UINT_MAX;
     begin = end = pExaScr->info->offScreenAreas;
     avail = 0;
-    score = 0;
+    cost = 0;
     best = 0;
 
     while (end != NULL)
@@ -106,23 +121,24 @@ exaFindAreaToEvict(ExaScreenPrivPtr pExaScr, int size, int align)
 	    if (end->state == ExaOffscreenLocked) {
 		/* Can't more room here, restart after this locked area */
 		avail = 0;
-		score = 0;
+		cost = 0;
 		begin = end;
 		goto restart;
 	    }
 	    avail += end->size;
-	    score += AREA_SCORE(end);
+	    exaUpdateEvictionCost(end, pExaScr->offScreenCounter);
+	    cost += end->eviction_cost;
 	    end = end->next;
 	}
 
-	/* Check the score, update best */
-	if (avail >= real_size && score < best_score) {
+	/* Check the cost, update best */
+	if (avail >= real_size && cost < best_cost) {
 	    best = begin;
-	    best_score = score;
+	    best_cost = cost;
 	}
 
 	avail -= begin->size;
-	score -= AREA_SCORE(begin);
+	cost -= begin->eviction_cost;
 	begin = begin->next;
     }
 
@@ -244,6 +260,7 @@ exaOffscreenAlloc (ScreenPtr pScreen, int size, int align,
 	new_area->state = ExaOffscreenAvail;
 	new_area->save = NULL;
 	new_area->last_use = 0;
+	new_area->eviction_cost = 0;
 	new_area->next = area->next;
 	area->next = new_area;
 	area->size = real_size;
@@ -409,6 +426,7 @@ exaOffscreenFree (ScreenPtr pScreen, ExaOffscreenArea *area)
     area->state = ExaOffscreenAvail;
     area->save = NULL;
     area->last_use = 0;
+    area->eviction_cost = 0;
     /*
      * Find previous area
      */
@@ -474,6 +492,7 @@ exaOffscreenInit (ScreenPtr pScreen)
     area->save = NULL;
     area->next = NULL;
     area->last_use = 0;
+    area->eviction_cost = 0;
 
     /* Add it to the free areas */
     pExaScr->info->offScreenAreas = area;
commit 40c6be1408a1f0b236fdb28af27ae18aea0d578f
Author: Julien Cristau <jcristau at debian.org>
Date:   Sun Apr 20 20:36:44 2008 +0200

    Minor xorg.conf manpage fixups
    
    Use __libmansuffix__ instead of __oslibmansuffix__ which isn't getting
    replaced, and rewrap some text to get __xservername__ replaced in the
    description of Option "Accel" (cpp doesn't like the preceding quote).

diff --git a/hw/xfree86/doc/man/xorg.conf.man.pre b/hw/xfree86/doc/man/xorg.conf.man.pre
index 9f39808..8b66f89 100644
--- a/hw/xfree86/doc/man/xorg.conf.man.pre
+++ b/hw/xfree86/doc/man/xorg.conf.man.pre
@@ -54,7 +54,7 @@ is the relative path (with no \(lq..\(rq components) specified by that
 environment variable, and
 .I <hostname>
 is the machine's hostname as reported by
-.BR gethostname (__oslibmansuffix__).
+.BR gethostname (__libmansuffix__).
 .PP
 When the __xservername__ server is started by the \(lqroot\(rq user, the config file
 search locations are as follows:
@@ -93,7 +93,7 @@ is the path specified by that environment variable (usually the home
 directory), and
 .I <hostname>
 is the machine's hostname as reported by
-.BR gethostname (__oslibmansuffix__).
+.BR gethostname (__libmansuffix__).
 .PP
 The
 .I __xconfigfile__
@@ -1624,8 +1624,8 @@ Others are driver\-independent, and will eventually be described here.
 .\" XXX These should really be in an xaa man page.
 .TP 7
 .BI "Option \*qAccel\*q"
-Enables XAA (X Acceleration Architecture), a mechanism that makes video
-cards' 2D hardware acceleration available to the  __xservername__ server.
+Enables XAA (X Acceleration Architecture), a mechanism that makes video cards'
+2D hardware acceleration available to the  __xservername__ server.
 This option is on by default, but it may be necessary to turn it off if
 there are bugs in the driver.
 There are many options to disable specific accelerated operations, listed
commit 4bcfed2f9cf5dbf682d3bc98873ba97c4efdff44
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sun Apr 20 08:35:42 2008 -0700

    Revert "Removed XWin DDX"
    
    This reverts commit 6550078b0925f754e3eec3bbce94dbfe5de8c419.
    
    Doctor, I'm starting to get a pulse...

diff --git a/.gitignore b/.gitignore
index afd5415..548e784 100644
--- a/.gitignore
+++ b/.gitignore
@@ -284,6 +284,7 @@ include/xgl-config.h
 include/xkb-config.h
 include/xorg-config.h
 include/xorg-server.h
+include/xwin-config.h
 mfb/mfbbltC.c
 mfb/mfbbltCI.c
 mfb/mfbbltG.c
diff --git a/configure.ac b/configure.ac
index ca16c5a..d3a2317 100644
--- a/configure.ac
+++ b/configure.ac
@@ -46,6 +46,8 @@ dnl xorg-config.h covers the Xorg DDX.
 AC_CONFIG_HEADERS(include/xorg-config.h)
 dnl xkb-config.h covers XKB for the Xorg and Xnest DDXs.
 AC_CONFIG_HEADERS(include/xkb-config.h)
+dnl xwin-config.h covers the XWin DDX.
+AC_CONFIG_HEADERS(include/xwin-config.h)
 dnl kdrive-config.h covers the kdrive DDX
 AC_CONFIG_HEADERS(include/kdrive-config.h)
 
@@ -564,6 +566,7 @@ AC_ARG_ENABLE(xquartz,        AS_HELP_STRING([--enable-xquartz], [Build Xquartz
 AC_ARG_ENABLE(x11app,         AS_HELP_STRING([--enable-x11app], [Build Apple's X11.app for Xquartz (default: auto)]), [X11APP=$enableval], [X11APP=auto])
 AC_ARG_WITH(x11app-archs,     AS_HELP_STRING([--with-x11app-archs=ARCHS], [Architectures to build X11.app for, space delimeted (default: "ppc i386")]), [X11APP_ARCHS=$enableval], [X11APP_ARCHS="ppc i386"])
 AC_SUBST([X11APP_ARCHS])
+AC_ARG_ENABLE(xwin,    	      AS_HELP_STRING([--enable-xwin], [Build XWin server (default: auto)]), [XWIN=$enableval], [XWIN=auto])
 AC_ARG_ENABLE(xprint,         AS_HELP_STRING([--enable-xprint], [Build Xprint extension and server (default: no)]), [XPRINT=$enableval], [XPRINT=no])
 AC_ARG_ENABLE(xgl,            AS_HELP_STRING([--enable-xgl], [Build Xgl server (default: no)]), [XGL=$enableval], [XGL=no])
 AC_ARG_ENABLE(xglx,           AS_HELP_STRING([--enable-xglx], [Build Xglx xgl module (default: no)]), [XGLX=$enableval], [XGLX=no])
@@ -1636,6 +1639,76 @@ if test "x$XPRINT" = xyes; then
 fi
 AM_CONDITIONAL(XP_USE_FREETYPE, [test "x$XPRINT" = xyes && test "x$XP_USE_FREETYPE" = xyes])
 
+
+dnl XWin DDX
+
+AC_MSG_CHECKING([whether to build XWin DDX])
+if test "x$XWIN" = xauto; then
+	case $host_os in
+		cygwin*) XWIN="yes" ;;
+		mingw*) XWIN="yes" ;;
+		*) XWIN="no" ;;
+	esac
+	XWIN_LIBS="$FB_LIB $XEXT_LIB $CONFIG_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $DAMAGE_LIB $LAYER_LIB $XPSTUBS_LIB $SHADOW_LIB"
+	AC_SUBST([XWIN_LIBS])
+fi
+AC_MSG_RESULT([$XWIN])
+
+if test "x$XWIN" = xyes; then
+	case $host_os in
+		cygwin*)
+			XWIN_SERVER_NAME=XWin
+			PKG_CHECK_MODULES([XWINMODULES],[x11 xdmcp xau xfont])
+			AC_DEFINE(HAS_DEVWINDOWS,1,[Cygwin has /dev/windows for signaling new win32 messages])
+			AC_DEFINE(ROOTLESS,1,[Build Rootless code])
+			CFLAGS="$CFLAGS -DFD_SETSIZE=256"
+			;;
+		mingw*)
+			XWIN_SERVER_NAME=Xming
+			PKG_CHECK_MODULES([XWINMODULES],[x11 xdmcp xau xfont])
+			AC_DEFINE(RELOCATE_PROJECTROOT,1,[Make PROJECT_ROOT relative to the xserver location])
+			AC_DEFINE(HAS_WINSOCK,1,[Use Windows sockets])
+			XWIN_SYS_LIBS=-lwinsock2
+			;;
+	esac
+	XWIN_SYS_LIBS="$XWIN_SYS_LIBS $(XWINMODULES_LIBS)"
+	AC_SUBST(XWIN_SERVER_NAME)
+	AC_SUBST(XWIN_SYS_LIBS)
+
+	if test "x$DEBUGGING" = xyes; then
+		AC_DEFINE(CYGDEBUG, 1, [Simple debug messages])
+		AC_DEFINE(CYGWINDOWING_DEBUG, 1, [Debug messages for window handling])
+		AC_DEFINE(CYGMULTIWINDOW_DEBUG, 1, [Debug window manager])
+	fi
+
+	AC_DEFINE(DDXOSINIT, 1, [Use OsVendorInit])
+	AC_DEFINE(DDXTIME, 1, [Use GetTimeInMillis])
+	AC_DEFINE(DDXOSFATALERROR, 1, [Use OsVendorFatalError])
+	AC_DEFINE(DDXOSVERRORF, 1, [Use OsVendorVErrorF])
+	AC_DEFINE(DDXBEFORERESET, 1, [Use ddxBeforeReset ])
+	if test "x$XF86VIDMODE" = xyes; then
+		AC_MSG_NOTICE([Disabling XF86VidMode extension])
+		XF86VIDMODE=no
+	fi
+	if test "x$XF86MISC" = xyes; then
+		AC_MSG_NOTICE([Disabling XF86Misc extension])
+		XF86MISC=no
+	fi
+	if test "x$COMPOSITE" = xyes; then
+		AC_MSG_NOTICE([Disabling Composite extension])
+		COMPOSITE=no
+	fi
+fi
+AM_CONDITIONAL(XWIN, [test "x$XWIN" = xyes])
+AM_CONDITIONAL(XWIN_MULTIWINDOW, [test "x$XWIN" = xyes])
+AM_CONDITIONAL(XWIN_MULTIWINDOWEXTWM, [test "x$XWIN" = xyes && false])
+AM_CONDITIONAL(XWIN_CLIPBOARD, [test "x$XWIN" = xyes])
+AM_CONDITIONAL(XWIN_GLX_WINDOWS, [test "x$XWIN" = xyes && false])
+AM_CONDITIONAL(XWIN_NATIVEGDI, [test "x$XWIN" = xyes && false])
+AM_CONDITIONAL(XWIN_PRIMARYFB, [test "x$XWIN" = xyes && false])
+AM_CONDITIONAL(XWIN_RANDR, [test "x$XWIN" = xyes])
+AM_CONDITIONAL(XWIN_XV, [test "x$XWIN" = xyes && test "x$XV" = xyes])
+
 dnl Darwin / OS X DDX
 if test "X$XQUARTZ" = Xauto; then
 	AC_CACHE_CHECK([whether to build Xquartz],xorg_cv_Carbon_framework,[
@@ -2133,6 +2206,7 @@ hw/xgl/glx/module/Makefile
 hw/xgl/glxext/Makefile
 hw/xgl/glxext/module/Makefile
 hw/xnest/Makefile
+hw/xwin/Makefile
 hw/xquartz/Makefile
 hw/xquartz/bundle/Makefile
 hw/xquartz/xpr/Makefile
diff --git a/hw/Makefile.am b/hw/Makefile.am
index 011a280..c2b9571 100644
--- a/hw/Makefile.am
+++ b/hw/Makefile.am
@@ -14,6 +14,10 @@ if XNEST
 XNEST_SUBDIRS = xnest
 endif
 
+if XWIN
+XWIN_SUBDIRS = xwin
+endif
+
 if XGL
 XGL_SUBDIRS = xgl
 endif
@@ -33,6 +37,7 @@ endif
 SUBDIRS =			\
 	$(XORG_SUBDIRS)		\
 	$(XGL_SUBDIRS)		\
+	$(XWIN_SUBDIRS)		\
 	$(XVFB_SUBDIRS)		\
 	$(XNEST_SUBDIRS)	\
 	$(DMX_SUBDIRS)		\
@@ -40,7 +45,7 @@ SUBDIRS =			\
 	$(XQUARTZ_SUBDIRS)	\
 	$(XPRINT_SUBDIRS)
 
-DIST_SUBDIRS = dmx xfree86 vfb xnest xquartz kdrive xgl xprint
+DIST_SUBDIRS = dmx xfree86 vfb xnest xwin xquartz kdrive xgl xprint
 
 relink:
 	for i in $(SUBDIRS) ; do $(MAKE) -C $$i relink ; done
diff --git a/hw/xwin/ChangeLog b/hw/xwin/ChangeLog
new file mode 100644
index 0000000..aca2ffc
--- /dev/null
+++ b/hw/xwin/ChangeLog
@@ -0,0 +1,683 @@
+2006-03-03  Alan Hourihane  <alanh at fairlite.demon.co.uk>
+
+	* winprefs.c: (HandleCustomWM_COMMAND):
+	https://bugs.freedesktop.org/show_bug.cgi?id=4341
+	Make Xming error messages more meaningful.
+
+2006-03-03  Alan Hourihane  <alanh at fairlite.demon.co.uk>
+
+	* winmultiwindowwndproc.c: (winTopLevelWindowProc):
+	* winwndproc.c: (winWindowProc):
+	https://bugs.freedesktop.org/show_bug.cgi?id=4538
+	Fix mouse button release on multiwindows scrolling.
+
+2006-03-03  Alan Hourihane  <alanh at fairlite.demon.co.uk>
+
+	* winmultiwindowicons.c: (winXIconToHICON), (winUpdateIcon):
+	* winwin32rootlesswindow.c: (winMWExtWMUpdateIcon):
+	https://bugs.freedesktop.org/show_bug.cgi?id=5138
+	Check for NULL pointer
+
+2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwm.c:
+	Fix crash on server shutdown
+	
+2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winkeybd.c:
+	* winkeybd.h:
+	* winwndproc.c:
+	Fix simultanious presses of Left and Right Control and Shift keys.
+	https://bugs.freedesktop.org/show_bug.cgi?id=3677
+
+2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwm.c:
+	Fix typo which broke window titles
+
+2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	* winkeybd.c:
+	Fix problem with fake Control press on Alt-Gr
+	https://bugs.freedesktop.org/show_bug.cgi?id=3680
+	https://bugs.freedesktop.org/show_bug.cgi?id=3497
+
+	* InitOutput.c:
+	Fix static declaration of winGetBaseDir
+
+2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winwindow.h:
+	* winmultiwindowwm.c:
+	* winscrinit.c:
+	External windowmanagers could connect in multiwindow mode which lead
+	to strange results with the internal windowmanager.
+
+2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* *.c:
+	Include xwin-config.h if HAVE_XWIN_CONFIG is defined
+	Cleanup X11 includes handling
+	Warning fixes
+	
+2005-06-30  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	Pass serverClient instead of NULL to ConfigureWindow.
+	This should fix a crash reported by Øyvind Harboe
+
+2005-06-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winlayouts.h:
+	Merge from CYGWIN
+	Added layout "French (Canada)" as ca_enhanced 
+	Added Czech (QWERTY) layout
+	* winshaddnl.c:
+	Merge from CYGWIN
+	Print error code if winStoreColorsShadowDDNL fails
+
+2005-06-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwindow.c:
+	Fix crash reported by Øyvind Harboe
+
+2005-06-03  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	* winblock.c:
+	Backout last winRaiseWindow patch which caused stacking problems
+
+2005-05-25  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* win.h:
+	* winmultiwindowwm.c:
+	Workaround bug in pthread.h
+
+2005-05-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	* winblock.c:
+	Only call ConfigureWindow from winRaiseWindow if the windows
+	message dispatch loop is running.
+
+2005-05-02  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winerror.c:
+	Print correct logfile in FatalError message
+
+2005-04-19  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	Prevent recursive calls to winRaiseWindow. 
+
+2005-03-10  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	Force rebuilding of window stack if a window changes it's state from 
+	minimized.
+
+2005-03-07  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	* winmultiwindowwindow.c:
+	Prevent winRaiseWindow from calling ConfigureWindow if the message
+	was sent from within winDestroyWindowsWindow
+
+	DestroyWindow send a WM_WINDOWPOSCHANGED to another window causing
+	a restacking of all windows, even of the window which is just about
+	to destroyed and whose structures may not be intact anymore.
+
+2005-02-24  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	on WM_WINDOWPOSCHANGED raise window directly and in sync without 
+	utilizing the async windowmanager thread. Fixes some restacking 
+	problems occuring which were timing dependent
+	Do not raise the window on WM_ACTIVATE
+	Removed unused code for WM_WINDOWPOSCHANGING
+	ESC is debug key. Print status but do not abort processing the message
+	
+2005-02-12  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwindow.c
+	* winmultiwindowwndproc.c
+	* winwin32rootlesswndproc.c:
+	Cleanup some message debugging
+	
+2005-02-12  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* win.h
+	* winfont.c
+	* winmultiwindowshape.c
+	* winmultiwindowwindow.c
+	* winpfbdd.c
+	* winshaddd.c
+	* winshadddnl.c
+	* winshadgdi.c
+	* winwindow.c:
+	Fix incorrect wrapping of functions. Ensure the pointers from pScreen 
+	point to the called function even if wrapped functions changed it
+	
+	* winmultiwindowwindow.c:
+	Set the window properties to NULL to avoid referencing freed memory 
+	because of timing problems after deleting a window
+
+	* winscrinit.c:
+	Do not wrap ChangeWindowAttributes. All functions are noops currently
+	
+2005-02-12  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmsg.h:
+	* winmsg.c:
+	print window handle in message output
+	
+2005-02-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winkeybd.c:
+	* winkeynames.h:
+	Updated fix for ABNT2 and HK_Toggle keys. 
+
+2005-02-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winkeybd.h:
+	* winkeynames.h:
+	Backout ABNT2 and HK_Toggle fix since it broke keys F1 and F4. 
+
+2005-02-07  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winlayouts.h:
+	* winconfig.c:
+	Moved keyboard layout table to external file.
+
+2005-02-02  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* wincreatewnd.c:
+	Force ShowWindow if XWin was started via run.exe. Fixes mainwindow
+	not showing bug
+
+2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwindow.c
+	* winmultiwindowwndproc.c:
+	Create windows with SWP_NOACTIVATE flag (updated) (Kensuke Matsuzaki)
+
+2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwndproc.c:
+	Fixes for window ordering problem (updated) (Kensuke Matsuzaki)
+
+2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winconfig.c:
+	Added hungarian keyboard layout.
+
+2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmessages.h
+	* winmsg.h
+	* winmsg.c
+	* winmultiwindowwndproc.c
+	* winwin32rootlesswndproc.c
+	* winwndproc.c:
+	Make logging of messages configurable with environment variables
+
+2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* InitOutput.c:
+	resolve SHGetFolderPath dynamicly since it is not available on all Windows 
+	systems.
+
+2005-01-12  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmsg.c
+	* winmsg.h:
+	Introduce function winTrace which prints log message with verbosity 10
+	* winmultiwindowwindow.c:
+	Use winTrace for 3 heavily called functions
+
+2005-01-11  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* XWin.man:
+	Document the -silent-dup-error switch
+
+2005-01-11  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winkeyhook.c:
+	Do not grab ALT-TAB when window is in multiwindow mode
+	
+2005-01-11  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winprefs.h:
+	Fix crash with not matching definitions of PATH_MAX
+	
+2005-01-10  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winkeybd.h
+	* winkeynames.h:
+	Adjust keysyms for  Hiragana_Katakana toggle and backslash/underscore
+	on Japanese and ABNT2 keyboards
+
+2005-01-10  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winkeybd.h
+	* winkeyhook.c
+	* winwndproc.c:
+	Make keyhook feature work in multiwindowmode too
+	Hook windows keys
+
+2005-01-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winblock.c:
+	Fix a possible null-pointer dereference	(Keishi Suenaga)
+
+2005-01-06  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* Imakefile 
+	* InitOutput.c 
+	* XWin.rc 
+	* winerror.c 
+	* wintrayicon.c 
+	* winvideo.c
+	* winshaddd.c       	
+	* winwindow.h:
+	Set PROJECT_NAME in Imakefile to create alternative window titles 
+	for Cygwin/X and Xming
+	
+2005-01-06  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowclass.c:
+	* winmultiwindowwm.c:
+	Fix crash with non-nullterminated strings (reported by Øyvind Harboe)
+
+2004-12-14  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* InitOutput.c:
+	* winprocarg.c:
+	EnumDisplayMonitors is not available on Window NT4 and 95. Resolve
+	the function dynamicly
+
+2004-12-08  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* InitOutput.c:
+	* winprocarg.c:
+	Added support for placing the main window with the @<monitor#>.
+	Patch by Mark Fisher, small changes by Alexander Gottwald
+	
+2004-12-06  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* XWin.rc:
+	include windows.h
+
+2004-12-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* ddraw.h:
+	redone ddraw.h to be able to mix it with w32api style COM header 
+	files. 
+	
+	* winmultiwindowwm.c:
+	* obj_base.h:
+	* ddraw.h:
+	obj_base.h is not needed anymore. Using <objbase.h> instead.
+
+	* winms.h:
+	Use Xwindows.h instead of windows.h
+
+	* winresource.h:
+	do not include win_ms.h
+	
+	* win.h:
+	remove extra definition of sleep()
+
+	* InitOutput.c:
+	Set HOME to Documents and Settings/username if not set
+	
+	* winprefs.c:
+	Use Xming basedir instead of ProjectRoot for system.XWinrc
+
+	* windialogs.c:
+	* winshadgdi.c:
+	* winprefs.c:
+	Fix callback functions to use wBOOL instead of BOOL
+
+	* winmultiwindowwindow.c:
+	* winwin32rootless.c:
+	* winwin32rootlesswindow.c:
+	* winerror.c:
+	Fix compiler warnings. Added debug output.
+
+	* winconfig.c:
+	Fix warning about undefined macro max
+	
+2004-12-04  Earle Philhower
+
+	* InitOutput.c:
+	* win.h:
+	* wincreatewnd.c:
+	* winprocarg.c:
+	Optional position -screen parameter (-screen n WxH+X+Y or 
+	-screen n W H X Y)
+
+2004-12-03  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* windialogs.c:
+	* win.h:
+	* Imakefile:
+	* winerror.c:
+	Removed scprintf, aprintf and snprintf stuff and use newXprintf
+
+2004-12-02  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winwin32rootless.c:
+	Adjust the width of the rootless backbuffer to match 32 bit alignment
+
+	* winprocarg.c:
+	Make multiplemonitors default for -internalwm
+
+2004-12-01  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* InitOutput.c:
+	Set XERRORDB environment variable to relocate the XErrorDB file
+
+2004-11-29  Kensuke Matsuzaki  <zakki at peppermint.jp>
+
+	* winmultiwindowwm.c:
+	Fixed windows.h include for cygwin.
+	
+	* winmultiwindowwindow.c:
+	Bugzilla #1945: Stop unnecessary reordering.
+
+2004-11-24  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwm.c:
+	Finally the multiwindow mode defines a default cursor
+
+2004-11-22  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmultiwindowwm.c: 
+	Fixes for building multiwindow and internalwm on mingw
+	* winwin32rootless.c:
+	Changed some debugging output
+
+2004-11-22  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* InitOutput.c, winglobals.c, winprocarg.c:
+	Xming: Place logfile in users tempdir
+	
+2004-11-15  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* Imakefile:
+	Remove override of HasSnprintf
+
+2004-11-15  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* Imakefile:
+	* InitInput.c: (InitInput):
+	* InitOutput.c: (winClipboardShutdown), (ddxGiveUp),
+	(winCheckMount), (winGetBaseDir), (winFixupPaths), (OsVendorInit),
+	(winCheckDisplayNumber):
+	* win.h:
+	* winblock.c: (winBlockHandler):
+	* winclipboard.h:
+	* winclipboardthread.c: (winClipboardProc):
+	* winclipboardwndproc.c: (winClipboardWindowProc):
+	* winconfig.c: (winConfigKeyboard), (winConfigFiles):
+	* wincreatewnd.c: (winCreateBoundingWindowWindowed):
+	* windialogs.c: (winDisplayExitDialog), (winExitDlgProc),
+	(winAboutDlgProc):
+	* winengine.c: (winSetEngine):
+	* winerror.c: (OsVendorVErrorF), (winMessageBoxF), (scprintf):
+	* winglobals.c: (winInitializeGlobals):
+	* winkeybd.c: (winKeybdReleaseKeys):
+	* winmultiwindowicons.c:
+	* winmultiwindowwindow.c: (winCreateWindowsWindow):
+	* winmultiwindowwm.c:
+	* winprefs.c: (ReloadPrefs), (HandleCustomWM_COMMAND):
+	* winprocarg.c: (ddxProcessArgument):
+	* winscrinit.c: (winFinishScreenInitFB):
+	* winshadddnl.c:
+	* wintrayicon.c: (winHandleIconMessage):
+	* winwakeup.c: (winWakeupHandler):
+	* winwin32rootless.c: (winMWExtWMCreateFrame):
+	* winwindow.c: (winReshapeRootless):
+	* winwindow.h:
+	* winwndproc.c: (winWindowProc):
+	Bufzilla #1802, http://freedesktop.org/bugzilla/show_bug.cgi?id=1802
+	Added mingw (Win32) port     
+
+2004-11-11  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winconfig.c:
+	added keyboard layout "French (Switzerland)"
+
+2004-11-06  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winwndproc.c, wintrayicon.c, winscrinit.c:
+	* winmultiwindowwindow.c:
+	Wrap all mwextwm and internalwm code with XWIN_MULTIWINDOWEXTWM
+
+2004-11-04  Kensuke Matsuzaki  <zakki at peppermint.jp>
+
+	* InitOutput.c: (winUseMsg):
+	* win.h:
+	* winmultiwindowwindow.c: (winMinimizeWindow):
+	* winmultiwindowwm.c: (PushMessage), (UpdateName),
+	(PreserveWin32Stack), (winMultiWindowWMProc),
+	(winMultiWindowXMsgProc), (winInitWM), (winInitMultiWindowWM),
+	(CheckAnotherWindowManager):
+	* winprocarg.c: (winInitializeDefaultScreens),
+	(ddxProcessArgument):
+	* winscrinit.c: (winFinishScreenInitFB):
+	* wintrayicon.c: (winHandleIconMessage):
+	* winwin32rootless.c: (InitWin32RootlessEngine),
+	(winMWExtWMResizeFrame), (winMWExtWMRestackFrame),
+	(winMWExtWMStartDrawing), (winMWExtWMRootlessSwitchWindow),
+	(winMWExtWMSetNativeProperty):
+	* winwin32rootlesswindow.c: (winMWExtWMReorderWindows),
+	(winMWExtWMDecorateWindow), (winMWExtWMUpdateWindowDecoration),
+	(winIsInternalWMRunning), (winMWExtWMRestackWindows):
+	* winwin32rootlesswndproc.c: (winMWExtWMWindowProc):
+	* winwindow.h:
+	* winwndproc.c: (winWindowProc):
+	Add internalwm mode.
+
+2004-10-28  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* win.h:
+	add fRetryCreateSurface
+	* winshaddnl.c (winBltExposedRegionsShadowDDNL):
+	try to recreate the primary surface if it was lost
+	* winshaddnl.c (winCreatePrimarySurfaceShadowDDNL):
+	mark screen to retry creating the primary surface if it failed
+
+2004-10-23  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winconfig (winConfigFiles):
+	Simplify /etc/X11/font-dirs parsing
+
+2004-10-20  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* XWin.rc, winresource.h, winwndproc.c:
+	Add ShowCursor entry to tray menu 
+
+2004-10-20  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* Imakefile:
+	Add ETCX11DIR to DEFINES
+	* InitOutput.c (InitOutput):
+	* winconfig.c (winConfigFiles) :
+	Add entries from /etc/X11/font-dirs to default fontpath
+
+2004-10-16  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winprocarg.c (winInitializeDefaultScreens, ddxProcessArgument):
+	* win.h:
+	Make multiple monitors default for -multiwindow and -mwextwm.
+	Added a flag to indicate if the user has overridden the multimonitor
+	settings. (Øyvind Harboe, Alexander Gottwald)
+
+2004-10-07  Torrey Lyons  <torrey at freedesktop dot org>
+
+	* winscrinit.c:
+	Add compatibility with the generic rootless layer's new
+	DoReorderWindow function.
+
+2004-10-05  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* XWin.rc:
+	Set the dialogstyle to DS_CENTERMOUSE. Dialogs will now popup on the
+	monitor where the mouse is and not on the center of the whole desktop.
+
+2004-10-02  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winmouse.c (winMouseProc):
+	Make sure buttons 1-3 are mouse buttons and wheel events are 4-5
+	Document code
+	Replace ErrorF with appropriate winMsg
+	use a symbolic name for the wheel event offset
+	
+2004-10-01  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* wincreatewnd.c (winCreateBoundingWindowWindowed):
+	Do not adjust workarea if native windowmanager is used
+
+2004-09-22  Kensuke Matsuzaki
+
+	* winclipboardthread.c (winClipboardErrorHandler):
+	* winclipboardwndproc.c (winClipboardWindowProc):
+	* winclipboardxevents.c (winClipboardFlushXEvents):
+	Fix clipboard bug with unicode applications.
+	
+2004-09-17  Torrey Lyons  <torrey at freedesktop dot org>
+
+	* winscrinit.c: (winFinishScreenInitFB):
+	Bugzilla #1032: Make rootless acceleration functions compatible with
+	Damage.
+
+2004-09-16  Alexander Gottwald <ago at freedesktop dot org>
+
+	* wincreatewnd.c (winCreateBoundingWindowWindowed):
+	Remove code which prevented the use from specifying the window
+	size in nodecoration mode. 	
+
+2004-08-26  Chris B  <news at sempermax dot com>
+
+	* win.h, winmessages.h:
+	Add defines for WM_XBUTTON
+	* winmouse.c (winMouseProc):
+	Query number of mouse buttons from windows. 
+	* winmultiwindowwndproc.c (winTopLevelWindowProc):
+	* winwin32rootlesswndproc.c (winMWExtWMWindowProc):
+	* winwndproc.c (winWindowProc):
+	Handle WM_XBUTTON messages.  
+
+2004-08-02  Kensuke Matsuzaki
+
+	* winclipboardthread.c winclipboardwndproc.c: 
+	* winclipboardxevents.c winwin32rootlesswndproc.c:
+	Fix the bug that we can't copy & paste multi-byte string to
+	Unicode-base Windows application.  Rename fUnicodeSupport to
+	fUseUnicode, because it don't mean wheather Windows support
+	Unicode or not.
+	
+2004-07-31  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* win.h:
+	adjust prototype for winInitCmapPrivates to match Egberts change.	
+
+2004-07-30  Egbert Eich  <eich at freedesktop dot org>
+
+	* winallpriv.c: (winInitCmapPrivates):
+	test if colormap with index really exists in the list of
+	installed maps before using it.
+
+2004-07-09  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winconfig.c: Add entry for irish layout (ie)
+	* InitOutput.c, winerror.c, winglobals.c: rename g_fUseMsg to 
+	g_fSilentFatalError
+	* InitOutput.c, winglobals.c, winprocarg.c: added commandline option 
+	-silent-dup-error to allow silent termination if another instance of
+	XWin was found running
+
+2004-06-27  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winconfig.c: Add entry for us layout. This changes not much but 
+	removes a strange error message about the unknown us layout. 
+
+2004-06-24  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* InitOutput.c: Check for textmode mounted /tmp and print a warning
+
+2004-06-15  Harold Hunt  <huntharo at msu dot edu>
+
+	* windialogs.c: Fix path to locally installed changelog for the About 
+	dialog box.
+
+2004-05-27  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* winpriv.c: Create win32 window if not already created
+	* winmultiwindowwindow.c: Export winCreateWindowWindow
+
+2004-05-27  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* win.h: Allow CYGDEBUG to defined in the Makefile
+	* winwindow.h: Allow CYGWINDOWING_DEBUG to defined in the Makefile
+
+2004-05-19  Alexander Gottwald  <ago at freedesktop dot org>
+	
+	* winmultiwindowicons.c (winInitGlobalIcons): Load the small default
+	icon too
+	* winprefs.h, winprefs.c (winOverrideDefaultIcon): Takes the iconsize
+	as parameter
+
+2004-05-19  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* win.h, winmultiwindowicons.c (winXIconToHICON): Takes iconsize
+	as parameter 
+	* winglobals.c, winmultiwindowicons.c: Rename g_hiconX to g_hIconX.
+	Added new variable g_hSmallIconX for 16x16 icon.
+	* winwindow.h, winmultiwindowicons.c (winInitGlobalIcons): Inits the 
+	global g_hIconX handles.
+	* winwindow.h, winmultiwindowicons.c (winDestroyIcon): Free the icon
+	without messing with the global icon handle. 
+	* winmultiwindowicons.c (winSelectIcons): Generate a custom icon from
+	window settigns or set them to globals.
+	* winmultiwindowshape.c, winmultiwindowwindow.c, winwin32rootless.c,
+	  winwin32rootlesswindow.c, winwin32rootlesswndproc.c: Remove 
+	declaration of g_hiconX;
+	* winmultiwindowwindow.c (winCreateWindowsWindow),
+	  winwin32rootless.c (winMWExtWMCreateFrame): Use winSelectIcons 
+	to get the window icons. Set the small icon too.
+	* winmultiwindowwindow.c (winDestroyWindowsWindow),
+	  winmultiwindowicons.c (winUpdateIcon), 
+	  winprefs.c (ReloadEnumWindowsProc),
+	  winwin32rootlesswindow.c (winMWExtWMUpdateIcon),
+	  winwin32rootless.c (winMWExtWMDestroyFrame): Use winDestroyIcon
+	to free the icon without destroying the global icon.  
+	  
+2004-05-17  Alexander Gottwald  <ago at freedesktop dot org>
+
+	* windialogs.c (winExitDlgProc, winAboutDlgProc),
+	  winmultiwindowwndproc.c (winTopLevelWindowProc),
+	  winwndproc.c (winWindowProc): Check if g_fSoftwareCursor is set 
+	before calling ShowCursor.  
+
+2004-05-09  Dan Wilks  <Dan_Wilks at intuit dot com>
+    
+	* winclipboard.h: Add extern prototypes for winDebug, winErrorFVerb
+	copied from winmsg.h.
+	* winclipboardinit.c (winFixClipboardChain): Post rather than send the
+	reinit message to the clipboard window.  Sending the message caused,
+	or possibly just exacerbated an existing, race condition that would
+	cause the X server to hang when coming back from a remote desktop
+	session.
+	* winclipboardwndproc.c (winProcessXEventsTimeout): switch to new
+	logging api's.
+	* winclipboardwindproc.c (winClipboardWindowProc): switch to new 
+	logging api's.  Add some additional debug logging.  Make best effort 
+	to prevent our window appearing twice in the clipboard chain.  Also 
+	detect loops when they occur and try to behave in a reasonable way.
+
+# vim:ts=8:noexpandtab:encoding=utf8        
diff --git a/hw/xwin/InitInput.c b/hw/xwin/InitInput.c
new file mode 100644
index 0000000..6a850cd
--- /dev/null
+++ b/hw/xwin/InitInput.c
@@ -0,0 +1,177 @@
+/*
+
+  Copyright 1993, 1998  The Open Group
+
+  Permission to use, copy, modify, distribute, and sell this software and its
+  documentation for any purpose is hereby granted without fee, provided that
+  the above copyright notice appear in all copies and that both that
+  copyright notice and this permission notice appear in supporting
+  documentation.
+
+  The above copyright notice and this permission notice shall be included
+  in all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+  IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
+  OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+  ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+  OTHER DEALINGS IN THE SOFTWARE.
+
+  Except as contained in this notice, the name of The Open Group shall
+  not be used in advertising or otherwise to promote the sale, use or
+  other dealings in this Software without prior written authorization
+  from The Open Group.
+
+*/
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#ifdef XWIN_CLIPBOARD
+# include "../../Xext/xf86miscproc.h"
+#endif
+#include "dixstruct.h"
+
+
+/*
+ * Local function prototypes
+ */
+
+#ifdef XWIN_CLIPBOARD
+DISPATCH_PROC(winProcEstablishConnection);
+DISPATCH_PROC(winProcQueryTree);
+DISPATCH_PROC(winProcSetSelectionOwner);
+#endif
+
+
+/*
+ * Local global declarations
+ */
+
+CARD32				g_c32LastInputEventTime = 0;
+
+
+/*
+ * References to external symbols
+ */
+
+#ifdef HAS_DEVWINDOWS
+extern int			g_fdMessageQueue;
+#endif
+extern Bool			g_fXdmcpEnabled;
+#ifdef XWIN_CLIPBOARD
+extern winDispatchProcPtr	winProcEstablishConnectionOrig;
+extern winDispatchProcPtr	winProcQueryTreeOrig;
+#endif
+
+
+/* Called from dix/devices.c */
+/*
+ * All of our keys generate up and down transition notifications,
+ * so all of our keys can be used as modifiers.
+ * 
+ * An example of a modifier is mapping the A key to the Control key.
+ * A has to be a legal modifier.  I think.
+ */
+
+Bool
+LegalModifier (unsigned int uiKey, DeviceIntPtr pDevice)
+{
+  return TRUE;
+}
+
+
+/* Called from dix/dispatch.c */
+/*
+ * Run through the Windows message queue(s) one more time.
+ * Tell mi to dequeue the events that we have sent it.
+ */
+void
+ProcessInputEvents (void)
+{
+#if 0
+  ErrorF ("ProcessInputEvents\n");
+#endif
+
+  mieqProcessInputEvents ();
+  miPointerUpdate ();
+
+#if 0
+  ErrorF ("ProcessInputEvents - returning\n");
+#endif
+}
+
+
+int
+TimeSinceLastInputEvent ()
+{
+  if (g_c32LastInputEventTime == 0)
+    g_c32LastInputEventTime = GetTickCount ();
+  return GetTickCount () - g_c32LastInputEventTime;
+}
+
+
+/* See Porting Layer Definition - p. 17 */
+void
+InitInput (int argc, char *argv[])
+{
+  DeviceIntPtr		pMouse, pKeyboard;
+
+#if CYGDEBUG
+  winDebug ("InitInput\n");
+#endif
+
+#ifdef XWIN_CLIPBOARD
+  /*
+   * Wrap some functions at every generation of the server.
+   */
+  if (InitialVector[2] != winProcEstablishConnection)
+    {
+      winProcEstablishConnectionOrig = InitialVector[2];
+      InitialVector[2] = winProcEstablishConnection;
+    }
+  if (g_fXdmcpEnabled
+      && ProcVector[X_QueryTree] != winProcQueryTree)
+    {
+      winProcQueryTreeOrig = ProcVector[X_QueryTree];
+      ProcVector[X_QueryTree] = winProcQueryTree;
+    }
+#endif
+
+  pMouse = AddInputDevice (winMouseProc, TRUE);
+  pKeyboard = AddInputDevice (winKeybdProc, TRUE);
+  
+  RegisterPointerDevice (pMouse);
+  RegisterKeyboardDevice (pKeyboard);
+
+  miRegisterPointerDevice (screenInfo.screens[0], pMouse);
+  mieqInit ((DevicePtr)pKeyboard, (DevicePtr)pMouse);
+
+  /* Initialize the mode key states */
+  winInitializeModeKeyStates ();
+
+#ifdef HAS_DEVWINDOWS
+  /* Only open the windows message queue device once */
+  if (g_fdMessageQueue == WIN_FD_INVALID)
+    {
+      /* Open a file descriptor for the Windows message queue */
+      g_fdMessageQueue = open (WIN_MSG_QUEUE_FNAME, O_RDONLY);
+      
+      if (g_fdMessageQueue == -1)
+	{
+	  FatalError ("InitInput - Failed opening %s\n",
+		      WIN_MSG_QUEUE_FNAME);
+	}
+
+      /* Add the message queue as a device to wait for in WaitForSomething */
+      AddEnabledDevice (g_fdMessageQueue);
+    }
+#endif
+
+#if CYGDEBUG
+  winDebug ("InitInput - returning\n");
+#endif
+}
diff --git a/hw/xwin/InitOutput.c b/hw/xwin/InitOutput.c
new file mode 100644
index 0000000..d215981
--- /dev/null
+++ b/hw/xwin/InitOutput.c
@@ -0,0 +1,1144 @@
+/*
+
+Copyright 1993, 1998  The Open Group
+
+Permission to use, copy, modify, distribute, and sell this software and its
+documentation for any purpose is hereby granted without fee, provided that
+the above copyright notice appear in all copies and that both that
+copyright notice and this permission notice appear in supporting
+documentation.
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of The Open Group shall
+not be used in advertising or otherwise to promote the sale, use or
+other dealings in this Software without prior written authorization
+from The Open Group.
+
+*/
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winmsg.h"
+#include "winconfig.h"
+#include "winprefs.h"
+#ifdef XWIN_CLIPBOARD
+#include "X11/Xlocale.h"
+#endif
+#ifdef DPMSExtension
+#include "dpmsproc.h"
+#endif
+#ifdef __CYGWIN__
+#include <mntent.h>
+#endif
+#if defined(XKB) && defined(WIN32)
+#include <xkbsrv.h>
+#endif
+#ifdef RELOCATE_PROJECTROOT
+#include <shlobj.h>
+typedef HRESULT (*SHGETFOLDERPATHPROC)(
+    HWND hwndOwner,
+    int nFolder,
+    HANDLE hToken,
+    DWORD dwFlags,
+    LPTSTR pszPath
+);
+#endif
+
+
+/*
+ * References to external symbols
+ */
+
+extern int			g_iNumScreens;
+extern winScreenInfo		g_ScreenInfo[];
+extern int			g_iLastScreen;
+extern char *			g_pszCommandLine;
+extern Bool			g_fSilentFatalError;
+
+extern char *			g_pszLogFile;
+extern Bool			g_fLogFileChanged;
+extern int			g_iLogVerbose;
+Bool				g_fLogInited;
+
+extern Bool			g_fXdmcpEnabled;
+#ifdef HAS_DEVWINDOWS
+extern int			g_fdMessageQueue;
+#endif
+extern const char *		g_pszQueryHost;
+extern HINSTANCE		g_hInstance;
+
+#ifdef XWIN_CLIPBOARD
+extern Bool			g_fUnicodeClipboard;
+extern Bool			g_fClipboardLaunched;
+extern Bool			g_fClipboardStarted;
+extern pthread_t		g_ptClipboardProc;
+extern HWND			g_hwndClipboard;
+extern Bool			g_fClipboard;
+#endif
+
+extern HMODULE			g_hmodDirectDraw;
+extern FARPROC			g_fpDirectDrawCreate;
+extern FARPROC			g_fpDirectDrawCreateClipper;
+  
+extern HMODULE			g_hmodCommonControls;
+extern FARPROC			g_fpTrackMouseEvent;
+extern Bool			g_fNoHelpMessageBox;                     
+extern Bool			g_fSilentDupError;                     
+  
+  
+/*
+ * Function prototypes
+ */
+
+#ifdef XWIN_CLIPBOARD
+static void
+winClipboardShutdown (void);
+#endif
+
+#if defined(DDXOSVERRORF)
+void
+OsVendorVErrorF (const char *pszFormat, va_list va_args);
+#endif
+
+void
+winInitializeDefaultScreens (void);
+
+static Bool
+winCheckDisplayNumber (void);
+
+void
+winLogCommandLine (int argc, char *argv[]);
+
+void
+winLogVersionInfo (void);
+
+Bool
+winValidateArgs (void);
+
+#ifdef RELOCATE_PROJECTROOT
+const char *
+winGetBaseDir(void);
+#endif
+
+/*
+ * For the depth 24 pixmap we default to 32 bits per pixel, but
+ * we change this pixmap format later if we detect that the display
+ * is going to be running at 24 bits per pixel.
+ *
+ * FIXME: On second thought, don't DIBs only support 32 bits per pixel?
+ * DIBs are the underlying bitmap used for DirectDraw surfaces, so it
+ * seems that all pixmap formats with depth 24 would be 32 bits per pixel.
+ * Confirm whether depth 24 DIBs can have 24 bits per pixel, then remove/keep
+ * the bits per pixel adjustment and update this comment to reflect the
+ * situation.  Harold Hunt - 2002/07/02
+ */
+
+static PixmapFormatRec g_PixmapFormats[] = {
+  { 1,    1,      BITMAP_SCANLINE_PAD },
+  { 4,    8,      BITMAP_SCANLINE_PAD },
+  { 8,    8,      BITMAP_SCANLINE_PAD },
+  { 15,   16,     BITMAP_SCANLINE_PAD },
+  { 16,   16,     BITMAP_SCANLINE_PAD },
+  { 24,   32,     BITMAP_SCANLINE_PAD },
+#ifdef RENDER
+  { 32,   32,     BITMAP_SCANLINE_PAD }
+#endif
+};
+
+const int NUMFORMATS = sizeof (g_PixmapFormats) / sizeof (g_PixmapFormats[0]);
+
+#ifdef XWIN_CLIPBOARD
+static void
+winClipboardShutdown (void)
+{
+  /* Close down clipboard resources */
+  if (g_fClipboard && g_fClipboardLaunched && g_fClipboardStarted)
+    {
+      /* Synchronously destroy the clipboard window */
+      if (g_hwndClipboard != NULL)
+	{
+	  SendMessage (g_hwndClipboard, WM_DESTROY, 0, 0);
+	  /* NOTE: g_hwndClipboard is set to NULL in winclipboardthread.c */
+	}
+      else
+	return;
+      
+      /* Wait for the clipboard thread to exit */
+      pthread_join (g_ptClipboardProc, NULL);
+
+      g_fClipboardLaunched = FALSE;
+      g_fClipboardStarted = FALSE;
+
+      winDebug ("winClipboardShutdown - Clipboard thread has exited.\n");
+    }
+}
+#endif
+
+
+#if defined(DDXBEFORERESET)
+/*
+ * Called right before KillAllClients when the server is going to reset,
+ * allows us to shutdown our seperate threads cleanly.
+ */
+
+void
+ddxBeforeReset (void)
+{
+  winDebug ("ddxBeforeReset - Hello\n");
+
+#ifdef XWIN_CLIPBOARD
+  winClipboardShutdown ();
+#endif
+}
+#endif
+
+
+/* See Porting Layer Definition - p. 57 */
+void
+ddxGiveUp (void)
+{
+  int		i;
+
+#if CYGDEBUG
+  winDebug ("ddxGiveUp\n");
+#endif
+
+  /* Perform per-screen deinitialization */
+  for (i = 0; i < g_iNumScreens; ++i)
+    {
+      /* Delete the tray icon */
+      if (!g_ScreenInfo[i].fNoTrayIcon && g_ScreenInfo[i].pScreen)
+ 	winDeleteNotifyIcon (winGetScreenPriv (g_ScreenInfo[i].pScreen));
+    }
+
+#ifdef XWIN_MULTIWINDOW
+  /* Notify the worker threads we're exiting */
+  winDeinitMultiWindowWM ();
+#endif
+
+#ifdef HAS_DEVWINDOWS
+  /* Close our handle to our message queue */
+  if (g_fdMessageQueue != WIN_FD_INVALID)
+    {
+      /* Close /dev/windows */
+      close (g_fdMessageQueue);
+
+      /* Set the file handle to invalid */
+      g_fdMessageQueue = WIN_FD_INVALID;
+    }
+#endif
+
+  if (!g_fLogInited) {
+    LogInit (g_pszLogFile, NULL);
+    g_fLogInited = TRUE;
+  }  
+  LogClose ();
+
+  /*
+   * At this point we aren't creating any new screens, so
+   * we are guaranteed to not need the DirectDraw functions.
+   */
+  if (g_hmodDirectDraw != NULL)
+    {
+      FreeLibrary (g_hmodDirectDraw);
+      g_hmodDirectDraw = NULL;
+      g_fpDirectDrawCreate = NULL;
+      g_fpDirectDrawCreateClipper = NULL;
+    }
+
+  /* Unload our TrackMouseEvent funtion pointer */
+  if (g_hmodCommonControls != NULL)
+    {
+      FreeLibrary (g_hmodCommonControls);
+      g_hmodCommonControls = NULL;
+      g_fpTrackMouseEvent = (FARPROC) (void (*)(void))NoopDDA;
+    }
+  
+  /* Free concatenated command line */
+  if (g_pszCommandLine)
+    {
+      free (g_pszCommandLine);
+      g_pszCommandLine = NULL;
+    }
+
+  /* Remove our keyboard hook if it is installed */
+  winRemoveKeyboardHookLL ();
+
+  /* Tell Windows that we want to end the app */
+  PostQuitMessage (0);
+}
+
+
+/* See Porting Layer Definition - p. 57 */
+void
+AbortDDX (void)
+{
+#if CYGDEBUG
+  winDebug ("AbortDDX\n");
+#endif
+  ddxGiveUp ();
+}
+
+#ifdef __CYGWIN__
+/* hasmntopt is currently not implemented for cygwin */
+static const char *winCheckMntOpt(const struct mntent *mnt, const char *opt)
+{
+    const char *s;
+    size_t len;
+    if (mnt == NULL)
+        return NULL;
+    if (opt == NULL)
+        return NULL;
+    if (mnt->mnt_opts == NULL)
+        return NULL;
+
+    len = strlen(opt);
+    s = strstr(mnt->mnt_opts, opt);
+    if (s == NULL)
+        return NULL;
+    if ((s == mnt->mnt_opts || *(s-1) == ',') &&  (s[len] == 0 || s[len] == ','))
+        return (char *)opt;
+    return NULL;
+}
+
+static void
+winCheckMount(void)
+{
+  FILE *mnt;
+  struct mntent *ent;
+
+  enum { none = 0, sys_root, user_root, sys_tmp, user_tmp } 
+    level = none, curlevel;
+  BOOL binary = TRUE;
+
+  mnt = setmntent("/etc/mtab", "r");
+  if (mnt == NULL)
+  {
+    ErrorF("setmntent failed");
+    return;
+  }
+
+  while ((ent = getmntent(mnt)) != NULL)
+  {
+    BOOL system = (strcmp(ent->mnt_type, "system") == 0);
+    BOOL root = (strcmp(ent->mnt_dir, "/") == 0);
+    BOOL tmp = (strcmp(ent->mnt_dir, "/tmp") == 0);
+    
+    if (system)
+    {
+      if (root)
+        curlevel = sys_root;
+      else if (tmp)
+        curlevel = sys_tmp;
+      else
+        continue;
+    }
+    else
+    {
+      if (root)
+        curlevel = user_root;
+      else if (tmp) 
+        curlevel = user_tmp;
+      else
+        continue;
+    }
+
+    if (curlevel <= level)
+      continue;
+    level = curlevel;
+
+    if (winCheckMntOpt(ent, "binmode") == NULL)
+      binary = 0;
+    else
+      binary = 1;
+  }
+    
+  if (endmntent(mnt) != 1)
+  {
+    ErrorF("endmntent failed");
+    return;
+  }
+  
+ if (!binary) 
+   winMsg(X_WARNING, "/tmp mounted int textmode\n"); 
+}
+#else
+static void
+winCheckMount(void) 
+{
+}
+#endif
+
+#ifdef RELOCATE_PROJECTROOT
+const char * 
+winGetBaseDir(void)
+{
+    static BOOL inited = FALSE;
+    static char buffer[MAX_PATH];
+    if (!inited)
+    {
+        char *fendptr;
+        HMODULE module = GetModuleHandle(NULL);
+        DWORD size = GetModuleFileName(module, buffer, sizeof(buffer));
+        if (sizeof(buffer) > 0)
+            buffer[sizeof(buffer)-1] = 0;
+    
+        fendptr = buffer + size;
+        while (fendptr > buffer)
+        {
+            if (*fendptr == '\\' || *fendptr == '/')
+            {
+                *fendptr = 0;
+                break;
+            }
+            fendptr--;
+        }
+        inited = TRUE;
+    }
+    return buffer;
+}
+#endif
+
+static void
+winFixupPaths (void)
+{
+    BOOL changed_fontpath = FALSE;
+    MessageType font_from = X_DEFAULT;
+#ifdef RELOCATE_PROJECTROOT
+    const char *basedir = winGetBaseDir();
+    size_t basedirlen = strlen(basedir);
+#endif
+
+#ifdef READ_FONTDIRS
+    {
+        /* Open fontpath configuration file */
+        FILE *fontdirs = fopen(ETCX11DIR "/font-dirs", "rt");
+        if (fontdirs != NULL)
+        {
+            char buffer[256];
+            int needs_sep = TRUE; 
+            int comment_block = FALSE;
+
+            /* get defautl fontpath */
+            char *fontpath = xstrdup(defaultFontPath);
+            size_t size = strlen(fontpath);
+
+            /* read all lines */
+            while (!feof(fontdirs))
+            {
+                size_t blen;
+                char *hashchar;
+                char *str;
+                int has_eol = FALSE;
+
+                /* read one line */
+                str = fgets(buffer, sizeof(buffer), fontdirs);
+                if (str == NULL) /* stop on error or eof */
+                    break;
+
+                if (strchr(str, '\n') != NULL)
+                    has_eol = TRUE;
+
+                /* check if block is continued comment */
+                if (comment_block)
+                {
+                    /* ignore all input */
+                    *str = 0; 
+                    blen = 0; 
+                    if (has_eol) /* check if line ended in this block */
+                        comment_block = FALSE;
+                }
+                else 
+                {
+                    /* find comment character. ignore all trailing input */
+                    hashchar = strchr(str, '#');
+                    if (hashchar != NULL)
+                    {
+                        *hashchar = 0;
+                        if (!has_eol) /* mark next block as continued comment */
+                            comment_block = TRUE;
+                    }
+                }
+
+                /* strip whitespaces from beginning */
+                while (*str == ' ' || *str == '\t')
+                    str++;
+
+                /* get size, strip whitespaces from end */ 
+                blen = strlen(str);
+                while (blen > 0 && (str[blen-1] == ' ' || 
+                            str[blen-1] == '\t' || str[blen-1] == '\n'))
+                {
+                    str[--blen] = 0;
+                }
+
+                /* still something left to add? */ 
+                if (blen > 0)
+                {
+                    size_t newsize = size + blen;
+                    /* reserve one character more for ',' */
+                    if (needs_sep)
+                        newsize++;
+
+                    /* allocate memory */
+                    if (fontpath == NULL)
+                        fontpath = malloc(newsize+1);
+                    else
+                        fontpath = realloc(fontpath, newsize+1);
+
+                    /* add separator */
+                    if (needs_sep)
+                    {
+                        fontpath[size] = ',';
+                        size++;
+                        needs_sep = FALSE;
+                    }
+
+                    /* mark next line as new entry */
+                    if (has_eol)
+                        needs_sep = TRUE;
+
+                    /* add block */
+                    strncpy(fontpath + size, str, blen);
+                    fontpath[newsize] = 0;
+                    size = newsize;
+                }
+            }
+
+            /* cleanup */
+            fclose(fontdirs);  
+            defaultFontPath = xstrdup(fontpath);
+            free(fontpath);
+            changed_fontpath = TRUE;
+            font_from = X_CONFIG;
+        }
+    }
+#endif /* READ_FONTDIRS */
+#ifdef RELOCATE_PROJECTROOT
+    {
+        const char *libx11dir = PROJECTROOT "/lib/X11";
+        size_t libx11dir_len = strlen(libx11dir);
+        char *newfp = NULL;
+        size_t newfp_len = 0;
+        const char *endptr, *ptr, *oldptr = defaultFontPath;
+
+        endptr = oldptr + strlen(oldptr);
+        ptr = strchr(oldptr, ',');
+        if (ptr == NULL)
+            ptr = endptr;
+        while (ptr != NULL)
+        {
+            size_t oldfp_len = (ptr - oldptr);
+            size_t newsize = oldfp_len;
+            char *newpath = malloc(newsize + 1);
+            strncpy(newpath, oldptr, newsize);
+            newpath[newsize] = 0;
+
+
+            if (strncmp(libx11dir, newpath, libx11dir_len) == 0)
+            {
+                char *compose;
+                newsize = newsize - libx11dir_len + basedirlen;
+                compose = malloc(newsize + 1);  
+                strcpy(compose, basedir);
+                strncat(compose, newpath + libx11dir_len, newsize - basedirlen);
+                compose[newsize] = 0;
+                free(newpath);
+                newpath = compose;
+            }
+
+            oldfp_len = newfp_len;
+            if (oldfp_len > 0)
+                newfp_len ++; /* space for separator */
+            newfp_len += newsize;
+
+            if (newfp == NULL)
+                newfp = malloc(newfp_len + 1);
+            else
+                newfp = realloc(newfp, newfp_len + 1);
+
+            if (oldfp_len > 0)
+            {
+                strcpy(newfp + oldfp_len, ",");
+                oldfp_len++;
+            }
+            strcpy(newfp + oldfp_len, newpath);
+
+            free(newpath);
+
+            if (*ptr == 0)
+            {
+                oldptr = ptr;
+                ptr = NULL;
+            } else
+            {
+                oldptr = ptr + 1;
+                ptr = strchr(oldptr, ',');
+                if (ptr == NULL)
+                    ptr = endptr;
+            }
+        } 
+
+        defaultFontPath = xstrdup(newfp);
+        free(newfp);
+        changed_fontpath = TRUE;
+    }
+#endif /* RELOCATE_PROJECTROOT */
+    if (changed_fontpath)
+        winMsg (font_from, "FontPath set to \"%s\"\n", defaultFontPath);
+
+#ifdef RELOCATE_PROJECTROOT
+    if (getenv("XKEYSYMDB") == NULL)
+    {
+        char buffer[MAX_PATH];
+        snprintf(buffer, sizeof(buffer), "XKEYSYMDB=%s\\XKeysymDB",
+                basedir);
+        buffer[sizeof(buffer)-1] = 0;
+        putenv(buffer);
+    }
+    if (getenv("XERRORDB") == NULL)
+    {
+        char buffer[MAX_PATH];
+        snprintf(buffer, sizeof(buffer), "XERRORDB=%s\\XErrorDB",
+                basedir);
+        buffer[sizeof(buffer)-1] = 0;
+        putenv(buffer);
+    }
+    if (getenv("XLOCALEDIR") == NULL)
+    {
+        char buffer[MAX_PATH];
+        snprintf(buffer, sizeof(buffer), "XLOCALEDIR=%s\\locale",
+                basedir);
+        buffer[sizeof(buffer)-1] = 0;
+        putenv(buffer);
+    }
+    if (getenv("HOME") == NULL)
+    {
+        HMODULE shfolder;
+        SHGETFOLDERPATHPROC shgetfolderpath = NULL;
+        char buffer[MAX_PATH + 5];
+        strncpy(buffer, "HOME=", 5);
+
+        /* Try to load SHGetFolderPath from shfolder.dll and shell32.dll */
+        
+        shfolder = LoadLibrary("shfolder.dll");
+        /* fallback to shell32.dll */
+        if (shfolder == NULL)
+            shfolder = LoadLibrary("shell32.dll");
+
+        /* resolve SHGetFolderPath */
+        if (shfolder != NULL)
+            shgetfolderpath = (SHGETFOLDERPATHPROC)GetProcAddress(shfolder, "SHGetFolderPathA");
+
+        /* query appdata directory */
+        if (shgetfolderpath &&
+                shgetfolderpath(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE, NULL, 0, 
+                    buffer + 5) == 0)
+        { 
+            putenv(buffer);
+        } else
+        {
+            winMsg (X_ERROR, "Can not determine HOME directory\n");
+        } 
+        if (shfolder != NULL)
+            FreeLibrary(shfolder);
+    }
+    if (!g_fLogFileChanged) {
+        static char buffer[MAX_PATH];
+        DWORD size = GetTempPath(sizeof(buffer), buffer);
+        if (size && size < sizeof(buffer))
+        {
+            snprintf(buffer + size, sizeof(buffer) - size, 
+                    "XWin.%s.log", display); 
+            buffer[sizeof(buffer)-1] = 0;
+            g_pszLogFile = buffer;
+            winMsg (X_DEFAULT, "Logfile set to \"%s\"\n", g_pszLogFile);
+        }
+    }
+#ifdef XKB
+    {
+        static char xkbbasedir[MAX_PATH];
+
+        snprintf(xkbbasedir, sizeof(xkbbasedir), "%s\\xkb", basedir);
+        if (sizeof(xkbbasedir) > 0)
+            xkbbasedir[sizeof(xkbbasedir)-1] = 0;
+        XkbBaseDirectory = xkbbasedir;
+	XkbBinDirectory = basedir;
+    }
+#endif /* XKB */
+#endif /* RELOCATE_PROJECTROOT */
+}
+
+void
+OsVendorInit (void)
+{
+  /* Re-initialize global variables on server reset */
+  winInitializeGlobals ();
+
+  LogInit (NULL, NULL);
+  LogSetParameter (XLOG_VERBOSITY, g_iLogVerbose);
+
+  winFixupPaths();
+
+#ifdef DDXOSVERRORF
+  if (!OsVendorVErrorFProc)
+    OsVendorVErrorFProc = OsVendorVErrorF;
+#endif
+
+  if (!g_fLogInited) {
+    /* keep this order. If LogInit fails it calls Abort which then calls
+     * ddxGiveUp where LogInit is called again and creates an infinite 
+     * recursion. If we set g_fLogInited to TRUE before the init we 
+     * avoid the second call 
+     */  
+    g_fLogInited = TRUE;
+    LogInit (g_pszLogFile, NULL);
+  } 
+  LogSetParameter (XLOG_FLUSH, 1);
+  LogSetParameter (XLOG_VERBOSITY, g_iLogVerbose);
+  LogSetParameter (XLOG_FILE_VERBOSITY, 1);
+
+  /* Log the version information */
+  if (serverGeneration == 1)
+    winLogVersionInfo ();
+
+  winCheckMount();  
+
+  /* Add a default screen if no screens were specified */
+  if (g_iNumScreens == 0)
+    {
+      winDebug ("OsVendorInit - Creating bogus screen 0\n");
+
+      /* 
+       * We need to initialize default screens if no arguments
+       * were processed.  Otherwise, the default screens would
+       * already have been initialized by ddxProcessArgument ().
+       */
+      winInitializeDefaultScreens ();
+
+      /*
+       * Add a screen 0 using the defaults set by 
+       * winInitializeDefaultScreens () and any additional parameters
+       * processed by ddxProcessArgument ().
+       */
+      g_iNumScreens = 1;
+      g_iLastScreen = 0;
+
+      /* We have to flag this as an explicit screen, even though it isn't */
+      g_ScreenInfo[0].fExplicitScreen = TRUE;
+    }
+}
+
+
+static void
+winUseMsg (void)
+{
+  ErrorF ("-depth bits_per_pixel\n"
+	  "\tSpecify an optional bitdepth to use in fullscreen mode\n"
+	  "\twith a DirectDraw engine.\n");
+
+  ErrorF ("-emulate3buttons [timeout]\n"
+	  "\tEmulate 3 button mouse with an optional timeout in\n"
+	  "\tmilliseconds.\n");
+
+  ErrorF ("-engine engine_type_id\n"
+	  "\tOverride the server's automatically selected engine type:\n"
+	  "\t\t1 - Shadow GDI\n"
+	  "\t\t2 - Shadow DirectDraw\n"
+	  "\t\t4 - Shadow DirectDraw4 Non-Locking\n"
+#ifdef XWIN_NATIVEGDI
+	  "\t\t16 - Native GDI - experimental\n"
+#endif
+	  );
+
+  ErrorF ("-fullscreen\n"
+	  "\tRun the server in fullscreen mode.\n");
+  
+  ErrorF ("-refresh rate_in_Hz\n"
+	  "\tSpecify an optional refresh rate to use in fullscreen mode\n"
+	  "\twith a DirectDraw engine.\n");
+
+  ErrorF ("-screen scr_num [width height [x y] | [[WxH[+X+Y]][@m]] ]\n"
+	  "\tEnable screen scr_num and optionally specify a width and\n"
+	  "\theight and initial position for that screen. Additionally\n"
+	  "\ta monitor number can be specified to start the server on,\n"
+	  "\tat which point, all coordinates become relative to that\n"
+      "\tmonitor (Not for Windows NT4 and 95). Examples:\n"
+      "\t -screen 0 800x600+100+100 at 2 ; 2nd monitor offset 100,100 size 800x600\n"
+      "\t -screen 0 1024x768 at 3        ; 3rd monitor size 1024x768\n"
+      "\t -screen 0 @1 ; on 1st monitor using its full resolution (the default)\n");
+
+  ErrorF ("-lesspointer\n"
+	  "\tHide the windows mouse pointer when it is over an inactive\n"
+          "\t" PROJECT_NAME " window.  This prevents ghost cursors appearing where\n"
+	  "\tthe Windows cursor is drawn overtop of the X cursor\n");
+
+  ErrorF ("-nodecoration\n"
+          "\tDo not draw a window border, title bar, etc.  Windowed\n"
+	  "\tmode only.\n");
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  ErrorF ("-mwextwm\n"
+	  "\tRun the server in multi-window external window manager mode.\n");
+
+  ErrorF ("-internalwm\n"
+	  "\tRun the internal window manager.\n");
+#endif
+
+  ErrorF ("-rootless\n"
+	  "\tRun the server in rootless mode.\n");
+
+#ifdef XWIN_MULTIWINDOW
+  ErrorF ("-multiwindow\n"
+	  "\tRun the server in multi-window mode.\n");
+#endif
+
+  ErrorF ("-multiplemonitors\n"
+	  "\tEXPERIMENTAL: Use the entire virtual screen if multiple\n"
+	  "\tmonitors are present.\n");
+
+#ifdef XWIN_CLIPBOARD
+  ErrorF ("-clipboard\n"
+	  "\tRun the clipboard integration module.\n"
+	  "\tDo not use at the same time as 'xwinclip'.\n");
+
+  ErrorF ("-nounicodeclipboard\n"
+	  "\tDo not use Unicode clipboard even if NT-based platform.\n");
+#endif
+
+  ErrorF ("-scrollbars\n"
+	  "\tIn windowed mode, allow screens bigger than the Windows desktop.\n"
+	  "\tMoreover, if the window has decorations, one can now resize\n"
+	  "\tit.\n");
+
+  ErrorF ("-[no]trayicon\n"
+          "\tDo not create a tray icon.  Default is to create one\n"
+	  "\ticon per screen.  You can globally disable tray icons with\n"
+	  "\t-notrayicon, then enable it for specific screens with\n"
+	  "\t-trayicon for those screens.\n");
+
+  ErrorF ("-clipupdates num_boxes\n"
+	  "\tUse a clipping region to constrain shadow update blits to\n"
+	  "\tthe updated region when num_boxes, or more, are in the\n"
+	  "\tupdated region.  Currently supported only by `-engine 1'.\n");
+
+#ifdef XWIN_EMULATEPSEUDO
+  ErrorF ("-emulatepseudo\n"
+	  "\tCreate a depth 8 PseudoColor visual when running in\n"
+	  "\tdepths 15, 16, 24, or 32, collectively known as TrueColor\n"
+	  "\tdepths.  The PseudoColor visual does not have correct colors,\n"
+	  "\tand it may crash, but it at least allows you to run your\n"
+	  "\tapplication in TrueColor modes.\n");
+#endif
+
+  ErrorF ("-[no]unixkill\n"
+          "\tCtrl+Alt+Backspace exits the X Server.\n");
+
+  ErrorF ("-[no]winkill\n"
+          "\tAlt+F4 exits the X Server.\n");
+
+#ifdef XWIN_XF86CONFIG
+  ErrorF ("-config\n"
+          "\tSpecify a configuration file.\n");
+
+  ErrorF ("-keyboard\n"
+	  "\tSpecify a keyboard device from the configuration file.\n");
+#endif
+
+#ifdef XKB
+  ErrorF ("-xkbrules XKBRules\n"
+	  "\tEquivalent to XKBRules in XF86Config files.\n");
+
+  ErrorF ("-xkbmodel XKBModel\n"
+	  "\tEquivalent to XKBModel in XF86Config files.\n");
+
+  ErrorF ("-xkblayout XKBLayout\n"
+	  "\tEquivalent to XKBLayout in XF86Config files.\n"
+	  "\tFor example: -xkblayout de\n");
+
+  ErrorF ("-xkbvariant XKBVariant\n"
+	  "\tEquivalent to XKBVariant in XF86Config files.\n"
+	  "\tFor example: -xkbvariant nodeadkeys\n");
+
+  ErrorF ("-xkboptions XKBOptions\n"
+	  "\tEquivalent to XKBOptions in XF86Config files.\n");
+#endif
+
+  ErrorF ("-logfile filename\n"
+	  "\tWrite logmessages to <filename> instead of /tmp/Xwin.log.\n");
+
+  ErrorF ("-logverbose verbosity\n"
+	  "\tSet the verbosity of logmessages. [NOTE: Only a few messages\n"
+	  "\trespect the settings yet]\n"
+	  "\t\t0 - only print fatal error.\n"
+	  "\t\t1 - print additional configuration information.\n"
+	  "\t\t2 - print additional runtime information [default].\n"
+	  "\t\t3 - print debugging and tracing information.\n");
+
+  ErrorF ("-[no]keyhook\n"
+	  "\tGrab special windows key combinations like Alt-Tab or the Menu "
+          "key.\n These keys are discarded by default.\n");
+
+  ErrorF ("-swcursor\n"
+	  "\tDisable the usage of the windows cursor and use the X11 software "
+	  "cursor instead\n");
+}
+
+/* See Porting Layer Definition - p. 57 */
+void
+ddxUseMsg(void)
+{
+  /* Set a flag so that FatalError won't give duplicate warning message */
+  g_fSilentFatalError = TRUE;
+  
+  winUseMsg();  
+
+  /* Log file will not be opened for UseMsg unless we open it now */
+  if (!g_fLogInited) {
+    LogInit (g_pszLogFile, NULL);
+    g_fLogInited = TRUE;
+  }  
+  LogClose ();
+
+  /* Notify user where UseMsg text can be found.*/
+  if (!g_fNoHelpMessageBox)
+    winMessageBoxF ("The " PROJECT_NAME " help text has been printed to "
+		  "/tmp/XWin.log.\n"
+		  "Please open /tmp/XWin.log to read the help text.\n",
+		  MB_ICONINFORMATION);
+}
+
+/* ddxInitGlobals - called by |InitGlobals| from os/util.c */
+void ddxInitGlobals(void)
+{
+}
+
+/* See Porting Layer Definition - p. 20 */
+/*
+ * Do any global initialization, then initialize each screen.
+ * 
+ * NOTE: We use ddxProcessArgument, so we don't need to touch argc and argv
+ */
+
+void
+InitOutput (ScreenInfo *screenInfo, int argc, char *argv[])
+{
+  int		i;
+
+  /* Log the command line */
+  winLogCommandLine (argc, argv);
+
+#if CYGDEBUG
+  winDebug ("InitOutput\n");
+#endif
+
+  /* Validate command-line arguments */
+  if (serverGeneration == 1 && !winValidateArgs ())
+    {
+      FatalError ("InitOutput - Invalid command-line arguments found.  "
+		  "Exiting.\n");
+    }
+
+  /* Check for duplicate invocation on same display number.*/
+  if (serverGeneration == 1 && !winCheckDisplayNumber ())
+    {
+      if (g_fSilentDupError)
+        g_fSilentFatalError = TRUE;  
+      FatalError ("InitOutput - Duplicate invocation on display "
+		  "number: %s.  Exiting.\n", display);
+    }
+
+#ifdef XWIN_XF86CONFIG
+  /* Try to read the xorg.conf-style configuration file */
+  if (!winReadConfigfile ())
+    winErrorFVerb (1, "InitOutput - Error reading config file\n");
+#else
+  winMsg(X_INFO, "XF86Config is not supported\n");
+  winMsg(X_INFO, "See http://x.cygwin.com/docs/faq/cygwin-x-faq.html "
+         "for more information\n");
+  winConfigFiles ();
+#endif
+
+  /* Load preferences from XWinrc file */
+  LoadPreferences();
+
+  /* Setup global screen info parameters */
+  screenInfo->imageByteOrder = IMAGE_BYTE_ORDER;
+  screenInfo->bitmapScanlinePad = BITMAP_SCANLINE_PAD;
+  screenInfo->bitmapScanlineUnit = BITMAP_SCANLINE_UNIT;
+  screenInfo->bitmapBitOrder = BITMAP_BIT_ORDER;
+  screenInfo->numPixmapFormats = NUMFORMATS;
+  
+  /* Describe how we want common pixmap formats padded */
+  for (i = 0; i < NUMFORMATS; i++)
+    {
+      screenInfo->formats[i] = g_PixmapFormats[i];
+    }
+
+  /* Load pointers to DirectDraw functions */
+  winGetDDProcAddresses ();
+  
+  /* Detect supported engines */
+  winDetectSupportedEngines ();
+
+  /* Load common controls library */
+  g_hmodCommonControls = LoadLibraryEx ("comctl32.dll", NULL, 0);
+
+  /* Load TrackMouseEvent function pointer */  
+  g_fpTrackMouseEvent = GetProcAddress (g_hmodCommonControls,
+					 "_TrackMouseEvent");
+  if (g_fpTrackMouseEvent == NULL)
+    {
+      winErrorFVerb (1, "InitOutput - Could not get pointer to function\n"
+	      "\t_TrackMouseEvent in comctl32.dll.  Try installing\n"
+	      "\tInternet Explorer 3.0 or greater if you have not\n"
+	      "\talready.\n");
+
+      /* Free the library since we won't need it */
+      FreeLibrary (g_hmodCommonControls);
+      g_hmodCommonControls = NULL;
+
+      /* Set function pointer to point to no operation function */
+      g_fpTrackMouseEvent = (FARPROC) (void (*)(void))NoopDDA;
+    }
+
+  /* Store the instance handle */
+  g_hInstance = GetModuleHandle (NULL);
+
+  /* Initialize each screen */
+  for (i = 0; i < g_iNumScreens; ++i)
+    {
+      /* Initialize the screen */
+      if (-1 == AddScreen (winScreenInit, argc, argv))
+	{
+	  FatalError ("InitOutput - Couldn't add screen %d", i);
+	}
+    }
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+
+#if defined(XCSECURITY)
+  /* Generate a cookie used by internal clients for authorization */
+  if (g_fXdmcpEnabled)
+    winGenerateAuthorization ();
+#endif
+
+  /* Perform some one time initialization */
+  if (1 == serverGeneration)
+    {
+      /*
+       * setlocale applies to all threads in the current process.
+       * Apply locale specified in LANG environment variable.
+       */
+      setlocale (LC_ALL, "");
+    }
+#endif
+
+#if CYGDEBUG || YES
+  winDebug ("InitOutput - Returning.\n");
+#endif
+}
+
+
+/*
+ * winCheckDisplayNumber - Check if another instance of Cygwin/X is
+ * already running on the same display number.  If no one exists,
+ * make a mutex to prevent new instances from running on the same display.
+ *
+ * return FALSE if the display number is already used.
+ */
+
+static Bool
+winCheckDisplayNumber ()
+{
+  int			nDisp;
+  HANDLE		mutex;
+  char			name[MAX_PATH];
+  char *		pszPrefix = '\0';
+  OSVERSIONINFO		osvi = {0};
+
+  /* Check display range */
+  nDisp = atoi (display);
+  if (nDisp < 0 || nDisp > 65535)
+    {
+      ErrorF ("winCheckDisplayNumber - Bad display number: %d\n", nDisp);
+      return FALSE;
+    }
+
+  /* Set first character of mutex name to null */
+  name[0] = '\0';
+
+  /* Get operating system version information */
+  osvi.dwOSVersionInfoSize = sizeof (osvi);
+  GetVersionEx (&osvi);
+
+  /* Want a mutex shared among all terminals on NT > 4.0 */
+  if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT
+      && osvi.dwMajorVersion >= 5)
+    {
+      pszPrefix = "Global\\";
+    }
+
+  /* Setup Cygwin/X specific part of name */
+  snprintf (name, sizeof(name), "%sCYGWINX_DISPLAY:%d", pszPrefix, nDisp);
+
+  /* Windows automatically releases the mutex when this process exits */
+  mutex = CreateMutex (NULL, FALSE, name);
+  if (!mutex)
+    {
+      LPVOID lpMsgBuf;
+
+      /* Display a fancy error message */
+      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | 
+		     FORMAT_MESSAGE_FROM_SYSTEM | 
+		     FORMAT_MESSAGE_IGNORE_INSERTS,
+		     NULL,
+		     GetLastError (),
+		     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+		     (LPTSTR) &lpMsgBuf,
+		     0, NULL);
+      ErrorF ("winCheckDisplayNumber - CreateMutex failed: %s\n",
+	      (LPSTR)lpMsgBuf);
+      LocalFree (lpMsgBuf);
+
+      return FALSE;
+    }
+  if (GetLastError () == ERROR_ALREADY_EXISTS)
+    {
+      ErrorF ("winCheckDisplayNumber - "
+	      PROJECT_NAME " is already running on display %d\n",
+	      nDisp);
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+#ifdef DPMSExtension
+Bool DPMSSupported(void)
+{
+  return FALSE;
+}
+
+void DPMSSet(int level)
+{
+  return;
+}
+
+int DPMSGet(int *plevel)
+{
+  return 0;
+}
+#endif
diff --git a/hw/xwin/Makefile.am b/hw/xwin/Makefile.am
new file mode 100644
index 0000000..5ffba12
--- /dev/null
+++ b/hw/xwin/Makefile.am
@@ -0,0 +1,197 @@
+bin_PROGRAMS = XWin
+
+if XWIN_CLIPBOARD
+SRCS_CLIPBOARD = \
+	winclipboardinit.c \
+	winclipboardtextconv.c \
+	winclipboardthread.c \
+	winclipboardunicode.c \
+	winclipboardwndproc.c \
+	winclipboardwrappers.c \
+	winclipboardxevents.c
+DEFS_CLIPBOARD = -DXWIN_CLIPBOARD
+endif
+
+if XWIN_GLX_WINDOWS
+SRCS_GLX_WINDOWS = \
+	winpriv.c
+DEFS_GLX_WINDOWS = -DXWIN_GLX_WINDOWS
+endif
+
+if XWIN_MULTIWINDOW
+SRCS_MULTIWINDOW = \
+	winmultiwindowshape.c \
+	winmultiwindowwindow.c \
+	winmultiwindowwm.c \
+	winmultiwindowwndproc.c
+DEFS_MULTIWINDOW = -DXWIN_MULTIWINDOW
+endif
+
+if XWIN_MULTIWINDOWEXTWM
+SRCS_MULTIWINDOWEXTWM = \
+	winwin32rootless.c \
+	winwin32rootlesswindow.c \
+	winwin32rootlesswndproc.c \
+	winwindowswm.c
+DEFS_MULTIWINDOWEXTWM = -DXWIN_MULTIWINDOWEXTWM
+endif
+
+if XWIN_NATIVEGDI
+SRCS_NATIVEGDI = \
+	winclip.c \
+	winfillsp.c \
+	winfont.c \
+	wingc.c \
+	wingetsp.c \
+	winnativegdi.c \
+	winpixmap.c \
+	winpolyline.c \
+	winpushpxl.c \
+	winrop.c \
+	winsetsp.c
+DEFS_NATIVEGDI = -DXWIN_NATIVEGDI
+endif
+
+if XWIN_PRIMARYFB
+SRCS_PRIMARYFB = \
+	winpfbdd.c
+DEFS_PRIMARYFB = -DXWIN_PRIMARYFB
+endif
+
+if XWIN_RANDR
+SRCS_RANDR = \
+	winrandr.c
+DEFS_RANDR = -DXWIN_RANDR
+endif
+
+if XWIN_XV
+SRCS_XV = \
+	winvideo.c
+DEFS_XV = -DXWIN_XV
+endif
+
+SRCS =	InitInput.c \
+	InitOutput.c \
+	winallpriv.c \
+	winauth.c \
+	winblock.c \
+	wincmap.c \
+	winconfig.c \
+	wincreatewnd.c \
+	wincursor.c \
+	windialogs.c \
+	winengine.c \
+	winerror.c \
+	winglobals.c \
+	winkeybd.c \
+	winkeyhook.c \
+	winmisc.c \
+	winmouse.c \
+	winmsg.c \
+	winmultiwindowclass.c \
+	winmultiwindowicons.c \
+	winprefs.c \
+	winprefsyacc.y \
+	winprefslex.l \
+	winprocarg.c \
+	winregistry.c \
+	winscrinit.c \
+	winshaddd.c \
+	winshadddnl.c \
+	winshadgdi.c \
+	wintrayicon.c \
+	winvalargs.c \
+	winwakeup.c \
+	winwindow.c \
+	winwndproc.c \
+	ddraw.h \
+	winclipboard.h \
+	winconfig.h \
+	win.h \
+	winkeybd.h \
+	winkeymap.h \
+	winkeynames.h \
+	winlayouts.h \
+	winmessages.h \
+	winmsg.h \
+	winms.h \
+	winmultiwindowclass.h \
+	winprefs.h \
+	winpriv.h \
+	winresource.h \
+	winwindow.h \
+	$(top_srcdir)/mi/miinitext.c \
+	$(top_srcdir)/fb/fbcmap.c \
+	$(SRCS_CLIPBOARD) \
+	$(SRCS_GLX_WINDOWS) \
+	$(SRCS_MULTIWINDOW) \
+	$(SRCS_MULTIWINDOWEXTWM) \
+	$(SRCS_NATIVEGDI) \
+	$(SRCS_PRIMARYFB) \
+	$(SRCS_RANDR) \
+	$(SRCS_XV)
+
+ DEFS = $(DEFS_CLIPBOARD) \
+	$(DEFS_GLX_WINDOWS) \
+	$(DEFS_MULTIWINDOW) \
+	$(DEFS_MULTIWINDOWEXTWM) \
+	$(DEFS_NATIVEGDI) \
+	$(DEFS_PRIMARYFB) \
+	$(DEFS_RANDR) \
+	$(DEFS_XV)
+
+XWin_SOURCES = $(SRCS)
+
+INCLUDES = -I$(top_srcdir)/miext/rootless \
+           -I$(top_srcdir)/miext/rootless/safeAlpha
+
+XWIN_LIBS = \
+	$(top_builddir)/fb/libfb.la \
+	$(XSERVER_LIBS)
+
+XWin_DEPENDENCIES = $(XWIN_LIBS)
+XWin_LDADD = $(XWIN_LIBS) $(XSERVER_SYS_LIBS) $(XWIN_SYS_LIBS)
+
+XWin_LDFLAGS = -mwindows -static
+
+winprefsyacc.h: winprefsyacc.c
+winprefslex.c: winprefslex.l winprefsyacc.c winprefsyacc.h
+
+BUILT_SOURCES = winprefsyacc.h winprefsyacc.c winprefslex.c
+CLEANFILES = $(BUILT_SOURCES)
+
+AM_YFLAGS = -d
+AM_LFLAGS = -i
+AM_CFLAGS = -DHAVE_XWIN_CONFIG_H $(DIX_CFLAGS) \
+            $(XWINMODULES_CFLAGS)
+
+dist_man1_MANS = XWin.man XWinrc.man
+
+EXTRA_DIST = \
+	_usr_X11R6_lib_X11_system.XWinrc \
+	X-boxed.ico \
+	X.ico \
+	XWin.rc \
+	xlaunch/config.cc \
+	xlaunch/COPYING \
+	xlaunch/main.cc \
+	xlaunch/resources/dialog.rc \
+	xlaunch/resources/fullscreen.bmp \
+	xlaunch/resources/images.rc \
+	xlaunch/resources/multiwindow.bmp \
+	xlaunch/resources/nodecoration.bmp \
+	xlaunch/resources/resources.h \
+	xlaunch/resources/resources.rc \
+	xlaunch/resources/strings.rc \
+	xlaunch/resources/windowed.bmp \
+	xlaunch/window/dialog.cc \
+	xlaunch/window/dialog.h \
+	xlaunch/window/util.cc \
+	xlaunch/window/util.h \
+	xlaunch/window/window.cc \
+	xlaunch/window/window.h \
+	xlaunch/window/wizard.cc \
+	xlaunch/window/wizard.h
+
+relink:
+	rm -f XWin && $(MAKE) XWin
diff --git a/hw/xwin/README b/hw/xwin/README
new file mode 100644
index 0000000..219fd13
--- /dev/null
+++ b/hw/xwin/README
@@ -0,0 +1,141 @@
+Cygwin/X Release Notes
+======================
+
+Release X11R6.7
+===============
+
+Cygwin/X has continued its rapid pace of development that it has sustained
+since Spring 2001 and this release shows it, we now have: a stable and fast
+multi-window mode, seamless clipboard integration, a configurable tray menu
+icon, popups on error messages pointing users to the log file and our mailing
+list, the beginnings of indirect 3D acceleration for OpenGL applications,
+improved non-US keyboard and clipboard support, and only a handful of bugs
+that continue to be reported.
+
+Between the XFree86 4.3.0 release and the X.Org X11R6.7 release the Cyg-
+win/XFree86 project broke away from The XFree86 Project, Inc. due to a lack
+of support from the XFree86 project.  As such, the Cygwin/XFree86 project was
+renamed to the Cygwin/X project and the upstream source code tree that Cyg-
+win/X pulls from and pushes to is now the tree managed by the X.Org Founda-
+tion.  The Cygwin/X project has seen a rush of development and interest in
+the project since the split; one metric showing this is that the number of
+CVS committers we have has gone from zero to six.
+
+The most outstanding features of this release are
+
+   o Major multi-window mode improvements. (Takuma Murakami, Earle F. 
+     Philhower III)
+
+   o Initial work of accelerated OpenGL using the windows OpenGL drivers. 
+     (Alexander Gottwald)
+
+   o Massive rework of clipboard integration with windows. (Harold L Hunt II,
+     Kensuke Matsuzaki)
+
+   o Improved Japanese clipboard and keyboard support. (Kensuke Matsuzaki,
+     Takuma Murakami, Alexander Gottwald)
+
+   o Customizable tray menu icon allowing shortcuts to start programs,
+     etc.(Earle F. Philhower III)
+
+   o New icons. (Jehan Bing, Michael Bax, Benjamin Rienfenstahl)
+
+   o Fix some multi-monitor problems.(Takuma Murakami)
+
+   o Fix repeated key strokes. (Ivan Pascal)
+
+   o Automatic keyboard layouts for the most frequently used keyboard lay-
+     outs. (Alexander Gottwald)
+
+   o Built in SHM support with detection of the SHM engine (cygserver).
+     (Ralf Habacker, Harold L Hunt II)
+
+   o Merged in work on the NativeGDI engine. (Alan Hourihane)
+
+OpenGL with Cygwin/X
+====================
+
+Cygwin/X has supported GLX only with software rendering provided by the Mesa
+library. Starting with X11R6.7 we add support for hardware accelerated OpenGL.
+
+This support is still under development and still has some bigger problems. 
+To provide both versions (the stable software rendering and the new hardware
+accelerated) we ship to binaries. XWin.exe contains the software rendering 
+and XWin_GL.exe uses the hardware acceleration provided by the windows drivers.
+
+The known problems with hardware accelerated OpenGL are:
+
+   o Only multiwindow mode is useful. In the other modes the OpenGL output 
+     does not align with the X11 windows.
+
+   o Using two programs which require different visuals will fail. For example
+     glxgears and glxinfo will not work without restarting XWin_GL.exe.
+
+   o OpenGL extensions and functions from OpenGL 1.2 and later should work 
+     but are not completely tested.
+
+   o The standard Windows OpenGL driver will produce no output. Use the one 
+     from your video adapter vendor.  
+
+If you notice problems with some programs please send a message with the 
+logfile /tmp/XWin.log and a short error description to <cygwin-xfree at cygwin.com>
+
+The hardware accelerated OpenGL was tested using: 
+
+   o glxgears
+   o glxinfo
+   o blender
+   o tuxkart
+   o GLUT demos (some did fail)
+   o tuxracer (currently not working)
+
+    
+Release X11R6.8
+===============
+
+Having reached a quite mature state in release X11R6.7 the development 
+has slowed down a little bit. Some of the former active developers have
+retired or cut their work for the Cygwin/X project due to conflicts with 
+job, study and family. 
+
+The X11R6.8 release now includes major improvements from the xserver project.
+This includes the XFixes, Damage, Composite and XEVIE extension which is a 
+major step towards allowing Cygwin/X to have real transparency. 
+
+But at the current state Composite is not working with Cygwin/X. Not all code
+in the Cygwin/X Server has been updated to support the Composite feature and
+using it will even crash the xserver. But as a second problem nearly all
+functions required for compositing are lacking acceleration in Cygwin/X so
+the feature would not be very useful if it would work. So it is disabled by
+default. 
+
+OpenGL with Cygwin/X
+====================
+
+The OpenGL support has lost some of it's limitations from the last release 
+and should be much more stable. But due to missing wide spread testing in 
+the community it is still available in a separate program. XWin still uses 
+the old software OpenGL which is known to be stable.
+
+The known problems with hardware accelerated OpenGL are:
+
+   o Only multiwindow mode is useful. In the other modes the OpenGL output 
+     does not align with the X11 windows.
+
+   o OpenGL extensions and functions from OpenGL 1.2 and later should work 
+     but are not completely tested.
+
+   o The standard Windows OpenGL driver will produce no output. Use the one 
+     from your video adapter vendor.  
+
+If you notice problems with some programs please send a message with the 
+logfile /tmp/XWin.log and a short error description to <cygwin-xfree at cygwin.com>
+
+The hardware accelerated OpenGL was tested using: 
+
+   o glxgears
+   o glxinfo
+   o blender
+   o tuxkart
+   o GLUT demos (some did fail)
+
diff --git a/hw/xwin/X-boxed.ico b/hw/xwin/X-boxed.ico
new file mode 100755
index 0000000..0727042
Binary files /dev/null and b/hw/xwin/X-boxed.ico differ
diff --git a/hw/xwin/X.ico b/hw/xwin/X.ico
new file mode 100644
index 0000000..d47168f
Binary files /dev/null and b/hw/xwin/X.ico differ
diff --git a/hw/xwin/XWin.man b/hw/xwin/XWin.man
new file mode 100644
index 0000000..4e70c19
--- /dev/null
+++ b/hw/xwin/XWin.man
@@ -0,0 +1,287 @@
+.TH XWIN 1 __vendorversion__
+.SH NAME
+XWin \- X Server for the Cygwin environment on Microsoft Windows
+
+
+.SH SYNOPSIS
+.B XWin
+[ options ] ...
+
+
+.SH DESCRIPTION
+.I XWin is an X Server for the X Window System on the Cygwin environment
+running on Microsoft Windows.
+
+
+.SH MODES
+\fIXWin\fP can operate in five different and incompatible modes:
+.br
+* \fISingle Window\fP: This is the default option.  The X server
+appears as a single Windows window and all X windows are contained
+within this window.  This mode requires an external window manager.
+.br
+* \fINo Decoration\fP: This mode is like single window mode except
+that the X server window does not have a title bar or border, thus
+maximizing the amount of space available for X windows within the X
+server window.  This mode requires an external window manager.
+.br
+* \fIFull Screen\fP: This mode is like single window mode except that
+the X server window takes the full screen, covering completely the
+Windows desktop.  This mode requires an external window manager.
+.br
+* \fIRootless\fP: The X server works on a window covering the whole
+screen but the root window (traditionally covered with an X hatch
+pattern) is hidden from view.  This mode requires an external window
+manager.
+.br
+* \fIMulti-Window\fP: In this mode \fIXWin\fP uses its own integrated
+window manager in order to handle the top-level X windows, in such a
+way that they appear as normal Windows windows.
+.PP
+NOTE: \fIMulti-Window\fP mode will crash if an external window manager
+such as \fItwm\fP or \fIfvwm\fP is launched since \fIMulti-Window\fP
+uses its own internal window manager; all other modes require an
+external window manager in order to move, resize, and perform other
+operations on the individual X windows.
+
+
+.SH LOG
+As it runs \fIXWin\fP writes messages indicating the most relevant events
+to  the console
+from which it was called and to a log file that by default is located at
+\fI/tmp/XWin.log\fP.  This file is mainly for debugging purposes.
+
+
+.SH PREFERENCES FILE
+On startup \fIXWin\fP looks for the file \fI$HOME/.XWinrc\fP or, if
+the previous file does not exist,
+\fI/usr/X11R6/lib/X11/system.XWinrc\fP.  \fI.XWinrc\fP allows setting
+preferences for the following:
+.br
+1- To include items into the menu associated with the \fIXWin\fP icon
+which is in the \fIWindows\fP system tray.  This functions in all
+modes that have a tray icon.
+.br
+2- To include items in the menu which is associated with the Windows
+window that \fIXWin -multiwindow\fP produces for each top-level X
+window.  That can be done both for the generic case and for particular
+programs.
+.br
+3- To change the icon that is associated to the Windows window that
+\fIXWin -multiwindow\fP produces for each top-level X-window.  Again,
+that can be done both for the generic case and for particular
+programs.
+.PP
+The format of the \fI.XWinrc\fP file is given in the man page XWinrc(5).
+
+
+.SH OPTIONS
+In addition to the normal server options described in the \fIXserver(1)\fP
+manual page, \fIXWin\fP accepts the following command line switches,
+\fIall\fP of which are optional:
+.TP 8
+.B \-clipboard
+Enables the integration
+between the Cygwin/X clipboard and Windows clipboard.  Do not use in
+conjunction with the \fIxwinclip\fP program.
+.TP 8
+.B "\-clipupdates \fInum_boxes\fP"
+Specify an optional threshold, above which the boxes in a shadow
+update operation will be collected into a GDI clipping region.  The
+clipping region is then used to do a single bit block transfer that is
+constrained to the updated area by the clipping region.  There is some
+overhead involved in creating, installing, destroying, and removing
+the clipping region, thus there may not be much benefit for a small
+number of boxes (less than 10).  It is even possible that this
+functionality does not provide a benefit at any number of boxes; we
+can only determine the usefulness of this feature through testing.
+This parameter works in conjunction with engines 1, 2, and 4 (Shadow
+GDI, Shadow DirectDraw, and Shadow DirectDraw Non-Locking,
+respectively).
+.TP 8
+.B "\-emulate3buttons \fItimeout\fP"
+Emulate a three button mouse; pressing both buttons within
+.I timeout
+milliseconds causes an emulated middle button press.  The default 
+.I timeout
+is 50 milliseconds.  Note that most mice with scroll wheel have middle
+button functionality, usually you will need this option only if you have
+a two button mouse without scroll wheel.
+.TP 8
+.B \-emulatepseudo
+Create a depth 8 PseudoColor visual when running in depths 15, 16, 24,
+or 32, collectively known as TrueColor depths.
+ At this date (April 2004) this option is not still operative.
+.TP 8
+.B "\-engine \fIengine_type_id\fP"
+This option, which is intended for Cygwin/X developers,
+overrides the server's automatically supported engine type.  This
+parameter will be ignored if the specified engine type is not
+supported on the current system.  The supported engine type ids are 1
+- Shadow GDI, 2 - Shadow DirectDraw, and 4 - Shadow DirectDraw4.
+Additionally, there is a barely functional experimental engine type id
+16 - Native GDI.
+.TP 8
+.B "\-fullscreen [-depth \fIdepth\fP] [-refresh \fIrate_in_Hz\fP]"
+Run the server in fullscreen mode, as opposed to the default windowed
+mode.
+.TP 8
+.B "\-depth \fIdepth\fP"
+Specify the color depth, in bits per pixel, to use when running in
+fullscreen with a DirectDraw engine.  This parameter is ignored if
+\fB\-fullscreen\fP is not specified.
+.TP 8
+.B "\-refresh \fIrate_in_Hz\fP"
+Specify an optional refresh rate to use when running in
+fullscreen with a DirectDraw engine.  This parameter is ignored if
+\fB\-fullscreen\fP is not specified.
+.TP 8
+.B \-help
+Write a help text to the console and to the log file.
+.TP 8
+.B \-ignoreinput
+Ignore keyboard and mouse input.  This is usually only used for testing
+and debugging purposes.
+.TP 8
+.B \-[no]keyhook
+Enable [disable] a low-level keyboard hook for catching
+special key combinations like Alt+Tab and passing them to the X
+Server instead of letting \fIWindows\fP handle them.
+.TP 8
+.B \-lesspointer
+Hide the Windows mouse cursor when the mouse is over any Cygwin/X
+window (regardless of whether that window is active or inactive).  This
+prevents the Windows mouse cursor from being placed overtop of the X
+cursor.
+.TP 8
+.B "\-logfile \fIFile_Name\fP"
+Change the log file from the default located at \fI/tmp/XWin.log\fP to
+the one indicated by \fIFile_Name\fP.
+.TP 8
+.B "\-logverbose \fIlevel\fP"
+Control the degree of verbosity of the log messages with the integer
+parameter \fIlevel\fP.  For \fIlevel\fP=0 only fatal errors are
+reported, for \fIlevel\fP=1 (default) simple information about
+configuration is also given, for \fIlevel\fP=2 a detailed log
+information (including trace and debug output) is produced.  Bigger
+values will yield a still more detailed debug output.  At this date
+(April 2004) the option is still not fully operative; the default
+value is 2 and the output is insensitive to the level value.
+.TP 8
+.B \-multimonitors
+Create a root window that covers all monitors on a system with
+multiple monitors.
+.TP 8
+.B \-multiwindow
+Start the integrated \fIWindowsi\fP-based window manager, which launches each
+top-level X window in its own \fIWindows\fP window.  Not to be used together
+with \fB\-rootless\fP nor \fB\-fullscreen\fP.
+.TP 8
+.B \-nodecoration
+Do not give the Cygwin/X window a Windows window border, title bar,
+etc.  This parameter only applies to windowed mode screens, i.e., this
+parameter is ignored when the \fB\-fullscreen\fP parameter is specified.
+.TP 8
+.B \-nounicodeclipboard
+Do not use Unicode clipboard even if NT-based platform.
+.TP 8
+.B \-rootless
+Run the server in rootless mode.  Not to be used with \fB\-multiwindow\fP
+nor with \fB\-fullscreen\fP.
+.TP 8
+.B "\-screen \fIscreen_number\fP \fIwidth\fP \fIheight\fP"
+This parameter may be used to specify the
+.I screen_number,
+.I height,
+and
+.I width
+of one or several Cygwin/X screens; each Cygwin/X screen will be
+opened in its own window.  When using multiple screens, be sure not to
+duplicate any screen numbers.
+.I XWin
+default behavior is to create a single screen that is roughly
+the size of the current Windows display area.
+Screen specific parameters, such as \fB\-fullscreen\fP, can be applied as a
+default to all screens by placing those screen specific parameters
+before any \fB\-screen\fP parameter.  Screen specific parameters placed after
+the first \fB\-screen\fP parameter will apply only to the immediately
+preceeding \fB\-screen\fP parameter.
+.TP 8
+.B \-scrollbars
+In windowed mode, allow screens bigger than the Windows desktop.
+Moreover, if the window has decorations, one can now resize it.
+.TP 8
+.B \-[no]trayicon
+Do not create a tray icon.  Default is to create one
+icon per screen.  You can globally disable tray icons with
+\fB\-notrayicon\fP, then enable it for specific screens with
+\fB\-trayicon\fP for those screens.
+.TP 8
+.B \-[no]unixkill
+Enable or disable the \fICtrl-Alt-Backspace\fP key combination as a
+signal to exit the X Server.  The \fICtrl-Alt-Backspace\fP key combination
+is disabled by default.
+.TP 8
+.B \-[no]winkill
+Enable or disable the \fIAlt-F4\fP key combination as a signal to exit the
+X Server.
+The \fIAlt-F4\fP key combination is enabled by default.
+.TP 8
+.B \-swcursor
+Disable the usage of the windows cursor and use the X11 software cursor instead.
+.B \-silent-dup-error
+If another instance of XWin is found running, exit silently and don't display 
+the error messge.
+.TP 8
+.B "\-xkblayout \fIlayout\fP"
+.TP 8
+.B "\-xkbmodel \fImodel\fP"
+.TP 8
+.B "\-xkboptions \fIoption\fP"
+.TP 8
+.B "\-xkbrules \fIrule\fP"
+.TP 8
+.B "\-xkbvariant \fIvariant\fp"
+These options implement the xkeyboard extension for loading
+a particular keyboard map as the X server starts.  The behavior is similar
+to the \fIsetxkbmap\fP program.  The layout data is located at
+\fI/usr/X11R6/lib/X11/xkb/\fP.  Additional information is found in the
+README files therein and in the man page of \fIsetxkbmap\fP.  For example
+in order to load a German layout for a pc105 keyboard one uses
+the options:
+.br
+.I " \-xkblayout de \-xkbmodel pc105"
+.PP
+Alternatively one may use the \fIsetxkbmap\fP program after XWin is
+running or even the \fIxmodmap\fP program for loading the old-style
+keyboard maps.
+
+
+.SH "SEE ALSO"
+X(__miscmansuffix__), Xserver(1), xdm(1), xinit(1), XWinrc(1), setxkbmap(1)
+
+
+.SH BUGS
+.I XWin
+and this man page still have many limitations.  Some of the more obvious
+ones are:
+.br
+- The display mode can not be changed once the X server has started.
+.br
+- The XWin software is developing rapidly; it is therefore likely that
+this man page is not up to date.  It is always prudent to 
+look also at the output of \fIXWin -help\fP and to the Cygwin/X User Guide
+at /usr/share/doc/cygwin-x-doc-x.x.x/ug/cygwin-x-ug.xxx in order to
+check the options that are operative.
+
+
+.SH AUTHORS
+This list is by no means complete, but direct contributors to the
+Cygwin/X project include (in alphabetical order by last name): Stuart
+Adamson, Michael Bax, Jehan Bing, Lev Bishop, Dr. Peter Busch, Biju G
+C, Robert Collins, Nick Crabtree, Early Ehlinger, Christopher Faylor,
+John Fortin, Brian Genisio, Fabrizio Gennari, Alexander Gottwald, Ralf
+Habacker, Colin Harrison, Matthieu Herrb, Alan Hourihane, Pierre A
+Humblet, Harold L Hunt II, Dakshinamurthy Karra, Kensuke Matsuzaki,
+Takuma Murakami, Earle F. Philhower III, Benjamin Riefenstahl, Suhaib
+Siddiqi, Jack Tanner, and Nicholas Wourms.
diff --git a/hw/xwin/XWin.rc b/hw/xwin/XWin.rc
new file mode 100644
index 0000000..749c0f5
--- /dev/null
+++ b/hw/xwin/XWin.rc
@@ -0,0 +1,109 @@
+/*
+ *Copyright (C) 2002-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#include "windows.h"
+#include "winresource.h"
+
+/*
+ * Dialogs
+ */
+
+/* About */
+ABOUT_BOX DIALOG DISCARDABLE  32, 32, 240, 105
+STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_TABSTOP  | DS_CENTERMOUSE
+CAPTION "About " PROJECT_NAME
+FONT 8, "MS Sans Serif"
+BEGIN
+  CONTROL               PROJECT_NAME " Website", ID_ABOUT_WEBSITE, "Button",
+                        BS_OWNERDRAW | WS_TABSTOP, 30, 45, 75, 15
+  CONTROL               "Change Log", ID_ABOUT_CHANGELOG, "Button",
+                        BS_OWNERDRAW | WS_TABSTOP, 135, 45, 75, 15
+  CONTROL               "User's Guide", ID_ABOUT_UG, "Button",
+                        BS_OWNERDRAW | WS_TABSTOP, 30, 65, 75, 15
+  CONTROL               "FAQ", ID_ABOUT_FAQ, "Button",
+                        BS_OWNERDRAW | WS_TABSTOP, 135, 65, 75, 15
+
+  DEFPUSHBUTTON		"Dismiss", IDOK, 95, 85, 50, 15
+
+  CTEXT			"Welcome to the preliminary About box for the " PROJECT_NAME " X Server.  This dialog was created on 2004/03/25 and will eventually be filled with more useful information.  For now, use the links below to learn more about the " PROJECT_NAME " project.", IDC_STATIC, 5, 5, 230, 35
+END
+
+
+/* Depth change */
+
+DEPTH_CHANGE_BOX DIALOG DISCARDABLE	32, 32, 180, 100
+STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | DS_CENTERMOUSE
+FONT 8, "MS Sans Serif"
+CAPTION PROJECT_NAME
+BEGIN
+  DEFPUSHBUTTON		"Dismiss", IDOK, 66, 80, 50, 14
+  CTEXT			PROJECT_NAME, IDC_STATIC, 40, 12, 100, 8
+  CTEXT			"Disruptive screen configuration change.", IDC_STATIC, 7, 40, 166, 8
+  CTEXT			"Restore previous resolution to use " PROJECT_NAME ".", IDC_STATIC, 7, 52, 166, 8
+END
+
+
+/* Exit */
+
+EXIT_DIALOG DIALOG DISCARDABLE	32, 32, 180, 78
+STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_TABSTOP | DS_CENTERMOUSE
+FONT 8, "MS Sans Serif"
+CAPTION PROJECT_NAME " - Exit?"
+BEGIN
+  PUSHBUTTON "E&xit", IDOK, 55, 56, 30, 14
+  DEFPUSHBUTTON "&Cancel", IDCANCEL, 95, 56, 30, 14
+  CTEXT "Exiting will close all screens running on this display.", IDC_STATIC, 7, 12, 166, 8
+  CTEXT "No information about connected clients available.", IDC_CLIENTS_CONNECTED, 7, 24, 166, 8
+  CTEXT "Proceed with shutdown of this display/server?", IDC_STATIC, 7, 36, 166, 8
+END
+
+
+/*
+ * Menus
+ */
+
+IDM_TRAYICON_MENU MENU DISCARDABLE
+BEGIN
+	POPUP "TRAYICON_MENU"
+	BEGIN
+		MENUITEM "&Hide Root Window", ID_APP_HIDE_ROOT
+		MENUITEM "&About...", ID_APP_ABOUT
+		MENUITEM SEPARATOR
+		MENUITEM "E&xit", ID_APP_EXIT
+	END
+END
+
+
+/*
+ * Icons
+ */
+
+IDI_XWIN		ICON	DISCARDABLE	"X.ico"
+IDI_XWIN_BOXED		ICON	DISCARDABLE	"X-boxed.ico"
diff --git a/hw/xwin/XWinrc.man b/hw/xwin/XWinrc.man
new file mode 100755
index 0000000..eba3fb6
--- /dev/null
+++ b/hw/xwin/XWinrc.man
@@ -0,0 +1,180 @@
+.TH XWIN 5 __vendorversion__
+
+
+.SH NAME
+XWinrc\- XWin Server Resource Configuration File.
+
+
+.SH DESCRIPTION
+The X Server for the X Window System on the Cygwin/X environment
+running on Microsoft Windows, \fIXWin\fP can be optionally configured
+with the \fIXWinrc\fP file.  A system-wide configuration file should
+be placed in \fI/usr/X11R6/lib/X11/system.XWinrc\fP, a per-user file
+should be put at \fI$HOME/.XWinrc\fP.  The \fIsystem.XWinrc\fP file is
+read only if no \fI$HOME/.XWinrc\fP exist.
+.PP
+With the \fI.XWinrc\fP configuration file it is possible to do the
+following:
+.PP
+1- To include items into the menu associated with the \fIXWin\fP icon
+which is in the \fIWindows\fP system tray.  This feature functions in
+all XWin modes that have such tray icon.
+.PP
+2- To include items into the menu which is associated with the
+\fIWindows\fP window that \fIXWin -multiwindow\fP produces for each
+top-level X-window.  That can be done both for the generic case and
+for particular programs.
+.PP
+3- To change the icon that is associated to the \fIWindows\fP window
+that \fIXWin -multiwindow\fP produces for each top-level X-window.
+Again, that can be done both for the generic case and for particular
+programs.  The new icons associated should be \fIWindows\fP format
+icons \fI.ico\fP.
+
+
+.SH FILE FORMAT
+.B Keywords
+are case insensitive, but in this document they will be written
+completely capitalized.
+.PP
+.B Comments
+are legal pretty much anywhere you can have an end-of-line; they
+begin with "#" or "//" and go to the end-of-line.
+.PP
+Quote marks in strings are optional unless the string has included spaces.
+.PP
+There are three kinds of instructions: miscellaneous, menu, and icon.
+
+
+.SH Miscellaneous instruction
+.TP 8
+.B DEBUG \fIString\fP
+The \fIString\fP is printed to the XWin.log file.
+
+.TP 8
+.B TRAYICON \fIicon-specifier\fB
+The \fBTRAYICON\fP keyword changes the icon \fIXWin\fP displays in the
+system tray area.
+
+.TP 8
+.B SILENTEXIT
+The \fBSILENTEXIT\fP keyword, which takes no parameters, disables the
+exit confirmation dialog.
+
+
+.SH Menu instructions
+.TP 8
+.B MENU \fIMenu_Name\fP {
+.br
+.B       \fIMenu_Item_Line\fP
+.br
+.B       \fIMenu_Item_Line\fP
+.br
+.B        \fI...\fP
+.br
+.B }
+.br
+This instruction defines a menu and asigns a \fIMenu_Name\fP to it.
+\fIMenu_Item_Line\fP are lines  of any of the following types:
+.TP 8
+.B \t SEPARATOR
+.TP 8
+.B  \t \fIItem_Label\fP  EXEC \fICommand\fP
+.TP 8
+.B \t \fIItem_Label\fP  MENU \fIpreviously-defined-menu-name\fP
+.TP 8
+.B \t \fIItem_Label\fP  ALWAYSONTOP
+.TP 8
+.B \t \fIItem_Label\fP  RELOAD
+.br
+The \fIItem_Label\fP is the string that is written in the menu item.
+.br
+\fICommand\fP is a string with the command that will be executed by /bin/sh.
+Here paths should be \fICYGWIN\fP style (e.g. /usr/local/bin/myprogram).
+A string "%display%" appearing in the \fICommand\fP will be replaced
+with the proper display variable (i.e. 127.0.0.1:<display>.0).
+.br
+\fBALWAYSONTOP\fP sets the window to which the menu is associated to
+display above all others.
+.br
+\fBRELOAD\fP causes the XWinrc file to be reloaded and icons and menus
+regenerated.
+.TP 8
+.B ROOTMENU \fIpreviously-defined-menu-name\fP
+Includes the items in the indicated menu into the menu associated with
+\fIXWin\fP that appears in the system tray.
+.TP 8
+.B DEFAULTSYSMENU \fIpreviously-defined-menu-name\fP ATSTART|ATEND
+Includes the items in the indicated menu into the menu associated with
+generic top-level X-Windows in the \fIXWin\fP \fImultiwindow\fP mode.  The
+keywords \fBATSTART\fP and \fBATEND\fP indicate if such items should be
+included at the start or at the end of the menu.
+.TP 8
+.B SYSMENU {
+  \fIclass-or-name-of-window\fP \fIdefined-menu-name\fP \fBATSTART|ATEND\fP
+.br
+  \fI...\fP
+.br
+  \fB}\fP
+.br
+Associates a specific menu to a specific WM_CLASS or WM_NAME.
+
+
+.SH Icon Instructions
+When specifying an \fIicon-file\fP in the following commands several different formats are allowed:
+.br
+\fB"NAME.ICO"\fP\fI of an .ico format file\fP
+.br
+\t \t ("cygwin.ico", "apple.ico")
+.br
+\fB"NAME.DLL,nn"\fP\fI of a .DLL and icon index\fP
+.br
+\t \t ("c:\\windows\\system32\\shell32.dll,4" is the default folder icon)
+.br
+\fB",nn"\fP\fI index into XWin.EXE internal ICON resources\fP
+.br
+\t \t (",101" is the 1st icon inside \fIXWin.EXE\fP)
+.TP 8
+.B ICONDIRECTORY \fIWindows-path-to-icon-directory\fP
+Defines the default directory to search for \ficon-file\fP files.
+It should be a \fIWindows\fP style path (e.g. C:\\cygwin\\usr\\local\\icons).
+.TP 8
+.B DEFAULTICON \fIicon-file\fP
+Defines a replacement for the standard X icon for applications without
+specified icons.
+.TP 8
+.B ICONS {
+.br
+ \fIclass-or-name-of-window\fP \fIicon-file\fP
+.br
+  \fI...\fP
+.br
+  \fB}\fP
+.br
+Defines icon replacements windows matching the specified window class or names.
+If multiple name or class matches occur for a window, only the first one
+will be used.
+
+
+.SH EXAMPLE
+.TP 8
+This example adds an Xterm menu item to the system tray icon
+\fBMENU systray {
+.br
+\t xterm  EXEC "xterm -display %display% -sb -sl 999"
+.br
+\t SEPARATOR
+.br
+}
+.br
+ROOTMENU systray
+\fP
+
+
+.SH "SEE ALSO"
+ XWin(1)
+
+
+.SH AUTHOR
+The XWinrc feature of XWin was written primarily by Earle F. Philhower
+III.
diff --git a/hw/xwin/_usr_X11R6_lib_X11_system.XWinrc b/hw/xwin/_usr_X11R6_lib_X11_system.XWinrc
new file mode 100644
index 0000000..d9c2d42
--- /dev/null
+++ b/hw/xwin/_usr_X11R6_lib_X11_system.XWinrc
@@ -0,0 +1,125 @@
+# XWin Server Resource File - EXAMPLE
+# Earle F. Philhower, III
+
+# Place in ~/.XWinrc or in /usr/X11R6/lib/X11/system.XWinrc
+
+# Keywords are case insensitive, comments legal pretty much anywhere
+# you can have an end-of-line
+
+# Comments begin with "#" or "//" and go to the end-of-line
+
+# Paths to commands are **cygwin** based (i.e. /usr/local/bin/xcalc)
+
+# Paths to icons are **WINDOWS** based (i.e. c:\windows\icons)
+
+# Menus are defined as...
+# MENU <name> {
+#	<Menu Text>	EXEC	<command>
+#                               ^^ This command will have any "%display%"
+#                                  string replaced with the proper display
+#                                  variable (i.e. 127.0.0.1:<display>.0)
+#  or	<Menu Text>	MENU	<name-of-some-prior-defined-menu>
+#  or	<Menu Text>	ALWAYSONTOP
+#                         ^^ Sets the window to display above all others
+#  or   <Menu Text>	RELOAD
+#                         ^^ Causes ~/.XWinrc or the system.XWinrc file
+#                            to be reloaded and icons and menus regenerated
+#  or	SEPARATOR
+#       ...
+# }
+
+# Set the taskmar menu with
+# ROOTMENU <name-of-some-prior-defined-menu>
+
+# If you want a menu to be applied to all popup window's system menu
+# DEFAULTSYSMENU <name-of-some-prior-defined-menu> <atstart|atend>
+
+# To choose a specific menu for a specific WM_CLASS or WM_NAME use ...
+# SYSMENU {
+#	<class-or-name-of-window> <name-of-prior-defined-menu> <atstart|atend>
+#	...
+# }
+
+# When specifying an ICONFILE in the following commands several different
+# formats are allowed:
+# 1. Name of a regular Windows .ico format file
+#    (ex:  "cygwin.ico", "apple.ico")
+# 2. Name and index into a Windows .DLL
+#    (ex: "c:\windows\system32\shell32.dll,4" gives the default folder icon
+#         "c:\windows\system32\shell32.dll,5" gives the floppy drive icon)
+# 3. Index into XWin.EXE internal ICON resource
+#    (ex: ",101" is the 1st icon inside XWin.exe)
+
+# To define where ICO files live (** Windows path**)
+# ICONDIRECTORY	<windows-path i.e. c:\cygwin\usr\icons>
+# NOTE: If you specify a fully qualified path to an ICON below
+#             (i.e. "c:\xxx" or "d:\xxxx")
+#       this ICONDIRECTORY will not be prepended
+
+# To change the taskbar icon use...
+# TRAYICON       <name-of-windows-ico-file-in-icondirectory>
+
+# To define a replacement for the standard X icon for apps w/o specified icons
+# DEFAULTICON	<name-of-windows-ico-file-in-icondirectory>
+
+# To define substitute icons on a per-window basis use...
+# ICONS {
+#	<class-or-name-of-window> <icon-file-name.ico>
+#	...
+# }
+# In the case where multiple matches occur, the first listed in the ICONS
+# section will be chosen.
+
+# To disable exit confirmation dialog add the line containing SilentExit
+
+# DEBUG <string> prints out the string to the XWin.log file
+
+// Below are just some silly menus to demonstrate writing your
+// own configuration file.
+
+// Make some menus...
+menu apps {
+	xterm	exec	"xterm"
+	"Emacs"		exec	"emacs"
+	notepad	exec	notepad
+	xload	exec	"xload -display %display%"  # Comment
+}
+
+menu root {
+// Comments fit here, too...
+	"Reload .XWinrc"	RELOAD
+	"Applications"	menu	apps
+	SEParATOR
+}
+
+menu aot {
+	Separator
+	"Always on Top"	alwaysontop
+}
+
+menu xtermspecial {
+	"Emacs"		exec	"emacs"
+	"Always on Top"	alwaysontop
+	SepArAtor
+}
+
+RootMenu root
+
+DefaultSysMenu aot atend
+
+SysMenu {
+	"xterm"	xtermspecial atstart
+}
+
+# IconDirectory	"c:\winnt\"
+
+# DefaultIcon	"reinstall.ico"
+
+# Icons {
+# 	"xterm"	"uninstall.ico"
+# }
+
+# SilentExit
+
+DEBUG "Done parsing the configuration file..."
+
diff --git a/hw/xwin/ddraw.h b/hw/xwin/ddraw.h
new file mode 100644
index 0000000..2eb7c26
--- /dev/null
+++ b/hw/xwin/ddraw.h
@@ -0,0 +1,2106 @@
+#ifndef __XWIN_DDRAW_H
+#define __XWIN_DDRAW_H
+
+#include <winnt.h>
+#include <wingdi.h>
+#include <objbase.h>
+
+#if defined(NONAMELESSUNION) && !defined(DUMMYUNIONNAME1)
+#define DUMMYUNIONNAME1 u1
+#endif
+
+#define ICOM_CALL_( xfn, p, args) (p)->lpVtbl->xfn args
+
+# ifdef UNICODE
+#  define WINELIB_NAME_AW(func) func##W
+# else
+#  define WINELIB_NAME_AW(func) func##A
+# endif  /* UNICODE */
+#define DECL_WINELIB_TYPE_AW(type)  typedef WINELIB_NAME_AW(type) type;
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* defined(__cplusplus) */
+
+#ifndef	DIRECTDRAW_VERSION
+#define	DIRECTDRAW_VERSION	0x0700
+#endif /* DIRECTDRAW_VERSION */
+
+/*****************************************************************************
+ * Predeclare the interfaces
+ */
+DEFINE_GUID( CLSID_DirectDraw,		0xD7B70EE0,0x4340,0x11CF,0xB0,0x63,0x00,0x20,0xAF,0xC2,0xCD,0x35 );
+DEFINE_GUID( CLSID_DirectDraw7,         0x3C305196,0x50DB,0x11D3,0x9C,0xFE,0x00,0xC0,0x4F,0xD9,0x30,0xC5 );
+DEFINE_GUID( CLSID_DirectDrawClipper,	0x593817A0,0x7DB3,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xb9,0x33,0x56 );
+DEFINE_GUID( IID_IDirectDraw,		0x6C14DB80,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 );
+DEFINE_GUID( IID_IDirectDraw2,		0xB3A6F3E0,0x2B43,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xB9,0x33,0x56 );
+DEFINE_GUID( IID_IDirectDraw4,          0x9c59509a,0x39bd,0x11d1,0x8c,0x4a,0x00,0xc0,0x4f,0xd9,0x30,0xc5 );
+DEFINE_GUID( IID_IDirectDraw7,          0x15e65ec0,0x3b9c,0x11d2,0xb9,0x2f,0x00,0x60,0x97,0x97,0xea,0x5b );
+DEFINE_GUID( IID_IDirectDrawSurface,	0x6C14DB81,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 );
+DEFINE_GUID( IID_IDirectDrawSurface2,	0x57805885,0x6eec,0x11cf,0x94,0x41,0xa8,0x23,0x03,0xc1,0x0e,0x27 );
+DEFINE_GUID( IID_IDirectDrawSurface3,	0xDA044E00,0x69B2,0x11D0,0xA1,0xD5,0x00,0xAA,0x00,0xB8,0xDF,0xBB );
+DEFINE_GUID( IID_IDirectDrawSurface4,   0x0B2B8630,0xAD35,0x11D0,0x8E,0xA6,0x00,0x60,0x97,0x97,0xEA,0x5B );
+DEFINE_GUID( IID_IDirectDrawSurface7,   0x06675a80,0x3b9b,0x11d2,0xb9,0x2f,0x00,0x60,0x97,0x97,0xea,0x5b );
+DEFINE_GUID( IID_IDirectDrawPalette,	0x6C14DB84,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 );
+DEFINE_GUID( IID_IDirectDrawClipper,	0x6C14DB85,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 );
+DEFINE_GUID( IID_IDirectDrawColorControl,0x4B9F0EE0,0x0D7E,0x11D0,0x9B,0x06,0x00,0xA0,0xC9,0x03,0xA3,0xB8 );
+DEFINE_GUID( IID_IDirectDrawGammaControl,0x69C11C3E,0xB46B,0x11D1,0xAD,0x7A,0x00,0xC0,0x4F,0xC2,0x9B,0x4E );
+
+typedef struct IDirectDraw *LPDIRECTDRAW;
+typedef struct IDirectDraw2 *LPDIRECTDRAW2;
+typedef struct IDirectDraw4 *LPDIRECTDRAW4;
+typedef struct IDirectDraw7 *LPDIRECTDRAW7;
+typedef struct IDirectDrawClipper *LPDIRECTDRAWCLIPPER;
+typedef struct IDirectDrawPalette *LPDIRECTDRAWPALETTE;
+typedef struct IDirectDrawSurface *LPDIRECTDRAWSURFACE;
+typedef struct IDirectDrawSurface2 *LPDIRECTDRAWSURFACE2;
+typedef struct IDirectDrawSurface3 *LPDIRECTDRAWSURFACE3;
+typedef struct IDirectDrawSurface4 *LPDIRECTDRAWSURFACE4;
+typedef struct IDirectDrawSurface7 *LPDIRECTDRAWSURFACE7;
+typedef struct IDirectDrawColorControl *LPDIRECTDRAWCOLORCONTROL;
+typedef struct IDirectDrawGammaControl *LPDIRECTDRAWGAMMACONTROL;
+
+
+#define DDENUMRET_CANCEL	0
+#define DDENUMRET_OK		1
+
+#define DD_OK			0
+
+
+#define _FACDD		0x876
+#define MAKE_DDHRESULT( code )  MAKE_HRESULT( 1, _FACDD, code )
+
+#define DDERR_ALREADYINITIALIZED		MAKE_DDHRESULT( 5 )
+#define DDERR_CANNOTATTACHSURFACE		MAKE_DDHRESULT( 10 )
+#define DDERR_CANNOTDETACHSURFACE		MAKE_DDHRESULT( 20 )
+#define DDERR_CURRENTLYNOTAVAIL			MAKE_DDHRESULT( 40 )
+#define DDERR_EXCEPTION				MAKE_DDHRESULT( 55 )
+#define DDERR_GENERIC				E_FAIL
+#define DDERR_HEIGHTALIGN			MAKE_DDHRESULT( 90 )
+#define DDERR_INCOMPATIBLEPRIMARY		MAKE_DDHRESULT( 95 )
+#define DDERR_INVALIDCAPS			MAKE_DDHRESULT( 100 )
+#define DDERR_INVALIDCLIPLIST			MAKE_DDHRESULT( 110 )
+#define DDERR_INVALIDMODE			MAKE_DDHRESULT( 120 )
+#define DDERR_INVALIDOBJECT			MAKE_DDHRESULT( 130 )
+#define DDERR_INVALIDPARAMS			E_INVALIDARG
+#define DDERR_INVALIDPIXELFORMAT		MAKE_DDHRESULT( 145 )
+#define DDERR_INVALIDRECT			MAKE_DDHRESULT( 150 )
+#define DDERR_LOCKEDSURFACES			MAKE_DDHRESULT( 160 )
+#define DDERR_NO3D				MAKE_DDHRESULT( 170 )
+#define DDERR_NOALPHAHW				MAKE_DDHRESULT( 180 )
+#define DDERR_NOSTEREOHARDWARE          	MAKE_DDHRESULT( 181 )
+#define DDERR_NOSURFACELEFT                     MAKE_DDHRESULT( 182 )
+#define DDERR_NOCLIPLIST			MAKE_DDHRESULT( 205 )
+#define DDERR_NOCOLORCONVHW			MAKE_DDHRESULT( 210 )
+#define DDERR_NOCOOPERATIVELEVELSET		MAKE_DDHRESULT( 212 )
+#define DDERR_NOCOLORKEY			MAKE_DDHRESULT( 215 )
+#define DDERR_NOCOLORKEYHW			MAKE_DDHRESULT( 220 )
+#define DDERR_NODIRECTDRAWSUPPORT		MAKE_DDHRESULT( 222 )
+#define DDERR_NOEXCLUSIVEMODE			MAKE_DDHRESULT( 225 )
+#define DDERR_NOFLIPHW				MAKE_DDHRESULT( 230 )
+#define DDERR_NOGDI				MAKE_DDHRESULT( 240 )
+#define DDERR_NOMIRRORHW			MAKE_DDHRESULT( 250 )
+#define DDERR_NOTFOUND				MAKE_DDHRESULT( 255 )
+#define DDERR_NOOVERLAYHW			MAKE_DDHRESULT( 260 )
+#define DDERR_OVERLAPPINGRECTS                  MAKE_DDHRESULT( 270 )
+#define DDERR_NORASTEROPHW			MAKE_DDHRESULT( 280 )
+#define DDERR_NOROTATIONHW			MAKE_DDHRESULT( 290 )
+#define DDERR_NOSTRETCHHW			MAKE_DDHRESULT( 310 )
+#define DDERR_NOT4BITCOLOR			MAKE_DDHRESULT( 316 )
+#define DDERR_NOT4BITCOLORINDEX			MAKE_DDHRESULT( 317 )
+#define DDERR_NOT8BITCOLOR			MAKE_DDHRESULT( 320 )
+#define DDERR_NOTEXTUREHW			MAKE_DDHRESULT( 330 )
+#define DDERR_NOVSYNCHW				MAKE_DDHRESULT( 335 )
+#define DDERR_NOZBUFFERHW			MAKE_DDHRESULT( 340 )
+#define DDERR_NOZOVERLAYHW			MAKE_DDHRESULT( 350 )
+#define DDERR_OUTOFCAPS				MAKE_DDHRESULT( 360 )
+#define DDERR_OUTOFMEMORY			E_OUTOFMEMORY
+#define DDERR_OUTOFVIDEOMEMORY			MAKE_DDHRESULT( 380 )
+#define DDERR_OVERLAYCANTCLIP			MAKE_DDHRESULT( 382 )
+#define DDERR_OVERLAYCOLORKEYONLYONEACTIVE	MAKE_DDHRESULT( 384 )
+#define DDERR_PALETTEBUSY			MAKE_DDHRESULT( 387 )
+#define DDERR_COLORKEYNOTSET			MAKE_DDHRESULT( 400 )
+#define DDERR_SURFACEALREADYATTACHED		MAKE_DDHRESULT( 410 )
+#define DDERR_SURFACEALREADYDEPENDENT		MAKE_DDHRESULT( 420 )
+#define DDERR_SURFACEBUSY			MAKE_DDHRESULT( 430 )
+#define DDERR_CANTLOCKSURFACE			MAKE_DDHRESULT( 435 )
+#define DDERR_SURFACEISOBSCURED			MAKE_DDHRESULT( 440 )
+#define DDERR_SURFACELOST			MAKE_DDHRESULT( 450 )
+#define DDERR_SURFACENOTATTACHED		MAKE_DDHRESULT( 460 )
+#define DDERR_TOOBIGHEIGHT			MAKE_DDHRESULT( 470 )
+#define DDERR_TOOBIGSIZE			MAKE_DDHRESULT( 480 )
+#define DDERR_TOOBIGWIDTH			MAKE_DDHRESULT( 490 )
+#define DDERR_UNSUPPORTED			E_NOTIMPL
+#define DDERR_UNSUPPORTEDFORMAT			MAKE_DDHRESULT( 510 )
+#define DDERR_UNSUPPORTEDMASK			MAKE_DDHRESULT( 520 )
+#define DDERR_INVALIDSTREAM                     MAKE_DDHRESULT( 521 )
+#define DDERR_VERTICALBLANKINPROGRESS		MAKE_DDHRESULT( 537 )
+#define DDERR_WASSTILLDRAWING			MAKE_DDHRESULT( 540 )
+#define DDERR_DDSCAPSCOMPLEXREQUIRED            MAKE_DDHRESULT( 542 )
+#define DDERR_XALIGN				MAKE_DDHRESULT( 560 )
+#define DDERR_INVALIDDIRECTDRAWGUID		MAKE_DDHRESULT( 561 )
+#define DDERR_DIRECTDRAWALREADYCREATED		MAKE_DDHRESULT( 562 )
+#define DDERR_NODIRECTDRAWHW			MAKE_DDHRESULT( 563 )
+#define DDERR_PRIMARYSURFACEALREADYEXISTS	MAKE_DDHRESULT( 564 )
+#define DDERR_NOEMULATION			MAKE_DDHRESULT( 565 )
+#define DDERR_REGIONTOOSMALL			MAKE_DDHRESULT( 566 )
+#define DDERR_CLIPPERISUSINGHWND		MAKE_DDHRESULT( 567 )
+#define DDERR_NOCLIPPERATTACHED			MAKE_DDHRESULT( 568 )
+#define DDERR_NOHWND				MAKE_DDHRESULT( 569 )
+#define DDERR_HWNDSUBCLASSED			MAKE_DDHRESULT( 570 )
+#define DDERR_HWNDALREADYSET			MAKE_DDHRESULT( 571 )
+#define DDERR_NOPALETTEATTACHED			MAKE_DDHRESULT( 572 )
+#define DDERR_NOPALETTEHW			MAKE_DDHRESULT( 573 )
+#define DDERR_BLTFASTCANTCLIP			MAKE_DDHRESULT( 574 )
+#define DDERR_NOBLTHW				MAKE_DDHRESULT( 575 )
+#define DDERR_NODDROPSHW			MAKE_DDHRESULT( 576 )
+#define DDERR_OVERLAYNOTVISIBLE			MAKE_DDHRESULT( 577 )
+#define DDERR_NOOVERLAYDEST			MAKE_DDHRESULT( 578 )
+#define DDERR_INVALIDPOSITION			MAKE_DDHRESULT( 579 )
+#define DDERR_NOTAOVERLAYSURFACE		MAKE_DDHRESULT( 580 )
+#define DDERR_EXCLUSIVEMODEALREADYSET		MAKE_DDHRESULT( 581 )
+#define DDERR_NOTFLIPPABLE			MAKE_DDHRESULT( 582 )
+#define DDERR_CANTDUPLICATE			MAKE_DDHRESULT( 583 )
+#define DDERR_NOTLOCKED				MAKE_DDHRESULT( 584 )
+#define DDERR_CANTCREATEDC			MAKE_DDHRESULT( 585 )
+#define DDERR_NODC				MAKE_DDHRESULT( 586 )
+#define DDERR_WRONGMODE				MAKE_DDHRESULT( 587 )
+#define DDERR_IMPLICITLYCREATED			MAKE_DDHRESULT( 588 )
+#define DDERR_NOTPALETTIZED			MAKE_DDHRESULT( 589 )
+#define DDERR_UNSUPPORTEDMODE			MAKE_DDHRESULT( 590 )
+#define DDERR_NOMIPMAPHW			MAKE_DDHRESULT( 591 )
+#define DDERR_INVALIDSURFACETYPE		MAKE_DDHRESULT( 592 )
+#define DDERR_NOOPTIMIZEHW			MAKE_DDHRESULT( 600 )
+#define DDERR_NOTLOADED				MAKE_DDHRESULT( 601 )
+#define DDERR_NOFOCUSWINDOW			MAKE_DDHRESULT( 602 )
+#define DDERR_NOTONMIPMAPSUBLEVEL               MAKE_DDHRESULT( 603 )
+#define DDERR_DCALREADYCREATED			MAKE_DDHRESULT( 620 )
+#define DDERR_NONONLOCALVIDMEM			MAKE_DDHRESULT( 630 )
+#define DDERR_CANTPAGELOCK			MAKE_DDHRESULT( 640 )
+#define DDERR_CANTPAGEUNLOCK			MAKE_DDHRESULT( 660 )
+#define DDERR_NOTPAGELOCKED			MAKE_DDHRESULT( 680 )
+#define DDERR_MOREDATA				MAKE_DDHRESULT( 690 )
+#define DDERR_EXPIRED                           MAKE_DDHRESULT( 691 )
+#define DDERR_TESTFINISHED                      MAKE_DDHRESULT( 692 )
+#define DDERR_NEWMODE                           MAKE_DDHRESULT( 693 )
+#define DDERR_D3DNOTINITIALIZED                 MAKE_DDHRESULT( 694 )
+#define DDERR_VIDEONOTACTIVE			MAKE_DDHRESULT( 695 )
+#define DDERR_NOMONITORINFORMATION              MAKE_DDHRESULT( 696 )
+#define DDERR_NODRIVERSUPPORT                   MAKE_DDHRESULT( 697 )
+#define DDERR_DEVICEDOESNTOWNSURFACE		MAKE_DDHRESULT( 699 )
+#define DDERR_NOTINITIALIZED			CO_E_NOTINITIALIZED
+
+/* dwFlags for Blt* */
+#define DDBLT_ALPHADEST				0x00000001
+#define DDBLT_ALPHADESTCONSTOVERRIDE		0x00000002
+#define DDBLT_ALPHADESTNEG			0x00000004
+#define DDBLT_ALPHADESTSURFACEOVERRIDE		0x00000008
+#define DDBLT_ALPHAEDGEBLEND			0x00000010
+#define DDBLT_ALPHASRC				0x00000020
+#define DDBLT_ALPHASRCCONSTOVERRIDE		0x00000040
+#define DDBLT_ALPHASRCNEG			0x00000080
+#define DDBLT_ALPHASRCSURFACEOVERRIDE		0x00000100
+#define DDBLT_ASYNC				0x00000200
+#define DDBLT_COLORFILL				0x00000400
+#define DDBLT_DDFX				0x00000800
+#define DDBLT_DDROPS				0x00001000
+#define DDBLT_KEYDEST				0x00002000
+#define DDBLT_KEYDESTOVERRIDE			0x00004000
+#define DDBLT_KEYSRC				0x00008000
+#define DDBLT_KEYSRCOVERRIDE			0x00010000
+#define DDBLT_ROP				0x00020000
+#define DDBLT_ROTATIONANGLE			0x00040000
+#define DDBLT_ZBUFFER				0x00080000
+#define DDBLT_ZBUFFERDESTCONSTOVERRIDE		0x00100000
+#define DDBLT_ZBUFFERDESTOVERRIDE		0x00200000
+#define DDBLT_ZBUFFERSRCCONSTOVERRIDE		0x00400000
+#define DDBLT_ZBUFFERSRCOVERRIDE		0x00800000
+#define DDBLT_WAIT				0x01000000
+#define DDBLT_DEPTHFILL				0x02000000
+#define DDBLT_DONOTWAIT                         0x08000000
+
+/* dwTrans for BltFast */
+#define DDBLTFAST_NOCOLORKEY			0x00000000
+#define DDBLTFAST_SRCCOLORKEY			0x00000001
+#define DDBLTFAST_DESTCOLORKEY			0x00000002
+#define DDBLTFAST_WAIT				0x00000010
+#define DDBLTFAST_DONOTWAIT                     0x00000020
+
+/* dwFlags for Flip */
+#define DDFLIP_WAIT		0x00000001
+#define DDFLIP_EVEN		0x00000002 /* only valid for overlay */
+#define DDFLIP_ODD		0x00000004 /* only valid for overlay */
+#define DDFLIP_NOVSYNC		0x00000008
+#define DDFLIP_STEREO		0x00000010
+#define DDFLIP_DONOTWAIT	0x00000020
+
+/* dwFlags for GetBltStatus */
+#define DDGBS_CANBLT				0x00000001
+#define DDGBS_ISBLTDONE				0x00000002
+
+/* dwFlags for IDirectDrawSurface7::GetFlipStatus */
+#define DDGFS_CANFLIP		1L
+#define DDGFS_ISFLIPDONE	2L
+
+/* dwFlags for IDirectDrawSurface7::SetPrivateData */
+#define DDSPD_IUNKNOWNPTR	1L
+#define DDSPD_VOLATILE		2L
+
+/* DDSCAPS.dwCaps */
+/* reserved1, was 3d capable */
+#define DDSCAPS_RESERVED1		0x00000001
+/* surface contains alpha information */
+#define DDSCAPS_ALPHA			0x00000002
+/* this surface is a backbuffer */
+#define DDSCAPS_BACKBUFFER		0x00000004
+/* complex surface structure */
+#define DDSCAPS_COMPLEX			0x00000008
+/* part of surface flipping structure */
+#define DDSCAPS_FLIP			0x00000010
+/* this surface is the frontbuffer surface */
+#define DDSCAPS_FRONTBUFFER		0x00000020
+/* this is a plain offscreen surface */
+#define DDSCAPS_OFFSCREENPLAIN		0x00000040
+/* overlay */
+#define DDSCAPS_OVERLAY			0x00000080
+/* palette objects can be created and attached to us */
+#define DDSCAPS_PALETTE			0x00000100
+/* primary surface (the one the user looks at currently)(right eye)*/
+#define DDSCAPS_PRIMARYSURFACE		0x00000200
+/* primary surface for left eye */
+#define DDSCAPS_PRIMARYSURFACELEFT	0x00000400
+/* surface exists in systemmemory */
+#define DDSCAPS_SYSTEMMEMORY		0x00000800
+/* surface can be used as a texture */
+#define DDSCAPS_TEXTURE		        0x00001000
+/* surface may be destination for 3d rendering */
+#define DDSCAPS_3DDEVICE		0x00002000
+/* surface exists in videomemory */
+#define DDSCAPS_VIDEOMEMORY		0x00004000
+/* surface changes immediately visible */
+#define DDSCAPS_VISIBLE			0x00008000
+/* write only surface */
+#define DDSCAPS_WRITEONLY		0x00010000
+/* zbuffer surface */
+#define DDSCAPS_ZBUFFER			0x00020000
+/* has its own DC */
+#define DDSCAPS_OWNDC			0x00040000
+/* surface should be able to receive live video */
+#define DDSCAPS_LIVEVIDEO		0x00080000
+/* should be able to have a hw codec decompress stuff into it */
+#define DDSCAPS_HWCODEC			0x00100000
+/* mode X (320x200 or 320x240) surface */
+#define DDSCAPS_MODEX			0x00200000
+/* one mipmap surface (1 level) */
+#define DDSCAPS_MIPMAP			0x00400000
+#define DDSCAPS_RESERVED2		0x00800000
+/* memory allocation delayed until Load() */
+#define DDSCAPS_ALLOCONLOAD		0x04000000
+/* Indicates that the surface will receive data from a video port */
+#define DDSCAPS_VIDEOPORT		0x08000000
+/* surface is in local videomemory */
+#define DDSCAPS_LOCALVIDMEM		0x10000000
+/* surface is in nonlocal videomemory */
+#define DDSCAPS_NONLOCALVIDMEM		0x20000000
+/* surface is a standard VGA mode surface (NOT ModeX) */
+#define DDSCAPS_STANDARDVGAMODE		0x40000000
+/* optimized? surface */
+#define DDSCAPS_OPTIMIZED		0x80000000
+
+typedef struct _DDSCAPS {
+	DWORD	dwCaps;	/* capabilities of surface wanted */
+} DDSCAPS,*LPDDSCAPS;
+
+/* DDSCAPS2.dwCaps2 */
+/* indicates the surface will receive data from a video port using
+   deinterlacing hardware. */
+#define DDSCAPS2_HARDWAREDEINTERLACE	0x00000002
+/* indicates the surface will be locked very frequently. */
+#define DDSCAPS2_HINTDYNAMIC		0x00000004
+/* indicates surface can be re-ordered or retiled on load() */
+#define DDSCAPS2_HINTSTATIC             0x00000008
+/* indicates surface to be managed by directdraw/direct3D */
+#define DDSCAPS2_TEXTUREMANAGE          0x00000010
+/* reserved bits */
+#define DDSCAPS2_RESERVED1              0x00000020
+#define DDSCAPS2_RESERVED2              0x00000040
+/* indicates surface will never be locked again */
+#define DDSCAPS2_OPAQUE                 0x00000080
+/* set at CreateSurface() time to indicate antialising will be used */
+#define DDSCAPS2_HINTANTIALIASING       0x00000100
+/* set at CreateSurface() time to indicate cubic environment map */
+#define DDSCAPS2_CUBEMAP                0x00000200
+/* face flags for cube maps */
+#define DDSCAPS2_CUBEMAP_POSITIVEX      0x00000400
+#define DDSCAPS2_CUBEMAP_NEGATIVEX      0x00000800
+#define DDSCAPS2_CUBEMAP_POSITIVEY      0x00001000
+#define DDSCAPS2_CUBEMAP_NEGATIVEY      0x00002000
+#define DDSCAPS2_CUBEMAP_POSITIVEZ      0x00004000
+#define DDSCAPS2_CUBEMAP_NEGATIVEZ      0x00008000
+/* specifies all faces of a cube for CreateSurface() */
+#define DDSCAPS2_CUBEMAP_ALLFACES ( DDSCAPS2_CUBEMAP_POSITIVEX |\
+                                    DDSCAPS2_CUBEMAP_NEGATIVEX |\
+                                    DDSCAPS2_CUBEMAP_POSITIVEY |\
+                                    DDSCAPS2_CUBEMAP_NEGATIVEY |\
+                                    DDSCAPS2_CUBEMAP_POSITIVEZ |\
+                                    DDSCAPS2_CUBEMAP_NEGATIVEZ )
+/* set for mipmap sublevels on DirectX7 and later.  ignored by CreateSurface() */
+#define DDSCAPS2_MIPMAPSUBLEVEL         0x00010000
+/* indicates texture surface to be managed by Direct3D *only* */
+#define DDSCAPS2_D3DTEXTUREMANAGE       0x00020000
+/* indicates managed surface that can safely be lost */
+#define DDSCAPS2_DONOTPERSIST           0x00040000
+/* indicates surface is part of a stereo flipping chain */
+#define DDSCAPS2_STEREOSURFACELEFT      0x00080000
+
+typedef struct _DDSCAPS2 {
+	DWORD	dwCaps;	/* capabilities of surface wanted */
+	DWORD   dwCaps2; /* additional capabilities */
+	DWORD   dwCaps3; /* reserved capabilities */
+	DWORD   dwCaps4; /* more reserved capabilities */
+} DDSCAPS2,*LPDDSCAPS2;
+
+#define	DD_ROP_SPACE	(256/32)	/* space required to store ROP array */
+
+typedef struct _DDCAPS_DX7		/* DirectX 7 version of caps struct */
+{
+    DWORD	dwSize;                 /* size of the DDDRIVERCAPS structure */
+    DWORD	dwCaps;                 /* driver specific capabilities */
+    DWORD	dwCaps2;                /* more driver specific capabilites */
+    DWORD	dwCKeyCaps;             /* color key capabilities of the surface */
+    DWORD	dwFXCaps;               /* driver specific stretching and effects capabilites */
+    DWORD	dwFXAlphaCaps;          /* alpha driver specific capabilities */
+    DWORD	dwPalCaps;              /* palette capabilities */
+    DWORD	dwSVCaps;               /* stereo vision capabilities */
+    DWORD	dwAlphaBltConstBitDepths;       /* DDBD_2,4,8 */
+    DWORD	dwAlphaBltPixelBitDepths;       /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaBltSurfaceBitDepths;     /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlayConstBitDepths;   /* DDBD_2,4,8 */
+    DWORD	dwAlphaOverlayPixelBitDepths;   /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */
+    DWORD	dwZBufferBitDepths;             /* DDBD_8,16,24,32 */
+    DWORD	dwVidMemTotal;          /* total amount of video memory */
+    DWORD	dwVidMemFree;           /* amount of free video memory */
+    DWORD	dwMaxVisibleOverlays;   /* maximum number of visible overlays */
+    DWORD	dwCurrVisibleOverlays;  /* current number of visible overlays */
+    DWORD	dwNumFourCCCodes;       /* number of four cc codes */
+    DWORD	dwAlignBoundarySrc;     /* source rectangle alignment */
+    DWORD	dwAlignSizeSrc;         /* source rectangle byte size */
+    DWORD	dwAlignBoundaryDest;    /* dest rectangle alignment */
+    DWORD	dwAlignSizeDest;        /* dest rectangle byte size */
+    DWORD	dwAlignStrideAlign;     /* stride alignment */
+    DWORD	dwRops[DD_ROP_SPACE];   /* ROPS supported */
+    DDSCAPS	ddsOldCaps;             /* old DDSCAPS - superceded for DirectX6+ */
+    DWORD	dwMinOverlayStretch;    /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxOverlayStretch;    /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinLiveVideoStretch;  /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxLiveVideoStretch;  /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinHwCodecStretch;    /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxHwCodecStretch;    /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwReserved1;
+    DWORD	dwReserved2;
+    DWORD	dwReserved3;
+    DWORD	dwSVBCaps;              /* driver specific capabilities for System->Vmem blts */
+    DWORD	dwSVBCKeyCaps;          /* driver color key capabilities for System->Vmem blts */
+    DWORD	dwSVBFXCaps;            /* driver FX capabilities for System->Vmem blts */
+    DWORD	dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */
+    DWORD	dwVSBCaps;              /* driver specific capabilities for Vmem->System blts */
+    DWORD	dwVSBCKeyCaps;          /* driver color key capabilities for Vmem->System blts */
+    DWORD	dwVSBFXCaps;            /* driver FX capabilities for Vmem->System blts */
+    DWORD	dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */
+    DWORD	dwSSBCaps;              /* driver specific capabilities for System->System blts */
+    DWORD	dwSSBCKeyCaps;          /* driver color key capabilities for System->System blts */
+    DWORD	dwSSBFXCaps;            /* driver FX capabilities for System->System blts */
+    DWORD	dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */
+    DWORD       dwMaxVideoPorts;        /* maximum number of usable video ports */
+    DWORD   	dwCurrVideoPorts;       /* current number of video ports used */
+    DWORD   	dwSVBCaps2;             /* more driver specific capabilities for System->Vmem blts */
+    DWORD   	dwNLVBCaps;             /* driver specific capabilities for non-local->local vidmem blts */
+    DWORD   	dwNLVBCaps2;            /* more driver specific capabilities non-local->local vidmem blts */
+    DWORD   	dwNLVBCKeyCaps;         /* driver color key capabilities for non-local->local vidmem blts */
+    DWORD   	dwNLVBFXCaps;           /* driver FX capabilities for non-local->local blts */
+    DWORD   	dwNLVBRops[DD_ROP_SPACE]; /* ROPS supported for non-local->local blts */
+    DDSCAPS2    ddsCaps;		/* surface capabilities */
+} DDCAPS_DX7,*LPDDCAPS_DX7;
+
+typedef struct _DDCAPS_DX6		/* DirectX 6 version of caps struct */
+{
+    DWORD	dwSize;                 /* size of the DDDRIVERCAPS structure */
+    DWORD	dwCaps;                 /* driver specific capabilities */
+    DWORD	dwCaps2;                /* more driver specific capabilites */
+    DWORD	dwCKeyCaps;             /* color key capabilities of the surface */
+    DWORD	dwFXCaps;               /* driver specific stretching and effects capabilites */
+    DWORD	dwFXAlphaCaps;          /* alpha driver specific capabilities */
+    DWORD	dwPalCaps;              /* palette capabilities */
+    DWORD	dwSVCaps;               /* stereo vision capabilities */
+    DWORD	dwAlphaBltConstBitDepths;       /* DDBD_2,4,8 */
+    DWORD	dwAlphaBltPixelBitDepths;       /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaBltSurfaceBitDepths;     /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlayConstBitDepths;   /* DDBD_2,4,8 */
+    DWORD	dwAlphaOverlayPixelBitDepths;   /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */
+    DWORD	dwZBufferBitDepths;             /* DDBD_8,16,24,32 */
+    DWORD	dwVidMemTotal;          /* total amount of video memory */
+    DWORD	dwVidMemFree;           /* amount of free video memory */
+    DWORD	dwMaxVisibleOverlays;   /* maximum number of visible overlays */
+    DWORD	dwCurrVisibleOverlays;  /* current number of visible overlays */
+    DWORD	dwNumFourCCCodes;       /* number of four cc codes */
+    DWORD	dwAlignBoundarySrc;     /* source rectangle alignment */
+    DWORD	dwAlignSizeSrc;         /* source rectangle byte size */
+    DWORD	dwAlignBoundaryDest;    /* dest rectangle alignment */
+    DWORD	dwAlignSizeDest;        /* dest rectangle byte size */
+    DWORD	dwAlignStrideAlign;     /* stride alignment */
+    DWORD	dwRops[DD_ROP_SPACE];   /* ROPS supported */
+    DDSCAPS	ddsOldCaps;             /* old DDSCAPS - superceded for DirectX6+ */
+    DWORD	dwMinOverlayStretch;    /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxOverlayStretch;    /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinLiveVideoStretch;  /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxLiveVideoStretch;  /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinHwCodecStretch;    /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxHwCodecStretch;    /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwReserved1;
+    DWORD	dwReserved2;
+    DWORD	dwReserved3;
+    DWORD	dwSVBCaps;              /* driver specific capabilities for System->Vmem blts */
+    DWORD	dwSVBCKeyCaps;          /* driver color key capabilities for System->Vmem blts */
+    DWORD	dwSVBFXCaps;            /* driver FX capabilities for System->Vmem blts */
+    DWORD	dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */
+    DWORD	dwVSBCaps;              /* driver specific capabilities for Vmem->System blts */
+    DWORD	dwVSBCKeyCaps;          /* driver color key capabilities for Vmem->System blts */
+    DWORD	dwVSBFXCaps;            /* driver FX capabilities for Vmem->System blts */
+    DWORD	dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */
+    DWORD	dwSSBCaps;              /* driver specific capabilities for System->System blts */
+    DWORD	dwSSBCKeyCaps;          /* driver color key capabilities for System->System blts */
+    DWORD	dwSSBFXCaps;            /* driver FX capabilities for System->System blts */
+    DWORD	dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */
+    DWORD       dwMaxVideoPorts;        /* maximum number of usable video ports */
+    DWORD   	dwCurrVideoPorts;       /* current number of video ports used */
+    DWORD   	dwSVBCaps2;             /* more driver specific capabilities for System->Vmem blts */
+    DWORD   	dwNLVBCaps;             /* driver specific capabilities for non-local->local vidmem blts */
+    DWORD   	dwNLVBCaps2;            /* more driver specific capabilities non-local->local vidmem blts */
+    DWORD   	dwNLVBCKeyCaps;         /* driver color key capabilities for non-local->local vidmem blts */
+    DWORD   	dwNLVBFXCaps;           /* driver FX capabilities for non-local->local blts */
+    DWORD   	dwNLVBRops[DD_ROP_SPACE]; /* ROPS supported for non-local->local blts */
+    /* and one new member for DirectX 6 */
+    DDSCAPS2    ddsCaps;		/* surface capabilities */
+} DDCAPS_DX6,*LPDDCAPS_DX6;
+
+typedef struct _DDCAPS_DX5		/* DirectX5 version of caps struct */
+{
+    DWORD	dwSize;                 /* size of the DDDRIVERCAPS structure */
+    DWORD	dwCaps;                 /* driver specific capabilities */
+    DWORD	dwCaps2;                /* more driver specific capabilites */
+    DWORD	dwCKeyCaps;             /* color key capabilities of the surface */
+    DWORD	dwFXCaps;               /* driver specific stretching and effects capabilites */
+    DWORD	dwFXAlphaCaps;          /* alpha driver specific capabilities */
+    DWORD	dwPalCaps;              /* palette capabilities */
+    DWORD	dwSVCaps;               /* stereo vision capabilities */
+    DWORD	dwAlphaBltConstBitDepths;       /* DDBD_2,4,8 */
+    DWORD	dwAlphaBltPixelBitDepths;       /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaBltSurfaceBitDepths;     /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlayConstBitDepths;   /* DDBD_2,4,8 */
+    DWORD	dwAlphaOverlayPixelBitDepths;   /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */
+    DWORD	dwZBufferBitDepths;             /* DDBD_8,16,24,32 */
+    DWORD	dwVidMemTotal;          /* total amount of video memory */
+    DWORD	dwVidMemFree;           /* amount of free video memory */
+    DWORD	dwMaxVisibleOverlays;   /* maximum number of visible overlays */
+    DWORD	dwCurrVisibleOverlays;  /* current number of visible overlays */
+    DWORD	dwNumFourCCCodes;       /* number of four cc codes */
+    DWORD	dwAlignBoundarySrc;     /* source rectangle alignment */
+    DWORD	dwAlignSizeSrc;         /* source rectangle byte size */
+    DWORD	dwAlignBoundaryDest;    /* dest rectangle alignment */
+    DWORD	dwAlignSizeDest;        /* dest rectangle byte size */
+    DWORD	dwAlignStrideAlign;     /* stride alignment */
+    DWORD	dwRops[DD_ROP_SPACE];   /* ROPS supported */
+    DDSCAPS	ddsCaps;                /* DDSCAPS structure has all the general capabilities */
+    DWORD	dwMinOverlayStretch;    /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxOverlayStretch;    /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinLiveVideoStretch;  /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxLiveVideoStretch;  /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinHwCodecStretch;    /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxHwCodecStretch;    /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwReserved1;
+    DWORD	dwReserved2;
+    DWORD	dwReserved3;
+    DWORD	dwSVBCaps;              /* driver specific capabilities for System->Vmem blts */
+    DWORD	dwSVBCKeyCaps;          /* driver color key capabilities for System->Vmem blts */
+    DWORD	dwSVBFXCaps;            /* driver FX capabilities for System->Vmem blts */
+    DWORD	dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */
+    DWORD	dwVSBCaps;              /* driver specific capabilities for Vmem->System blts */
+    DWORD	dwVSBCKeyCaps;          /* driver color key capabilities for Vmem->System blts */
+    DWORD	dwVSBFXCaps;            /* driver FX capabilities for Vmem->System blts */
+    DWORD	dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */
+    DWORD	dwSSBCaps;              /* driver specific capabilities for System->System blts */
+    DWORD	dwSSBCKeyCaps;          /* driver color key capabilities for System->System blts */
+    DWORD	dwSSBFXCaps;            /* driver FX capabilities for System->System blts */
+    DWORD	dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */
+    /* the following are the new DirectX 5 members */
+    DWORD       dwMaxVideoPorts;        /* maximum number of usable video ports */
+    DWORD   	dwCurrVideoPorts;       /* current number of video ports used */
+    DWORD   	dwSVBCaps2;             /* more driver specific capabilities for System->Vmem blts */
+    DWORD   	dwNLVBCaps;             /* driver specific capabilities for non-local->local vidmem blts */
+    DWORD   	dwNLVBCaps2;            /* more driver specific capabilities non-local->local vidmem blts */
+    DWORD   	dwNLVBCKeyCaps;         /* driver color key capabilities for non-local->local vidmem blts */
+    DWORD   	dwNLVBFXCaps;           /* driver FX capabilities for non-local->local blts */
+    DWORD   	dwNLVBRops[DD_ROP_SPACE]; /* ROPS supported for non-local->local blts */
+} DDCAPS_DX5,*LPDDCAPS_DX5;
+
+typedef struct _DDCAPS_DX3		/* DirectX3 version of caps struct */
+{
+    DWORD	dwSize;                 /* size of the DDDRIVERCAPS structure */
+    DWORD	dwCaps;                 /* driver specific capabilities */
+    DWORD	dwCaps2;                /* more driver specific capabilites */
+    DWORD	dwCKeyCaps;             /* color key capabilities of the surface */
+    DWORD	dwFXCaps;               /* driver specific stretching and effects capabilites */
+    DWORD	dwFXAlphaCaps;          /* alpha driver specific capabilities */
+    DWORD	dwPalCaps;              /* palette capabilities */
+    DWORD	dwSVCaps;               /* stereo vision capabilities */
+    DWORD	dwAlphaBltConstBitDepths;       /* DDBD_2,4,8 */
+    DWORD	dwAlphaBltPixelBitDepths;       /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaBltSurfaceBitDepths;     /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlayConstBitDepths;   /* DDBD_2,4,8 */
+    DWORD	dwAlphaOverlayPixelBitDepths;   /* DDBD_1,2,4,8 */
+    DWORD	dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */
+    DWORD	dwZBufferBitDepths;             /* DDBD_8,16,24,32 */
+    DWORD	dwVidMemTotal;          /* total amount of video memory */
+    DWORD	dwVidMemFree;           /* amount of free video memory */
+    DWORD	dwMaxVisibleOverlays;   /* maximum number of visible overlays */
+    DWORD	dwCurrVisibleOverlays;  /* current number of visible overlays */
+    DWORD	dwNumFourCCCodes;       /* number of four cc codes */
+    DWORD	dwAlignBoundarySrc;     /* source rectangle alignment */
+    DWORD	dwAlignSizeSrc;         /* source rectangle byte size */
+    DWORD	dwAlignBoundaryDest;    /* dest rectangle alignment */
+    DWORD	dwAlignSizeDest;        /* dest rectangle byte size */
+    DWORD	dwAlignStrideAlign;     /* stride alignment */
+    DWORD	dwRops[DD_ROP_SPACE];   /* ROPS supported */
+    DDSCAPS	ddsCaps;                /* DDSCAPS structure has all the general capabilities */
+    DWORD	dwMinOverlayStretch;    /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxOverlayStretch;    /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinLiveVideoStretch;  /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxLiveVideoStretch;  /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMinHwCodecStretch;    /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwMaxHwCodecStretch;    /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
+    DWORD	dwReserved1;
+    DWORD	dwReserved2;
+    DWORD	dwReserved3;
+    DWORD	dwSVBCaps;              /* driver specific capabilities for System->Vmem blts */
+    DWORD	dwSVBCKeyCaps;          /* driver color key capabilities for System->Vmem blts */
+    DWORD	dwSVBFXCaps;            /* driver FX capabilities for System->Vmem blts */
+    DWORD	dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */
+    DWORD	dwVSBCaps;              /* driver specific capabilities for Vmem->System blts */
+    DWORD	dwVSBCKeyCaps;          /* driver color key capabilities for Vmem->System blts */
+    DWORD	dwVSBFXCaps;            /* driver FX capabilities for Vmem->System blts */
+    DWORD	dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */
+    DWORD	dwSSBCaps;              /* driver specific capabilities for System->System blts */
+    DWORD	dwSSBCKeyCaps;          /* driver color key capabilities for System->System blts */
+    DWORD	dwSSBFXCaps;            /* driver FX capabilities for System->System blts */
+    DWORD	dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */
+    DWORD	dwReserved4;
+    DWORD	dwReserved5;
+    DWORD	dwReserved6;
+} DDCAPS_DX3,*LPDDCAPS_DX3;
+
+/* set caps struct according to DIRECTDRAW_VERSION */
+
+#if DIRECTDRAW_VERSION <= 0x300
+typedef DDCAPS_DX3 DDCAPS;
+#elif DIRECTDRAW_VERSION <= 0x500
+typedef DDCAPS_DX5 DDCAPS;
+#elif DIRECTDRAW_VERSION <= 0x600
+typedef DDCAPS_DX6 DDCAPS;
+#else
+typedef DDCAPS_DX7 DDCAPS;
+#endif
+
+typedef DDCAPS *LPDDCAPS;
+
+/* DDCAPS.dwCaps */
+#define DDCAPS_3D			0x00000001
+#define DDCAPS_ALIGNBOUNDARYDEST	0x00000002
+#define DDCAPS_ALIGNSIZEDEST		0x00000004
+#define DDCAPS_ALIGNBOUNDARYSRC		0x00000008
+#define DDCAPS_ALIGNSIZESRC		0x00000010
+#define DDCAPS_ALIGNSTRIDE		0x00000020
+#define DDCAPS_BLT			0x00000040
+#define DDCAPS_BLTQUEUE			0x00000080
+#define DDCAPS_BLTFOURCC		0x00000100
+#define DDCAPS_BLTSTRETCH		0x00000200
+#define DDCAPS_GDI			0x00000400
+#define DDCAPS_OVERLAY			0x00000800
+#define DDCAPS_OVERLAYCANTCLIP		0x00001000
+#define DDCAPS_OVERLAYFOURCC		0x00002000
+#define DDCAPS_OVERLAYSTRETCH		0x00004000
+#define DDCAPS_PALETTE			0x00008000
+#define DDCAPS_PALETTEVSYNC		0x00010000
+#define DDCAPS_READSCANLINE		0x00020000
+#define DDCAPS_STEREOVIEW		0x00040000
+#define DDCAPS_VBI			0x00080000
+#define DDCAPS_ZBLTS			0x00100000
+#define DDCAPS_ZOVERLAYS		0x00200000
+#define DDCAPS_COLORKEY			0x00400000
+#define DDCAPS_ALPHA			0x00800000
+#define DDCAPS_COLORKEYHWASSIST		0x01000000
+#define DDCAPS_NOHARDWARE		0x02000000
+#define DDCAPS_BLTCOLORFILL		0x04000000
+#define DDCAPS_BANKSWITCHED		0x08000000
+#define DDCAPS_BLTDEPTHFILL		0x10000000
+#define DDCAPS_CANCLIP			0x20000000
+#define DDCAPS_CANCLIPSTRETCHED		0x40000000
+#define DDCAPS_CANBLTSYSMEM		0x80000000
+
+/* DDCAPS.dwCaps2 */
+#define DDCAPS2_CERTIFIED		0x00000001
+#define DDCAPS2_NO2DDURING3DSCENE       0x00000002
+#define DDCAPS2_VIDEOPORT		0x00000004
+#define DDCAPS2_AUTOFLIPOVERLAY		0x00000008
+#define DDCAPS2_CANBOBINTERLEAVED	0x00000010
+#define DDCAPS2_CANBOBNONINTERLEAVED	0x00000020
+#define DDCAPS2_COLORCONTROLOVERLAY	0x00000040
+#define DDCAPS2_COLORCONTROLPRIMARY	0x00000080
+#define DDCAPS2_CANDROPZ16BIT		0x00000100
+#define DDCAPS2_NONLOCALVIDMEM		0x00000200
+#define DDCAPS2_NONLOCALVIDMEMCAPS	0x00000400
+#define DDCAPS2_NOPAGELOCKREQUIRED	0x00000800
+#define DDCAPS2_WIDESURFACES		0x00001000
+#define DDCAPS2_CANFLIPODDEVEN		0x00002000
+#define DDCAPS2_CANBOBHARDWARE		0x00004000
+#define DDCAPS2_COPYFOURCC              0x00008000
+#define DDCAPS2_PRIMARYGAMMA            0x00020000
+#define DDCAPS2_CANRENDERWINDOWED       0x00080000
+#define DDCAPS2_CANCALIBRATEGAMMA       0x00100000
+#define DDCAPS2_FLIPINTERVAL            0x00200000
+#define DDCAPS2_FLIPNOVSYNC             0x00400000
+#define DDCAPS2_CANMANAGETEXTURE        0x00800000
+#define DDCAPS2_TEXMANINNONLOCALVIDMEM  0x01000000
+#define DDCAPS2_STEREO                  0x02000000
+#define DDCAPS2_SYSTONONLOCAL_AS_SYSTOLOCAL   0x04000000
+
+
+/* Set/Get Colour Key Flags */
+#define DDCKEY_COLORSPACE  0x00000001  /* Struct is single colour space */
+#define DDCKEY_DESTBLT     0x00000002  /* To be used as dest for blt */
+#define DDCKEY_DESTOVERLAY 0x00000004  /* To be used as dest for CK overlays */
+#define DDCKEY_SRCBLT      0x00000008  /* To be used as src for blt */
+#define DDCKEY_SRCOVERLAY  0x00000010  /* To be used as src for CK overlays */
+
+typedef struct _DDCOLORKEY
+{
+	DWORD	dwColorSpaceLowValue;/* low boundary of color space that is to
+                                      * be treated as Color Key, inclusive
+				      */
+	DWORD	dwColorSpaceHighValue;/* high boundary of color space that is
+                                       * to be treated as Color Key, inclusive
+				       */
+} DDCOLORKEY,*LPDDCOLORKEY;
+
+/* ddCKEYCAPS bits */
+#define DDCKEYCAPS_DESTBLT			0x00000001
+#define DDCKEYCAPS_DESTBLTCLRSPACE		0x00000002
+#define DDCKEYCAPS_DESTBLTCLRSPACEYUV		0x00000004
+#define DDCKEYCAPS_DESTBLTYUV			0x00000008
+#define DDCKEYCAPS_DESTOVERLAY			0x00000010
+#define DDCKEYCAPS_DESTOVERLAYCLRSPACE		0x00000020
+#define DDCKEYCAPS_DESTOVERLAYCLRSPACEYUV	0x00000040
+#define DDCKEYCAPS_DESTOVERLAYONEACTIVE		0x00000080
+#define DDCKEYCAPS_DESTOVERLAYYUV		0x00000100
+#define DDCKEYCAPS_SRCBLT			0x00000200
+#define DDCKEYCAPS_SRCBLTCLRSPACE		0x00000400
+#define DDCKEYCAPS_SRCBLTCLRSPACEYUV		0x00000800
+#define DDCKEYCAPS_SRCBLTYUV			0x00001000
+#define DDCKEYCAPS_SRCOVERLAY			0x00002000
+#define DDCKEYCAPS_SRCOVERLAYCLRSPACE		0x00004000
+#define DDCKEYCAPS_SRCOVERLAYCLRSPACEYUV	0x00008000
+#define DDCKEYCAPS_SRCOVERLAYONEACTIVE		0x00010000
+#define DDCKEYCAPS_SRCOVERLAYYUV		0x00020000
+#define DDCKEYCAPS_NOCOSTOVERLAY		0x00040000
+
+typedef struct _DDPIXELFORMAT {
+    DWORD	dwSize;                 /* 0: size of structure */
+    DWORD	dwFlags;                /* 4: pixel format flags */
+    DWORD	dwFourCC;               /* 8: (FOURCC code) */
+    union {
+	DWORD	dwRGBBitCount;          /* C: how many bits per pixel */
+	DWORD	dwYUVBitCount;          /* C: how many bits per pixel */
+	DWORD	dwZBufferBitDepth;      /* C: how many bits for z buffers */
+	DWORD	dwAlphaBitDepth;        /* C: how many bits for alpha channels*/
+	DWORD	dwLuminanceBitCount;
+	DWORD	dwBumpBitCount;
+    } DUMMYUNIONNAME1;
+    union {
+	DWORD	dwRBitMask;             /* 10: mask for red bit*/
+	DWORD	dwYBitMask;             /* 10: mask for Y bits*/
+	DWORD	dwStencilBitDepth;
+	DWORD	dwLuminanceBitMask;
+	DWORD	dwBumpDuBitMask;
+    } DUMMYUNIONNAME2;
+    union {
+	DWORD	dwGBitMask;             /* 14: mask for green bits*/
+	DWORD	dwUBitMask;             /* 14: mask for U bits*/
+	DWORD	dwZBitMask;
+	DWORD	dwBumpDvBitMask;
+    } DUMMYUNIONNAME3;
+    union {
+	DWORD   dwBBitMask;             /* 18: mask for blue bits*/
+	DWORD   dwVBitMask;             /* 18: mask for V bits*/
+	DWORD	dwStencilBitMask;
+	DWORD	dwBumpLuminanceBitMask;
+    } DUMMYUNIONNAME4;
+    union {
+    	DWORD	dwRGBAlphaBitMask;	/* 1C: mask for alpha channel */
+    	DWORD	dwYUVAlphaBitMask;	/* 1C: mask for alpha channel */
+	DWORD	dwLuminanceAlphaBitMask;
+	DWORD	dwRGBZBitMask;		/* 1C: mask for Z channel */
+	DWORD	dwYUVZBitMask;		/* 1C: mask for Z channel */
+    } DUMMYUNIONNAME5;
+    					/* 20: next structure */
+} DDPIXELFORMAT,*LPDDPIXELFORMAT;
+
+/* DDCAPS.dwFXCaps */
+#define DDFXCAPS_BLTALPHA               0x00000001
+#define DDFXCAPS_OVERLAYALPHA           0x00000004
+#define DDFXCAPS_BLTARITHSTRETCHYN	0x00000010
+#define DDFXCAPS_BLTARITHSTRETCHY	0x00000020
+#define DDFXCAPS_BLTMIRRORLEFTRIGHT	0x00000040
+#define DDFXCAPS_BLTMIRRORUPDOWN	0x00000080
+#define DDFXCAPS_BLTROTATION		0x00000100
+#define DDFXCAPS_BLTROTATION90		0x00000200
+#define DDFXCAPS_BLTSHRINKX		0x00000400
+#define DDFXCAPS_BLTSHRINKXN		0x00000800
+#define DDFXCAPS_BLTSHRINKY		0x00001000
+#define DDFXCAPS_BLTSHRINKYN		0x00002000
+#define DDFXCAPS_BLTSTRETCHX		0x00004000
+#define DDFXCAPS_BLTSTRETCHXN		0x00008000
+#define DDFXCAPS_BLTSTRETCHY		0x00010000
+#define DDFXCAPS_BLTSTRETCHYN		0x00020000
+#define DDFXCAPS_OVERLAYARITHSTRETCHY	0x00040000
+#define DDFXCAPS_OVERLAYARITHSTRETCHYN	0x00000008
+#define DDFXCAPS_OVERLAYSHRINKX		0x00080000
+#define DDFXCAPS_OVERLAYSHRINKXN	0x00100000
+#define DDFXCAPS_OVERLAYSHRINKY		0x00200000
+#define DDFXCAPS_OVERLAYSHRINKYN	0x00400000
+#define DDFXCAPS_OVERLAYSTRETCHX	0x00800000
+#define DDFXCAPS_OVERLAYSTRETCHXN	0x01000000
+#define DDFXCAPS_OVERLAYSTRETCHY	0x02000000
+#define DDFXCAPS_OVERLAYSTRETCHYN	0x04000000
+#define DDFXCAPS_OVERLAYMIRRORLEFTRIGHT	0x08000000
+#define DDFXCAPS_OVERLAYMIRRORUPDOWN	0x10000000
+
+#define DDFXCAPS_OVERLAYFILTER          DDFXCAPS_OVERLAYARITHSTRETCHY
+
+/* DDCAPS.dwFXAlphaCaps */
+#define DDFXALPHACAPS_BLTALPHAEDGEBLEND		0x00000001
+#define DDFXALPHACAPS_BLTALPHAPIXELS		0x00000002
+#define DDFXALPHACAPS_BLTALPHAPIXELSNEG		0x00000004
+#define DDFXALPHACAPS_BLTALPHASURFACES		0x00000008
+#define DDFXALPHACAPS_BLTALPHASURFACESNEG	0x00000010
+#define DDFXALPHACAPS_OVERLAYALPHAEDGEBLEND	0x00000020
+#define DDFXALPHACAPS_OVERLAYALPHAPIXELS	0x00000040
+#define DDFXALPHACAPS_OVERLAYALPHAPIXELSNEG	0x00000080
+#define DDFXALPHACAPS_OVERLAYALPHASURFACES	0x00000100
+#define DDFXALPHACAPS_OVERLAYALPHASURFACESNEG	0x00000200
+
+/* DDCAPS.dwPalCaps */
+#define DDPCAPS_4BIT			0x00000001
+#define DDPCAPS_8BITENTRIES		0x00000002
+#define DDPCAPS_8BIT			0x00000004
+#define DDPCAPS_INITIALIZE		0x00000008
+#define DDPCAPS_PRIMARYSURFACE		0x00000010
+#define DDPCAPS_PRIMARYSURFACELEFT	0x00000020
+#define DDPCAPS_ALLOW256		0x00000040
+#define DDPCAPS_VSYNC			0x00000080
+#define DDPCAPS_1BIT			0x00000100
+#define DDPCAPS_2BIT			0x00000200
+#define DDPCAPS_ALPHA                   0x00000400
+
+/* DDCAPS.dwSVCaps */
+/* the first 4 of these are now obsolete */
+#if DIRECTDRAW_VERSION >= 0x700	/* FIXME: I'm not sure when this switch occured */
+#define DDSVCAPS_RESERVED1		0x00000001
+#define DDSVCAPS_RESERVED2		0x00000002
+#define DDSVCAPS_RESERVED3		0x00000004
+#define DDSVCAPS_RESERVED4		0x00000008
+#else
+#define DDSVCAPS_ENIGMA			0x00000001
+#define DDSVCAPS_FLICKER		0x00000002
+#define DDSVCAPS_REDBLUE		0x00000004
+#define DDSVCAPS_SPLIT			0x00000008
+#endif
+#define DDSVCAPS_STEREOSEQUENTIAL       0x00000010
+
+/* BitDepths */
+#define DDBD_1				0x00004000
+#define DDBD_2				0x00002000
+#define DDBD_4				0x00001000
+#define DDBD_8				0x00000800
+#define DDBD_16				0x00000400
+#define DDBD_24				0x00000200
+#define DDBD_32				0x00000100
+
+/* DDOVERLAYFX.dwDDFX */
+#define DDOVERFX_ARITHSTRETCHY		0x00000001
+#define DDOVERFX_MIRRORLEFTRIGHT	0x00000002
+#define DDOVERFX_MIRRORUPDOWN		0x00000004
+
+/* UpdateOverlay flags */
+#define DDOVER_ALPHADEST                        0x00000001
+#define DDOVER_ALPHADESTCONSTOVERRIDE           0x00000002
+#define DDOVER_ALPHADESTNEG                     0x00000004
+#define DDOVER_ALPHADESTSURFACEOVERRIDE         0x00000008
+#define DDOVER_ALPHAEDGEBLEND                   0x00000010
+#define DDOVER_ALPHASRC                         0x00000020
+#define DDOVER_ALPHASRCCONSTOVERRIDE            0x00000040
+#define DDOVER_ALPHASRCNEG                      0x00000080
+#define DDOVER_ALPHASRCSURFACEOVERRIDE          0x00000100
+#define DDOVER_HIDE                             0x00000200
+#define DDOVER_KEYDEST                          0x00000400
+#define DDOVER_KEYDESTOVERRIDE                  0x00000800
+#define DDOVER_KEYSRC                           0x00001000
+#define DDOVER_KEYSRCOVERRIDE                   0x00002000
+#define DDOVER_SHOW                             0x00004000
+#define DDOVER_ADDDIRTYRECT                     0x00008000
+#define DDOVER_REFRESHDIRTYRECTS                0x00010000
+#define DDOVER_REFRESHALL                       0x00020000
+#define DDOVER_DDFX                             0x00080000
+#define DDOVER_AUTOFLIP                         0x00100000
+#define DDOVER_BOB                              0x00200000
+#define DDOVER_OVERRIDEBOBWEAVE                 0x00400000
+#define DDOVER_INTERLEAVED                      0x00800000
+
+/* DDCOLORKEY.dwFlags */
+#define DDPF_ALPHAPIXELS		0x00000001
+#define DDPF_ALPHA			0x00000002
+#define DDPF_FOURCC			0x00000004
+#define DDPF_PALETTEINDEXED4		0x00000008
+#define DDPF_PALETTEINDEXEDTO8		0x00000010
+#define DDPF_PALETTEINDEXED8		0x00000020
+#define DDPF_RGB			0x00000040
+#define DDPF_COMPRESSED			0x00000080
+#define DDPF_RGBTOYUV			0x00000100
+#define DDPF_YUV			0x00000200
+#define DDPF_ZBUFFER			0x00000400
+#define DDPF_PALETTEINDEXED1		0x00000800
+#define DDPF_PALETTEINDEXED2		0x00001000
+#define DDPF_ZPIXELS			0x00002000
+#define DDPF_STENCILBUFFER              0x00004000
+#define DDPF_ALPHAPREMULT               0x00008000
+#define DDPF_LUMINANCE                  0x00020000
+#define DDPF_BUMPLUMINANCE              0x00040000
+#define DDPF_BUMPDUDV                   0x00080000
+
+/* SetCooperativeLevel dwFlags */
+#define DDSCL_FULLSCREEN		0x00000001
+#define DDSCL_ALLOWREBOOT		0x00000002
+#define DDSCL_NOWINDOWCHANGES		0x00000004
+#define DDSCL_NORMAL			0x00000008
+#define DDSCL_EXCLUSIVE			0x00000010
+#define DDSCL_ALLOWMODEX		0x00000040
+#define DDSCL_SETFOCUSWINDOW		0x00000080
+#define DDSCL_SETDEVICEWINDOW		0x00000100
+#define DDSCL_CREATEDEVICEWINDOW	0x00000200
+#define DDSCL_MULTITHREADED             0x00000400
+#define DDSCL_FPUSETUP                  0x00000800
+#define DDSCL_FPUPRESERVE               0x00001000
+
+
+/* DDSURFACEDESC.dwFlags */
+#define	DDSD_CAPS		0x00000001
+#define	DDSD_HEIGHT		0x00000002
+#define	DDSD_WIDTH		0x00000004
+#define	DDSD_PITCH		0x00000008
+#define	DDSD_BACKBUFFERCOUNT	0x00000020
+#define	DDSD_ZBUFFERBITDEPTH	0x00000040
+#define	DDSD_ALPHABITDEPTH	0x00000080
+#define	DDSD_LPSURFACE		0x00000800
+#define	DDSD_PIXELFORMAT	0x00001000
+#define	DDSD_CKDESTOVERLAY	0x00002000
+#define	DDSD_CKDESTBLT		0x00004000
+#define	DDSD_CKSRCOVERLAY	0x00008000
+#define	DDSD_CKSRCBLT		0x00010000
+#define	DDSD_MIPMAPCOUNT	0x00020000
+#define	DDSD_REFRESHRATE	0x00040000
+#define	DDSD_LINEARSIZE		0x00080000
+#define DDSD_TEXTURESTAGE       0x00100000
+#define DDSD_FVF                0x00200000
+#define DDSD_SRCVBHANDLE        0x00400000
+#define	DDSD_ALL		0x007ff9ee
+
+/* EnumSurfaces flags */
+#define DDENUMSURFACES_ALL          0x00000001
+#define DDENUMSURFACES_MATCH        0x00000002
+#define DDENUMSURFACES_NOMATCH      0x00000004
+#define DDENUMSURFACES_CANBECREATED 0x00000008
+#define DDENUMSURFACES_DOESEXIST    0x00000010
+
+/* SetDisplayMode flags */
+#define DDSDM_STANDARDVGAMODE	0x00000001
+
+/* EnumDisplayModes flags */
+#define DDEDM_REFRESHRATES	0x00000001
+#define DDEDM_STANDARDVGAMODES	0x00000002
+
+/* WaitForVerticalDisplay flags */
+
+#define DDWAITVB_BLOCKBEGIN		0x00000001
+#define DDWAITVB_BLOCKBEGINEVENT	0x00000002
+#define DDWAITVB_BLOCKEND		0x00000004
+
+typedef struct _DDSURFACEDESC
+{
+	DWORD	dwSize;		/* 0: size of the DDSURFACEDESC structure*/
+	DWORD	dwFlags;	/* 4: determines what fields are valid*/
+	DWORD	dwHeight;	/* 8: height of surface to be created*/
+	DWORD	dwWidth;	/* C: width of input surface*/
+	union {
+		LONG	lPitch;	/* 10: distance to start of next line (return value only)*/
+		DWORD	dwLinearSize;
+	} DUMMYUNIONNAME1;
+	DWORD	dwBackBufferCount;/* 14: number of back buffers requested*/
+	union {
+		DWORD	dwMipMapCount;/* 18:number of mip-map levels requested*/
+		DWORD	dwZBufferBitDepth;/*18: depth of Z buffer requested*/
+		DWORD	dwRefreshRate;/* 18:refresh rate (used when display mode is described)*/
+	} DUMMYUNIONNAME2;		
+	DWORD	dwAlphaBitDepth;/* 1C:depth of alpha buffer requested*/
+	DWORD	dwReserved;	/* 20:reserved*/
+	LPVOID	lpSurface;	/* 24:pointer to the associated surface memory*/
+	DDCOLORKEY	ddckCKDestOverlay;/* 28: CK for dest overlay use*/
+	DDCOLORKEY	ddckCKDestBlt;	/* 30: CK for destination blt use*/
+	DDCOLORKEY	ddckCKSrcOverlay;/* 38: CK for source overlay use*/
+	DDCOLORKEY	ddckCKSrcBlt;	/* 40: CK for source blt use*/
+	DDPIXELFORMAT	ddpfPixelFormat;/* 48: pixel format description of the surface*/
+	DDSCAPS		ddsCaps;	/* 68: direct draw surface caps */
+} DDSURFACEDESC,*LPDDSURFACEDESC;
+
+typedef struct _DDSURFACEDESC2
+{
+	DWORD	dwSize;		/* 0: size of the DDSURFACEDESC structure*/
+	DWORD	dwFlags;	/* 4: determines what fields are valid*/
+	DWORD	dwHeight;	/* 8: height of surface to be created*/
+	DWORD	dwWidth;	/* C: width of input surface*/
+	union {
+		LONG	lPitch;	      /*10: distance to start of next line (return value only)*/
+		DWORD   dwLinearSize; /*10: formless late-allocated optimized surface size */
+	} DUMMYUNIONNAME1;
+	DWORD	dwBackBufferCount;/* 14: number of back buffers requested*/
+	union {
+		DWORD	dwMipMapCount;/* 18:number of mip-map levels requested*/
+		DWORD	dwRefreshRate;/* 18:refresh rate (used when display mode is described)*/
+		DWORD   dwSrcVBHandle;/* 18:source used in VB::Optimize */
+	} DUMMYUNIONNAME2;
+	DWORD	dwAlphaBitDepth;/* 1C:depth of alpha buffer requested*/
+	DWORD	dwReserved;	/* 20:reserved*/
+	LPVOID	lpSurface;	/* 24:pointer to the associated surface memory*/
+	union {
+		DDCOLORKEY	ddckCKDestOverlay; /* 28: CK for dest overlay use*/
+		DWORD 		dwEmptyFaceColor;  /* 28: color for empty cubemap faces */
+	} DUMMYUNIONNAME3;
+	DDCOLORKEY	ddckCKDestBlt;	/* 30: CK for destination blt use*/
+	DDCOLORKEY	ddckCKSrcOverlay;/* 38: CK for source overlay use*/
+	DDCOLORKEY	ddckCKSrcBlt;	/* 40: CK for source blt use*/
+
+	union {
+		DDPIXELFORMAT	ddpfPixelFormat;/* 48: pixel format description of the surface*/
+		DWORD 		dwFVF;	/* 48: vertex format description of vertex buffers */	
+	} DUMMYUNIONNAME4;
+	DDSCAPS2	ddsCaps;  /* 68: DDraw surface caps */
+	DWORD		dwTextureStage; /* 78: stage in multitexture cascade */
+} DDSURFACEDESC2,*LPDDSURFACEDESC2;
+
+/* DDCOLORCONTROL.dwFlags */
+#define DDCOLOR_BRIGHTNESS	0x00000001
+#define DDCOLOR_CONTRAST	0x00000002
+#define DDCOLOR_HUE		0x00000004
+#define DDCOLOR_SATURATION	0x00000008
+#define DDCOLOR_SHARPNESS	0x00000010
+#define DDCOLOR_GAMMA		0x00000020
+#define DDCOLOR_COLORENABLE	0x00000040
+
+typedef struct {
+	DWORD	dwSize;
+	DWORD	dwFlags;
+	LONG	lBrightness;
+	LONG	lContrast;
+	LONG	lHue;
+	LONG	lSaturation;
+	LONG	lSharpness;
+	LONG	lGamma;
+	LONG	lColorEnable;
+	DWORD	dwReserved1;
+} DDCOLORCONTROL,*LPDDCOLORCONTROL;
+
+typedef struct {
+	WORD	red[256];
+	WORD	green[256];
+	WORD	blue[256];
+} DDGAMMARAMP,*LPDDGAMMARAMP;
+
+typedef BOOL CALLBACK (*LPDDENUMCALLBACKA)(GUID *, LPSTR, LPSTR, LPVOID);
+typedef BOOL CALLBACK (*LPDDENUMCALLBACKW)(GUID *, LPWSTR, LPWSTR, LPVOID);
+DECL_WINELIB_TYPE_AW(LPDDENUMCALLBACK)
+
+typedef HRESULT CALLBACK (*LPDDENUMMODESCALLBACK)(LPDDSURFACEDESC, LPVOID);
+typedef HRESULT CALLBACK (*LPDDENUMMODESCALLBACK2)(LPDDSURFACEDESC2, LPVOID);
+typedef HRESULT CALLBACK (*LPDDENUMSURFACESCALLBACK)(LPDIRECTDRAWSURFACE, LPDDSURFACEDESC, LPVOID);
+typedef HRESULT CALLBACK (*LPDDENUMSURFACESCALLBACK2)(LPDIRECTDRAWSURFACE4, LPDDSURFACEDESC2, LPVOID);
+typedef HRESULT CALLBACK (*LPDDENUMSURFACESCALLBACK7)(LPDIRECTDRAWSURFACE7, LPDDSURFACEDESC2, LPVOID);
+
+typedef BOOL CALLBACK (*LPDDENUMCALLBACKEXA)(GUID *, LPSTR, LPSTR, LPVOID, HMONITOR);
+typedef BOOL CALLBACK (*LPDDENUMCALLBACKEXW)(GUID *, LPWSTR, LPWSTR, LPVOID, HMONITOR);
+DECL_WINELIB_TYPE_AW(LPDDENUMCALLBACKEX)
+
+HRESULT WINAPI DirectDrawEnumerateExA( LPDDENUMCALLBACKEXA lpCallback, LPVOID lpContext, DWORD dwFlags);
+HRESULT WINAPI DirectDrawEnumerateExW( LPDDENUMCALLBACKEXW lpCallback, LPVOID lpContext, DWORD dwFlags);
+#define DirectDrawEnumerateEx WINELIB_NAME_AW(DirectDrawEnumerateEx)
+
+/* flags for DirectDrawEnumerateEx */
+#define DDENUM_ATTACHEDSECONDARYDEVICES	0x00000001
+#define DDENUM_DETACHEDSECONDARYDEVICES	0x00000002
+#define DDENUM_NONDISPLAYDEVICES	0x00000004
+
+/* flags for DirectDrawCreate or IDirectDraw::Initialize */
+#define DDCREATE_HARDWAREONLY	1L
+#define DDCREATE_EMULATIONONLY	2L
+
+typedef struct _DDBLTFX
+{
+    DWORD       dwSize;                         /* size of structure */
+    DWORD       dwDDFX;                         /* FX operations */
+    DWORD       dwROP;                          /* Win32 raster operations */
+    DWORD       dwDDROP;                        /* Raster operations new for DirectDraw */
+    DWORD       dwRotationAngle;                /* Rotation angle for blt */
+    DWORD       dwZBufferOpCode;                /* ZBuffer compares */
+    DWORD       dwZBufferLow;                   /* Low limit of Z buffer */
+    DWORD       dwZBufferHigh;                  /* High limit of Z buffer */
+    DWORD       dwZBufferBaseDest;              /* Destination base value */
+    DWORD       dwZDestConstBitDepth;           /* Bit depth used to specify Z constant for destination */
+    union
+    {
+        DWORD   dwZDestConst;                   /* Constant to use as Z buffer for dest */
+        LPDIRECTDRAWSURFACE lpDDSZBufferDest;   /* Surface to use as Z buffer for dest */
+    } DUMMYUNIONNAME1;
+    DWORD       dwZSrcConstBitDepth;            /* Bit depth used to specify Z constant for source */
+    union
+    {
+        DWORD   dwZSrcConst;                    /* Constant to use as Z buffer for src */
+        LPDIRECTDRAWSURFACE lpDDSZBufferSrc;    /* Surface to use as Z buffer for src */
+    } DUMMYUNIONNAME2;
+    DWORD       dwAlphaEdgeBlendBitDepth;       /* Bit depth used to specify constant for alpha edge blend */
+    DWORD       dwAlphaEdgeBlend;               /* Alpha for edge blending */
+    DWORD       dwReserved;
+    DWORD       dwAlphaDestConstBitDepth;       /* Bit depth used to specify alpha constant for destination */
+    union
+    {
+        DWORD   dwAlphaDestConst;               /* Constant to use as Alpha Channel */
+        LPDIRECTDRAWSURFACE lpDDSAlphaDest;     /* Surface to use as Alpha Channel */
+    } DUMMYUNIONNAME3;
+    DWORD       dwAlphaSrcConstBitDepth;        /* Bit depth used to specify alpha constant for source */
+    union
+    {
+        DWORD   dwAlphaSrcConst;                /* Constant to use as Alpha Channel */
+        LPDIRECTDRAWSURFACE lpDDSAlphaSrc;      /* Surface to use as Alpha Channel */
+    } DUMMYUNIONNAME4;
+    union
+    {
+        DWORD   dwFillColor;                    /* color in RGB or Palettized */
+        DWORD   dwFillDepth;                    /* depth value for z-buffer */
+	DWORD   dwFillPixel;			/* pixel val for RGBA or RGBZ */
+        LPDIRECTDRAWSURFACE lpDDSPattern;       /* Surface to use as pattern */
+    } DUMMYUNIONNAME5;
+    DDCOLORKEY  ddckDestColorkey;               /* DestColorkey override */
+    DDCOLORKEY  ddckSrcColorkey;                /* SrcColorkey override */
+} DDBLTFX,*LPDDBLTFX;
+
+/* dwDDFX */
+/* arithmetic stretching along y axis */
+#define DDBLTFX_ARITHSTRETCHY			0x00000001
+/* mirror on y axis */
+#define DDBLTFX_MIRRORLEFTRIGHT			0x00000002
+/* mirror on x axis */
+#define DDBLTFX_MIRRORUPDOWN			0x00000004
+/* do not tear */
+#define DDBLTFX_NOTEARING			0x00000008
+/* 180 degrees clockwise rotation */
+#define DDBLTFX_ROTATE180			0x00000010
+/* 270 degrees clockwise rotation */
+#define DDBLTFX_ROTATE270			0x00000020
+/* 90 degrees clockwise rotation */
+#define DDBLTFX_ROTATE90			0x00000040
+/* dwZBufferLow and dwZBufferHigh specify limits to the copied Z values */
+#define DDBLTFX_ZBUFFERRANGE			0x00000080
+/* add dwZBufferBaseDest to every source z value before compare */
+#define DDBLTFX_ZBUFFERBASEDEST			0x00000100
+
+typedef struct _DDOVERLAYFX
+{
+    DWORD       dwSize;                         /* size of structure */
+    DWORD       dwAlphaEdgeBlendBitDepth;       /* Bit depth used to specify constant for alpha edge blend */
+    DWORD       dwAlphaEdgeBlend;               /* Constant to use as alpha for edge blend */
+    DWORD       dwReserved;
+    DWORD       dwAlphaDestConstBitDepth;       /* Bit depth used to specify alpha constant for destination */
+    union
+    {
+        DWORD   dwAlphaDestConst;               /* Constant to use as alpha channel for dest */
+        LPDIRECTDRAWSURFACE lpDDSAlphaDest;     /* Surface to use as alpha channel for dest */
+    } DUMMYUNIONNAME1;
+    DWORD       dwAlphaSrcConstBitDepth;        /* Bit depth used to specify alpha constant for source */
+    union
+    {
+        DWORD   dwAlphaSrcConst;                /* Constant to use as alpha channel for src */
+        LPDIRECTDRAWSURFACE lpDDSAlphaSrc;      /* Surface to use as alpha channel for src */
+    } DUMMYUNIONNAME2;
+    DDCOLORKEY  dckDestColorkey;                /* DestColorkey override */
+    DDCOLORKEY  dckSrcColorkey;                 /* DestColorkey override */
+    DWORD       dwDDFX;                         /* Overlay FX */
+    DWORD       dwFlags;                        /* flags */
+} DDOVERLAYFX,*LPDDOVERLAYFX;
+
+typedef struct _DDBLTBATCH
+{
+    LPRECT		lprDest;
+    LPDIRECTDRAWSURFACE	lpDDSSrc;
+    LPRECT		lprSrc;
+    DWORD		dwFlags;
+    LPDDBLTFX		lpDDBltFx;
+} DDBLTBATCH,*LPDDBLTBATCH;
+
+#define MAX_DDDEVICEID_STRING          512
+
+typedef struct tagDDDEVICEIDENTIFIER {
+  char    szDriver[MAX_DDDEVICEID_STRING];
+  char    szDescription[MAX_DDDEVICEID_STRING];
+  LARGE_INTEGER  liDriverVersion;
+  DWORD   dwVendorId;
+  DWORD   dwDeviceId;
+  DWORD   dwSubSysId;
+  DWORD   dwRevision;
+  GUID    guidDeviceIdentifier;
+} DDDEVICEIDENTIFIER, * LPDDDEVICEIDENTIFIER;
+
+typedef struct tagDDDEVICEIDENTIFIER2 {
+  char    szDriver[MAX_DDDEVICEID_STRING];	/* user readable driver name */
+  char    szDescription[MAX_DDDEVICEID_STRING]; /* user readable description */
+  LARGE_INTEGER  liDriverVersion;		/* driver version */
+  DWORD   dwVendorId;				/* vendor ID, zero if unknown */
+  DWORD   dwDeviceId;				/* chipset ID, zero if unknown */
+  DWORD   dwSubSysId;				/* board ID, zero if unknown */
+  DWORD   dwRevision;				/* chipset version, zero if unknown */
+  GUID    guidDeviceIdentifier;			/* unique ID for this driver/chipset combination */
+  DWORD   dwWHQLLevel;				/* Windows Hardware Quality Lab certification level */
+} DDDEVICEIDENTIFIER2, * LPDDDEVICEIDENTIFIER2;
+
+/*****************************************************************************
+ * IDirectDrawPalette interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawPalette
+DECLARE_INTERFACE_(IDirectDrawPalette,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE;
+    STDMETHOD(GetCaps)(THIS_ LPDWORD lpdwCaps) PURE;
+    STDMETHOD(GetEntries)(THIS_ DWORD dwFlags, DWORD dwBase, DWORD dwNumEntries, LPPALETTEENTRY lpEntries) PURE;
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, DWORD dwFlags, LPPALETTEENTRY lpDDColorTable) PURE;
+    STDMETHOD(SetEntries)(THIS_ DWORD dwFlags, DWORD dwStartingEntry, DWORD dwCount, LPPALETTEENTRY lpEntries) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawPalette_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawPalette_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawPalette_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDrawPalette methods ***/
+#define IDirectDrawPalette_GetCaps(p,a)          ICOM_CALL_(GetCaps,p,(p,a))
+#define IDirectDrawPalette_GetEntries(p,a,b,c,d) ICOM_CALL_(GetEntries,p,(p,a,b,c,d))
+#define IDirectDrawPalette_Initialize(p,a,b,c)   ICOM_CALL_(Initialize,p,(p,a,b,c))
+#define IDirectDrawPalette_SetEntries(p,a,b,c,d) ICOM_CALL_(SetEntries,p,(p,a,b,c,d))
+
+
+/*****************************************************************************
+ * IDirectDrawClipper interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawClipper
+DECLARE_INTERFACE_(IDirectDrawClipper,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE;
+    STDMETHOD(GetClipList)(THIS_ LPRECT lpRect, LPRGNDATA lpClipList, LPDWORD lpdwSize) PURE;
+    STDMETHOD(GetHWnd)(THIS_ HWND* lphWnd) PURE;
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, DWORD dwFlags) PURE;
+    STDMETHOD(IsClipListChanged)(THIS_ BOOL* lpbChanged) PURE;
+    STDMETHOD(SetClipList)(THIS_ LPRGNDATA lpClipList, DWORD dwFlags) PURE;
+    STDMETHOD(SetHWnd)(THIS_ DWORD dwFlags, HWND hWnd) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawClipper_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawClipper_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawClipper_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDrawClipper methods ***/
+#define IDirectDrawClipper_GetClipList(p,a,b,c)   ICOM_CALL_(GetClipList,p,(p,a,b,c))
+#define IDirectDrawClipper_GetHWnd(p,a)           ICOM_CALL_(GetHWnd,p,(p,a))
+#define IDirectDrawClipper_Initialize(p,a,b)      ICOM_CALL_(Initialize,p,(p,a,b))
+#define IDirectDrawClipper_IsClipListChanged(p,a) ICOM_CALL_(IsClipListChanged,p,(p,a))
+#define IDirectDrawClipper_SetClipList(p,a,b)     ICOM_CALL_(SetClipList,p,(p,a,b))
+#define IDirectDrawClipper_SetHWnd(p,a,b)         ICOM_CALL_(SetHWnd,p,(p,a,b))
+
+
+/*****************************************************************************
+ * IDirectDraw interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDraw
+DECLARE_INTERFACE_(IDirectDraw,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE;
+    STDMETHOD(Compact)(THIS) PURE;
+    STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE;
+    STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE;
+    STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc, LPDIRECTDRAWSURFACE* lplpDDSurface, IUnknown* pUnkOuter) PURE;
+    STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE lpDDSurface, LPDIRECTDRAWSURFACE* lplpDupDDSurface) PURE;
+    STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK lpEnumModesCallback) PURE;
+    STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE;
+    STDMETHOD(FlipToGDISurface)(THIS) PURE;
+    STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE;
+    STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE;
+    STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE;
+    STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE* lplpGDIDDSurface) PURE;
+    STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE;
+    STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE;
+    STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE;
+    STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE;
+    STDMETHOD(RestoreDisplayMode)(THIS) PURE;
+    STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE;
+    STDMETHOD(SetDisplayMode)(THIS_ DWORD, DWORD, DWORD) PURE;
+    STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDraw_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDraw_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDraw_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDraw methods ***/
+#define IDirectDraw_Compact(p)                  ICOM_CALL_(Compact,p,(p))
+#define IDirectDraw_CreateClipper(p,a,b,c)      ICOM_CALL_(CreateClipper,p,(p,a,b,c))
+#define IDirectDraw_CreatePalette(p,a,b,c,d)    ICOM_CALL_(CreatePalette,p,(p,a,b,c,d))
+#define IDirectDraw_CreateSurface(p,a,b,c)      ICOM_CALL_(CreateSurface,p,(p,a,b,c))
+#define IDirectDraw_DuplicateSurface(p,a,b)     ICOM_CALL_(DuplicateSurface,p,(p,a,b))
+#define IDirectDraw_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d))
+#define IDirectDraw_EnumSurfaces(p,a,b,c,d)     ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d))
+#define IDirectDraw_FlipToGDISurface(p)         ICOM_CALL_(FlipToGDISurface,p,(p))
+#define IDirectDraw_GetCaps(p,a,b)              ICOM_CALL_(GetCaps,p,(p,a,b))
+#define IDirectDraw_GetDisplayMode(p,a)         ICOM_CALL_(GetDisplayMode,p,(p,a))
+#define IDirectDraw_GetFourCCCodes(p,a,b)       ICOM_CALL_(GetFourCCCodes,p,(p,a,b))
+#define IDirectDraw_GetGDISurface(p,a)          ICOM_CALL_(GetGDISurface,p,(p,a))
+#define IDirectDraw_GetMonitorFrequency(p,a)    ICOM_CALL_(GetMonitorFrequency,p,(p,a))
+#define IDirectDraw_GetScanLine(p,a)            ICOM_CALL_(GetScanLine,p,(p,a))
+#define IDirectDraw_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a))
+#define IDirectDraw_Initialize(p,a)             ICOM_CALL_(Initialize,p,(p,a))
+#define IDirectDraw_RestoreDisplayMode(p)       ICOM_CALL_(RestoreDisplayMode,p,(p))
+#define IDirectDraw_SetCooperativeLevel(p,a,b)  ICOM_CALL_(SetCooperativeLevel,p,(p,a,b))
+#define IDirectDraw_SetDisplayMode(p,a,b,c)     ICOM_CALL_(SetDisplayMode,p,(p,a,b,c))
+#define IDirectDraw_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b))
+
+
+/* flags for Lock() */
+#define DDLOCK_SURFACEMEMORYPTR	0x00000000
+#define DDLOCK_WAIT		0x00000001
+#define DDLOCK_EVENT		0x00000002
+#define DDLOCK_READONLY		0x00000010
+#define DDLOCK_WRITEONLY	0x00000020
+#define DDLOCK_NOSYSLOCK	0x00000800
+
+
+/*****************************************************************************
+ * IDirectDraw2 interface
+ */
+/* Note: IDirectDraw2 cannot derive from IDirectDraw because the number of 
+ * arguments of SetDisplayMode has changed !
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDraw2
+DECLARE_INTERFACE_(IDirectDraw2,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE;
+    STDMETHOD(Compact)(THIS) PURE; 
+    STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc, LPDIRECTDRAWSURFACE2* lplpDDSurface, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE2 lpDDSurface, LPDIRECTDRAWSURFACE2* lplpDupDDSurface) PURE; 
+    STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK lpEnumModesCallback) PURE; 
+    STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(FlipToGDISurface)(THIS) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; 
+    STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; 
+    STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE2* lplpGDIDDSurface) PURE; 
+    STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; 
+    STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; 
+    STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; 
+    STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; 
+    STDMETHOD(RestoreDisplayMode)(THIS) PURE; 
+    STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; 
+    STDMETHOD(SetDisplayMode)(THIS_ DWORD dwWidth, DWORD dwHeight, DWORD dwBPP, DWORD dwRefreshRate, DWORD dwFlags) PURE; 
+    STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; 
+           
+    STDMETHOD(GetAvailableVidMem)(THIS_ LPDDSCAPS lpDDCaps, LPDWORD lpdwTotal, LPDWORD lpdwFree) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDraw2_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDraw2_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDraw2_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDraw methods ***/
+#define IDirectDraw2_Compact(p)                  ICOM_CALL_(Compact,p,(p))
+#define IDirectDraw2_CreateClipper(p,a,b,c)      ICOM_CALL_(CreateClipper,p,(p,a,b,c))
+#define IDirectDraw2_CreatePalette(p,a,b,c,d)    ICOM_CALL_(CreatePalette,p,(p,a,b,c,d))
+#define IDirectDraw2_CreateSurface(p,a,b,c)      ICOM_CALL_(CreateSurface,p,(p,a,b,c))
+#define IDirectDraw2_DuplicateSurface(p,a,b)     ICOM_CALL_(DuplicateSurface,p,(p,a,b))
+#define IDirectDraw2_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d))
+#define IDirectDraw2_EnumSurfaces(p,a,b,c,d)     ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d))
+#define IDirectDraw2_FlipToGDISurface(p)         ICOM_CALL_(FlipToGDISurface,p,(p))
+#define IDirectDraw2_GetCaps(p,a,b)              ICOM_CALL_(GetCaps,p,(p,a,b))
+#define IDirectDraw2_GetDisplayMode(p,a)         ICOM_CALL_(GetDisplayMode,p,(p,a))
+#define IDirectDraw2_GetFourCCCodes(p,a,b)       ICOM_CALL_(GetFourCCCodes,p,(p,a,b))
+#define IDirectDraw2_GetGDISurface(p,a)          ICOM_CALL_(GetGDISurface,p,(p,a))
+#define IDirectDraw2_GetMonitorFrequency(p,a)    ICOM_CALL_(GetMonitorFrequency,p,(p,a))
+#define IDirectDraw2_GetScanLine(p,a)            ICOM_CALL_(GetScanLine,p,(p,a))
+#define IDirectDraw2_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a))
+#define IDirectDraw2_Initialize(p,a)             ICOM_CALL_(Initialize,p,(p,a))
+#define IDirectDraw2_RestoreDisplayMode(p)       ICOM_CALL_(RestoreDisplayMode,p,(p))
+#define IDirectDraw2_SetCooperativeLevel(p,a,b)  ICOM_CALL_(SetCooperativeLevel,p,(p,a,b))
+#define IDirectDraw2_SetDisplayMode(p,a,b,c,d,e) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c,d,e))
+#define IDirectDraw2_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b))
+/*** IDirectDraw2 methods ***/
+#define IDirectDraw2_GetAvailableVidMem(p,a,b,c) ICOM_CALL_(GetAvailableVidMem,p,(p,a,b,c))
+
+
+/*****************************************************************************
+ * IDirectDraw4 interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDraw4
+DECLARE_INTERFACE_(IDirectDraw4,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE;
+    STDMETHOD(Compact)(THIS) PURE; 
+    STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc, LPDIRECTDRAWSURFACE4* lplpDDSurface, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE4 lpDDSurface, LPDIRECTDRAWSURFACE4* lplpDupDDSurface) PURE; 
+    STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK2 lpEnumModesCallback) PURE; 
+    STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK2 lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(FlipToGDISurface)(THIS) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; 
+    STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; 
+    STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; 
+    STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE4* lplpGDIDDSurface) PURE; 
+    STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; 
+    STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; 
+    STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; 
+    STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; 
+    STDMETHOD(RestoreDisplayMode)(THIS) PURE; 
+    STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; 
+    STDMETHOD(SetDisplayMode)(THIS_ DWORD dwWidth, DWORD dwHeight, DWORD dwBPP, DWORD dwRefreshRate, DWORD dwFlags) PURE; 
+    STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; 
+           
+    STDMETHOD(GetAvailableVidMem)(THIS_ LPDDSCAPS2 lpDDCaps, LPDWORD lpdwTotal, LPDWORD lpdwFree) PURE; 
+     
+    STDMETHOD(GetSurfaceFromDC)(THIS_ HDC , LPDIRECTDRAWSURFACE4* ) PURE; 
+    STDMETHOD(RestoreAllSurfaces)(THIS) PURE; 
+    STDMETHOD(TestCooperativeLevel)(THIS) PURE; 
+    STDMETHOD(GetDeviceIdentifier)(THIS_ LPDDDEVICEIDENTIFIER , DWORD ) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDraw4_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDraw4_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDraw4_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDraw methods ***/
+#define IDirectDraw4_Compact(p)                  ICOM_CALL_(Compact,p,(p))
+#define IDirectDraw4_CreateClipper(p,a,b,c)      ICOM_CALL_(CreateClipper,p,(p,a,b,c))
+#define IDirectDraw4_CreatePalette(p,a,b,c,d)    ICOM_CALL_(CreatePalette,p,(p,a,b,c,d))
+#define IDirectDraw4_CreateSurface(p,a,b,c)      ICOM_CALL_(CreateSurface,p,(p,a,b,c))
+#define IDirectDraw4_DuplicateSurface(p,a,b)     ICOM_CALL_(DuplicateSurface,p,(p,a,b))
+#define IDirectDraw4_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d))
+#define IDirectDraw4_EnumSurfaces(p,a,b,c,d)     ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d))
+#define IDirectDraw4_FlipToGDISurface(p)         ICOM_CALL_(FlipToGDISurface,p,(p))
+#define IDirectDraw4_GetCaps(p,a,b)              ICOM_CALL_(GetCaps,p,(p,a,b))
+#define IDirectDraw4_GetDisplayMode(p,a)         ICOM_CALL_(GetDisplayMode,p,(p,a))
+#define IDirectDraw4_GetFourCCCodes(p,a,b)       ICOM_CALL_(GetFourCCCodes,p,(p,a,b))
+#define IDirectDraw4_GetGDISurface(p,a)          ICOM_CALL_(GetGDISurface,p,(p,a))
+#define IDirectDraw4_GetMonitorFrequency(p,a)    ICOM_CALL_(GetMonitorFrequency,p,(p,a))
+#define IDirectDraw4_GetScanLine(p,a)            ICOM_CALL_(GetScanLine,p,(p,a))
+#define IDirectDraw4_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a))
+#define IDirectDraw4_Initialize(p,a)             ICOM_CALL_(Initialize,p,(p,a))
+#define IDirectDraw4_RestoreDisplayMode(p)       ICOM_CALL_(RestoreDisplayMode,p,(p))
+#define IDirectDraw4_SetCooperativeLevel(p,a,b)  ICOM_CALL_(SetCooperativeLevel,p,(p,a,b))
+#define IDirectDraw4_SetDisplayMode(p,a,b,c,d,e) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c,d,e))
+#define IDirectDraw4_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b))
+/*** IDirectDraw2 methods ***/
+#define IDirectDraw4_GetAvailableVidMem(p,a,b,c) ICOM_CALL_(GetAvailableVidMem,p,(p,a,b,c))
+/*** IDirectDraw4 methods ***/
+#define IDirectDraw4_GetSurfaceFromDC(p,a,b)    ICOM_CALL_(GetSurfaceFromDC,p,(p,a,b))
+#define IDirectDraw4_RestoreAllSurfaces(pc)     ICOM_CALL_(RestoreAllSurfaces,p,(p))
+#define IDirectDraw4_TestCooperativeLevel(p)    ICOM_CALL_(TestCooperativeLevel,p,(p))
+#define IDirectDraw4_GetDeviceIdentifier(p,a,b) ICOM_CALL_(GetDeviceIdentifier,p,(p,a,b))
+
+
+/*****************************************************************************
+ * IDirectDraw7 interface
+ */
+/* Note: IDirectDraw7 cannot derive from IDirectDraw4; it is even documented
+ * as not interchangeable with earlier DirectDraw interfaces.
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDraw7
+DECLARE_INTERFACE_(IDirectDraw7,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE;
+    STDMETHOD(Compact)(THIS) PURE; 
+    STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc, LPDIRECTDRAWSURFACE7* lplpDDSurface, IUnknown* pUnkOuter) PURE; 
+    STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE7 lpDDSurface, LPDIRECTDRAWSURFACE7* lplpDupDDSurface) PURE; 
+    STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK2 lpEnumModesCallback) PURE; 
+    STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK7 lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(FlipToGDISurface)(THIS) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; 
+    STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; 
+    STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; 
+    STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE7* lplpGDIDDSurface) PURE; 
+    STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; 
+    STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; 
+    STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; 
+    STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; 
+    STDMETHOD(RestoreDisplayMode)(THIS) PURE; 
+    STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; 
+    STDMETHOD(SetDisplayMode)(THIS_ DWORD dwWidth, DWORD dwHeight, DWORD dwBPP, DWORD dwRefreshRate, DWORD dwFlags) PURE; 
+    STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; 
+           
+    STDMETHOD(GetAvailableVidMem)(THIS_ LPDDSCAPS2 lpDDCaps, LPDWORD lpdwTotal, LPDWORD lpdwFree) PURE; 
+           
+    STDMETHOD(GetSurfaceFromDC)(THIS_ HDC , LPDIRECTDRAWSURFACE7* ) PURE; 
+    STDMETHOD(RestoreAllSurfaces)(THIS) PURE; 
+    STDMETHOD(TestCooperativeLevel)(THIS) PURE; 
+    STDMETHOD(GetDeviceIdentifier)(THIS_ LPDDDEVICEIDENTIFIER2 , DWORD ) PURE; 
+           
+    STDMETHOD(StartModeTest)(THIS_ LPSIZE , DWORD , DWORD ) PURE; 
+    STDMETHOD(EvaluateMode)(THIS_ DWORD , DWORD * ) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDraw7_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDraw7_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDraw7_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDraw methods ***/
+#define IDirectDraw7_Compact(p)                  ICOM_CALL_(Compact,p,(p))
+#define IDirectDraw7_CreateClipper(p,a,b,c)      ICOM_CALL_(CreateClipper,p,(p,a,b,c))
+#define IDirectDraw7_CreatePalette(p,a,b,c,d)    ICOM_CALL_(CreatePalette,p,(p,a,b,c,d))
+#define IDirectDraw7_CreateSurface(p,a,b,c)      ICOM_CALL_(CreateSurface,p,(p,a,b,c))
+#define IDirectDraw7_DuplicateSurface(p,a,b)     ICOM_CALL_(DuplicateSurface,p,(p,a,b))
+#define IDirectDraw7_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d))
+#define IDirectDraw7_EnumSurfaces(p,a,b,c,d)     ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d))
+#define IDirectDraw7_FlipToGDISurface(p)         ICOM_CALL_(FlipToGDISurface,p,(p))
+#define IDirectDraw7_GetCaps(p,a,b)              ICOM_CALL_(GetCaps,p,(p,a,b))
+#define IDirectDraw7_GetDisplayMode(p,a)         ICOM_CALL_(GetDisplayMode,p,(p,a))
+#define IDirectDraw7_GetFourCCCodes(p,a,b)       ICOM_CALL_(GetFourCCCodes,p,(p,a,b))
+#define IDirectDraw7_GetGDISurface(p,a)          ICOM_CALL_(GetGDISurface,p,(p,a))
+#define IDirectDraw7_GetMonitorFrequency(p,a)    ICOM_CALL_(GetMonitorFrequency,p,(p,a))
+#define IDirectDraw7_GetScanLine(p,a)            ICOM_CALL_(GetScanLine,p,(p,a))
+#define IDirectDraw7_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a))
+#define IDirectDraw7_Initialize(p,a)             ICOM_CALL_(Initialize,p,(p,a))
+#define IDirectDraw7_RestoreDisplayMode(p)       ICOM_CALL_(RestoreDisplayMode,p,(p))
+#define IDirectDraw7_SetCooperativeLevel(p,a,b)  ICOM_CALL_(SetCooperativeLevel,p,(p,a,b))
+#define IDirectDraw7_SetDisplayMode(p,a,b,c,d,e) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c,d,e))
+#define IDirectDraw7_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b))
+/*** added in IDirectDraw2 ***/
+#define IDirectDraw7_GetAvailableVidMem(p,a,b,c) ICOM_CALL_(GetAvailableVidMem,p,(p,a,b,c))
+/*** added in IDirectDraw4 ***/
+#define IDirectDraw7_GetSurfaceFromDC(p,a,b)    ICOM_CALL_(GetSurfaceFromDC,p,(p,a,b))
+#define IDirectDraw7_RestoreAllSurfaces(p)     ICOM_CALL_(RestoreAllSurfaces,p,(p))
+#define IDirectDraw7_TestCooperativeLevel(p)    ICOM_CALL_(TestCooperativeLevel,p,(p))
+#define IDirectDraw7_GetDeviceIdentifier(p,a,b) ICOM_CALL_(GetDeviceIdentifier,p,(p,a,b))
+/*** added in IDirectDraw 7 ***/
+#define IDirectDraw7_StartModeTest(p,a,b,c)     ICOM_CALL_(StartModeTest,p,(p,a,b,c))
+#define IDirectDraw7_EvaluateMode(p,a,b)        ICOM_CALL_(EvaluateMode,p,(p,a,b))
+
+
+/*****************************************************************************
+ * IDirectDrawSurface interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawSurface
+DECLARE_INTERFACE_(IDirectDrawSurface,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE lpDDSAttachedSurface) PURE; 
+    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
+    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
+    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
+    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
+    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE lpDDSAttachedSurface) PURE; 
+    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; 
+    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
+    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS lpDDSCaps, LPDIRECTDRAWSURFACE* lplpDDAttachedSurface) PURE; 
+    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS lpDDSCaps) PURE; 
+    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
+    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
+    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
+    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
+    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
+    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(IsLost)(THIS) PURE; 
+    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
+    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
+    STDMETHOD(Restore)(THIS) PURE; 
+    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
+    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
+    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
+    STDMETHOD(Unlock)(THIS_ LPVOID lpSurfaceData) PURE; 
+    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
+    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE lpDDSReference) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawSurface_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawSurface_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawSurface_Release(p)            ICOM_CALL_(Release,p,(p))
+    /*** IDirectDrawSurface methods ***/
+#define IDirectDrawSurface_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
+#define IDirectDrawSurface_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
+#define IDirectDrawSurface_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
+#define IDirectDrawSurface_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
+#define IDirectDrawSurface_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
+#define IDirectDrawSurface_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
+#define IDirectDrawSurface_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
+#define IDirectDrawSurface_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
+#define IDirectDrawSurface_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
+#define IDirectDrawSurface_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
+#define IDirectDrawSurface_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
+#define IDirectDrawSurface_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
+#define IDirectDrawSurface_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
+#define IDirectDrawSurface_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
+#define IDirectDrawSurface_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
+#define IDirectDrawSurface_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
+#define IDirectDrawSurface_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
+#define IDirectDrawSurface_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
+#define IDirectDrawSurface_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
+#define IDirectDrawSurface_Restore(p)                   ICOM_CALL_(Restore,p,(p))
+#define IDirectDrawSurface_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
+#define IDirectDrawSurface_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
+#define IDirectDrawSurface_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
+#define IDirectDrawSurface_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
+#define IDirectDrawSurface_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
+#define IDirectDrawSurface_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
+
+
+/*****************************************************************************
+ * IDirectDrawSurface2 interface
+ */
+/* Cannot inherit from IDirectDrawSurface because the LPDIRECTDRAWSURFACE parameters 
+ * have been converted to LPDIRECTDRAWSURFACE2.
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawSurface2
+DECLARE_INTERFACE_(IDirectDrawSurface2,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE2 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
+    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE2 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
+    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
+    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE2 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
+    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE2 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; 
+    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE2 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
+    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS lpDDSCaps, LPDIRECTDRAWSURFACE2* lplpDDAttachedSurface) PURE; 
+    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS lpDDSCaps) PURE; 
+    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
+    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
+    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
+    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
+    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
+    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(IsLost)(THIS) PURE; 
+    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
+    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
+    STDMETHOD(Restore)(THIS) PURE; 
+    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
+    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
+    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
+    STDMETHOD(Unlock)(THIS_ LPVOID lpSurfaceData) PURE; 
+    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE2 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
+    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE2 lpDDSReference) PURE; 
+    /* added in v2 */ 
+    STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; 
+    STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawSurface2_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawSurface2_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawSurface2_Release(p)            ICOM_CALL_(Release,p,(p))
+/*** IDirectDrawSurface methods (almost) ***/
+#define IDirectDrawSurface2_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
+#define IDirectDrawSurface2_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
+#define IDirectDrawSurface2_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface2_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
+#define IDirectDrawSurface2_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface2_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface2_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
+#define IDirectDrawSurface2_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
+#define IDirectDrawSurface2_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
+#define IDirectDrawSurface2_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface2_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
+#define IDirectDrawSurface2_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
+#define IDirectDrawSurface2_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
+#define IDirectDrawSurface2_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
+#define IDirectDrawSurface2_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
+#define IDirectDrawSurface2_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
+#define IDirectDrawSurface2_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface2_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
+#define IDirectDrawSurface2_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
+#define IDirectDrawSurface2_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
+#define IDirectDrawSurface2_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
+#define IDirectDrawSurface2_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
+#define IDirectDrawSurface2_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
+#define IDirectDrawSurface2_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
+#define IDirectDrawSurface2_Restore(p)                   ICOM_CALL_(Restore,p,(p))
+#define IDirectDrawSurface2_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
+#define IDirectDrawSurface2_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
+#define IDirectDrawSurface2_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface2_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
+#define IDirectDrawSurface2_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
+#define IDirectDrawSurface2_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface2_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
+#define IDirectDrawSurface2_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
+/*** IDirectDrawSurface2 methods ***/
+#define IDirectDrawSurface2_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a))
+#define IDirectDrawSurface2_PageLock(p,a)       ICOM_CALL_(PageLock,p,(p,a))
+#define IDirectDrawSurface2_PageUnlock(p,a)     ICOM_CALL_(PageUnlock,p,(p,a))
+
+
+/*****************************************************************************
+ * IDirectDrawSurface3 interface
+ */
+/* Cannot inherit from IDirectDrawSurface2 because the LPDIRECTDRAWSURFACE2 parameters 
+ * have been converted to LPDIRECTDRAWSURFACE3.
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawSurface3
+DECLARE_INTERFACE_(IDirectDrawSurface3,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE3 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
+    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE3 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
+    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
+    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE3 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
+    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE3 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; 
+    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE3 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
+    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS lpDDSCaps, LPDIRECTDRAWSURFACE3* lplpDDAttachedSurface) PURE; 
+    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS lpDDSCaps) PURE; 
+    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
+    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
+    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
+    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
+    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
+    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(IsLost)(THIS) PURE; 
+    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
+    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
+    STDMETHOD(Restore)(THIS) PURE; 
+    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
+    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
+    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
+    STDMETHOD(Unlock)(THIS_ LPVOID lpSurfaceData) PURE; 
+    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE3 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
+    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE3 lpDDSReference) PURE; 
+    /* added in v2 */ 
+    STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; 
+    STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; 
+    /* added in v3 */ 
+    STDMETHOD(SetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSD, DWORD dwFlags) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawSurface3_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawSurface3_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawSurface3_Release(p)            ICOM_CALL_(Release,p,(p))
+/*** IDirectDrawSurface methods (almost) ***/
+#define IDirectDrawSurface3_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
+#define IDirectDrawSurface3_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
+#define IDirectDrawSurface3_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface3_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
+#define IDirectDrawSurface3_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface3_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface3_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
+#define IDirectDrawSurface3_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
+#define IDirectDrawSurface3_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
+#define IDirectDrawSurface3_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface3_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
+#define IDirectDrawSurface3_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
+#define IDirectDrawSurface3_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
+#define IDirectDrawSurface3_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
+#define IDirectDrawSurface3_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
+#define IDirectDrawSurface3_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
+#define IDirectDrawSurface3_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface3_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
+#define IDirectDrawSurface3_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
+#define IDirectDrawSurface3_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
+#define IDirectDrawSurface3_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
+#define IDirectDrawSurface3_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
+#define IDirectDrawSurface3_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
+#define IDirectDrawSurface3_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
+#define IDirectDrawSurface3_Restore(p)                   ICOM_CALL_(Restore,p,(p))
+#define IDirectDrawSurface3_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
+#define IDirectDrawSurface3_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
+#define IDirectDrawSurface3_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface3_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
+#define IDirectDrawSurface3_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
+#define IDirectDrawSurface3_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface3_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
+#define IDirectDrawSurface3_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
+/*** IDirectDrawSurface2 methods ***/
+#define IDirectDrawSurface3_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a))
+#define IDirectDrawSurface3_PageLock(p,a)       ICOM_CALL_(PageLock,p,(p,a))
+#define IDirectDrawSurface3_PageUnlock(p,a)     ICOM_CALL_(PageUnlock,p,(p,a))
+/*** IDirectDrawSurface3 methods ***/
+#define IDirectDrawSurface3_SetSurfaceDesc(p,a,b) ICOM_CALL_(SetSurfaceDesc,p,(p,a,b))
+
+
+/*****************************************************************************
+ * IDirectDrawSurface4 interface
+ */
+/* Cannot inherit from IDirectDrawSurface2 because DDSCAPS changed to DDSCAPS2.
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawSurface4
+DECLARE_INTERFACE_(IDirectDrawSurface4,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE4 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
+    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE4 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
+    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
+    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE4 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
+    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE4 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; 
+    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE4 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
+    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS2 lpDDSCaps, LPDIRECTDRAWSURFACE4* lplpDDAttachedSurface) PURE; 
+    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS2 lpDDSCaps) PURE; 
+    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
+    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
+    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
+    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
+    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
+    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
+    STDMETHOD(IsLost)(THIS) PURE; 
+    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
+    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
+    STDMETHOD(Restore)(THIS) PURE; 
+    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
+    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
+    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
+    STDMETHOD(Unlock)(THIS_ LPRECT lpSurfaceData) PURE; 
+    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE4 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
+    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE4 lpDDSReference) PURE; 
+    /* added in v2 */ 
+    STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; 
+    STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; 
+    /* added in v3 */ 
+    STDMETHOD(SetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSD, DWORD dwFlags) PURE; 
+    /* added in v4 */ 
+    STDMETHOD(SetPrivateData)(THIS_ REFGUID , LPVOID , DWORD , DWORD ) PURE; 
+    STDMETHOD(GetPrivateData)(THIS_ REFGUID , LPVOID , LPDWORD ) PURE; 
+    STDMETHOD(FreePrivateData)(THIS_ REFGUID ) PURE; 
+    STDMETHOD(GetUniquenessValue)(THIS_ LPDWORD ) PURE; 
+    STDMETHOD(ChangeUniquenessValue)(THIS) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawSurface4_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawSurface4_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawSurface4_Release(p)            ICOM_CALL_(Release,p,(p))
+/*** IDirectDrawSurface (almost) methods ***/
+#define IDirectDrawSurface4_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
+#define IDirectDrawSurface4_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
+#define IDirectDrawSurface4_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface4_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
+#define IDirectDrawSurface4_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface4_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface4_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
+#define IDirectDrawSurface4_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
+#define IDirectDrawSurface4_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
+#define IDirectDrawSurface4_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface4_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
+#define IDirectDrawSurface4_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
+#define IDirectDrawSurface4_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
+#define IDirectDrawSurface4_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
+#define IDirectDrawSurface4_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
+#define IDirectDrawSurface4_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
+#define IDirectDrawSurface4_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface4_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
+#define IDirectDrawSurface4_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
+#define IDirectDrawSurface4_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
+#define IDirectDrawSurface4_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
+#define IDirectDrawSurface4_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
+#define IDirectDrawSurface4_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
+#define IDirectDrawSurface4_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
+#define IDirectDrawSurface4_Restore(p)                   ICOM_CALL_(Restore,p,(p))
+#define IDirectDrawSurface4_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
+#define IDirectDrawSurface4_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
+#define IDirectDrawSurface4_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface4_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
+#define IDirectDrawSurface4_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
+#define IDirectDrawSurface4_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface4_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
+#define IDirectDrawSurface4_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
+/*** IDirectDrawSurface2 methods ***/
+#define IDirectDrawSurface4_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a))
+#define IDirectDrawSurface4_PageLock(p,a)       ICOM_CALL_(PageLock,p,(p,a))
+#define IDirectDrawSurface4_PageUnlock(p,a)     ICOM_CALL_(PageUnlock,p,(p,a))
+/*** IDirectDrawSurface3 methods ***/
+#define IDirectDrawSurface4_SetSurfaceDesc(p,a,b) ICOM_CALL_(SetSurfaceDesc,p,(p,a,b))
+/*** IDirectDrawSurface4 methods ***/
+#define IDirectDrawSurface4_SetPrivateData(p,a,b,c,d) ICOM_CALL_(SetPrivateData,p,(p,a,b,c,d))
+#define IDirectDrawSurface4_GetPrivateData(p,a,b,c)   ICOM_CALL_(GetPrivateData,p,(p,a,b,c))
+#define IDirectDrawSurface4_FreePrivateData(p,a)      ICOM_CALL_(FreePrivateData,p,(p,a))
+#define IDirectDrawSurface4_GetUniquenessValue(p,a)   ICOM_CALL_(GetUniquenessValue,p,(p,a))
+#define IDirectDrawSurface4_ChangeUniquenessValue(p)  ICOM_CALL_(ChangeUniquenessValue,p,(p))
+
+
+/*****************************************************************************
+ * IDirectDrawSurface7 interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawSurface7
+DECLARE_INTERFACE_(IDirectDrawSurface7,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE7 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
+    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE7 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
+    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
+    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE7 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
+    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE7 lpDDSAttachedSurface) PURE; 
+    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK7 lpEnumSurfacesCallback) PURE; 
+    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK7 lpfnCallback) PURE; 
+    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE7 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
+    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS2 lpDDSCaps, LPDIRECTDRAWSURFACE7* lplpDDAttachedSurface) PURE; 
+    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS2 lpDDSCaps) PURE; 
+    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
+    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
+    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
+    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
+    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
+    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; 
+    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; 
+    STDMETHOD(IsLost)(THIS) PURE; 
+    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC2 lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
+    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
+    STDMETHOD(Restore)(THIS) PURE; 
+    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
+    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
+    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
+    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
+    STDMETHOD(Unlock)(THIS_ LPRECT lpSurfaceData) PURE; 
+    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE7 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
+    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE7 lpDDSReference) PURE; 
+    /* added in v2 */ 
+    STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; 
+    STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; 
+    STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; 
+    /* added in v3 */ 
+    STDMETHOD(SetSurfaceDesc)(THIS_ LPDDSURFACEDESC2 lpDDSD, DWORD dwFlags) PURE; 
+    /* added in v4 */ 
+    STDMETHOD(SetPrivateData)(THIS_ REFGUID , LPVOID , DWORD , DWORD ) PURE; 
+    STDMETHOD(GetPrivateData)(THIS_ REFGUID , LPVOID , LPDWORD ) PURE; 
+    STDMETHOD(FreePrivateData)(THIS_ REFGUID ) PURE; 
+    STDMETHOD(GetUniquenessValue)(THIS_ LPDWORD ) PURE; 
+    STDMETHOD(ChangeUniquenessValue)(THIS) PURE; 
+    /* added in v7 */ 
+    STDMETHOD(SetPriority)(THIS_ DWORD prio) PURE; 
+    STDMETHOD(GetPriority)(THIS_ LPDWORD prio) PURE; 
+    STDMETHOD(SetLOD)(THIS_ DWORD lod) PURE; 
+    STDMETHOD(GetLOD)(THIS_ LPDWORD lod) PURE;
+};
+
+    /*** IUnknown methods ***/
+#define IDirectDrawSurface7_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawSurface7_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawSurface7_Release(p)            ICOM_CALL_(Release,p,(p))
+/*** IDirectDrawSurface (almost) methods ***/
+#define IDirectDrawSurface7_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
+#define IDirectDrawSurface7_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
+#define IDirectDrawSurface7_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface7_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
+#define IDirectDrawSurface7_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface7_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface7_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
+#define IDirectDrawSurface7_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
+#define IDirectDrawSurface7_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
+#define IDirectDrawSurface7_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
+#define IDirectDrawSurface7_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
+#define IDirectDrawSurface7_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
+#define IDirectDrawSurface7_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
+#define IDirectDrawSurface7_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
+#define IDirectDrawSurface7_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
+#define IDirectDrawSurface7_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
+#define IDirectDrawSurface7_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface7_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
+#define IDirectDrawSurface7_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
+#define IDirectDrawSurface7_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
+#define IDirectDrawSurface7_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
+#define IDirectDrawSurface7_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
+#define IDirectDrawSurface7_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
+#define IDirectDrawSurface7_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
+#define IDirectDrawSurface7_Restore(p)                   ICOM_CALL_(Restore,p,(p))
+#define IDirectDrawSurface7_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
+#define IDirectDrawSurface7_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
+#define IDirectDrawSurface7_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
+#define IDirectDrawSurface7_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
+#define IDirectDrawSurface7_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
+#define IDirectDrawSurface7_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
+#define IDirectDrawSurface7_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
+#define IDirectDrawSurface7_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
+/*** IDirectDrawSurface2 methods ***/
+#define IDirectDrawSurface7_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a))
+#define IDirectDrawSurface7_PageLock(p,a)       ICOM_CALL_(PageLock,p,(p,a))
+#define IDirectDrawSurface7_PageUnlock(p,a)     ICOM_CALL_(PageUnlock,p,(p,a))
+/*** IDirectDrawSurface3 methods ***/
+#define IDirectDrawSurface7_SetSurfaceDesc(p,a,b) ICOM_CALL_(SetSurfaceDesc,p,(p,a,b))
+/*** IDirectDrawSurface4 methods ***/
+#define IDirectDrawSurface7_SetPrivateData(p,a,b,c,d) ICOM_CALL_(SetPrivateData,p,(p,a,b,c,d))
+#define IDirectDrawSurface7_GetPrivateData(p,a,b,c)   ICOM_CALL_(GetPrivateData,p,(p,a,b,c))
+#define IDirectDrawSurface7_FreePrivateData(p,a)      ICOM_CALL_(FreePrivateData,p,(p,a))
+#define IDirectDrawSurface7_GetUniquenessValue(p,a)   ICOM_CALL_(GetUniquenessValue,p,(p,a))
+#define IDirectDrawSurface7_ChangeUniquenessValue(p)  ICOM_CALL_(ChangeUniquenessValue,p,(p))
+/*** IDirectDrawSurface7 methods ***/
+#define IDirectDrawSurface7_SetPriority(p,a)          ICOM_CALL_(SetPriority,p,(p,a))
+#define IDirectDrawSurface7_GetPriority(p,a)          ICOM_CALL_(GetPriority,p,(p,a))
+#define IDirectDrawSurface7_SetLOD(p,a)               ICOM_CALL_(SetLOD,p,(p,a))
+#define IDirectDrawSurface7_GetLOD(p,a)               ICOM_CALL_(GetLOD,p,(p,a))
+
+/*****************************************************************************
+ * IDirectDrawColorControl interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawColorControl
+DECLARE_INTERFACE_(IDirectDrawColorControl,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(GetColorControls)(THIS_ LPDDCOLORCONTROL lpColorControl) PURE; 
+    STDMETHOD(SetColorControls)(THIS_ LPDDCOLORCONTROL lpColorControl) PURE;
+};
+
+	/*** IUnknown methods ***/
+#define IDirectDrawColorControl_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawColorControl_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawColorControl_Release(p)            ICOM_CALL_(Release,p,(p))
+	/*** IDirectDrawColorControl methods ***/
+#define IDirectDrawColorControl_GetColorControls(p,a) ICOM_CALL_(GetColorControls,p,(p,a))
+#define IDirectDrawColorControl_SetColorControls(p,a) ICOM_CALL_(SetColorControls,p,(p,a))
+
+/*****************************************************************************
+ * IDirectDrawGammaControl interface
+ */
+#undef INTERFACE
+#define INTERFACE IDirectDrawGammaControl
+DECLARE_INTERFACE_(IDirectDrawGammaControl,IUnknown)
+{
+    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
+    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
+    STDMETHOD_(ULONG,Release)(THIS) PURE; 
+    STDMETHOD(GetGammaRamp)(THIS_ DWORD dwFlags, LPDDGAMMARAMP lpGammaRamp) PURE; 
+    STDMETHOD(SetGammaRamp)(THIS_ DWORD dwFlags, LPDDGAMMARAMP lpGammaRamp) PURE;
+};
+
+	/*** IUnknown methods ***/
+#define IDirectDrawGammaControl_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
+#define IDirectDrawGammaControl_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
+#define IDirectDrawGammaControl_Release(p)            ICOM_CALL_(Release,p,(p))
+	/*** IDirectDrawGammaControl methods ***/
+#define IDirectDrawGammaControl_GetGammaRamp(p,a,b)   ICOM_CALL_(GetGammaRamp,p,(p,a,b))
+#define IDirectDrawGammaControl_SetGammaRamp(p,a,b)   ICOM_CALL_(SetGammaRamp,p,(p,a,b))
+
+
+HRESULT WINAPI DirectDrawCreate(LPGUID,LPDIRECTDRAW*,LPUNKNOWN);
+HRESULT WINAPI DirectDrawCreateEx(LPGUID,LPVOID*,REFIID,LPUNKNOWN);
+HRESULT WINAPI DirectDrawEnumerateA(LPDDENUMCALLBACKA,LPVOID);
+HRESULT WINAPI DirectDrawEnumerateW(LPDDENUMCALLBACKW,LPVOID);
+#define DirectDrawEnumerate WINELIB_NAME_AW(DirectDrawEnumerate)
+HRESULT WINAPI DirectDrawCreateClipper(DWORD,LPDIRECTDRAWCLIPPER*,LPUNKNOWN);
+
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* defined(__cplusplus) */
+
+#endif /* __XWIN_DDRAW_H */
diff --git a/hw/xwin/win.h b/hw/xwin/win.h
new file mode 100644
index 0000000..3ab3249
--- /dev/null
+++ b/hw/xwin/win.h
@@ -0,0 +1,1453 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ *		Kensuke Matsuzaki
+ */
+
+#ifndef _WIN_H_
+#define _WIN_H_
+
+#ifndef NO
+#define NO					0
+#endif
+#ifndef YES
+#define YES					1
+#endif
+
+/* Turn debug messages on or off */
+#ifndef CYGDEBUG
+#define CYGDEBUG				NO
+#endif
+
+/* WM_XBUTTON Messages. They should go into w32api. */
+#ifndef WM_XBUTTONDOWN
+# define WM_XBUTTONDOWN 523
+#endif
+#ifndef WM_XBUTTONUP
+# define WM_XBUTTONUP 524
+#endif
+#ifndef WM_XBUTTONDBLCLK
+# define WM_XBUTTONDBLCLK 525
+#endif
+
+#define NEED_EVENTS
+
+#define WIN_DEFAULT_BPP				0
+#define WIN_DEFAULT_WHITEPIXEL			255
+#define WIN_DEFAULT_BLACKPIXEL			0
+#define WIN_DEFAULT_LINEBIAS			0
+#define WIN_DEFAULT_E3B_TIME			50 /* milliseconds */
+#define WIN_DEFAULT_DPI				75
+#define WIN_DEFAULT_REFRESH			0
+#define WIN_DEFAULT_WIN_KILL			TRUE
+#define WIN_DEFAULT_UNIX_KILL			FALSE
+#define WIN_DEFAULT_CLIP_UPDATES_NBOXES		0
+#ifdef XWIN_EMULATEPSEUDO
+#define WIN_DEFAULT_EMULATE_PSEUDO		FALSE
+#endif
+#define WIN_DEFAULT_USER_GAVE_HEIGHT_AND_WIDTH	FALSE
+
+#define WIN_DIB_MAXIMUM_SIZE	0x08000000 /* 16 MB on Windows 95, 98, Me */
+#define WIN_DIB_MAXIMUM_SIZE_MB (WIN_DIB_MAXIMUM_SIZE / 8 / 1024 / 1024)
+
+/*
+ * Windows only supports 256 color palettes
+ */
+#define WIN_NUM_PALETTE_ENTRIES			256
+
+/*
+ * Number of times to call Restore in an attempt to restore the primary surface
+ */
+#define WIN_REGAIN_SURFACE_RETRIES		1
+
+/*
+ * Build a supported display depths mask by shifting one to the left
+ * by the number of bits in the supported depth.
+ */
+#define WIN_SUPPORTED_BPPS	( (1 << (32 - 1)) | (1 << (24 - 1)) \
+				| (1 << (16 - 1)) | (1 << (15 - 1)) \
+				| (1 << ( 8 - 1)))
+#define WIN_CHECK_DEPTH		YES
+
+/*
+ * Timer IDs for WM_TIMER
+ */
+#define WIN_E3B_TIMER_ID		1
+#define WIN_POLLING_MOUSE_TIMER_ID	2
+
+
+#define WIN_E3B_OFF		-1
+#define WIN_FD_INVALID		-1
+
+#define WIN_SERVER_NONE		0x0L	/* 0 */
+#define WIN_SERVER_SHADOW_GDI	0x1L	/* 1 */
+#define WIN_SERVER_SHADOW_DD	0x2L	/* 2 */
+#define WIN_SERVER_SHADOW_DDNL	0x4L	/* 4 */
+#ifdef XWIN_PRIMARYFB
+#define WIN_SERVER_PRIMARY_DD	0x8L	/* 8 */
+#endif
+#ifdef XWIN_NATIVEGDI
+# define WIN_SERVER_NATIVE_GDI	0x10L	/* 16 */
+#endif
+
+#define AltMapIndex		Mod1MapIndex
+#define NumLockMapIndex		Mod2MapIndex
+#define AltLangMapIndex		Mod3MapIndex
+#define KanaMapIndex		Mod4MapIndex
+#define ScrollLockMapIndex	Mod5MapIndex
+
+#define WIN_MOD_LALT		0x00000001
+#define WIN_MOD_RALT		0x00000002
+#define WIN_MOD_LCONTROL	0x00000004
+#define WIN_MOD_RCONTROL	0x00000008
+
+#define WIN_24BPP_MASK_RED	0x00FF0000
+#define WIN_24BPP_MASK_GREEN	0x0000FF00
+#define WIN_24BPP_MASK_BLUE	0x000000FF
+
+#define WIN_MAX_KEYS_PER_KEY	4
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdio.h>
+
+#include <errno.h>
+#if defined(XWIN_MULTIWINDOWEXTWM) || defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+#define HANDLE void *
+#include <pthread.h>
+#undef HANDLE
+#endif
+
+#ifdef HAS_MMAP
+#include <sys/mman.h>
+#ifndef MAP_FILE
+#define MAP_FILE 0
+#endif /* MAP_FILE */
+#endif /* HAS_MMAP */
+
+#include <X11/X.h>
+#include <X11/Xproto.h>
+#include <X11/Xos.h>
+#include <X11/Xprotostr.h>
+#include "scrnintstr.h"
+#include "pixmapstr.h"
+#include "pixmap.h"
+#include "region.h"
+#include "gcstruct.h"
+#include "colormap.h"
+#include "colormapst.h"
+#include "miscstruct.h"
+#include "servermd.h"
+#include "windowstr.h"
+#include "mi.h"
+#include "micmap.h"
+#include "mifillarc.h"
+#include "mifpoly.h"
+#include "mibstore.h"
+#include "input.h"
+#include "mipointer.h"
+#include "X11/keysym.h"
+#include "mibstore.h"
+#include "micoord.h"
+#include "dix.h"
+#include "miline.h"
+#include "shadow.h"
+#include "fb.h"
+#include "rootless.h"
+
+#ifdef RENDER
+#include "mipict.h"
+#include "picturestr.h"
+#endif
+
+#ifdef RANDR
+#include "randrstr.h"
+#endif
+
+/*
+ * Windows headers
+ */
+#include "winms.h"
+#include "./winresource.h"
+
+
+/*
+ * Define Windows constants
+ */
+
+#define WM_TRAYICON		(WM_USER + 1000)
+#define WM_INIT_SYS_MENU	(WM_USER + 1001)
+#define WM_GIVEUP		(WM_USER + 1002)
+
+
+/* Local includes */
+#include "winwindow.h"
+#include "winmsg.h"
+
+
+/*
+ * Debugging macros
+ */
+
+#if CYGDEBUG
+#define DEBUG_MSG(str,...) \
+if (fDebugProcMsg) \
+{ \
+  char *pszTemp; \
+  int iLength; \
+  pszTemp = Xprintf (str, ##__VA_ARGS__); \
+  MessageBox (NULL, pszTemp, szFunctionName, MB_OK); \
+  xfree (pszTemp); \
+}
+#else
+#define DEBUG_MSG(str,...)
+#endif
+
+#if CYGDEBUG
+#define DEBUG_FN_NAME(str) PTSTR szFunctionName = str
+#else
+#define DEBUG_FN_NAME(str)
+#endif
+
+#if CYGDEBUG || YES
+#define DEBUGVARS BOOL fDebugProcMsg = FALSE
+#else
+#define DEBUGVARS
+#endif
+
+#if CYGDEBUG || YES
+#define DEBUGPROC_MSG fDebugProcMsg = TRUE
+#else
+#define DEBUGPROC_MSG
+#endif
+
+#define PROFILEPOINT(point,thresh)\
+{\
+static unsigned int PROFPT##point = 0;\
+if (++PROFPT##point % thresh == 0)\
+ErrorF (#point ": PROFILEPOINT hit %u times\n", PROFPT##point);\
+}
+
+
+/* We use xor this macro for detecting toggle key state changes */
+#define WIN_XOR(a,b) ((!(a) && (b)) || ((a) && !(b)))
+
+#define DEFINE_ATOM_HELPER(func,atom_name)			\
+static Atom func (void) {					\
+    static int generation;					\
+    static Atom atom;						\
+    if (generation != serverGeneration) {			\
+	generation = serverGeneration;				\
+	atom = MakeAtom (atom_name, strlen (atom_name), TRUE);	\
+    }								\
+    return atom;						\
+}
+
+/*
+ * Typedefs for engine dependent function pointers
+ */
+
+typedef Bool (*winAllocateFBProcPtr)(ScreenPtr);
+
+typedef void (*winShadowUpdateProcPtr)(ScreenPtr, shadowBufPtr);
+
+typedef Bool (*winCloseScreenProcPtr)(int, ScreenPtr);
+
+typedef Bool (*winInitVisualsProcPtr)(ScreenPtr);
+
+typedef Bool (*winAdjustVideoModeProcPtr)(ScreenPtr);
+
+typedef Bool (*winCreateBoundingWindowProcPtr)(ScreenPtr);
+
+typedef Bool (*winFinishScreenInitProcPtr)(int, ScreenPtr, int, char **);
+
+typedef Bool (*winBltExposedRegionsProcPtr)(ScreenPtr);
+
+typedef Bool (*winActivateAppProcPtr)(ScreenPtr);
+
+typedef Bool (*winRedrawScreenProcPtr)(ScreenPtr pScreen);
+
+typedef Bool (*winRealizeInstalledPaletteProcPtr)(ScreenPtr pScreen);
+
+typedef Bool (*winInstallColormapProcPtr)(ColormapPtr pColormap);
+
+typedef Bool (*winStoreColorsProcPtr)(ColormapPtr pmap, 
+				      int ndef, xColorItem *pdefs);
+
+typedef Bool (*winCreateColormapProcPtr)(ColormapPtr pColormap);
+
+typedef Bool (*winDestroyColormapProcPtr)(ColormapPtr pColormap);
+
+typedef Bool (*winHotKeyAltTabProcPtr)(ScreenPtr);
+
+typedef Bool (*winCreatePrimarySurfaceProcPtr)(ScreenPtr);
+
+typedef Bool (*winReleasePrimarySurfaceProcPtr)(ScreenPtr);
+
+typedef Bool (*winFinishCreateWindowsWindowProcPtr)(WindowPtr pWin);
+
+
+/* Typedef for DIX wrapper functions */
+typedef int (*winDispatchProcPtr) (ClientPtr);
+
+
+/*
+ * GC (graphics context) privates
+ */
+
+typedef struct
+{
+  HDC			hdc;
+  HDC			hdcMem;
+} winPrivGCRec, *winPrivGCPtr;
+
+
+/*
+ * Pixmap privates
+ */
+
+typedef struct
+{
+  HDC			hdcSelected;
+  HBITMAP		hBitmap;
+  BYTE			*pbBits;
+  DWORD			dwScanlineBytes;
+  BITMAPINFOHEADER	*pbmih;
+} winPrivPixmapRec, *winPrivPixmapPtr;
+
+
+/*
+ * Colormap privates
+ */
+
+typedef struct
+{
+  HPALETTE		hPalette;
+  LPDIRECTDRAWPALETTE	lpDDPalette;
+  RGBQUAD		rgbColors[WIN_NUM_PALETTE_ENTRIES];
+  PALETTEENTRY		peColors[WIN_NUM_PALETTE_ENTRIES];
+} winPrivCmapRec, *winPrivCmapPtr;
+
+/*
+ * Windows Cursor handling.
+ */ 
+  
+typedef struct {
+  /* from GetSystemMetrics */
+  int sm_cx;
+  int sm_cy;
+
+  BOOL visible;
+  HCURSOR handle;
+  QueryBestSizeProcPtr QueryBestSize;
+  miPointerSpriteFuncPtr spriteFuncs;
+} winCursorRec;
+
+/*
+ * Screen information structure that we need before privates are available
+ * in the server startup sequence.
+ */
+
+typedef struct
+{
+  ScreenPtr		pScreen;
+  
+  /* Did the user specify a height and width? */
+  Bool			fUserGaveHeightAndWidth;
+
+  DWORD			dwScreen;
+  DWORD			dwUserWidth;
+  DWORD			dwUserHeight;
+  DWORD			dwWidth;
+  DWORD			dwHeight;
+  DWORD			dwWidth_mm;
+  DWORD			dwHeight_mm;
+  DWORD			dwPaddedWidth;
+
+  /* Did the user specify a screen position? */
+  Bool			fUserGavePosition;
+  DWORD                 dwInitialX;
+  DWORD                 dwInitialY;
+
+  /*
+   * dwStride is the number of whole pixels that occupy a scanline,
+   * including those pixels that are not displayed.  This is basically
+   * a rounding up of the width.
+   */
+  DWORD			dwStride;
+
+  /* Offset of the screen in the window when using scrollbars */
+  DWORD			dwXOffset;
+  DWORD			dwYOffset;
+
+  DWORD			dwBPP;
+  DWORD			dwDepth;
+  DWORD			dwRefreshRate;
+  char			*pfb;
+  DWORD			dwEngine;
+  DWORD			dwEnginePreferred;
+  DWORD			dwClipUpdatesNBoxes;
+#ifdef XWIN_EMULATEPSEUDO
+  Bool			fEmulatePseudo;
+#endif
+  Bool			fFullScreen;
+  Bool			fDecoration;
+#ifdef XWIN_MULTIWINDOWEXTWM
+  Bool			fMWExtWM;
+  Bool			fInternalWM;
+  Bool			fAnotherWMRunning;
+#endif
+  Bool			fRootless;
+#ifdef XWIN_MULTIWINDOW
+  Bool			fMultiWindow;
+#endif
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+  Bool			fMultiMonitorOverride;
+#endif
+  Bool                  fMultipleMonitors;
+  Bool			fLessPointer;
+  Bool			fScrollbars;
+  Bool			fNoTrayIcon;
+  int			iE3BTimeout;
+  /* Windows (Alt+F4) and Unix (Ctrl+Alt+Backspace) Killkey */
+  Bool                  fUseWinKillKey;
+  Bool                  fUseUnixKillKey;
+  Bool			fIgnoreInput;
+
+  /* Did the user explicitly set this screen? */
+  Bool			fExplicitScreen;
+} winScreenInfo, *winScreenInfoPtr;
+
+
+/*
+ * Screen privates
+ */
+
+typedef struct _winPrivScreenRec
+{
+  winScreenInfoPtr	pScreenInfo;
+
+  Bool			fEnabled;
+  Bool			fClosed;
+  Bool			fActive;
+  Bool			fBadDepth;
+
+  int			iDeltaZ;
+
+  int			iConnectedClients;
+
+  CloseScreenProcPtr	CloseScreen;
+
+  DWORD			dwRedMask;
+  DWORD			dwGreenMask;
+  DWORD			dwBlueMask;
+  DWORD			dwBitsPerRGB;
+
+  DWORD			dwModeKeyStates;
+
+  /* Handle to icons that must be freed */
+  HICON			hiconNotifyIcon;
+
+  /* Last width, height, and depth of the Windows display */
+  DWORD			dwLastWindowsWidth;
+  DWORD			dwLastWindowsHeight;
+  DWORD			dwLastWindowsBitsPixel;
+
+  /* Palette management */
+  ColormapPtr		pcmapInstalled;
+
+  /* Pointer to the root visual so we only have to look it up once */
+  VisualPtr		pRootVisual;
+
+  /* 3 button emulation variables */
+  int			iE3BCachedPress;
+  Bool			fE3BFakeButton2Sent;
+
+  /* Privates used by shadow fb GDI server */
+  HBITMAP		hbmpShadow;
+  HDC			hdcScreen;
+  HDC			hdcShadow;
+  HWND			hwndScreen;
+  
+  /* Privates used by shadow fb and primary fb DirectDraw servers */
+  LPDIRECTDRAW		pdd;
+  LPDIRECTDRAWSURFACE2	pddsPrimary;
+  LPDIRECTDRAW2		pdd2;
+
+  /* Privates used by shadow fb DirectDraw server */
+  LPDIRECTDRAWSURFACE2	pddsShadow;
+  LPDDSURFACEDESC	pddsdShadow;
+
+  /* Privates used by primary fb DirectDraw server */
+  LPDIRECTDRAWSURFACE2	pddsOffscreen;
+  LPDDSURFACEDESC	pddsdOffscreen;
+  LPDDSURFACEDESC	pddsdPrimary;
+
+  /* Privates used by shadow fb DirectDraw Nonlocking server */
+  LPDIRECTDRAW4		pdd4;
+  LPDIRECTDRAWSURFACE4	pddsShadow4;
+  LPDIRECTDRAWSURFACE4	pddsPrimary4;
+  BOOL			fRetryCreateSurface;
+
+  /* Privates used by both shadow fb DirectDraw servers */
+  LPDIRECTDRAWCLIPPER	pddcPrimary;
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  /* Privates used by multi-window external window manager */
+  RootlessFrameID	widTop;
+  Bool			fRestacking;
+#endif
+
+#ifdef XWIN_MULTIWINDOW
+  /* Privates used by multi-window */
+  pthread_t		ptWMProc;
+  pthread_t		ptXMsgProc;
+  void			*pWMInfo;
+#endif
+
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+  /* Privates used by both multi-window and rootless */
+  Bool			fRootWindowShown;
+#endif
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  /* Privates used for any module running in a seperate thread */
+  pthread_mutex_t	pmServerStarted;
+  Bool			fServerStarted;
+#endif
+  
+  /* Engine specific functions */
+  winAllocateFBProcPtr			pwinAllocateFB;
+  winShadowUpdateProcPtr		pwinShadowUpdate;
+  winCloseScreenProcPtr			pwinCloseScreen;
+  winInitVisualsProcPtr			pwinInitVisuals;
+  winAdjustVideoModeProcPtr		pwinAdjustVideoMode;
+  winCreateBoundingWindowProcPtr	pwinCreateBoundingWindow;
+  winFinishScreenInitProcPtr		pwinFinishScreenInit;
+  winBltExposedRegionsProcPtr		pwinBltExposedRegions;
+  winActivateAppProcPtr			pwinActivateApp;
+  winRedrawScreenProcPtr		pwinRedrawScreen;
+  winRealizeInstalledPaletteProcPtr	pwinRealizeInstalledPalette;
+  winInstallColormapProcPtr		pwinInstallColormap;
+  winStoreColorsProcPtr			pwinStoreColors;
+  winCreateColormapProcPtr		pwinCreateColormap;
+  winDestroyColormapProcPtr		pwinDestroyColormap;
+  winHotKeyAltTabProcPtr		pwinHotKeyAltTab;
+  winCreatePrimarySurfaceProcPtr	pwinCreatePrimarySurface;
+  winReleasePrimarySurfaceProcPtr	pwinReleasePrimarySurface;
+
+#ifdef XWIN_MULTIWINDOW
+  /* Window Procedures for MultiWindow mode */
+  winFinishCreateWindowsWindowProcPtr	pwinFinishCreateWindowsWindow;
+#endif
+
+  /* Window Procedures for Rootless mode */
+  CreateWindowProcPtr			CreateWindow;
+  DestroyWindowProcPtr			DestroyWindow;
+  PositionWindowProcPtr			PositionWindow;
+  ChangeWindowAttributesProcPtr		ChangeWindowAttributes;
+  RealizeWindowProcPtr			RealizeWindow;
+  UnrealizeWindowProcPtr		UnrealizeWindow;
+  ValidateTreeProcPtr			ValidateTree;
+  PostValidateTreeProcPtr		PostValidateTree;
+  WindowExposuresProcPtr		WindowExposures;
+  CopyWindowProcPtr			CopyWindow;
+  ClearToBackgroundProcPtr		ClearToBackground;
+  ClipNotifyProcPtr			ClipNotify;
+  RestackWindowProcPtr			RestackWindow;
+  ReparentWindowProcPtr			ReparentWindow;
+  ResizeWindowProcPtr			ResizeWindow;
+  MoveWindowProcPtr			MoveWindow;
+#ifdef SHAPE
+  SetShapeProcPtr			SetShape;
+#endif
+
+  winCursorRec                          cursor;
+} winPrivScreenRec;
+
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+typedef struct {
+  RootlessWindowPtr	pFrame;
+  HWND			hWnd;
+  int			dwWidthBytes;
+  BITMAPINFOHEADER	*pbmihShadow;
+  HBITMAP		hbmpShadow;
+  HDC			hdcShadow;
+  HDC			hdcScreen;
+  BOOL			fResized;
+  BOOL			fRestackingNow;
+  BOOL			fClose;
+  BOOL			fMovingOrSizing;
+  BOOL			fDestroyed;//for debug
+  char			*pfb;
+} win32RootlessWindowRec, *win32RootlessWindowPtr;
+#endif
+
+
+typedef struct {
+  pointer		value;
+  XID			id;
+} WindowIDPairRec, *WindowIDPairPtr;
+
+
+/*
+ * Extern declares for general global variables
+ */
+
+extern winScreenInfo		g_ScreenInfo[];
+extern miPointerScreenFuncRec	g_winPointerCursorFuncs;
+extern DWORD			g_dwEvents;
+#ifdef HAS_DEVWINDOWS
+extern int			g_fdMessageQueue;
+#endif
+extern DevPrivateKey		g_iScreenPrivateKey;
+extern DevPrivateKey		g_iCmapPrivateKey;
+extern DevPrivateKey		g_iGCPrivateKey;
+extern DevPrivateKey		g_iPixmapPrivateKey;
+extern DevPrivateKey		g_iWindowPrivateKey;
+extern unsigned long		g_ulServerGeneration;
+extern CARD32			g_c32LastInputEventTime;
+extern DWORD			g_dwEnginesSupported;
+extern HINSTANCE		g_hInstance;
+extern int                      g_copyROP[];
+extern int                      g_patternROP[];
+extern const char *		g_pszQueryHost;
+
+
+/*
+ * Extern declares for dynamically loaded libraries and function pointers
+ */
+
+extern HMODULE			g_hmodDirectDraw;
+extern FARPROC			g_fpDirectDrawCreate;
+extern FARPROC			g_fpDirectDrawCreateClipper;
+
+extern HMODULE			g_hmodCommonControls;
+extern FARPROC			g_fpTrackMouseEvent;
+
+
+/*
+ * Screen privates macros
+ */
+
+#define winGetScreenPriv(pScreen) ((winPrivScreenPtr) \
+    dixLookupPrivate(&(pScreen)->devPrivates, g_iScreenPrivateKey))
+
+#define winSetScreenPriv(pScreen,v) \
+    dixSetPrivate(&(pScreen)->devPrivates, g_iScreenPrivateKey, v)
+
+#define winScreenPriv(pScreen) \
+	winPrivScreenPtr pScreenPriv = winGetScreenPriv(pScreen)
+
+
+/*
+ * Colormap privates macros
+ */
+
+#define winGetCmapPriv(pCmap) ((winPrivCmapPtr) \
+    dixLookupPrivate(&(pCmap)->devPrivates, g_iCmapPrivateKey))
+
+#define winSetCmapPriv(pCmap,v) \
+    dixSetPrivate(&(pCmap)->devPrivates, g_iCmapPrivateKey, v)
+
+#define winCmapPriv(pCmap) \
+	winPrivCmapPtr pCmapPriv = winGetCmapPriv(pCmap)
+
+
+/*
+ * GC privates macros
+ */
+
+#define winGetGCPriv(pGC) ((winPrivGCPtr) \
+    dixLookupPrivate(&(pGC)->devPrivates, g_iGCPrivateKey))
+
+#define winSetGCPriv(pGC,v) \
+    dixSetPrivate(&(pGC)->devPrivates, g_iGCPrivateKey, v)
+
+#define winGCPriv(pGC) \
+	winPrivGCPtr pGCPriv = winGetGCPriv(pGC)
+
+
+/*
+ * Pixmap privates macros
+ */
+
+#define winGetPixmapPriv(pPixmap) ((winPrivPixmapPtr) \
+    dixLookupPrivate(&(pPixmap)->devPrivates, g_iPixmapPrivateKey))
+
+#define winSetPixmapPriv(pPixmap,v) \
+    dixLookupPrivate(&(pPixmap)->devPrivates, g_iPixmapPrivateKey, v)
+
+#define winPixmapPriv(pPixmap) \
+	winPrivPixmapPtr pPixmapPriv = winGetPixmapPriv(pPixmap)
+
+
+/*
+ * Window privates macros
+ */
+
+#define winGetWindowPriv(pWin) ((winPrivWinPtr) \
+    dixLookupPrivate(&(pWin)->devPrivates, g_iWindowPrivateKey))
+
+#define winSetWindowPriv(pWin,v) \
+    dixLookupPrivate(&(pWin)->devPrivates, g_iWindowPrivateKey, v)
+
+#define winWindowPriv(pWin) \
+	winPrivWinPtr pWinPriv = winGetWindowPriv(pWin)
+
+/*
+ * wrapper macros 
+ */
+#define _WIN_WRAP(priv, real, mem, func) {\
+    priv->mem = real->mem; \
+    real->mem = func; \
+}
+
+#define _WIN_UNWRAP(priv, real, mem) {\
+    real->mem = priv->mem; \
+}
+
+#define WIN_WRAP(mem, func) _WIN_WRAP(pScreenPriv, pScreen, mem, func) 
+
+#define WIN_UNWRAP(mem) _WIN_UNWRAP(pScreenPriv, pScreen, mem)
+
+/*
+ * BEGIN DDX and DIX Function Prototypes
+ */
+
+
+/*
+ * winallpriv.c
+ */
+
+Bool
+winAllocatePrivates (ScreenPtr pScreen);
+
+Bool
+winInitCmapPrivates (ColormapPtr pCmap, int index);
+
+Bool
+winAllocateCmapPrivates (ColormapPtr pCmap);
+
+
+/*
+ * winauth.c
+ */
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+# if defined(XCSECURITY)  
+Bool
+winGenerateAuthorization (void);
+# endif
+#endif
+
+
+/*
+ * winblock.c
+ */
+
+void
+winBlockHandler (int nScreen,
+		 pointer pBlockData,
+		 pointer pTimeout,
+		 pointer pReadMask);
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winclip.c
+ */
+
+RegionPtr
+winPixmapToRegionNativeGDI (PixmapPtr pPix);
+#endif
+
+
+#ifdef XWIN_CLIPBOARD
+/*
+ * winclipboardinit.c
+ */
+
+Bool
+winInitClipboard (void);
+
+void
+winFixClipboardChain (void);
+#endif
+
+
+/*
+ * wincmap.c
+ */
+
+void
+winSetColormapFunctions (ScreenPtr pScreen);
+
+Bool
+winCreateDefColormap (ScreenPtr pScreen);
+
+
+/*
+ * wincreatewnd.c
+ */
+
+Bool
+winCreateBoundingWindowFullScreen (ScreenPtr pScreen);
+
+Bool
+winCreateBoundingWindowWindowed (ScreenPtr pScreen);
+
+
+/*
+ * windialogs.c
+ */
+
+void
+winDisplayExitDialog (winPrivScreenPtr pScreenPriv);
+
+void
+winDisplayDepthChangeDialog (winPrivScreenPtr pScreenPriv);
+
+void
+winDisplayAboutDialog (winPrivScreenPtr pScreenPriv);
+
+
+/*
+ * winengine.c
+ */
+
+void
+winDetectSupportedEngines (void);
+
+Bool
+winSetEngine (ScreenPtr pScreen);
+
+Bool
+winGetDDProcAddresses (void);
+
+
+/*
+ * winerror.c
+ */
+
+#ifdef DDXOSVERRORF
+void
+OSVenderVErrorF (const char *pszFormat, va_list va_args);
+#endif
+
+void
+winMessageBoxF (const char *pszError, UINT uType, ...);
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winfillsp.c
+ */
+
+void
+winFillSpansNativeGDI (DrawablePtr	pDrawable,
+		       GCPtr		pGC,
+		       int		nSpans,
+		       DDXPointPtr	pPoints,
+		       int		*pWidths,
+		       int		fSorted);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winfont.c
+ */
+
+Bool
+winRealizeFontNativeGDI (ScreenPtr pScreen, FontPtr pFont);
+
+Bool
+winUnrealizeFontNativeGDI (ScreenPtr pScreen, FontPtr pFont);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * wingc.c
+ */
+
+Bool
+winCreateGCNativeGDI (GCPtr pGC);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * wingetsp.c
+ */
+
+void
+winGetSpansNativeGDI (DrawablePtr	pDrawable, 
+		      int		wMax, 
+		      DDXPointPtr	pPoints, 
+		      int		*pWidths, 
+		      int		nSpans, 
+		      char		*pDst);
+#endif
+
+
+/*
+ * winglobals.c
+ */
+
+void
+winInitializeGlobals (void);
+
+
+/*
+ * winkeybd.c
+ */
+
+void
+winTranslateKey (WPARAM wParam, LPARAM lParam, int *piScanCode);
+
+int
+winKeybdProc (DeviceIntPtr pDeviceInt, int iState);
+
+void
+winInitializeModeKeyStates (void);
+
+void
+winRestoreModeKeyStates (void);
+
+Bool
+winIsFakeCtrl_L (UINT message, WPARAM wParam, LPARAM lParam);
+
+void
+winKeybdReleaseKeys (void);
+
+void
+winSendKeyEvent (DWORD dwKey, Bool fDown);
+
+
+/*
+ * winkeyhook.c
+ */
+
+Bool
+winInstallKeyboardHookLL (void);
+
+void
+winRemoveKeyboardHookLL (void);
+
+
+/*
+ * winmisc.c
+ */
+
+#ifdef XWIN_NATIVEGDI
+void
+winQueryBestSizeNativeGDI (int class, unsigned short *pWidth,
+			   unsigned short *pHeight, ScreenPtr pScreen);
+#endif
+
+CARD8
+winCountBits (DWORD dw);
+
+Bool
+winUpdateFBPointer (ScreenPtr pScreen, void *pbits);
+
+#ifdef XWIN_NATIVEGDI
+BOOL
+winPaintBackground (HWND hwnd, COLORREF colorref);
+#endif
+
+
+/*
+ * winmouse.c
+ */
+
+int
+winMouseProc (DeviceIntPtr pDeviceInt, int iState);
+
+int
+winMouseWheel (ScreenPtr pScreen, int iDeltaZ);
+
+void
+winMouseButtonsSendEvent (int iEventType, int iButton);
+
+int
+winMouseButtonsHandle (ScreenPtr pScreen,
+		       int iEventType, int iButton,
+		       WPARAM wParam);
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winnativegdi.c
+ */
+
+HBITMAP
+winCreateDIBNativeGDI (int iWidth, int iHeight, int iDepth,
+		       BYTE **ppbBits, BITMAPINFO **ppbmi);
+
+Bool
+winSetEngineFunctionsNativeGDI (ScreenPtr pScreen);
+#endif
+
+
+#ifdef XWIN_PRIMARYFB
+/*
+ * winpfbddd.c
+ */
+
+Bool
+winSetEngineFunctionsPrimaryDD (ScreenPtr pScreen);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winpixmap.c
+ */
+
+PixmapPtr
+winCreatePixmapNativeGDI (ScreenPtr pScreen, int width, int height, int depth,
+			  unsigned usage_hint);
+
+Bool
+winDestroyPixmapNativeGDI (PixmapPtr pPixmap);
+
+Bool
+winModifyPixmapHeaderNativeGDI (PixmapPtr pPixmap,
+				int iWidth, int iHeight,
+				int iDepth,
+				int iBitsPerPixel,
+				int devKind,
+				pointer pPixData);
+#endif
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winpolyline.c
+ */
+
+void
+winPolyLineNativeGDI (DrawablePtr	pDrawable,
+		      GCPtr		pGC,
+		      int		mode,
+		      int		npt,
+		      DDXPointPtr	ppt);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winpushpxl.c
+ */
+
+void
+winPushPixels (GCPtr pGC, PixmapPtr pBitMap, DrawablePtr pDrawable,
+	       int dx, int dy, int xOrg, int yOrg);
+#endif
+
+
+/*
+ * winscrinit.c
+ */
+
+Bool
+winScreenInit (int index,
+	       ScreenPtr pScreen,
+	       int argc, char **argv);
+
+Bool
+winFinishScreenInitFB (int index,
+		       ScreenPtr pScreen,
+		       int argc, char **argv);
+
+#if defined(XWIN_NATIVEGDI)
+Bool
+winFinishScreenInitNativeGDI (int index,
+			      ScreenPtr pScreen,
+			      int argc, char **argv);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * winsetsp.c
+ */
+
+void
+winSetSpansNativeGDI (DrawablePtr	pDrawable,
+		      GCPtr		pGC,
+		      char		*pSrc,
+		      DDXPointPtr	pPoints,
+		      int		*pWidth,
+		      int		nSpans,
+		      int		fSorted);
+#endif
+
+
+/*
+ * winshaddd.c
+ */
+
+Bool
+winSetEngineFunctionsShadowDD (ScreenPtr pScreen);
+
+
+/*
+ * winshadddnl.c
+ */
+
+Bool
+winSetEngineFunctionsShadowDDNL (ScreenPtr pScreen);
+
+
+/*
+ * winshadgdi.c
+ */
+
+Bool
+winSetEngineFunctionsShadowGDI (ScreenPtr pScreen);
+
+
+/*
+ * winwakeup.c
+ */
+
+void
+winWakeupHandler (int nScreen,
+		  pointer pWakeupData,
+		  unsigned long ulResult,
+		  pointer pReadmask);
+
+
+/*
+ * winwindow.c
+ */
+
+#ifdef XWIN_NATIVEGDI
+Bool
+winCreateWindowNativeGDI (WindowPtr pWin);
+
+Bool
+winDestroyWindowNativeGDI (WindowPtr pWin);
+
+Bool
+winPositionWindowNativeGDI (WindowPtr pWin, int x, int y);
+
+void 
+winCopyWindowNativeGDI (WindowPtr pWin,
+			DDXPointRec ptOldOrg,
+			RegionPtr prgnSrc);
+
+Bool
+winChangeWindowAttributesNativeGDI (WindowPtr pWin, unsigned long mask);
+
+Bool
+winUnmapWindowNativeGDI (WindowPtr pWindow);
+
+Bool
+winMapWindowNativeGDI (WindowPtr pWindow);
+#endif
+
+Bool
+winCreateWindowRootless (WindowPtr pWindow);
+
+Bool
+winDestroyWindowRootless (WindowPtr pWindow);
+
+Bool
+winPositionWindowRootless (WindowPtr pWindow, int x, int y);
+
+Bool
+winChangeWindowAttributesRootless (WindowPtr pWindow, unsigned long mask);
+
+Bool
+winUnmapWindowRootless (WindowPtr pWindow);
+
+Bool
+winMapWindowRootless (WindowPtr pWindow);
+
+#ifdef SHAPE
+void
+winSetShapeRootless (WindowPtr pWindow);
+#endif
+
+
+/*
+ * winmultiwindowicons.c - Used by both multi-window and Win32Rootless
+ */
+
+HICON
+winXIconToHICON (WindowPtr pWin, int iconSize);
+
+
+#ifdef XWIN_MULTIWINDOW
+/*
+ * winmultiwindowshape.c
+ */
+
+# ifdef SHAPE
+void
+winReshapeMultiWindow (WindowPtr pWin);
+
+void
+winSetShapeMultiWindow (WindowPtr pWindow);
+
+void
+winUpdateRgnMultiWindow (WindowPtr pWindow);
+# endif
+#endif
+
+
+#ifdef XWIN_MULTIWINDOW
+/*
+ * winmultiwindowwindow.c
+ */
+
+Bool
+winCreateWindowMultiWindow (WindowPtr pWindow);
+
+Bool
+winDestroyWindowMultiWindow (WindowPtr pWindow);
+
+Bool
+winPositionWindowMultiWindow (WindowPtr pWindow, int x, int y);
+
+Bool
+winChangeWindowAttributesMultiWindow (WindowPtr pWindow, unsigned long mask);
+
+Bool
+winUnmapWindowMultiWindow (WindowPtr pWindow);
+
+Bool
+winMapWindowMultiWindow (WindowPtr pWindow);
+
+void
+winReparentWindowMultiWindow (WindowPtr pWin, WindowPtr pPriorParent);
+
+void
+winRestackWindowMultiWindow (WindowPtr pWin, WindowPtr pOldNextSib);
+
+void
+winReorderWindowsMultiWindow (void);
+
+void
+winResizeWindowMultiWindow (WindowPtr pWin, int x, int y, unsigned int w,
+			    unsigned int h, WindowPtr pSib);
+void
+winMoveWindowMultiWindow (WindowPtr pWin, int x, int y,
+			  WindowPtr pSib, VTKind kind);
+
+void
+winCopyWindowMultiWindow (WindowPtr pWin, DDXPointRec oldpt,
+			  RegionPtr oldRegion);
+
+XID
+winGetWindowID (WindowPtr pWin);
+
+int
+winAdjustXWindow (WindowPtr pWin, HWND hwnd);
+#endif
+
+
+#ifdef XWIN_MULTIWINDOW
+/*
+ * winmultiwindowwndproc.c
+ */
+
+LRESULT CALLBACK
+winTopLevelWindowProc (HWND hwnd, UINT message, 
+		       WPARAM wParam, LPARAM lParam);
+#endif
+
+
+/*
+ * wintrayicon.c
+ */
+
+void
+winInitNotifyIcon (winPrivScreenPtr pScreenPriv);
+
+void
+winDeleteNotifyIcon (winPrivScreenPtr pScreenPriv);
+
+LRESULT
+winHandleIconMessage (HWND hwnd, UINT message,
+		      WPARAM wParam, LPARAM lParam,
+		      winPrivScreenPtr pScreenPriv);
+
+
+/*
+ * winwndproc.c
+ */
+
+LRESULT CALLBACK
+winWindowProc (HWND hWnd, UINT message, 
+	       WPARAM wParam, LPARAM lParam);
+
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+/*
+ * winwin32rootless.c
+ */
+
+Bool
+winMWExtWMCreateFrame (RootlessWindowPtr pFrame, ScreenPtr pScreen,
+			     int newX, int newY, RegionPtr pShape);
+
+void
+winMWExtWMDestroyFrame (RootlessFrameID wid);
+
+void
+winMWExtWMMoveFrame (RootlessFrameID wid, ScreenPtr pScreen, int newX, int newY);
+
+void
+winMWExtWMResizeFrame (RootlessFrameID wid, ScreenPtr pScreen,
+			     int newX, int newY, unsigned int newW, unsigned int newH,
+			     unsigned int gravity);
+
+void
+winMWExtWMRestackFrame (RootlessFrameID wid, RootlessFrameID nextWid);
+
+void
+winMWExtWMReshapeFrame (RootlessFrameID wid, RegionPtr pShape);
+
+void
+winMWExtWMUnmapFrame (RootlessFrameID wid);
+
+void
+winMWExtWMStartDrawing (RootlessFrameID wid, char **pixelData, int *bytesPerRow);
+
+void
+winMWExtWMStopDrawing (RootlessFrameID wid, Bool flush);
+
+void
+winMWExtWMUpdateRegion (RootlessFrameID wid, RegionPtr pDamage);
+
+void
+winMWExtWMDamageRects (RootlessFrameID wid, int count, const BoxRec *rects,
+			     int shift_x, int shift_y);
+
+void
+winMWExtWMRootlessSwitchWindow (RootlessWindowPtr pFrame, WindowPtr oldWin);
+
+void
+winMWExtWMCopyBytes (unsigned int width, unsigned int height,
+			   const void *src, unsigned int srcRowBytes,
+			   void *dst, unsigned int dstRowBytes);
+
+void
+winMWExtWMFillBytes (unsigned int width, unsigned int height, unsigned int value,
+			   void *dst, unsigned int dstRowBytes);
+
+int
+winMWExtWMCompositePixels (unsigned int width, unsigned int height, unsigned int function,
+				 void *src[2], unsigned int srcRowBytes[2],
+				 void *mask, unsigned int maskRowBytes,
+				 void *dst[2], unsigned int dstRowBytes[2]);
+
+void
+winMWExtWMCopyWindow (RootlessFrameID wid, int dstNrects, const BoxRec *dstRects,
+			    int dx, int dy);
+#endif
+
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+/*
+ * winwin32rootlesswindow.c
+ */
+
+void
+winMWExtWMReorderWindows (ScreenPtr pScreen);
+
+void
+winMWExtWMMoveXWindow (WindowPtr pWin, int x, int y);
+
+void
+winMWExtWMResizeXWindow (WindowPtr pWin, int w, int h);
+
+void
+winMWExtWMMoveResizeXWindow (WindowPtr pWin, int x, int y, int w, int h);
+
+void
+winMWExtWMUpdateIcon (Window id);
+
+void
+winMWExtWMUpdateWindowDecoration (win32RootlessWindowPtr pRLWinPriv,
+				  winScreenInfoPtr pScreenInfo);
+
+wBOOL CALLBACK
+winMWExtWMDecorateWindow (HWND hwnd, LPARAM lParam);
+
+Bool
+winIsInternalWMRunning (winScreenInfoPtr pScreenInfo);
+
+void
+winMWExtWMRestackWindows (ScreenPtr pScreen);
+#endif
+
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+/*
+ * winwin32rootlesswndproc.c
+ */
+
+LRESULT CALLBACK
+winMWExtWMWindowProc (HWND hwnd, UINT message, 
+			    WPARAM wParam, LPARAM lParam);
+#endif
+
+
+/*
+ * winwindowswm.c
+ */
+
+void
+winWindowsWMSendEvent (int type, unsigned int mask, int which, int arg,
+		       Window window, int x, int y, int w, int h);
+
+void
+winWindowsWMExtensionInit (void);
+
+/*
+ * wincursor.c
+ */
+
+Bool
+winInitCursor (ScreenPtr pScreen);
+
+/*
+ * END DDX and DIX Function Prototypes
+ */
+
+#endif /* _WIN_H_ */
+
diff --git a/hw/xwin/winallpriv.c b/hw/xwin/winallpriv.c
new file mode 100644
index 0000000..21ccd9b
--- /dev/null
+++ b/hw/xwin/winallpriv.c
@@ -0,0 +1,172 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Keith Packard, MIT X Consortium
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/* See Porting Layer Definition - p. 58 */
+/*
+ * Allocate indexes for the privates that we use.
+ * Allocate memory directly for the screen privates.
+ * Reserve space in GCs and Pixmaps for our privates.
+ * Colormap privates are handled in winAllocateCmapPrivates ()
+ */
+
+Bool
+winAllocatePrivates (ScreenPtr pScreen)
+{
+  winPrivScreenPtr	pScreenPriv;
+
+#if CYGDEBUG
+  winDebug ("winAllocateScreenPrivates - g_ulServerGeneration: %d "
+	  "serverGeneration: %d\n",
+	  g_ulServerGeneration, serverGeneration);
+#endif
+
+  /* We need a new slot for our privates if the screen gen has changed */
+  if (g_ulServerGeneration != serverGeneration)
+    {
+      g_ulServerGeneration = serverGeneration;
+    }
+
+  /* Allocate memory for the screen private structure */
+  pScreenPriv = (winPrivScreenPtr) malloc (sizeof (winPrivScreenRec));
+  if (!pScreenPriv)
+    {
+      ErrorF ("winAllocateScreenPrivates - malloc () failed\n");
+      return FALSE;
+    }
+
+  /* Initialize the memory of the private structure */
+  ZeroMemory (pScreenPriv, sizeof (winPrivScreenRec));
+
+  /* Intialize private structure members */
+  pScreenPriv->fActive = TRUE;
+
+  /* Save the screen private pointer */
+  winSetScreenPriv (pScreen, pScreenPriv);
+
+  /* Reserve GC memory for our privates */
+  if (!dixRequestPrivate(g_iGCPrivateKey, sizeof (winPrivGCRec)))
+    {
+      ErrorF ("winAllocatePrivates - AllocateGCPrivate () failed\n");
+      return FALSE;
+    }
+
+  /* Reserve Pixmap memory for our privates */
+  if (!dixRequestPrivate(g_iPixmapPrivateKey, sizeof (winPrivPixmapRec)))
+    {
+      ErrorF ("winAllocatePrivates - AllocatePixmapPrivates () failed\n");
+      return FALSE;
+    }
+
+  /* Reserve Window memory for our privates */
+  if (!dixRequestPrivate(g_iWindowPrivateKey, sizeof (winPrivWinRec)))
+    {
+      ErrorF ("winAllocatePrivates () - AllocateWindowPrivates () failed\n");
+       return FALSE;
+     }
+
+  return TRUE;
+}
+
+
+/*
+ * Colormap privates may be allocated after the default colormap has
+ * already been created for some screens.  This initialization procedure
+ * is called for each default colormap that is found.
+ */
+
+Bool
+winInitCmapPrivates (ColormapPtr pcmap, int index)
+{
+#if CYGDEBUG
+  winDebug ("winInitCmapPrivates\n");
+#endif
+  
+  /*
+   * I see no way that this function can do anything useful
+   * with only a ColormapPtr.  We don't have the index for
+   * our dev privates yet, so we can't really initialize
+   * anything.  Perhaps I am misunderstanding the purpose
+   * of this function.
+   */
+  /*  That's definitely true.
+   *  I therefore changed the API and added the index as argument.
+   */
+  return TRUE;
+}
+
+
+/*
+ * Allocate memory for our colormap privates
+ */
+
+Bool
+winAllocateCmapPrivates (ColormapPtr pCmap)
+{
+  winPrivCmapPtr		pCmapPriv;
+  static unsigned long		s_ulPrivateGeneration = 0;
+
+#if CYGDEBUG
+  winDebug ("winAllocateCmapPrivates\n");
+#endif
+
+  /* Get a new privates index when the server generation changes */
+  if (s_ulPrivateGeneration != serverGeneration)
+    {
+      /* Save the new server generation */
+      s_ulPrivateGeneration = serverGeneration;
+    }
+
+  /* Allocate memory for our private structure */
+  pCmapPriv = (winPrivCmapPtr) malloc (sizeof (winPrivCmapRec));
+  if (!pCmapPriv)
+    {
+      ErrorF ("winAllocateCmapPrivates - malloc () failed\n");
+      return FALSE;
+    }
+
+  /* Initialize the memory of the private structure */
+  ZeroMemory (pCmapPriv, sizeof (winPrivCmapRec));
+
+  /* Save the cmap private pointer */
+  winSetCmapPriv (pCmap, pCmapPriv);
+
+#if CYGDEBUG
+  winDebug ("winAllocateCmapPrivates - Returning\n");
+#endif
+
+  return TRUE;
+}
diff --git a/hw/xwin/winauth.c b/hw/xwin/winauth.c
new file mode 100644
index 0000000..b57a35a
--- /dev/null
+++ b/hw/xwin/winauth.c
@@ -0,0 +1,131 @@
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#if defined(XCSECURITY)
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#include "win.h"
+
+/* Includes for authorization */
+#include <X11/Xauth.h>
+#include "securitysrv.h"
+#include <X11/extensions/securstr.h>
+
+
+/*
+ * Constants
+ */
+
+#define AUTH_NAME	"MIT-MAGIC-COOKIE-1"
+
+
+/*
+ * Globals
+ */
+
+XID		g_authId = 0;
+unsigned int	g_uiAuthDataLen = 0;
+char		*g_pAuthData = NULL;
+
+
+/*
+ * Generate authorization cookie for internal server clients
+ */
+
+Bool
+winGenerateAuthorization ()
+{
+  Bool				fFreeAuth = FALSE;
+  SecurityAuthorizationPtr	pAuth = NULL;
+
+  /* Call OS layer to generate authorization key */
+  g_authId = GenerateAuthorization (strlen (AUTH_NAME),
+				    AUTH_NAME,
+				    0,
+				    NULL,
+				    &g_uiAuthDataLen,
+				    &g_pAuthData);
+  if ((XID) ~0L == g_authId)
+    {
+      ErrorF ("winGenerateAuthorization - GenerateAuthorization failed\n");
+      goto auth_bailout;
+    }
+#if 0
+  else
+    {
+      ErrorF ("winGenerateAuthorization - GenerateAuthorization success!\n"
+	      "AuthDataLen: %d AuthData: %s\n",
+	      g_uiAuthDataLen, g_pAuthData);
+    }
+#endif
+  
+  /* Allocate structure for additional auth information */
+  pAuth = (SecurityAuthorizationPtr) 
+    xalloc (sizeof (SecurityAuthorizationRec));
+  if (!(pAuth))
+    {
+      ErrorF ("winGenerateAuthorization - Failed allocating "
+	      "SecurityAuthorizationPtr.\n");
+      goto auth_bailout;
+    }
+  
+  /* Fill in the auth fields */
+  pAuth->id = g_authId;
+  pAuth->timeout = 0; /* live for x seconds after refcnt == 0 */
+  pAuth->group = None;
+  pAuth->trustLevel = XSecurityClientTrusted;
+  pAuth->refcnt = 1; /* this auth must stick around */
+  pAuth->secondsRemaining = 0;
+  pAuth->timer = NULL;
+  pAuth->eventClients = NULL;
+  
+  /* Add the authorization to the server's auth list */
+  if (!AddResource (g_authId,
+		    SecurityAuthorizationResType,
+		    pAuth))
+    {
+      ErrorF ("winGenerateAuthorization - AddResource failed for auth.\n");
+      fFreeAuth = TRUE;
+      goto auth_bailout;
+    }
+  
+  /* Don't free the auth data, since it is still used internally */
+  pAuth = NULL;
+  
+  return TRUE;
+
+ auth_bailout:
+  if (fFreeAuth)
+    xfree (pAuth);
+  
+  return FALSE;
+}
+#endif
diff --git a/hw/xwin/winblock.c b/hw/xwin/winblock.c
new file mode 100644
index 0000000..abea60e
--- /dev/null
+++ b/hw/xwin/winblock.c
@@ -0,0 +1,106 @@
+/*
+ *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winmsg.h"
+
+
+/*
+ * References to external symbols
+ */
+
+extern HWND			g_hDlgDepthChange;
+extern HWND			g_hDlgExit;
+extern HWND			g_hDlgAbout;
+
+
+/* See Porting Layer Definition - p. 6 */
+void
+winBlockHandler (int nScreen,
+		 pointer pBlockData,
+		 pointer pTimeout,
+		 pointer pReadMask)
+{
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  winScreenPriv((ScreenPtr)pBlockData);
+#endif
+  MSG			msg;
+#ifndef HAS_DEVWINDOWS
+  struct timeval **tvp = pTimeout;
+  if (*tvp != NULL) 
+  {
+    (*tvp)->tv_sec = 0;
+    (*tvp)->tv_usec = 100;
+  }
+#endif
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  /* Signal threaded modules to begin */
+  if (pScreenPriv != NULL && !pScreenPriv->fServerStarted)
+    {
+      int		iReturn;
+      
+      winDebug ("winBlockHandler - Releasing pmServerStarted\n");
+
+      /* Flag that modules are to be started */
+      pScreenPriv->fServerStarted = TRUE;
+
+      /* Unlock the mutex for threaded modules */
+      iReturn = pthread_mutex_unlock (&pScreenPriv->pmServerStarted);
+      if (iReturn != 0)
+	{
+	  ErrorF ("winBlockHandler - pthread_mutex_unlock () failed: %d\n",
+		  iReturn);
+	  goto winBlockHandler_ProcessMessages; 
+	}
+
+      winDebug ("winBlockHandler - pthread_mutex_unlock () returned\n");
+    }
+
+winBlockHandler_ProcessMessages:
+#endif
+
+  /* Process all messages on our queue */
+  while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
+    {
+      if ((g_hDlgDepthChange == 0
+	   || !IsDialogMessage (g_hDlgDepthChange, &msg))
+	  && (g_hDlgExit == 0
+	      || !IsDialogMessage (g_hDlgExit, &msg))
+	  && (g_hDlgAbout == 0
+	      || !IsDialogMessage (g_hDlgAbout, &msg)))
+	{
+	  DispatchMessage (&msg);
+	}
+    }
+}
diff --git a/hw/xwin/winclip.c b/hw/xwin/winclip.c
new file mode 100644
index 0000000..aab7d63
--- /dev/null
+++ b/hw/xwin/winclip.c
@@ -0,0 +1,42 @@
+/*
+ *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+/* Look at mfb/mfbclip.c for sample implementation */
+RegionPtr
+winPixmapToRegionNativeGDI (PixmapPtr pPix)
+{
+  ErrorF ("winPixmapToRegion()\n");
+  return NULL;
+}
diff --git a/hw/xwin/winclipboard.h b/hw/xwin/winclipboard.h
new file mode 100644
index 0000000..445c01b
--- /dev/null
+++ b/hw/xwin/winclipboard.h
@@ -0,0 +1,164 @@
+#ifndef _WINCLIPBOARD_H_
+#define _WINCLIPBOARD_H_
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+/* Standard library headers */
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#ifdef __CYGWIN__
+#include <sys/select.h>
+#else
+#include "Xwinsock.h"
+#define HAS_WINSOCK
+#endif
+#include <fcntl.h>
+#include <setjmp.h>
+#include <pthread.h>
+
+/* X headers */
+#include <X11/X.h>
+#include <X11/Xatom.h>
+/* NOTE: For some unknown reason, including Xproto.h solves
+ * tons of problems with including windows.h.  Unknowns reasons
+ * are usually bad, so someone should investigate this.
+ */
+#include <X11/Xproto.h>
+#include "X11/Xutil.h"
+#include "X11/Xlocale.h"
+
+/* Fixups to prevent collisions between Windows and X headers */
+#define ATOM			DWORD
+
+#ifndef __CYGWIN__
+#define sleep(x) Sleep (1000 * (x))
+#endif
+
+/* Windows headers */
+#ifndef XFree86Server
+#define XFree86Server
+#endif
+#include <windows.h>
+#undef XFree86Server
+
+
+/* Clipboard module constants */
+#define WIN_CLIPBOARD_WINDOW_CLASS		"xwinclip"
+#define WIN_CLIPBOARD_WINDOW_TITLE		"xwinclip"
+#ifdef HAS_DEVWINDOWS
+# define WIN_MSG_QUEUE_FNAME			"/dev/windows"
+#endif
+#define WIN_CONNECT_RETRIES			40
+#define WIN_CONNECT_DELAY			4
+#define WIN_JMP_OKAY				0
+#define WIN_JMP_ERROR_IO			2
+#define WIN_LOCAL_PROPERTY			"CYGX_CUT_BUFFER"
+#define WIN_XEVENTS_SUCCESS			0
+#define WIN_XEVENTS_SHUTDOWN			1
+#define WIN_XEVENTS_CONVERT			2
+#define WIN_XEVENTS_NOTIFY			3
+
+#define WM_WM_REINIT                           (WM_USER + 1)
+
+/*
+ * References to external symbols
+ */
+
+extern char *display;
+extern void ErrorF (const char* /*f*/, ...);
+extern void winDebug (const char *format, ...);
+extern void winErrorFVerb (int verb, const char *format, ...);
+
+
+/*
+ * winclipboardinit.c
+ */
+
+Bool
+winInitClipboard (void);
+
+HWND
+winClipboardCreateMessagingWindow (void);
+
+
+/*
+ * winclipboardtextconv.c
+ */
+
+void
+winClipboardDOStoUNIX (char *pszData, int iLength);
+
+void
+winClipboardUNIXtoDOS (unsigned char **ppszData, int iLength);
+
+
+/*
+ * winclipboardthread.c
+ */
+
+void *
+winClipboardProc (void *);
+
+void
+winDeinitClipboard (void);
+
+
+/*
+ * winclipboardunicode.c
+ */
+
+Bool
+winClipboardDetectUnicodeSupport (void);
+
+
+/*
+ * winclipboardwndproc.c
+ */
+
+BOOL
+winClipboardFlushWindowsMessageQueue (HWND hwnd);
+
+LRESULT CALLBACK
+winClipboardWindowProc (HWND hwnd, UINT message, 
+			WPARAM wParam, LPARAM lParam);
+
+
+/*
+ * winclipboardxevents.c
+ */
+
+int
+winClipboardFlushXEvents (HWND hwnd,
+			  int iWindow,
+			  Display *pDisplay,
+			  Bool fUnicodeSupport);
+#endif
diff --git a/hw/xwin/winclipboardinit.c b/hw/xwin/winclipboardinit.c
new file mode 100644
index 0000000..6a0cbaf
--- /dev/null
+++ b/hw/xwin/winclipboardinit.c
@@ -0,0 +1,143 @@
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "dixstruct.h"
+#include "winclipboard.h"
+
+
+/*
+ * Local typedefs
+ */
+
+typedef int (*winDispatchProcPtr) (ClientPtr);
+
+DISPATCH_PROC(winProcSetSelectionOwner);
+
+
+/*
+ * References to external symbols
+ */
+
+extern pthread_t		g_ptClipboardProc;
+extern winDispatchProcPtr	winProcSetSelectionOwnerOrig;
+extern Bool			g_fClipboard;
+extern HWND			g_hwndClipboard;
+
+
+/*
+ * Intialize the Clipboard module
+ */
+
+Bool
+winInitClipboard ()
+{
+  ErrorF ("winInitClipboard ()\n");
+
+  /* Wrap some internal server functions */
+  if (ProcVector[X_SetSelectionOwner] != winProcSetSelectionOwner)
+    {
+      winProcSetSelectionOwnerOrig = ProcVector[X_SetSelectionOwner];
+      ProcVector[X_SetSelectionOwner] = winProcSetSelectionOwner;
+    }
+  
+  /* Spawn a thread for the Clipboard module */
+  if (pthread_create (&g_ptClipboardProc,
+		      NULL,
+		      winClipboardProc,
+		      NULL))
+    {
+      /* Bail if thread creation failed */
+      ErrorF ("winInitClipboard - pthread_create failed.\n");
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Create the Windows window that we use to recieve Windows messages
+ */
+
+HWND
+winClipboardCreateMessagingWindow ()
+{
+  WNDCLASS			wc;
+  HWND				hwnd;
+
+  /* Setup our window class */
+  wc.style = CS_HREDRAW | CS_VREDRAW;
+  wc.lpfnWndProc = winClipboardWindowProc;
+  wc.cbClsExtra = 0;
+  wc.cbWndExtra = 0;
+  wc.hInstance = GetModuleHandle (NULL);
+  wc.hIcon = 0;
+  wc.hCursor = 0;
+  wc.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
+  wc.lpszMenuName = NULL;
+  wc.lpszClassName = WIN_CLIPBOARD_WINDOW_CLASS;
+  RegisterClass (&wc);
+
+  /* Create the window */
+  hwnd = CreateWindowExA (0,			/* Extended styles */
+			  WIN_CLIPBOARD_WINDOW_CLASS,/* Class name */
+			  WIN_CLIPBOARD_WINDOW_TITLE,/* Window name */
+			  WS_OVERLAPPED,	/* Not visible anyway */
+			  CW_USEDEFAULT,	/* Horizontal position */
+			  CW_USEDEFAULT,	/* Vertical position */
+			  CW_USEDEFAULT,	/* Right edge */
+			  CW_USEDEFAULT,	/* Bottom edge */
+			  (HWND) NULL,		/* No parent or owner window */
+			  (HMENU) NULL,		/* No menu */
+			  GetModuleHandle (NULL),/* Instance handle */
+			  NULL);		/* Creation data */
+  assert (hwnd != NULL);
+
+  /* I'm not sure, but we may need to call this to start message processing */
+  ShowWindow (hwnd, SW_HIDE);
+
+  /* Similarly, we may need a call to this even though we don't paint */
+  UpdateWindow (hwnd);
+
+  return hwnd;
+}
+
+void
+winFixClipboardChain (void)
+{
+   if (g_fClipboard
+       && g_hwndClipboard)
+     {
+       PostMessage (g_hwndClipboard, WM_WM_REINIT, 0, 0);
+     }
+}
diff --git a/hw/xwin/winclipboardtextconv.c b/hw/xwin/winclipboardtextconv.c
new file mode 100644
index 0000000..fd2e696
--- /dev/null
+++ b/hw/xwin/winclipboardtextconv.c
@@ -0,0 +1,159 @@
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+void
+winClipboardDOStoUNIX (char *pszSrc, int iLength);
+void
+winClipboardUNIXtoDOS (unsigned char **ppszData, int iLength);
+
+/*
+ * Convert \r\n to \n
+ *
+ * NOTE: This was heavily inspired by, Cygwin's
+ * winsup/cygwin/fhandler.cc/fhandler_base::read ()
+ */
+
+void
+winClipboardDOStoUNIX (char *pszSrc, int iLength)
+{
+  char			*pszDest = pszSrc;
+  char			*pszEnd = pszSrc + iLength;
+
+  /* Loop until the last character */
+  while (pszSrc < pszEnd)
+    {
+      /* Copy the current source character to current destination character */
+      *pszDest = *pszSrc;
+
+      /* Advance to the next source character */
+      pszSrc++;
+
+      /* Don't advance the destination character if we need to drop an \r */
+      if (*pszDest != '\r' || *pszSrc != '\n')
+	pszDest++;
+    }
+
+  /* Move the terminating null */
+  *pszDest = '\0';
+}
+
+
+/*
+ * Convert \n to \r\n
+ */
+
+void
+winClipboardUNIXtoDOS (unsigned char **ppszData, int iLength)
+{
+  int			iNewlineCount = 0;
+  unsigned char		*pszSrc = *ppszData;
+  unsigned char		*pszEnd = pszSrc + iLength;
+  unsigned char		*pszDest = NULL, *pszDestBegin = NULL;
+
+#if 0
+  ErrorF ("UNIXtoDOS () - Original data:\n%s\n", *ppszData);
+#endif
+
+  /* Count \n characters without leading \r */
+  while (pszSrc < pszEnd)
+    {
+      /* Skip ahead two character if found set of \r\n */
+      if (*pszSrc == '\r' && pszSrc + 1 < pszEnd && *(pszSrc + 1) == '\n')
+	{
+	  pszSrc += 2;
+	  continue;
+	} 
+
+      /* Increment the count if found naked \n */
+      if (*pszSrc == '\n')
+	{
+	  iNewlineCount++;
+	}
+
+      pszSrc++;
+    }
+  
+  /* Return if no naked \n's */
+  if (iNewlineCount == 0)
+    return;
+
+  /* Allocate a new string */
+  pszDestBegin = pszDest = malloc (iLength + iNewlineCount + 1);
+
+  /* Set source pointer to beginning of data string */
+  pszSrc = *ppszData;
+
+  /* Loop through all characters in source string */
+  while (pszSrc < pszEnd)
+    {
+      /* Copy line endings that are already valid */
+      if (*pszSrc == '\r' && pszSrc + 1 < pszEnd && *(pszSrc + 1) == '\n')
+	{
+	  *pszDest = *pszSrc;
+	  *(pszDest + 1) = *(pszSrc + 1);
+	  pszDest += 2;
+	  pszSrc += 2;
+	  continue;
+	}
+
+      /* Add \r to naked \n's */
+      if (*pszSrc == '\n')
+	{
+	  *pszDest = '\r';
+	  *(pszDest + 1) = *pszSrc;
+	  pszDest += 2;
+	  pszSrc += 1;
+	  continue;
+	}
+
+      /* Copy normal characters */
+      *pszDest = *pszSrc;
+      pszSrc++;
+      pszDest++;
+    }
+
+  /* Put terminating null at end of new string */
+  *pszDest = '\0';
+
+  /* Swap string pointers */
+  free (*ppszData);
+  *ppszData = pszDestBegin;
+
+#if 0
+  ErrorF ("UNIXtoDOS () - Final string:\n%s\n", pszDestBegin);
+#endif
+}
diff --git a/hw/xwin/winclipboardthread.c b/hw/xwin/winclipboardthread.c
new file mode 100644
index 0000000..081abd5
--- /dev/null
+++ b/hw/xwin/winclipboardthread.c
@@ -0,0 +1,477 @@
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include <sys/types.h>
+#include "winclipboard.h"
+#ifdef __CYGWIN__
+#include <errno.h>
+#endif
+#include "X11/Xauth.h"
+
+
+/*
+ * Constants
+ */
+
+#define AUTH_NAME	"MIT-MAGIC-COOKIE-1"
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool		g_fUnicodeClipboard;
+extern unsigned long	serverGeneration;
+#if defined(XCSECURITY)
+extern unsigned int	g_uiAuthDataLen;
+extern char		*g_pAuthData;
+#endif
+extern Bool		g_fClipboardStarted;
+extern HWND		g_hwndClipboard;
+extern void		*g_pClipboardDisplay;
+extern Window		g_iClipboardWindow;
+
+
+/*
+ * Global variables
+ */
+
+static jmp_buf			g_jmpEntry;
+Bool				g_fUnicodeSupport = FALSE;
+Bool				g_fUseUnicode = FALSE;
+
+
+/*
+ * Local function prototypes
+ */
+
+static int
+winClipboardErrorHandler (Display *pDisplay, XErrorEvent *pErr);
+
+static int
+winClipboardIOErrorHandler (Display *pDisplay);
+
+
+/*
+ * Main thread function
+ */
+
+void *
+winClipboardProc (void *pvNotUsed)
+{
+  Atom			atomClipboard, atomClipboardManager;
+  int			iReturn;
+  HWND			hwnd = NULL;
+  int			iConnectionNumber = 0;
+#ifdef HAS_DEVWINDOWS
+  int			fdMessageQueue = 0;
+#else
+  struct timeval        tvTimeout;
+#endif
+  fd_set		fdsRead;
+  int			iMaxDescriptor;
+  Display		*pDisplay = NULL;
+  Window		iWindow = None;
+  int			iRetries;
+  Bool			fUseUnicode;
+  char			szDisplay[512];
+  int			iSelectError;
+
+  ErrorF ("winClipboardProc - Hello\n");
+
+  /* Do we have Unicode support? */
+  g_fUnicodeSupport = winClipboardDetectUnicodeSupport ();
+
+  /* Do we use Unicode clipboard? */
+  fUseUnicode = g_fUnicodeClipboard && g_fUnicodeSupport;
+
+  /* Save the Unicode support flag in a global */
+  g_fUseUnicode = fUseUnicode;
+
+  /* Allow multiple threads to access Xlib */
+  if (XInitThreads () == 0)
+    {
+      ErrorF ("winClipboardProc - XInitThreads failed.\n");
+      pthread_exit (NULL);
+    }
+
+  /* See if X supports the current locale */
+  if (XSupportsLocale () == False)
+    {
+      ErrorF ("winClipboardProc - Locale not supported by X.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* Set jump point for Error exits */
+  iReturn = setjmp (g_jmpEntry);
+  
+  /* Check if we should continue operations */
+  if (iReturn != WIN_JMP_ERROR_IO
+      && iReturn != WIN_JMP_OKAY)
+    {
+      /* setjmp returned an unknown value, exit */
+      ErrorF ("winClipboardProc - setjmp returned: %d exiting\n",
+	      iReturn);
+      pthread_exit (NULL);
+    }
+  else if (iReturn == WIN_JMP_ERROR_IO)
+    {
+      /* TODO: Cleanup the Win32 window and free any allocated memory */
+      ErrorF ("winClipboardProc - setjmp returned for IO Error Handler.\n");
+      pthread_exit (NULL);
+    }
+
+#if defined(XCSECURITY)
+  /* Use our generated cookie for authentication */
+  XSetAuthorization (AUTH_NAME,
+		     strlen (AUTH_NAME),
+		     g_pAuthData,
+		     g_uiAuthDataLen);
+#endif
+
+  /* Set error handler */
+  XSetErrorHandler (winClipboardErrorHandler);
+  XSetIOErrorHandler (winClipboardIOErrorHandler);
+
+  /* Initialize retry count */
+  iRetries = 0;
+
+  /* Setup the display connection string x */
+  /*
+   * NOTE: Always connect to screen 0 since we require that screen
+   * numbers start at 0 and increase without gaps.  We only need
+   * to connect to one screen on the display to get events
+   * for all screens on the display.  That is why there is only
+   * one clipboard client thread.
+   */
+  snprintf (szDisplay,
+	    512,
+	    "127.0.0.1:%s.0",
+	    display);
+
+  /* Print the display connection string */
+  ErrorF ("winClipboardProc - DISPLAY=%s\n", szDisplay);
+
+  /* Open the X display */
+  do
+    {
+      pDisplay = XOpenDisplay (szDisplay);
+      if (pDisplay == NULL)
+	{
+	  ErrorF ("winClipboardProc - Could not open display, "
+		  "try: %d, sleeping: %d\n",
+		  iRetries + 1, WIN_CONNECT_DELAY);
+	  ++iRetries;
+	  sleep (WIN_CONNECT_DELAY);
+	  continue;
+	}
+      else
+	break;
+    }
+  while (pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
+
+  /* Make sure that the display opened */
+  if (pDisplay == NULL)
+    {
+      ErrorF ("winClipboardProc - Failed opening the display, giving up\n");
+      pthread_exit (NULL);
+    }
+
+  /* Save the display in the screen privates */
+  g_pClipboardDisplay = pDisplay;
+
+  ErrorF ("winClipboardProc - XOpenDisplay () returned and "
+	  "successfully opened the display.\n");
+
+  /* Get our connection number */
+  iConnectionNumber = ConnectionNumber (pDisplay);
+
+#ifdef HAS_DEVWINDOWS
+  /* Open a file descriptor for the windows message queue */
+  fdMessageQueue = open (WIN_MSG_QUEUE_FNAME, O_RDONLY);
+  if (fdMessageQueue == -1)
+    {
+      ErrorF ("winClipboardProc - Failed opening %s\n", WIN_MSG_QUEUE_FNAME);
+      pthread_exit (NULL);
+    }
+
+  /* Find max of our file descriptors */
+  iMaxDescriptor = max (fdMessageQueue, iConnectionNumber) + 1;
+#else
+  iMaxDescriptor = iConnectionNumber + 1;
+#endif
+
+  /* Select event types to watch */
+  if (XSelectInput (pDisplay,
+		    DefaultRootWindow (pDisplay),
+		    SubstructureNotifyMask |
+		    StructureNotifyMask |
+		    PropertyChangeMask) == BadWindow)
+    ErrorF ("winClipboardProc - XSelectInput generated BadWindow "
+	    "on RootWindow\n\n");
+
+  /* Create atoms */
+  atomClipboard = XInternAtom (pDisplay, "CLIPBOARD", False);
+  atomClipboardManager = XInternAtom (pDisplay, "CLIPBOARD_MANAGER", False);
+
+  /* Create a messaging window */
+  iWindow = XCreateSimpleWindow (pDisplay,
+				 DefaultRootWindow (pDisplay),
+				 1, 1,
+				 500, 500,
+				 0,
+				 BlackPixel (pDisplay, 0),
+				 BlackPixel (pDisplay, 0));
+  if (iWindow == 0)
+    {
+      ErrorF ("winClipboardProc - Could not create an X window.\n");
+      pthread_exit (NULL);
+    }
+
+  /* Save the window in the screen privates */
+  g_iClipboardWindow = iWindow;
+
+  /* Create Windows messaging window */
+  hwnd = winClipboardCreateMessagingWindow ();
+  
+  /* Save copy of HWND in screen privates */
+  g_hwndClipboard = hwnd;
+
+  /* Assert ownership of selections if Win32 clipboard is owned */
+  if (NULL != GetClipboardOwner ())
+    {
+      /* PRIMARY */
+      iReturn = XSetSelectionOwner (pDisplay, XA_PRIMARY,
+				    iWindow, CurrentTime);
+      if (iReturn == BadAtom || iReturn == BadWindow)
+	{
+	  ErrorF ("winClipboardProc - Could not set PRIMARY owner\n");
+	  pthread_exit (NULL);
+	}
+
+      /* CLIPBOARD */
+      iReturn = XSetSelectionOwner (pDisplay, atomClipboard,
+				    iWindow, CurrentTime);
+      if (iReturn == BadAtom || iReturn == BadWindow)
+	{
+	  ErrorF ("winClipboardProc - Could not set CLIPBOARD owner\n");
+	  pthread_exit (NULL);
+	}
+    }
+
+  /* Pre-flush X events */
+  /* 
+   * NOTE: Apparently you'll freeze if you don't do this,
+   *	   because there may be events in local data structures
+   *	   already.
+   */
+  winClipboardFlushXEvents (hwnd,
+			    iWindow,
+			    pDisplay,
+			    fUseUnicode);
+
+  /* Pre-flush Windows messages */
+  if (!winClipboardFlushWindowsMessageQueue (hwnd))
+    return 0;
+
+  /* Signal that the clipboard client has started */
+  g_fClipboardStarted = TRUE;
+
+  /* Loop for X events */
+  while (1)
+    {
+      /* Setup the file descriptor set */
+      /*
+       * NOTE: You have to do this before every call to select
+       *       because select modifies the mask to indicate
+       *       which descriptors are ready.
+       */
+      FD_ZERO (&fdsRead);
+      FD_SET (iConnectionNumber, &fdsRead);
+#ifdef HAS_DEVWINDOWS
+      FD_SET (fdMessageQueue, &fdsRead);
+#else
+      tvTimeout.tv_sec = 0;
+      tvTimeout.tv_usec = 100;
+#endif
+
+      /* Wait for a Windows event or an X event */
+      iReturn = select (iMaxDescriptor,	/* Highest fds number */
+			&fdsRead,	/* Read mask */
+			NULL,		/* No write mask */
+			NULL,		/* No exception mask */
+#ifdef HAS_DEVWINDOWS
+			NULL		/* No timeout */
+#else
+			&tvTimeout      /* Set timeout */
+#endif
+          );
+
+#ifndef HAS_WINSOCK
+      iSelectError = errno;
+#else
+      iSelectError = WSAGetLastError();
+#endif
+
+      if (iReturn < 0)
+	{
+#ifndef HAS_WINSOCK
+          if (iSelectError == EINTR)
+#else
+          if (iSelectError == WSAEINTR)
+#endif
+            continue;
+          
+	  ErrorF ("winClipboardProc - Call to select () failed: %d.  "
+		  "Bailing.\n", iReturn);
+	  break;
+	}
+
+      /* Branch on which descriptor became active */
+      if (FD_ISSET (iConnectionNumber, &fdsRead))
+	{
+	  /* Process X events */
+	  /* Exit when we see that server is shutting down */
+	  iReturn = winClipboardFlushXEvents (hwnd,
+					      iWindow,
+					      pDisplay,
+					      fUseUnicode);
+	  if (WIN_XEVENTS_SHUTDOWN == iReturn)
+	    {
+	      ErrorF ("winClipboardProc - winClipboardFlushXEvents "
+		      "trapped shutdown event, exiting main loop.\n");
+	      break;
+	    }
+	}
+
+#ifdef HAS_DEVWINDOWS
+      /* Check for Windows event ready */
+      if (FD_ISSET (fdMessageQueue, &fdsRead))
+#else
+      if (1)
+#endif
+	{
+	  /* Process Windows messages */
+	  if (!winClipboardFlushWindowsMessageQueue (hwnd))
+	    {
+	      ErrorF ("winClipboardProc - "
+		      "winClipboardFlushWindowsMessageQueue trapped "
+		      "WM_QUIT message, exiting main loop.\n");
+	      break;
+	    }
+	}
+    }
+
+  /* Close our X window */
+  if (pDisplay && iWindow)
+    {
+      iReturn = XDestroyWindow (pDisplay, iWindow);
+      if (iReturn == BadWindow)
+	ErrorF ("winClipboardProc - XDestroyWindow returned BadWindow.\n");
+      else
+	ErrorF ("winClipboardProc - XDestroyWindow succeeded.\n");
+    }
+
+
+#ifdef HAS_DEVWINDOWS
+  /* Close our Win32 message handle */
+  if (fdMessageQueue)
+    close (fdMessageQueue);
+#endif
+
+#if 0
+  /*
+   * FIXME: XCloseDisplay hangs if we call it, as of 2004/03/26.  The
+   * XSync and XSelectInput calls did not help.
+   */
+
+  /* Discard any remaining events */
+  XSync (pDisplay, TRUE);
+
+  /* Select event types to watch */
+  XSelectInput (pDisplay,
+		DefaultRootWindow (pDisplay),
+		None);
+
+  /* Close our X display */
+  if (pDisplay)
+    {
+      XCloseDisplay (pDisplay);
+    }
+#endif
+
+  g_iClipboardWindow = None;
+  g_pClipboardDisplay = NULL;
+  g_hwndClipboard = NULL;
+
+  return NULL;
+}
+
+
+/*
+ * winClipboardErrorHandler - Our application specific error handler
+ */
+
+static int
+winClipboardErrorHandler (Display *pDisplay, XErrorEvent *pErr)
+{
+  char pszErrorMsg[100];
+  
+  XGetErrorText (pDisplay,
+		 pErr->error_code,
+		 pszErrorMsg,
+		 sizeof (pszErrorMsg));
+  ErrorF ("winClipboardErrorHandler - ERROR: \n\t%s\n"
+	  "\tSerial: %d, Request Code: %d, Minor Code: %d\n",
+	  pszErrorMsg,
+	  pErr->serial,
+	  pErr->request_code,
+	  pErr->minor_code);
+  return 0;
+}
+
+
+/*
+ * winClipboardIOErrorHandler - Our application specific IO error handler
+ */
+
+static int
+winClipboardIOErrorHandler (Display *pDisplay)
+{
+  ErrorF ("\nwinClipboardIOErrorHandler!\n\n");
+
+  /* Restart at the main entry point */
+  longjmp (g_jmpEntry, WIN_JMP_ERROR_IO);
+  
+  return 0;
+}
diff --git a/hw/xwin/winclipboardunicode.c b/hw/xwin/winclipboardunicode.c
new file mode 100644
index 0000000..ba86915
--- /dev/null
+++ b/hw/xwin/winclipboardunicode.c
@@ -0,0 +1,69 @@
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "winclipboard.h"
+
+
+/*
+ * Determine whether we suport Unicode or not.
+ * NOTE: Currently, just check if we are on an NT-based platform or not.
+ */
+
+Bool
+winClipboardDetectUnicodeSupport (void)
+{
+  Bool			fReturn = FALSE;
+  OSVERSIONINFO		osvi = {0};
+  
+  /* Get operating system version information */
+  osvi.dwOSVersionInfoSize = sizeof (osvi);
+  GetVersionEx (&osvi);
+
+  /* Branch on platform ID */
+  switch (osvi.dwPlatformId)
+    {
+    case VER_PLATFORM_WIN32_NT:
+      /* Unicode supported on NT only */
+      ErrorF ("DetectUnicodeSupport - Windows NT/2000/XP\n");
+      fReturn = TRUE;
+      break;
+
+    case VER_PLATFORM_WIN32_WINDOWS:
+      /* Unicode is not supported on non-NT */
+      ErrorF ("DetectUnicodeSupport - Windows 95/98/Me\n");
+      fReturn = FALSE;
+      break;
+    }
+
+  return fReturn;
+}
diff --git a/hw/xwin/winclipboardwndproc.c b/hw/xwin/winclipboardwndproc.c
new file mode 100644
index 0000000..802a740
--- /dev/null
+++ b/hw/xwin/winclipboardwndproc.c
@@ -0,0 +1,622 @@
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include <sys/types.h>
+#include <sys/time.h>
+#include "winclipboard.h"
+
+extern void		winFixClipboardChain();
+
+
+/*
+ * Constants
+ */
+
+#define WIN_CLIPBOARD_PROP	"cyg_clipboard_prop"
+#define WIN_POLL_TIMEOUT	1
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool		g_fUseUnicode;
+extern Bool		g_fUnicodeSupport;
+extern void		*g_pClipboardDisplay;
+extern Window		g_iClipboardWindow;
+extern Atom		g_atomLastOwnedSelection;
+
+/* BPS - g_hwndClipboard needed for X app->Windows paste fix */
+extern HWND		g_hwndClipboard;
+
+/* 
+ * Local function prototypes
+ */
+
+static Bool
+winProcessXEventsTimeout (HWND hwnd, int iWindow, Display *pDisplay,
+			  Bool fUseUnicode, int iTimeoutSec);
+
+
+/*
+ * Process X events up to specified timeout
+ */
+
+static int
+winProcessXEventsTimeout (HWND hwnd, int iWindow, Display *pDisplay,
+			  Bool fUseUnicode, int iTimeoutSec)
+{
+  int			iConnNumber;
+  struct timeval	tv;
+  int			iReturn;
+  DWORD			dwStopTime = (GetTickCount () / 1000) + iTimeoutSec;
+
+  /* We need to ensure that all pending events are processed */
+  XSync (pDisplay, FALSE);
+
+  /* Get our connection number */
+  iConnNumber = ConnectionNumber (pDisplay);
+
+  /* Loop for X events */
+  while (1)
+    {
+      fd_set		fdsRead;
+
+      /* Setup the file descriptor set */
+      FD_ZERO (&fdsRead);
+      FD_SET (iConnNumber, &fdsRead);
+
+      /* Adjust timeout */
+      tv.tv_sec = dwStopTime - (GetTickCount () / 1000);
+      tv.tv_usec = 0;
+
+      /* Break out if no time left */
+      if (tv.tv_sec < 0)
+	return WIN_XEVENTS_SUCCESS;
+
+      /* Wait for a Windows event or an X event */
+      iReturn = select (iConnNumber + 1,/* Highest fds number */
+			&fdsRead,	/* Read mask */
+			NULL,		/* No write mask */
+			NULL,		/* No exception mask */
+			&tv);		/* No timeout */
+      if (iReturn <= 0)
+	{
+	  ErrorF ("winProcessXEventsTimeout - Call to select () failed: %d.  "
+		  "Bailing.\n", iReturn);
+	  break;
+	}
+
+      /* Branch on which descriptor became active */
+      if (FD_ISSET (iConnNumber, &fdsRead))
+	{
+	  /* Process X events */
+	  /* Exit when we see that server is shutting down */
+	  iReturn = winClipboardFlushXEvents (hwnd,
+					      iWindow,
+					      pDisplay,
+					      fUseUnicode);
+	  if (WIN_XEVENTS_NOTIFY == iReturn
+	      || WIN_XEVENTS_CONVERT == iReturn)
+	    {
+	      /* Bail out if convert or notify processed */
+	      return iReturn;
+	    }
+	}
+    }
+
+  return WIN_XEVENTS_SUCCESS;
+}
+
+
+/*
+ * Process a given Windows message
+ */
+
+/* BPS - Define our own message, which we'll post to ourselves to facilitate
+ * resetting the delayed rendering mechanism after each paste from X app to
+ * Windows app. TODO - Perhaps move to win.h with the other WM_USER messages.
+ */
+#define WM_USER_PASTE_COMPLETE		(WM_USER + 1003)
+
+LRESULT CALLBACK
+winClipboardWindowProc (HWND hwnd, UINT message, 
+			WPARAM wParam, LPARAM lParam)
+{
+  static HWND		s_hwndNextViewer;
+  static Bool		s_fCBCInitialized;
+
+  /* Branch on message type */
+  switch (message)
+    {
+    case WM_DESTROY:
+      {
+	winDebug ("winClipboardWindowProc - WM_DESTROY\n");
+
+	/* Remove ourselves from the clipboard chain */
+	ChangeClipboardChain (hwnd, s_hwndNextViewer);
+	
+	s_hwndNextViewer = NULL;
+
+	PostQuitMessage (0);
+      }
+      return 0;
+
+
+    case WM_CREATE:
+      {
+	HWND first, next;
+	DWORD error_code = 0;
+	winDebug ("winClipboardWindowProc - WM_CREATE\n");
+	
+	first = GetClipboardViewer();			/* Get handle to first viewer in chain. */
+	if (first == hwnd) return 0;			/* Make sure it's not us! */
+	/* Add ourselves to the clipboard viewer chain */
+	next = SetClipboardViewer (hwnd);
+	error_code = GetLastError();
+	if (SUCCEEDED(error_code) && (next == first))	/* SetClipboardViewer must have succeeded, and the handle */
+		s_hwndNextViewer = next;		/* it returned must have been the first window in the chain */
+	else
+		s_fCBCInitialized = FALSE;
+      }
+      return 0;
+
+
+    case WM_CHANGECBCHAIN:
+      {
+	winDebug ("winClipboardWindowProc - WM_CHANGECBCHAIN: wParam(%x) "
+		  "lParam(%x) s_hwndNextViewer(%x)\n", 
+		  wParam, lParam, s_hwndNextViewer);
+
+	if ((HWND) wParam == s_hwndNextViewer)
+	  {
+	    s_hwndNextViewer = (HWND) lParam;
+	    if (s_hwndNextViewer == hwnd)
+	      {
+		s_hwndNextViewer = NULL;
+		winErrorFVerb (1, "winClipboardWindowProc - WM_CHANGECBCHAIN: "
+			       "attempted to set next window to ourselves.");
+	      }
+	  }
+	else if (s_hwndNextViewer)
+	  SendMessage (s_hwndNextViewer, message,
+		       wParam, lParam);
+
+      }
+      winDebug ("winClipboardWindowProc - WM_CHANGECBCHAIN: Exit\n");
+      return 0;
+
+    case WM_WM_REINIT:
+      {
+        /* Ensure that we're in the clipboard chain.  Some apps,
+         * WinXP's remote desktop for one, don't play nice with the
+         * chain.  This message is called whenever we receive a
+         * WM_ACTIVATEAPP message to ensure that we continue to
+         * receive clipboard messages.
+	 *
+	 * It might be possible to detect if we're still in the chain
+	 * by calling SendMessage (GetClipboardViewer(),
+	 * WM_DRAWCLIPBOARD, 0, 0); and then seeing if we get the
+	 * WM_DRAWCLIPBOARD message.  That, however, might be more
+	 * expensive than just putting ourselves back into the chain.
+	 */
+
+	HWND first, next;
+	DWORD error_code = 0;
+	winDebug ("winClipboardWindowProc - WM_WM_REINIT: Enter\n");
+
+	first = GetClipboardViewer();			/* Get handle to first viewer in chain. */
+	if (first == hwnd) return 0;			/* Make sure it's not us! */
+	winDebug ("  WM_WM_REINIT: Replacing us(%x) with %x at head "
+		  "of chain\n", hwnd, s_hwndNextViewer);
+	s_fCBCInitialized = FALSE;
+	ChangeClipboardChain (hwnd, s_hwndNextViewer);
+	s_hwndNextViewer = NULL;
+	s_fCBCInitialized = FALSE;
+	winDebug ("  WM_WM_REINIT: Putting us back at head of chain.\n");
+	first = GetClipboardViewer();			/* Get handle to first viewer in chain. */
+	if (first == hwnd) return 0;			/* Make sure it's not us! */
+	next = SetClipboardViewer (hwnd);
+	error_code = GetLastError();
+	if (SUCCEEDED(error_code) && (next == first))	/* SetClipboardViewer must have succeeded, and the handle */
+		s_hwndNextViewer = next;		/* it returned must have been the first window in the chain */
+	else
+		s_fCBCInitialized = FALSE;
+      }
+      winDebug ("winClipboardWindowProc - WM_WM_REINIT: Exit\n");
+      return 0;
+
+
+    case WM_DRAWCLIPBOARD:
+      {
+	static Bool s_fProcessingDrawClipboard = FALSE;
+	Display	*pDisplay = g_pClipboardDisplay;
+	Window	iWindow = g_iClipboardWindow;
+	int	iReturn;
+
+	winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Enter\n");
+
+	/*
+	 * We've occasionally seen a loop in the clipboard chain.
+	 * Try and fix it on the first hint of recursion.
+	 */
+	if (! s_fProcessingDrawClipboard) 
+	  {
+	    s_fProcessingDrawClipboard = TRUE;
+	  }
+	else
+	  {
+	    /* Attempt to break the nesting by getting out of the chain, twice?, and then fix and bail */
+	    s_fCBCInitialized = FALSE;
+	    ChangeClipboardChain (hwnd, s_hwndNextViewer);
+	    winFixClipboardChain();
+	    winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+			   "Nested calls detected.  Re-initing.\n");
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+	    s_fProcessingDrawClipboard = FALSE;
+	    return 0;
+	  }
+
+	/* Bail on first message */
+	if (!s_fCBCInitialized)
+	  {
+	    s_fCBCInitialized = TRUE;
+	    s_fProcessingDrawClipboard = FALSE;
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+	    return 0;
+	  }
+
+	/*
+	 * NOTE: We cannot bail out when NULL == GetClipboardOwner ()
+	 * because some applications deal with the clipboard in a manner
+	 * that causes the clipboard owner to be NULL when they are in
+	 * fact taking ownership.  One example of this is the Win32
+	 * native compile of emacs.
+	 */
+	
+	/* Bail when we still own the clipboard */
+	if (hwnd == GetClipboardOwner ())
+	  {
+
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		    "We own the clipboard, returning.\n");
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+	    s_fProcessingDrawClipboard = FALSE;
+	    if (s_hwndNextViewer)
+		SendMessage (s_hwndNextViewer, message, wParam, lParam);
+	    return 0;
+	  }
+
+	/*
+	 * Do not take ownership of the X11 selections when something
+	 * other than CF_TEXT or CF_UNICODETEXT has been copied
+	 * into the Win32 clipboard.
+	 */
+	if (!IsClipboardFormatAvailable (CF_TEXT)
+	    && !IsClipboardFormatAvailable (CF_UNICODETEXT))
+	  {
+
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		    "Clipboard does not contain CF_TEXT nor "
+		    "CF_UNICODETEXT.\n");
+
+	    /*
+	     * We need to make sure that the X Server has processed
+	     * previous XSetSelectionOwner messages.
+	     */
+	    XSync (pDisplay, FALSE);
+	    
+	    /* Release PRIMARY selection if owned */
+	    iReturn = XGetSelectionOwner (pDisplay, XA_PRIMARY);
+	    if (iReturn == g_iClipboardWindow)
+	      {
+		winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+			"PRIMARY selection is owned by us.\n");
+		XSetSelectionOwner (pDisplay,
+				    XA_PRIMARY,
+				    None,
+				    CurrentTime);
+	      }
+	    else if (BadWindow == iReturn || BadAtom == iReturn)
+	      winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		      "XGetSelection failed for PRIMARY: %d\n", iReturn);
+
+	    /* Release CLIPBOARD selection if owned */
+	    iReturn = XGetSelectionOwner (pDisplay,
+					  XInternAtom (pDisplay,
+						       "CLIPBOARD",
+						       False));
+	    if (iReturn == g_iClipboardWindow)
+	      {
+		winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+			"CLIPBOARD selection is owned by us.\n");
+		XSetSelectionOwner (pDisplay,
+				    XInternAtom (pDisplay,
+						 "CLIPBOARD",
+						 False),
+				    None,
+				    CurrentTime);
+	      }
+	    else if (BadWindow == iReturn || BadAtom == iReturn)
+	      winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		      "XGetSelection failed for CLIPBOARD: %d\n", iReturn);
+
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+	    s_fProcessingDrawClipboard = FALSE;
+	    if (s_hwndNextViewer)
+		SendMessage (s_hwndNextViewer, message, wParam, lParam);
+	    return 0;
+	  }
+
+	/* Reassert ownership of PRIMARY */	  
+	iReturn = XSetSelectionOwner (pDisplay,
+				      XA_PRIMARY,
+				      iWindow,
+				      CurrentTime);
+	if (iReturn == BadAtom || iReturn == BadWindow)
+	  {
+	    winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		    "Could not reassert ownership of PRIMARY\n");
+	  }
+	else
+	  {
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		    "Reasserted ownership of PRIMARY\n");
+	  }
+	
+	/* Reassert ownership of the CLIPBOARD */	  
+	iReturn = XSetSelectionOwner (pDisplay,
+				      XInternAtom (pDisplay,
+						   "CLIPBOARD",
+						   False),
+				      iWindow,
+				      CurrentTime);
+	if (iReturn == BadAtom || iReturn == BadWindow)
+	  {
+	    winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		    "Could not reassert ownership of CLIPBOARD\n");
+	  }
+	else
+	  {
+	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+		    "Reasserted ownership of CLIPBOARD\n");
+	  }
+	
+	/* Flush the pending SetSelectionOwner event now */
+	XFlush (pDisplay);
+
+	s_fProcessingDrawClipboard = FALSE;
+      }
+      winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+      /* Pass the message on the next window in the clipboard viewer chain */
+      if (s_hwndNextViewer)
+	SendMessage (s_hwndNextViewer, message, wParam, lParam);
+      return 0;
+
+
+    case WM_DESTROYCLIPBOARD:
+      /*
+       * NOTE: Intentionally do nothing.
+       * Changes in the Win32 clipboard are handled by WM_DRAWCLIPBOARD
+       * above.  We only process this message to conform to the specs
+       * for delayed clipboard rendering in Win32.  You might think
+       * that we need to release ownership of the X11 selections, but
+       * we do not, because a WM_DRAWCLIPBOARD message will closely
+       * follow this message and reassert ownership of the X11
+       * selections, handling the issue for us.
+       */
+      return 0;
+
+
+    case WM_RENDERFORMAT:
+    case WM_RENDERALLFORMATS:
+      {
+	int	iReturn;
+	Display *pDisplay = g_pClipboardDisplay;
+	Window	iWindow = g_iClipboardWindow;
+	Bool	fConvertToUnicode;
+
+	winDebug ("winClipboardWindowProc - WM_RENDER*FORMAT - Hello.\n");
+
+	/* Flag whether to convert to Unicode or not */
+	if (message == WM_RENDERALLFORMATS)
+	  fConvertToUnicode = FALSE;
+	else
+	  fConvertToUnicode = g_fUnicodeSupport && (CF_UNICODETEXT == wParam);
+
+	/* Request the selection contents */
+	iReturn = XConvertSelection (pDisplay,
+				     g_atomLastOwnedSelection,
+				     XInternAtom (pDisplay,
+						  "COMPOUND_TEXT", False),
+				     XInternAtom (pDisplay,
+						  "CYGX_CUT_BUFFER", False),
+				     iWindow,
+				     CurrentTime);
+	if (iReturn == BadAtom || iReturn == BadWindow)
+	  {
+	    winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMAT - "
+		    "XConvertSelection () failed\n");
+	    break;
+	  }
+
+	/* Special handling for WM_RENDERALLFORMATS */
+	if (message == WM_RENDERALLFORMATS)
+	  {
+	    /* We must open and empty the clipboard */
+
+	    /* Close clipboard if we have it open already */
+	    if (GetOpenClipboardWindow () == hwnd)
+	      {
+		CloseClipboard ();
+	      }	    
+
+	    if (!OpenClipboard (hwnd))
+	      {
+		winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMATS - "
+			"OpenClipboard () failed: %08x\n",
+			GetLastError ());
+		break;
+	      }
+	    
+	    if (!EmptyClipboard ())
+	      {
+		winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMATS - "
+			"EmptyClipboard () failed: %08x\n",
+		      GetLastError ());
+		break;
+	      }
+	  }
+
+	/* Process the SelectionNotify event */
+	iReturn = winProcessXEventsTimeout (hwnd,
+					    iWindow,
+					    pDisplay,
+					    fConvertToUnicode,
+					    WIN_POLL_TIMEOUT);
+	if (WIN_XEVENTS_CONVERT == iReturn)
+	  {
+	    /*
+	     * The selection was offered for conversion first, so we have
+	     * to process a second SelectionNotify event to get the actual
+	     * data in the selection.
+	     */
+	    iReturn = winProcessXEventsTimeout (hwnd,
+						iWindow,
+						pDisplay,
+						fConvertToUnicode,
+						WIN_POLL_TIMEOUT);
+	  }
+	
+	/*
+	 * The last of the up-to two calls to winProcessXEventsTimeout
+	 * from above had better have seen a notify event, or else we
+	 * are dealing with a buggy or old X11 app.  In these cases we
+	 * have to paste some fake data to the Win32 clipboard to
+	 * satisfy the requirement that we write something to it.
+	 */
+	if (WIN_XEVENTS_NOTIFY != iReturn)
+	  {
+	    /* Paste no data, to satisfy required call to SetClipboardData */
+	    if (g_fUnicodeSupport)
+	      SetClipboardData (CF_UNICODETEXT, NULL);
+	    SetClipboardData (CF_TEXT, NULL);
+	  }
+
+	/* BPS - Post ourselves a user message whose handler will reset the
+	 * delayed rendering mechanism after the paste is complete. This is
+	 * necessary because calling SetClipboardData() with a NULL argument
+	 * here will cause the data we just put on the clipboard to be lost!
+	 */
+	PostMessage(g_hwndClipboard, WM_USER_PASTE_COMPLETE, 0, 0);
+
+	/* Special handling for WM_RENDERALLFORMATS */
+	if (message == WM_RENDERALLFORMATS)
+	  {
+	    /* We must close the clipboard */
+	    
+	    if (!CloseClipboard ())
+	      {
+	      winErrorFVerb (1, "winClipboardWindowProc - WM_RENDERALLFORMATS - "
+		      "CloseClipboard () failed: %08x\n",
+		      GetLastError ());
+	      break;
+	      }
+	  }
+
+	winDebug ("winClipboardWindowProc - WM_RENDER*FORMAT - Returning.\n");
+	return 0;
+      }
+    /* BPS - This WM_USER message is posted by us. It gives us the opportunity
+     * to reset the delayed rendering mechanism after each and every paste
+     * from an X app to a Windows app. Without such a mechanism, subsequent
+     * changes of selection in the X app owning the selection are not
+     * reflected in pastes into Windows apps, since Windows won't send us the
+     * WM_RENDERFORMAT message unless someone has set changed data (or NULL)
+     * on the clipboard. */
+    case WM_USER_PASTE_COMPLETE:
+      {
+	if (hwnd != GetClipboardOwner ())
+	  /* In case we've lost the selection since posting the message */
+	  return 0;
+	winDebug ("winClipboardWindowProc - WM_USER_PASTE_COMPLETE\n");
+
+	/* Set up for another delayed rendering callback */
+	OpenClipboard (g_hwndClipboard);
+
+	/* Take ownership of the Windows clipboard */
+	EmptyClipboard ();
+
+	/* Advertise Unicode if we support it */
+	if (g_fUnicodeSupport)
+	  SetClipboardData (CF_UNICODETEXT, NULL);
+
+	/* Always advertise regular text */
+	SetClipboardData (CF_TEXT, NULL);
+
+	/* Release the clipboard */
+	CloseClipboard ();
+      }
+      return 0;
+    }
+
+  /* Let Windows perform default processing for unhandled messages */
+  return DefWindowProc (hwnd, message, wParam, lParam);
+}
+
+
+/*
+ * Process any pending Windows messages
+ */
+
+BOOL
+winClipboardFlushWindowsMessageQueue (HWND hwnd)
+{
+  MSG			msg;
+
+  /* Flush the messaging window queue */
+  /* NOTE: Do not pass the hwnd of our messaging window to PeekMessage,
+   * as this will filter out many non-window-specific messages that
+   * are sent to our thread, such as WM_QUIT.
+   */
+  while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
+    {
+      /* Dispatch the message if not WM_QUIT */
+      if (msg.message == WM_QUIT)
+	return FALSE;
+      else
+	DispatchMessage (&msg);
+    }
+  
+  return TRUE;
+}
diff --git a/hw/xwin/winclipboardwrappers.c b/hw/xwin/winclipboardwrappers.c
new file mode 100755
index 0000000..2cfe0ff
--- /dev/null
+++ b/hw/xwin/winclipboardwrappers.c
@@ -0,0 +1,541 @@
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "dixstruct.h"
+#include <X11/Xatom.h>
+
+
+/*
+ * Constants
+ */
+
+#define CLIP_NUM_SELECTIONS		2
+#define CLIP_OWN_PRIMARY		0
+#define CLIP_OWN_CLIPBOARD		1
+
+
+/*
+ * Local function prototypes
+ */
+
+DISPATCH_PROC(winProcEstablishConnection);
+DISPATCH_PROC(winProcQueryTree);
+DISPATCH_PROC(winProcSetSelectionOwner);
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool		g_fUnicodeSupport;
+extern int		g_iNumScreens;
+extern unsigned int	g_uiAuthDataLen;
+extern char		*g_pAuthData;
+extern Bool		g_fXdmcpEnabled;
+extern Bool		g_fClipboardLaunched;
+extern Bool		g_fClipboardStarted;
+extern Bool		g_fClipboard;
+extern Window		g_iClipboardWindow;
+extern Atom		g_atomLastOwnedSelection;
+extern HWND		g_hwndClipboard;
+
+extern winDispatchProcPtr	winProcEstablishConnectionOrig;
+extern winDispatchProcPtr	winProcQueryTreeOrig;
+extern winDispatchProcPtr	winProcSetSelectionOwnerOrig;
+
+
+/*
+ * Wrapper for internal QueryTree function.
+ * Hides the clipboard client when it is the only client remaining.
+ */
+
+int
+winProcQueryTree (ClientPtr client)
+{
+  int			iReturn;
+
+  /*
+   * This procedure is only used for initialization.
+   * We can unwrap the original procedure at this point
+   * so that this function is no longer called until the
+   * server resets and the function is wrapped again.
+   */
+  ProcVector[X_QueryTree] = winProcQueryTreeOrig;
+
+  /*
+   * Call original function and bail if it fails.
+   * NOTE: We must do this first, since we need XdmcpOpenDisplay
+   * to be called before we initialize our clipboard client.
+   */
+  iReturn = (*winProcQueryTreeOrig) (client);
+  if (iReturn != 0)
+    {
+      ErrorF ("winProcQueryTree - ProcQueryTree failed, bailing.\n");
+      return iReturn;
+    }
+
+  /* Make errors more obvious */
+  winProcQueryTreeOrig = NULL;
+
+  /* Do nothing if clipboard is not enabled */
+  if (!g_fClipboard)
+    {
+      ErrorF ("winProcQueryTree - Clipboard is not enabled, "
+	      "returning.\n");
+      return iReturn;
+    }
+
+  /* If the clipboard client has already been started, abort */
+  if (g_fClipboardLaunched)
+    {
+      ErrorF ("winProcQueryTree - Clipboard client already "
+	      "launched, returning.\n");
+      return iReturn;
+    }
+
+  /* Startup the clipboard client if clipboard mode is being used */
+  if (g_fXdmcpEnabled && g_fClipboard)
+    {
+      /*
+       * NOTE: The clipboard client is started here for a reason:
+       * 1) Assume you are using XDMCP (e.g. XWin -query %hostname%)
+       * 2) If the clipboard client attaches during X Server startup,
+       *    then it becomes the "magic client" that causes the X Server
+       *    to reset if it exits.
+       * 3) XDMCP calls KillAllClients when it starts up.
+       * 4) The clipboard client is a client, so it is killed.
+       * 5) The clipboard client is the "magic client", so the X Server
+       *    resets itself.
+       * 6) This repeats ad infinitum.
+       * 7) We avoid this by waiting until at least one client (could
+       *    be XDM, could be another client) connects, which makes it
+       *    almost certain that the clipboard client will not connect
+       *    until after XDM when using XDMCP.
+       * 8) Unfortunately, there is another problem.
+       * 9) XDM walks the list of windows with XQueryTree,
+       *    killing any client it finds with a window.
+       * 10)Thus, when using XDMCP we wait until the first call
+       *    to ProcQueryTree before we startup the clipboard client.
+       *    This should prevent XDM from finding the clipboard client,
+       *    since it has not yet created a window.
+       * 11)Startup when not using XDMCP is handled in
+       *    winProcEstablishConnection.
+       */
+      
+      /* Create the clipboard client thread */
+      if (!winInitClipboard ())
+	{
+	  ErrorF ("winProcQueryTree - winClipboardInit "
+		  "failed.\n");
+	  return iReturn;
+	}
+      
+      ErrorF ("winProcQueryTree - winInitClipboard returned.\n");
+    }
+  
+  /* Flag that clipboard client has been launched */
+  g_fClipboardLaunched = TRUE;
+
+  return iReturn;
+}
+
+
+/*
+ * Wrapper for internal EstablishConnection function.
+ * Initializes internal clients that must not be started until
+ * an external client has connected.
+ */
+
+int
+winProcEstablishConnection (ClientPtr client)
+{
+  int			iReturn;
+  static int		s_iCallCount = 0;
+  static unsigned long	s_ulServerGeneration = 0;
+
+  ErrorF ("winProcEstablishConnection - Hello\n");
+
+  /* Do nothing if clipboard is not enabled */
+  if (!g_fClipboard)
+    {
+      ErrorF ("winProcEstablishConnection - Clipboard is not enabled, "
+	      "returning.\n");
+      
+      /* Unwrap the original function, call it, and return */
+      InitialVector[2] = winProcEstablishConnectionOrig;
+      iReturn = (*winProcEstablishConnectionOrig) (client);
+      winProcEstablishConnectionOrig = NULL;
+      return iReturn;
+    }
+
+  /* Watch for server reset */
+  if (s_ulServerGeneration != serverGeneration)
+    {
+      /* Save new generation number */
+      s_ulServerGeneration = serverGeneration;
+
+      /* Reset call count */
+      s_iCallCount = 0;
+    }
+
+  /* Increment call count */
+  ++s_iCallCount;
+
+  /* Wait for second call when Xdmcp is enabled */
+  if (g_fXdmcpEnabled
+      && !g_fClipboardLaunched
+      && s_iCallCount < 4)
+    {
+      ErrorF ("winProcEstablishConnection - Xdmcp enabled, waiting to "
+	      "start clipboard client until fourth call.\n");
+      return (*winProcEstablishConnectionOrig) (client);
+    }
+
+  /*
+   * This procedure is only used for initialization.
+   * We can unwrap the original procedure at this point
+   * so that this function is no longer called until the
+   * server resets and the function is wrapped again.
+   */
+  InitialVector[2] = winProcEstablishConnectionOrig;
+
+  /*
+   * Call original function and bail if it fails.
+   * NOTE: We must do this first, since we need XdmcpOpenDisplay
+   * to be called before we initialize our clipboard client.
+   */
+  iReturn = (*winProcEstablishConnectionOrig) (client);
+  if (iReturn != 0)
+    {
+      ErrorF ("winProcEstablishConnection - ProcEstablishConnection "
+	      "failed, bailing.\n");
+      return iReturn;
+    }
+
+  /* Clear original function pointer */
+  winProcEstablishConnectionOrig = NULL;
+
+  /* If the clipboard client has already been started, abort */
+  if (g_fClipboardLaunched)
+    {
+      ErrorF ("winProcEstablishConnection - Clipboard client already "
+	      "launched, returning.\n");
+      return iReturn;
+    }
+
+  /* Startup the clipboard client if clipboard mode is being used */
+  if (g_fClipboard)
+    {
+      /*
+       * NOTE: The clipboard client is started here for a reason:
+       * 1) Assume you are using XDMCP (e.g. XWin -query %hostname%)
+       * 2) If the clipboard client attaches during X Server startup,
+       *    then it becomes the "magic client" that causes the X Server
+       *    to reset if it exits.
+       * 3) XDMCP calls KillAllClients when it starts up.
+       * 4) The clipboard client is a client, so it is killed.
+       * 5) The clipboard client is the "magic client", so the X Server
+       *    resets itself.
+       * 6) This repeats ad infinitum.
+       * 7) We avoid this by waiting until at least one client (could
+       *    be XDM, could be another client) connects, which makes it
+       *    almost certain that the clipboard client will not connect
+       *    until after XDM when using XDMCP.
+       * 8) Unfortunately, there is another problem.
+       * 9) XDM walks the list of windows with XQueryTree,
+       *    killing any client it finds with a window.
+       * 10)Thus, when using XDMCP we wait until the second call
+       *    to ProcEstablishCeonnection before we startup the clipboard
+       *    client.  This should prevent XDM from finding the clipboard
+       *    client, since it has not yet created a window.
+       */
+      
+      /* Create the clipboard client thread */
+      if (!winInitClipboard ())
+	{
+	  ErrorF ("winProcEstablishConnection - winClipboardInit "
+		  "failed.\n");
+	  return iReturn;
+	}
+      
+      ErrorF ("winProcEstablishConnection - winInitClipboard returned.\n");
+    }
+  
+  /* Flag that clipboard client has been launched */
+  g_fClipboardLaunched = TRUE;
+
+  return iReturn;
+}
+
+
+/*
+ * Wrapper for internal SetSelectionOwner function.
+ * Grabs ownership of Windows clipboard when X11 clipboard owner changes.
+ */
+
+int
+winProcSetSelectionOwner (ClientPtr client)
+{
+  int			i;
+  DrawablePtr		pDrawable;
+  WindowPtr		pWindow = None;
+  Bool			fOwnedToNotOwned = FALSE;
+  static Window		s_iOwners[CLIP_NUM_SELECTIONS] = {None};
+  static unsigned long	s_ulServerGeneration = 0;
+  REQUEST(xSetSelectionOwnerReq);
+  
+  REQUEST_SIZE_MATCH(xSetSelectionOwnerReq);
+
+#if 0
+  ErrorF ("winProcSetSelectionOwner - Hello.\n");
+#endif
+
+  /* Watch for server reset */
+  if (s_ulServerGeneration != serverGeneration)
+    {
+      /* Save new generation number */
+      s_ulServerGeneration = serverGeneration;
+
+      /* Initialize static variables */
+      for (i = 0; i < CLIP_NUM_SELECTIONS; ++i)
+	s_iOwners[i] = None;
+    }
+
+  /* Abort if clipboard not completely initialized yet */
+  if (!g_fClipboardStarted)
+    {
+      ErrorF ("winProcSetSelectionOwner - Clipboard not yet started, "
+	      "aborting.\n");
+      goto winProcSetSelectionOwner_Done;
+    }
+  
+  /* Grab window if we have one */
+  if (None != stuff->window)
+    {
+      /* Grab the Window from the request */
+      int rc = dixLookupWindow(&pWindow, stuff->window, client, DixReadAccess);
+      if (rc != Success) {
+	  ErrorF ("winProcSetSelectionOwner - Found BadWindow, aborting.\n");
+	  goto winProcSetSelectionOwner_Done;
+      }
+    }
+
+  /* Now we either have a valid window or None */
+
+  /* Save selection owners for monitored selections, ignore other selections */
+  if (XA_PRIMARY == stuff->selection)
+    {
+      /* Look for owned -> not owned transition */
+      if (None == stuff->window
+	  && None != s_iOwners[CLIP_OWN_PRIMARY])
+	{
+	  fOwnedToNotOwned = TRUE;
+
+#if 0
+	  ErrorF ("winProcSetSelectionOwner - PRIMARY - Going from "
+		  "owned to not owned.\n");
+#endif
+
+	  /* Adjust last owned selection */
+	  if (None != s_iOwners[CLIP_OWN_CLIPBOARD])
+	    g_atomLastOwnedSelection = MakeAtom ("CLIPBOARD", 9, TRUE);
+	  else
+	    g_atomLastOwnedSelection = None;
+	}
+      
+      /* Save new selection owner or None */
+      s_iOwners[CLIP_OWN_PRIMARY] = stuff->window;
+
+#if 0
+      ErrorF ("winProcSetSelectionOwner - PRIMARY - Now owned by: %d\n",
+	      stuff->window);
+#endif
+    }
+  else if (MakeAtom ("CLIPBOARD", 9, TRUE) == stuff->selection)
+    {
+      /* Look for owned -> not owned transition */
+      if (None == stuff->window
+	  && None != s_iOwners[CLIP_OWN_CLIPBOARD])
+	{
+	  fOwnedToNotOwned = TRUE;
+	  
+#if 0
+	  ErrorF ("winProcSetSelectionOwner - CLIPBOARD - Going from "
+		  "owned to not owned.\n");
+#endif
+
+	  /* Adjust last owned selection */
+	  if (None != s_iOwners[CLIP_OWN_PRIMARY])
+	    g_atomLastOwnedSelection = XA_PRIMARY;
+	  else
+	    g_atomLastOwnedSelection = None;
+	}
+      
+      /* Save new selection owner or None */
+      s_iOwners[CLIP_OWN_CLIPBOARD] = stuff->window;
+
+#if 0
+      ErrorF ("winProcSetSelectionOwner - CLIPBOARD - Now owned by: %d\n",
+	      stuff->window);
+#endif
+    }
+  else
+    goto winProcSetSelectionOwner_Done;
+
+  /*
+   * At this point, if one of the selections is still owned by the 
+   * clipboard manager then it should be marked as unowned since
+   * we will be taking ownership of the Win32 clipboard.
+   */
+  if (g_iClipboardWindow == s_iOwners[CLIP_OWN_PRIMARY])
+    s_iOwners[CLIP_OWN_PRIMARY] = None;
+  if (g_iClipboardWindow == s_iOwners[CLIP_OWN_CLIPBOARD])
+    s_iOwners[CLIP_OWN_CLIPBOARD] = None;
+
+  /*
+   * Handle case when selection is being disowned,
+   * WM_DRAWCLIPBOARD did not do the disowning,
+   * both monitored selections are no longer owned,
+   * an owned to not owned transition was detected,
+   * and we currently own the Win32 clipboard.
+   */
+  if (None == stuff->window
+      && (None == s_iOwners[CLIP_OWN_PRIMARY]
+	  || g_iClipboardWindow == s_iOwners[CLIP_OWN_PRIMARY])
+      && (None == s_iOwners[CLIP_OWN_CLIPBOARD]
+	  || g_iClipboardWindow == s_iOwners[CLIP_OWN_CLIPBOARD])
+      && fOwnedToNotOwned
+      && g_hwndClipboard != NULL
+      && g_hwndClipboard == GetClipboardOwner ())
+    {
+#if 0
+      ErrorF ("winProcSetSelectionOwner - We currently own the "
+	      "clipboard and neither the PRIMARY nor the CLIPBOARD "
+	      "selections are owned, releasing ownership of Win32 "
+	      "clipboard.\n");
+#endif
+      
+      /* Release ownership of the Windows clipboard */
+      OpenClipboard (NULL);
+      EmptyClipboard ();
+      CloseClipboard ();
+
+      /* Clear X selection ownership (might still be marked as us owning) */
+      s_iOwners[CLIP_OWN_PRIMARY] = None;
+      s_iOwners[CLIP_OWN_CLIPBOARD] = None;
+      
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Abort if no window at this point */
+  if (None == stuff->window)
+    {
+#if 0
+      ErrorF ("winProcSetSelectionOwner - No window, returning.\n");
+#endif
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Abort if invalid selection */
+  if (!ValidAtom (stuff->selection))
+    {
+      ErrorF ("winProcSetSelectionOwner - Found BadAtom, aborting.\n");
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Cast Window to Drawable */
+  pDrawable = (DrawablePtr) pWindow;
+  
+  /* Abort if clipboard manager is owning the selection */
+  if (pDrawable->id == g_iClipboardWindow)
+    {
+#if 0
+      ErrorF ("winProcSetSelectionOwner - We changed ownership, "
+	      "aborting.\n");
+#endif
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Abort if root window is taking ownership */
+  if (pDrawable->id == 0)
+    {
+      ErrorF ("winProcSetSelectionOwner - Root window taking ownership, "
+	      "aborting\n");
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Close clipboard if we have it open already */
+  if (GetOpenClipboardWindow () == g_hwndClipboard)
+    {
+      CloseClipboard ();
+    }
+
+  /* Access the Windows clipboard */
+  if (!OpenClipboard (g_hwndClipboard))
+    {
+      ErrorF ("winProcSetSelectionOwner - OpenClipboard () failed: %08x\n",
+	      (int) GetLastError ());
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Take ownership of the Windows clipboard */
+  if (!EmptyClipboard ())
+    {
+      ErrorF ("winProcSetSelectionOwner - EmptyClipboard () failed: %08x\n",
+	      (int) GetLastError ());
+      goto winProcSetSelectionOwner_Done;
+    }
+
+  /* Advertise Unicode if we support it */
+  if (g_fUnicodeSupport)
+    SetClipboardData (CF_UNICODETEXT, NULL);
+
+  /* Always advertise regular text */
+  SetClipboardData (CF_TEXT, NULL);
+
+  /* Save handle to last owned selection */
+  g_atomLastOwnedSelection = stuff->selection;
+
+  /* Release the clipboard */
+  if (!CloseClipboard ())
+    {
+      ErrorF ("winProcSetSelectionOwner - CloseClipboard () failed: "
+	      "%08x\n",
+	      (int) GetLastError ());
+      goto winProcSetSelectionOwner_Done;
+    }
+
+ winProcSetSelectionOwner_Done:
+  return (*winProcSetSelectionOwnerOrig) (client);
+}
diff --git a/hw/xwin/winclipboardxevents.c b/hw/xwin/winclipboardxevents.c
new file mode 100644
index 0000000..d4c617b
--- /dev/null
+++ b/hw/xwin/winclipboardxevents.c
@@ -0,0 +1,796 @@
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "winclipboard.h"
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool		g_fUnicodeSupport;
+
+
+/*
+ * Process any pending X events
+ */
+
+int
+winClipboardFlushXEvents (HWND hwnd,
+			  int iWindow,
+			  Display *pDisplay,
+			  Bool fUseUnicode)
+{
+  Atom			atomLocalProperty = XInternAtom (pDisplay,
+							 WIN_LOCAL_PROPERTY,
+							 False);
+  Atom			atomUTF8String = XInternAtom (pDisplay,
+						      "UTF8_STRING",
+						      False);
+  Atom			atomCompoundText = XInternAtom (pDisplay,
+							"COMPOUND_TEXT",
+							False);
+  Atom			atomTargets = XInternAtom (pDisplay,
+						   "TARGETS",
+						   False);
+
+  /* Process all pending events */
+  while (XPending (pDisplay))
+    {
+      XTextProperty		xtpText = {0};
+      XEvent			event;
+      XSelectionEvent		eventSelection;
+      unsigned long		ulReturnBytesLeft;
+      unsigned char		*pszReturnData = NULL;
+      char			*pszGlobalData = NULL;
+      int			iReturn;
+      HGLOBAL			hGlobal = NULL;
+      XICCEncodingStyle		xiccesStyle;
+      int			iConvertDataLen = 0;
+      char			*pszConvertData = NULL;
+      char			*pszTextList[2] = {NULL};
+      int			iCount;
+      char			**ppszTextList = NULL;
+      wchar_t			*pwszUnicodeStr = NULL;
+      int			iUnicodeLen = 0;
+      int			iReturnDataLen = 0;
+      int			i;
+      Bool			fAbort = FALSE;
+      Bool			fCloseClipboard = FALSE;
+      Bool			fSetClipboardData = TRUE;
+
+      /* Get the next event - will not block because one is ready */
+      XNextEvent (pDisplay, &event);
+
+      /* Branch on the event type */
+      switch (event.type)
+	{
+	  /*
+	   * SelectionRequest
+	   */
+
+	case SelectionRequest:
+#if 0
+	  {
+	    char			*pszAtomName = NULL;
+	    
+	    ErrorF ("SelectionRequest - target %d\n",
+		    event.xselectionrequest.target);
+	    
+	    pszAtomName = XGetAtomName (pDisplay,
+					event.xselectionrequest.target);
+	    ErrorF ("SelectionRequest - Target atom name %s\n", pszAtomName);
+	    XFree (pszAtomName);
+	    pszAtomName = NULL;
+	  }
+#endif
+
+	  /* Abort if invalid target type */
+	  if (event.xselectionrequest.target != XA_STRING
+	      && event.xselectionrequest.target != atomUTF8String
+	      && event.xselectionrequest.target != atomCompoundText
+	      && event.xselectionrequest.target != atomTargets)
+	    {
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+
+	  /* Handle targets type of request */
+	  if (event.xselectionrequest.target == atomTargets)
+	    {
+	      Atom atomTargetArr[] = {atomTargets,
+				      atomCompoundText,
+				      atomUTF8String,
+				      XA_STRING};
+
+	      /* Try to change the property */
+	      iReturn = XChangeProperty (pDisplay,
+					 event.xselectionrequest.requestor,
+					 event.xselectionrequest.property,
+					 XA_ATOM,
+					 32,
+					 PropModeReplace,
+					 (unsigned char *) atomTargetArr,
+					 (sizeof (atomTargetArr)
+					  / sizeof (atomTargetArr[0])));
+	      if (iReturn == BadAlloc
+		  || iReturn == BadAtom
+		  || iReturn == BadMatch
+		  || iReturn == BadValue
+		  || iReturn == BadWindow)
+		{
+		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+			  "XChangeProperty failed: %d\n",
+			  iReturn);
+		}
+
+	      /* Setup selection notify xevent */
+	      eventSelection.type	= SelectionNotify;
+	      eventSelection.send_event	= True;
+	      eventSelection.display	= pDisplay;
+	      eventSelection.requestor	= event.xselectionrequest.requestor;
+	      eventSelection.selection	= event.xselectionrequest.selection;
+	      eventSelection.target	= event.xselectionrequest.target;
+	      eventSelection.property	= event.xselectionrequest.property;
+	      eventSelection.time	= event.xselectionrequest.time;
+
+	      /*
+	       * Notify the requesting window that
+	       * the operation has completed
+	       */
+	      iReturn = XSendEvent (pDisplay,
+				    eventSelection.requestor,
+				    False,
+				    0L,
+				    (XEvent *) &eventSelection);
+	      if (iReturn == BadValue || iReturn == BadWindow)
+		{
+		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+			  "XSendEvent () failed\n");
+		}
+	      break;
+	    }
+
+	  /* Check that clipboard format is available */
+	  if (fUseUnicode
+	      && !IsClipboardFormatAvailable (CF_UNICODETEXT))
+	    {
+	      ErrorF ("winClipboardFlushXEvents - CF_UNICODETEXT is not "
+		      "available from Win32 clipboard.  Aborting.\n");
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+	  else if (!fUseUnicode
+		   && !IsClipboardFormatAvailable (CF_TEXT))
+	    {
+	      ErrorF ("winClipboardFlushXEvents - CF_TEXT is not "
+		      "available from Win32 clipboard.  Aborting.\n");
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+
+	  /* Close clipboard if we have it open already */
+	  if (GetOpenClipboardWindow () == hwnd)
+	    {
+	      CloseClipboard ();
+	    }
+
+	  /* Access the clipboard */
+	  if (!OpenClipboard (hwnd))
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+		      "OpenClipboard () failed: %08x\n",
+		      GetLastError ());
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+	  
+	  /* Indicate that clipboard was opened */
+	  fCloseClipboard = TRUE;
+
+	  /* Setup the string style */
+	  if (event.xselectionrequest.target == XA_STRING)
+	    xiccesStyle = XStringStyle;
+#ifdef X_HAVE_UTF8_STRING
+	  else if (event.xselectionrequest.target == atomUTF8String)
+	    xiccesStyle = XUTF8StringStyle;
+#endif
+	  else if (event.xselectionrequest.target == atomCompoundText)
+	    xiccesStyle = XCompoundTextStyle;
+	  else
+	    xiccesStyle = XStringStyle;
+
+	  /*
+	   * FIXME: Can't pass CF_UNICODETEXT on Windows 95/98/Me
+	   */
+	  
+	  /* Get a pointer to the clipboard text, in desired format */
+	  if (fUseUnicode)
+	    {
+	      /* Retrieve clipboard data */
+	      hGlobal = GetClipboardData (CF_UNICODETEXT);
+	    }
+	  else
+	    {
+	      /* Retrieve clipboard data */
+	      hGlobal = GetClipboardData (CF_TEXT);
+	    }
+	  if (!hGlobal)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+		      "GetClipboardData () failed: %08x\n",
+		      GetLastError ());
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+	  pszGlobalData = (char *) GlobalLock (hGlobal);
+
+	  /* Convert the Unicode string to UTF8 (MBCS) */
+	  if (fUseUnicode)
+	    {
+	      iConvertDataLen = WideCharToMultiByte (CP_UTF8,
+						     0,
+						     (LPCWSTR)pszGlobalData,
+						     -1,
+						     NULL,
+						     0,
+						     NULL,
+						     NULL);
+	      /* NOTE: iConvertDataLen includes space for null terminator */
+	      pszConvertData = (char *) malloc (iConvertDataLen);
+	      WideCharToMultiByte (CP_UTF8,
+				   0,
+				   (LPCWSTR)pszGlobalData,
+				   -1,
+				   pszConvertData,
+				   iConvertDataLen,
+				   NULL,
+				   NULL);
+	    }
+	  else
+	    {
+	      pszConvertData = strdup (pszGlobalData);
+	      iConvertDataLen = strlen (pszConvertData) + 1;
+	    }
+
+	  /* Convert DOS string to UNIX string */
+	  winClipboardDOStoUNIX (pszConvertData, strlen (pszConvertData));
+
+	  /* Setup our text list */
+	  pszTextList[0] = pszConvertData;
+	  pszTextList[1] = NULL;
+
+	  /* Initialize the text property */
+	  xtpText.value = NULL;
+
+	  /* Create the text property from the text list */
+	  if (fUseUnicode)
+	    {
+#ifdef X_HAVE_UTF8_STRING
+	      iReturn = Xutf8TextListToTextProperty (pDisplay,
+						     pszTextList,
+						     1,
+						     xiccesStyle,
+						     &xtpText);
+#endif
+	    }
+	  else
+	    {
+	      iReturn = XmbTextListToTextProperty (pDisplay,
+						   pszTextList,
+						   1,
+						   xiccesStyle,
+						   &xtpText);
+	    }
+	  if (iReturn == XNoMemory || iReturn == XLocaleNotSupported)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+		      "X*TextListToTextProperty failed: %d\n",
+		      iReturn);
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+	  
+	  /* Free the converted string */
+	  free (pszConvertData);
+	  pszConvertData = NULL;
+
+	  /* Copy the clipboard text to the requesting window */
+	  iReturn = XChangeProperty (pDisplay,
+				     event.xselectionrequest.requestor,
+				     event.xselectionrequest.property,
+				     event.xselectionrequest.target,
+				     8,
+				     PropModeReplace,
+				     xtpText.value,
+				     xtpText.nitems);
+	  if (iReturn == BadAlloc || iReturn == BadAtom
+	      || iReturn == BadMatch || iReturn == BadValue
+	      || iReturn == BadWindow)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+		      "XChangeProperty failed: %d\n",
+		      iReturn);
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+
+	  /* Release the clipboard data */
+	  GlobalUnlock (hGlobal);
+	  pszGlobalData = NULL;
+
+	  /* Clean up */
+	  XFree (xtpText.value);
+	  xtpText.value = NULL;
+
+	  /* Setup selection notify event */
+	  eventSelection.type = SelectionNotify;
+	  eventSelection.send_event = True;
+	  eventSelection.display = pDisplay;
+	  eventSelection.requestor = event.xselectionrequest.requestor;
+	  eventSelection.selection = event.xselectionrequest.selection;
+	  eventSelection.target = event.xselectionrequest.target;
+	  eventSelection.property = event.xselectionrequest.property;
+	  eventSelection.time = event.xselectionrequest.time;
+
+	  /* Notify the requesting window that the operation has completed */
+	  iReturn = XSendEvent (pDisplay,
+				eventSelection.requestor,
+				False,
+				0L,
+				(XEvent *) &eventSelection);
+	  if (iReturn == BadValue || iReturn == BadWindow)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+		      "XSendEvent () failed\n");
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionRequest_Done;
+	    }
+
+	winClipboardFlushXEvents_SelectionRequest_Done:
+	  /* Free allocated resources */
+	  if (xtpText.value)
+	    XFree (xtpText.value);
+	  if (pszConvertData)
+	    free (pszConvertData);
+	  if (hGlobal && pszGlobalData)
+	    GlobalUnlock (hGlobal);
+	  
+	  /*
+	   * Send a SelectionNotify event to the requesting
+	   * client when we abort.
+	   */
+	  if (fAbort)
+	    {
+	      /* Setup selection notify event */
+	      eventSelection.type = SelectionNotify;
+	      eventSelection.send_event = True;
+	      eventSelection.display = pDisplay;
+	      eventSelection.requestor = event.xselectionrequest.requestor;
+	      eventSelection.selection = event.xselectionrequest.selection;
+	      eventSelection.target = event.xselectionrequest.target;
+	      eventSelection.property = None;
+	      eventSelection.time = event.xselectionrequest.time;
+
+	      /* Notify the requesting window that the operation is complete */
+	      iReturn = XSendEvent (pDisplay,
+				    eventSelection.requestor,
+				    False,
+				    0L,
+				    (XEvent *) &eventSelection);
+	      if (iReturn == BadValue || iReturn == BadWindow)
+		{
+		  /*
+		   * Should not be a problem if XSendEvent fails because
+		   * the client may simply have exited.
+		   */
+		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+			  "XSendEvent () failed for abort event.\n");
+		}
+	    }
+
+	  /* Close clipboard if it was opened */
+	  if (fCloseClipboard)
+	    CloseClipboard ();
+	  break;
+
+
+	  /*
+	   * SelectionNotify
+	   */ 
+
+	case SelectionNotify:
+#if 0
+	  ErrorF ("winClipboardFlushXEvents - SelectionNotify\n");
+	  {
+	    char		*pszAtomName;
+	    
+	    pszAtomName = XGetAtomName (pDisplay,
+					event.xselection.selection);
+
+	    ErrorF ("winClipboardFlushXEvents - SelectionNotify - ATOM: %s\n",
+		    pszAtomName);
+	    
+	    XFree (pszAtomName);
+	  }
+#endif
+
+
+	  /*
+	   * Request conversion of UTF8 and CompoundText targets.
+	   */
+	  if (event.xselection.property == None)
+	    {
+	      if (event.xselection.target == XA_STRING)
+		{
+#if 0
+		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			  "XA_STRING\n");
+#endif
+		  return WIN_XEVENTS_CONVERT;
+		}
+	      else if (event.xselection.target == atomUTF8String)
+		{
+#if 0
+		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			  "Requesting conversion of UTF8 target.\n");
+#endif
+		  iReturn = XConvertSelection (pDisplay,
+					       event.xselection.selection,
+					       XA_STRING,
+					       atomLocalProperty,
+					       iWindow,
+					       CurrentTime);
+		  if (iReturn != Success)
+		    {
+		      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			      "XConvertSelection () failed for UTF8String, "
+			      "aborting: %d\n",
+			      iReturn);
+		      break;
+		    }
+
+		  /* Process the ConvertSelection event */
+		  XFlush (pDisplay);
+		  return WIN_XEVENTS_CONVERT;
+		}
+#ifdef X_HAVE_UTF8_STRING
+	      else if (event.xselection.target == atomCompoundText)
+		{
+#if 0
+		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			  "Requesting conversion of CompoundText target.\n");
+#endif
+		  iReturn = XConvertSelection (pDisplay,
+					       event.xselection.selection,
+					       atomUTF8String,
+					       atomLocalProperty,
+					       iWindow,
+					       CurrentTime);
+		  if (iReturn != Success)
+		    {
+		      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			      "XConvertSelection () failed for CompoundText, "
+			      "aborting: %d\n",
+			      iReturn);
+		      break;
+		    }
+
+		  /* Process the ConvertSelection event */
+		  XFlush (pDisplay);
+		  return WIN_XEVENTS_CONVERT;
+		}
+#endif
+	      else
+		{
+		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			  "Unknown format.  Cannot request conversion, "
+			  "aborting.\n");
+		  break;
+		}
+	    }
+
+	  /* Retrieve the size of the stored data */
+	  iReturn = XGetWindowProperty (pDisplay,
+					iWindow,
+					atomLocalProperty,
+					0,
+					0, /* Don't get data, just size */
+					False,
+					AnyPropertyType,
+					&xtpText.encoding,
+					&xtpText.format,
+					&xtpText.nitems,
+					&ulReturnBytesLeft,
+					&xtpText.value);
+	  if (iReturn != Success)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+		      "XGetWindowProperty () failed, aborting: %d\n",
+		      iReturn);
+	      break;
+	    }
+
+#if 0
+	  ErrorF ("SelectionNotify - returned data %d left %d\n",
+		  xtpText.nitems, ulReturnBytesLeft);
+#endif
+
+	  /* Request the selection data */
+	  iReturn = XGetWindowProperty (pDisplay,
+					iWindow,
+					atomLocalProperty,
+					0,
+					ulReturnBytesLeft,
+					False,
+					AnyPropertyType,
+					&xtpText.encoding,
+					&xtpText.format,
+					&xtpText.nitems,
+					&ulReturnBytesLeft,
+					&xtpText.value);
+	  if (iReturn != Success)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+		      "XGetWindowProperty () failed, aborting: %d\n",
+		      iReturn);
+	      break;
+	    }
+
+#if 0
+	    {
+	      char		*pszAtomName = NULL;
+
+	      ErrorF ("SelectionNotify - returned data %d left %d\n",
+		      xtpText.nitems, ulReturnBytesLeft);
+	      
+	      pszAtomName = XGetAtomName(pDisplay, xtpText.encoding);
+	      ErrorF ("Notify atom name %s\n", pszAtomName);
+	      XFree (pszAtomName);
+	      pszAtomName = NULL;
+	    }
+#endif
+
+	  if (fUseUnicode)
+	    {
+#ifdef X_HAVE_UTF8_STRING
+	      /* Convert the text property to a text list */
+	      iReturn = Xutf8TextPropertyToTextList (pDisplay,
+						     &xtpText,
+						     &ppszTextList,
+						     &iCount);
+#endif
+	    }
+	  else
+	    {
+	      iReturn = XmbTextPropertyToTextList (pDisplay,
+						   &xtpText,
+						   &ppszTextList,
+						   &iCount);
+	    }
+	  if (iReturn == Success || iReturn > 0)
+	    {
+	      /* Conversion succeeded or some unconvertible characters */
+	      if (ppszTextList != NULL)
+		{
+		  for (i = 0; i < iCount; i++)
+		    {
+		      iReturnDataLen += strlen(ppszTextList[i]);
+		    }
+		  pszReturnData = malloc (iReturnDataLen + 1);
+		  pszReturnData[0] = '\0';
+		  for (i = 0; i < iCount; i++)
+		    {
+		      strcat (pszReturnData, ppszTextList[i]);
+		    }
+		}
+	      else
+		{
+		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+			  "X*TextPropertyToTextList list_return is NULL.\n");
+		  pszReturnData = malloc (1);
+		  pszReturnData[0] = '\0';
+		}
+	    }
+	  else
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+		      "X*TextPropertyToTextList returned: ");
+	      switch (iReturn)
+		{
+		case XNoMemory:
+		  ErrorF ("XNoMemory\n");
+		  break;
+		case XConverterNotFound:
+		  ErrorF ("XConverterNotFound\n");
+		  break;
+		default:
+		  ErrorF ("%d", iReturn);
+		  break;
+		}
+	      pszReturnData = malloc (1);
+	      pszReturnData[0] = '\0';
+	    }
+
+	  /* Free the data returned from XGetWindowProperty */
+	  if (ppszTextList)
+	    XFreeStringList (ppszTextList);
+	  ppszTextList = NULL;
+	  XFree (xtpText.value);
+	  xtpText.value = NULL;
+
+	  /* Convert the X clipboard string to DOS format */
+	  winClipboardUNIXtoDOS (&pszReturnData, strlen (pszReturnData));
+
+	  if (fUseUnicode)
+	    {
+	      /* Find out how much space needed to convert MBCS to Unicode */
+	      iUnicodeLen = MultiByteToWideChar (CP_UTF8,
+						 0,
+						 pszReturnData,
+						 -1,
+						 NULL,
+						 0);
+
+	      /* Allocate memory for the Unicode string */
+	      pwszUnicodeStr
+		= (wchar_t*) malloc (sizeof (wchar_t) * (iUnicodeLen + 1));
+	      if (!pwszUnicodeStr)
+		{
+		  ErrorF ("winClipboardFlushXEvents - SelectionNotify "
+			  "malloc failed for pwszUnicodeStr, aborting.\n");
+
+		  /* Abort */
+		  fAbort = TRUE;
+		  goto winClipboardFlushXEvents_SelectionNotify_Done;
+		}
+
+	      /* Do the actual conversion */
+	      MultiByteToWideChar (CP_UTF8,
+				   0,
+				   pszReturnData,
+				   -1,
+				   pwszUnicodeStr,
+				   iUnicodeLen);
+	      
+	      /* Allocate global memory for the X clipboard data */
+	      hGlobal = GlobalAlloc (GMEM_MOVEABLE,
+				     sizeof (wchar_t) * (iUnicodeLen + 1));
+	    }
+	  else
+	    {
+	      pszConvertData = strdup (pszReturnData);
+	      iConvertDataLen = strlen (pszConvertData) + 1;
+
+	      /* Allocate global memory for the X clipboard data */
+	      hGlobal = GlobalAlloc (GMEM_MOVEABLE, iConvertDataLen);
+	    }
+
+	  /* Check that global memory was allocated */
+	  if (!hGlobal)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - SelectionNotify "
+		      "GlobalAlloc failed, aborting: %ld\n",
+		      GetLastError ());
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionNotify_Done;
+	    }
+
+	  /* Obtain a pointer to the global memory */
+	  pszGlobalData = GlobalLock (hGlobal);
+	  if (pszGlobalData == NULL)
+	    {
+	      ErrorF ("winClipboardFlushXEvents - Could not lock global "
+		      "memory for clipboard transfer\n");
+
+	      /* Abort */
+	      fAbort = TRUE;
+	      goto winClipboardFlushXEvents_SelectionNotify_Done;
+	    }
+
+	  /* Copy the returned string into the global memory */
+	  if (fUseUnicode)
+	    {
+	      memcpy (pszGlobalData,
+		      pwszUnicodeStr,
+		      sizeof (wchar_t) * (iUnicodeLen + 1));
+	      free (pwszUnicodeStr);
+	      pwszUnicodeStr = NULL;
+	    }
+	  else
+	    {
+	      strcpy (pszGlobalData, pszConvertData);
+	      free (pszConvertData);
+	      pszConvertData = NULL;
+	    }
+
+	  /* Release the pointer to the global memory */
+	  GlobalUnlock (hGlobal);
+	  pszGlobalData = NULL;
+
+	  /* Push the selection data to the Windows clipboard */
+	  if (fUseUnicode)
+	    SetClipboardData (CF_UNICODETEXT, hGlobal);
+	  else
+	    SetClipboardData (CF_TEXT, hGlobal);
+
+	  /* Flag that SetClipboardData has been called */
+	  fSetClipboardData = FALSE;
+
+	  /*
+	   * NOTE: Do not try to free pszGlobalData, it is owned by
+	   * Windows after the call to SetClipboardData ().
+	   */
+
+	winClipboardFlushXEvents_SelectionNotify_Done:
+	  /* Free allocated resources */
+	  if (ppszTextList)
+	    XFreeStringList (ppszTextList);
+	  if (xtpText.value)
+	    XFree (xtpText.value);
+	  if (pszConvertData)
+	    free (pszConvertData);
+	  if (pwszUnicodeStr)
+	    free (pwszUnicodeStr);
+	  if (hGlobal && pszGlobalData)
+	    GlobalUnlock (hGlobal);
+	  if (fSetClipboardData && g_fUnicodeSupport)
+	    SetClipboardData (CF_UNICODETEXT, NULL);
+	  if (fSetClipboardData)
+	    SetClipboardData (CF_TEXT, NULL);
+	  return WIN_XEVENTS_NOTIFY;
+
+	default:
+	  break;
+	}
+    }
+
+  return WIN_XEVENTS_SUCCESS;
+}
diff --git a/hw/xwin/wincmap.c b/hw/xwin/wincmap.c
new file mode 100644
index 0000000..7ebe002
--- /dev/null
+++ b/hw/xwin/wincmap.c
@@ -0,0 +1,674 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * Local prototypes
+ */
+
+static int
+winListInstalledColormaps (ScreenPtr pScreen, Colormap *pmaps);
+
+static void
+winStoreColors (ColormapPtr pmap, int ndef, xColorItem *pdefs);
+
+static void
+winInstallColormap (ColormapPtr pmap);
+
+static void
+winUninstallColormap (ColormapPtr pmap);
+
+static void
+winResolveColor (unsigned short *pred,
+		 unsigned short *pgreen,
+		 unsigned short *pblue,
+		 VisualPtr	pVisual);
+
+static Bool
+winCreateColormap (ColormapPtr pmap);
+
+static void
+winDestroyColormap (ColormapPtr pmap);
+
+static Bool
+winGetPaletteDIB (ScreenPtr pScreen, ColormapPtr pcmap);
+
+static Bool
+winGetPaletteDD (ScreenPtr pScreen, ColormapPtr pcmap);
+
+
+/*
+ * Set screen functions for colormaps
+ */
+
+void
+winSetColormapFunctions (ScreenPtr pScreen)
+{
+  pScreen->CreateColormap = winCreateColormap;
+  pScreen->DestroyColormap = winDestroyColormap;
+  pScreen->InstallColormap = winInstallColormap;
+  pScreen->UninstallColormap = winUninstallColormap;
+  pScreen->ListInstalledColormaps = winListInstalledColormaps;
+  pScreen->StoreColors = winStoreColors;
+  pScreen->ResolveColor = winResolveColor;
+}
+
+
+/* See Porting Layer Definition - p. 30 */
+/*
+ * Walk the list of installed colormaps, filling the pmaps list
+ * with the resource ids of the installed maps, and return
+ * a count of the total number of installed maps.
+ */
+static int
+winListInstalledColormaps (ScreenPtr pScreen, Colormap *pmaps)
+{
+  winScreenPriv(pScreen);
+
+  /*
+   * There will only be one installed colormap, so we only need
+   * to return one id, and the count of installed maps will always
+   * be one.
+   */
+  *pmaps = pScreenPriv->pcmapInstalled->mid;
+  return 1;
+}
+
+
+/* See Porting Layer Definition - p. 30 */
+/* See Programming Windows - p. 663 */
+static void
+winInstallColormap (ColormapPtr pColormap)
+{
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  ColormapPtr		oldpmap = pScreenPriv->pcmapInstalled;
+
+#if CYGDEBUG
+  winDebug ("winInstallColormap\n");
+#endif
+ 
+  /* Did the colormap actually change? */
+  if (pColormap != oldpmap)
+    {
+#if CYGDEBUG
+      winDebug ("winInstallColormap - Colormap has changed, attempt "
+	      "to install.\n");
+#endif
+      
+      /* Was there a previous colormap? */
+      if (oldpmap != (ColormapPtr) None)
+	{
+	  /* There was a previous colormap; tell clients it is gone */
+	  WalkTree (pColormap->pScreen, TellLostMap, (char *)&oldpmap->mid);
+	}
+      
+      /* Install new colormap */
+      pScreenPriv->pcmapInstalled = pColormap;
+      WalkTree (pColormap->pScreen, TellGainedMap, (char *)&pColormap->mid);
+      
+      /* Call the engine specific colormap install procedure */
+      if (!((*pScreenPriv->pwinInstallColormap) (pColormap)))
+	{
+	  winErrorFVerb (2, "winInstallColormap - Screen specific colormap install "
+		  "procedure failed.  Continuing, but colors may be "
+		  "messed up from now on.\n");
+	}
+    }
+
+  /* Save a pointer to the newly installed colormap */
+  pScreenPriv->pcmapInstalled = pColormap;
+}
+
+
+/* See Porting Layer Definition - p. 30 */
+static void
+winUninstallColormap (ColormapPtr pmap)
+{
+  winScreenPriv(pmap->pScreen);
+  ColormapPtr curpmap = pScreenPriv->pcmapInstalled;
+
+#if CYGDEBUG
+  winDebug ("winUninstallColormap\n");
+#endif
+
+  /* Is the colormap currently installed? */
+  if (pmap != curpmap)
+    {
+      /* Colormap not installed, nothing to do */
+      return;
+    }
+  
+  /* Clear the installed colormap flag */
+  pScreenPriv->pcmapInstalled = NULL;
+  
+  /*
+   * NOTE: The default colormap does not get "uninstalled" before
+   * it is destroyed.
+   */
+
+  /* Install the default cmap in place of the cmap to be uninstalled */
+  if (pmap->mid != pmap->pScreen->defColormap)
+    {
+      curpmap = (ColormapPtr) LookupIDByType(pmap->pScreen->defColormap,
+					     RT_COLORMAP);
+      (*pmap->pScreen->InstallColormap) (curpmap);
+    }
+}
+
+
+/* See Porting Layer Definition - p. 30 */
+static void
+winStoreColors (ColormapPtr pmap,
+		int ndef,
+		xColorItem *pdefs)
+{
+  ScreenPtr		pScreen = pmap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pmap);
+  int			i;
+  unsigned short	nRed, nGreen, nBlue;
+
+#if CYGDEBUG
+  if (ndef != 1)
+    winDebug ("winStoreColors - ndef: %d\n",
+	    ndef);
+#endif
+
+  /* Save the new colors in the colormap privates */
+  for (i = 0; i < ndef; ++i)
+    {
+      /* Adjust the colors from the X color spec to the Windows color spec */
+      nRed = pdefs[i].red >> 8;
+      nGreen = pdefs[i].green >> 8;
+      nBlue = pdefs[i].blue >> 8;
+
+      /* Copy the colors to a palette entry table */
+      pCmapPriv->peColors[pdefs[0].pixel + i].peRed = nRed;
+      pCmapPriv->peColors[pdefs[0].pixel + i].peGreen = nGreen;
+      pCmapPriv->peColors[pdefs[0].pixel + i].peBlue = nBlue;
+      
+      /* Copy the colors to a RGBQUAD table */
+      pCmapPriv->rgbColors[pdefs[0].pixel + i].rgbRed = nRed;
+      pCmapPriv->rgbColors[pdefs[0].pixel + i].rgbGreen = nGreen;
+      pCmapPriv->rgbColors[pdefs[0].pixel + i].rgbBlue = nBlue;
+
+#if CYGDEBUG
+      winDebug ("winStoreColors - nRed %d nGreen %d nBlue %d\n",
+	      nRed, nGreen, nBlue);
+#endif
+    }
+
+  /* Call the engine specific store colors procedure */
+  if (!((pScreenPriv->pwinStoreColors) (pmap, ndef, pdefs)))
+    {
+      winErrorFVerb (2, "winStoreColors - Engine cpecific color storage procedure "
+	      "failed.  Continuing, but colors may be messed up from now "
+	      "on.\n");
+    }
+}
+
+
+/* See Porting Layer Definition - p. 30 */
+static void
+winResolveColor (unsigned short *pred,
+		 unsigned short *pgreen,
+		 unsigned short *pblue,
+		 VisualPtr	pVisual)
+{
+#if CYGDEBUG
+  winDebug ("winResolveColor ()\n");
+#endif
+
+  miResolveColor (pred, pgreen, pblue, pVisual);
+}
+
+
+/* See Porting Layer Definition - p. 29 */
+static Bool
+winCreateColormap (ColormapPtr pmap)
+{
+  winPrivCmapPtr	pCmapPriv = NULL;
+  ScreenPtr		pScreen = pmap->pScreen;
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winDebug ("winCreateColormap\n");
+#endif
+
+  /* Allocate colormap privates */
+  if (!winAllocateCmapPrivates (pmap))
+    {
+      ErrorF ("winCreateColorma - Couldn't allocate cmap privates\n");
+      return FALSE;
+    }
+
+  /* Get a pointer to the newly allocated privates */
+  pCmapPriv = winGetCmapPriv (pmap);
+
+  /*
+   * FIXME: This is some evil hackery to help in handling some X clients
+   * that expect the top pixel to be white.  This "help" only lasts until
+   * some client overwrites the top colormap entry.
+   * 
+   * We don't want to actually allocate the top entry, as that causes
+   * problems with X clients that need 7 planes (128 colors) in the default
+   * colormap, such as Magic 7.1.
+   */
+  pCmapPriv->rgbColors[WIN_NUM_PALETTE_ENTRIES - 1].rgbRed = 255;
+  pCmapPriv->rgbColors[WIN_NUM_PALETTE_ENTRIES - 1].rgbGreen = 255;
+  pCmapPriv->rgbColors[WIN_NUM_PALETTE_ENTRIES - 1].rgbBlue = 255;
+  pCmapPriv->peColors[WIN_NUM_PALETTE_ENTRIES - 1].peRed = 255;
+  pCmapPriv->peColors[WIN_NUM_PALETTE_ENTRIES - 1].peGreen = 255;
+  pCmapPriv->peColors[WIN_NUM_PALETTE_ENTRIES - 1].peBlue = 255;
+
+  /* Call the engine specific colormap initialization procedure */
+  if (!((*pScreenPriv->pwinCreateColormap) (pmap)))
+    {
+      ErrorF ("winCreateColormap - Engine specific colormap creation "
+	      "procedure failed.  Aborting.\n");
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+
+/* See Porting Layer Definition - p. 29, 30 */
+static void
+winDestroyColormap (ColormapPtr pColormap)
+{
+  winScreenPriv(pColormap->pScreen);
+  winCmapPriv(pColormap);
+
+  /* Call the engine specific colormap destruction procedure */
+  if (!((*pScreenPriv->pwinDestroyColormap) (pColormap)))
+    {
+      winErrorFVerb (2, "winDestroyColormap - Engine specific colormap destruction "
+	      "procedure failed.  Continuing, but it is possible that memory "
+	      "was leaked, or that colors will be messed up from now on.\n");
+    }
+
+  /* Free the colormap privates */
+  free (pCmapPriv);
+  winSetCmapPriv (pColormap, NULL);
+
+#if CYGDEBUG
+  winDebug ("winDestroyColormap - Returning\n");
+#endif
+}
+
+
+/*
+ * Internal function to load the palette used by the Shadow DIB
+ */
+
+static Bool
+winGetPaletteDIB (ScreenPtr pScreen, ColormapPtr pcmap)
+{
+  winScreenPriv(pScreen);
+  int			i;
+  Pixel			pixel; /* Pixel == CARD32 */
+  CARD16		nRed, nGreen, nBlue; /* CARD16 == unsigned short */
+  UINT			uiColorsRetrieved = 0;
+  RGBQUAD		rgbColors[WIN_NUM_PALETTE_ENTRIES];
+      
+  /* Get the color table for the screen */
+  uiColorsRetrieved = GetDIBColorTable (pScreenPriv->hdcScreen,
+					0,
+					WIN_NUM_PALETTE_ENTRIES,
+					rgbColors);
+  if (uiColorsRetrieved == 0)
+    {
+      ErrorF ("winGetPaletteDIB - Could not retrieve screen color table\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winGetPaletteDIB - Retrieved %d colors from DIB\n",
+	  uiColorsRetrieved);
+#endif
+
+  /* Set the DIB color table to the default screen palette */
+  if (SetDIBColorTable (pScreenPriv->hdcShadow,
+			0,
+			uiColorsRetrieved,
+			rgbColors) == 0)
+    {
+      ErrorF ("winGetPaletteDIB - SetDIBColorTable () failed\n");
+      return FALSE;
+    }
+
+  /* Alloc each color in the DIB color table */
+  for (i = 0; i < uiColorsRetrieved; ++i)
+    {
+      pixel = i;
+
+      /* Extract the color values for current palette entry */
+      nRed = rgbColors[i].rgbRed << 8;
+      nGreen = rgbColors[i].rgbGreen << 8;
+      nBlue = rgbColors[i].rgbBlue << 8;
+
+#if CYGDEBUG
+      winDebug ("winGetPaletteDIB - Allocating a color: %d; "
+	      "%d %d %d\n",
+	      pixel, nRed, nGreen, nBlue);
+#endif
+
+      /* Allocate a entry in the X colormap */
+      if (AllocColor (pcmap,
+		      &nRed,
+		      &nGreen,
+		      &nBlue,
+		      &pixel,
+		      0) != Success)
+	{
+	  ErrorF ("winGetPaletteDIB - AllocColor () failed, pixel %d\n",
+		  i);
+	  return FALSE;
+	}
+
+      if (i != pixel
+	  || nRed != rgbColors[i].rgbRed 
+	  || nGreen != rgbColors[i].rgbGreen
+	  || nBlue != rgbColors[i].rgbBlue)
+	{
+	  winDebug ("winGetPaletteDIB - Got: %d; "
+		  "%d %d %d\n",
+		  (int) pixel, nRed, nGreen, nBlue);
+	}
+	  
+      /* FIXME: Not sure that this bit is needed at all */
+      pcmap->red[i].co.local.red = nRed;
+      pcmap->red[i].co.local.green = nGreen;
+      pcmap->red[i].co.local.blue = nBlue;
+    }
+
+  /* System is using a colormap */
+  /* Set the black and white pixel indices */
+  pScreen->whitePixel = uiColorsRetrieved - 1;
+  pScreen->blackPixel = 0;
+
+  return TRUE;
+}
+
+
+/*
+ * Internal function to load the standard system palette being used by DD
+ */
+
+static Bool
+winGetPaletteDD (ScreenPtr pScreen, ColormapPtr pcmap)
+{
+  int			i;
+  Pixel			pixel; /* Pixel == CARD32 */
+  CARD16		nRed, nGreen, nBlue; /* CARD16 == unsigned short */
+  UINT			uiSystemPaletteEntries;
+  LPPALETTEENTRY	ppeColors = NULL;
+  HDC			hdc = NULL;
+
+  /* Get a DC to obtain the default palette */
+  hdc = GetDC (NULL);
+  if (hdc == NULL)
+    {
+      ErrorF ("winGetPaletteDD - Couldn't get a DC\n");
+      return FALSE;
+    }
+
+  /* Get the number of entries in the system palette */
+  uiSystemPaletteEntries = GetSystemPaletteEntries (hdc,
+						    0, 0, NULL);
+  if (uiSystemPaletteEntries == 0)
+    {
+      ErrorF ("winGetPaletteDD - Unable to determine number of "
+	      "system palette entries\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winGetPaletteDD - uiSystemPaletteEntries %d\n",
+	  uiSystemPaletteEntries);
+#endif
+  
+  /* Allocate palette entries structure */
+  ppeColors = malloc (uiSystemPaletteEntries * sizeof (PALETTEENTRY));
+  if (ppeColors == NULL)
+    {
+      ErrorF ("winGetPaletteDD - malloc () for colormap failed\n");
+      return FALSE;
+    }
+
+  /* Get system palette entries */
+  GetSystemPaletteEntries (hdc,
+			   0, uiSystemPaletteEntries, ppeColors);
+
+  /* Allocate an X colormap entry for every system palette entry */
+  for (i = 0; i < uiSystemPaletteEntries; ++i)
+    {
+      pixel = i;
+
+      /* Extract the color values for current palette entry */
+      nRed = ppeColors[i].peRed << 8;
+      nGreen = ppeColors[i].peGreen << 8;
+      nBlue = ppeColors[i].peBlue << 8;
+#if CYGDEBUG
+      winDebug ("winGetPaletteDD - Allocating a color: %d; "
+	      "%d %d %d\n",
+	      pixel, nRed, nGreen, nBlue);
+#endif
+      if (AllocColor (pcmap,
+		      &nRed,
+		      &nGreen,
+		      &nBlue,
+		      &pixel,
+		      0) != Success)
+	{
+	  ErrorF ("winGetPaletteDD - AllocColor () failed, pixel %d\n",
+		  i);
+	  free (ppeColors);
+	  ppeColors = NULL;
+	  return FALSE;
+	}
+
+      pcmap->red[i].co.local.red = nRed;
+      pcmap->red[i].co.local.green = nGreen;
+      pcmap->red[i].co.local.blue = nBlue;
+    }
+
+  /* System is using a colormap */
+  /* Set the black and white pixel indices */
+  pScreen->whitePixel = uiSystemPaletteEntries - 1;
+  pScreen->blackPixel = 0;
+
+  /* Free colormap */
+  if (ppeColors != NULL)
+    {
+      free (ppeColors);
+      ppeColors = NULL;
+    }
+
+  /* Free the DC */
+  if (hdc != NULL)
+    {
+      ReleaseDC (NULL, hdc);
+      hdc = NULL;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Install the standard fb colormap, or the GDI colormap,
+ * depending on the current screen depth.
+ */
+
+Bool
+winCreateDefColormap (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  unsigned short	zero = 0, ones = 0xFFFF;
+  VisualPtr		pVisual = pScreenPriv->pRootVisual;
+  ColormapPtr		pcmap = NULL;
+  Pixel			wp, bp;
+
+#if CYGDEBUG
+  winDebug ("winCreateDefColormap\n");
+#endif
+
+  /* Use standard fb colormaps for non palettized color modes */
+  if (pScreenInfo->dwBPP > 8)
+    {
+      winDebug ("winCreateDefColormap - Deferring to " \
+	      "fbCreateDefColormap ()\n");
+      return fbCreateDefColormap (pScreen);
+    }
+
+  /*
+   *  AllocAll for non-Dynamic visual classes,
+   *  AllocNone for Dynamic visual classes.
+   */
+
+  /*
+   * Dynamic visual classes allow the colors of the color map
+   * to be changed by clients.
+   */
+
+#if CYGDEBUG
+  winDebug ("winCreateDefColormap - defColormap: %d\n",
+	  pScreen->defColormap);
+#endif
+
+  /* Allocate an X colormap, owned by client 0 */
+  if (CreateColormap (pScreen->defColormap, 
+		      pScreen,
+		      pVisual,
+		      &pcmap,
+		      (pVisual->class & DynamicClass) ? AllocNone : AllocAll,
+		      0) != Success)
+    {
+      ErrorF ("winCreateDefColormap - CreateColormap failed\n");
+      return FALSE;
+    }
+  if (pcmap == NULL)
+    {
+      ErrorF ("winCreateDefColormap - Colormap could not be created\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winCreateDefColormap - Created a colormap\n");
+#endif
+
+  /* Branch on the visual class */
+  if (!(pVisual->class & DynamicClass))
+    {
+      /* Branch on engine type */
+      if (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_GDI)
+	{
+	  /* Load the colors being used by the Shadow DIB */
+	  if (!winGetPaletteDIB (pScreen, pcmap))
+	    {
+	      ErrorF ("winCreateDefColormap - Couldn't get DIB colors\n");
+	      return FALSE;
+	    }
+	}
+      else
+	{
+	  /* Load the colors from the default system palette */
+	  if (!winGetPaletteDD (pScreen, pcmap))
+	    {
+	      ErrorF ("winCreateDefColormap - Couldn't get colors "
+		      "for DD\n");
+	      return FALSE;
+	    }
+	}
+    }
+  else
+    {
+      wp = pScreen->whitePixel;
+      bp = pScreen->blackPixel;
+      
+      /* Allocate a black and white pixel */
+      if ((AllocColor (pcmap, &ones, &ones, &ones, &wp, 0) !=
+	   Success)
+	  ||
+	  (AllocColor (pcmap, &zero, &zero, &zero, &bp, 0) !=
+	   Success))
+	{
+	  ErrorF ("winCreateDefColormap - Couldn't allocate bp or wp\n");
+	  return FALSE;
+	}
+      
+      pScreen->whitePixel = wp;
+      pScreen->blackPixel = bp;
+
+#if 0
+      /* Have to reserve first 10 and last ten pixels in DirectDraw windowed */
+      if (pScreenInfo->dwEngine != WIN_SERVER_SHADOW_GDI)
+	{
+	  int		k;
+	  Pixel		p;
+
+	  for (k = 1; k < 10; ++k)
+	    {
+	      p = k;
+	      if (AllocColor (pcmap, &ones, &ones, &ones, &p, 0) != Success)
+		FatalError ("Foo!\n");
+	    }
+	  
+	  for (k = 245; k < 255; ++k)
+	    {
+	      p = k;
+	      if (AllocColor (pcmap, &zero, &zero, &zero, &p, 0) != Success)
+		FatalError ("Baz!\n");
+	    }
+	}
+#endif
+    }
+
+  /* Install the created colormap */
+  (*pScreen->InstallColormap)(pcmap);
+
+#if CYGDEBUG
+  winDebug ("winCreateDefColormap - Returning\n");
+#endif
+
+  return TRUE;
+}
diff --git a/hw/xwin/winconfig.c b/hw/xwin/winconfig.c
new file mode 100644
index 0000000..38966bf
--- /dev/null
+++ b/hw/xwin/winconfig.c
@@ -0,0 +1,1150 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors: Alexander Gottwald	
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winconfig.h"
+#include "winmsg.h"
+#include "globals.h"
+
+#ifdef XKB
+#ifndef XKB_IN_SERVER
+#define XKB_IN_SERVER
+#endif
+#include <xkbsrv.h>
+#endif
+
+#ifdef XWIN_XF86CONFIG
+#ifndef CONFIGPATH
+#define CONFIGPATH  "%A," "%R," \
+                    "/etc/X11/%R," "%P/etc/X11/%R," \
+                    "%E," "%F," \
+                    "/etc/X11/%F," "%P/etc/X11/%F," \
+                    "/etc/X11/%X-%M," "/etc/X11/%X," "/etc/%X," \
+                    "%P/etc/X11/%X.%H," "%P/etc/X11/%X-%M," \
+                    "%P/etc/X11/%X," \
+                    "%P/lib/X11/%X.%H," "%P/lib/X11/%X-%M," \
+                    "%P/lib/X11/%X"
+#endif
+
+XF86ConfigPtr g_xf86configptr = NULL;
+#endif
+
+WinCmdlineRec g_cmdline = {
+#ifdef XWIN_XF86CONFIG
+  NULL,				/* configFile */
+#endif
+  NULL,				/* fontPath */
+#ifdef XWIN_XF86CONFIG
+  NULL,				/* keyboard */
+#endif
+#ifdef XKB
+  FALSE,			/* noXkbExtension */
+  NULL,				/* xkbMap */
+  NULL,             /* xkbRules */
+  NULL,             /* xkbModel */
+  NULL,             /* xkbLayout */
+  NULL,             /* xkbVariant */
+  NULL,             /* xkbOptions */
+#endif
+  NULL,				/* screenname */
+  NULL,				/* mousename */
+  FALSE,			/* emulate3Buttons */
+  0				/* emulate3Timeout */
+};
+
+winInfoRec g_winInfo = {
+  {				/* keyboard */
+   0,				/* leds */
+   500,				/* delay */
+   30				/* rate */
+#ifdef XKB
+   }
+  ,
+  {				/* xkb */
+   FALSE,			/* disable */
+   NULL,			/* rules */
+   NULL,			/* model */
+   NULL,			/* layout */
+   NULL,			/* variant */
+   NULL,			/* options */
+   NULL,			/* initialMap */
+   NULL,			/* keymap */
+   NULL,			/* types */
+   NULL,			/* compat */
+   NULL,			/* keycodes */
+   NULL,			/* symbols */
+   NULL				/* geometry */
+#endif
+   }
+  ,
+  {
+   FALSE,
+   50}
+};
+
+#define NULL_IF_EMPTY(x) (winNameCompare(x,"")?x:NULL)
+
+#ifdef XWIN_XF86CONFIG
+serverLayoutRec g_winConfigLayout;
+
+static Bool ParseOptionValue (int scrnIndex, pointer options,
+			      OptionInfoPtr p);
+static Bool configLayout (serverLayoutPtr, XF86ConfLayoutPtr, char *);
+static Bool configImpliedLayout (serverLayoutPtr, XF86ConfScreenPtr);
+static Bool GetBoolValue (OptionInfoPtr p, const char *s);
+
+
+Bool
+winReadConfigfile ()
+{
+  Bool		retval = TRUE;
+  const char	*filename;
+  MessageType	from = X_DEFAULT;
+  char		*xf86ConfigFile = NULL;
+
+  if (g_cmdline.configFile)
+    {
+      from = X_CMDLINE;
+      xf86ConfigFile = g_cmdline.configFile;
+    }
+
+  /* Parse config file into data structure */
+
+  filename = xf86openConfigFile (CONFIGPATH, xf86ConfigFile, PROJECTROOT);
+    
+  /* Hack for backward compatibility */
+  if (!filename && from == X_DEFAULT)
+    filename = xf86openConfigFile (CONFIGPATH, "XF86Config", PROJECTROOT);
+
+  if (filename)
+    {
+      winMsg (from, "Using config file: \"%s\"\n", filename);
+    }
+  else
+    {
+      winMsg (X_ERROR, "Unable to locate/open config file");
+      if (xf86ConfigFile)
+	ErrorF (": \"%s\"", xf86ConfigFile);
+      ErrorF ("\n");
+      return FALSE;
+    }
+  if ((g_xf86configptr = xf86readConfigFile ()) == NULL)
+    {
+      winMsg (X_ERROR, "Problem parsing the config file\n");
+      return FALSE;
+    }
+  xf86closeConfigFile ();
+
+  LogPrintMarkers();
+
+  /* set options from data structure */
+
+  if (g_xf86configptr->conf_layout_lst == NULL || g_cmdline.screenname != NULL)
+    {
+      if (g_cmdline.screenname == NULL)
+	{
+	  winMsg (X_WARNING,
+		  "No Layout section. Using the first Screen section.\n");
+	}
+      if (!configImpliedLayout (&g_winConfigLayout,
+				g_xf86configptr->conf_screen_lst))
+	{
+	  winMsg (X_ERROR, "Unable to determine the screen layout\n");
+	  return FALSE;
+	}
+    }
+  else
+    {
+      /* Check if layout is given in the config file */
+      if (g_xf86configptr->conf_flags != NULL)
+	{
+	  char *dfltlayout = NULL;
+	  pointer optlist = g_xf86configptr->conf_flags->flg_option_lst;
+
+	  if (optlist && winFindOption (optlist, "defaultserverlayout"))
+	    dfltlayout =
+	      winSetStrOption (optlist, "defaultserverlayout", NULL);
+
+	  if (!configLayout (&g_winConfigLayout,
+			     g_xf86configptr->conf_layout_lst,
+			     dfltlayout))
+	    {
+	      winMsg (X_ERROR, "Unable to determine the screen layout\n");
+	      return FALSE;
+	    }
+	}
+      else
+	{
+	  if (!configLayout (&g_winConfigLayout,
+			     g_xf86configptr->conf_layout_lst,
+			     NULL))
+	    {
+	      winMsg (X_ERROR, "Unable to determine the screen layout\n");
+	      return FALSE;
+	    }
+	}
+    }
+
+  /* setup special config files */
+  winConfigFiles ();
+  return retval;
+}
+#endif
+
+/* load layout definitions */
+#include "winlayouts.h"
+
+/* Set the keyboard configuration */
+Bool
+winConfigKeyboard (DeviceIntPtr pDevice)
+{
+#ifdef XKB
+  char                          layoutName[KL_NAMELENGTH];
+  static unsigned int           layoutNum = 0;
+  int                           keyboardType;
+#endif
+#ifdef XWIN_XF86CONFIG
+  XF86ConfInputPtr		kbd = NULL;
+  XF86ConfInputPtr		input_list = NULL;
+  MessageType			kbdfrom = X_CONFIG;
+#endif
+  MessageType			from = X_DEFAULT;
+  char				*s = NULL;
+
+  /* Setup defaults */
+#ifdef XKB
+  g_winInfo.xkb.disable = FALSE;
+# ifdef PC98 /* japanese */	/* not implemented */
+  g_winInfo.xkb.rules = "xfree98";
+  g_winInfo.xkb.model = "pc98";
+  g_winInfo.xkb.layout = "nex/jp";
+  g_winInfo.xkb.variant = NULL;
+  g_winInfo.xkb.options = NULL;
+# else
+  g_winInfo.xkb.rules = "xorg";
+  g_winInfo.xkb.model = "pc101";
+  g_winInfo.xkb.layout = "us";
+  g_winInfo.xkb.variant = NULL;
+  g_winInfo.xkb.options = NULL;
+# endif	/* PC98 */
+
+  /*
+   * Query the windows autorepeat settings and change the xserver defaults.   
+   * If XKB is disabled then windows handles the autorepeat and the special 
+   * treatment is not needed
+   */
+  {
+    int kbd_delay;
+    DWORD kbd_speed;
+    if (SystemParametersInfo(SPI_GETKEYBOARDDELAY, 0, &kbd_delay, 0) &&
+        SystemParametersInfo(SPI_GETKEYBOARDSPEED, 0, &kbd_speed, 0))
+      {
+        switch (kbd_delay) 
+          {
+            case 0:  g_winInfo.keyboard.delay = 250; break;
+            case 1:  g_winInfo.keyboard.delay = 500; break;
+            case 2:  g_winInfo.keyboard.delay = 750; break;
+            default:
+            case 3:  g_winInfo.keyboard.delay = 1000; break;
+          }
+        g_winInfo.keyboard.rate = (kbd_speed>0)?kbd_speed:1;
+        winMsgVerb(X_PROBED, 1, "Setting autorepeat to delay=%d, rate=%d\n",
+                g_winInfo.keyboard.delay, g_winInfo.keyboard.rate);
+      }
+  }
+  
+
+  keyboardType = GetKeyboardType (0);
+  if (keyboardType > 0 && GetKeyboardLayoutName (layoutName)) 
+  {
+    WinKBLayoutPtr	pLayout;
+    Bool                bfound = FALSE;
+
+    if (! layoutNum)
+      layoutNum = strtoul (layoutName, (char **)NULL, 16);
+    if ((layoutNum & 0xffff) == 0x411) {
+        /* The japanese layouts know a lot of different IMEs which all have
+	   different layout numbers set. Map them to a single entry. 
+	   Same might apply for chinese, korean and other symbol languages
+	   too */
+        layoutNum = (layoutNum & 0xffff);
+	if (keyboardType == 7)
+	  {
+	    /* Japanese layouts have problems with key event messages
+	       such as the lack of WM_KEYUP for Caps Lock key.
+	       Loading US layout fixes this problem. */
+	    if (LoadKeyboardLayout("00000409", KLF_ACTIVATE) != NULL)
+	      winMsg (X_INFO, "Loading US keyboard layout.\n");
+	    else
+	      winMsg (X_ERROR, "LoadKeyboardLaout failed.\n");
+	  }
+    }
+    winMsg (X_PROBED, "winConfigKeyboard - Layout: \"%s\" (%08x) \n", 
+            layoutName, layoutNum);
+
+    for (pLayout = winKBLayouts; pLayout->winlayout != -1; pLayout++)
+      {
+	if (pLayout->winlayout != layoutNum)
+	  continue;
+	if (pLayout->winkbtype > 0 && pLayout->winkbtype != keyboardType)
+	  continue;
+	
+        bfound = TRUE;
+	winMsg (X_PROBED,
+		"Using preset keyboard for \"%s\" (%x), type \"%d\"\n",
+		pLayout->layoutname, pLayout->winlayout, keyboardType);
+	
+	g_winInfo.xkb.model = pLayout->xkbmodel;
+	g_winInfo.xkb.layout = pLayout->xkblayout;
+	g_winInfo.xkb.variant = pLayout->xkbvariant;
+	g_winInfo.xkb.options = pLayout->xkboptions; 
+	break;
+      }
+    
+    if (!bfound)
+      {
+        HKEY                regkey = NULL;
+        const char          regtempl[] = 
+          "SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts\\";
+        char                *regpath;
+        char                lname[256];
+        DWORD               namesize = sizeof(lname);
+
+        regpath = malloc(sizeof(regtempl) + KL_NAMELENGTH + 1);
+        strcpy(regpath, regtempl);
+        strcat(regpath, layoutName);
+
+        if (!RegOpenKey(HKEY_LOCAL_MACHINE, regpath, &regkey) &&
+          !RegQueryValueEx(regkey, "Layout Text", 0, NULL, lname, &namesize))
+          {
+	    winMsg (X_ERROR,
+		"Keyboardlayout \"%s\" (%s) is unknown\n", lname, layoutName);
+          }
+
+	/* Close registry key */
+	if (regkey)
+	  RegCloseKey (regkey);
+        free(regpath);
+      }
+  }  
+  
+  g_winInfo.xkb.initialMap = NULL;
+  g_winInfo.xkb.keymap = NULL;
+  g_winInfo.xkb.types = NULL;
+  g_winInfo.xkb.compat = NULL;
+  g_winInfo.xkb.keycodes = NULL;
+  g_winInfo.xkb.symbols = NULL;
+  g_winInfo.xkb.geometry = NULL;
+#endif /* XKB */
+
+  /* parse the configuration */
+#ifdef XWIN_XF86CONFIG
+  if (g_cmdline.keyboard)
+    kbdfrom = X_CMDLINE;
+
+  /*
+   * Until the layout code is finished, I search for the keyboard 
+   * device and configure the server with it.
+   */
+
+  if (g_xf86configptr != NULL)
+    input_list = g_xf86configptr->conf_input_lst;
+
+  while (input_list != NULL)
+    {
+      if (winNameCompare (input_list->inp_driver, "keyboard") == 0)
+	{
+	  /* Check if device name matches requested name */
+	  if (g_cmdline.keyboard && winNameCompare (input_list->inp_identifier,
+						    g_cmdline.keyboard))
+	    continue;
+	  kbd = input_list;
+	}
+      input_list = input_list->list.next;
+    }
+
+  if (kbd != NULL)
+    {
+
+      if (kbd->inp_identifier)
+	winMsg (kbdfrom, "Using keyboard \"%s\" as primary keyboard\n",
+		kbd->inp_identifier);
+
+      if ((s = winSetStrOption(kbd->inp_option_lst, "AutoRepeat", NULL)))
+        {
+          if ((sscanf(s, "%ld %ld", &g_winInfo.keyboard.delay, 
+                      &g_winInfo.keyboard.rate) != 2) ||
+                  (g_winInfo.keyboard.delay < 1) || 
+                  (g_winInfo.keyboard.rate == 0) || 
+                  (1000 / g_winInfo.keyboard.rate) < 1) 
+            {
+              winErrorFVerb (2, "\"%s\" is not a valid AutoRepeat value", s);
+              xfree(s);
+              return FALSE;
+            }
+          xfree(s);
+          winMsg (X_CONFIG, "AutoRepeat: %ld %ld\n", 
+                  g_winInfo.keyboard.delay, g_winInfo.keyboard.rate);
+        }
+#endif
+      
+#ifdef XKB
+      from = X_DEFAULT;
+      if (g_cmdline.noXkbExtension)
+	{
+	  from = X_CMDLINE;
+	  g_winInfo.xkb.disable = TRUE;
+	}
+#ifdef XWIN_XF86CONFIG
+      else if (kbd->inp_option_lst)
+	{
+	  int b = winSetBoolOption (kbd->inp_option_lst, "XkbDisable", FALSE);
+	  if (b)
+	    {
+	      from = X_CONFIG;
+	      g_winInfo.xkb.disable = TRUE;
+	    }
+	}
+#endif
+      if (g_winInfo.xkb.disable)
+	{
+	  winMsg (from, "XkbExtension disabled\n");
+	}
+      else
+	{
+          s = NULL;  
+          if (g_cmdline.xkbRules)
+            {
+              s = g_cmdline.xkbRules;
+              from = X_CMDLINE;  
+            }
+#ifdef XWIN_XF86CONFIG
+          else 
+            {
+              s = winSetStrOption (kbd->inp_option_lst, "XkbRules", NULL);
+              from = X_CONFIG;  
+            }
+#endif
+          if (s)
+	    {
+	      g_winInfo.xkb.rules = NULL_IF_EMPTY (s);
+	      winMsg (from, "XKB: rules: \"%s\"\n", s);
+	    }
+          
+          s = NULL;
+          if (g_cmdline.xkbModel)
+            {
+              s = g_cmdline.xkbModel;
+              from = X_CMDLINE;
+            }
+#ifdef XWIN_XF86CONFIG
+          else
+            {
+              s = winSetStrOption (kbd->inp_option_lst, "XkbModel", NULL);
+              from = X_CONFIG;
+            }  
+#endif
+	  if (s)
+	    {
+	      g_winInfo.xkb.model = NULL_IF_EMPTY (s);
+	      winMsg (from, "XKB: model: \"%s\"\n", s);
+	    }
+
+          s = NULL;
+          if (g_cmdline.xkbLayout)
+            {
+              s = g_cmdline.xkbLayout;
+              from = X_CMDLINE;
+            }
+#ifdef XWIN_XF86CONFIG
+          else
+            {
+              s = winSetStrOption (kbd->inp_option_lst, "XkbLayout", NULL);
+              from = X_CONFIG;
+            }
+#endif
+          if (s)  
+	    {
+	      g_winInfo.xkb.layout = NULL_IF_EMPTY (s);
+	      winMsg (from, "XKB: layout: \"%s\"\n", s);
+	    }
+
+          s = NULL;
+          if (g_cmdline.xkbVariant)
+            {
+              s = g_cmdline.xkbVariant;
+              from = X_CMDLINE;
+            }
+#ifdef XWIN_XF86CONFIG
+          else
+            { 
+              s = winSetStrOption (kbd->inp_option_lst, "XkbVariant", NULL);
+              from = X_CONFIG;
+            }
+#endif
+	  if (s)
+	    {
+	      g_winInfo.xkb.variant = NULL_IF_EMPTY (s);
+	      winMsg (from, "XKB: variant: \"%s\"\n", s);
+	    }
+
+          s = NULL;
+          if (g_cmdline.xkbOptions)
+            {
+              s = g_cmdline.xkbOptions;
+              from = X_CMDLINE;
+            }
+#ifdef XWIN_XF86CONFIG
+          else
+            { 
+              s = winSetStrOption (kbd->inp_option_lst, "XkbOptions", NULL);
+              from = X_CONFIG;
+            }
+#endif
+          if (s)
+	    {
+	      g_winInfo.xkb.options = NULL_IF_EMPTY (s);
+	      winMsg (from, "XKB: options: \"%s\"\n", s);
+	    }
+
+#ifdef XWIN_XF86CONFIG
+	  from = X_CMDLINE;
+
+	  if ((s = winSetStrOption (kbd->inp_option_lst, "XkbKeymap", NULL)))
+	    {
+	      g_winInfo.xkb.keymap = NULL_IF_EMPTY (s);
+	      winMsg (X_CONFIG, "XKB: keymap: \"%s\" "
+		      " (overrides other XKB settings)\n", s);
+	    }
+
+	  if ((s = winSetStrOption (kbd->inp_option_lst, "XkbCompat", NULL)))
+	    {
+	      g_winInfo.xkb.compat = NULL_IF_EMPTY (s);
+	      winMsg (X_CONFIG, "XKB: compat: \"%s\"\n", s);
+	    }
+
+	  if ((s = winSetStrOption (kbd->inp_option_lst, "XkbTypes", NULL)))
+	    {
+	      g_winInfo.xkb.types = NULL_IF_EMPTY (s);
+	      winMsg (X_CONFIG, "XKB: types: \"%s\"\n", s);
+	    }
+
+	  if ((s =
+	       winSetStrOption (kbd->inp_option_lst, "XkbKeycodes", NULL)))
+	    {
+	      g_winInfo.xkb.keycodes = NULL_IF_EMPTY (s);
+	      winMsg (X_CONFIG, "XKB: keycodes: \"%s\"\n", s);
+	    }
+
+	  if ((s =
+	       winSetStrOption (kbd->inp_option_lst, "XkbGeometry", NULL)))
+	    {
+	      g_winInfo.xkb.geometry = NULL_IF_EMPTY (s);
+	      winMsg (X_CONFIG, "XKB: geometry: \"%s\"\n", s);
+	    }
+
+	  if ((s = winSetStrOption (kbd->inp_option_lst, "XkbSymbols", NULL)))
+	    {
+	      g_winInfo.xkb.symbols = NULL_IF_EMPTY (s);
+	      winMsg (X_CONFIG, "XKB: symbols: \"%s\"\n", s);
+	    }
+#endif
+#endif
+	}
+#ifdef XWIN_XF86CONFIG
+    }
+#endif
+
+  return TRUE;
+}
+
+
+#ifdef XWIN_XF86CONFIG
+Bool
+winConfigMouse (DeviceIntPtr pDevice)
+{
+  MessageType			mousefrom = X_CONFIG;
+
+  XF86ConfInputPtr		mouse = NULL;
+  XF86ConfInputPtr		input_list = NULL;
+
+  if (g_cmdline.mouse)
+    mousefrom = X_CMDLINE;
+
+  if (g_xf86configptr != NULL)
+    input_list = g_xf86configptr->conf_input_lst;
+
+  while (input_list != NULL)
+    {
+      if (winNameCompare (input_list->inp_driver, "mouse") == 0)
+	{
+	  /* Check if device name matches requested name */
+	  if (g_cmdline.mouse && winNameCompare (input_list->inp_identifier,
+						 g_cmdline.mouse))
+	    continue;
+	  mouse = input_list;
+	}
+      input_list = input_list->list.next;
+    }
+
+  if (mouse != NULL)
+    {
+      if (mouse->inp_identifier)
+	winMsg (mousefrom, "Using pointer \"%s\" as primary pointer\n",
+		mouse->inp_identifier);
+
+      g_winInfo.pointer.emulate3Buttons =
+	winSetBoolOption (mouse->inp_option_lst, "Emulate3Buttons", FALSE);
+      if (g_cmdline.emulate3buttons)
+	g_winInfo.pointer.emulate3Buttons = g_cmdline.emulate3buttons;
+
+      g_winInfo.pointer.emulate3Timeout =
+	winSetIntOption (mouse->inp_option_lst, "Emulate3Timeout", 50);
+      if (g_cmdline.emulate3timeout)
+	g_winInfo.pointer.emulate3Timeout = g_cmdline.emulate3timeout;
+    }
+  else
+    {
+      winMsg (X_ERROR, "No primary pointer configured\n");
+      winMsg (X_DEFAULT, "Using compiletime defaults for pointer\n");
+    }
+
+  return TRUE;
+}
+
+
+Bool
+winConfigFiles ()
+{
+  MessageType from;
+  XF86ConfFilesPtr filesptr = NULL;
+
+  /* set some shortcuts */
+  if (g_xf86configptr != NULL)
+    {
+      filesptr = g_xf86configptr->conf_files;
+    }
+
+
+  /* Fontpath */
+  from = X_DEFAULT;
+
+  if (g_cmdline.fontPath)
+    {
+      from = X_CMDLINE;
+      defaultFontPath = g_cmdline.fontPath;
+    }
+  else if (filesptr != NULL && filesptr->file_fontpath)
+    {
+      from = X_CONFIG;
+      defaultFontPath = xstrdup (filesptr->file_fontpath);
+    }
+  winMsg (from, "FontPath set to \"%s\"\n", defaultFontPath);
+
+  return TRUE;
+}
+#else
+Bool
+winConfigFiles ()
+{
+  MessageType from;
+
+  /* Fontpath */
+  if (g_cmdline.fontPath)
+    {
+      defaultFontPath = g_cmdline.fontPath;
+      winMsg (X_CMDLINE, "FontPath set to \"%s\"\n", defaultFontPath);
+    }
+
+  return TRUE;
+}
+#endif
+
+
+Bool
+winConfigOptions ()
+{
+  return TRUE;
+}
+
+
+Bool
+winConfigScreens ()
+{
+  return TRUE;
+}
+
+
+#ifdef XWIN_XF86CONFIG
+char *
+winSetStrOption (pointer optlist, const char *name, char *deflt)
+{
+  OptionInfoRec o;
+
+  o.name = name;
+  o.type = OPTV_STRING;
+  if (ParseOptionValue (-1, optlist, &o))
+    deflt = o.value.str;
+  if (deflt)
+    return xstrdup (deflt);
+  else
+    return NULL;
+}
+
+
+int
+winSetBoolOption (pointer optlist, const char *name, int deflt)
+{
+  OptionInfoRec o;
+
+  o.name = name;
+  o.type = OPTV_BOOLEAN;
+  if (ParseOptionValue (-1, optlist, &o))
+    deflt = o.value.bool;
+  return deflt;
+}
+
+
+int
+winSetIntOption (pointer optlist, const char *name, int deflt)
+{
+  OptionInfoRec o;
+
+  o.name = name;
+  o.type = OPTV_INTEGER;
+  if (ParseOptionValue (-1, optlist, &o))
+    deflt = o.value.num;
+  return deflt;
+}
+
+
+double
+winSetRealOption (pointer optlist, const char *name, double deflt)
+{
+  OptionInfoRec o;
+
+  o.name = name;
+  o.type = OPTV_REAL;
+  if (ParseOptionValue (-1, optlist, &o))
+    deflt = o.value.realnum;
+  return deflt;
+}
+#endif
+
+
+/*
+ * Compare two strings for equality. This is caseinsensitive  and
+ * The characters '_', ' ' (space) and '\t' (tab) are treated as 
+ * not existing.
+ */
+
+int
+winNameCompare (const char *s1, const char *s2)
+{
+  char c1, c2;
+
+  if (!s1 || *s1 == 0)
+    {
+      if (!s2 || *s2 == 0)
+	return 0;
+      else
+	return 1;
+    }
+
+  while (*s1 == '_' || *s1 == ' ' || *s1 == '\t')
+    s1++;
+  while (*s2 == '_' || *s2 == ' ' || *s2 == '\t')
+    s2++;
+
+  c1 = (isupper (*s1) ? tolower (*s1) : *s1);
+  c2 = (isupper (*s2) ? tolower (*s2) : *s2);
+
+  while (c1 == c2)
+    {
+      if (c1 == 0)
+	return 0;
+      s1++;
+      s2++;
+
+      while (*s1 == '_' || *s1 == ' ' || *s1 == '\t')
+	s1++;
+      while (*s2 == '_' || *s2 == ' ' || *s2 == '\t')
+	s2++;
+
+      c1 = (isupper (*s1) ? tolower (*s1) : *s1);
+      c2 = (isupper (*s2) ? tolower (*s2) : *s2);
+    }
+  return (c1 - c2);
+}
+
+
+#ifdef XWIN_XF86CONFIG
+/*
+ * Find the named option in the list. 
+ * @return the pointer to the option record, or NULL if not found.
+ */
+
+XF86OptionPtr
+winFindOption (XF86OptionPtr list, const char *name)
+{
+  while (list)
+    {
+      if (winNameCompare (list->opt_name, name) == 0)
+	return list;
+      list = list->list.next;
+    }
+  return NULL;
+}
+
+
+/*
+ * Find the Value of an named option.
+ * @return The option value or NULL if not found.
+ */
+
+char *
+winFindOptionValue (XF86OptionPtr list, const char *name)
+{
+  list = winFindOption (list, name);
+  if (list)
+    {
+      if (list->opt_val)
+	return (list->opt_val);
+      else
+	return "";
+    }
+  return (NULL);
+}
+
+
+/*
+ * Parse the option.
+ */
+
+static Bool
+ParseOptionValue (int scrnIndex, pointer options, OptionInfoPtr p)
+{
+  char *s, *end;
+
+  if ((s = winFindOptionValue (options, p->name)) != NULL)
+    {
+      switch (p->type)
+	{
+	case OPTV_INTEGER:
+	  if (*s == '\0')
+	    {
+	      winDrvMsg (scrnIndex, X_WARNING,
+			 "Option \"%s\" requires an integer value\n",
+			 p->name);
+	      p->found = FALSE;
+	    }
+	  else
+	    {
+	      p->value.num = strtoul (s, &end, 0);
+	      if (*end == '\0')
+		{
+		  p->found = TRUE;
+		}
+	      else
+		{
+		  winDrvMsg (scrnIndex, X_WARNING,
+			     "Option \"%s\" requires an integer value\n",
+			     p->name);
+		  p->found = FALSE;
+		}
+	    }
+	  break;
+	case OPTV_STRING:
+	  if (*s == '\0')
+	    {
+	      winDrvMsg (scrnIndex, X_WARNING,
+			 "Option \"%s\" requires an string value\n", p->name);
+	      p->found = FALSE;
+	    }
+	  else
+	    {
+	      p->value.str = s;
+	      p->found = TRUE;
+	    }
+	  break;
+	case OPTV_ANYSTR:
+	  p->value.str = s;
+	  p->found = TRUE;
+	  break;
+	case OPTV_REAL:
+	  if (*s == '\0')
+	    {
+	      winDrvMsg (scrnIndex, X_WARNING,
+			 "Option \"%s\" requires a floating point value\n",
+			 p->name);
+	      p->found = FALSE;
+	    }
+	  else
+	    {
+	      p->value.realnum = strtod (s, &end);
+	      if (*end == '\0')
+		{
+		  p->found = TRUE;
+		}
+	      else
+		{
+		  winDrvMsg (scrnIndex, X_WARNING,
+			     "Option \"%s\" requires a floating point value\n",
+			     p->name);
+		  p->found = FALSE;
+		}
+	    }
+	  break;
+	case OPTV_BOOLEAN:
+	  if (GetBoolValue (p, s))
+	    {
+	      p->found = TRUE;
+	    }
+	  else
+	    {
+	      winDrvMsg (scrnIndex, X_WARNING,
+			 "Option \"%s\" requires a boolean value\n", p->name);
+	      p->found = FALSE;
+	    }
+	  break;
+	case OPTV_FREQ:
+	  if (*s == '\0')
+	    {
+	      winDrvMsg (scrnIndex, X_WARNING,
+			 "Option \"%s\" requires a frequency value\n",
+			 p->name);
+	      p->found = FALSE;
+	    }
+	  else
+	    {
+	      double freq = strtod (s, &end);
+	      int units = 0;
+
+	      if (end != s)
+		{
+		  p->found = TRUE;
+		  if (!winNameCompare (end, "Hz"))
+		    units = 1;
+		  else if (!winNameCompare (end, "kHz") ||
+			   !winNameCompare (end, "k"))
+		    units = 1000;
+		  else if (!winNameCompare (end, "MHz") ||
+			   !winNameCompare (end, "M"))
+		    units = 1000000;
+		  else
+		    {
+		      winDrvMsg (scrnIndex, X_WARNING,
+				 "Option \"%s\" requires a frequency value\n",
+				 p->name);
+		      p->found = FALSE;
+		    }
+		  if (p->found)
+		    freq *= (double) units;
+		}
+	      else
+		{
+		  winDrvMsg (scrnIndex, X_WARNING,
+			     "Option \"%s\" requires a frequency value\n",
+			     p->name);
+		  p->found = FALSE;
+		}
+	      if (p->found)
+		{
+		  p->value.freq.freq = freq;
+		  p->value.freq.units = units;
+		}
+	    }
+	  break;
+	case OPTV_NONE:
+	  /* Should never get here */
+	  p->found = FALSE;
+	  break;
+	}
+      if (p->found)
+	{
+	  winDrvMsgVerb (scrnIndex, X_CONFIG, 2, "Option \"%s\"", p->name);
+	  if (!(p->type == OPTV_BOOLEAN && *s == 0))
+	    {
+	      winErrorFVerb (2, " \"%s\"", s);
+	    }
+	  winErrorFVerb (2, "\n");
+	}
+    }
+  else if (p->type == OPTV_BOOLEAN)
+    {
+      /* Look for matches with options with or without a "No" prefix. */
+      char *n, *newn;
+      OptionInfoRec opt;
+
+      n = winNormalizeName (p->name);
+      if (!n)
+	{
+	  p->found = FALSE;
+	  return FALSE;
+	}
+      if (strncmp (n, "no", 2) == 0)
+	{
+	  newn = n + 2;
+	}
+      else
+	{
+	  free (n);
+	  n = malloc (strlen (p->name) + 2 + 1);
+	  if (!n)
+	    {
+	      p->found = FALSE;
+	      return FALSE;
+	    }
+	  strcpy (n, "No");
+	  strcat (n, p->name);
+	  newn = n;
+	}
+      if ((s = winFindOptionValue (options, newn)) != NULL)
+	{
+	  if (GetBoolValue (&opt, s))
+	    {
+	      p->value.bool = !opt.value.bool;
+	      p->found = TRUE;
+	    }
+	  else
+	    {
+	      winDrvMsg (scrnIndex, X_WARNING,
+			 "Option \"%s\" requires a boolean value\n", newn);
+	      p->found = FALSE;
+	    }
+	}
+      else
+	{
+	  p->found = FALSE;
+	}
+      if (p->found)
+	{
+	  winDrvMsgVerb (scrnIndex, X_CONFIG, 2, "Option \"%s\"", newn);
+	  if (*s != 0)
+	    {
+	      winErrorFVerb (2, " \"%s\"", s);
+	    }
+	  winErrorFVerb (2, "\n");
+	}
+      free (n);
+    }
+  else
+    {
+      p->found = FALSE;
+    }
+  return p->found;
+}
+
+
+static Bool
+configLayout (serverLayoutPtr servlayoutp, XF86ConfLayoutPtr conf_layout,
+	      char *default_layout)
+{
+#if 0
+#pragma warn UNIMPLEMENTED
+#endif
+  return TRUE;
+}
+
+
+static Bool
+configImpliedLayout (serverLayoutPtr servlayoutp,
+		     XF86ConfScreenPtr conf_screen)
+{
+#if 0
+#pragma warn UNIMPLEMENTED
+#endif
+  return TRUE;
+}
+
+
+static Bool
+GetBoolValue (OptionInfoPtr p, const char *s)
+{
+  if (*s == 0)
+    {
+      p->value.bool = TRUE;
+    }
+  else
+    {
+      if (winNameCompare (s, "1") == 0)
+	p->value.bool = TRUE;
+      else if (winNameCompare (s, "on") == 0)
+	p->value.bool = TRUE;
+      else if (winNameCompare (s, "true") == 0)
+	p->value.bool = TRUE;
+      else if (winNameCompare (s, "yes") == 0)
+	p->value.bool = TRUE;
+      else if (winNameCompare (s, "0") == 0)
+	p->value.bool = FALSE;
+      else if (winNameCompare (s, "off") == 0)
+	p->value.bool = FALSE;
+      else if (winNameCompare (s, "false") == 0)
+	p->value.bool = FALSE;
+      else if (winNameCompare (s, "no") == 0)
+	p->value.bool = FALSE;
+    }
+  return TRUE;
+}
+#endif
+
+
+char *
+winNormalizeName (const char *s)
+{
+  char *ret, *q;
+  const char *p;
+
+  if (s == NULL)
+    return NULL;
+
+  ret = malloc (strlen (s) + 1);
+  for (p = s, q = ret; *p != 0; p++)
+    {
+      switch (*p)
+	{
+	case '_':
+	case ' ':
+	case '\t':
+	  continue;
+	default:
+	  if (isupper (*p))
+	    *q++ = tolower (*p);
+	  else
+	    *q++ = *p;
+	}
+    }
+  *q = '\0';
+  return ret;
+}
+
diff --git a/hw/xwin/winconfig.h b/hw/xwin/winconfig.h
new file mode 100644
index 0000000..4b56d63
--- /dev/null
+++ b/hw/xwin/winconfig.h
@@ -0,0 +1,343 @@
+#ifndef __WIN_CONFIG_H__
+#define __WIN_CONFIG_H__
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors: Alexander Gottwald	
+ */
+
+#include "win.h"
+#ifdef XWIN_XF86CONFIG
+#include "../xfree86/parser/xf86Parser.h"
+#endif
+
+
+/* These are taken from hw/xfree86/common/xf86str.h */
+
+typedef struct
+{
+  CARD32 red, green, blue;
+}
+rgb;
+
+
+typedef struct
+{
+  float red, green, blue;
+}
+Gamma;
+
+
+typedef struct
+{
+  char *identifier;
+  char *vendor;
+  char *board;
+  char *chipset;
+  char *ramdac;
+  char *driver;
+  struct _confscreenrec *myScreenSection;
+  Bool claimed;
+  Bool active;
+  Bool inUse;
+  int videoRam;
+  int textClockFreq;
+  pointer options;
+  int screen;			/* For multi-CRTC cards */
+}
+GDevRec, *GDevPtr;
+
+
+typedef struct
+{
+  char *identifier;
+  char *driver;
+  pointer commonOptions;
+  pointer extraOptions;
+}
+IDevRec, *IDevPtr;
+
+
+typedef struct
+{
+  int frameX0;
+  int frameY0;
+  int virtualX;
+  int virtualY;
+  int depth;
+  int fbbpp;
+  rgb weight;
+  rgb blackColour;
+  rgb whiteColour;
+  int defaultVisual;
+  char **modes;
+  pointer options;
+}
+DispRec, *DispPtr;
+
+
+typedef struct _confxvportrec
+{
+  char *identifier;
+  pointer options;
+}
+confXvPortRec, *confXvPortPtr;
+
+
+typedef struct _confxvadaptrec
+{
+  char *identifier;
+  int numports;
+  confXvPortPtr ports;
+  pointer options;
+}
+confXvAdaptorRec, *confXvAdaptorPtr;
+
+
+typedef struct _confscreenrec
+{
+  char *id;
+  int screennum;
+  int defaultdepth;
+  int defaultbpp;
+  int defaultfbbpp;
+  GDevPtr device;
+  int numdisplays;
+  DispPtr displays;
+  int numxvadaptors;
+  confXvAdaptorPtr xvadaptors;
+  pointer options;
+}
+confScreenRec, *confScreenPtr;
+
+
+typedef enum
+{
+  PosObsolete = -1,
+  PosAbsolute = 0,
+  PosRightOf,
+  PosLeftOf,
+  PosAbove,
+  PosBelow,
+  PosRelative
+}
+PositionType;
+
+
+typedef struct _screenlayoutrec
+{
+  confScreenPtr screen;
+  char *topname;
+  confScreenPtr top;
+  char *bottomname;
+  confScreenPtr bottom;
+  char *leftname;
+  confScreenPtr left;
+  char *rightname;
+  confScreenPtr right;
+  PositionType where;
+  int x;
+  int y;
+  char *refname;
+  confScreenPtr refscreen;
+}
+screenLayoutRec, *screenLayoutPtr;
+
+
+typedef struct _serverlayoutrec
+{
+  char *id;
+  screenLayoutPtr screens;
+  GDevPtr inactives;
+  IDevPtr inputs;
+  pointer options;
+}
+serverLayoutRec, *serverLayoutPtr;
+
+
+/*
+ * winconfig.c
+ */
+
+typedef struct
+{
+  /* Files */
+#ifdef XWIN_XF86CONFIG
+  char *configFile;
+#endif
+  char *fontPath;
+  /* input devices - keyboard */
+#ifdef XWIN_XF86CONFIG
+  char *keyboard;
+#endif
+#ifdef XKB
+  Bool noXkbExtension;
+  char *xkbMap;
+  char *xkbRules; 
+  char *xkbModel;
+  char *xkbLayout;
+  char *xkbVariant;
+  char *xkbOptions;
+#endif
+  /* layout */
+  char *screenname;
+  /* mouse settings */
+  char *mouse;
+  Bool emulate3buttons;
+  long emulate3timeout;
+}
+WinCmdlineRec, *WinCmdlinePtr;
+
+
+extern WinCmdlineRec g_cmdline;
+#ifdef XWIN_XF86CONFIG
+extern XF86ConfigPtr g_xf86configptr;
+#endif
+extern serverLayoutRec g_winConfigLayout;
+
+
+/*
+ * Function prototypes
+ */
+
+Bool winReadConfigfile (void);
+Bool winConfigFiles (void);
+Bool winConfigOptions (void);
+Bool winConfigScreens (void);
+Bool winConfigKeyboard (DeviceIntPtr pDevice);
+Bool winConfigMouse (DeviceIntPtr pDevice);
+
+
+typedef struct
+{
+  double freq;
+  int units;
+}
+OptFrequency;
+
+
+typedef union
+{
+  unsigned long num;
+  char *str;
+  double realnum;
+  Bool bool;
+  OptFrequency freq;
+}
+ValueUnion;
+
+
+typedef enum
+{
+  OPTV_NONE = 0,
+  OPTV_INTEGER,
+  OPTV_STRING,			/* a non-empty string */
+  OPTV_ANYSTR,			/* Any string, including an empty one */
+  OPTV_REAL,
+  OPTV_BOOLEAN,
+  OPTV_FREQ
+}
+OptionValueType;
+
+
+typedef enum
+{
+  OPTUNITS_HZ = 1,
+  OPTUNITS_KHZ,
+  OPTUNITS_MHZ
+}
+OptFreqUnits;
+
+
+typedef struct
+{
+  int token;
+  const char *name;
+  OptionValueType type;
+  ValueUnion value;
+  Bool found;
+}
+OptionInfoRec, *OptionInfoPtr;
+
+
+/*
+ * Function prototypes
+ */
+
+char *winSetStrOption (pointer optlist, const char *name, char *deflt);
+int winSetBoolOption (pointer optlist, const char *name, int deflt);
+int winSetIntOption (pointer optlist, const char *name, int deflt);
+double winSetRealOption (pointer optlist, const char *name, double deflt);
+#ifdef XWIN_XF86CONFIG
+XF86OptionPtr winFindOption (XF86OptionPtr list, const char *name);
+char *winFindOptionValue (XF86OptionPtr list, const char *name);
+#endif
+int winNameCompare (const char *s1, const char *s2);
+char *winNormalizeName (const char *s);
+
+
+typedef struct
+{
+  struct
+  {
+    long leds;
+    long delay;
+    long rate;
+  }
+  keyboard;
+#ifdef XKB
+  struct
+  {
+    Bool disable;
+    char *rules;
+    char *model;
+    char *layout;
+    char *variant;
+    char *options;
+    char *initialMap;
+    char *keymap;
+    char *types;
+    char *compat;
+    char *keycodes;
+    char *symbols;
+    char *geometry;
+  }
+  xkb;
+#endif
+  struct
+  {
+    Bool emulate3Buttons;
+    long emulate3Timeout;
+  }
+  pointer;
+}
+winInfoRec, *winInfoPtr;
+
+
+extern winInfoRec g_winInfo;
+
+#endif
diff --git a/hw/xwin/wincreatewnd.c b/hw/xwin/wincreatewnd.c
new file mode 100644
index 0000000..796a085
--- /dev/null
+++ b/hw/xwin/wincreatewnd.c
@@ -0,0 +1,644 @@
+/*
+ *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "shellapi.h"
+
+#ifndef ABS_AUTOHIDE
+#define ABS_AUTOHIDE 1
+#endif
+
+/*
+ * Local function prototypes
+ */
+
+static Bool
+winGetWorkArea (RECT *prcWorkArea, winScreenInfo *pScreenInfo);
+
+static Bool
+winAdjustForAutoHide (RECT *prcWorkArea);
+
+
+/*
+ * Create a full screen window
+ */
+
+Bool
+winCreateBoundingWindowFullScreen (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  int			iX = pScreenInfo->dwInitialX;
+  int			iY = pScreenInfo->dwInitialY;
+  int			iWidth = pScreenInfo->dwWidth;
+  int			iHeight = pScreenInfo->dwHeight;
+  HWND			*phwnd = &pScreenPriv->hwndScreen;
+  WNDCLASS		wc;
+  char			szTitle[256];
+
+#if CYGDEBUG
+  winDebug ("winCreateBoundingWindowFullScreen\n");
+#endif
+
+  /* Setup our window class */
+  wc.style = CS_HREDRAW | CS_VREDRAW;
+  wc.lpfnWndProc = winWindowProc;
+  wc.cbClsExtra = 0;
+  wc.cbWndExtra = 0;
+  wc.hInstance = g_hInstance;
+  wc.hIcon = LoadIcon (g_hInstance, MAKEINTRESOURCE(IDI_XWIN));
+  wc.hCursor = 0;
+  wc.hbrBackground = 0;
+  wc.lpszMenuName = NULL;
+  wc.lpszClassName = WINDOW_CLASS;
+  RegisterClass (&wc);
+
+  /* Set display and screen-specific tooltip text */
+  if (g_pszQueryHost != NULL)
+    snprintf (szTitle,
+	    sizeof (szTitle),
+	    WINDOW_TITLE_XDMCP,
+	    g_pszQueryHost); 
+  else    
+    snprintf (szTitle,
+	    sizeof (szTitle),
+	    WINDOW_TITLE,
+	    display, 
+	    (int) pScreenInfo->dwScreen);
+
+  /* Create the window */
+  *phwnd = CreateWindowExA (0,			/* Extended styles */
+			    WINDOW_CLASS,	/* Class name */
+			    szTitle,		/* Window name */
+			    WS_POPUP,
+			    iX,			/* Horizontal position */
+			    iY,			/* Vertical position */
+			    iWidth,		/* Right edge */ 
+			    iHeight,		/* Bottom edge */
+			    (HWND) NULL,	/* No parent or owner window */
+			    (HMENU) NULL,	/* No menu */
+			    GetModuleHandle (NULL),/* Instance handle */
+			    pScreenPriv);	/* ScreenPrivates */
+
+  /* Branch on the server engine */
+  switch (pScreenInfo->dwEngine)
+    {
+#ifdef XWIN_NATIVEGDI
+    case WIN_SERVER_SHADOW_GDI:
+      /* Show the window */
+      ShowWindow (*phwnd, SW_SHOWMAXIMIZED);
+      break;
+#endif
+
+    default:
+      /* Hide the window */
+      ShowWindow (*phwnd, SW_SHOWNORMAL);
+      break;
+    }
+
+  /* Send first paint message */
+  UpdateWindow (*phwnd);
+
+  /* Attempt to bring our window to the top of the display */
+  BringWindowToTop (*phwnd);
+
+  return TRUE;
+}
+
+
+/*
+ * Create our primary Windows display window
+ */
+
+Bool
+winCreateBoundingWindowWindowed (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  int			iWidth = pScreenInfo->dwUserWidth;
+  int			iHeight = pScreenInfo->dwUserHeight;
+  int                   iPosX;
+  int                   iPosY;
+  HWND			*phwnd = &pScreenPriv->hwndScreen;
+  WNDCLASS		wc;
+  RECT			rcClient, rcWorkArea;
+  DWORD			dwWindowStyle;
+  BOOL			fForceShowWindow = FALSE;
+  char			szTitle[256];
+  
+  winDebug ("winCreateBoundingWindowWindowed - User w: %d h: %d\n",
+	  (int) pScreenInfo->dwUserWidth, (int) pScreenInfo->dwUserHeight);
+  winDebug ("winCreateBoundingWindowWindowed - Current w: %d h: %d\n",
+	  (int) pScreenInfo->dwWidth, (int) pScreenInfo->dwHeight);
+
+  /* Set the common window style flags */
+  dwWindowStyle = WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX;
+  
+  /* Decorated or undecorated window */
+  if (pScreenInfo->fDecoration
+#ifdef XWIN_MULTIWINDOWEXTWM
+      && !pScreenInfo->fMWExtWM
+#endif
+      && !pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOW
+      && !pScreenInfo->fMultiWindow
+#endif
+      )
+    {
+        /* Try to handle startup via run.exe. run.exe instructs Windows to 
+         * hide all created windows. Detect this case and make sure the 
+         * window is shown nevertheless */
+        STARTUPINFO   startupInfo;
+        GetStartupInfo(&startupInfo);
+        if (startupInfo.dwFlags & STARTF_USESHOWWINDOW && 
+                startupInfo.wShowWindow == SW_HIDE)
+        {
+          fForceShowWindow = TRUE;
+        } 
+        dwWindowStyle |= WS_CAPTION;
+        if (pScreenInfo->fScrollbars)
+            dwWindowStyle |= WS_THICKFRAME | WS_MAXIMIZEBOX;
+    }
+  else
+    dwWindowStyle |= WS_POPUP;
+
+  /* Setup our window class */
+  wc.style = CS_HREDRAW | CS_VREDRAW;
+  wc.lpfnWndProc = winWindowProc;
+  wc.cbClsExtra = 0;
+  wc.cbWndExtra = 0;
+  wc.hInstance = g_hInstance;
+  wc.hIcon = LoadIcon (g_hInstance, MAKEINTRESOURCE(IDI_XWIN));
+  wc.hCursor = 0;
+  wc.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
+  wc.lpszMenuName = NULL;
+  wc.lpszClassName = WINDOW_CLASS;
+  RegisterClass (&wc);
+
+  /* Get size of work area */
+  winGetWorkArea (&rcWorkArea, pScreenInfo);
+
+  /* Adjust for auto-hide taskbars */
+  winAdjustForAutoHide (&rcWorkArea);
+
+  /* Did the user specify a position? */
+  if (pScreenInfo->fUserGavePosition)
+    {
+      iPosX = pScreenInfo->dwInitialX;
+      iPosY = pScreenInfo->dwInitialY;
+    }
+  else
+    {
+      iPosX = rcWorkArea.left;
+      iPosY = rcWorkArea.top;
+    }
+
+  /* Did the user specify a height and width? */
+  if (pScreenInfo->fUserGaveHeightAndWidth)
+    {
+      /* User gave a desired height and width, try to accomodate */
+#if CYGDEBUG
+      winDebug ("winCreateBoundingWindowWindowed - User gave height "
+	      "and width\n");
+#endif
+      
+      /* Adjust the window width and height for borders and title bar */
+      if (pScreenInfo->fDecoration
+#ifdef XWIN_MULTIWINDOWEXTWM
+	  && !pScreenInfo->fMWExtWM
+#endif
+	  && !pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOW
+	  && !pScreenInfo->fMultiWindow
+#endif
+	  )
+	{
+#if CYGDEBUG
+	  winDebug ("winCreateBoundingWindowWindowed - Window has decoration\n");
+#endif
+	  /* Are we using scrollbars? */
+	  if (pScreenInfo->fScrollbars)
+	    {
+#if CYGDEBUG
+	      winDebug ("winCreateBoundingWindowWindowed - Window has "
+		      "scrollbars\n");
+#endif
+
+	      iWidth += 2 * GetSystemMetrics (SM_CXSIZEFRAME);
+	      iHeight += 2 * GetSystemMetrics (SM_CYSIZEFRAME) 
+		+ GetSystemMetrics (SM_CYCAPTION);
+	    }
+	  else
+	    {
+#if CYGDEBUG
+	      winDebug ("winCreateBoundingWindowWindowed - Window does not have "
+		      "scrollbars\n");
+#endif
+
+	      iWidth += 2 * GetSystemMetrics (SM_CXFIXEDFRAME);
+	      iHeight += 2 * GetSystemMetrics (SM_CYFIXEDFRAME) 
+		+ GetSystemMetrics (SM_CYCAPTION);
+	    }
+	}
+    }
+  else
+    {
+      /* By default, we are creating a window that is as large as possible */
+#if CYGDEBUG
+      winDebug ("winCreateBoundingWindowWindowed - User did not give "
+	      "height and width\n");
+#endif
+      /* Defaults are wrong if we have multiple monitors */
+      if (pScreenInfo->fMultipleMonitors)
+	{
+	  iWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
+	  iHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
+	}
+    }
+
+  /* Clean up the scrollbars flag, if necessary */
+  if ((!pScreenInfo->fDecoration
+#ifdef XWIN_MULTIWINDOWEXTWM
+       || pScreenInfo->fMWExtWM
+#endif
+       || pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOW
+       || pScreenInfo->fMultiWindow
+#endif
+       )
+      && pScreenInfo->fScrollbars)
+    {
+      /* We cannot have scrollbars if we do not have a window border */
+      pScreenInfo->fScrollbars = FALSE;
+    }
+ 
+  if (TRUE 
+#ifdef XWIN_MULTIWINDOWEXTWM
+       && !pScreenInfo->fMWExtWM
+#endif
+#ifdef XWIN_MULTIWINDOW
+       && !pScreenInfo->fMultiWindow
+#endif
+     )
+    {
+      /* Trim window width to fit work area */
+      if (iWidth > (rcWorkArea.right - rcWorkArea.left))
+        iWidth = rcWorkArea.right - rcWorkArea.left;
+  
+      /* Trim window height to fit work area */
+      if (iHeight >= (rcWorkArea.bottom - rcWorkArea.top))
+        iHeight = rcWorkArea.bottom - rcWorkArea.top;
+  
+#if CYGDEBUG
+      winDebug ("winCreateBoundingWindowWindowed - Adjusted width: %d "\
+	      "height: %d\n",
+    	  iWidth, iHeight);
+#endif
+    }
+
+  /* Set display and screen-specific tooltip text */
+  if (g_pszQueryHost != NULL)
+    snprintf (szTitle,
+	    sizeof (szTitle),
+	    WINDOW_TITLE_XDMCP,
+	    g_pszQueryHost); 
+  else    
+    snprintf (szTitle,
+	    sizeof (szTitle),
+	    WINDOW_TITLE,
+	    display, 
+	    (int) pScreenInfo->dwScreen);
+
+  /* Create the window */
+  *phwnd = CreateWindowExA (0,			/* Extended styles */
+			    WINDOW_CLASS,	/* Class name */
+			    szTitle,		/* Window name */
+			    dwWindowStyle,
+			    iPosX,	        /* Horizontal position */
+			    iPosY,	        /* Vertical position */
+			    iWidth,		/* Right edge */
+			    iHeight,		/* Bottom edge */
+			    (HWND) NULL,	/* No parent or owner window */
+			    (HMENU) NULL,	/* No menu */
+			    GetModuleHandle (NULL),/* Instance handle */
+			    pScreenPriv);	/* ScreenPrivates */
+  if (*phwnd == NULL)
+    {
+      ErrorF ("winCreateBoundingWindowWindowed - CreateWindowEx () failed\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winCreateBoundingWindowWindowed - CreateWindowEx () returned\n");
+#endif
+
+  if (fForceShowWindow)
+  {
+      ErrorF("winCreateBoundingWindowWindowed - Setting normal windowstyle\n");
+      ShowWindow(*phwnd, SW_SHOW);      
+  }
+
+  /* Get the client area coordinates */
+  if (!GetClientRect (*phwnd, &rcClient))
+    {
+      ErrorF ("winCreateBoundingWindowWindowed - GetClientRect () "
+	      "failed\n");
+      return FALSE;
+    }
+
+  winDebug ("winCreateBoundingWindowWindowed - WindowClient "
+	  "w %ld h %ld r %ld l %ld b %ld t %ld\n",
+	  rcClient.right - rcClient.left,
+	  rcClient.bottom - rcClient.top,
+	  rcClient.right, rcClient.left,
+	  rcClient.bottom, rcClient.top);
+  
+  /* We adjust the visual size if the user did not specify it */
+  if (!(pScreenInfo->fScrollbars && pScreenInfo->fUserGaveHeightAndWidth))
+    {
+      /*
+       * User did not give a height and width with scrollbars enabled,
+       * so we will resize the underlying visual to be as large as
+       * the initial view port (page size).  This way scrollbars will
+       * not appear until the user shrinks the window, if they ever do.
+       *
+       * NOTE: We have to store the viewport size here because
+       * the user may have an autohide taskbar, which would
+       * cause the viewport size to be one less in one dimension
+       * than the viewport size that we calculated by subtracting
+       * the size of the borders and caption.
+       */
+      pScreenInfo->dwWidth = rcClient.right - rcClient.left;
+      pScreenInfo->dwHeight = rcClient.bottom - rcClient.top;
+    }
+
+#if 0
+  /*
+   * NOTE: For the uninitiated, the page size is the number of pixels
+   * that we can display in the x or y direction at a time and the
+   * range is the total number of pixels in the x or y direction that we
+   * have available to display.  In other words, the page size is the
+   * size of the window area minus the space the caption, borders, and
+   * scrollbars (if any) occupy, and the range is the size of the
+   * underlying X visual.  Notice that, contrary to what some of the
+   * MSDN Library arcticles lead you to believe, the windows
+   * ``client area'' size does not include the scrollbars.  In other words,
+   * the whole client area size that is reported to you is drawable by
+   * you; you do not have to subtract the size of the scrollbars from
+   * the client area size, and if you did it would result in the size
+   * of the scrollbars being double counted.
+   */
+
+  /* Setup scrollbar page and range, if scrollbars are enabled */
+  if (pScreenInfo->fScrollbars)
+    {
+      SCROLLINFO		si;
+      
+      /* Initialize the scrollbar info structure */
+      si.cbSize = sizeof (si);
+      si.fMask = SIF_RANGE | SIF_PAGE;
+      si.nMin = 0;
+      
+      /* Setup the width range and page size */
+      si.nMax = pScreenInfo->dwWidth - 1;
+      si.nPage = rcClient.right - rcClient.left;
+      winDebug ("winCreateBoundingWindowWindowed - HORZ nMax: %d nPage :%d\n",
+	      si.nMax, si.nPage);
+      SetScrollInfo (*phwnd, SB_HORZ, &si, TRUE);
+      
+      /* Setup the height range and page size */
+      si.nMax = pScreenInfo->dwHeight - 1;
+      si.nPage = rcClient.bottom - rcClient.top;
+      winDebug ("winCreateBoundingWindowWindowed - VERT nMax: %d nPage :%d\n",
+	      si.nMax, si.nPage);
+      SetScrollInfo (*phwnd, SB_VERT, &si, TRUE);
+    }
+#endif
+
+  /* Show the window */
+  if (FALSE
+#ifdef XWIN_MULTIWINDOWEXTWM
+      || pScreenInfo->fMWExtWM
+#endif
+#ifdef XWIN_MULTIWINDOW
+      || pScreenInfo->fMultiWindow
+#endif
+      )
+    {
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+      pScreenPriv->fRootWindowShown = FALSE;
+#endif
+      ShowWindow (*phwnd, SW_HIDE);
+    }
+  else
+    ShowWindow (*phwnd, SW_SHOWNORMAL);
+  if (!UpdateWindow (*phwnd))
+    {
+      ErrorF ("winCreateBoundingWindowWindowed - UpdateWindow () failed\n");
+      return FALSE;
+    }
+  
+  /* Attempt to bring our window to the top of the display */
+  if (TRUE
+#ifdef XWIN_MULTIWINDOWEXTWM
+      && !pScreenInfo->fMWExtWM
+#endif
+      && !pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOW
+      && !pScreenInfo->fMultiWindow
+#endif
+      )
+    {
+      if (!BringWindowToTop (*phwnd))
+	{
+	  ErrorF ("winCreateBoundingWindowWindowed - BringWindowToTop () "
+		  "failed\n");
+	  return FALSE;
+	}
+    }
+
+#ifdef XWIN_NATIVEGDI
+  /* Paint window background blue */
+  if (pScreenInfo->dwEngine == WIN_SERVER_NATIVE_GDI)
+    winPaintBackground (*phwnd, RGB (0x00, 0x00, 0xFF));
+#endif
+
+  winDebug ("winCreateBoundingWindowWindowed -  Returning\n");
+
+  return TRUE;
+}
+
+
+/*
+ * Find the work area of all attached monitors
+ */
+
+static Bool
+winGetWorkArea (RECT *prcWorkArea, winScreenInfo *pScreenInfo)
+{
+  int			iPrimaryWidth, iPrimaryHeight;
+  int			iWidth, iHeight;
+  int			iLeft, iTop;
+  int			iPrimaryNonWorkAreaWidth, iPrimaryNonWorkAreaHeight;
+
+  /* SPI_GETWORKAREA only gets the work area of the primary screen. */
+  SystemParametersInfo (SPI_GETWORKAREA, 0, prcWorkArea, 0);
+
+  /* Bail out here if we aren't using multiple monitors */
+  if (!pScreenInfo->fMultipleMonitors)
+    return TRUE;
+  
+  winDebug ("winGetWorkArea - Original WorkArea: %d %d %d %d\n",
+	  (int) prcWorkArea->top, (int) prcWorkArea->left,
+	  (int) prcWorkArea->bottom, (int) prcWorkArea->right);
+
+  /* Get size of full virtual screen */
+  iWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
+  iHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
+
+  winDebug ("winGetWorkArea - Virtual screen is %d x %d\n", iWidth, iHeight);
+
+  /* Get origin of full virtual screen */
+  iLeft = GetSystemMetrics (SM_XVIRTUALSCREEN);
+  iTop = GetSystemMetrics (SM_YVIRTUALSCREEN);
+
+  winDebug ("winGetWorkArea - Virtual screen origin is %d, %d\n", iLeft, iTop);
+  
+  /* Get size of primary screen */
+  iPrimaryWidth = GetSystemMetrics (SM_CXSCREEN);
+  iPrimaryHeight = GetSystemMetrics (SM_CYSCREEN);
+
+  winDebug ("winGetWorkArea - Primary screen is %d x %d\n",
+	 iPrimaryWidth, iPrimaryHeight);
+  
+  /* Work out how much of the primary screen we aren't using */
+  iPrimaryNonWorkAreaWidth = iPrimaryWidth - (prcWorkArea->right -
+					      prcWorkArea->left);
+  iPrimaryNonWorkAreaHeight = iPrimaryHeight - (prcWorkArea->bottom
+						- prcWorkArea->top);
+  
+  /* Update the rectangle to include all monitors */
+  if (iLeft < 0) 
+    {
+      prcWorkArea->left = iLeft;
+    }
+  if (iTop < 0) 
+    {
+      prcWorkArea->top = iTop;
+    }
+  prcWorkArea->right = prcWorkArea->left + iWidth -
+    iPrimaryNonWorkAreaWidth;
+  prcWorkArea->bottom = prcWorkArea->top + iHeight -
+    iPrimaryNonWorkAreaHeight;
+  
+  winDebug ("winGetWorkArea - Adjusted WorkArea for multiple "
+	  "monitors: %d %d %d %d\n",
+	  (int) prcWorkArea->top, (int) prcWorkArea->left,
+	  (int) prcWorkArea->bottom, (int) prcWorkArea->right);
+  
+  return TRUE;
+}
+
+
+/*
+ * Adjust the client area so that any auto-hide toolbars
+ * will work correctly.
+ */
+
+static Bool
+winAdjustForAutoHide (RECT *prcWorkArea)
+{
+  APPBARDATA		abd;
+  HWND			hwndAutoHide;
+
+  winDebug ("winAdjustForAutoHide - Original WorkArea: %d %d %d %d\n",
+	  (int) prcWorkArea->top, (int) prcWorkArea->left,
+	  (int) prcWorkArea->bottom, (int) prcWorkArea->right);
+
+  /* Find out if the Windows taskbar is set to auto-hide */
+  ZeroMemory (&abd, sizeof (abd));
+  abd.cbSize = sizeof (abd);
+  if (SHAppBarMessage (ABM_GETSTATE, &abd) & ABS_AUTOHIDE)
+    winDebug ("winAdjustForAutoHide - Taskbar is auto hide\n");
+
+  /* Look for a TOP auto-hide taskbar */
+  abd.uEdge = ABE_TOP;
+  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETAUTOHIDEBAR, &abd);
+  if (hwndAutoHide != NULL)
+    {
+      winDebug ("winAdjustForAutoHide - Found TOP auto-hide taskbar\n");
+      prcWorkArea->top += 1;
+    }
+
+  /* Look for a LEFT auto-hide taskbar */
+  abd.uEdge = ABE_LEFT;
+  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETAUTOHIDEBAR, &abd);
+  if (hwndAutoHide != NULL)
+    {
+      winDebug ("winAdjustForAutoHide - Found LEFT auto-hide taskbar\n");
+      prcWorkArea->left += 1;
+    }
+
+  /* Look for a BOTTOM auto-hide taskbar */
+  abd.uEdge = ABE_BOTTOM;
+  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETAUTOHIDEBAR, &abd);
+  if (hwndAutoHide != NULL)
+    {
+      winDebug ("winAdjustForAutoHide - Found BOTTOM auto-hide taskbar\n");
+      prcWorkArea->bottom -= 1;
+    }
+
+  /* Look for a RIGHT auto-hide taskbar */
+  abd.uEdge = ABE_RIGHT;
+  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETAUTOHIDEBAR, &abd);
+  if (hwndAutoHide != NULL)
+    {
+      winDebug ("winAdjustForAutoHide - Found RIGHT auto-hide taskbar\n");
+      prcWorkArea->right -= 1;
+    }
+
+  winDebug ("winAdjustForAutoHide - Adjusted WorkArea: %d %d %d %d\n",
+	  (int) prcWorkArea->top, (int) prcWorkArea->left,
+	  (int) prcWorkArea->bottom, (int) prcWorkArea->right);
+  
+#if 0
+  /* Obtain the task bar window dimensions */
+  abd.hWnd = hwndAutoHide;
+  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETTASKBARPOS, &abd);
+  winDebug ("hwndAutoHide %08x abd.hWnd %08x %d %d %d %d\n",
+	  hwndAutoHide, abd.hWnd,
+	  abd.rc.top, abd.rc.left, abd.rc.bottom, abd.rc.right);
+#endif
+
+  return TRUE;
+}
diff --git a/hw/xwin/wincursor.c b/hw/xwin/wincursor.c
new file mode 100644
index 0000000..021b8b8
--- /dev/null
+++ b/hw/xwin/wincursor.c
@@ -0,0 +1,614 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winmsg.h"
+#include <cursorstr.h>
+#include <mipointrst.h>
+#include <servermd.h>
+
+extern Bool	g_fSoftwareCursor;
+
+
+#ifndef MIN
+#define MIN(x,y) ((x)<(y)?(x):(y))
+#endif
+
+#define BYTE_COUNT(x) (((x) + 7) / 8)
+
+#define BRIGHTNESS(x) (x##Red * 0.299 + x##Green * 0.587 + x##Blue * 0.114)
+
+#if 0
+# define WIN_DEBUG_MSG winDebug
+#else
+# define WIN_DEBUG_MSG(...)
+#endif
+
+/*
+ * Local function prototypes
+ */
+
+static void
+winPointerWarpCursor (ScreenPtr pScreen, int x, int y);
+
+static Bool
+winCursorOffScreen (ScreenPtr *ppScreen, int *x, int *y);
+
+static void
+winCrossScreen (ScreenPtr pScreen, Bool fEntering);
+
+miPointerScreenFuncRec g_winPointerCursorFuncs =
+{
+  winCursorOffScreen,
+  winCrossScreen,
+  winPointerWarpCursor
+};
+
+
+static void
+winPointerWarpCursor (ScreenPtr pScreen, int x, int y)
+{
+  winScreenPriv(pScreen);
+  RECT			rcClient;
+  static Bool		s_fInitialWarp = TRUE;
+
+  /* Discard first warp call */
+  if (s_fInitialWarp)
+    {
+      /* First warp moves mouse to center of window, just ignore it */
+
+      /* Don't ignore subsequent warps */
+      s_fInitialWarp = FALSE;
+
+      winErrorFVerb (2, "winPointerWarpCursor - Discarding first warp: %d %d\n",
+	      x, y);
+      
+      return;
+    }
+
+  /* Only update the Windows cursor position if we are active */
+  if (pScreenPriv->hwndScreen == GetForegroundWindow ())
+    {
+      /* Get the client area coordinates */
+      GetClientRect (pScreenPriv->hwndScreen, &rcClient);
+      
+      /* Translate the client area coords to screen coords */
+      MapWindowPoints (pScreenPriv->hwndScreen,
+		       HWND_DESKTOP,
+		       (LPPOINT)&rcClient,
+		       2);
+      
+      /* 
+       * Update the Windows cursor position so that we don't
+       * immediately warp back to the current position.
+       */
+      SetCursorPos (rcClient.left + x, rcClient.top + y);
+    }
+
+  /* Call the mi warp procedure to do the actual warping in X. */
+  miPointerWarpCursor (pScreen, x, y);
+}
+
+static Bool
+winCursorOffScreen (ScreenPtr *ppScreen, int *x, int *y)
+{
+  return FALSE;
+}
+
+static void
+winCrossScreen (ScreenPtr pScreen, Bool fEntering)
+{
+}
+
+static unsigned char
+reverse(unsigned char c)
+{
+  int i;
+  unsigned char ret = 0;
+  for (i = 0; i < 8; ++i)
+    {
+      ret |= ((c >> i)&1) << (7 - i);
+    }
+  return ret;
+}
+
+/*
+ * Convert X cursor to Windows cursor
+ * FIXME: Perhaps there are more smart code
+ */
+static HCURSOR
+winLoadCursor (ScreenPtr pScreen, CursorPtr pCursor, int screen)
+{
+  winScreenPriv(pScreen);
+  HCURSOR hCursor = NULL;
+  unsigned char *pAnd;
+  unsigned char *pXor;
+  int nCX, nCY;
+  int nBytes;
+  double dForeY, dBackY;
+  BOOL fReverse;
+  HBITMAP hAnd, hXor;
+  ICONINFO ii;
+  unsigned char *pCur;
+  int x, y;
+  unsigned char bit;
+  HDC hDC;
+  BITMAPV4HEADER bi;
+  BITMAPINFO *pbmi;
+  unsigned long *lpBits;
+
+  WIN_DEBUG_MSG("winLoadCursor: Win32: %dx%d X11: %dx%d hotspot: %d,%d\n", 
+          pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy,
+          pCursor->bits->width, pCursor->bits->height,
+          pCursor->bits->xhot, pCursor->bits->yhot
+          );
+
+  /* We can use only White and Black, so calc brightness of color 
+   * Also check if the cursor is inverted */  
+  dForeY = BRIGHTNESS(pCursor->fore);
+  dBackY = BRIGHTNESS(pCursor->back);
+  fReverse = dForeY < dBackY;
+ 
+  /* Check wether the X11 cursor is bigger than the win32 cursor */
+  if (pScreenPriv->cursor.sm_cx < pCursor->bits->width || 
+      pScreenPriv->cursor.sm_cy < pCursor->bits->height)
+    {
+      winErrorFVerb (2, "winLoadCursor - Windows requires %dx%d cursor\n"
+	      "\tbut X requires %dx%d\n",
+	      pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy,
+	      pCursor->bits->width, pCursor->bits->height);
+    }
+
+  /* Get the number of bytes required to store the whole cursor image 
+   * This is roughly (sm_cx * sm_cy) / 8 
+   * round up to 8 pixel boundary so we can convert whole bytes */
+  nBytes = BYTE_COUNT(pScreenPriv->cursor.sm_cx) * pScreenPriv->cursor.sm_cy;
+
+  /* Get the effective width and height */
+  nCX = MIN(pScreenPriv->cursor.sm_cx, pCursor->bits->width);
+  nCY = MIN(pScreenPriv->cursor.sm_cy, pCursor->bits->height);
+
+  /* Allocate memory for the bitmaps */
+  pAnd = malloc (nBytes);
+  memset (pAnd, 0xFF, nBytes);
+  pXor = malloc (nBytes);
+  memset (pXor, 0x00, nBytes);
+
+  /* Convert the X11 bitmap to a win32 bitmap 
+   * The first is for an empty mask */
+  if (pCursor->bits->emptyMask)
+    {
+      int x, y, xmax = BYTE_COUNT(nCX);
+      for (y = 0; y < nCY; ++y)
+	for (x = 0; x < xmax; ++x)
+	  {
+	    int nWinPix = BYTE_COUNT(pScreenPriv->cursor.sm_cx) * y + x;
+	    int nXPix = BitmapBytePad(pCursor->bits->width) * y + x;
+
+	    pAnd[nWinPix] = 0;
+	    if (fReverse)
+	      pXor[nWinPix] = reverse (~pCursor->bits->source[nXPix]);
+	    else
+	      pXor[nWinPix] = reverse (pCursor->bits->source[nXPix]);
+	  }
+    }
+  else
+    {
+      int x, y, xmax = BYTE_COUNT(nCX);
+      for (y = 0; y < nCY; ++y)
+	for (x = 0; x < xmax; ++x)
+	  {
+	    int nWinPix = BYTE_COUNT(pScreenPriv->cursor.sm_cx) * y + x;
+	    int nXPix = BitmapBytePad(pCursor->bits->width) * y + x;
+
+	    unsigned char mask = pCursor->bits->mask[nXPix];
+	    pAnd[nWinPix] = reverse (~mask);
+	    if (fReverse)
+	      pXor[nWinPix] = reverse (~pCursor->bits->source[nXPix] & mask);
+	    else
+	      pXor[nWinPix] = reverse (pCursor->bits->source[nXPix] & mask);
+	  }
+    }
+
+  /* prepare the pointers */ 
+  hCursor = NULL;
+  lpBits = NULL;
+
+  /* We have a truecolor alpha-blended cursor and can use it! */
+  if (pCursor->bits->argb) 
+    {
+      WIN_DEBUG_MSG("winLoadCursor: Trying truecolor alphablended cursor\n"); 
+      memset (&bi, 0, sizeof (BITMAPV4HEADER));
+      bi.bV4Size = sizeof(BITMAPV4HEADER);
+      bi.bV4Width = pScreenPriv->cursor.sm_cx;
+      bi.bV4Height = -(pScreenPriv->cursor.sm_cy); /* right-side up */
+      bi.bV4Planes = 1;
+      bi.bV4BitCount = 32;
+      bi.bV4V4Compression = BI_BITFIELDS;
+      bi.bV4RedMask = 0x00FF0000;
+      bi.bV4GreenMask = 0x0000FF00;
+      bi.bV4BlueMask = 0x000000FF;
+      bi.bV4AlphaMask = 0xFF000000; 
+      
+      lpBits = (unsigned long *) calloc (pScreenPriv->cursor.sm_cx*pScreenPriv->cursor.sm_cy,
+					 sizeof (unsigned long));
+      
+      if (lpBits)
+	{
+	  for (y=0; y<nCY; y++)
+	    {
+	      unsigned long *src, *dst;
+	      src = &(pCursor->bits->argb[y * pCursor->bits->width]);
+	      dst = &(lpBits[y * pScreenPriv->cursor.sm_cx]);
+	      memcpy (dst, src, 4*nCX);
+	    }
+	}
+    } /* End if-truecolor-icon */
+  
+  if (!lpBits)
+    {
+      /* Bicolor, use a palettized DIB */
+      WIN_DEBUG_MSG("winLoadCursor: Trying two color cursor\n"); 
+      pbmi = (BITMAPINFO*)&bi;
+      memset (pbmi, 0, sizeof (BITMAPINFOHEADER));
+      pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+      pbmi->bmiHeader.biWidth = pScreenPriv->cursor.sm_cx;
+      pbmi->bmiHeader.biHeight = -abs(pScreenPriv->cursor.sm_cy); /* right-side up */
+      pbmi->bmiHeader.biPlanes = 1;
+      pbmi->bmiHeader.biBitCount = 8;
+      pbmi->bmiHeader.biCompression = BI_RGB;
+      pbmi->bmiHeader.biSizeImage = 0;
+      pbmi->bmiHeader.biClrUsed = 3;
+      pbmi->bmiHeader.biClrImportant = 3;
+      pbmi->bmiColors[0].rgbRed = 0; /* Empty */
+      pbmi->bmiColors[0].rgbGreen = 0;
+      pbmi->bmiColors[0].rgbBlue = 0;
+      pbmi->bmiColors[0].rgbReserved = 0;
+      pbmi->bmiColors[1].rgbRed = pCursor->backRed>>8; /* Background */
+      pbmi->bmiColors[1].rgbGreen = pCursor->backGreen>>8;
+      pbmi->bmiColors[1].rgbBlue = pCursor->backBlue>>8;
+      pbmi->bmiColors[1].rgbReserved = 0;
+      pbmi->bmiColors[2].rgbRed = pCursor->foreRed>>8; /* Foreground */
+      pbmi->bmiColors[2].rgbGreen = pCursor->foreGreen>>8;
+      pbmi->bmiColors[2].rgbBlue = pCursor->foreBlue>>8;
+      pbmi->bmiColors[2].rgbReserved = 0;
+      
+      lpBits = (unsigned long *) calloc (pScreenPriv->cursor.sm_cx*pScreenPriv->cursor.sm_cy,
+					 sizeof (char));
+      
+      pCur = (unsigned char *)lpBits;
+      if (lpBits)
+	{
+	  for (y=0; y<pScreenPriv->cursor.sm_cy; y++)
+	    {
+	      for (x=0; x<pScreenPriv->cursor.sm_cx; x++)
+		{
+		  if (x>=nCX || y>=nCY) /* Outside of X11 icon bounds */
+		    (*pCur++) = 0;
+		  else /* Within X11 icon bounds */
+		    {
+		      int nWinPix = BYTE_COUNT(pScreenPriv->cursor.sm_cx) * y + (x/8);
+
+		      bit = pAnd[nWinPix];
+		      bit = bit & (1<<(7-(x&7)));
+		      if (!bit) /* Within the cursor mask? */
+			{
+			  int nXPix = BitmapBytePad(pCursor->bits->width) * y + (x/8);
+			  bit = ~reverse(~pCursor->bits->source[nXPix] & pCursor->bits->mask[nXPix]);
+			  bit = bit & (1<<(7-(x&7)));
+			  if (bit) /* Draw foreground */
+			    (*pCur++) = 2;
+			  else /* Draw background */
+			    (*pCur++) = 1;
+			}
+		      else /* Outside the cursor mask */
+			(*pCur++) = 0;
+		    }
+		} /* end for (x) */
+	    } /* end for (y) */
+	} /* end if (lpbits) */
+    }
+
+  /* If one of the previous two methods gave us the bitmap we need, make a cursor */
+  if (lpBits)
+    {
+      WIN_DEBUG_MSG("winLoadCursor: Creating bitmap cursor: hotspot %d,%d\n",
+              pCursor->bits->xhot, pCursor->bits->yhot);
+
+      hAnd = NULL;
+      hXor = NULL;
+
+      hAnd = CreateBitmap (pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy, 1, 1, pAnd);
+
+      hDC = GetDC (NULL);
+      if (hDC)
+	{
+	  hXor = CreateCompatibleBitmap (hDC, pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy);
+	  SetDIBits (hDC, hXor, 0, pScreenPriv->cursor.sm_cy, lpBits, (BITMAPINFO*)&bi, DIB_RGB_COLORS);
+	  ReleaseDC (NULL, hDC);
+	}
+      free (lpBits);
+      
+      
+      if (hAnd && hXor)
+	{
+	  ii.fIcon = FALSE;
+	  ii.xHotspot = pCursor->bits->xhot;
+	  ii.yHotspot = pCursor->bits->yhot;
+	  ii.hbmMask = hAnd;
+	  ii.hbmColor = hXor;
+	  hCursor = (HCURSOR) CreateIconIndirect( &ii );
+
+	  if (hCursor == NULL)
+	    winW32Error(2, "winLoadCursor - CreateIconIndirect failed:");
+	  else 
+	    {
+	      if (GetIconInfo(hCursor, &ii))
+		{
+		  if (ii.fIcon)
+		    {
+		      WIN_DEBUG_MSG("winLoadCursor: CreateIconIndirect returned  no cursor. Trying again.\n");
+		      
+		      DestroyCursor(hCursor);
+		      
+		      ii.fIcon = FALSE;
+		      ii.xHotspot = pCursor->bits->xhot;
+		      ii.yHotspot = pCursor->bits->yhot;
+		      hCursor = (HCURSOR) CreateIconIndirect( &ii );
+		      
+		      if (hCursor == NULL)
+			winW32Error(2, "winLoadCursor - CreateIconIndirect failed:");
+		    }
+		  /* GetIconInfo creates new bitmaps. Destroy them again */
+		  if (ii.hbmMask)
+     	            DeleteObject(ii.hbmMask);
+		  if (ii.hbmColor)
+		    DeleteObject(ii.hbmColor);
+		}
+	    }
+	}
+
+      if (hAnd)
+	DeleteObject (hAnd);
+      if (hXor)
+	DeleteObject (hXor);
+    }
+
+  if (!hCursor)
+    {
+      /* We couldn't make a color cursor for this screen, use
+	 black and white instead */
+      hCursor = CreateCursor (g_hInstance,
+			      pCursor->bits->xhot, pCursor->bits->yhot,
+			      pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy,
+			      pAnd, pXor);
+      if (hCursor == NULL)
+	winW32Error(2, "winLoadCursor - CreateCursor failed:");
+    }
+  free (pAnd);
+  free (pXor);
+
+  return hCursor;
+}
+
+/*
+===========================================================================
+
+ Pointer sprite functions
+
+===========================================================================
+*/
+
+/*
+ * winRealizeCursor
+ *  Convert the X cursor representation to native format if possible.
+ */
+static Bool
+winRealizeCursor (ScreenPtr pScreen, CursorPtr pCursor)
+{
+  if(pCursor == NULL || pCursor->bits == NULL)
+    return FALSE;
+  
+  /* FIXME: cache ARGB8888 representation? */
+
+  return TRUE;
+}
+
+
+/*
+ * winUnrealizeCursor
+ *  Free the storage space associated with a realized cursor.
+ */
+static Bool
+winUnrealizeCursor(ScreenPtr pScreen, CursorPtr pCursor)
+{
+  return TRUE;
+}
+
+
+/*
+ * winSetCursor
+ *  Set the cursor sprite and position.
+ */
+static void
+winSetCursor (ScreenPtr pScreen, CursorPtr pCursor, int x, int y)
+{
+  POINT ptCurPos, ptTemp;
+  HWND  hwnd;
+  RECT  rcClient;
+  BOOL  bInhibit;
+  winScreenPriv(pScreen);
+  WIN_DEBUG_MSG("winSetCursor: cursor=%p\n", pCursor); 
+  
+  /* Inhibit changing the cursor if the mouse is not in a client area */
+  bInhibit = FALSE;
+  if (GetCursorPos (&ptCurPos))
+    {
+      hwnd = WindowFromPoint (ptCurPos);
+      if (hwnd)
+	{
+	  if (GetClientRect (hwnd, &rcClient))
+	    {
+	      ptTemp.x = rcClient.left;
+	      ptTemp.y = rcClient.top;
+	      if (ClientToScreen (hwnd, &ptTemp))
+		{
+		  rcClient.left = ptTemp.x;
+		  rcClient.top = ptTemp.y;
+		  ptTemp.x = rcClient.right;
+		  ptTemp.y = rcClient.bottom;
+		  if (ClientToScreen (hwnd, &ptTemp))
+		    {
+		      rcClient.right = ptTemp.x;
+		      rcClient.bottom = ptTemp.y;
+		      if (!PtInRect (&rcClient, ptCurPos))
+			bInhibit = TRUE;
+		    }
+		}
+	    }
+	}
+    }
+
+  if (pCursor == NULL)
+    {
+      if (pScreenPriv->cursor.visible)
+	{
+	  if (!bInhibit && g_fSoftwareCursor)
+	    ShowCursor (FALSE);
+	  pScreenPriv->cursor.visible = FALSE;
+	}
+    }
+  else
+    {
+      if (pScreenPriv->cursor.handle)
+	{
+	  if (!bInhibit)
+	    SetCursor (NULL);
+	  DestroyCursor (pScreenPriv->cursor.handle);
+	  pScreenPriv->cursor.handle = NULL;
+	}
+      pScreenPriv->cursor.handle =
+	winLoadCursor (pScreen, pCursor, pScreen->myNum);
+      WIN_DEBUG_MSG("winSetCursor: handle=%p\n", pScreenPriv->cursor.handle); 
+
+      if (!bInhibit)
+	SetCursor (pScreenPriv->cursor.handle);
+
+      if (!pScreenPriv->cursor.visible)
+	{
+	  if (!bInhibit && g_fSoftwareCursor)
+	    ShowCursor (TRUE);
+	  pScreenPriv->cursor.visible = TRUE;
+	}
+    }
+}
+
+
+/*
+ * QuartzMoveCursor
+ *  Move the cursor. This is a noop for us.
+ */
+static void
+winMoveCursor (ScreenPtr pScreen, int x, int y)
+{
+}
+
+
+static miPointerSpriteFuncRec winSpriteFuncsRec = {
+  winRealizeCursor,
+  winUnrealizeCursor,
+  winSetCursor,
+  winMoveCursor
+};
+
+
+/*
+===========================================================================
+
+ Other screen functions
+
+===========================================================================
+*/
+
+/*
+ * winCursorQueryBestSize
+ *  Handle queries for best cursor size
+ */
+static void
+winCursorQueryBestSize (int class, unsigned short *width,
+				     unsigned short *height, ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  
+  if (class == CursorShape)
+    {
+      *width = pScreenPriv->cursor.sm_cx;
+      *height = pScreenPriv->cursor.sm_cy;
+    }
+  else
+    {
+      if (pScreenPriv->cursor.QueryBestSize)
+        (*pScreenPriv->cursor.QueryBestSize)(class, width, height, pScreen);
+    }
+}
+
+/*
+ * winInitCursor
+ *  Initialize cursor support
+ */
+Bool
+winInitCursor (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  miPointerScreenPtr pPointPriv;
+  /* override some screen procedures */
+  pScreenPriv->cursor.QueryBestSize = pScreen->QueryBestSize;
+  pScreen->QueryBestSize = winCursorQueryBestSize;
+  
+  pPointPriv = (miPointerScreenPtr)
+      dixLookupPrivate(&pScreen->devPrivates, miPointerScreenKey);
+  
+  pScreenPriv->cursor.spriteFuncs = pPointPriv->spriteFuncs;
+  pPointPriv->spriteFuncs = &winSpriteFuncsRec;
+
+  pScreenPriv->cursor.handle = NULL;
+  pScreenPriv->cursor.visible = FALSE;
+  
+  pScreenPriv->cursor.sm_cx = GetSystemMetrics (SM_CXCURSOR);
+  pScreenPriv->cursor.sm_cy = GetSystemMetrics (SM_CYCURSOR);
+
+  return TRUE;
+}
diff --git a/hw/xwin/windialogs.c b/hw/xwin/windialogs.c
new file mode 100755
index 0000000..ab06b0d
--- /dev/null
+++ b/hw/xwin/windialogs.c
@@ -0,0 +1,788 @@
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ *              Earle F. Philhower III
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#ifdef __CYGWIN__
+#include <sys/cygwin.h>
+#endif
+#include <shellapi.h>
+#include "winprefs.h"
+
+
+/*
+ * References to external globals
+ */
+
+extern Bool			g_fCursor;
+extern HWND			g_hDlgDepthChange;
+extern HWND			g_hDlgExit;
+extern HWND			g_hDlgAbout;
+extern WINPREFS			pref;
+#ifdef XWIN_CLIPBOARD
+extern Bool			g_fClipboardStarted;
+#endif
+extern Bool			g_fSoftwareCursor;
+
+
+/*
+ * Local function prototypes
+ */
+
+static wBOOL CALLBACK
+winExitDlgProc (HWND hDialog, UINT message,
+		WPARAM wParam, LPARAM lParam);
+
+static wBOOL CALLBACK
+winChangeDepthDlgProc (HWND hDialog, UINT message,
+		       WPARAM wParam, LPARAM lParam);
+
+static wBOOL CALLBACK
+winAboutDlgProc (HWND hDialog, UINT message,
+		 WPARAM wParam, LPARAM lParam);
+
+
+static void
+winDrawURLWindow (LPARAM lParam);
+
+static LRESULT CALLBACK
+winURLWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
+
+static void
+winOverrideURLButton (HWND hdlg, int id);
+
+static void
+winUnoverrideURLButton (HWND hdlg, int id);
+
+
+/*
+ * Owner-draw a button as a URL
+ */
+
+static void
+winDrawURLWindow (LPARAM lParam)
+{
+  DRAWITEMSTRUCT *draw;
+  char str[256];
+  RECT rect;
+  HFONT font;
+  COLORREF crText;
+  
+  draw = (DRAWITEMSTRUCT *) lParam;
+  GetWindowText (draw->hwndItem, str, sizeof(str));
+  str[255] = 0;
+  GetClientRect (draw->hwndItem, &rect);
+  
+  /* Color the button depending upon its state */
+  if (draw->itemState & ODS_SELECTED)
+    crText = RGB(128+64,0,0);
+  else if (draw->itemState & ODS_FOCUS)
+    crText = RGB(0,128+64,0);
+  else
+    crText = RGB(0,0,128+64);
+  SetTextColor (draw->hDC, crText);
+  
+  /* Create underlined font 14 high, standard dialog font */
+  font = CreateFont (-14, 0, 0, 0, FW_NORMAL, FALSE, TRUE, FALSE,
+		     0, 0, 0, 0, 0, "MS Sans Serif");
+  if (!font)
+    {
+      ErrorF ("winDrawURLWindow: Unable to create URL font, bailing.\n");
+      return;
+    }
+  /* Draw it */
+  SetBkMode (draw->hDC, OPAQUE);
+  SelectObject (draw->hDC, font);
+  DrawText (draw->hDC, str, strlen (str),&rect,DT_CENTER | DT_VCENTER);
+  /* Delete the created font, replace it with stock font */
+  DeleteObject (SelectObject (draw->hDC, GetStockObject (ANSI_VAR_FONT)));
+}
+
+
+/*
+ * WndProc for overridden buttons
+ */
+
+static LRESULT CALLBACK
+winURLWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+  WNDPROC origCB = NULL;
+  HCURSOR cursor;
+  
+  /* If it's a SetCursor message, tell it to the hand */
+  if (msg==WM_SETCURSOR) {
+    cursor = LoadCursor (NULL, IDC_HAND);
+    if (cursor)
+      SetCursor (cursor);
+    return TRUE;
+  }
+  origCB = (WNDPROC)GetWindowLong (hwnd, GWL_USERDATA);
+  /* Otherwise fall through to original WndProc */
+  if (origCB)
+    return CallWindowProc (origCB, hwnd, msg, wParam, lParam);
+  else
+    return FALSE;
+}
+
+
+/*
+ * Register and unregister the custom WndProc
+ */
+
+static void
+winOverrideURLButton (HWND hwnd, int id)
+{
+  WNDPROC origCB;
+  origCB = (WNDPROC)SetWindowLong (GetDlgItem (hwnd, id),
+				   GWL_WNDPROC, (LONG)winURLWndProc);
+  SetWindowLong (GetDlgItem (hwnd, id), GWL_USERDATA, (LONG)origCB);
+}
+
+static void
+winUnoverrideURLButton (HWND hwnd, int id)
+{
+  WNDPROC origCB;
+  origCB = (WNDPROC)SetWindowLong (GetDlgItem (hwnd, id),
+				   GWL_USERDATA, 0);
+  if (origCB)
+    SetWindowLong (GetDlgItem (hwnd, id), GWL_WNDPROC, (LONG)origCB);
+}
+
+
+/*
+ * Center a dialog window in the desktop window
+ */
+
+static void
+winCenterDialog (HWND hwndDlg)
+{
+  HWND hwndDesk; 
+  RECT rc, rcDlg, rcDesk; 
+ 
+  hwndDesk = GetParent (hwndDlg);
+  if (!hwndDesk || IsIconic (hwndDesk))
+    hwndDesk = GetDesktopWindow (); 
+  
+  GetWindowRect (hwndDesk, &rcDesk); 
+  GetWindowRect (hwndDlg, &rcDlg); 
+  CopyRect (&rc, &rcDesk); 
+  
+  OffsetRect (&rcDlg, -rcDlg.left, -rcDlg.top); 
+  OffsetRect (&rc, -rc.left, -rc.top); 
+  OffsetRect (&rc, -rcDlg.right, -rcDlg.bottom); 
+  
+  SetWindowPos (hwndDlg, 
+		HWND_TOP, 
+		rcDesk.left + (rc.right / 2), 
+		rcDesk.top + (rc.bottom / 2), 
+		0, 0,
+		SWP_NOSIZE | SWP_NOZORDER); 
+}
+
+
+/*
+ * Display the Exit dialog box
+ */
+
+void
+winDisplayExitDialog (winPrivScreenPtr pScreenPriv)
+{
+  int i;
+  int liveClients = 0;
+
+  /* Count up running clinets (clients[0] is serverClient) */
+  for (i = 1; i < currentMaxClients; i++)
+    if (clients[i] != NullClient)	
+      liveClients++;
+#if defined(XWIN_MULTIWINDOW)
+  /* Count down server internal clients */
+  if (pScreenPriv->pScreenInfo->fMultiWindow)
+    liveClients -= 2; /* multiwindow window manager & XMsgProc  */
+#endif
+#if defined(XWIN_CLIPBOARD)
+  if (g_fClipboardStarted)
+    liveClients--; /* clipboard manager */
+#endif
+
+  /* A user reported that this sometimes drops below zero. just eye-candy. */ 
+  if (liveClients < 0)
+    liveClients = 0;      
+
+  /* Don't show the exit confirmation dialog if SilentExit is enabled */
+  if (pref.fSilentExit && liveClients <= 0)
+    {
+      if (g_hDlgExit != NULL)
+	{
+	  DestroyWindow (g_hDlgExit);
+	  g_hDlgExit = NULL;
+	}
+      PostMessage (pScreenPriv->hwndScreen, WM_GIVEUP, 0, 0);
+      return;
+    }
+
+  pScreenPriv->iConnectedClients = liveClients;
+  
+  /* Check if dialog already exists */
+  if (g_hDlgExit != NULL)
+    {
+      /* Dialog box already exists, display it */
+      ShowWindow (g_hDlgExit, SW_SHOWDEFAULT);
+
+      /* User has lost the dialog.  Show them where it is. */
+      SetForegroundWindow (g_hDlgExit);
+
+      return;
+    }
+
+  /* Create dialog box */
+  g_hDlgExit = CreateDialogParam (g_hInstance,
+				  "EXIT_DIALOG",
+				  pScreenPriv->hwndScreen,
+				  winExitDlgProc,
+				  (int) pScreenPriv);
+
+  /* Drop minimize and maximize buttons */
+  SetWindowLong (g_hDlgExit, GWL_STYLE,
+		 GetWindowLong (g_hDlgExit, GWL_STYLE)
+		 & ~(WS_MAXIMIZEBOX | WS_MINIMIZEBOX));
+  SetWindowLong (g_hDlgExit, GWL_EXSTYLE,
+		 GetWindowLong (g_hDlgExit, GWL_EXSTYLE) & ~WS_EX_APPWINDOW );
+  SetWindowPos (g_hDlgExit, HWND_TOPMOST, 0, 0, 0, 0,
+		SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE); 
+ 
+  /* Show the dialog box */
+  ShowWindow (g_hDlgExit, SW_SHOW);
+  
+  /* Needed to get keyboard controls (tab, arrows, enter, esc) to work */
+  SetForegroundWindow (g_hDlgExit);
+  
+  /* Set focus to the Cancel button */
+  PostMessage (g_hDlgExit, WM_NEXTDLGCTL,
+	       (int) GetDlgItem (g_hDlgExit, IDCANCEL), TRUE);
+}
+
+#define CONNECTED_CLIENTS_FORMAT	"There are currently %d clients connected."
+
+
+/*
+ * Exit dialog window procedure
+ */
+
+static wBOOL CALLBACK
+winExitDlgProc (HWND hDialog, UINT message,
+		WPARAM wParam, LPARAM lParam)
+{
+  static winPrivScreenPtr	s_pScreenPriv = NULL;
+
+  /* Branch on message type */
+  switch (message)
+    {
+    case WM_INITDIALOG:
+      {
+	char			*pszConnectedClients;
+
+	/* Store pointers to private structures for future use */
+	s_pScreenPriv = (winPrivScreenPtr) lParam;
+	
+	winCenterDialog (hDialog);
+	
+	/* Set icon to standard app icon */
+	PostMessage (hDialog,
+		     WM_SETICON,
+		     ICON_SMALL,
+		     (LPARAM) LoadIcon (g_hInstance,
+					MAKEINTRESOURCE(IDI_XWIN)));
+
+	/* Format the connected clients string */
+	pszConnectedClients = Xprintf (CONNECTED_CLIENTS_FORMAT,
+            s_pScreenPriv->iConnectedClients);
+	if (!pszConnectedClients)
+	    return TRUE;
+     
+        
+	
+	/* Set the number of connected clients */
+	SetWindowText (GetDlgItem (hDialog, IDC_CLIENTS_CONNECTED),
+		       pszConnectedClients);
+	xfree (pszConnectedClients);
+      }
+      return TRUE;
+
+    case WM_COMMAND:
+      switch (LOWORD (wParam))
+	{
+	case IDOK:
+	  /* Send message to call the GiveUp function */
+	  PostMessage (s_pScreenPriv->hwndScreen, WM_GIVEUP, 0, 0);
+	  DestroyWindow (g_hDlgExit);
+	  g_hDlgExit = NULL;
+
+	  /* Fix to make sure keyboard focus isn't trapped */
+	  PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
+	  return TRUE;
+
+	case IDCANCEL:
+	  DestroyWindow (g_hDlgExit);
+	  g_hDlgExit = NULL;
+
+	  /* Fix to make sure keyboard focus isn't trapped */
+	  PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
+	  return TRUE;
+	}
+      break;
+
+    case WM_MOUSEMOVE:
+    case WM_NCMOUSEMOVE:
+      /* Show the cursor if it is hidden */
+      if (g_fSoftwareCursor && !g_fCursor)
+	{
+	  g_fCursor = TRUE;
+	  ShowCursor (TRUE);
+	}
+      return TRUE;
+
+    case WM_CLOSE:
+      DestroyWindow (g_hDlgExit);
+      g_hDlgExit = NULL;
+
+      /* Fix to make sure keyboard focus isn't trapped */
+      PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
+      return TRUE;
+    }
+
+  return FALSE;
+}
+
+
+/*
+ * Display the Depth Change dialog box
+ */
+
+void
+winDisplayDepthChangeDialog (winPrivScreenPtr pScreenPriv)
+{
+  /* Check if dialog already exists */
+  if (g_hDlgDepthChange != NULL)
+    {
+      /* Dialog box already exists, display it */
+      ShowWindow (g_hDlgDepthChange, SW_SHOWDEFAULT);
+
+      /* User has lost the dialog.  Show them where it is. */
+      SetForegroundWindow (g_hDlgDepthChange);
+
+      return;
+    }
+
+  /*
+   * Display a notification to the user that the visual 
+   * will not be displayed until the Windows display depth 
+   * is restored to the original value.
+   */
+  g_hDlgDepthChange = CreateDialogParam (g_hInstance,
+					 "DEPTH_CHANGE_BOX",
+					 pScreenPriv->hwndScreen,
+					 winChangeDepthDlgProc,
+					 (int) pScreenPriv);
+ 
+  /* Drop minimize and maximize buttons */
+  SetWindowLong (g_hDlgDepthChange, GWL_STYLE,
+		 GetWindowLong (g_hDlgDepthChange, GWL_STYLE)
+		 & ~(WS_MAXIMIZEBOX | WS_MINIMIZEBOX));
+  SetWindowLong (g_hDlgDepthChange, GWL_EXSTYLE,
+		 GetWindowLong (g_hDlgDepthChange, GWL_EXSTYLE)
+		 & ~WS_EX_APPWINDOW );
+  SetWindowPos (g_hDlgDepthChange, 0, 0, 0, 0, 0,
+		SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOZORDER | SWP_NOSIZE); 
+
+  /* Show the dialog box */
+  ShowWindow (g_hDlgDepthChange, SW_SHOW);
+  
+  ErrorF ("winDisplayDepthChangeDialog - DialogBox returned: %d\n",
+	  (int) g_hDlgDepthChange);
+  ErrorF ("winDisplayDepthChangeDialog - GetLastError: %d\n",
+	  (int) GetLastError ());
+	      
+  /* Minimize the display window */
+  ShowWindow (pScreenPriv->hwndScreen, SW_MINIMIZE);
+}
+
+
+/*
+ * Process messages for the dialog that is displayed for
+ * disruptive screen depth changes. 
+ */
+
+static wBOOL CALLBACK
+winChangeDepthDlgProc (HWND hwndDialog, UINT message,
+		       WPARAM wParam, LPARAM lParam)
+{
+  static winPrivScreenPtr	s_pScreenPriv = NULL;
+  static winScreenInfo		*s_pScreenInfo = NULL;
+  static ScreenPtr		s_pScreen = NULL;
+
+#if CYGDEBUG
+  winDebug ("winChangeDepthDlgProc\n");
+#endif
+
+  /* Branch on message type */
+  switch (message)
+    {
+    case WM_INITDIALOG:
+#if CYGDEBUG
+      winDebug ("winChangeDepthDlgProc - WM_INITDIALOG\n");
+#endif
+
+      /* Store pointers to private structures for future use */
+      s_pScreenPriv = (winPrivScreenPtr) lParam;
+      s_pScreenInfo = s_pScreenPriv->pScreenInfo;
+      s_pScreen = s_pScreenInfo->pScreen;
+
+#if CYGDEBUG
+      winDebug ("winChangeDepthDlgProc - WM_INITDIALOG - s_pScreenPriv: %08x, "
+	      "s_pScreenInfo: %08x, s_pScreen: %08x\n",
+	      s_pScreenPriv, s_pScreenInfo, s_pScreen);
+#endif
+
+#if CYGDEBUG
+      winDebug ("winChangeDepthDlgProc - WM_INITDIALOG - orig bpp: %d, "
+	      "last bpp: %d\n",
+	      s_pScreenInfo->dwBPP,
+	      s_pScreenPriv->dwLastWindowsBitsPixel);
+#endif
+      
+      winCenterDialog( hwndDialog );
+
+      /* Set icon to standard app icon */
+      PostMessage (hwndDialog,
+		   WM_SETICON,
+		   ICON_SMALL,
+		   (LPARAM) LoadIcon (g_hInstance, MAKEINTRESOURCE(IDI_XWIN)));
+
+      return TRUE;
+
+    case WM_DISPLAYCHANGE:
+#if CYGDEBUG
+      winDebug ("winChangeDepthDlgProc - WM_DISPLAYCHANGE - orig bpp: %d, "
+	      "last bpp: %d, new bpp: %d\n",
+	      s_pScreenInfo->dwBPP,
+	      s_pScreenPriv->dwLastWindowsBitsPixel,
+	      wParam);
+#endif
+
+      /* Dismiss the dialog if the display returns to the original depth */
+      if (wParam == s_pScreenInfo->dwBPP)
+	{
+	  ErrorF ("winChangeDelthDlgProc - wParam == s_pScreenInfo->dwBPP\n");
+
+	  /* Depth has been restored, dismiss dialog */
+	  DestroyWindow (g_hDlgDepthChange);
+	  g_hDlgDepthChange = NULL;
+
+	  /* Flag that we have a valid screen depth */
+	  s_pScreenPriv->fBadDepth = FALSE;
+	}
+      return TRUE;
+
+    case WM_COMMAND:
+      switch (LOWORD (wParam))
+	{
+	case IDOK:
+	case IDCANCEL:
+	  ErrorF ("winChangeDepthDlgProc - WM_COMMAND - IDOK or IDCANCEL\n");
+
+	  /* 
+	   * User dismissed the dialog, hide it until the
+	   * display mode is restored.
+	   */
+	  ShowWindow (g_hDlgDepthChange, SW_HIDE);
+	  return TRUE;
+	}
+      break;
+
+    case WM_CLOSE:
+      ErrorF ("winChangeDepthDlgProc - WM_CLOSE\n");
+
+      DestroyWindow (g_hDlgAbout);
+      g_hDlgAbout = NULL;
+
+      /* Fix to make sure keyboard focus isn't trapped */
+      PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
+      return TRUE;
+    }
+
+  return FALSE;
+}
+
+
+/*
+ * Display the About dialog box
+ */
+
+void
+winDisplayAboutDialog (winPrivScreenPtr pScreenPriv)
+{
+  /* Check if dialog already exists */
+  if (g_hDlgAbout != NULL)
+    {
+      /* Dialog box already exists, display it */
+      ShowWindow (g_hDlgAbout, SW_SHOWDEFAULT);
+
+      /* User has lost the dialog.  Show them where it is. */
+      SetForegroundWindow (g_hDlgAbout);
+
+      return;
+    }
+
+  /*
+   * Display the about box
+   */
+  g_hDlgAbout = CreateDialogParam (g_hInstance,
+				   "ABOUT_BOX",
+				   pScreenPriv->hwndScreen,
+				   winAboutDlgProc,
+				   (int) pScreenPriv);
+ 
+  /* Drop minimize and maximize buttons */
+  SetWindowLong (g_hDlgAbout, GWL_STYLE,
+		 GetWindowLong (g_hDlgAbout, GWL_STYLE)
+		 & ~(WS_MAXIMIZEBOX | WS_MINIMIZEBOX));
+  SetWindowLong (g_hDlgAbout, GWL_EXSTYLE,
+		 GetWindowLong (g_hDlgAbout, GWL_EXSTYLE) & ~WS_EX_APPWINDOW);
+  SetWindowPos (g_hDlgAbout, 0, 0, 0, 0, 0,
+		SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE); 
+
+  /* Show the dialog box */
+  ShowWindow (g_hDlgAbout, SW_SHOW);
+
+  /* Needed to get keyboard controls (tab, arrows, enter, esc) to work */
+  SetForegroundWindow (g_hDlgAbout);
+  
+  /* Set focus to the OK button */
+  PostMessage (g_hDlgAbout, WM_NEXTDLGCTL,
+	       (int) GetDlgItem (g_hDlgAbout, IDOK), TRUE);
+}
+
+
+/*
+ * Process messages for the about dialog.
+ */
+
+static wBOOL CALLBACK
+winAboutDlgProc (HWND hwndDialog, UINT message,
+		 WPARAM wParam, LPARAM lParam)
+{
+  static winPrivScreenPtr	s_pScreenPriv = NULL;
+  static winScreenInfo		*s_pScreenInfo = NULL;
+  static ScreenPtr		s_pScreen = NULL;
+
+#if CYGDEBUG
+  winDebug ("winAboutDlgProc\n");
+#endif
+
+  /* Branch on message type */
+  switch (message)
+    {
+    case WM_INITDIALOG:
+#if CYGDEBUG
+      winDebug ("winAboutDlgProc - WM_INITDIALOG\n");
+#endif
+
+      /* Store pointers to private structures for future use */
+      s_pScreenPriv = (winPrivScreenPtr) lParam;
+      s_pScreenInfo = s_pScreenPriv->pScreenInfo;
+      s_pScreen = s_pScreenInfo->pScreen;
+
+      winCenterDialog (hwndDialog);
+
+      /* Set icon to standard app icon */
+      PostMessage (hwndDialog,
+		   WM_SETICON,
+		   ICON_SMALL,
+		   (LPARAM) LoadIcon (g_hInstance, MAKEINTRESOURCE(IDI_XWIN)));
+
+      /* Override the URL buttons */
+      winOverrideURLButton (hwndDialog, ID_ABOUT_CHANGELOG);
+      winOverrideURLButton (hwndDialog, ID_ABOUT_WEBSITE);
+      winOverrideURLButton (hwndDialog, ID_ABOUT_UG);
+      winOverrideURLButton (hwndDialog, ID_ABOUT_FAQ);
+
+      return TRUE;
+
+    case WM_DRAWITEM:
+      /* Draw the URL buttons as needed */
+      winDrawURLWindow (lParam);
+      return TRUE;
+
+    case WM_MOUSEMOVE:
+    case WM_NCMOUSEMOVE:
+      /* Show the cursor if it is hidden */
+      if (g_fSoftwareCursor && !g_fCursor)
+	{
+	  g_fCursor = TRUE;
+	  ShowCursor (TRUE);
+	}
+      return TRUE;
+
+    case WM_COMMAND:
+      switch (LOWORD (wParam))
+	{
+	case IDOK:
+	case IDCANCEL:
+	  ErrorF ("winAboutDlgProc - WM_COMMAND - IDOK or IDCANCEL\n");
+
+	  DestroyWindow (g_hDlgAbout);
+	  g_hDlgAbout = NULL;
+
+	  /* Fix to make sure keyboard focus isn't trapped */
+	  PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
+
+	  /* Restore window procedures for URL buttons */
+	  winUnoverrideURLButton (hwndDialog, ID_ABOUT_CHANGELOG);
+	  winUnoverrideURLButton (hwndDialog, ID_ABOUT_WEBSITE);
+	  winUnoverrideURLButton (hwndDialog, ID_ABOUT_UG);
+	  winUnoverrideURLButton (hwndDialog, ID_ABOUT_FAQ);
+
+	  return TRUE;
+
+	case ID_ABOUT_CHANGELOG:
+	  {
+	    int			iReturn;
+#ifdef __CYGWIN__
+	    const char *	pszCygPath = "/usr/X11R6/share/doc/"
+	      "xorg-x11-xwin/changelog.html";
+	    char		pszWinPath[MAX_PATH + 1];
+
+	    /* Convert the POSIX path to a Win32 path */
+	    cygwin_conv_to_win32_path (pszCygPath, pszWinPath);
+#else
+	    const char *	pszWinPath = "http://x.cygwin.com/"
+		    "devel/server/changelog.html";
+#endif
+	    
+	    iReturn = (int) ShellExecute (NULL,
+					  "open",
+					  pszWinPath,
+					  NULL,
+					  NULL,
+					  SW_MAXIMIZE);
+	    if (iReturn < 32)
+	      {
+		ErrorF ("winAboutDlgProc - WM_COMMAND - ID_ABOUT_CHANGELOG - "
+			"ShellExecute failed: %d\n",
+			iReturn);
+	      }	    
+	  }
+	  return TRUE;
+
+	case ID_ABOUT_WEBSITE:
+	  {
+	    const char *	pszPath = "http://x.cygwin.com/";
+	    int			iReturn;
+	    
+	    iReturn = (int) ShellExecute (NULL,
+					  "open",
+					  pszPath,
+					  NULL,
+					  NULL,
+					  SW_MAXIMIZE);
+	    if (iReturn < 32)
+	      {
+		ErrorF ("winAboutDlgProc - WM_COMMAND - ID_ABOUT_WEBSITE - "
+			"ShellExecute failed: %d\n",
+			iReturn);
+	      }	    
+	  }
+	  return TRUE;
+
+	case ID_ABOUT_UG:
+	  {
+	    const char *	pszPath = "http://x.cygwin.com/docs/ug/";
+	    int			iReturn;
+	    
+	    iReturn = (int) ShellExecute (NULL,
+					  "open",
+					  pszPath,
+					  NULL,
+					  NULL,
+					  SW_MAXIMIZE);
+	    if (iReturn < 32)
+	      {
+		ErrorF ("winAboutDlgProc - WM_COMMAND - ID_ABOUT_UG - "
+			"ShellExecute failed: %d\n",
+			iReturn);
+	      }	    
+	  }
+	  return TRUE;
+
+	case ID_ABOUT_FAQ:
+	  {
+	    const char *	pszPath = "http://x.cygwin.com/docs/faq/";
+	    int			iReturn;
+	    
+	    iReturn = (int) ShellExecute (NULL,
+					  "open",
+					  pszPath,
+					  NULL,
+					  NULL,
+					  SW_MAXIMIZE);
+	    if (iReturn < 32)
+	      {
+		ErrorF ("winAboutDlgProc - WM_COMMAND - ID_ABOUT_FAQ - "
+			"ShellExecute failed: %d\n",
+			iReturn);
+	      }	    
+	  }
+	  return TRUE;
+	}
+      break;
+
+    case WM_CLOSE:
+      ErrorF ("winAboutDlgProc - WM_CLOSE\n");
+
+      DestroyWindow (g_hDlgAbout);
+      g_hDlgAbout = NULL;
+
+      /* Fix to make sure keyboard focus isn't trapped */
+      PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
+
+      /* Restore window procedures for URL buttons */
+      winUnoverrideURLButton (hwndDialog, ID_ABOUT_CHANGELOG);
+      winUnoverrideURLButton (hwndDialog, ID_ABOUT_WEBSITE);
+      winUnoverrideURLButton (hwndDialog, ID_ABOUT_UG);
+      winUnoverrideURLButton (hwndDialog, ID_ABOUT_FAQ);
+
+      return TRUE;
+    }
+
+  return FALSE;
+}
diff --git a/hw/xwin/winengine.c b/hw/xwin/winengine.c
new file mode 100644
index 0000000..f0bc671
--- /dev/null
+++ b/hw/xwin/winengine.c
@@ -0,0 +1,336 @@
+/*
+ *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winmsg.h"
+
+
+/*
+ * External global variables
+ */
+
+extern const GUID _IID_IDirectDraw4;
+
+
+/*
+ * Detect engines supported by current Windows version
+ * DirectDraw version and hardware
+ */
+
+void
+winDetectSupportedEngines ()
+{
+  OSVERSIONINFO		osvi;
+
+  /* Initialize the engine support flags */
+  g_dwEnginesSupported = WIN_SERVER_SHADOW_GDI;
+
+#ifdef XWIN_NATIVEGDI
+  g_dwEnginesSupported |= WIN_SERVER_NATIVE_GDI;
+#endif
+
+  /* Get operating system version information */
+  ZeroMemory (&osvi, sizeof (osvi));
+  osvi.dwOSVersionInfoSize = sizeof (osvi);
+  GetVersionEx (&osvi);
+
+  /* Branch on platform ID */
+  switch (osvi.dwPlatformId)
+    {
+    case VER_PLATFORM_WIN32_NT:
+      /* Engine 4 is supported on NT only */
+      winErrorFVerb (2, "winDetectSupportedEngines - Windows NT/2000/XP\n");
+      break;
+
+    case VER_PLATFORM_WIN32_WINDOWS:
+      /* Engine 4 is supported on NT only */
+      winErrorFVerb (2, "winDetectSupportedEngines - Windows 95/98/Me\n");
+      break;
+    }
+
+  /* Do we have DirectDraw? */
+  if (g_hmodDirectDraw != NULL)
+    {
+      LPDIRECTDRAW	lpdd = NULL;
+      LPDIRECTDRAW4	lpdd4 = NULL;
+      HRESULT		ddrval;
+
+      /* Was the DirectDrawCreate function found? */
+      if (g_fpDirectDrawCreate == NULL)
+	{
+	  /* No DirectDraw support */
+	  return;
+	}
+
+      /* DirectDrawCreate exists, try to call it */
+      /* Create a DirectDraw object, store the address at lpdd */
+      ddrval = (*g_fpDirectDrawCreate) (NULL,
+					(void**) &lpdd,
+					NULL);
+      if (FAILED (ddrval))
+	{
+	  /* No DirectDraw support */
+	  winErrorFVerb (2, "winDetectSupportedEngines - DirectDraw not installed\n");
+	  return;
+	}
+      else
+	{
+	  /* We have DirectDraw */
+	  winErrorFVerb (2, "winDetectSupportedEngines - DirectDraw installed\n");
+	  g_dwEnginesSupported |= WIN_SERVER_SHADOW_DD;
+
+#ifdef XWIN_PRIMARYFB
+	  /* Allow PrimaryDD engine if NT */
+	  if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
+	    {
+	      g_dwEnginesSupported |= WIN_SERVER_PRIMARY_DD;
+	      winErrorFVerb (2, "winDetectSupportedEngines - Allowing PrimaryDD\n");
+	    }
+#endif
+	}
+      
+      /* Try to query for DirectDraw4 interface */
+      ddrval = IDirectDraw_QueryInterface (lpdd,
+					   &IID_IDirectDraw4,
+					   (LPVOID*) &lpdd4);
+      if (SUCCEEDED (ddrval))
+	{
+	  /* We have DirectDraw4 */
+	  winErrorFVerb (2, "winDetectSupportedEngines - DirectDraw4 installed\n");
+	  g_dwEnginesSupported |= WIN_SERVER_SHADOW_DDNL;
+	}
+
+      /* Cleanup DirectDraw interfaces */
+      if (lpdd4 != NULL)
+	IDirectDraw_Release (lpdd4);
+      if (lpdd != NULL)
+	IDirectDraw_Release (lpdd);
+    }
+
+  winErrorFVerb (2, "winDetectSupportedEngines - Returning, supported engines %08x\n",
+	  (unsigned int) g_dwEnginesSupported);
+}
+
+
+/*
+ * Set the engine type, depending on the engines
+ * supported for this screen, and whether the user
+ * suggested an engine type
+ */
+
+Bool
+winSetEngine (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  HDC			hdc;
+  DWORD			dwBPP;
+
+  /* Get a DC */
+  hdc = GetDC (NULL);
+  if (hdc == NULL)
+    {
+      ErrorF ("winSetEngine - Couldn't get an HDC\n");
+      return FALSE;
+    }
+
+  /*
+   * pScreenInfo->dwBPP may be 0 to indicate that the current screen
+   * depth is to be used.  Thus, we must query for the current display
+   * depth here.
+   */
+  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
+
+  /* Release the DC */
+  ReleaseDC (NULL, hdc);
+  hdc = NULL;
+
+  /* ShadowGDI is the only engine that supports windowed PseudoColor */
+  if (dwBPP == 8 && !pScreenInfo->fFullScreen)
+    {
+      winErrorFVerb (2, "winSetEngine - Windowed && PseudoColor => ShadowGDI\n");
+      pScreenInfo->dwEngine = WIN_SERVER_SHADOW_GDI;
+
+      /* Set engine function pointers */
+      winSetEngineFunctionsShadowGDI (pScreen);
+      return TRUE;
+    }
+
+  /* ShadowGDI is the only engine that supports Multi Window Mode */
+  if (
+#ifdef XWIN_MULTIWINDOWEXTWM
+      pScreenInfo->fMWExtWM
+#else
+      FALSE
+#endif
+#ifdef XWIN_MULTIWINDOW
+      || pScreenInfo->fMultiWindow
+#else
+      || FALSE
+#endif
+      )
+    {
+      winErrorFVerb (2, "winSetEngine - Multi Window or Rootless => ShadowGDI\n");
+      pScreenInfo->dwEngine = WIN_SERVER_SHADOW_GDI;
+
+      /* Set engine function pointers */
+      winSetEngineFunctionsShadowGDI (pScreen);
+      return TRUE;
+    }
+
+  /* If the user's choice is supported, we'll use that */
+  if (g_dwEnginesSupported & pScreenInfo->dwEnginePreferred)
+    {
+      winErrorFVerb (2, "winSetEngine - Using user's preference: %d\n",
+	      (int) pScreenInfo->dwEnginePreferred);
+      pScreenInfo->dwEngine = pScreenInfo->dwEnginePreferred;
+
+      /* Setup engine function pointers */
+      switch (pScreenInfo->dwEngine)
+	{
+	case WIN_SERVER_SHADOW_GDI:
+	  winSetEngineFunctionsShadowGDI (pScreen);
+	  break;
+	case WIN_SERVER_SHADOW_DD:
+	  winSetEngineFunctionsShadowDD (pScreen);
+	  break;
+	case WIN_SERVER_SHADOW_DDNL:
+	  winSetEngineFunctionsShadowDDNL (pScreen);
+	  break;
+#ifdef XWIN_PRIMARYFB
+	case WIN_SERVER_PRIMARY_DD:
+	  winSetEngineFunctionsPrimaryDD (pScreen);
+	  break;
+#endif
+#ifdef XWIN_NATIVEGDI
+	case WIN_SERVER_NATIVE_GDI:
+	  winSetEngineFunctionsNativeGDI (pScreen);
+	  break;
+#endif
+	default:
+	  FatalError ("winSetEngine - Invalid engine type\n");
+	}
+      return TRUE;
+    }
+
+  /* ShadowDDNL has good performance, so why not */
+  if (g_dwEnginesSupported & WIN_SERVER_SHADOW_DDNL)
+    {
+      winErrorFVerb (2, "winSetEngine - Using Shadow DirectDraw NonLocking\n");
+      pScreenInfo->dwEngine = WIN_SERVER_SHADOW_DDNL;
+
+      /* Set engine function pointers */
+      winSetEngineFunctionsShadowDDNL (pScreen);
+      return TRUE;
+    }
+
+  /* ShadowDD is next in line */
+  if (g_dwEnginesSupported & WIN_SERVER_SHADOW_DD)
+    {
+      winErrorFVerb (2, "winSetEngine - Using Shadow DirectDraw\n");
+      pScreenInfo->dwEngine = WIN_SERVER_SHADOW_DD;
+
+      /* Set engine function pointers */
+      winSetEngineFunctionsShadowDD (pScreen);
+      return TRUE;
+    }
+
+  /* ShadowGDI is next in line */
+  if (g_dwEnginesSupported & WIN_SERVER_SHADOW_GDI)
+    {
+      winErrorFVerb (2, "winSetEngine - Using Shadow GDI DIB\n");
+      pScreenInfo->dwEngine = WIN_SERVER_SHADOW_GDI;
+
+      /* Set engine function pointers */
+      winSetEngineFunctionsShadowGDI (pScreen);
+      return TRUE;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Get procedure addresses for DirectDrawCreate and DirectDrawCreateClipper
+ */
+
+Bool
+winGetDDProcAddresses ()
+{
+  Bool			fReturn = TRUE;
+  
+  /* Load the DirectDraw library */
+  g_hmodDirectDraw = LoadLibraryEx ("ddraw.dll", NULL, 0);
+  if (g_hmodDirectDraw == NULL)
+    {
+      ErrorF ("winGetDDProcAddresses - Could not load ddraw.dll\n");
+      fReturn = TRUE;
+      goto winGetDDProcAddresses_Exit;
+    }
+
+  /* Try to get the DirectDrawCreate address */
+  g_fpDirectDrawCreate = GetProcAddress (g_hmodDirectDraw,
+					 "DirectDrawCreate");
+  if (g_fpDirectDrawCreate == NULL)
+    {
+      ErrorF ("winGetDDProcAddresses - Could not get DirectDrawCreate "
+	      "address\n");
+      fReturn = TRUE;
+      goto winGetDDProcAddresses_Exit;
+    }
+
+  /* Try to get the DirectDrawCreateClipper address */
+  g_fpDirectDrawCreateClipper = GetProcAddress (g_hmodDirectDraw,
+						"DirectDrawCreateClipper");
+  if (g_fpDirectDrawCreateClipper == NULL)
+    {
+      ErrorF ("winGetDDProcAddresses - Could not get "
+	      "DirectDrawCreateClipper address\n");
+      fReturn = FALSE;
+      goto winGetDDProcAddresses_Exit;
+    }
+
+  /*
+   * Note: Do not unload ddraw.dll here.  Do it in GiveUp
+   */
+
+ winGetDDProcAddresses_Exit:
+  /* Unload the DirectDraw library if we failed to initialize */
+  if (!fReturn && g_hmodDirectDraw != NULL)
+    {
+      FreeLibrary (g_hmodDirectDraw);
+      g_hmodDirectDraw = NULL;
+    }
+  
+  return fReturn;
+}
diff --git a/hw/xwin/winerror.c b/hw/xwin/winerror.c
new file mode 100644
index 0000000..7d29213
--- /dev/null
+++ b/hw/xwin/winerror.c
@@ -0,0 +1,143 @@
+/*
+ *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#ifdef XVENDORNAME
+#define VENDOR_STRING XVENDORNAME
+#define VERSION_STRING XORG_RELEASE
+#define VENDOR_CONTACT BUILDERADDR
+#endif
+
+#include "win.h"
+
+/* References to external symbols */
+extern char *		g_pszCommandLine;
+extern char *		g_pszLogFile;
+extern Bool		g_fSilentFatalError;
+
+
+#ifdef DDXOSVERRORF
+/* Prototype */
+void
+OsVendorVErrorF (const char *pszFormat, va_list va_args);
+
+void
+OsVendorVErrorF (const char *pszFormat, va_list va_args)
+{
+#if defined(XWIN_CLIPBOARD) || defined (XWIN_MULTIWINDOW)
+  /* make sure the clipboard and multiwindow threads do not interfere the
+   * main thread */
+  static pthread_mutex_t	s_pmPrinting = PTHREAD_MUTEX_INITIALIZER;
+
+  /* Lock the printing mutex */
+  pthread_mutex_lock (&s_pmPrinting);
+#endif
+
+  /* Print the error message to a log file, could be stderr */
+  LogVWrite (0, pszFormat, va_args);
+
+#if defined(XWIN_CLIPBOARD) || defined (XWIN_MULTIWINDOW)
+  /* Unlock the printing mutex */
+  pthread_mutex_unlock (&s_pmPrinting);
+#endif
+}
+#endif
+
+
+/*
+ * os/util.c/FatalError () calls our vendor ErrorF, so the message
+ * from a FatalError will be logged.  Thus, the message for the
+ * fatal error is not passed to this function.
+ *
+ * Attempt to do last-ditch, safe, important cleanup here.
+ */
+#ifdef DDXOSFATALERROR
+void
+OsVendorFatalError (void)
+{
+  /* Don't give duplicate warning if UseMsg was called */
+  if (g_fSilentFatalError)
+    return;
+
+  winMessageBoxF (
+          "A fatal error has occurred and " PROJECT_NAME " will now exit.\n" \
+		  "Please open %s for more information.\n",
+		  MB_ICONERROR, (g_pszLogFile?g_pszLogFile:"the logfile"));
+}
+#endif
+
+
+/*
+ * winMessageBoxF - Print a formatted error message in a useful
+ * message box.
+ */
+
+void
+winMessageBoxF (const char *pszError, UINT uType, ...)
+{
+  char *	pszErrorF = NULL;
+  char *	pszMsgBox = NULL;
+  va_list	args;
+
+  va_start(args, uType);
+  pszErrorF = Xvprintf(pszError, args);
+  va_end(args);
+  if (!pszErrorF)
+    goto winMessageBoxF_Cleanup;
+
+#define MESSAGEBOXF \
+	"%s\n" \
+	"Vendor: %s\n" \
+	"Release: %s\n" \
+	"Contact: %s\n" \
+	"XWin was started with the following command-line:\n\n" \
+	"%s\n"
+
+  pszMsgBox = Xprintf (MESSAGEBOXF,
+	   pszErrorF, VENDOR_STRING, VERSION_STRING, VENDOR_CONTACT,
+	   g_pszCommandLine);
+  if (!pszMsgBox)
+    goto winMessageBoxF_Cleanup;
+
+  /* Display the message box string */
+  MessageBox (NULL,
+	      pszMsgBox,
+	      PROJECT_NAME,
+	      MB_OK | uType);
+
+ winMessageBoxF_Cleanup:
+  if (pszErrorF)
+    xfree (pszErrorF);
+  if (pszMsgBox)
+    xfree (pszMsgBox);
+#undef MESSAGEBOXF
+}
diff --git a/hw/xwin/winfillsp.c b/hw/xwin/winfillsp.c
new file mode 100644
index 0000000..702f34f
--- /dev/null
+++ b/hw/xwin/winfillsp.c
@@ -0,0 +1,866 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Harold L Hunt II
+ * 		Alan Hourihane <alanh at fairlite.demon.co.uk>
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+extern void ROP16(HDC hdc, int rop);
+
+#define TRANSLATE_COLOR(color)						\
+{									\
+  if (pDrawable->depth == 15)						\
+    color = ((color & 0x1F) << 19) | ((color & 0x03E0) << 6) |		\
+      ((color & 0xF800) >> 8);						\
+  else if (pDrawable->depth == 16)					\
+    color = ((color & 0x1F) << 19) | ((color & 0x07E0) << 5) |		\
+      ((color & 0xF800) >> 8);						\
+  else if (pDrawable->depth == 24 || pDrawable->depth == 32)		\
+    color = ((color & 0xFF) << 16) | (color & 0xFF00) |			\
+      ((color & 0xFF0000) >> 16);					\
+}
+
+/* See Porting Layer Definition - p. 54 */
+void
+winFillSpansNativeGDI (DrawablePtr	pDrawable,
+		       GCPtr		pGC,
+		       int		iSpans,
+		       DDXPointPtr	pPoints,
+		       int		*piWidths,
+		       int		fSorted)
+{
+  winGCPriv(pGC);
+  HBITMAP		hbmpOrig = NULL, hbmpOrigStipple = NULL;
+  HBITMAP		hPenOrig = NULL;
+  HBITMAP		hBitmap = NULL;
+  PixmapPtr		pPixmap = NULL;
+  winPrivPixmapPtr	pPixmapPriv = NULL;
+  PixmapPtr		pStipple = NULL;
+  winPrivPixmapPtr	pStipplePriv = NULL;
+  PixmapPtr		pTile = NULL;
+  winPrivPixmapPtr	pTilePriv = NULL;
+  HDC			hdcStipple = NULL, hdcTile = NULL;
+  HPEN			hPen = NULL;
+  int			iX;
+  int			fg, bg;
+  RegionPtr	    	pClip = pGC->pCompositeClip;
+  BoxPtr	    	pextent, pbox;
+  int		    	nbox;
+  int		    	extentX1, extentX2, extentY1, extentY2;
+  int		    	fullX1, fullX2, fullY1;
+  HRGN			hrgn = NULL, combined = NULL;
+
+  nbox = REGION_NUM_RECTS (pClip);
+  pbox = REGION_RECTS (pClip);
+
+  if (!nbox) return;
+
+  combined = CreateRectRgn (pbox->x1, pbox->y1, pbox->x2, pbox->y2);
+  nbox--; pbox++;
+
+  while (nbox--)
+    {
+      hrgn = CreateRectRgn (pbox->x1, pbox->y1, pbox->x2, pbox->y2);
+      CombineRgn (combined, combined, hrgn, RGN_OR);
+      DeleteObject (hrgn);
+      hrgn = NULL;
+      pbox++;
+    }
+
+  pextent = REGION_EXTENTS (pGC->pScreen, pClip);
+  extentX1 = pextent->x1;
+  extentY1 = pextent->y1;
+  extentX2 = pextent->x2;
+  extentY2 = pextent->y2;
+
+  /* Branch on the type of drawable we have */
+  switch (pDrawable->type)
+    {
+    case DRAWABLE_PIXMAP:
+
+      SelectClipRgn (pGCPriv->hdcMem, combined);
+      DeleteObject (combined);
+      combined = NULL;
+
+      /* Get a pixmap pointer from the drawable pointer, and fetch privates  */
+      pPixmap = (PixmapPtr) pDrawable;
+      pPixmapPriv = winGetPixmapPriv (pPixmap);
+
+      /* Select the drawable pixmap into memory hdc */
+      hbmpOrig = SelectObject (pGCPriv->hdcMem, pPixmapPriv->hBitmap);
+      if (hbmpOrig == NULL)
+	FatalError ("winFillSpans - DRAWABLE_PIXMAP - "
+		    "SelectObject () failed on\n\tpPixmapPriv->hBitmap: "
+		    "%08x\n", (unsigned int) pPixmapPriv->hBitmap);
+      
+      /* Branch on the fill type */
+      switch (pGC->fillStyle)
+	{
+	case FillSolid:
+
+          ROP16 (pGCPriv->hdcMem, pGC->alu);
+
+	  if (pDrawable->depth == 1) 
+	    {
+	      if (pGC->fgPixel == 0)
+		hPenOrig = SelectObject (pGCPriv->hdcMem, 
+					 GetStockObject (BLACK_PEN));
+	      else
+		hPenOrig = SelectObject (pGCPriv->hdcMem,
+					 GetStockObject (WHITE_PEN));
+	    } 
+	  else 
+	    {
+	      fg = pGC->fgPixel;
+	      TRANSLATE_COLOR (fg);
+	      hPen = CreatePen (PS_SOLID, 0, fg);
+	      hPenOrig = SelectObject (pGCPriv->hdcMem, hPen);
+	    }
+    	
+	  while (iSpans--)
+	    {
+	      fullX1 = pPoints->x;
+	      fullY1 = pPoints->y;
+	      fullX2 = fullX1 + (int) *piWidths;
+	      pPoints++;
+	      piWidths++;
+	
+	      if (fullY1 < extentY1 || extentY2 <= fullY1)
+		continue;
+	
+	      if (fullX1 < extentX1)
+		fullX1 = extentX1;
+	      if (fullX2 > extentX2)
+		fullX2 = extentX2;
+	
+	      if (fullX1 >= fullX2)
+		continue;
+	
+	      MoveToEx (pGCPriv->hdcMem, fullX1, fullY1, NULL);
+	      LineTo (pGCPriv->hdcMem, fullX2, fullY1);
+	    }
+
+          SetROP2 (pGCPriv->hdcMem, R2_COPYPEN);
+
+	  /* Give back the Pen */
+	  SelectObject (pGCPriv->hdcMem, hPenOrig);
+
+	  if (pDrawable->depth != 1)
+	    DeleteObject (hPen);
+	  break;
+
+	case FillOpaqueStippled:
+
+	  pStipple = pGC->stipple;
+	  pStipplePriv = winGetPixmapPriv (pStipple);
+
+	  /* Create a device-dependent bitmap for the stipple */
+	  hBitmap = CreateDIBitmap (pGCPriv->hdcMem,
+				    (BITMAPINFOHEADER *)pStipplePriv->pbmih,
+				    CBM_INIT,
+				    pStipplePriv->pbBits,
+				    (BITMAPINFO *)pStipplePriv->pbmih,
+				    DIB_RGB_COLORS);
+
+	  /* Create a memory DC to hold the stipple */
+	  hdcStipple = CreateCompatibleDC (pGCPriv->hdcMem);
+
+	  /* Select the stipple bitmap into the stipple DC */
+	  hbmpOrigStipple = SelectObject (hdcStipple, hBitmap);
+	  if (hbmpOrigStipple == NULL)
+	    FatalError ("winFillSpans () - DRAWABLE_PIXMAP - FillStippled - "
+			"SelectObject () failed on hbmpOrigStipple\n");
+
+	  /* Make a temporary copy of the foreground and background colors */
+   	  bg = pGC->bgPixel;
+   	  fg = pGC->fgPixel;
+
+	  /* Translate the depth-dependent colors to Win32 COLORREFs */
+	  TRANSLATE_COLOR (fg);
+	  TRANSLATE_COLOR (bg);
+	  SetTextColor (pGCPriv->hdcMem, fg);
+	  SetBkColor (pGCPriv->hdcMem, bg);
+
+	  while (iSpans--)
+	    {
+	      int width = pStipple->drawable.width;
+	      fullX1 = pPoints->x;
+	      fullY1 = pPoints->y;
+	      fullX2 = fullX1 + (int) *piWidths;
+	      pPoints++;
+	      piWidths++;
+	
+	      if (fullY1 < extentY1 || extentY2 <= fullY1)
+		continue;
+	
+	      if (fullX1 < extentX1)
+		fullX1 = extentX1;
+	      if (fullX2 > extentX2)
+		fullX2 = extentX2;
+	
+	      if (fullX1 >= fullX2)
+		continue;
+	
+	      for (iX = fullX1; iX < fullX2; iX += width)
+		{
+		  int xoffset;
+
+		  if ((iX + pStipple->drawable.width) > fullX2)
+		    width = fullX2 - iX;
+		  else
+		    width = pStipple->drawable.width;
+
+		  if (iX == fullX1)
+		    xoffset = (fullX1 - (pDrawable->x + (pGC->patOrg.x % pStipple->drawable.width) - pStipple->drawable.width)) % pStipple->drawable.width;
+		  else
+		    xoffset = 0;
+
+		  if (xoffset + width > pStipple->drawable.width)
+		    width = pStipple->drawable.width - xoffset;
+
+		  BitBlt (pGCPriv->hdcMem,
+			  iX, fullY1,
+			  width, 1,
+			  hdcStipple,
+			  xoffset,
+			  (fullY1 - (pDrawable->y + (pGC->patOrg.y % pStipple->drawable.height) - pStipple->drawable.height)) % pStipple->drawable.height,
+			  g_copyROP[pGC->alu]);
+		}
+	    }
+
+	  /* Clear the stipple HDC */
+	  SelectObject (hdcStipple, hbmpOrigStipple);
+	  DeleteDC (hdcStipple);
+
+	  /* Delete the device dependent stipple bitmap */
+	  DeleteObject (hBitmap);
+
+	  break;
+	case FillStippled:
+
+	  pStipple = pGC->stipple;
+	  pStipplePriv = winGetPixmapPriv (pStipple);
+
+	  /* Create a device-dependent bitmap for the stipple */
+	  hBitmap = CreateDIBitmap (pGCPriv->hdcMem,
+				    (BITMAPINFOHEADER *)pStipplePriv->pbmih,
+				    CBM_INIT,
+				    pStipplePriv->pbBits,
+				    (BITMAPINFO *)pStipplePriv->pbmih,
+				    DIB_RGB_COLORS);
+
+	  /* Create a memory DC to hold the stipple */
+	  hdcStipple = CreateCompatibleDC (pGCPriv->hdcMem);
+
+	  /* Select the stipple bitmap into the stipple DC */
+	  hbmpOrigStipple = SelectObject (hdcStipple, hBitmap);
+	  if (hbmpOrigStipple == NULL)
+	    FatalError ("winFillSpans () - DRAWABLE_PIXMAP - FillStippled - "
+			"SelectObject () failed on hbmpOrigStipple\n");
+
+	  /* Make a temporary copy of the foreground and background colors */
+   	  bg = pGC->bgPixel;
+   	  fg = pGC->fgPixel;
+
+	  /* Translate the depth-dependent colors to Win32 COLORREFs */
+	  TRANSLATE_COLOR (fg);
+	  TRANSLATE_COLOR (bg);
+
+	  /* this is fudgy, we should only invert on the last one
+	   * We need to get the black/white pixels right in the
+	   * colormap. But yeah ! it's working.. 
+	   */
+	  if (pGC->bgPixel != -1 && pGC->fgPixel != -1) 
+	    {
+	      SetTextColor (pGCPriv->hdcMem, fg);
+	      SetBkColor (pGCPriv->hdcMem, bg);
+	      BitBlt (hdcStipple,
+		      0, 0,
+		      pStipple->drawable.width, pStipple->drawable.height,
+		      hdcStipple,
+		      0, 0,
+		      0x330008);
+	    } 
+	  else if (pGC->bgPixel == -1) 
+	    {
+	      SetTextColor (pGCPriv->hdcMem, fg);
+	      SetBkMode (pGCPriv->hdcMem, TRANSPARENT);
+	      BitBlt (hdcStipple,
+		      0, 0,
+		      pStipple->drawable.width, pStipple->drawable.height,
+		      hdcStipple,
+		      0, 0,
+		      0x330008);
+	    } 
+	  else if (pGC->fgPixel == -1) 
+	    {
+	      SetTextColor (pGCPriv->hdcMem, bg);
+	      SetBkMode (pGCPriv->hdcMem, TRANSPARENT);
+#if 0
+	      BitBlt (hdcStipple,
+		      0, 0,
+		      pStipple->drawable.width, pStipple->drawable.height,
+		      hdcStipple,
+		      0, 0,
+		      0x330008);
+#endif
+	    }
+
+	  while (iSpans--)
+	    {
+	      int width = pStipple->drawable.width;
+	      fullX1 = pPoints->x;
+	      fullY1 = pPoints->y;
+	      fullX2 = fullX1 + (int) *piWidths;
+	      pPoints++;
+	      piWidths++;
+	
+	      if (fullY1 < extentY1 || extentY2 <= fullY1)
+		continue;
+	
+	      if (fullX1 < extentX1)
+		fullX1 = extentX1;
+	      if (fullX2 > extentX2)
+		fullX2 = extentX2;
+	
+	      if (fullX1 >= fullX2)
+		continue;
+	
+	      for (iX = fullX1; iX < fullX2; iX += width)
+		{
+		  int xoffset;
+
+		  if ((iX + pStipple->drawable.width) > fullX2)
+		    width = fullX2 - iX;
+		  else
+		    width = pStipple->drawable.width;
+
+		  if (iX == fullX1)
+		    xoffset = (fullX1 - (pDrawable->x + (pGC->patOrg.x % pStipple->drawable.width) - pStipple->drawable.width)) % pStipple->drawable.width;
+		  else
+		    xoffset = 0;
+
+		  if (xoffset + width > pStipple->drawable.width)
+		    width = pStipple->drawable.width - xoffset;
+
+		  BitBlt (pGCPriv->hdcMem,
+		          iX, fullY1,
+		          width, 1,
+		          hdcStipple,
+			  xoffset,
+			  (fullY1 - (pDrawable->y + (pGC->patOrg.y % pStipple->drawable.height) - pStipple->drawable.height)) % pStipple->drawable.height,
+			  g_copyROP[pGC->alu]);
+		}
+	    }
+
+	  /* Clear the stipple HDC */
+	  SelectObject (hdcStipple, hbmpOrigStipple);
+	  DeleteDC (hdcStipple);
+
+	  /* Delete the device dependent stipple bitmap */
+	  DeleteObject (hBitmap);
+
+	  /* Restore the background mode */
+	  SetBkMode (pGCPriv->hdcMem, OPAQUE);
+	  break;
+
+	case FillTiled:
+
+	  /* Get a pixmap pointer from the tile pointer, and fetch privates  */
+	  pTile = (PixmapPtr) pGC->tile.pixmap;
+	  pTilePriv = winGetPixmapPriv (pTile);
+
+	  /* Create a memory DC to hold the tile */
+	  hdcTile = CreateCompatibleDC (pGCPriv->hdcMem);
+
+	  /* Select the tile into a DC */
+	  hbmpOrig = SelectObject (hdcTile, pTilePriv->hBitmap);
+	  if (hbmpOrig == NULL)
+	    FatalError ("winFillSpans - DRAWABLE_PIXMAP - FillTiled - "
+			"SelectObject () failed on pTilePriv->hBitmap\n");
+
+	  while (iSpans--)
+	    {
+	      int width = pTile->drawable.width;
+	      fullX1 = pPoints->x;
+	      fullY1 = pPoints->y;
+	      fullX2 = fullX1 + (int) *piWidths;
+	      pPoints++;
+	      piWidths++;
+	
+	      if (fullY1 < extentY1 || extentY2 <= fullY1)
+		continue;
+	
+	      if (fullX1 < extentX1)
+		fullX1 = extentX1;
+	      if (fullX2 > extentX2)
+		fullX2 = extentX2;
+	
+	      if (fullX1 >= fullX2)
+		continue;
+	
+	      for (iX = fullX1; iX < fullX2; iX += width)
+	      	{
+		  int xoffset;
+
+		  if ((iX + pTile->drawable.width) > fullX2)
+		    width = fullX2 - iX;
+		  else
+		    width = pTile->drawable.width;
+
+		  if (iX == fullX1)
+		    xoffset = (fullX1 - (pDrawable->x + (pGC->patOrg.x % pTile->drawable.width) - pTile->drawable.width)) % pTile->drawable.width;
+		  else
+		    xoffset = 0;
+
+		  if (xoffset + width > pTile->drawable.width)
+		    width = pTile->drawable.width - xoffset;
+
+		  BitBlt (pGCPriv->hdcMem,
+			  iX, fullY1,
+			  width, 1,
+			  hdcTile,
+			  xoffset,
+			  (fullY1 - (pDrawable->y + (pGC->patOrg.y % pTile->drawable.height) - pTile->drawable.height)) % pTile->drawable.height,
+			  g_copyROP[pGC->alu]);
+		}
+	    }
+
+	  /* Push the tile pixmap out of the memory HDC */
+	  SelectObject (hdcTile, hbmpOrig);
+
+	  /* Delete the tile */
+	  DeleteDC (hdcTile);
+	  break;
+
+	default:
+	  ErrorF ("winFillSpans - DRAWABLE_PIXMAP - Unknown fillStyle\n");
+	  break;
+	}
+
+      /* Reset clip region */
+      SelectClipRgn (pGCPriv->hdcMem, NULL);
+
+      /* Push the drawable pixmap out of the GC HDC */
+      SelectObject (pGCPriv->hdcMem, hbmpOrig);
+      break;
+      
+    case DRAWABLE_WINDOW:
+
+      SelectClipRgn (pGCPriv->hdc, combined);
+      DeleteObject (combined);
+      combined = NULL;
+
+      /* Branch on fill style */
+      switch (pGC->fillStyle)
+	{
+	case FillSolid:
+
+          ROP16 (pGCPriv->hdc, pGC->alu);
+
+	  if (pDrawable->depth == 1) 
+	    {
+	      if (pGC->fgPixel == 0)
+		hPenOrig = SelectObject (pGCPriv->hdc, 
+					 GetStockObject (BLACK_PEN));
+	      else
+		hPenOrig = SelectObject (pGCPriv->hdc,
+					 GetStockObject (WHITE_PEN));
+	    } 
+	  else 
+	    {
+	      fg = pGC->fgPixel;
+	      TRANSLATE_COLOR (fg);
+	      hPen = CreatePen (PS_SOLID, 0, fg);
+	      hPenOrig = SelectObject (pGCPriv->hdc, hPen);
+	    }
+
+	  while (iSpans--)
+	    {
+	      fullX1 = pPoints->x;
+	      fullY1 = pPoints->y;
+	      fullX2 = fullX1 + (int) *piWidths;
+	      pPoints++;
+	      piWidths++;
+	
+	      if (fullY1 < extentY1 || extentY2 <= fullY1)
+		continue;
+	
+	      if (fullX1 < extentX1)
+		fullX1 = extentX1;
+	      if (fullX2 > extentX2)
+		fullX2 = extentX2;
+	
+	      if (fullX1 >= fullX2)
+		continue;
+	
+	      MoveToEx (pGCPriv->hdc, fullX1, fullY1, NULL);
+	      LineTo (pGCPriv->hdc, fullX2, fullY1);
+	    }
+
+          SetROP2 (pGCPriv->hdc, R2_COPYPEN);
+
+	  /* Give back the Brush */
+	  SelectObject (pGCPriv->hdc, hPenOrig);
+
+	  if (pDrawable->depth != 1)
+	    DeleteObject (hPen);
+	  break;
+
+	case FillOpaqueStippled:
+
+	  pStipple = pGC->stipple;
+	  pStipplePriv = winGetPixmapPriv (pStipple);
+
+	  /* Create a device-dependent bitmap for the stipple */
+	  hBitmap = CreateDIBitmap (pGCPriv->hdc,
+				    (BITMAPINFOHEADER *)pStipplePriv->pbmih,
+				    CBM_INIT,
+				    pStipplePriv->pbBits,
+				    (BITMAPINFO *)pStipplePriv->pbmih,
+				    DIB_RGB_COLORS);
+
+	  /* Create a memory DC to hold the stipple */
+	  hdcStipple = CreateCompatibleDC (pGCPriv->hdc);
+
+	  /* Select the stipple bitmap into the stipple DC */
+	  hbmpOrigStipple = SelectObject (hdcStipple, hBitmap);
+	  if (hbmpOrigStipple == NULL)
+	    FatalError ("winFillSpans () - DRAWABLE_PIXMAP - FillStippled - "
+			"SelectObject () failed on hbmpOrigStipple\n");
+
+	  /* Make a temporary copy of the foreground and background colors */
+   	  bg = pGC->bgPixel;
+   	  fg = pGC->fgPixel;
+
+	  /* Translate the depth-dependent colors to Win32 COLORREFs */
+	  TRANSLATE_COLOR (fg);
+	  TRANSLATE_COLOR (bg);
+	  SetTextColor (pGCPriv->hdc, fg);
+	  SetBkColor (pGCPriv->hdc, bg);
+
+	  while (iSpans--)
+	    {
+	      int width = pStipple->drawable.width;
+	      fullX1 = pPoints->x;
+	      fullY1 = pPoints->y;
+	      fullX2 = fullX1 + (int) *piWidths;
+	      pPoints++;
+	      piWidths++;
+	
+	      if (fullY1 < extentY1 || extentY2 <= fullY1)
+		continue;
+	
+	      if (fullX1 < extentX1)
+		fullX1 = extentX1;
+	      if (fullX2 > extentX2)
+		fullX2 = extentX2;
+	
+	      if (fullX1 >= fullX2)
+		continue;
+	
+	      for (iX = fullX1; iX < fullX2; iX += width)
+		{
+		  int xoffset;
+
+		  if ((iX + pStipple->drawable.width) > fullX2)
+		    width = fullX2 - iX;
+		  else
+		    width = pStipple->drawable.width;
+
+		  if (iX == fullX1)
+		    xoffset = (fullX1 - (pDrawable->x + (pGC->patOrg.x % pStipple->drawable.width) - pStipple->drawable.width)) % pStipple->drawable.width;
+		  else
+		    xoffset = 0;
+
+		  if (xoffset + width > pStipple->drawable.width)
+		    width = pStipple->drawable.width - xoffset;
+
+		  BitBlt (pGCPriv->hdc,
+			  iX, fullY1,
+			  width, 1,
+			  hdcStipple,
+			  xoffset,
+			  (fullY1 - (pDrawable->y + (pGC->patOrg.y % pStipple->drawable.height) - pStipple->drawable.height)) % pStipple->drawable.height,
+			  g_copyROP[pGC->alu]);
+		}
+	    }
+
+	  /* Clear the stipple HDC */
+	  SelectObject (hdcStipple, hbmpOrigStipple);
+	  DeleteDC (hdcStipple);
+
+	  /* Delete the device dependent stipple bitmap */
+	  DeleteObject (hBitmap);
+
+	  break;
+
+	case FillStippled:
+	  pStipple = pGC->stipple;
+	  pStipplePriv = winGetPixmapPriv (pStipple);
+
+	  /* Create a device-dependent bitmap for the stipple */
+	  hBitmap = CreateDIBitmap (pGCPriv->hdcMem,
+				    (BITMAPINFOHEADER *)pStipplePriv->pbmih,
+				    CBM_INIT,
+				    pStipplePriv->pbBits,
+				    (BITMAPINFO *)pStipplePriv->pbmih,
+				    DIB_RGB_COLORS);
+
+	  /* Create a memory DC to hold the stipple */
+	  hdcStipple = CreateCompatibleDC (pGCPriv->hdc);
+
+	  /* Select the stipple bitmap into the stipple DC */
+	  hbmpOrigStipple = SelectObject (hdcStipple, hBitmap);
+	  if (hbmpOrigStipple == NULL)
+	    FatalError ("winFillSpans () - DRAWABLE_PIXMAP - FillStippled - "
+			"SelectObject () failed on hbmpOrigStipple\n");
+
+	  /* Make a temporary copy of the foreground and background colors */
+   	  bg = pGC->bgPixel;
+   	  fg = pGC->fgPixel;
+
+	  /* Translate the depth-dependent colors to Win32 COLORREFs */
+	  TRANSLATE_COLOR (fg);
+	  TRANSLATE_COLOR (bg);
+
+	  /* this is fudgy, we should only invert on the last one
+	   * We need to get the black/white pixels right in the
+	   * colormap. But yeah ! it's working.. 
+	   */
+	  if (pGC->bgPixel != -1 && pGC->fgPixel != -1) 
+	    {
+	      SetTextColor (pGCPriv->hdc, fg);
+	      SetBkColor (pGCPriv->hdc, bg);
+	      BitBlt (hdcStipple,
+		      0, 0,
+		      pStipple->drawable.width, pStipple->drawable.height,
+		      hdcStipple,
+		      0,0,
+		      0x330008);
+	    } 
+	  else if (pGC->bgPixel == -1) 
+	    {
+	      SetTextColor (pGCPriv->hdc, fg);
+	      SetBkMode (pGCPriv->hdc, TRANSPARENT);
+	      BitBlt (hdcStipple,
+		      0, 0,
+		      pStipple->drawable.width, pStipple->drawable.height,
+		      hdcStipple,
+		      0,0,
+		      0x330008);
+	    } 
+	  else if (pGC->fgPixel == -1) 
+	    {
+	      SetTextColor (pGCPriv->hdc, bg);
+	      SetBkMode (pGCPriv->hdc, TRANSPARENT);
+#if 0
+	      BitBlt (hdcStipple,
+		      0, 0,
+		      pStipple->drawable.width, pStipple->drawable.height,
+		      hdcStipple,
+		      0, 0,
+		      0x330008);
+#endif
+	    }
+
+	  while (iSpans--)
+	    {
+ 	      int width = pStipple->drawable.width;
+	      fullX1 = pPoints->x;
+	      fullY1 = pPoints->y;
+	      fullX2 = fullX1 + (int) *piWidths;
+	      pPoints++;
+	      piWidths++;
+	
+	      if (fullY1 < extentY1 || extentY2 <= fullY1)
+		continue;
+	
+	      if (fullX1 < extentX1)
+		fullX1 = extentX1;
+	      if (fullX2 > extentX2)
+		fullX2 = extentX2;
+	
+	      if (fullX1 >= fullX2)
+		continue;
+	
+	      for (iX = fullX1; iX < fullX2; iX += width)
+		{
+		  int xoffset;
+
+		  if ((iX + pStipple->drawable.width) > fullX2)
+		    width = fullX2 - iX;
+		  else
+		    width = pStipple->drawable.width;
+
+		  if (iX == fullX1)
+		    xoffset = (fullX1 - (pDrawable->x + (pGC->patOrg.x % pStipple->drawable.width) - pStipple->drawable.width)) % pStipple->drawable.width;
+		  else
+		    xoffset = 0;
+
+		  if (xoffset + width > pStipple->drawable.width)
+		    width = pStipple->drawable.width - xoffset;
+
+		  BitBlt (pGCPriv->hdc,
+			  iX, fullY1,
+			  width, 1,
+			  hdcStipple,
+			  xoffset,
+			  (fullY1 - (pDrawable->y + (pGC->patOrg.y % pStipple->drawable.height) - pStipple->drawable.height)) % pStipple->drawable.height,
+			  g_copyROP[pGC->alu]);
+		}
+	    }
+
+	  /* Clear the stipple HDC */
+	  SelectObject (hdcStipple, hbmpOrigStipple);
+	  DeleteDC (hdcStipple);
+
+	  /* Delete the device dependent stipple bitmap */
+	  DeleteObject (hBitmap);
+
+	  /* Restore the background mode */
+	  SetBkMode (pGCPriv->hdc, OPAQUE);	  
+	  break;
+
+	case FillTiled:
+
+	  /* Get a pixmap pointer from the tile pointer, and fetch privates  */
+	  pTile = (PixmapPtr) pGC->tile.pixmap;
+	  pTilePriv = winGetPixmapPriv (pTile);
+
+	  /* Select the tile into a DC */
+	  hbmpOrig = SelectObject (pGCPriv->hdcMem, pTilePriv->hBitmap);
+	  if (hbmpOrig == NULL)
+	    FatalError ("winFillSpans - DRAWABLE_WINDOW - FillTiled - "
+			"SelectObject () failed on pTilePriv->hBitmap\n");
+
+	  while (iSpans--)
+	    {
+	      int width = pTile->drawable.width;
+	      fullX1 = pPoints->x;
+	      fullY1 = pPoints->y;
+	      fullX2 = fullX1 + (int) *piWidths;
+	      pPoints++;
+	      piWidths++;
+	
+	      if (fullY1 < extentY1 || extentY2 <= fullY1)
+		continue;
+	
+	      if (fullX1 < extentX1)
+		fullX1 = extentX1;
+	      if (fullX2 > extentX2)
+		fullX2 = extentX2;
+	
+	      if (fullX1 >= fullX2)
+		continue;
+	
+	      for (iX = fullX1; iX < fullX2; iX += width)
+	      	{
+		  int xoffset;
+
+		  if ((iX + pTile->drawable.width) > fullX2)
+		    width = fullX2 - iX;
+		  else
+		    width = pTile->drawable.width;
+
+		  if (iX == fullX1)
+		    xoffset = (fullX1 - (pDrawable->x + (pGC->patOrg.x % pTile->drawable.width) - pTile->drawable.width)) % pTile->drawable.width;
+		  else
+		    xoffset = 0;
+
+		  if (xoffset + width > pTile->drawable.width)
+		    width = pTile->drawable.width - xoffset;
+
+		  BitBlt (pGCPriv->hdc,
+			  iX, fullY1,
+			  width, 1,
+			  pGCPriv->hdcMem,
+			  xoffset,
+			  (fullY1 - (pDrawable->y + (pGC->patOrg.y % pTile->drawable.height) - pTile->drawable.height)) % pTile->drawable.height,
+			  g_copyROP[pGC->alu]);
+		}
+	    }
+
+	  /* Push the tile pixmap out of the memory HDC */
+	  SelectObject (pGCPriv->hdcMem, hbmpOrig);
+	  break;
+
+	default:
+	  ErrorF ("winFillSpans - DRAWABLE_WINDOW - Unknown fillStyle\n");
+	  break;
+	}
+
+      /* Reset clip region */
+      SelectClipRgn (pGCPriv->hdc, NULL);
+      break;
+
+    case UNDRAWABLE_WINDOW:
+      /* UNDRAWABLE_WINDOW doesn't appear to get called when running xterm */
+      switch (pGC->fillStyle)
+	{
+	case FillSolid:
+	  ErrorF ("winFillSpans - UNDRAWABLE_WINDOW - FillSolid - "
+		  "Unimplemented\n");
+	  break;
+
+	case FillStippled:
+	  ErrorF ("winFillSpans - UNDRAWABLE_WINDOW - FillStippled - "
+		  "Unimplemented\n");
+	  break;
+
+	case FillTiled:
+	  ErrorF ("winFillSpans - UNDRAWABLE_WINDOW - FillTiled - "
+		  "Unimplemented\n");
+	  break;
+
+	case FillOpaqueStippled:
+	  ErrorF ("winFillSpans - UNDRAWABLE_WINDOW - OpaqueStippled - "
+		  "Unimplemented\n");
+	  break;
+
+	default:
+	  ErrorF ("winFillSpans - UNDRAWABLE_WINDOW - Unknown fillStyle\n");
+	  break;
+	}
+      break;
+
+    case DRAWABLE_BUFFER:
+      /* DRAWABLE_BUFFER seems to be undocumented. */
+      ErrorF ("winFillSpans - DRAWABLE_BUFFER - Unimplemented\n");
+      break;
+
+    default:
+      ErrorF ("winFillSpans - Unknown drawable type\n");
+      break;
+    }
+}
diff --git a/hw/xwin/winfont.c b/hw/xwin/winfont.c
new file mode 100644
index 0000000..af3e90d
--- /dev/null
+++ b/hw/xwin/winfont.c
@@ -0,0 +1,80 @@
+/*
+ *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+#ifdef XWIN_NATIVEGDI
+/* See Porting Layer Definition - p. 32 */
+/* See mfb/mfbfont.c - mfbRealizeFont() - which is empty :) */
+Bool
+winRealizeFontNativeGDI (ScreenPtr pScreen, FontPtr pFont)
+{
+  BOOL			fResult = TRUE;
+  winScreenPriv(pScreen);
+  
+#if CYGDEBUG
+  winTrace ("winRealizeFont (%p, %p)\n", pScreen, pFont);
+#endif
+
+  WIN_UNWRAP(RealizeFont);
+  if (pScreen->RealizeFont)
+    fResult = (*pScreen->RealizeFont) (pScreen, pFont);
+  WIN_WRAP(RealizeFont, winRealizeFontNativeGDI);
+  
+  return fResult;
+}
+
+/* See Porting Layer Definition - p. 32 */
+/* See mfb/mfbfont.c - mfbUnrealizeFont() - which is empty :) */
+Bool
+winUnrealizeFontNativeGDI (ScreenPtr pScreen, FontPtr pFont)
+{
+  BOOL			fResult = TRUE;
+  winScreenPriv(pScreen);
+  
+#if CYGDEBUG
+  winTrace ("winUnrealizeFont (%p, %p)\n", pScreen, pFont);
+#endif
+
+  WIN_UNWRAP(UnrealizeFont);
+  if (pScreen->UnrealizeFont)
+    fResult = (*pScreen->UnrealizeFont) (pScreen, pFont);
+  WIN_WRAP(UnrealizeFont, winUnrealizeFontNativeGDI);
+  
+  return fResult;
+#if CYGDEBUG
+  winDebug ("winUnrealizeFont()\n");
+#endif
+  return TRUE;
+}
+#endif
diff --git a/hw/xwin/wingc.c b/hw/xwin/wingc.c
new file mode 100644
index 0000000..107d87a
--- /dev/null
+++ b/hw/xwin/wingc.c
@@ -0,0 +1,256 @@
+/*
+ *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+void
+winPushPixels (GCPtr pGC, PixmapPtr pBitMap, DrawablePtr pDrawable, int dx, int dy, int xOrg, int yOrg);
+
+
+/*
+ * Local prototypes
+ */
+
+#if 0
+static void
+winChangeGCNativeGDI (GCPtr pGC, unsigned long ulChanges);
+#endif
+
+static void
+winValidateGCNativeGDI (GCPtr pGC,
+			unsigned long changes,
+			DrawablePtr pDrawable);
+
+#if 0
+static void
+winCopyGCNativeGDI (GCPtr pGCsrc, unsigned long ulMask, GCPtr pGCdst);
+#endif
+
+static void
+winDestroyGCNativeGDI (GCPtr pGC);
+
+#if 0
+static void
+winChangeClipNativeGDI (GCPtr pGC, int nType, pointer pValue, int nRects);
+
+static void
+winDestroyClipNativeGDI (GCPtr pGC);
+
+static void
+winCopyClipNativeGDI (GCPtr pGCdst, GCPtr pGCsrc);
+#endif
+
+#if 0
+/* GC Handling Routines */
+const GCFuncs winGCFuncs = {
+  winValidateGCNativeGDI,
+  winChangeGCNativeGDI,
+  winCopyGCNativeGDI,
+  winDestroyGCNativeGDI,
+  winChangeClipNativeGDI,
+  winDestroyClipNativeGDI,
+  winCopyClipNativeGDI,
+};
+#else
+const GCFuncs winGCFuncs = {
+  winValidateGCNativeGDI,
+  miChangeGC,
+  miCopyGC,
+  winDestroyGCNativeGDI,
+  miChangeClip,
+  miDestroyClip,
+  miCopyClip,
+};
+#endif
+
+/* Drawing Primitives */
+const GCOps winGCOps = {
+  winFillSpansNativeGDI,
+  winSetSpansNativeGDI,
+  miPutImage,
+  miCopyArea,
+  miCopyPlane,
+  miPolyPoint,
+  winPolyLineNativeGDI,
+  miPolySegment,
+  miPolyRectangle,
+  miPolyArc,
+  miFillPolygon,
+  miPolyFillRect,
+  miPolyFillArc,
+  miPolyText8,
+  miPolyText16,
+  miImageText8,
+  miImageText16,
+#if 0
+  winImageGlyphBltNativeGDI,
+  winPolyGlyphBltNativeGDI,
+#else
+  miImageGlyphBlt,
+  miPolyGlyphBlt,
+#endif
+  winPushPixels
+};
+
+
+/* See Porting Layer Definition - p. 45 */
+/* See mfb/mfbgc.c - mfbCreateGC() */
+/* See Strategies for Porting - pp. 15, 16 */
+Bool
+winCreateGCNativeGDI (GCPtr pGC)
+{
+  winPrivGCPtr		pGCPriv = NULL;
+  winPrivScreenPtr	pScreenPriv = NULL;
+
+#if 0
+  ErrorF ("winCreateGCNativeGDI - depth: %d\n",
+	  pGC->depth);
+#endif
+
+  pGC->clientClip = NULL;
+  pGC->clientClipType = CT_NONE;
+  pGC->freeCompClip = FALSE;
+  pGC->pCompositeClip = 0;
+
+  pGC->ops = (GCOps *) &winGCOps;
+  pGC->funcs = (GCFuncs *) &winGCFuncs;
+
+  /* We want all coordinates passed to spans functions to be screen relative */
+  pGC->miTranslate = TRUE;
+
+  /* Allocate privates for this GC */
+  pGCPriv = winGetGCPriv (pGC);
+  if (pGCPriv == NULL)
+    {
+      ErrorF ("winCreateGCNativeGDI () - Privates pointer was NULL\n");
+      return FALSE;
+    }
+
+  /* Create a new screen DC for the display window */
+  pScreenPriv = winGetScreenPriv (pGC->pScreen);
+  pGCPriv->hdc = GetDC (pScreenPriv->hwndScreen);
+
+  /* Allocate a memory DC for the GC */
+  pGCPriv->hdcMem = CreateCompatibleDC (pGCPriv->hdc);
+
+  return TRUE;
+}
+
+
+#if 0
+/* See Porting Layer Definition - p. 45 */
+static void
+winChangeGCNativeGDI (GCPtr pGC, unsigned long ulChanges)
+{
+#if 0
+  ErrorF ("winChangeGCNativeGDI () - Doing nothing\n");
+#endif
+}
+#endif
+
+
+static void
+winValidateGCNativeGDI (GCPtr pGC,
+			unsigned long ulChanges,
+			DrawablePtr pDrawable)
+{
+  if ((ulChanges & (GCClipXOrigin | GCClipYOrigin | GCClipMask | GCSubwindowMode)) 
+      || (pDrawable->serialNumber != (pGC->serialNumber & DRAWABLE_SERIAL_BITS)))
+  {
+    miComputeCompositeClip (pGC, pDrawable);
+  }
+}
+
+
+#if 0
+/* See Porting Layer Definition - p. 46 */
+static void
+winCopyGCNativeGDI (GCPtr pGCsrc, unsigned long ulMask, GCPtr pGCdst)
+{
+
+}
+#endif
+
+
+/* See Porting Layer Definition - p. 46 */
+static void
+winDestroyGCNativeGDI (GCPtr pGC)
+{
+  winGCPriv(pGC);
+  winScreenPriv(pGC->pScreen);
+
+  if (pGC->freeCompClip)
+	REGION_DESTROY (pGC->pScreen, pGC->pCompositeClip);
+
+  /* Free the memory DC */
+  if (pGCPriv->hdcMem != NULL)
+    {
+      DeleteDC (pGCPriv->hdcMem);
+      pGCPriv->hdcMem = NULL;
+    }
+
+  /* Release the screen DC for the display window */
+  if (pGCPriv->hdc != NULL)
+    {
+      ReleaseDC (pScreenPriv->hwndScreen, pGCPriv->hdc);
+      pGCPriv->hdc = NULL;
+    }
+
+  /* Invalidate the GC privates pointer */
+  winSetGCPriv (pGC, NULL);
+}
+
+#if 0
+/* See Porting Layer Definition - p. 46 */
+static void
+winChangeClipNativeGDI (GCPtr pGC, int nType, pointer pValue, int nRects)
+{
+
+}
+
+
+/* See Porting Layer Definition - p. 47 */
+static void
+winDestroyClipNativeGDI (GCPtr pGC)
+{
+
+}
+
+
+/* See Porting Layer Definition - p. 47 */
+static void
+winCopyClipNativeGDI (GCPtr pGCdst, GCPtr pGCsrc)
+{
+
+}
+#endif
diff --git a/hw/xwin/wingetsp.c b/hw/xwin/wingetsp.c
new file mode 100644
index 0000000..03f7f10
--- /dev/null
+++ b/hw/xwin/wingetsp.c
@@ -0,0 +1,192 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Harold L Hunt II
+ * 		Alan Hourihane <alanh at fairlite.demon.co.uk>
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+/* See Porting Layer Definition - p. 55 */
+void
+winGetSpansNativeGDI (DrawablePtr	pDrawable, 
+		      int		nMax, 
+		      DDXPointPtr	pPoints, 
+		      int		*piWidths, 
+		      int		iSpans, 
+		      char		*pDsts)
+{
+  PixmapPtr		pPixmap = NULL;
+  winPrivPixmapPtr	pPixmapPriv = NULL;
+  int			iSpan;
+  DDXPointPtr		pPoint = NULL;
+  int			*piWidth = NULL;
+  char			*pDst = pDsts;
+  HBITMAP		hbmpWindow, hbmpOrig, hbmpOrig1;
+  BYTE			*pbWindow = NULL;
+  HDC			hdcMem, hdcMem1;
+  ScreenPtr		pScreen = pDrawable->pScreen;
+  winScreenPriv(pScreen);
+
+  /* Branch on the drawable type */
+  switch (pDrawable->type)
+    {
+    case DRAWABLE_PIXMAP:
+#if 0
+      ErrorF ("winGetSpans - DRAWABLE_PIXMAP %08x\n",
+	      pDrawable);
+#endif
+
+      pPixmap = (PixmapPtr) pDrawable;
+      pPixmapPriv = winGetPixmapPriv (pPixmap);
+
+      /* Open a memory HDC */
+      hdcMem1 = CreateCompatibleDC (NULL);
+      hdcMem = CreateCompatibleDC (NULL);
+
+      /* Select the drawable pixmap into a DC */
+      hbmpOrig1 = SelectObject (hdcMem1, pPixmapPriv->hBitmap);
+
+      if (hbmpOrig1 == NULL)
+	FatalError ("winGetSpans - DRAWABLE_PIXMAP - SelectObject () "
+		    "failed on pPixmapPriv->hBitmap\n");
+
+      /* Loop through spans */
+      for (iSpan = 0; iSpan < iSpans; ++iSpan)
+	{
+	  pPoint = pPoints + iSpan;
+	  piWidth = piWidths + iSpan;
+
+      	  hbmpWindow = winCreateDIBNativeGDI (*piWidth, 1,
+					      pDrawable->depth,
+					      &pbWindow,
+					      NULL);
+
+      	  hbmpOrig = SelectObject (hdcMem, hbmpWindow);
+			       
+          /* Transfer the window bits to the window bitmap */
+          BitBlt (hdcMem,
+		  0, 0,
+		  *piWidth, 1, 
+		  hdcMem1,
+		  pPoint->x, pPoint->y,
+		  SRCCOPY);
+
+	  memcpy (pDst,
+		  (char*) pbWindow,
+		  PixmapBytePad (*piWidth, pDrawable->depth));
+
+      	  /* Pop the window bitmap out of the HDC and delete the bitmap */
+      	  SelectObject (hdcMem, hbmpOrig);
+	  DeleteObject (hbmpWindow);
+
+#if 0
+	  ErrorF ("(%dx%dx%d) (%d,%d) w: %d\n",
+		  pDrawable->width, pDrawable->height, pDrawable->depth,
+		  pPoint->x, pPoint->y, *piWidth);
+#endif
+
+	  /* Calculate offset of next bit destination */
+	  pDst += PixmapBytePad (*piWidth, pDrawable->depth);
+	}
+      
+      /* Pop the pixmap's bitmap out of the HDC */
+      SelectObject (hdcMem1, hbmpOrig1);
+
+      /* Delete the HDCs */
+      DeleteDC (hdcMem1);
+      DeleteDC (hdcMem);
+      break;
+
+    case DRAWABLE_WINDOW:
+#if 0
+      ErrorF ("winGetSpans - DRAWABLE_WINDOW\n");
+#endif
+
+      /* Open a memory HDC */
+      hdcMem = CreateCompatibleDC (NULL);
+
+      /* Loop through spans */
+      for (iSpan = 0; iSpan < iSpans; ++iSpan)
+	{
+	  pPoint = pPoints + iSpan;
+	  piWidth = piWidths + iSpan;
+
+      	  hbmpWindow = winCreateDIBNativeGDI (*piWidth, 1,
+					      pDrawable->depth,
+					      &pbWindow,
+					      NULL);
+
+      	  hbmpOrig = SelectObject (hdcMem, hbmpWindow);
+
+          /* Transfer the window bits to the window bitmap */
+          BitBlt (hdcMem,
+		  0, 0,
+		  *piWidth, 1, 
+		  pScreenPriv->hdcScreen,
+		  pPoint->x, pPoint->y,
+		  SRCCOPY);
+
+	  memcpy (pDst,
+		  (char*) pbWindow,
+		  PixmapBytePad (*piWidth, pDrawable->depth));
+
+      	  /* Pop the window bitmap out of the HDC */
+      	  SelectObject (hdcMem, hbmpOrig);
+
+	  DeleteObject (hbmpWindow);
+
+#if 0
+	  ErrorF ("(%dx%dx%d) (%d,%d) w: %d\n",
+		  pDrawable->width, pDrawable->height, pDrawable->depth,
+		  pPoint->x, pPoint->y, *piWidth);
+#endif
+
+	  /* Calculate offset of next bit destination */
+	  pDst += PixmapBytePad (*piWidth, pDrawable->depth);
+	}
+
+      /* Delete the window bitmap */
+      DeleteDC (hdcMem);
+      break;
+
+    case UNDRAWABLE_WINDOW:
+      FatalError ("winGetSpans - UNDRAWABLE_WINDOW\n");
+      break;
+
+    case DRAWABLE_BUFFER:
+      FatalError ("winGetSpans - DRAWABLE_BUFFER\n");
+      break;
+      
+    default:
+      FatalError ("winGetSpans - Unknown drawable type\n");
+      break;
+    }
+}
diff --git a/hw/xwin/winglobals.c b/hw/xwin/winglobals.c
new file mode 100644
index 0000000..fddada3
--- /dev/null
+++ b/hw/xwin/winglobals.c
@@ -0,0 +1,138 @@
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * General global variables
+ */
+
+int		g_iNumScreens = 0;
+winScreenInfo	g_ScreenInfo[MAXSCREENS];
+int		g_iLastScreen = -1;
+#ifdef HAS_DEVWINDOWS
+int		g_fdMessageQueue = WIN_FD_INVALID;
+#endif
+DevPrivateKey	g_iScreenPrivateKey = &g_iScreenPrivateKey;
+DevPrivateKey	g_iCmapPrivateKey = &g_iCmapPrivateKey;
+DevPrivateKey	g_iGCPrivateKey = &g_iGCPrivateKey;
+DevPrivateKey	g_iPixmapPrivateKey = &g_iPixmapPrivateKey;
+DevPrivateKey	g_iWindowPrivateKey = &g_iWindowPrivateKey;
+unsigned long	g_ulServerGeneration = 0;
+Bool		g_fInitializedDefaultScreens = FALSE;
+DWORD		g_dwEnginesSupported = 0;
+HINSTANCE	g_hInstance = 0;
+HWND		g_hDlgDepthChange = NULL;
+HWND		g_hDlgExit = NULL;
+HWND		g_hDlgAbout = NULL;
+const char *	g_pszQueryHost = NULL;
+Bool		g_fXdmcpEnabled = FALSE;
+HICON		g_hIconX = NULL;
+HICON		g_hSmallIconX = NULL;
+#ifndef RELOCATE_PROJECTROOT
+char *		g_pszLogFile = "/tmp/XWin.log";
+#else
+char *		g_pszLogFile = "XWin.log";
+Bool		g_fLogFileChanged = FALSE;
+#endif
+int		g_iLogVerbose = 2;
+Bool		g_fLogInited = FALSE;
+char *		g_pszCommandLine = NULL;
+Bool		g_fSilentFatalError = FALSE;
+DWORD		g_dwCurrentThreadID = 0;
+Bool		g_fKeyboardHookLL = FALSE;
+HHOOK		g_hhookKeyboardLL = NULL;
+HWND		g_hwndKeyboardFocus = NULL;
+Bool		g_fNoHelpMessageBox = FALSE;
+Bool		g_fSoftwareCursor = FALSE;
+Bool		g_fSilentDupError = FALSE;
+
+
+/*
+ * Global variables for dynamically loaded libraries and
+ * their function pointers
+ */
+
+HMODULE		g_hmodDirectDraw = NULL;
+FARPROC		g_fpDirectDrawCreate = NULL;
+FARPROC		g_fpDirectDrawCreateClipper = NULL;
+
+HMODULE		g_hmodCommonControls = NULL;
+FARPROC		g_fpTrackMouseEvent = (FARPROC) (void (*)(void))NoopDDA;
+
+
+#ifdef XWIN_CLIPBOARD
+/*
+ * Wrapped DIX functions
+ */
+winDispatchProcPtr	winProcEstablishConnectionOrig = NULL;
+winDispatchProcPtr	winProcQueryTreeOrig = NULL;
+winDispatchProcPtr	winProcSetSelectionOwnerOrig = NULL;
+
+
+/*
+ * Clipboard variables
+ */
+
+Bool			g_fUnicodeClipboard = TRUE;
+Bool			g_fClipboard = FALSE;
+Bool			g_fClipboardLaunched = FALSE;
+Bool			g_fClipboardStarted = FALSE;
+pthread_t		g_ptClipboardProc;
+HWND			g_hwndClipboard = NULL;
+void			*g_pClipboardDisplay = NULL;
+Window			g_iClipboardWindow = None;
+Atom			g_atomLastOwnedSelection = None;
+#endif
+
+
+/*
+ * Re-initialize global variables that are invalidated
+ * by a server reset.
+ */
+
+void
+winInitializeGlobals (void)
+{
+  g_dwCurrentThreadID = GetCurrentThreadId ();
+  g_hwndKeyboardFocus = NULL;
+#ifdef XWIN_CLIPBOARD
+  g_fClipboardLaunched = FALSE;
+  g_fClipboardStarted = FALSE;
+  g_iClipboardWindow = None;
+  g_pClipboardDisplay = NULL;
+  g_atomLastOwnedSelection = None;
+  g_hwndClipboard = NULL;
+#endif
+}
diff --git a/hw/xwin/winkeybd.c b/hw/xwin/winkeybd.c
new file mode 100644
index 0000000..d574f20
--- /dev/null
+++ b/hw/xwin/winkeybd.c
@@ -0,0 +1,637 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ */
+
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winkeybd.h"
+#include "winconfig.h"
+#include "winmsg.h"
+
+#ifdef XKB
+#ifndef XKB_IN_SERVER
+#define XKB_IN_SERVER
+#endif
+#include <xkbsrv.h>
+#endif
+
+static Bool g_winKeyState[NUM_KEYCODES];
+
+/* Stored to get internal mode key states.  Must be read-only.  */
+static unsigned short const *g_winInternalModeKeyStatesPtr = NULL;
+
+
+/*
+ * Local prototypes
+ */
+
+static void
+winGetKeyMappings (KeySymsPtr pKeySyms, CARD8 *pModMap);
+
+static void
+winKeybdBell (int iPercent, DeviceIntPtr pDeviceInt,
+	      pointer pCtrl, int iClass);
+
+static void
+winKeybdCtrl (DeviceIntPtr pDevice, KeybdCtrl *pCtrl);
+
+
+/* 
+ * Translate a Windows WM_[SYS]KEY(UP/DOWN) message
+ * into an ASCII scan code.
+ *
+ * We do this ourselves, rather than letting Windows handle it,
+ * because Windows tends to munge the handling of special keys,
+ * like AltGr on European keyboards.
+ */
+
+void
+winTranslateKey (WPARAM wParam, LPARAM lParam, int *piScanCode)
+{
+  int		iKeyFixup = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 1];
+  int		iKeyFixupEx = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 2];
+  int		iParamScanCode = LOBYTE (HIWORD (lParam));
+
+  /* Branch on special extended, special non-extended, or normal key */
+  if ((HIWORD (lParam) & KF_EXTENDED) && iKeyFixupEx)
+    *piScanCode = iKeyFixupEx;
+  else if (iKeyFixup)
+    *piScanCode = iKeyFixup;
+  else if (wParam == 0 && iParamScanCode == 0x70)
+    *piScanCode = KEY_HKTG;
+  else
+    switch (iParamScanCode)
+    {
+      case 0x70:
+        *piScanCode = KEY_HKTG;
+        break;
+      case 0x73:
+        *piScanCode = KEY_BSlash2;
+        break;
+      default: 
+        *piScanCode = iParamScanCode;
+        break;
+    }
+}
+
+
+/*
+ * We call this function from winKeybdProc when we are
+ * initializing the keyboard.
+ */
+
+static void
+winGetKeyMappings (KeySymsPtr pKeySyms, CARD8 *pModMap)
+{
+  int			i;
+  KeySym		*pMap = map;
+  KeySym		*pKeySym;
+
+  /*
+   * Initialize all key states to up... which may not be true
+   * but it is close enough.
+   */
+  ZeroMemory (g_winKeyState, sizeof (g_winKeyState[0]) * NUM_KEYCODES);
+
+  /* MAP_LENGTH is defined in Xserver/include/input.h to be 256 */
+  for (i = 0; i < MAP_LENGTH; i++)
+    pModMap[i] = NoSymbol;  /* make sure it is restored */
+
+  /* Loop through all valid entries in the key symbol table */
+  for (pKeySym = pMap, i = MIN_KEYCODE;
+       i < (MIN_KEYCODE + NUM_KEYCODES);
+       i++, pKeySym += GLYPHS_PER_KEY)
+    {
+      switch (*pKeySym)
+	{
+	case XK_Shift_L:
+	case XK_Shift_R:
+	  pModMap[i] = ShiftMask;
+	  break;
+
+	case XK_Control_L:
+	case XK_Control_R:
+	  pModMap[i] = ControlMask;
+	  break;
+
+	case XK_Caps_Lock:
+	  pModMap[i] = LockMask;
+	  break;
+
+	case XK_Alt_L:
+	case XK_Alt_R:
+	  pModMap[i] = AltMask;
+	  break;
+
+	case XK_Num_Lock:
+	  pModMap[i] = NumLockMask;
+	  break;
+
+	case XK_Scroll_Lock:
+	  pModMap[i] = ScrollLockMask;
+	  break;
+
+#if 0
+	case XK_Super_L:
+	case XK_Super_R:
+	  pModMap[i] = Mod4Mask;
+	  break;
+#else
+	/* Hirigana/Katakana toggle */
+	case XK_Kana_Lock:
+	case XK_Kana_Shift:
+	  pModMap[i] = KanaMask;
+	  break;
+#endif
+
+	/* alternate toggle for multinational support */
+	case XK_Mode_switch:
+	  pModMap[i] = AltLangMask;
+	  break;
+	}
+    }
+
+  pKeySyms->map        = (KeySym *) pMap;
+  pKeySyms->mapWidth   = GLYPHS_PER_KEY;
+  pKeySyms->minKeyCode = MIN_KEYCODE;
+  pKeySyms->maxKeyCode = MAX_KEYCODE;
+}
+
+
+/* Ring the keyboard bell (system speaker on PCs) */
+static void
+winKeybdBell (int iPercent, DeviceIntPtr pDeviceInt,
+	      pointer pCtrl, int iClass)
+{
+  /*
+   * We can't use Beep () here because it uses the PC speaker
+   * on NT/2000.  MessageBeep (MB_OK) will play the default system
+   * sound on systems with a sound card or it will beep the PC speaker
+   * on systems that do not have a sound card.
+   */
+  MessageBeep (MB_OK);
+}
+
+
+/* Change some keyboard configuration parameters */
+static void
+winKeybdCtrl (DeviceIntPtr pDevice, KeybdCtrl *pCtrl)
+{
+  g_winInternalModeKeyStatesPtr = &(pDevice->key->state);
+}
+
+
+/* 
+ * See Porting Layer Definition - p. 18
+ * winKeybdProc is known as a DeviceProc.
+ */
+
+int
+winKeybdProc (DeviceIntPtr pDeviceInt, int iState)
+{
+  KeySymsRec		keySyms;
+  CARD8 		modMap[MAP_LENGTH];
+  DevicePtr		pDevice = (DevicePtr) pDeviceInt;
+#ifdef XKB
+  XkbComponentNamesRec names;
+  XkbSrvInfoPtr       xkbi;
+  XkbControlsPtr      ctrl;
+#endif
+
+  switch (iState)
+    {
+    case DEVICE_INIT:
+      winConfigKeyboard (pDeviceInt);
+
+      winGetKeyMappings (&keySyms, modMap);
+
+#ifdef XKB
+      /* FIXME: Maybe we should use winGetKbdLeds () here? */
+      defaultKeyboardControl.leds = g_winInfo.keyboard.leds;
+#else
+      defaultKeyboardControl.leds = g_winInfo.keyboard.leds;
+#endif
+
+#ifdef XKB
+      if (g_winInfo.xkb.disable) 
+	{
+#endif
+	  InitKeyboardDeviceStruct (pDevice,
+				    &keySyms,
+				    modMap,
+				    winKeybdBell,
+				    winKeybdCtrl);
+#ifdef XKB
+	} 
+      else 
+	{
+
+          names.keymap = g_winInfo.xkb.keymap;
+          names.keycodes = g_winInfo.xkb.keycodes;
+          names.types = g_winInfo.xkb.types;
+          names.compat = g_winInfo.xkb.compat;
+          names.symbols = g_winInfo.xkb.symbols;
+          names.geometry = g_winInfo.xkb.geometry;
+
+	  winErrorFVerb(2, "Rules = \"%s\" Model = \"%s\" Layout = \"%s\""
+		 " Variant = \"%s\" Options = \"%s\"\n",
+		 g_winInfo.xkb.rules, g_winInfo.xkb.model,
+		 g_winInfo.xkb.layout, g_winInfo.xkb.variant,
+		 g_winInfo.xkb.options);
+          
+	  XkbSetRulesDflts (g_winInfo.xkb.rules, g_winInfo.xkb.model, 
+			    g_winInfo.xkb.layout, g_winInfo.xkb.variant, 
+			    g_winInfo.xkb.options);
+	  XkbInitKeyboardDeviceStruct (pDeviceInt, &names, &keySyms,
+				       modMap, winKeybdBell, winKeybdCtrl);
+	}
+#endif
+
+#ifdef XKB
+      if (!g_winInfo.xkb.disable)
+        {  
+          xkbi = pDeviceInt->key->xkbInfo;
+          if (xkbi != NULL)
+            {  
+              ctrl = xkbi->desc->ctrls;
+              ctrl->repeat_delay = g_winInfo.keyboard.delay;
+              ctrl->repeat_interval = 1000/g_winInfo.keyboard.rate;
+            }
+          else
+            {  
+              winErrorFVerb (1, "winKeybdProc - Error initializing keyboard AutoRepeat (No XKB)\n");
+            }
+        }
+#endif
+
+      g_winInternalModeKeyStatesPtr = &(pDeviceInt->key->state);
+      break;
+      
+    case DEVICE_ON: 
+      pDevice->on = TRUE;
+      g_winInternalModeKeyStatesPtr = &(pDeviceInt->key->state);
+      break;
+
+    case DEVICE_CLOSE:
+    case DEVICE_OFF: 
+      pDevice->on = FALSE;
+      g_winInternalModeKeyStatesPtr = NULL;
+      break;
+    }
+
+  return Success;
+}
+
+
+/*
+ * Detect current mode key states upon server startup.
+ *
+ * Simulate a press and release of any key that is currently
+ * toggled.
+ */
+
+void
+winInitializeModeKeyStates (void)
+{
+  /* Restore NumLock */
+  if (GetKeyState (VK_NUMLOCK) & 0x0001)
+    {
+      winSendKeyEvent (KEY_NumLock, TRUE);
+      winSendKeyEvent (KEY_NumLock, FALSE);
+    }
+
+  /* Restore CapsLock */
+  if (GetKeyState (VK_CAPITAL) & 0x0001)
+    {
+      winSendKeyEvent (KEY_CapsLock, TRUE);
+      winSendKeyEvent (KEY_CapsLock, FALSE);
+    }
+
+  /* Restore ScrollLock */
+  if (GetKeyState (VK_SCROLL) & 0x0001)
+    {
+      winSendKeyEvent (KEY_ScrollLock, TRUE);
+      winSendKeyEvent (KEY_ScrollLock, FALSE);
+    }
+
+  /* Restore KanaLock */
+  if (GetKeyState (VK_KANA) & 0x0001)
+    {
+      winSendKeyEvent (KEY_HKTG, TRUE);
+      winSendKeyEvent (KEY_HKTG, FALSE);
+    }
+}
+
+
+/*
+ * Upon regaining the keyboard focus we must
+ * resynchronize our internal mode key states
+ * with the actual state of the keys.
+ */
+
+void
+winRestoreModeKeyStates ()
+{
+  DWORD			dwKeyState;
+  BOOL			processEvents = TRUE;
+  unsigned short	internalKeyStates;
+
+  /* X server is being initialized */
+  if (!g_winInternalModeKeyStatesPtr)
+    return;
+
+  /* Only process events if the rootwindow is mapped. The keyboard events
+   * will cause segfaults otherwise */
+  if (WindowTable && WindowTable[0] && WindowTable[0]->mapped == FALSE)
+    processEvents = FALSE;    
+  
+  /* Force to process all pending events in the mi event queue */
+  if (processEvents)
+    mieqProcessInputEvents ();
+  
+  /* Read the mode key states of our X server */
+  internalKeyStates = *g_winInternalModeKeyStatesPtr;
+
+  /* 
+   * NOTE: The C XOR operator, ^, will not work here because it is
+   * a bitwise operator, not a logical operator.  C does not
+   * have a logical XOR operator, so we use a macro instead.
+   */
+
+  /* Has the key state changed? */
+  dwKeyState = GetKeyState (VK_NUMLOCK) & 0x0001;
+  if (WIN_XOR (internalKeyStates & NumLockMask, dwKeyState))
+    {
+      winSendKeyEvent (KEY_NumLock, TRUE);
+      winSendKeyEvent (KEY_NumLock, FALSE);
+    }
+
+  /* Has the key state changed? */
+  dwKeyState = GetKeyState (VK_CAPITAL) & 0x0001;
+  if (WIN_XOR (internalKeyStates & LockMask, dwKeyState))
+    {
+      winSendKeyEvent (KEY_CapsLock, TRUE);
+      winSendKeyEvent (KEY_CapsLock, FALSE);
+    }
+
+  /* Has the key state changed? */
+  dwKeyState = GetKeyState (VK_SCROLL) & 0x0001;
+  if (WIN_XOR (internalKeyStates & ScrollLockMask, dwKeyState))
+    {
+      winSendKeyEvent (KEY_ScrollLock, TRUE);
+      winSendKeyEvent (KEY_ScrollLock, FALSE);
+    }
+
+  /* Has the key state changed? */
+  dwKeyState = GetKeyState (VK_KANA) & 0x0001;
+  if (WIN_XOR (internalKeyStates & KanaMask, dwKeyState))
+    {
+      winSendKeyEvent (KEY_HKTG, TRUE);
+      winSendKeyEvent (KEY_HKTG, FALSE);
+    }
+}
+
+
+/*
+ * Look for the lovely fake Control_L press/release generated by Windows
+ * when AltGr is pressed/released on a non-U.S. keyboard.
+ */
+
+Bool
+winIsFakeCtrl_L (UINT message, WPARAM wParam, LPARAM lParam)
+{
+  MSG		msgNext;
+  LONG		lTime;
+  Bool		fReturn;
+
+  /*
+   * Fake Ctrl_L presses will be followed by an Alt_R keypress
+   * with the same timestamp as the Ctrl_L press.
+   */
+  if ((message == WM_KEYDOWN || message == WM_SYSKEYDOWN)
+      && wParam == VK_CONTROL
+      && (HIWORD (lParam) & KF_EXTENDED) == 0)
+    {
+      /* Got a Ctrl_L press */
+
+      /* Get time of current message */
+      lTime = GetMessageTime ();
+
+      /* Look for fake Ctrl_L preceeding an Alt_R press. */
+      fReturn = PeekMessage (&msgNext, NULL,
+			     WM_KEYDOWN, WM_SYSKEYDOWN,
+			     PM_NOREMOVE);
+
+      /*
+       * Try again if the first call fails.
+       * NOTE: This usually happens when TweakUI is enabled.
+       */
+      if (!fReturn)
+	{
+	  /* Voodoo to make sure that the Alt_R message has posted */
+	  Sleep (0);
+
+	  /* Look for fake Ctrl_L preceeding an Alt_R press. */
+	  fReturn = PeekMessage (&msgNext, NULL,
+				 WM_KEYDOWN, WM_SYSKEYDOWN,
+				 PM_NOREMOVE);
+	}
+      if (msgNext.message != WM_KEYDOWN && msgNext.message != WM_SYSKEYDOWN)
+          fReturn = 0;
+
+      /* Is next press an Alt_R with the same timestamp? */
+      if (fReturn && msgNext.wParam == VK_MENU
+	  && msgNext.time == lTime
+	  && (HIWORD (msgNext.lParam) & KF_EXTENDED))
+	{
+	  /* 
+	   * Next key press is Alt_R with same timestamp as current
+	   * Ctrl_L message.  Therefore, this Ctrl_L press is a fake
+	   * event, so discard it.
+	   */
+	  return TRUE;
+	}
+    }
+
+  /* 
+   * Fake Ctrl_L releases will be followed by an Alt_R release
+   * with the same timestamp as the Ctrl_L release.
+   */
+  if ((message == WM_KEYUP || message == WM_SYSKEYUP)
+      && wParam == VK_CONTROL
+      && (HIWORD (lParam) & KF_EXTENDED) == 0)
+    {
+      /* Got a Ctrl_L release */
+
+      /* Get time of current message */
+      lTime = GetMessageTime ();
+
+      /* Look for fake Ctrl_L release preceeding an Alt_R release. */
+      fReturn = PeekMessage (&msgNext, NULL,
+			     WM_KEYUP, WM_SYSKEYUP, 
+			     PM_NOREMOVE);
+
+      /*
+       * Try again if the first call fails.
+       * NOTE: This usually happens when TweakUI is enabled.
+       */
+      if (!fReturn)
+	{
+	  /* Voodoo to make sure that the Alt_R message has posted */
+	  Sleep (0);
+
+	  /* Look for fake Ctrl_L release preceeding an Alt_R release. */
+	  fReturn = PeekMessage (&msgNext, NULL,
+				 WM_KEYUP, WM_SYSKEYUP, 
+				 PM_NOREMOVE);
+	}
+
+      if (msgNext.message != WM_KEYUP && msgNext.message != WM_SYSKEYUP)
+          fReturn = 0;
+      
+      /* Is next press an Alt_R with the same timestamp? */
+      if (fReturn
+	  && (msgNext.message == WM_KEYUP
+	      || msgNext.message == WM_SYSKEYUP)
+	  && msgNext.wParam == VK_MENU
+	  && msgNext.time == lTime
+	  && (HIWORD (msgNext.lParam) & KF_EXTENDED))
+	{
+	  /*
+	   * Next key release is Alt_R with same timestamp as current
+	   * Ctrl_L message. Therefore, this Ctrl_L release is a fake
+	   * event, so discard it.
+	   */
+	  return TRUE;
+	}
+    }
+  
+  /* Not a fake control left press/release */
+  return FALSE;
+}
+
+
+/*
+ * Lift any modifier keys that are pressed
+ */
+
+void
+winKeybdReleaseKeys ()
+{
+  int				i;
+
+#ifdef HAS_DEVWINDOWS
+  /* Verify that the mi input system has been initialized */
+  if (g_fdMessageQueue == WIN_FD_INVALID)
+    return;
+#endif
+
+  /* Loop through all keys */
+  for (i = 0; i < NUM_KEYCODES; ++i)
+    {
+      /* Pop key if pressed */
+      if (g_winKeyState[i])
+	winSendKeyEvent (i, FALSE);
+
+      /* Reset pressed flag for keys */
+      g_winKeyState[i] = FALSE;
+    }
+}
+
+
+/*
+ * Take a raw X key code and send an up or down event for it.
+ *
+ * Thanks to VNC for inspiration, though it is a simple function.
+ */
+
+void
+winSendKeyEvent (DWORD dwKey, Bool fDown)
+{
+  xEvent			xCurrentEvent;
+
+  /*
+   * When alt-tabing between screens we can get phantom key up messages
+   * Here we only pass them through it we think we should!
+   */
+  if (g_winKeyState[dwKey] == FALSE && fDown == FALSE) return;
+
+  /* Update the keyState map */
+  g_winKeyState[dwKey] = fDown;
+  
+  ZeroMemory (&xCurrentEvent, sizeof (xCurrentEvent));
+
+  xCurrentEvent.u.u.type = fDown ? KeyPress : KeyRelease;
+  xCurrentEvent.u.keyButtonPointer.time =
+    g_c32LastInputEventTime = GetTickCount ();
+  xCurrentEvent.u.u.detail = dwKey + MIN_KEYCODE;
+  mieqEnqueue (&xCurrentEvent);
+}
+
+BOOL winCheckKeyPressed(WPARAM wParam, LPARAM lParam)
+{
+  switch (wParam)
+  {
+    case VK_CONTROL:
+      if ((lParam & 0x1ff0000) == 0x11d0000 && g_winKeyState[KEY_RCtrl])
+        return TRUE;
+      if ((lParam & 0x1ff0000) == 0x01d0000 && g_winKeyState[KEY_LCtrl])
+        return TRUE;
+      break;
+    case VK_SHIFT:
+      if ((lParam & 0x1ff0000) == 0x0360000 && g_winKeyState[KEY_ShiftR])
+        return TRUE;
+      if ((lParam & 0x1ff0000) == 0x02a0000 && g_winKeyState[KEY_ShiftL])
+        return TRUE;
+      break;
+    default:
+      return TRUE;
+  }
+  return FALSE;
+}
+
+/* Only on shift release message is sent even if both are pressed.
+ * Fix this here 
+ */
+void winFixShiftKeys (int iScanCode)
+{
+  if (GetKeyState (VK_SHIFT) & 0x8000)
+    return;
+
+  if (iScanCode == KEY_ShiftL && g_winKeyState[KEY_ShiftR])
+    winSendKeyEvent (KEY_ShiftR, FALSE);
+  if (iScanCode == KEY_ShiftR && g_winKeyState[KEY_ShiftL])
+    winSendKeyEvent (KEY_ShiftL, FALSE);
+}
diff --git a/hw/xwin/winkeybd.h b/hw/xwin/winkeybd.h
new file mode 100644
index 0000000..09eed14
--- /dev/null
+++ b/hw/xwin/winkeybd.h
@@ -0,0 +1,309 @@
+#if !defined(WINKEYBD_H)
+#define WINKEYBD_H
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+/*
+ * We need symbols for the scan codes of keys.
+ */
+#include "winkeynames.h"
+
+
+/*
+ * Include the standard ASCII keymap.
+ *
+ * This header declares a static KeySym array called 'map'.
+ */
+#include "winkeymap.h"
+
+#define		WIN_KEYMAP_COLS		3
+
+const int
+g_iKeyMap [] = {
+  /* count	Windows VK,	ASCII,		ASCII when extended VK */
+  /* 0 */	0,		0,		0,
+  /* 1 */	0,		0,		0,
+  /* 2 */	0,		0,		0,
+  /* 3 */	VK_CANCEL,	0,		KEY_Break,
+  /* 4 */	0,		0,		0,
+  /* 5 */	0,		0,		0,
+  /* 6 */	0,		0,		0,
+  /* 7 */	0,		0,		0,
+  /* 8 */	0,		0,		0,
+  /* 9 */	0,		0,		0,
+  /* 10 */	0,		0,		0,
+  /* 11 */	0,		0,		0,
+  /* 12 */	0,		0,		0,
+  /* 13 */	VK_RETURN,	0,		KEY_KP_Enter,
+  /* 14 */	0,		0,		0,
+  /* 15 */	0,		0,		0,
+  /* 16 */	VK_SHIFT,	0,		0,
+  /* 17 */	VK_CONTROL,	0,		KEY_RCtrl,
+  /* 18 */	VK_MENU,	0,		KEY_AltLang,
+  /* 19 */	VK_PAUSE,	KEY_Pause,	0,
+  /* 20 */	0,		0,		0,
+  /* 21 */	0,		0,		0,
+  /* 22 */	0,		0,		0,
+  /* 23 */	0,		0,		0,
+  /* 24 */	0,		0,		0,
+  /* 25 */	0,		0,		0,
+  /* 26 */	0,		0,		0,
+  /* 27 */	0,		0,		0,
+  /* 28 */	0,		0,		0,
+  /* 29 */	0,		0,		0,
+  /* 30 */	0,		0,		0,
+  /* 31 */	0,		0,		0,
+  /* 32 */	0,		0,		0,
+  /* 33 */	VK_PRIOR,	0,		KEY_PgUp,
+  /* 34 */	VK_NEXT,	0,		KEY_PgDown,
+  /* 35 */	VK_END,		0,		KEY_End,
+  /* 36 */	VK_HOME,	0,		KEY_Home,
+  /* 37 */	VK_LEFT,	0,		KEY_Left,
+  /* 38 */	VK_UP,		0,		KEY_Up,
+  /* 39 */	VK_RIGHT,	0,		KEY_Right,
+  /* 40 */	VK_DOWN,	0,		KEY_Down,
+  /* 41 */	0,		0,		0,
+  /* 42 */	0,		0,		0,
+  /* 43 */	0,		0,		0,
+  /* 44 */	VK_SNAPSHOT,	0,		KEY_Print,  
+  /* 45 */	VK_INSERT,	0,		KEY_Insert,
+  /* 46 */	VK_DELETE,	0,		KEY_Delete,
+  /* 47 */	0,		0,		0,
+  /* 48 */	0,		0,		0,
+  /* 49 */	0,		0,		0,
+  /* 50 */	0,		0,		0,
+  /* 51 */	0,		0,		0,
+  /* 52 */	0,		0,		0,
+  /* 53 */	0,		0,		0,
+  /* 54 */	0,		0,		0,
+  /* 55 */	0,		0,		0,
+  /* 56 */	0,		0,		0,
+  /* 57 */	0,		0,		0,
+  /* 58 */	0,		0,		0,
+  /* 59 */	0,		0,		0,
+  /* 60 */	0,		0,		0,
+  /* 61 */	0,		0,		0,
+  /* 62 */	0,		0,		0,
+  /* 63 */	0,		0,		0,
+  /* 64 */	0,		0,		0,
+  /* 65 */	0,		0,		0,
+  /* 66 */	0,		0,		0,
+  /* 67 */	0,		0,		0,
+  /* 68 */	0,		0,		0,
+  /* 69 */	0,		0,		0,
+  /* 70 */	0,		0,		0,
+  /* 71 */	0,		0,		0,
+  /* 72 */	0,		0,		0,
+  /* 73 */	0,		0,		0,
+  /* 74 */	0,		0,		0,
+  /* 75 */	0,		0,		0,
+  /* 76 */	0,		0,		0,
+  /* 77 */	0,		0,		0,
+  /* 78 */	0,		0,		0,
+  /* 79 */	0,		0,		0,
+  /* 80 */	0,		0,		0,
+  /* 81 */	0,		0,		0,
+  /* 82 */	0,		0,		0,
+  /* 83 */	0,		0,		0,
+  /* 84 */	0,		0,		0,
+  /* 85 */	0,		0,		0,
+  /* 86 */	0,		0,		0,
+  /* 87 */	0,		0,		0,
+  /* 88 */	0,		0,		0,
+  /* 89 */	0,		0,		0,
+  /* 90 */	0,		0,		0,
+  /* 91 */	VK_LWIN,	KEY_LMeta,	0,
+  /* 92 */	VK_RWIN,	KEY_RMeta,	0,
+  /* 93 */	VK_APPS,	KEY_Menu,	0,
+  /* 94 */	0,		0,		0,
+  /* 95 */	0,		0,		0,
+  /* 96 */	0,		0,		0,
+  /* 97 */	0,		0,		0,
+  /* 98 */	0,		0,		0,
+  /* 99 */	0,		0,		0,
+  /* 100 */	0,		0,		0,
+  /* 101 */	0,		0,		0,
+  /* 102 */	0,		0,		0,
+  /* 103 */	0,		0,		0,
+  /* 104 */	0,		0,		0,
+  /* 105 */	0,		0,		0,
+  /* 106 */	0,		0,		0,
+  /* 107 */	0,		0,		0,
+  /* 108 */	0,		0,		0,
+  /* 109 */	0,		0,		0,
+  /* 110 */	0,		0,		0,
+  /* 111 */	VK_DIVIDE,	0,		KEY_KP_Divide,
+  /* 112 */	0,		0,		0,
+  /* 113 */	0,		0,		0,
+  /* 114 */	0,		0,		0,
+  /* 115 */	0,		0,		0,
+  /* 116 */	0,		0,		0,
+  /* 117 */	0,		0,		0,
+  /* 118 */	0,		0,		0,
+  /* 119 */	0,		0,		0,
+  /* 120 */	0,		0,		0,
+  /* 121 */	0,		0,		0,
+  /* 122 */	0,		0,		0,
+  /* 123 */	0,		0,		0,
+  /* 124 */	0,		0,		0,
+  /* 125 */	0,		0,		0,
+  /* 126 */	0,		0,		0,
+  /* 127 */	0,		0,		0,
+  /* 128 */	0,		0,		0,
+  /* 129 */	0,		0,		0,
+  /* 130 */	0,		0,		0,
+  /* 131 */	0,		0,		0,
+  /* 132 */	0,		0,		0,
+  /* 133 */	0,		0,		0,
+  /* 134 */	0,		0,		0,
+  /* 135 */	0,		0,		0,
+  /* 136 */	0,		0,		0,
+  /* 137 */	0,		0,		0,
+  /* 138 */	0,		0,		0,
+  /* 139 */	0,		0,		0,
+  /* 140 */	0,		0,		0,
+  /* 141 */	0,		0,		0,
+  /* 142 */	0,		0,		0,
+  /* 143 */	0,		0,		0,
+  /* 144 */	0,		0,		0,
+  /* 145 */	0,		0,		0,
+  /* 146 */	0,		0,		0,
+  /* 147 */	0,		0,		0,
+  /* 148 */	0,		0,		0,
+  /* 149 */	0,		0,		0,
+  /* 150 */	0,		0,		0,
+  /* 151 */	0,		0,		0,
+  /* 152 */	0,		0,		0,
+  /* 153 */	0,		0,		0,
+  /* 154 */	0,		0,		0,
+  /* 155 */	0,		0,		0,
+  /* 156 */	0,		0,		0,
+  /* 157 */	0,		0,		0,
+  /* 158 */	0,		0,		0,
+  /* 159 */	0,		0,		0,
+  /* 160 */	0,		0,		0,
+  /* 161 */	0,		0,		0,
+  /* 162 */	0,		0,		0,
+  /* 163 */	0,		0,		0,
+  /* 164 */	0,		0,		0,
+  /* 165 */	0,		0,		0,
+  /* 166 */	0,		0,		0,
+  /* 167 */	0,		0,		0,
+  /* 168 */	0,		0,		0,
+  /* 169 */	0,		0,		0,
+  /* 170 */	0,		0,		0,
+  /* 171 */	0,		0,		0,
+  /* 172 */	0,		0,		0,
+  /* 173 */	0,		0,		0,
+  /* 174 */	0,		0,		0,
+  /* 175 */	0,		0,		0,
+  /* 176 */	0,		0,		0,
+  /* 177 */	0,		0,		0,
+  /* 178 */	0,		0,		0,
+  /* 179 */	0,		0,		0,
+  /* 180 */	0,		0,		0,
+  /* 181 */	0,		0,		0,
+  /* 182 */	0,		0,		0,
+  /* 183 */	0,		0,		0,
+  /* 184 */	0,		0,		0,
+  /* 185 */	0,		0,		0,
+  /* 186 */	0,		0,		0,
+  /* 187 */	0,		0,		0,
+  /* 188 */	0,		0,		0,
+  /* 189 */	0,		0,		0,
+  /* 190 */	0,		0,		0,
+  /* 191 */	0,		0,		0,
+  /* 192 */	0,		0,		0,
+  /* 193 */	0,		0,		0,
+  /* 194 */	0,		0,		0,
+  /* 195 */	0,		0,		0,
+  /* 196 */	0,		0,		0,
+  /* 197 */	0,		0,		0,
+  /* 198 */	0,		0,		0,
+  /* 199 */	0,		0,		0,
+  /* 200 */	0,		0,		0,
+  /* 201 */	0,		0,		0,
+  /* 202 */	0,		0,		0,
+  /* 203 */	0,		0,		0,
+  /* 204 */	0,		0,		0,
+  /* 205 */	0,		0,		0,
+  /* 206 */	0,		0,		0,
+  /* 207 */	0,		0,		0,
+  /* 208 */	0,		0,		0,
+  /* 209 */	0,		0,		0,
+  /* 210 */	0,		0,		0,
+  /* 211 */	0,		0,		0,
+  /* 212 */	0,		0,		0,
+  /* 213 */	0,		0,		0,
+  /* 214 */	0,		0,		0,
+  /* 215 */	0,		0,		0,
+  /* 216 */	0,		0,		0,
+  /* 217 */	0,		0,		0,
+  /* 218 */	0,		0,		0,
+  /* 219 */	0,		0,		0,
+  /* 220 */	0,		0,		0,
+  /* 221 */	0,		0,		0,
+  /* 222 */	0,		0,		0,
+  /* 223 */	0,		0,		0,
+  /* 224 */	0,		0,		0,
+  /* 225 */	0,		0,		0,
+  /* 226 */	0,		0,		0,
+  /* 227 */	0,		0,		0,
+  /* 228 */	0,		0,		0,
+  /* 229 */	0,		0,		0,
+  /* 230 */	0,		0,		0,
+  /* 231 */	0,		0,		0,
+  /* 232 */	0,		0,		0,
+  /* 233 */	0,		0,		0,
+  /* 234 */	0,		0,		0,
+  /* 235 */	0,		0,		0,
+  /* 236 */	0,		0,		0,
+  /* 237 */	0,		0,		0,
+  /* 238 */	0,		0,		0,
+  /* 239 */	0,		0,		0,
+  /* 240 */	0,		0,		0,
+  /* 241 */	0,		0,		0,
+  /* 242 */	0,		0,		0,
+  /* 243 */	0,		0,		0,
+  /* 244 */	0,		0,		0,
+  /* 245 */	0,		0,		0,
+  /* 246 */	0,		0,		0,
+  /* 247 */	0,		0,		0,
+  /* 248 */	0,		0,		0,
+  /* 249 */	0,		0,		0,
+  /* 250 */	0,		0,		0,
+  /* 251 */	0,		0,		0,
+  /* 252 */	0,		0,		0,
+  /* 253 */	0,		0,		0,
+  /* 254 */	0,		0,		0,
+  /* 255 */	0,		0,		0
+};
+
+#endif /* WINKEYBD_H */
diff --git a/hw/xwin/winkeyhook.c b/hw/xwin/winkeyhook.c
new file mode 100755
index 0000000..53d91e6
--- /dev/null
+++ b/hw/xwin/winkeyhook.c
@@ -0,0 +1,194 @@
+/*
+ *Copyright (C) 2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * References to external symbols
+ */
+
+extern HHOOK			g_hhookKeyboardLL;
+extern DWORD			g_dwCurrentThreadID;
+extern HWND			g_hwndKeyboardFocus;
+
+
+/*
+ * Function prototypes
+ */
+
+static LRESULT CALLBACK
+winKeyboardMessageHookLL (int iCode, WPARAM wParam, LPARAM lParam);
+
+
+#ifndef LLKHF_EXTENDED
+# define LLKHF_EXTENDED  0x00000001
+#endif
+#ifndef LLKHF_UP
+# define LLKHF_UP  0x00000080
+#endif
+
+
+/*
+ * KeyboardMessageHook
+ */
+
+static LRESULT CALLBACK
+winKeyboardMessageHookLL (int iCode, WPARAM wParam, LPARAM lParam)
+{
+  BOOL			fPassKeystroke = FALSE;
+  BOOL			fPassAltTab = TRUE;
+  PKBDLLHOOKSTRUCT	p = (PKBDLLHOOKSTRUCT) lParam;
+  HWND			hwnd = GetActiveWindow(); 
+#ifdef XWIN_MULTIWINDOW
+  WindowPtr		pWin = NULL;
+  winPrivWinPtr	        pWinPriv = NULL;
+  winPrivScreenPtr	pScreenPriv = NULL;
+  winScreenInfo		*pScreenInfo = NULL;
+
+  /* Check if the Windows window property for our X window pointer is valid */
+  if ((pWin = GetProp (hwnd, WIN_WINDOW_PROP)) != NULL)
+    {
+      /* Get a pointer to our window privates */
+      pWinPriv		= winGetWindowPriv(pWin);
+
+      /* Get pointers to our screen privates and screen info */
+      pScreenPriv	= pWinPriv->pScreenPriv;
+      pScreenInfo	= pScreenPriv->pScreenInfo;
+
+      if (pScreenInfo->fMultiWindow)
+          fPassAltTab = FALSE;
+    }
+#endif
+
+  /* Pass keystrokes on to our main message loop */
+  if (iCode == HC_ACTION)
+    {
+#if 0
+      ErrorF ("vkCode: %08x\tscanCode: %08x\n", p->vkCode, p->scanCode);
+#endif
+
+      switch (wParam)
+	{
+	case WM_KEYDOWN:  case WM_SYSKEYDOWN:
+	case WM_KEYUP:    case WM_SYSKEYUP: 
+	  fPassKeystroke = 
+	    (fPassAltTab && 
+                (p->vkCode == VK_TAB) && ((p->flags & LLKHF_ALTDOWN) != 0))
+	    || (p->vkCode == VK_LWIN) || (p->vkCode == VK_RWIN)
+	    ;
+	  break;
+	}
+    }
+
+  /*
+   * Pass message on to our main message loop.
+   * We process this immediately with SendMessage so that the keystroke
+   * appears in, hopefully, the correct order.
+   */
+  if (fPassKeystroke)
+    {
+      LPARAM		lParamKey = 0x0;
+
+      /* Construct the lParam from KBDLLHOOKSTRUCT */
+      lParamKey = lParamKey | (0x0000FFFF & 0x00000001); /* Repeat count */
+      lParamKey = lParamKey | (0x00FF0000 & (p->scanCode << 16));
+      lParamKey = lParamKey
+	| (0x01000000 & ((p->flags & LLKHF_EXTENDED) << 23));
+      lParamKey = lParamKey
+	| (0x20000000
+	   & ((p->flags & LLKHF_ALTDOWN) << 24));
+      lParamKey = lParamKey | (0x80000000 & ((p->flags & LLKHF_UP) << 24));
+
+      /* Send message to our main window that has the keyboard focus */
+      PostMessage (hwnd,
+		   (UINT) wParam,
+		   (WPARAM) p->vkCode,
+		   lParamKey);
+
+      return 1;
+    }
+
+  /* Call next hook */
+  return CallNextHookEx (NULL, iCode, wParam, lParam);
+}
+
+
+/*
+ * Attempt to install the keyboard hook, return FALSE if it was not installed
+ */
+
+Bool
+winInstallKeyboardHookLL ()
+{
+  OSVERSIONINFO		osvi = {0};
+  
+  /* Get operating system version information */
+  osvi.dwOSVersionInfoSize = sizeof (osvi);
+  GetVersionEx (&osvi);
+
+  /* Branch on platform ID */
+  switch (osvi.dwPlatformId)
+    {
+    case VER_PLATFORM_WIN32_NT:
+      /* Low-level is supported on NT 4.0 SP3+ only */
+      /* TODO: Return FALSE on NT 4.0 with no SP, SP1, or SP2 */
+      break;
+
+    case VER_PLATFORM_WIN32_WINDOWS:
+      /* Low-level hook is not supported on non-NT */
+      return FALSE;
+    }
+
+  /* Install the hook only once */
+  if (!g_hhookKeyboardLL)
+    g_hhookKeyboardLL = SetWindowsHookEx (WH_KEYBOARD_LL,
+					  winKeyboardMessageHookLL,
+					  g_hInstance,
+					  0);
+
+  return TRUE;
+}
+
+
+/*
+ * Remove the keyboard hook if it is installed
+ */
+
+void
+winRemoveKeyboardHookLL ()
+{
+  if (g_hhookKeyboardLL)
+    UnhookWindowsHookEx (g_hhookKeyboardLL);
+  g_hhookKeyboardLL = NULL;
+}
diff --git a/hw/xwin/winkeymap.h b/hw/xwin/winkeymap.h
new file mode 100644
index 0000000..3862f03
--- /dev/null
+++ b/hw/xwin/winkeymap.h
@@ -0,0 +1,136 @@
+/*
+ *
+ * For Scancodes see notes in winkeynames.h  !!!!
+ *
+ */
+
+static KeySym map[NUM_KEYCODES * GLYPHS_PER_KEY] = {
+    /* 0x00 */  NoSymbol,       NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x01 */  XK_Escape,      NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x02 */  XK_1,           XK_exclam,	NoSymbol,	NoSymbol,
+    /* 0x03 */  XK_2,           XK_at,		NoSymbol,	NoSymbol,
+    /* 0x04 */  XK_3,           XK_numbersign,	NoSymbol,	NoSymbol,
+    /* 0x05 */  XK_4,           XK_dollar,	NoSymbol,	NoSymbol,
+    /* 0x06 */  XK_5,           XK_percent,	NoSymbol,	NoSymbol,
+    /* 0x07 */  XK_6,           XK_asciicircum,	NoSymbol,	NoSymbol,
+    /* 0x08 */  XK_7,           XK_ampersand,	NoSymbol,	NoSymbol,
+    /* 0x09 */  XK_8,           XK_asterisk,	NoSymbol,	NoSymbol,
+    /* 0x0a */  XK_9,           XK_parenleft,	NoSymbol,	NoSymbol,
+    /* 0x0b */  XK_0,           XK_parenright,	NoSymbol,	NoSymbol,
+    /* 0x0c */  XK_minus,       XK_underscore,	NoSymbol,	NoSymbol,
+    /* 0x0d */  XK_equal,       XK_plus,	NoSymbol,	NoSymbol,
+    /* 0x0e */  XK_BackSpace,   NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x0f */  XK_Tab,         XK_ISO_Left_Tab,NoSymbol,	NoSymbol,
+    /* 0x10 */  XK_Q,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x11 */  XK_W,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x12 */  XK_E,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x13 */  XK_R,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x14 */  XK_T,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x15 */  XK_Y,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x16 */  XK_U,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x17 */  XK_I,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x18 */  XK_O,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x19 */  XK_P,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x1a */  XK_bracketleft, XK_braceleft,	NoSymbol,	NoSymbol,
+    /* 0x1b */  XK_bracketright,XK_braceright,	NoSymbol,	NoSymbol,
+    /* 0x1c */  XK_Return,      NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x1d */  XK_Control_L,   NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x1e */  XK_A,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x1f */  XK_S,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x20 */  XK_D,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x21 */  XK_F,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x22 */  XK_G,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x23 */  XK_H,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x24 */  XK_J,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x25 */  XK_K,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x26 */  XK_L,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x27 */  XK_semicolon,   XK_colon,	NoSymbol,	NoSymbol,
+    /* 0x28 */  XK_quoteright,  XK_quotedbl,	NoSymbol,	NoSymbol,
+    /* 0x29 */  XK_quoteleft,	XK_asciitilde,	NoSymbol,	NoSymbol,
+    /* 0x2a */  XK_Shift_L,     NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x2b */  XK_backslash,   XK_bar,		NoSymbol,	NoSymbol,
+    /* 0x2c */  XK_Z,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x2d */  XK_X,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x2e */  XK_C,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x2f */  XK_V,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x30 */  XK_B,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x31 */  XK_N,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x32 */  XK_M,           NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x33 */  XK_comma,       XK_less,	NoSymbol,	NoSymbol,
+    /* 0x34 */  XK_period,      XK_greater,	NoSymbol,	NoSymbol,
+    /* 0x35 */  XK_slash,       XK_question,	NoSymbol,	NoSymbol,
+    /* 0x36 */  XK_Shift_R,     NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x37 */  XK_KP_Multiply, NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x38 */  XK_Alt_L,	XK_Meta_L,	NoSymbol,	NoSymbol,
+    /* 0x39 */  XK_space,       NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x3a */  XK_Caps_Lock,   NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x3b */  XK_F1,          NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x3c */  XK_F2,          NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x3d */  XK_F3,          NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x3e */  XK_F4,          NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x3f */  XK_F5,          NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x40 */  XK_F6,          NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x41 */  XK_F7,          NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x42 */  XK_F8,          NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x43 */  XK_F9,          NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x44 */  XK_F10,         NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x45 */  XK_Num_Lock,    NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x46 */  XK_Scroll_Lock,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x47 */  XK_KP_Home,	XK_KP_7,	NoSymbol,	NoSymbol,
+    /* 0x48 */  XK_KP_Up,	XK_KP_8,	NoSymbol,	NoSymbol,
+    /* 0x49 */  XK_KP_Prior,	XK_KP_9,	NoSymbol,	NoSymbol,
+    /* 0x4a */  XK_KP_Subtract, NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x4b */  XK_KP_Left,	XK_KP_4,	NoSymbol,	NoSymbol,
+    /* 0x4c */  XK_KP_Begin,	XK_KP_5,	NoSymbol,	NoSymbol,
+    /* 0x4d */  XK_KP_Right,	XK_KP_6,	NoSymbol,	NoSymbol,
+    /* 0x4e */  XK_KP_Add,      NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x4f */  XK_KP_End,	XK_KP_1,	NoSymbol,	NoSymbol,
+    /* 0x50 */  XK_KP_Down,	XK_KP_2,	NoSymbol,	NoSymbol,
+    /* 0x51 */  XK_KP_Next,	XK_KP_3,	NoSymbol,	NoSymbol,
+    /* 0x52 */  XK_KP_Insert,	XK_KP_0,	NoSymbol,	NoSymbol,
+    /* 0x53 */  XK_KP_Delete,	XK_KP_Decimal,	NoSymbol,	NoSymbol,
+    /* 0x54 */  XK_Sys_Req,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x55 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x56 */  XK_less,	XK_greater,	NoSymbol,	NoSymbol,
+    /* 0x57 */  XK_F11,		NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x58 */  XK_F12,		NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x59 */  XK_Home,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x5a */  XK_Up,		NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x5b */  XK_Prior,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x5c */  XK_Left,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x5d */  XK_Begin,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x5e */  XK_Right,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x5f */  XK_End,		NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x60 */  XK_Down,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x61 */  XK_Next,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x62 */  XK_Insert,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x63 */  XK_Delete,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x64 */  XK_KP_Enter,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x65 */  XK_Control_R,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x66 */  XK_Pause,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x67 */  XK_Print,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x68 */  XK_KP_Divide,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x69 */  XK_Alt_R,	XK_Meta_R,	NoSymbol,	NoSymbol,
+    /* 0x6a */  XK_Break,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x6b */  XK_Meta_L,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x6c */  XK_Meta_R,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x6d */  XK_Menu,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x6e */  XK_F13,		NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x6f */  XK_F14,		NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x70 */  XK_F15,		NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x71 */  XK_F16,		NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x72 */  XK_F17,		NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x73 */  XK_backslash,	XK_underscore,	NoSymbol,	NoSymbol,
+    /* 0x74 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x75 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x76 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x77 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x78 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x79 */  XK_Henkan,	XK_Mode_switch,	NoSymbol,	NoSymbol,
+    /* 0x7a */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x7b */  XK_Muhenkan,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x7c */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x7d */  XK_backslash,	XK_bar,		NoSymbol,	NoSymbol,
+    /* 0x7e */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+    /* 0x7f */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+};
diff --git a/hw/xwin/winkeynames.h b/hw/xwin/winkeynames.h
new file mode 100644
index 0000000..7c16337
--- /dev/null
+++ b/hw/xwin/winkeynames.h
@@ -0,0 +1,202 @@
+#ifndef _WINKEYNAMES_H
+#define _WINKEYNAMES_H
+/*
+ * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and its
+ * documentation for any purpose is hereby granted without fee, provided that
+ * the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of Thomas Roell not be used in
+ * advertising or publicity pertaining to distribution of the software without
+ * specific, written prior permission.  Thomas Roell makes no representations
+ * about the suitability of this software for any purpose.  It is provided
+ * "as is" without express or implied warranty.
+ *
+ * THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL THOMAS ROELL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+ * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ *
+ */
+
+#define XK_TECHNICAL
+#define	XK_KATAKANA
+#include <X11/keysym.h>
+
+#define GLYPHS_PER_KEY	4
+#define NUM_KEYCODES	248
+#define MIN_KEYCODE     8
+#define MAX_KEYCODE     (NUM_KEYCODES + MIN_KEYCODE - 1)
+
+#define AltMask		Mod1Mask
+#define NumLockMask	Mod2Mask
+#define AltLangMask	Mod3Mask
+#define KanaMask	Mod4Mask
+#define ScrollLockMask	Mod5Mask
+
+#define KeyPressed(k) (keyc->down[k >> 3] & (1 << (k & 7)))
+#define ModifierDown(k) ((keyc->state & (k)) == (k))
+
+/*
+ * NOTE: The AT/MF keyboards can generate (via the 8042) two (MF: three)
+ *       sets of scancodes. Set3 can only be generated by a MF keyboard.
+ *       Set2 sends a makecode for keypress, and the same code prefixed by a
+ *       F0 for keyrelease. This is a little bit ugly to handle. Thus we use
+ *       here for X386 the PC/XT compatible Set1. This set uses 8bit scancodes.
+ *       Bit 7 ist set if the key is released. The code E0 switches to a
+ *       different meaning to add the new MF cursorkeys, while not breaking old
+ *       applications. E1 is another special prefix. Since I assume that there
+ *       will be further versions of PC/XT scancode compatible keyboards, we
+ *       may be in trouble one day.
+ *
+ * IDEA: 1) Use Set2 on AT84 keyboards and translate it to MF Set3.
+ *       2) Use the keyboards native set and translate it to common keysyms.
+ */
+
+/*
+ * definition of the AT84/MF101/MF102 Keyboard:
+ * ============================================================
+ *       Defined             Key Cap Glyphs       Pressed value
+ *      Key Name            Main       Also       (hex)    (dec)
+ *      ----------------   ---------- -------    ------    ------
+ */
+
+#define KEY_Escape       /* Escape                0x01  */    1  
+#define KEY_1            /* 1           !         0x02  */    2 
+#define KEY_2            /* 2           @         0x03  */    3 
+#define KEY_3            /* 3           #         0x04  */    4 
+#define KEY_4            /* 4           $         0x05  */    5 
+#define KEY_5            /* 5           %         0x06  */    6 
+#define KEY_6            /* 6           ^         0x07  */    7 
+#define KEY_7            /* 7           &         0x08  */    8 
+#define KEY_8            /* 8           *         0x09  */    9 
+#define KEY_9            /* 9           (         0x0a  */   10 
+#define KEY_0            /* 0           )         0x0b  */   11 
+#define KEY_Minus        /* - (Minus)   _ (Under) 0x0c  */   12
+#define KEY_Equal        /* = (Equal)   +         0x0d  */   13 
+#define KEY_BackSpace    /* Back Space            0x0e  */   14 
+#define KEY_Tab          /* Tab                   0x0f  */   15
+#define KEY_Q            /* Q                     0x10  */   16
+#define KEY_W            /* W                     0x11  */   17
+#define KEY_E            /* E                     0x12  */   18
+#define KEY_R            /* R                     0x13  */   19
+#define KEY_T            /* T                     0x14  */   20
+#define KEY_Y            /* Y                     0x15  */   21
+#define KEY_U            /* U                     0x16  */   22
+#define KEY_I            /* I                     0x17  */   23
+#define KEY_O            /* O                     0x18  */   24
+#define KEY_P            /* P                     0x19  */   25
+#define KEY_LBrace       /* [           {         0x1a  */   26
+#define KEY_RBrace       /* ]           }         0x1b  */   27 
+#define KEY_Enter        /* Enter                 0x1c  */   28
+#define KEY_LCtrl        /* Ctrl(left)            0x1d  */   29
+#define KEY_A            /* A                     0x1e  */   30
+#define KEY_S            /* S                     0x1f  */   31
+#define KEY_D            /* D                     0x20  */   32 
+#define KEY_F            /* F                     0x21  */   33
+#define KEY_G            /* G                     0x22  */   34
+#define KEY_H            /* H                     0x23  */   35
+#define KEY_J            /* J                     0x24  */   36
+#define KEY_K            /* K                     0x25  */   37
+#define KEY_L            /* L                     0x26  */   38
+#define KEY_SemiColon    /* ;(SemiColon) :(Colon) 0x27  */   39
+#define KEY_Quote        /* ' (Apostr)  " (Quote) 0x28  */   40
+#define KEY_Tilde        /* ` (Accent)  ~ (Tilde) 0x29  */   41
+#define KEY_ShiftL       /* Shift(left)           0x2a  */   42
+#define KEY_BSlash       /* \(BckSlash) |(VertBar)0x2b  */   43
+#define KEY_Z            /* Z                     0x2c  */   44
+#define KEY_X            /* X                     0x2d  */   45
+#define KEY_C            /* C                     0x2e  */   46
+#define KEY_V            /* V                     0x2f  */   47
+#define KEY_B            /* B                     0x30  */   48
+#define KEY_N            /* N                     0x31  */   49
+#define KEY_M            /* M                     0x32  */   50
+#define KEY_Comma        /* , (Comma)   < (Less)  0x33  */   51
+#define KEY_Period       /* . (Period)  >(Greater)0x34  */   52
+#define KEY_Slash        /* / (Slash)   ?         0x35  */   53
+#define KEY_ShiftR       /* Shift(right)          0x36  */   54
+#define KEY_KP_Multiply  /* *                     0x37  */   55
+#define KEY_Alt          /* Alt(left)             0x38  */   56
+#define KEY_Space        /*   (SpaceBar)          0x39  */   57
+#define KEY_CapsLock     /* CapsLock              0x3a  */   58
+#define KEY_F1           /* F1                    0x3b  */   59
+#define KEY_F2           /* F2                    0x3c  */   60
+#define KEY_F3           /* F3                    0x3d  */   61
+#define KEY_F4           /* F4                    0x3e  */   62
+#define KEY_F5           /* F5                    0x3f  */   63
+#define KEY_F6           /* F6                    0x40  */   64
+#define KEY_F7           /* F7                    0x41  */   65
+#define KEY_F8           /* F8                    0x42  */   66
+#define KEY_F9           /* F9                    0x43  */   67
+#define KEY_F10          /* F10                   0x44  */   68
+#define KEY_NumLock      /* NumLock               0x45  */   69
+#define KEY_ScrollLock   /* ScrollLock            0x46  */   70
+#define KEY_KP_7         /* 7           Home      0x47  */   71 
+#define KEY_KP_8         /* 8           Up        0x48  */   72 
+#define KEY_KP_9         /* 9           PgUp      0x49  */   73 
+#define KEY_KP_Minus     /* - (Minus)             0x4a  */   74
+#define KEY_KP_4         /* 4           Left      0x4b  */   75
+#define KEY_KP_5         /* 5                     0x4c  */   76
+#define KEY_KP_6         /* 6           Right     0x4d  */   77
+#define KEY_KP_Plus      /* + (Plus)              0x4e  */   78
+#define KEY_KP_1         /* 1           End       0x4f  */   79
+#define KEY_KP_2         /* 2           Down      0x50  */   80
+#define KEY_KP_3         /* 3           PgDown    0x51  */   81
+#define KEY_KP_0         /* 0           Insert    0x52  */   82
+#define KEY_KP_Decimal   /* . (Decimal) Delete    0x53  */   83 
+#define KEY_SysReqest    /* SysReqest             0x54  */   84
+                         /* NOTUSED               0x55  */
+#define KEY_Less         /* < (Less)   >(Greater) 0x56  */   86
+#define KEY_F11          /* F11                   0x57  */   87
+#define KEY_F12          /* F12                   0x58  */   88
+
+#define KEY_Prefix0      /* special               0x60  */   96
+#define KEY_Prefix1      /* specail               0x61  */   97
+
+/*
+ * The 'scancodes' below are generated by the server, because the MF101/102
+ * keyboard sends them as sequence of other scancodes
+ */
+#define KEY_Home         /* Home                  0x59  */   89
+#define KEY_Up           /* Up                    0x5a  */   90
+#define KEY_PgUp         /* PgUp                  0x5b  */   91
+#define KEY_Left         /* Left                  0x5c  */   92
+#define KEY_Begin        /* Begin                 0x5d  */   93
+#define KEY_Right        /* Right                 0x5e  */   94
+#define KEY_End          /* End                   0x5f  */   95
+#define KEY_Down         /* Down                  0x60  */   96
+#define KEY_PgDown       /* PgDown                0x61  */   97
+#define KEY_Insert       /* Insert                0x62  */   98
+#define KEY_Delete       /* Delete                0x63  */   99
+#define KEY_KP_Enter     /* Enter                 0x64  */  100
+#define KEY_RCtrl        /* Ctrl(right)           0x65  */  101
+#define KEY_Pause        /* Pause                 0x66  */  102
+#define KEY_Print        /* Print                 0x67  */  103
+#define KEY_KP_Divide    /* Divide                0x68  */  104
+#define KEY_AltLang      /* AtlLang(right)        0x69  */  105
+#define KEY_Break        /* Break                 0x6a  */  106
+#define KEY_LMeta        /* Left Meta             0x6b  */  107
+#define KEY_RMeta        /* Right Meta            0x6c  */  108
+#define KEY_Menu         /* Menu                  0x6d  */  109
+#define KEY_F13          /* F13                   0x6e  */  110
+#define KEY_F14          /* F14                   0x6f  */  111
+#define KEY_F15          /* F15                   0x70  */  112
+#define KEY_F16          /* F16                   0x71  */  113
+#define KEY_F17          /* F17                   0x72  */  114
+#define KEY_KP_DEC       /* KP_DEC                0x73  */  115
+#define KEY_KP_Equal	 /* Equal (Keypad)        0x76  */  118
+#define KEY_XFER         /* Kanji Transfer        0x79  */  121
+#define KEY_NFER         /* No Kanji Transfer     0x7b  */  123
+#define KEY_Yen          /* Yen                   0x7d  */  125
+#define KEY_HKTG         /* Hirugana/Katakana tog 0xc8  */  200
+#define KEY_BSlash2      /* \           _         0xcb  */  203
+
+/* These are for "notused" and "unknown" entries in translation maps. */
+#define KEY_NOTUSED	  0
+#define KEY_UNKNOWN	255
+
+#endif /* _WINKEYNAMES_H */
diff --git a/hw/xwin/winlayouts.h b/hw/xwin/winlayouts.h
new file mode 100644
index 0000000..cc07524
--- /dev/null
+++ b/hw/xwin/winlayouts.h
@@ -0,0 +1,257 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+/* Definitions for various keyboard layouts from windows and their 
+ * XKB settings.
+ */
+
+typedef struct 
+{
+    unsigned int winlayout;
+    int winkbtype;
+    char *xkbmodel;
+    char *xkblayout;
+    char *xkbvariant;
+    char *xkboptions;
+    char *layoutname;
+} WinKBLayoutRec, *WinKBLayoutPtr;
+
+WinKBLayoutRec winKBLayouts[] = 
+{
+    {  0x405, -1, "pc105", "cz",      NULL, NULL, "Czech"},
+    {0x10405, -1, "pc105", "cz_qwerty", NULL, NULL, "Czech (QWERTY)"},
+    {  0x406, -1, "pc105", "dk",      NULL, NULL, "Danish"},
+    {  0x407, -1, "pc105", "de",      NULL, NULL, "German (Germany)"},
+    {0x10407, -1, "pc105", "de",      NULL, NULL, "German (Germany, IBM)"},
+    {  0x807, -1, "pc105", "de_CH",   NULL, NULL, "German (Switzerland)"},
+    {  0x409, -1, "pc105", "us",      NULL, NULL, "English (USA)"},
+    {0x10409, -1, "pc105", "dvorak",  NULL, NULL, "English (USA, Dvorak)"}, 
+    {0x20409, -1, "pc105", "us_intl", NULL, NULL, "English (USA, International)"}, 
+    {  0x809, -1, "pc105", "gb",      NULL, NULL, "English (United Kingdom)"},
+    { 0x1809, -1, "pc105", "ie",      NULL, NULL, "Irish"},
+    {  0x40a, -1, "pc105", "es",      NULL, NULL, "Spanish (Spain, Traditional Sort)"},
+    {  0x40b, -1, "pc105", "fi",      NULL, NULL, "Finnish"},
+    {  0x40c, -1, "pc105", "fr",      NULL, NULL, "French (Standard)"},
+    {  0x80c, -1, "pc105", "be",      NULL, NULL, "French (Belgian)"},
+    {  0xc0c, -1, "pc105", "ca_enhanced", NULL, NULL, "French (Canada)"},
+    { 0x100c, -1, "pc105", "fr_CH",   NULL, NULL, "French (Switzerland)"},
+    {  0x40e, -1, "pc105", "hu",      NULL, NULL, "Hungarian"},
+    {  0x410, -1, "pc105", "it",      NULL, NULL, "Italian"},
+    {  0x411,  7, "jp106", "jp",      NULL, NULL, "Japanese"},
+    {  0x813, -1, "pc105", "be",      NULL, NULL, "Dutch (Belgian)"},  
+    {  0x414, -1, "pc105", "no",      NULL, NULL, "Norwegian"},
+    {  0x416, -1, "pc105", "br",      NULL, NULL, "Portuguese (Brazil, ABNT)"},
+    {0x10416, -1, "abnt2", "br",      NULL, NULL, "Portuguese (Brazil, ABNT2)"},
+    {  0x816, -1, "pc105", "pt",      NULL, NULL, "Portuguese (Portugal)"},
+    {  0x41d, -1, "pc105", "se",      NULL, NULL, "Swedish (Sweden)"},
+    {     -1, -1, NULL,    NULL,      NULL, NULL, NULL}
+};
+
+/* Listing of language codes from MSDN */
+/*
+Support ID       XKB        Language
+====================================================================
+   ?    0x0000              Language Neutral
+   ?    0x0400              Process or User Default Language
+   ?    0x0800              System Default Language
+        0x0401              Arabic (Saudi Arabia)
+        0x0801              Arabic (Iraq)
+        0x0c01              Arabic (Egypt)
+        0x1001              Arabic (Libya)
+        0x1401              Arabic (Algeria)
+        0x1801              Arabic (Morocco)
+        0x1c01              Arabic (Tunisia)
+        0x2001              Arabic (Oman)
+        0x2401              Arabic (Yemen)
+        0x2801              Arabic (Syria)
+        0x2c01              Arabic (Jordan)
+        0x3001              Arabic (Lebanon)
+        0x3401              Arabic (Kuwait)
+        0x3801              Arabic (U.A.E.)
+        0x3c01              Arabic (Bahrain)
+        0x4001              Arabic (Qatar)
+                            Arabic (102) AZERTY        				
+        0x0402              Bulgarian
+        0x0403              Catalan
+        0x0404              Chinese (Taiwan)
+        0x0804              Chinese (PRC)
+        0x0c04              Chinese (Hong Kong SAR, PRC)
+        0x1004              Chinese (Singapore)
+        0x1404              Chinese (Macao SAR) (98/ME,2K/XP)
+   X    0x0405  cz          Czech
+   X            cz_qwerty   Czech (QWERTY)
+                            Czech (Programmers)
+   X    0x0406  dk          Danish
+   X    0x0407  de          German (Standard)
+   X    0x0807  de_CH       German (Switzerland)
+        0x0c07              German (Austria)
+        0x1007              German (Luxembourg)
+        0x1407              German (Liechtenstein)
+        0x0408              Greek
+   X    0x0409  us          English (United States)
+   X    0x0809  gb          English (United Kingdom)
+        0x0c09              English (Australian)
+        0x1009              English (Canadian)
+        0x1409              English (New Zealand)
+   X    0x1809  ie          English (Ireland)
+        0x1c09              English (South Africa)
+        0x2009              English (Jamaica)
+        0x2409              English (Caribbean)
+        0x2809              English (Belize)
+        0x2c09              English (Trinidad)
+        0x3009              English (Zimbabwe) (98/ME,2K/XP)
+        0x3409              English (Philippines) (98/ME,2K/XP)
+   X    0x040a  es          Spanish (Spain, Traditional Sort)
+        0x080a              Spanish (Mexican)
+        0x0c0a              Spanish (Spain, Modern Sort)
+        0x100a              Spanish (Guatemala)
+        0x140a              Spanish (Costa Rica)
+        0x180a              Spanish (Panama)
+        0x1c0a              Spanish (Dominican Republic)
+        0x200a              Spanish (Venezuela)
+        0x240a              Spanish (Colombia)
+        0x280a              Spanish (Peru)
+        0x2c0a              Spanish (Argentina)
+        0x300a              Spanish (Ecuador)
+        0x340a              Spanish (Chile)
+        0x380a              Spanish (Uruguay)
+        0x3c0a              Spanish (Paraguay)
+        0x400a              Spanish (Bolivia)
+        0x440a              Spanish (El Salvador)
+        0x480a              Spanish (Honduras)
+        0x4c0a              Spanish (Nicaragua)
+        0x500a              Spanish (Puerto Rico)
+   X    0x040b  fi          Finnish
+                            Finnish (with Sami)
+   X    0x040c  fr          French (Standard)
+   X    0x080c  be          French (Belgian)
+   .    0x0c0c              French (Canadian)
+                            French (Canadian, Legacy)
+                            Canadian (Multilingual)
+   X    0x100c  fr_CH       French (Switzerland)
+        0x140c              French (Luxembourg)
+        0x180c              French (Monaco) (98/ME,2K/XP)
+        0x040d              Hebrew
+   X    0x040e  hu          Hungarian
+   .    0x040f              Icelandic
+   X    0x0410  it          Italian (Standard)
+        0x0810              Italian (Switzerland)
+   X    0x0411  jp          Japanese
+        0x0412              Korean
+        0x0812              Korean (Johab) (95,NT)
+   .    0x0413              Dutch (Netherlands)
+   X    0x0813  be          Dutch (Belgium)
+   X    0x0414  no          Norwegian (Bokmal)
+        0x0814              Norwegian (Nynorsk)
+   .    0x0415              Polish
+   X    0x0416  br          Portuguese (Brazil)
+   X    0x0816  pt          Portuguese (Portugal)
+   .    0x0418              Romanian
+        0x0419              Russian
+   .    0x041a              Croatian
+   .    0x081a              Serbian (Latin)
+   .    0x0c1a              Serbian (Cyrillic)
+        0x101a              Croatian (Bosnia and Herzegovina)
+        0x141a              Bosnian (Bosnia and Herzegovina)
+        0x181a              Serbian (Latin, Bosnia, and Herzegovina)
+        0x1c1a              Serbian (Cyrillic, Bosnia, and Herzegovina)
+   .    0x041b              Slovak
+   .    0x041c              Albanian
+   X    0x041d  se          Swedish
+        0x081d              Swedish (Finland)
+        0x041e              Thai
+        0x041f              Turkish
+        0x0420              Urdu (Pakistan) (98/ME,2K/XP) 
+        0x0820              Urdu (India)
+        0x0421              Indonesian
+        0x0422              Ukrainian
+        0x0423              Belarusian
+   .    0x0424              Slovenian
+        0x0425              Estonian
+        0x0426              Latvian
+        0x0427              Lithuanian
+        0x0827              Lithuanian (Classic) (98)
+        0x0429              Farsi
+        0x042a              Vietnamese (98/ME,NT,2K/XP)
+        0x042b              Armenian. This is Unicode only. (2K/XP)
+                            Armenian Eastern
+                            Armenian Western
+        0x042c              Azeri (Latin)
+        0x082c              Azeri (Cyrillic)
+        0x042d              Basque
+        0x042f              Macedonian (FYROM)
+        0x0430              Sutu
+        0x0432              Setswana/Tswana (South Africa)
+        0x0434              isiXhosa/Xhosa (South Africa)
+        0x0435              isiZulu/Zulu (South Africa)
+        0x0436              Afrikaans
+        0x0437              Georgian. This is Unicode only. (2K/XP)
+   .    0x0438              Faeroese
+        0x0439              Hindi. This is Unicode only. (2K/XP)
+        0x043a              Maltese (Malta)
+        0x043b              Sami, Northern (Norway)
+        0x083b              Sami, Northern (Sweden)
+        0x0c3b              Sami, Northern (Finland)
+        0x103b              Sami, Lule (Norway)
+        0x143b              Sami, Lule (Sweden)
+        0x183b              Sami, Southern (Norway)
+        0x1c3b              Sami, Southern (Sweden)
+        0x203b              Sami, Skolt (Finland)
+        0x243b              Sami, Inari (Finland)
+        0x043e              Malay (Malaysian)
+        0x083e              Malay (Brunei Darussalam)
+        0x0440              Kyrgyz. (XP)
+        0x0441              Swahili (Kenya)
+        0x0443              Uzbek (Latin)
+        0x0843              Uzbek (Cyrillic)
+        0x0444              Tatar (Tatarstan)
+        0x0445              Bengali (India)
+                            Bengali (Inscript)
+        0x0446              Punjabi. This is Unicode only. (XP)
+        0x0447              Gujarati. This is Unicode only. (XP)
+        0x0449              Tamil. This is Unicode only. (2K/XP)
+        0x044a              Telugu. This is Unicode only. (XP)
+        0x044b              Kannada. This is Unicode only. (XP)
+        0x044c              Malayalam (India)
+        0x044e              Marathi. This is Unicode only. (2K/XP)
+        0x044f              Sanskrit. This is Unicode only. (2K/XP)
+        0x0450              Mongolian (XP)
+        0x0452              Welsh (United Kingdom)
+        0x0455              Burmese
+        0x0456              Galician (XP)
+        0x0457              Konkani. This is Unicode only. (2K/XP)
+        0x045a              Syriac. This is Unicode only. (XP)
+        0x0465              Divehi. This is Unicode only. (XP)
+                            Divehi (Phonetic)
+                            Divehi (Typewriter)
+        0x046b              Quechua (Bolivia)
+        0x086b              Quechua (Ecuador)
+        0x0c6b              Quechua (Peru)
+        0x046c              Sesotho sa Leboa/Northern Sotho (South Africa)
+        0x007f              LOCALE_INVARIANT. See MAKELCID.
+        0x0481              Maori (New Zealand)
+*/    
+
+
diff --git a/hw/xwin/winmessages.h b/hw/xwin/winmessages.h
new file mode 100755
index 0000000..ae50dc4
--- /dev/null
+++ b/hw/xwin/winmessages.h
@@ -0,0 +1,1030 @@
+#ifndef __WINMESSAGES_H__
+#define __WINMESSAGES_H__
+static const unsigned MESSAGE_NAMES_LEN =1024;
+static const char *MESSAGE_NAMES[1024] = {
+	"WM_NULL",
+	"WM_CREATE",
+	"WM_DESTROY",
+	"WM_MOVE",
+	"4",
+	"WM_SIZE",
+	"WM_ACTIVATE",
+	"WM_SETFOCUS",
+	"WM_KILLFOCUS",
+	"9",
+	"WM_ENABLE",
+	"WM_SETREDRAW",
+	"WM_SETTEXT",
+	"WM_GETTEXT",
+	"WM_GETTEXTLENGTH",
+	"WM_PAINT",
+	"WM_CLOSE",
+	"WM_QUERYENDSESSION",
+	"WM_QUIT",
+	"WM_QUERYOPEN",
+	"WM_ERASEBKGND",
+	"WM_SYSCOLORCHANGE",
+	"WM_ENDSESSION",
+	"23",
+	"WM_SHOWWINDOW",
+	"25",
+	"WM_WININICHANGE",
+	"WM_DEVMODECHANGE",
+	"WM_ACTIVATEAPP",
+	"WM_FONTCHANGE",
+	"WM_TIMECHANGE",
+	"WM_CANCELMODE",
+	NULL /* WM_SETCURSOR */,
+	"WM_MOUSEACTIVATE",
+	"WM_CHILDACTIVATE",
+	"WM_QUEUESYNC",
+	"WM_GETMINMAXINFO",
+	"37",
+	"WM_PAINTICON",
+	"WM_ICONERASEBKGND",
+	"WM_NEXTDLGCTL",
+	"41",
+	"WM_SPOOLERSTATUS",
+	"WM_DRAWITEM",
+	"WM_MEASUREITEM",
+	"WM_DELETEITEM",
+	"WM_VKEYTOITEM",
+	"WM_CHARTOITEM",
+	"WM_SETFONT",
+	"WM_GETFONT",
+	"WM_SETHOTKEY",
+	"WM_GETHOTKEY",
+	"52",
+	"53",
+	"54",
+	"WM_QUERYDRAGICON",
+	"56",
+	"WM_COMPAREITEM",
+	"58",
+	"59",
+	"60",
+	"61",
+	"62",
+	"63",
+	"64",
+	"WM_COMPACTING",
+	"66",
+	"67",
+	"WM_COMMNOTIFY",
+	"69",
+	"WM_WINDOWPOSCHANGING",
+	"WM_WINDOWPOSCHANGED",
+	"WM_POWER",
+	"73",
+	"WM_COPYDATA",
+	"WM_CANCELJOURNAL",
+	"76",
+	"77",
+	"WM_NOTIFY",
+	"79",
+	"WM_INPUTLANGCHANGEREQUEST",
+	"WM_INPUTLANGCHANGE",
+	"WM_TCARD",
+	"WM_HELP",
+	"WM_USERCHANGED",
+	"WM_NOTIFYFORMAT",
+	"86",
+	"87",
+	"88",
+	"89",
+	"90",
+	"91",
+	"92",
+	"93",
+	"94",
+	"95",
+	"96",
+	"97",
+	"98",
+	"99",
+	"100",
+	"101",
+	"102",
+	"103",
+	"104",
+	"105",
+	"106",
+	"107",
+	"108",
+	"109",
+	"110",
+	"111",
+	"112",
+	"113",
+	"114",
+	"115",
+	"116",
+	"117",
+	"118",
+	"119",
+	"120",
+	"121",
+	"122",
+	"WM_CONTEXTMENU",
+	"WM_STYLECHANGING",
+	"WM_STYLECHANGED",
+	"WM_DISPLAYCHANGE",
+	"WM_GETICON",
+	"WM_SETICON",
+	"WM_NCCREATE",
+	"WM_NCDESTROY",
+	"WM_NCCALCSIZE",
+	NULL /* WM_NCHITTEST */,
+	"WM_NCPAINT",
+	"WM_NCACTIVATE",
+	"WM_GETDLGCODE",
+	"WM_SYNCPAINT",
+	"137",
+	"138",
+	"139",
+	"140",
+	"141",
+	"142",
+	"143",
+	"144",
+	"145",
+	"146",
+	"147",
+	"148",
+	"149",
+	"150",
+	"151",
+	"152",
+	"153",
+	"154",
+	"155",
+	"156",
+	"157",
+	"158",
+	"159",
+	NULL /* WM_NCMOUSEMOVE */,
+	"WM_NCLBUTTONDOWN",
+	"WM_NCLBUTTONUP",
+	"WM_NCLBUTTONDBLCLK",
+	"WM_NCRBUTTONDOWN",
+	"WM_NCRBUTTONUP",
+	"WM_NCRBUTTONDBLCLK",
+	"WM_NCMBUTTONDOWN",
+	"WM_NCMBUTTONUP",
+	"WM_NCMBUTTONDBLCLK",
+	"170",
+	"171",
+	"172",
+	"173",
+	"174",
+	"175",
+	"176",
+	"177",
+	"178",
+	"179",
+	"180",
+	"181",
+	"182",
+	"183",
+	"184",
+	"185",
+	"186",
+	"187",
+	"188",
+	"189",
+	"190",
+	"191",
+	"192",
+	"193",
+	"194",
+	"195",
+	"196",
+	"197",
+	"198",
+	"199",
+	"200",
+	"201",
+	"202",
+	"203",
+	"204",
+	"205",
+	"206",
+	"207",
+	"208",
+	"209",
+	"210",
+	"211",
+	"212",
+	"213",
+	"214",
+	"215",
+	"216",
+	"217",
+	"218",
+	"219",
+	"220",
+	"221",
+	"222",
+	"223",
+	"224",
+	"225",
+	"226",
+	"227",
+	"228",
+	"229",
+	"230",
+	"231",
+	"232",
+	"233",
+	"234",
+	"235",
+	"236",
+	"237",
+	"238",
+	"239",
+	"240",
+	"241",
+	"242",
+	"243",
+	"244",
+	"245",
+	"246",
+	"247",
+	"248",
+	"249",
+	"250",
+	"251",
+	"252",
+	"253",
+	"254",
+	"255",
+	"WM_KEYDOWN",
+	"WM_KEYUP",
+	"WM_CHAR",
+	"WM_DEADCHAR",
+	"WM_SYSKEYDOWN",
+	"WM_SYSKEYUP",
+	"WM_SYSCHAR",
+	"WM_SYSDEADCHAR",
+	"WM_CONVERTREQUESTEX",
+	"265",
+	"266",
+	"267",
+	"268",
+	"WM_IME_STARTCOMPOSITION",
+	"WM_IME_ENDCOMPOSITION",
+	"WM_IME_KEYLAST",
+	"WM_INITDIALOG",
+	"WM_COMMAND",
+	"WM_SYSCOMMAND",
+	NULL /* WM_TIMER */,
+	"WM_HSCROLL",
+	"WM_VSCROLL",
+	"WM_INITMENU",
+	"WM_INITMENUPOPUP",
+	"280",
+	"281",
+	"282",
+	"283",
+	"284",
+	"285",
+	"286",
+	"WM_MENUSELECT",
+	"WM_MENUCHAR",
+	"WM_ENTERIDLE",
+	"290",
+	"291",
+	"292",
+	"293",
+	"294",
+	"295",
+	"296",
+	"297",
+	"298",
+	"299",
+	"300",
+	"301",
+	"302",
+	"303",
+	"304",
+	"305",
+	"WM_CTLCOLORMSGBOX",
+	"WM_CTLCOLOREDIT",
+	"WM_CTLCOLORLISTBOX",
+	"WM_CTLCOLORBTN",
+	"WM_CTLCOLORDLG",
+	"WM_CTLCOLORSCROLLBAR",
+	"WM_CTLCOLORSTATIC",
+	"313",
+	"314",
+	"315",
+	"316",
+	"317",
+	"318",
+	"319",
+	"320",
+	"321",
+	"322",
+	"323",
+	"324",
+	"325",
+	"326",
+	"327",
+	"328",
+	"329",
+	"330",
+	"331",
+	"332",
+	"333",
+	"334",
+	"335",
+	"336",
+	"337",
+	"338",
+	"339",
+	"340",
+	"341",
+	"342",
+	"343",
+	"344",
+	"345",
+	"346",
+	"347",
+	"348",
+	"349",
+	"350",
+	"351",
+	"352",
+	"353",
+	"354",
+	"355",
+	"356",
+	"357",
+	"358",
+	"359",
+	"360",
+	"361",
+	"362",
+	"363",
+	"364",
+	"365",
+	"366",
+	"367",
+	"368",
+	"369",
+	"370",
+	"371",
+	"372",
+	"373",
+	"374",
+	"375",
+	"376",
+	"377",
+	"378",
+	"379",
+	"380",
+	"381",
+	"382",
+	"383",
+	"384",
+	"385",
+	"386",
+	"387",
+	"388",
+	"389",
+	"390",
+	"391",
+	"392",
+	"393",
+	"394",
+	"395",
+	"396",
+	"397",
+	"398",
+	"399",
+	"400",
+	"401",
+	"402",
+	"403",
+	"404",
+	"405",
+	"406",
+	"407",
+	"408",
+	"409",
+	"410",
+	"411",
+	"412",
+	"413",
+	"414",
+	"415",
+	"416",
+	"417",
+	"418",
+	"419",
+	"420",
+	"421",
+	"422",
+	"423",
+	"424",
+	"425",
+	"426",
+	"427",
+	"428",
+	"429",
+	"430",
+	"431",
+	"432",
+	"433",
+	"434",
+	"435",
+	"436",
+	"437",
+	"438",
+	"439",
+	"440",
+	"441",
+	"442",
+	"443",
+	"444",
+	"445",
+	"446",
+	"447",
+	"448",
+	"449",
+	"450",
+	"451",
+	"452",
+	"453",
+	"454",
+	"455",
+	"456",
+	"457",
+	"458",
+	"459",
+	"460",
+	"461",
+	"462",
+	"463",
+	"464",
+	"465",
+	"466",
+	"467",
+	"468",
+	"469",
+	"470",
+	"471",
+	"472",
+	"473",
+	"474",
+	"475",
+	"476",
+	"477",
+	"478",
+	"479",
+	"480",
+	"481",
+	"482",
+	"483",
+	"484",
+	"485",
+	"486",
+	"487",
+	"488",
+	"489",
+	"490",
+	"491",
+	"492",
+	"493",
+	"494",
+	"495",
+	"496",
+	"497",
+	"498",
+	"499",
+	"500",
+	"501",
+	"502",
+	"503",
+	"504",
+	"505",
+	"506",
+	"507",
+	"508",
+	"509",
+	"510",
+	"511",
+	NULL /* WM_MOUSEMOVE */,
+	"WM_LBUTTONDOWN",
+	"WM_LBUTTONUP",
+	"WM_LBUTTONDBLCLK",
+	"WM_RBUTTONDOWN",
+	"WM_RBUTTONUP",
+	"WM_RBUTTONDBLCLK",
+	"WM_MBUTTONDOWN",
+	"WM_MBUTTONUP",
+	"WM_MBUTTONDBLCLK",
+	"WM_MOUSEWHEEL",
+	"WM_XBUTTONDOWN",
+	"WM_XBUTTONUP",
+	"WM_XBUTTONDBLCLK",
+	"526",
+	"527",
+	"WM_PARENTNOTIFY",
+	"WM_ENTERMENULOOP",
+	"WM_EXITMENULOOP",
+	"WM_NEXTMENU",
+	"WM_SIZING",
+	"WM_CAPTURECHANGED",
+	"WM_MOVING",
+	"535",
+	"WM_POWERBROADCAST",
+	"WM_DEVICECHANGE",
+	"538",
+	"539",
+	"540",
+	"541",
+	"542",
+	"543",
+	"WM_MDICREATE",
+	"WM_MDIDESTROY",
+	"WM_MDIACTIVATE",
+	"WM_MDIRESTORE",
+	"WM_MDINEXT",
+	"WM_MDIMAXIMIZE",
+	"WM_MDITILE",
+	"WM_MDICASCADE",
+	"WM_MDIICONARRANGE",
+	"WM_MDIGETACTIVE",
+	"554",
+	"555",
+	"556",
+	"557",
+	"558",
+	"559",
+	"WM_MDISETMENU",
+	"WM_ENTERSIZEMOVE",
+	"WM_EXITSIZEMOVE",
+	"WM_DROPFILES",
+	"WM_MDIREFRESHMENU",
+	"565",
+	"566",
+	"567",
+	"568",
+	"569",
+	"570",
+	"571",
+	"572",
+	"573",
+	"574",
+	"575",
+	"576",
+	"577",
+	"578",
+	"579",
+	"580",
+	"581",
+	"582",
+	"583",
+	"584",
+	"585",
+	"586",
+	"587",
+	"588",
+	"589",
+	"590",
+	"591",
+	"592",
+	"593",
+	"594",
+	"595",
+	"596",
+	"597",
+	"598",
+	"599",
+	"600",
+	"601",
+	"602",
+	"603",
+	"604",
+	"605",
+	"606",
+	"607",
+	"608",
+	"609",
+	"610",
+	"611",
+	"612",
+	"613",
+	"614",
+	"615",
+	"616",
+	"617",
+	"618",
+	"619",
+	"620",
+	"621",
+	"622",
+	"623",
+	"624",
+	"625",
+	"626",
+	"627",
+	"628",
+	"629",
+	"630",
+	"631",
+	"632",
+	"633",
+	"634",
+	"635",
+	"636",
+	"637",
+	"638",
+	"639",
+	"640",
+	"WM_IME_SETCONTEXT",
+	"WM_IME_NOTIFY",
+	"WM_IME_CONTROL",
+	"WM_IME_COMPOSITIONFULL",
+	"WM_IME_SELECT",
+	"WM_IME_CHAR",
+	"647",
+	"648",
+	"649",
+	"650",
+	"651",
+	"652",
+	"653",
+	"654",
+	"655",
+	"WM_IME_KEYDOWN",
+	"WM_IME_KEYUP",
+	"658",
+	"659",
+	"660",
+	"661",
+	"662",
+	"663",
+	"664",
+	"665",
+	"666",
+	"667",
+	"668",
+	"669",
+	"670",
+	"671",
+	"672",
+	"WM_MOUSEHOVER",
+	"674",
+	"WM_MOUSELEAVE",
+	"676",
+	"677",
+	"678",
+	"679",
+	"680",
+	"681",
+	"682",
+	"683",
+	"684",
+	"685",
+	"686",
+	"687",
+	"688",
+	"689",
+	"690",
+	"691",
+	"692",
+	"693",
+	"694",
+	"695",
+	"696",
+	"697",
+	"698",
+	"699",
+	"700",
+	"701",
+	"702",
+	"703",
+	"704",
+	"705",
+	"706",
+	"707",
+	"708",
+	"709",
+	"710",
+	"711",
+	"712",
+	"713",
+	"714",
+	"715",
+	"716",
+	"717",
+	"718",
+	"719",
+	"720",
+	"721",
+	"722",
+	"723",
+	"724",
+	"725",
+	"726",
+	"727",
+	"728",
+	"729",
+	"730",
+	"731",
+	"732",
+	"733",
+	"734",
+	"735",
+	"736",
+	"737",
+	"738",
+	"739",
+	"740",
+	"741",
+	"742",
+	"743",
+	"744",
+	"745",
+	"746",
+	"747",
+	"748",
+	"749",
+	"750",
+	"751",
+	"752",
+	"753",
+	"754",
+	"755",
+	"756",
+	"757",
+	"758",
+	"759",
+	"760",
+	"761",
+	"762",
+	"763",
+	"764",
+	"765",
+	"766",
+	"767",
+	"WM_CUT",
+	"WM_COPY",
+	"WM_PASTE",
+	"WM_CLEAR",
+	"WM_UNDO",
+	"WM_RENDERFORMAT",
+	"WM_RENDERALLFORMATS",
+	"WM_DESTROYCLIPBOARD",
+	"WM_DRAWCLIPBOARD",
+	"WM_PAINTCLIPBOARD",
+	"WM_VSCROLLCLIPBOARD",
+	"WM_SIZECLIPBOARD",
+	"WM_ASKCBFORMATNAME",
+	"WM_CHANGECBCHAIN",
+	"WM_HSCROLLCLIPBOARD",
+	"WM_QUERYNEWPALETTE",
+	"WM_PALETTEISCHANGING",
+	"WM_PALETTECHANGED",
+	"WM_HOTKEY",
+	"787",
+	"788",
+	"789",
+	"790",
+	"WM_PRINT",
+	"WM_PRINTCLIENT",
+	"793",
+	"794",
+	"795",
+	"796",
+	"797",
+	"798",
+	"799",
+	"800",
+	"801",
+	"802",
+	"803",
+	"804",
+	"805",
+	"806",
+	"807",
+	"808",
+	"809",
+	"810",
+	"811",
+	"812",
+	"813",
+	"814",
+	"815",
+	"816",
+	"817",
+	"818",
+	"819",
+	"820",
+	"821",
+	"822",
+	"823",
+	"824",
+	"825",
+	"826",
+	"827",
+	"828",
+	"829",
+	"830",
+	"831",
+	"832",
+	"833",
+	"834",
+	"835",
+	"836",
+	"837",
+	"838",
+	"839",
+	"840",
+	"841",
+	"842",
+	"843",
+	"844",
+	"845",
+	"846",
+	"847",
+	"848",
+	"849",
+	"850",
+	"851",
+	"852",
+	"853",
+	"854",
+	"855",
+	"856",
+	"857",
+	"858",
+	"859",
+	"860",
+	"861",
+	"862",
+	"863",
+	"864",
+	"865",
+	"866",
+	"867",
+	"868",
+	"869",
+	"870",
+	"871",
+	"872",
+	"873",
+	"874",
+	"875",
+	"876",
+	"877",
+	"878",
+	"879",
+	"880",
+	"881",
+	"882",
+	"883",
+	"884",
+	"885",
+	"886",
+	"887",
+	"888",
+	"889",
+	"890",
+	"891",
+	"892",
+	"893",
+	"894",
+	"895",
+	"896",
+	"897",
+	"898",
+	"899",
+	"900",
+	"901",
+	"902",
+	"903",
+	"904",
+	"905",
+	"906",
+	"907",
+	"908",
+	"909",
+	"910",
+	"911",
+	"912",
+	"913",
+	"914",
+	"915",
+	"916",
+	"917",
+	"918",
+	"919",
+	"920",
+	"921",
+	"922",
+	"923",
+	"924",
+	"925",
+	"926",
+	"927",
+	"928",
+	"929",
+	"930",
+	"931",
+	"932",
+	"933",
+	"934",
+	"935",
+	"936",
+	"937",
+	"938",
+	"939",
+	"940",
+	"941",
+	"942",
+	"943",
+	"944",
+	"945",
+	"946",
+	"947",
+	"948",
+	"949",
+	"950",
+	"951",
+	"952",
+	"953",
+	"954",
+	"955",
+	"956",
+	"957",
+	"958",
+	"959",
+	"960",
+	"961",
+	"962",
+	"963",
+	"964",
+	"965",
+	"966",
+	"967",
+	"968",
+	"969",
+	"970",
+	"971",
+	"972",
+	"973",
+	"974",
+	"975",
+	"976",
+	"977",
+	"978",
+	"979",
+	"980",
+	"981",
+	"982",
+	"983",
+	"984",
+	"985",
+	"986",
+	"987",
+	"988",
+	"989",
+	"990",
+	"991",
+	"992",
+	"993",
+	"994",
+	"995",
+	"996",
+	"997",
+	"998",
+	"999",
+	"1000",
+	"1001",
+	"1002",
+	"1003",
+	"1004",
+	"1005",
+	"1006",
+	"1007",
+	"1008",
+	"1009",
+	"1010",
+	"1011",
+	"1012",
+	"1013",
+	"1014",
+	"1015",
+	"1016",
+	"1017",
+	"1018",
+	"1019",
+	"1020",
+	"1021",
+	"1022",
+	"1023"
+};
+#endif
diff --git a/hw/xwin/winmisc.c b/hw/xwin/winmisc.c
new file mode 100644
index 0000000..8e66981
--- /dev/null
+++ b/hw/xwin/winmisc.c
@@ -0,0 +1,152 @@
+/*
+ *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+#ifdef XWIN_NATIVEGDI
+/* See Porting Layer Definition - p. 33 */
+/*
+ * Called by clients, returns the best size for a cursor, tile, or
+ * stipple, specified by class (sometimes called kind)
+ */
+
+void
+winQueryBestSizeNativeGDI (int class, unsigned short *pWidth,
+			   unsigned short *pHeight, ScreenPtr pScreen)
+{
+  ErrorF ("winQueryBestSizeNativeGDI\n");
+}
+#endif
+
+
+/*
+ * Count the number of one bits in a color mask.
+ */
+
+CARD8
+winCountBits (DWORD dw)
+{
+  DWORD		dwBits = 0;
+
+  while (dw)
+    {
+      dwBits += (dw & 1);
+      dw >>= 1;
+    }
+
+  return dwBits;
+}
+
+
+/*
+ * Modify the screen pixmap to point to the new framebuffer address
+ */
+
+Bool
+winUpdateFBPointer (ScreenPtr pScreen, void *pbits)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+
+  /* Location of shadow framebuffer has changed */
+  pScreenInfo->pfb = pbits;
+
+  /* Update the screen pixmap */
+  if (!(*pScreen->ModifyPixmapHeader) (pScreen->devPrivate,
+				       pScreen->width,
+				       pScreen->height,
+				       pScreen->rootDepth,
+				       BitsPerPixel (pScreen->rootDepth),
+				       PixmapBytePad (pScreenInfo->dwStride,
+						      pScreenInfo->dwBPP),
+				       pScreenInfo->pfb))
+    {
+      FatalError ("winUpdateFramebufferPointer - Failed modifying "\
+		  "screen pixmap\n");
+    }
+
+  return TRUE;
+}
+
+
+#ifdef XWIN_NATIVEGDI
+/*
+ * Paint the window background with the specified color
+ */
+
+BOOL
+winPaintBackground (HWND hwnd, COLORREF colorref)
+{
+  HDC			hdc;
+  HBRUSH		hbrush;
+  RECT			rect;
+
+  /* Create an hdc */
+  hdc = GetDC (hwnd);
+  if (hdc == NULL)
+    {
+      printf ("gdiWindowProc - GetDC failed\n");
+      exit (1);
+    }
+
+  /* Create and select blue brush */
+  hbrush = CreateSolidBrush (colorref);
+  if (hbrush == NULL)
+    {
+      printf ("gdiWindowProc - CreateSolidBrush failed\n");
+      exit (1);
+    }
+
+  /* Get window extents */
+  if (GetClientRect (hwnd, &rect) == FALSE)
+    {
+      printf ("gdiWindowProc - GetClientRect failed\n");
+      exit (1);
+    }
+
+  /* Fill window with blue brush */
+  if (FillRect (hdc, &rect, hbrush) == 0)
+    {
+      printf ("gdiWindowProc - FillRect failed\n");
+      exit (1);
+    }
+
+  /* Delete blue brush */
+  DeleteObject (hbrush);
+
+  /* Release the hdc */
+  ReleaseDC (hwnd, hdc);
+
+  return TRUE;
+}
+#endif
diff --git a/hw/xwin/winmouse.c b/hw/xwin/winmouse.c
new file mode 100644
index 0000000..1507dd3
--- /dev/null
+++ b/hw/xwin/winmouse.c
@@ -0,0 +1,341 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+#if defined(XFree86Server) && defined(XINPUT)
+#include "inputstr.h"
+
+/* Peek the internal button mapping */
+static CARD8 const *g_winMouseButtonMap = NULL;
+#endif
+
+
+/*
+ * Local prototypes
+ */
+
+static void
+winMouseCtrl (DeviceIntPtr pDevice, PtrCtrl *pCtrl);
+
+
+static void
+winMouseCtrl (DeviceIntPtr pDevice, PtrCtrl *pCtrl)
+{
+}
+
+
+/*
+ * See Porting Layer Definition - p. 18
+ * This is known as a DeviceProc
+ */
+
+int
+winMouseProc (DeviceIntPtr pDeviceInt, int iState)
+{
+  int 			lngMouseButtons, i;
+  int			lngWheelEvents = 2;
+  CARD8			*map;
+  DevicePtr		pDevice = (DevicePtr) pDeviceInt;
+
+  switch (iState)
+    {
+    case DEVICE_INIT:
+      /* Get number of mouse buttons */
+      lngMouseButtons = GetSystemMetrics(SM_CMOUSEBUTTONS);
+
+      /* Mapping of windows events to X events:
+       * LEFT:1 MIDDLE:2 RIGHT:3
+       * SCROLL_UP:4 SCROLL_DOWN:5
+       * XBUTTON 1:6 XBUTTON 2:7 ...
+       *
+       * To map scroll wheel correctly we need at least the 3 normal buttons
+       */
+      if (lngMouseButtons < 3)
+        lngMouseButtons = 3;
+      winMsg(X_PROBED, "%d mouse buttons found\n", lngMouseButtons);
+
+      /* allocate memory: 
+       * number of buttons + 2x mouse wheel event + 1 extra (offset for map) 
+       */
+      map = malloc(sizeof(CARD8) * (lngMouseButtons + lngWheelEvents + 1));
+    
+      /* initalize button map */ 
+      map[0] = 0;
+      for (i=1; i <= lngMouseButtons + lngWheelEvents; i++)
+      	map[i] = i;
+      InitPointerDeviceStruct (pDevice,
+			       map,
+			       lngMouseButtons + lngWheelEvents,
+			       GetMotionHistory,
+			       winMouseCtrl,
+			       GetMotionHistorySize(),
+			       2);
+      free(map);
+
+#if defined(XFree86Server) && defined(XINPUT)
+      g_winMouseButtonMap = pDeviceInt->button->map;
+#endif
+      break;
+
+    case DEVICE_ON:
+      pDevice->on = TRUE;
+      break;
+
+    case DEVICE_CLOSE:
+#if defined(XFree86Server) && defined(XINPUT)
+      g_winMouseButtonMap = NULL;
+#endif
+    case DEVICE_OFF:
+      pDevice->on = FALSE;
+      break;
+    }
+  return Success;
+}
+
+
+/* Handle the mouse wheel */
+int
+winMouseWheel (ScreenPtr pScreen, int iDeltaZ)
+{
+  winScreenPriv(pScreen);
+  int button; /* Button4 or Button5 */
+
+  /* Button4 = WheelUp */
+  /* Button5 = WheelDown */
+
+  /* Do we have any previous delta stored? */
+  if ((pScreenPriv->iDeltaZ > 0
+       && iDeltaZ > 0)
+      || (pScreenPriv->iDeltaZ < 0
+	  && iDeltaZ < 0))
+    {
+      /* Previous delta and of same sign as current delta */
+      iDeltaZ += pScreenPriv->iDeltaZ;
+      pScreenPriv->iDeltaZ = 0;
+    }
+  else
+    {
+      /*
+       * Previous delta of different sign, or zero.
+       * We will set it to zero for either case,
+       * as blindly setting takes just as much time
+       * as checking, then setting if necessary :)
+       */
+      pScreenPriv->iDeltaZ = 0;
+    }
+
+  /*
+   * Only process this message if the wheel has moved further than
+   * WHEEL_DELTA
+   */
+  if (iDeltaZ >= WHEEL_DELTA || (-1 * iDeltaZ) >= WHEEL_DELTA)
+    {
+      pScreenPriv->iDeltaZ = 0;
+	  
+      /* Figure out how many whole deltas of the wheel we have */
+      iDeltaZ /= WHEEL_DELTA;
+    }
+  else
+    {
+      /*
+       * Wheel has not moved past WHEEL_DELTA threshold;
+       * we will store the wheel delta until the threshold
+       * has been reached.
+       */
+      pScreenPriv->iDeltaZ = iDeltaZ;
+      return 0;
+    }
+
+  /* Set the button to indicate up or down wheel delta */
+  if (iDeltaZ > 0)
+    {
+      button = Button4;
+    }
+  else
+    {
+      button = Button5;
+    }
+
+  /*
+   * Flip iDeltaZ to positive, if negative,
+   * because always need to generate a *positive* number of
+   * button clicks for the Z axis.
+   */
+  if (iDeltaZ < 0)
+    {
+      iDeltaZ *= -1;
+    }
+
+  /* Generate X input messages for each wheel delta we have seen */
+  while (iDeltaZ--)
+    {
+      /* Push the wheel button */
+      winMouseButtonsSendEvent (ButtonPress, button);
+
+      /* Release the wheel button */
+      winMouseButtonsSendEvent (ButtonRelease, button);
+    }
+
+  return 0;
+}
+
+
+/*
+ * Enqueue a mouse button event
+ */
+
+void
+winMouseButtonsSendEvent (int iEventType, int iButton)
+{
+  xEvent		xCurrentEvent;
+
+  /* Load an xEvent and enqueue the event */
+  xCurrentEvent.u.u.type = iEventType;
+#if defined(XFree86Server) && defined(XINPUT)
+  if (g_winMouseButtonMap)
+    xCurrentEvent.u.u.detail = g_winMouseButtonMap[iButton];
+  else
+#endif
+  xCurrentEvent.u.u.detail = iButton;
+  xCurrentEvent.u.keyButtonPointer.time
+    = g_c32LastInputEventTime = GetTickCount ();
+  mieqEnqueue (&xCurrentEvent);
+}
+
+
+/*
+ * Decide what to do with a Windows mouse message
+ */
+
+int
+winMouseButtonsHandle (ScreenPtr pScreen,
+		       int iEventType, int iButton,
+		       WPARAM wParam)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+
+  /* Send button events right away if emulate 3 buttons is off */
+  if (pScreenInfo->iE3BTimeout == WIN_E3B_OFF)
+    {
+      /* Emulate 3 buttons is off, send the button event */
+      winMouseButtonsSendEvent (iEventType, iButton);
+      return 0;
+    }
+
+  /* Emulate 3 buttons is on, let the fun begin */
+  if (iEventType == ButtonPress
+      && pScreenPriv->iE3BCachedPress == 0
+      && !pScreenPriv->fE3BFakeButton2Sent)
+    {
+      /*
+       * Button was pressed, no press is cached,
+       * and there is no fake button 2 release pending.
+       */
+
+      /* Store button press type */
+      pScreenPriv->iE3BCachedPress = iButton;
+
+      /*
+       * Set a timer to send this button press if the other button
+       * is not pressed within the timeout time.
+       */
+      SetTimer (pScreenPriv->hwndScreen,
+		WIN_E3B_TIMER_ID,
+		pScreenInfo->iE3BTimeout,
+		NULL);
+    }
+  else if (iEventType == ButtonPress
+	   && pScreenPriv->iE3BCachedPress != 0
+	   && pScreenPriv->iE3BCachedPress != iButton
+	   && !pScreenPriv->fE3BFakeButton2Sent)
+    {
+      /*
+       * Button press is cached, other button was pressed,
+       * and there is no fake button 2 release pending.
+       */
+
+      /* Mouse button was cached and other button was pressed */
+      KillTimer (pScreenPriv->hwndScreen, WIN_E3B_TIMER_ID);
+      pScreenPriv->iE3BCachedPress = 0;
+
+      /* Send fake middle button */
+      winMouseButtonsSendEvent (ButtonPress, Button2);
+
+      /* Indicate that a fake middle button event was sent */
+      pScreenPriv->fE3BFakeButton2Sent = TRUE;
+    }
+  else if (iEventType == ButtonRelease
+	   && pScreenPriv->iE3BCachedPress == iButton)
+    {
+      /*
+       * Cached button was released before timer ran out,
+       * and before the other mouse button was pressed.
+       */
+      KillTimer (pScreenPriv->hwndScreen, WIN_E3B_TIMER_ID);
+      pScreenPriv->iE3BCachedPress = 0;
+
+      /* Send cached press, then send release */
+      winMouseButtonsSendEvent (ButtonPress, iButton);
+      winMouseButtonsSendEvent (ButtonRelease, iButton);
+    }
+  else if (iEventType == ButtonRelease
+	   && pScreenPriv->fE3BFakeButton2Sent
+	   && !(wParam & MK_LBUTTON)
+	   && !(wParam & MK_RBUTTON))
+    {
+      /*
+       * Fake button 2 was sent and both mouse buttons have now been released
+       */
+      pScreenPriv->fE3BFakeButton2Sent = FALSE;
+      
+      /* Send middle mouse button release */
+      winMouseButtonsSendEvent (ButtonRelease, Button2);
+    }
+  else if (iEventType == ButtonRelease
+	   && pScreenPriv->iE3BCachedPress == 0
+	   && !pScreenPriv->fE3BFakeButton2Sent)
+    {
+      /*
+       * Button was release, no button is cached,
+       * and there is no fake button 2 release is pending.
+       */
+      winMouseButtonsSendEvent (ButtonRelease, iButton);
+    }
+
+  return 0;
+}
diff --git a/hw/xwin/winms.h b/hw/xwin/winms.h
new file mode 100644
index 0000000..1ad30dc
--- /dev/null
+++ b/hw/xwin/winms.h
@@ -0,0 +1,46 @@
+#ifndef _WINMS_H_
+#define _WINMS_H_
+/*
+ *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#define NONAMELESSUNION
+#define DIRECTDRAW_VERSION	0x0300
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+
+#include <X11/Xwindows.h>
+#include <windowsx.h>
+
+#include "ddraw.h"
+
+#undef CreateWindow
+
+#endif /* _WINMS_H_ */
diff --git a/hw/xwin/winmsg.c b/hw/xwin/winmsg.c
new file mode 100644
index 0000000..d0464f7
--- /dev/null
+++ b/hw/xwin/winmsg.c
@@ -0,0 +1,179 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors: Alexander Gottwald	
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winmsg.h"
+#if CYGDEBUG
+#include "winmessages.h"
+#endif
+#include <stdarg.h>
+
+void winVMsg (int, MessageType, int verb, const char *, va_list);
+
+void
+winVMsg (int scrnIndex, MessageType type, int verb, const char *format,
+	 va_list ap)
+{
+  LogVMessageVerb(type, verb, format, ap);
+}
+
+
+void
+winDrvMsg (int scrnIndex, MessageType type, const char *format, ...)
+{
+  va_list ap;
+  va_start (ap, format);
+  LogVMessageVerb(type, 0, format, ap);
+  va_end (ap);
+}
+
+
+void
+winMsg (MessageType type, const char *format, ...)
+{
+  va_list ap;
+  va_start (ap, format);
+  LogVMessageVerb(type, 1, format, ap);
+  va_end (ap);
+}
+
+
+void
+winDrvMsgVerb (int scrnIndex, MessageType type, int verb, const char *format,
+	       ...)
+{
+  va_list ap;
+  va_start (ap, format);
+  LogVMessageVerb(type, verb, format, ap);
+  va_end (ap);
+}
+
+
+void
+winMsgVerb (MessageType type, int verb, const char *format, ...)
+{
+  va_list ap;
+  va_start (ap, format);
+  LogVMessageVerb(type, verb, format, ap);
+  va_end (ap);
+}
+
+
+void
+winErrorFVerb (int verb, const char *format, ...)
+{
+  va_list ap;
+  va_start (ap, format);
+  LogVMessageVerb(X_NONE, verb, format, ap);
+  va_end (ap);
+}
+
+void
+winDebug (const char *format, ...)
+{
+  va_list ap;
+  va_start (ap, format);
+  LogVMessageVerb(X_NONE, 3, format, ap);
+  va_end (ap);
+}
+
+void
+winTrace (const char *format, ...)
+{
+  va_list ap;
+  va_start (ap, format);
+  LogVMessageVerb(X_NONE, 10, format, ap);
+  va_end (ap);
+}
+
+void
+winW32Error(int verb, const char *msg)
+{
+    winW32ErrorEx(verb, msg, GetLastError());
+}
+
+void
+winW32ErrorEx(int verb, const char *msg, DWORD errorcode)
+{
+    LPVOID buffer;
+    if (!FormatMessage( 
+                FORMAT_MESSAGE_ALLOCATE_BUFFER | 
+                FORMAT_MESSAGE_FROM_SYSTEM | 
+                FORMAT_MESSAGE_IGNORE_INSERTS,
+                NULL,
+                errorcode,
+                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+                (LPTSTR) &buffer,
+                0,
+                NULL ))
+    {
+        winErrorFVerb(verb, "Unknown error in FormatMessage!\n"); 
+    }
+    else
+    {
+        winErrorFVerb(verb, "%s %s", msg, (char *)buffer); 
+        LocalFree(buffer);
+    }
+}
+
+#if CYGDEBUG
+void winDebugWin32Message(const char* function, HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
+{
+  static int force = 0;
+
+  if (message >= WM_USER)
+    {
+      if (force || getenv("WIN_DEBUG_MESSAGES") || getenv("WIN_DEBUG_WM_USER"))
+      {
+        winDebug("%s - Message WM_USER + %d\n", function, message - WM_USER);
+        winDebug("\thwnd 0x%x wParam 0x%x lParam 0x%x\n", hwnd, wParam, lParam);
+      }
+    }
+  else if (message < MESSAGE_NAMES_LEN && MESSAGE_NAMES[message])
+    {
+      const char *msgname = MESSAGE_NAMES[message];
+      char buffer[64];
+      snprintf(buffer, sizeof(buffer), "WIN_DEBUG_%s", msgname);
+      buffer[63] = 0;
+      if (force || getenv("WIN_DEBUG_MESSAGES") || getenv(buffer))
+      {
+        winDebug("%s - Message %s\n", function, MESSAGE_NAMES[message]);
+        winDebug("\thwnd 0x%x wParam 0x%x lParam 0x%x\n", hwnd, wParam, lParam);
+      }
+    }
+}
+#else
+void winDebugWin32Message(const char* function, HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
+{
+}
+#endif
diff --git a/hw/xwin/winmsg.h b/hw/xwin/winmsg.h
new file mode 100644
index 0000000..611dd69
--- /dev/null
+++ b/hw/xwin/winmsg.h
@@ -0,0 +1,50 @@
+#ifndef __WIN_MSG_H__
+#define __WIN_MSG_H__
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors: Alexander Gottwald	
+ */
+
+/*
+ * Function prototypes
+ */
+
+void winDrvMsgVerb (int scrnIndex,
+		    MessageType type, int verb, const char *format, ...);
+void winDrvMsg (int scrnIndex, MessageType type, const char *format, ...);
+void winMsgVerb (MessageType type, int verb, const char *format, ...);
+void winMsg (MessageType type, const char *format, ...);
+void winDebug (const char *format, ...);
+void winTrace (const char *format, ...);
+
+void winErrorFVerb (int verb, const char *format, ...);
+void winW32Error(int verb, const char *message);
+void winW32ErrorEx(int verb, const char *message, DWORD errorcode);
+void winDebugWin32Message(const char* function, HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
+
+#endif
diff --git a/hw/xwin/winmultiwindowclass.c b/hw/xwin/winmultiwindowclass.c
new file mode 100755
index 0000000..5b47c39
--- /dev/null
+++ b/hw/xwin/winmultiwindowclass.c
@@ -0,0 +1,325 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:     Earle F. Philhower, III
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include <X11/Xatom.h>
+#include "propertyst.h"
+#include "windowstr.h"
+#include "winmultiwindowclass.h"
+#include "win.h"
+
+/*
+ * Local function
+ */
+
+DEFINE_ATOM_HELPER(AtmWmWindowRole, "WM_WINDOW_ROLE")
+
+
+int
+winMultiWindowGetClassHint (WindowPtr pWin, char **res_name, char **res_class)
+{
+  struct _Window	*pwin;
+  struct _Property	*prop;
+  int			len_name, len_class;
+
+  if (!pWin || !res_name || !res_class)
+    {
+      ErrorF ("winMultiWindowGetClassHint - pWin, res_name, or res_class was "
+	      "NULL\n");
+      return 0;  
+    }
+  
+  pwin = (struct _Window*) pWin;
+
+  if (pwin->optional)
+    prop = (struct _Property *) pwin->optional->userProps;
+  else
+    prop = NULL;
+  
+  *res_name = *res_class = NULL;
+
+  while (prop)
+    {
+      if (prop->propertyName == XA_WM_CLASS
+	  && prop->type == XA_STRING
+	  && prop->format == 8
+	  && prop->data)
+	{
+	  len_name = strlen ((char *) prop->data);
+
+	  (*res_name) = malloc (len_name + 1);
+	  
+	  if (!*res_name)
+	    {
+	      ErrorF ("winMultiWindowGetClassHint - *res_name was NULL\n");
+	      return 0;
+	    }
+
+	  /* Add one to len_name to allow copying of trailing 0 */
+	  strncpy ((*res_name), prop->data, len_name + 1);
+
+	  if (len_name == prop->size)
+	    len_name--;
+
+	  len_class = strlen (((char *)prop->data) + 1 + len_name);
+
+	  (*res_class) = malloc (len_class + 1);
+
+	  if (!*res_class)
+	    {
+	      ErrorF ("winMultiWindowGetClassHint - *res_class was NULL\n");
+	      
+	      /* Free the previously allocated res_name */
+	      free (*res_name);
+	      return 0;
+	    }
+
+	  strcpy ((*res_class), ((char *)prop->data) + 1 + len_name);
+
+	  return 1;
+	}
+      else
+	prop = prop->next;
+    }
+  
+  return 0;
+}
+
+
+int
+winMultiWindowGetWMHints (WindowPtr pWin, WinXWMHints *hints)
+{
+  struct _Window	*pwin;
+  struct _Property	*prop;
+
+  if (!pWin || !hints)
+    {
+      ErrorF ("winMultiWindowGetWMHints - pWin or hints was NULL\n");
+      return 0; 
+    }
+
+  pwin = (struct _Window*) pWin;
+
+  if (pwin->optional)
+    prop = (struct _Property *) pwin->optional->userProps;
+  else
+    prop = NULL;
+  
+  memset (hints, 0, sizeof (WinXWMHints));
+
+  while (prop)
+    {
+      if (prop->propertyName == XA_WM_HINTS
+	  && prop->data)
+	{
+	  memcpy (hints, prop->data, sizeof (WinXWMHints));
+	  return 1;
+	}
+      else
+	prop = prop->next;
+    }
+  
+  return 0;
+}
+
+
+int
+winMultiWindowGetWindowRole (WindowPtr pWin, char **res_role)
+{
+  struct _Window	*pwin;
+  struct _Property	*prop;
+  int			len_role;
+
+  if (!pWin || !res_role) 
+    return 0; 
+
+  pwin = (struct _Window*) pWin;
+  
+  if (pwin->optional)
+    prop = (struct _Property *) pwin->optional->userProps;
+  else
+    prop = NULL;
+  
+  *res_role = NULL;
+  while (prop)
+    {
+      if (prop->propertyName == AtmWmWindowRole ()
+	  && prop->type == XA_STRING
+	  && prop->format == 8
+	  && prop->data)
+	{
+	  len_role= prop->size;
+
+	  (*res_role) = malloc (len_role + 1);
+
+	  if (!*res_role)
+	    {
+	      ErrorF ("winMultiWindowGetWindowRole - *res_role was NULL\n");
+	      return 0; 
+	    }
+
+	  strncpy ((*res_role), prop->data, len_role);
+	  (*res_role)[len_role] = 0;
+
+	  return 1;
+	}
+      else
+	prop = prop->next;
+    }
+  
+  return 0;
+}
+
+
+int
+winMultiWindowGetWMNormalHints (WindowPtr pWin, WinXSizeHints *hints)
+{
+  struct _Window	*pwin;
+  struct _Property	*prop;
+
+  if (!pWin || !hints)
+    {
+      ErrorF ("winMultiWindowGetWMNormalHints - pWin or hints was NULL\n");
+      return 0; 
+    }
+
+  pwin = (struct _Window*) pWin;
+
+  if (pwin->optional)
+    prop = (struct _Property *) pwin->optional->userProps;
+  else
+    prop = NULL;
+  
+  memset (hints, 0, sizeof (WinXSizeHints));
+
+  while (prop)
+    {
+      if (prop->propertyName == XA_WM_NORMAL_HINTS
+	  && prop->data)
+	{
+	  memcpy (hints, prop->data, sizeof (WinXSizeHints));
+	  return 1;
+	}
+      else
+	prop = prop->next;
+    }
+
+  return 0;
+}
+
+int
+winMultiWindowGetTransientFor (WindowPtr pWin, WindowPtr *ppDaddy)
+{
+  struct _Window        *pwin;
+  struct _Property      *prop;
+
+  if (!pWin)
+    {
+      ErrorF ("winMultiWindowGetTransientFor - pWin was NULL\n");
+      return 0;
+    }
+
+  pwin = (struct _Window*) pWin;
+
+  if (pwin->optional)
+    prop = (struct _Property *) pwin->optional->userProps;
+  else
+    prop = NULL;
+
+  if (ppDaddy)
+    *ppDaddy = NULL;
+
+  while (prop)
+    {
+      if (prop->propertyName == XA_WM_TRANSIENT_FOR)
+        {
+          if (ppDaddy)
+            memcpy (*ppDaddy, prop->data, sizeof (WindowPtr));
+          return 1;
+        }
+      else
+        prop = prop->next;
+    }
+
+  return 0;
+}
+
+int
+winMultiWindowGetWMName (WindowPtr pWin, char **wmName)
+{
+  struct _Window	*pwin;
+  struct _Property	*prop;
+  int			len_name;
+
+  if (!pWin || !wmName)
+    {
+      ErrorF ("winMultiWindowGetClassHint - pWin, res_name, or res_class was "
+	      "NULL\n");
+      return 0;  
+    }
+  
+  pwin = (struct _Window*) pWin;
+
+  if (pwin->optional)
+    prop = (struct _Property *) pwin->optional->userProps;
+  else
+    prop = NULL;
+  
+  *wmName = NULL;
+
+  while (prop)
+    {
+      if (prop->propertyName == XA_WM_NAME
+	  && prop->type == XA_STRING
+	  && prop->data)
+	{
+	  len_name = prop->size;
+
+	  (*wmName) = malloc (len_name + 1);
+	  
+	  if (!*wmName)
+	    {
+	      ErrorF ("winMultiWindowGetWMName - *wmName was NULL\n");
+	      return 0;
+	    }
+
+	  strncpy ((*wmName), prop->data, len_name);
+	  (*wmName)[len_name] = 0;
+
+	  return 1;
+	}
+      else
+	prop = prop->next;
+    }
+  
+  return 0;
+}
diff --git a/hw/xwin/winmultiwindowclass.h b/hw/xwin/winmultiwindowclass.h
new file mode 100755
index 0000000..c635ab2
--- /dev/null
+++ b/hw/xwin/winmultiwindowclass.h
@@ -0,0 +1,114 @@
+#if !defined(WINMULTIWINDOWCLASS_H)
+#define WINMULTIWINDOWCLASS_H
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:     Earle F. Philhower, III
+ */
+
+/*
+ * Structures
+ */
+
+typedef struct {
+  long		flags;	/* marks which fields in this structure are defined */
+  Bool		input;	/* does this application rely on the window manager to
+		   get keyboard input? */
+  int		initial_state;	/* see below */
+  Pixmap	icon_pixmap;	/* pixmap to be used as icon */
+  Window	icon_window; 	/* window to be used as icon */
+  int		icon_x, icon_y; 	/* initial position of icon */
+  Pixmap	icon_mask;	/* icon mask bitmap */
+  XID		window_group;	/* id of related window group */
+  /* this structure may be extended in the future */
+} WinXWMHints;
+
+
+/*
+ * new version containing base_width, base_height, and win_gravity fields;
+ * used with WM_NORMAL_HINTS.
+ */
+typedef struct {
+  long flags;     /* marks which fields in this structure are defined */
+  int x, y;               /* obsolete for new window mgrs, but clients */
+  int width, height;      /* should set so old wm's don't mess up */
+  int min_width, min_height;
+  int max_width, max_height;
+  int width_inc, height_inc;
+  struct {
+    int x;  /* numerator */
+    int y;  /* denominator */
+  } min_aspect, max_aspect;
+  int base_width, base_height;            /* added by ICCCM version 1 */
+  int win_gravity;                        /* added by ICCCM version 1 */
+} WinXSizeHints;
+
+/*
+ * The next block of definitions are for window manager properties that
+ * clients and applications use for communication.
+ */
+
+/* flags argument in size hints */
+#define USPosition      (1L << 0) /* user specified x, y */
+#define USSize          (1L << 1) /* user specified width, height */
+
+#define PPosition       (1L << 2) /* program specified position */
+#define PSize           (1L << 3) /* program specified size */
+#define PMinSize        (1L << 4) /* program specified minimum size */
+#define PMaxSize        (1L << 5) /* program specified maximum size */
+#define PResizeInc      (1L << 6) /* program specified resize increments */
+#define PAspect         (1L << 7) /* program specified min and max aspect ratios */
+#define PBaseSize       (1L << 8) /* program specified base for incrementing */
+#define PWinGravity     (1L << 9) /* program specified window gravity */
+
+/* obsolete */
+#define PAllHints (PPosition|PSize|PMinSize|PMaxSize|PResizeInc|PAspect)
+
+
+/*
+ * Function prototypes
+ */
+
+int
+winMultiWindowGetWMHints (WindowPtr pWin, WinXWMHints *hints);
+
+int
+winMultiWindowGetClassHint (WindowPtr pWin, char **res_name, char **res_class);
+
+int
+winMultiWindowGetWindowRole (WindowPtr pWin, char **res_role);
+
+int
+winMultiWindowGetWMNormalHints (WindowPtr pWin, WinXSizeHints *hints);
+
+int
+winMultiWindowGetWMName (WindowPtr pWin, char **wmName);
+
+int
+winMultiWindowGetTransientFor (WindowPtr pWin, WindowPtr *ppDaddy);
+
+#endif
diff --git a/hw/xwin/winmultiwindowicons.c b/hw/xwin/winmultiwindowicons.c
new file mode 100644
index 0000000..45ed093
--- /dev/null
+++ b/hw/xwin/winmultiwindowicons.c
@@ -0,0 +1,478 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Earle F. Philhower, III
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "dixevents.h"
+#include "winmultiwindowclass.h"
+#include "winprefs.h"
+
+
+/*
+ * External global variables
+ */
+
+extern HICON		g_hIconX;
+extern HICON		g_hSmallIconX;
+
+
+/*
+ * Prototypes for local functions
+ */
+
+static void
+winScaleXBitmapToWindows (int iconSize, int effBPP,
+			  PixmapPtr pixmap, unsigned char *image);
+
+
+/*
+ * Scale an X icon bitmap into a Windoze icon bitmap
+ */
+
+static void
+winScaleXBitmapToWindows (int iconSize,
+			  int effBPP,
+			  PixmapPtr pixmap,
+			  unsigned char *image)
+{
+  int			row, column, effXBPP, effXDepth;
+  unsigned char		*outPtr;
+  unsigned char		*iconData = 0;
+  int			stride, xStride;
+  float			factX, factY;
+  int			posX, posY;
+  unsigned char		*ptr;
+  unsigned int		zero;
+  unsigned int		color;
+
+  effXBPP = BitsPerPixel(pixmap->drawable.depth);
+  effXDepth = pixmap->drawable.depth;
+
+  if (pixmap->drawable.bitsPerPixel == 15)
+    effXBPP = 16;
+  
+  if (pixmap->drawable.depth == 15)
+    effXDepth = 16;
+
+  /* Need 32-bit aligned rows */
+  stride = ((iconSize * effBPP + 31) & (~31)) / 8;
+  xStride = PixmapBytePad (pixmap->drawable.width, pixmap->drawable.depth);
+  if (stride == 0 || xStride == 0)
+    {
+      ErrorF ("winScaleXBitmapToWindows - stride or xStride is zero.  "
+	      "Bailing.\n");
+      return;
+    }
+
+  /* Allocate memory for icon data */
+  iconData = malloc (xStride * pixmap->drawable.height);
+  if (!iconData)
+    {
+      ErrorF ("winScaleXBitmapToWindows - malloc failed for iconData.  "
+	      "Bailing.\n");
+      return;
+    }
+
+  /* Get icon data */
+  miGetImage ((DrawablePtr) &(pixmap->drawable), 0, 0,
+	      pixmap->drawable.width, pixmap->drawable.height,
+	      ZPixmap, 0xffffffff, iconData);
+
+  /* Keep aspect ratio */
+  factX = ((float)pixmap->drawable.width) / ((float)iconSize);
+  factY = ((float)pixmap->drawable.height) / ((float)iconSize);
+  if (factX > factY)
+    factY = factX;
+  else
+    factX = factY;
+  
+  /* Out-of-bounds, fill icon with zero */
+  zero = 0;
+ 
+  for (row = 0; row < iconSize; row++)
+    {
+      outPtr = image + stride * row;
+      for (column = 0; column < iconSize; column++)
+	{
+	  posX = factX * column;
+	  posY = factY * row;
+	  
+	  ptr = iconData + posY*xStride;
+	  if (effXBPP == 1)
+	    {
+	      ptr += posX / 8;
+	      
+	      /* Out of X icon bounds, leave space blank */
+	      if (posX >= pixmap->drawable.width
+		  || posY >= pixmap->drawable.height)
+		ptr = (unsigned char *) &zero;
+	      
+	      if ((*ptr) & (1 << (posX & 7)))
+		switch (effBPP)
+		  {
+		  case 32:
+		    *(outPtr++) = 0;
+		  case 24:
+		    *(outPtr++) = 0;
+		  case 16:
+		    *(outPtr++) = 0;
+		  case 8:
+		    *(outPtr++) = 0;
+		    break;
+		  case 1:
+		    outPtr[column / 8] &= ~(1 << (7 - (column & 7)));
+		    break;
+		  }
+	      else
+		switch (effBPP)
+		  {
+		  case 32:
+		    *(outPtr++) = 255;
+		    *(outPtr++) = 255;
+		    *(outPtr++) = 255;
+		    *(outPtr++) = 0;
+		    break;
+		  case 24:
+		    *(outPtr++) = 255;
+		  case 16:
+		    *(outPtr++) = 255;
+		  case 8: 
+		    *(outPtr++) = 255;
+		    break;
+		  case 1:
+		    outPtr[column / 8] |= (1 << (7 - (column & 7)));
+		    break;
+		  }
+	    }
+	  else if (effXDepth == 24 || effXDepth == 32)
+	    {
+	      ptr += posX * (effXBPP / 8);
+
+	      /* Out of X icon bounds, leave space blank */
+	      if (posX >= pixmap->drawable.width
+		  || posY >= pixmap->drawable.height)
+		ptr = (unsigned char *) &zero;
+	      color = (((*ptr) << 16)
+		       + ((*(ptr + 1)) << 8)
+		       + ((*(ptr + 2)) << 0));
+	      switch (effBPP)
+		{
+		case 32:
+		  *(outPtr++) = *(ptr++); // b
+		  *(outPtr++) = *(ptr++); // g
+		  *(outPtr++) = *(ptr++); // r
+		  *(outPtr++) = 0; // resvd
+		  break;
+		case 24:
+		  *(outPtr++) = *(ptr++);
+		  *(outPtr++) = *(ptr++);
+		  *(outPtr++) = *(ptr++);
+		  break;
+		case 16:
+		  color = ((((*ptr) >> 2) << 10)
+			   + (((*(ptr + 1)) >> 2) << 5)
+			   + (((*(ptr + 2)) >> 2)));
+		  *(outPtr++) = (color >> 8);
+		  *(outPtr++) = (color & 255);
+		  break;
+		case 8:
+		  color = (((*ptr))) + (((*(ptr + 1)))) + (((*(ptr + 2))));
+		  color /= 3;
+		  *(outPtr++) = color;
+		  break;
+		case 1:
+		  if (color)
+		    outPtr[column / 8] |= (1 << (7 - (column & 7)));
+		  else
+		    outPtr[column / 8] &= ~(1 << (7 - (column & 7)));
+		}
+	    }
+	  else if (effXDepth == 16)
+	    {
+	      ptr += posX * (effXBPP / 8);
+	
+	      /* Out of X icon bounds, leave space blank */
+	      if (posX >= pixmap->drawable.width
+		  || posY >= pixmap->drawable.height)
+		ptr = (unsigned char *) &zero;
+	      color = ((*ptr) << 8) + (*(ptr + 1));
+	      switch (effBPP)
+		{
+		case 32:
+		  *(outPtr++) = (color & 31) << 2;
+		  *(outPtr++) = ((color >> 5) & 31) << 2;
+		  *(outPtr++) = ((color >> 10) & 31) << 2;
+		  *(outPtr++) = 0; // resvd
+		  break;
+		case 24:
+		  *(outPtr++) = (color & 31) << 2;
+		  *(outPtr++) = ((color >> 5) & 31) << 2;
+		  *(outPtr++) = ((color >> 10) & 31) << 2;
+		  break;
+		case 16:
+		  *(outPtr++) = *(ptr++);
+		  *(outPtr++) = *(ptr++);
+		  break;
+		case 8:
+		  *(outPtr++) = (((color & 31)
+				  + ((color >> 5) & 31)
+				  + ((color >> 10) & 31)) / 3) << 2;
+		  break;
+		case 1:
+		  if (color)
+		    outPtr[column / 8] |= (1 << (7 - (column & 7)));
+		  else
+		    outPtr[column / 8] &= ~(1 << (7 - (column & 7)));
+		  break;
+		} /* end switch(effbpp) */
+	    } /* end if effxbpp==16) */
+	} /* end for column */
+    } /* end for row */
+  free (iconData);
+}
+
+
+/*
+ * Attempt to create a custom icon from the WM_HINTS bitmaps
+ */
+
+HICON
+winXIconToHICON (WindowPtr pWin, int iconSize)
+{
+  unsigned char		*mask, *image, *imageMask;
+  unsigned char		*dst, *src;
+  PixmapPtr		iconPtr;
+  PixmapPtr		maskPtr;
+  int			planes, bpp, effBPP, stride, maskStride, i;
+  HDC			hDC;
+  ICONINFO		ii;
+  WinXWMHints		hints;
+  HICON			hIcon;
+
+  winMultiWindowGetWMHints (pWin, &hints);
+  if (!hints.icon_pixmap) return NULL;
+
+  iconPtr = (PixmapPtr) LookupIDByType (hints.icon_pixmap, RT_PIXMAP);
+  
+  if (!iconPtr) return NULL;
+  
+  hDC = GetDC (GetDesktopWindow ());
+  planes = GetDeviceCaps (hDC, PLANES);
+  bpp = GetDeviceCaps (hDC, BITSPIXEL);
+  ReleaseDC (GetDesktopWindow (), hDC);
+  
+  /* 15 BPP is really 16BPP as far as we care */
+  if (bpp == 15)
+    effBPP = 16;
+  else
+    effBPP = bpp;
+  
+  /* Need 32-bit aligned rows */
+  stride = ((iconSize * effBPP + 31) & (~31)) / 8;
+
+  /* Mask is 1-bit deep */
+  maskStride = ((iconSize * 1 + 31) & (~31)) / 8; 
+
+  image = (unsigned char * ) malloc (stride * iconSize);
+  imageMask = (unsigned char *) malloc (stride * iconSize);
+  mask = (unsigned char *) malloc (maskStride * iconSize);
+  
+  /* Default to a completely black mask */
+  memset (mask, 0, maskStride * iconSize);
+  
+  winScaleXBitmapToWindows (iconSize, effBPP, iconPtr, image);
+  maskPtr = (PixmapPtr) LookupIDByType (hints.icon_mask, RT_PIXMAP);
+
+  if (maskPtr) 
+    {
+      winScaleXBitmapToWindows (iconSize, 1, maskPtr, mask);
+      
+      winScaleXBitmapToWindows (iconSize, effBPP, maskPtr, imageMask);
+      
+      /* Now we need to set all bits of the icon which are not masked */
+      /* on to 0 because Color is really an XOR, not an OR function */
+      dst = image;
+      src = imageMask;
+
+      for (i = 0; i < (stride * iconSize); i++)
+	if ((*(src++)))
+	  *(dst++) = 0;
+	else
+	  dst++;
+    }
+  
+  ii.fIcon = TRUE;
+  ii.xHotspot = 0; /* ignored */
+  ii.yHotspot = 0; /* ignored */
+  
+  /* Create Win32 mask from pixmap shape */
+  ii.hbmMask = CreateBitmap (iconSize, iconSize, planes, 1, mask);
+
+  /* Create Win32 bitmap from pixmap */
+  ii.hbmColor = CreateBitmap (iconSize, iconSize, planes, bpp, image);
+
+  /* Merge Win32 mask and bitmap into icon */
+  hIcon = CreateIconIndirect (&ii);
+
+  /* Release Win32 mask and bitmap */
+  DeleteObject (ii.hbmMask);
+  DeleteObject (ii.hbmColor);
+
+  /* Free X mask and bitmap */
+  free (mask);
+  free (image);
+  free (imageMask);
+
+  return hIcon;
+}
+
+
+
+/*
+ * Change the Windows window icon 
+ */
+
+#ifdef XWIN_MULTIWINDOW
+void
+winUpdateIcon (Window id)
+{
+  WindowPtr		pWin;
+  HICON			hIcon, hiconOld;
+
+  pWin = (WindowPtr) LookupIDByType (id, RT_WINDOW);
+  if (!pWin) return;
+  hIcon = (HICON)winOverrideIcon ((unsigned long)pWin);
+
+  if (!hIcon)
+    hIcon = winXIconToHICON (pWin, GetSystemMetrics(SM_CXICON));
+
+  if (hIcon)
+    {
+      winWindowPriv(pWin);
+
+      if (pWinPriv->hWnd)
+	{
+	  hiconOld = (HICON) SetClassLong (pWinPriv->hWnd,
+					   GCL_HICON,
+					   (int) hIcon);
+	  
+	  /* Delete the icon if its not the default */
+	  winDestroyIcon(hiconOld);
+	}
+    }
+ 
+  hIcon = winXIconToHICON (pWin, GetSystemMetrics(SM_CXSMICON));
+  if (hIcon)
+    {
+      winWindowPriv(pWin);
+
+      if (pWinPriv->hWnd)
+	{
+	  hiconOld = (HICON) SetClassLong (pWinPriv->hWnd,
+					   GCL_HICONSM,
+					   (int) hIcon);
+	  winDestroyIcon (hiconOld);
+	}
+    }
+}
+
+void winInitGlobalIcons (void)
+{
+  int sm_cx = GetSystemMetrics(SM_CXICON);
+  int sm_cxsm = GetSystemMetrics(SM_CXSMICON);
+  /* Load default X icon in case it's not ready yet */
+  if (!g_hIconX) 
+    {  
+      g_hIconX = (HICON)winOverrideDefaultIcon(sm_cx);
+      g_hSmallIconX = (HICON)winOverrideDefaultIcon(sm_cxsm);
+    }
+  
+  if (!g_hIconX)
+    {   
+      g_hIconX = (HICON)LoadImage (g_hInstance,
+	      MAKEINTRESOURCE(IDI_XWIN),
+	      IMAGE_ICON,
+	      GetSystemMetrics(SM_CXICON),
+	      GetSystemMetrics(SM_CYICON),
+	      0);
+      g_hSmallIconX = (HICON)LoadImage (g_hInstance,
+	      MAKEINTRESOURCE(IDI_XWIN),
+	      IMAGE_ICON,
+	      GetSystemMetrics(SM_CXSMICON),
+	      GetSystemMetrics(SM_CYSMICON),
+	      LR_DEFAULTSIZE);
+    }
+}
+
+void winSelectIcons(WindowPtr pWin, HICON *pIcon, HICON *pSmallIcon)
+{
+  HICON hIcon, hSmallIcon;
+  
+  winInitGlobalIcons();  
+  
+  /* Try and get the icon from WM_HINTS */
+  hIcon = winXIconToHICON (pWin, GetSystemMetrics(SM_CXICON));
+  hSmallIcon = winXIconToHICON (pWin, GetSystemMetrics(SM_CXSMICON));
+
+  /* If we got the small, but not the large one swap them */
+  if (!hIcon && hSmallIcon) 
+  {
+      hIcon = hSmallIcon;
+      hSmallIcon = NULL;
+  }
+  
+  /* Use default X icon if no icon loaded from WM_HINTS */
+  if (!hIcon) {
+    hIcon = g_hIconX;
+    hSmallIcon = g_hSmallIconX;
+  }
+
+  if (pIcon)
+    *pIcon = hIcon;
+  else
+    winDestroyIcon(hIcon);
+  if (pSmallIcon)
+    *pSmallIcon = hSmallIcon;
+  else
+    winDestroyIcon(hSmallIcon);
+}
+
+void winDestroyIcon(HICON hIcon)
+{
+  /* Delete the icon if its not the default */
+  if (hIcon &&
+      hIcon != g_hIconX &&
+      hIcon != g_hSmallIconX &&
+      !winIconIsOverride((unsigned long)hIcon))
+    DestroyIcon (hIcon);
+}
+#endif
diff --git a/hw/xwin/winmultiwindowshape.c b/hw/xwin/winmultiwindowshape.c
new file mode 100644
index 0000000..33deae3
--- /dev/null
+++ b/hw/xwin/winmultiwindowshape.c
@@ -0,0 +1,211 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Kensuke Matsuzaki
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#ifdef SHAPE
+
+#include "win.h"
+
+
+/*
+ * winSetShapeMultiWindow - See Porting Layer Definition - p. 42
+ */
+
+void
+winSetShapeMultiWindow (WindowPtr pWin)
+{
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winSetShapeMultiWindow - pWin: %08x\n", pWin);
+#endif
+  
+  WIN_UNWRAP(SetShape); 
+  (*pScreen->SetShape)(pWin);
+  WIN_WRAP(SetShape, winSetShapeMultiWindow);
+  
+  /* Update the Windows window's shape */
+  winReshapeMultiWindow (pWin);
+  winUpdateRgnMultiWindow (pWin);
+
+  return;
+}
+
+
+/*
+ * winUpdateRgnMultiWindow - Local function to update a Windows window region
+ */
+
+void
+winUpdateRgnMultiWindow (WindowPtr pWin)
+{
+  SetWindowRgn (winGetWindowPriv(pWin)->hWnd,
+		winGetWindowPriv(pWin)->hRgn, TRUE);
+}
+
+
+/*
+ * winReshapeMultiWindow - Computes the composite clipping region for a window
+ */
+
+void
+winReshapeMultiWindow (WindowPtr pWin)
+{
+  int		nRects;
+  RegionRec	rrNewShape;
+  BoxPtr	pShape, pRects, pEnd;
+  HRGN		hRgn, hRgnRect;
+  winWindowPriv(pWin);
+
+#if CYGDEBUG
+  winDebug ("winReshape ()\n");
+#endif
+  
+  /* Bail if the window is the root window */
+  if (pWin->parent == NULL)
+    return;
+
+  /* Bail if the window is not top level */
+  if (pWin->parent->parent != NULL)
+    return;
+
+  /* Bail if Windows window handle is invalid */
+  if (pWinPriv->hWnd == NULL)
+    return;
+  
+  /* Free any existing window region stored in the window privates */
+  if (pWinPriv->hRgn != NULL)
+    {
+      DeleteObject (pWinPriv->hRgn);
+      pWinPriv->hRgn = NULL;
+    }
+  
+  /* Bail if the window has no bounding region defined */
+  if (!wBoundingShape (pWin))
+    return;
+
+  REGION_NULL(pWin->drawable.pScreen, &rrNewShape);
+  REGION_COPY(pWin->drawable.pScreen, &rrNewShape, wBoundingShape(pWin));
+  REGION_TRANSLATE(pWin->drawable.pScreen,
+		   &rrNewShape,
+		   pWin->borderWidth,
+                   pWin->borderWidth);
+  
+  nRects = REGION_NUM_RECTS(&rrNewShape);
+  pShape = REGION_RECTS(&rrNewShape);
+  
+  /* Don't do anything if there are no rectangles in the region */
+  if (nRects > 0)
+    {
+      RECT			rcClient;
+      RECT			rcWindow;
+      int			iOffsetX, iOffsetY;
+      
+      /* Get client rectangle */
+      if (!GetClientRect (pWinPriv->hWnd, &rcClient))
+	{
+	  ErrorF ("winReshape - GetClientRect failed, bailing: %d\n",
+		  (int) GetLastError ());
+	  return;
+	}
+
+      /* Translate client rectangle coords to screen coords */
+      /* NOTE: Only transforms top and left members */
+      ClientToScreen (pWinPriv->hWnd, (LPPOINT) &rcClient);
+
+      /* Get window rectangle */
+      if (!GetWindowRect (pWinPriv->hWnd, &rcWindow))
+	{
+	  ErrorF ("winReshape - GetWindowRect failed, bailing: %d\n",
+		  (int) GetLastError ());
+	  return;
+	}
+
+      /* Calculate offset from window upper-left to client upper-left */
+      iOffsetX = rcClient.left - rcWindow.left;
+      iOffsetY = rcClient.top - rcWindow.top;
+
+      /* Create initial Windows region for title bar */
+      /* FIXME: Mean, nasty, ugly hack!!! */
+      hRgn = CreateRectRgn (0, 0, rcWindow.right, iOffsetY);
+      if (hRgn == NULL)
+	{
+	  ErrorF ("winReshape - Initial CreateRectRgn (%d, %d, %d, %d) "
+		  "failed: %d\n",
+		  0, 0, (int) rcWindow.right, iOffsetY, (int) GetLastError ());
+	}
+
+      /* Loop through all rectangles in the X region */
+      for (pRects = pShape, pEnd = pShape + nRects; pRects < pEnd; pRects++)
+        {
+	  /* Create a Windows region for the X rectangle */
+	  hRgnRect = CreateRectRgn (pRects->x1 + iOffsetX,
+				    pRects->y1 + iOffsetY,
+				    pRects->x2 + iOffsetX,
+				    pRects->y2 + iOffsetY);
+	  if (hRgnRect == NULL)
+	    {
+	      ErrorF ("winReshape - Loop CreateRectRgn (%d, %d, %d, %d) "
+		      "failed: %d\n"
+		      "\tx1: %d x2: %d xOff: %d y1: %d y2: %d yOff: %d\n",
+		      pRects->x1 + iOffsetX,
+		      pRects->y1 + iOffsetY,
+		      pRects->x2 + iOffsetX,
+		      pRects->y2 + iOffsetY,
+		      (int) GetLastError (),
+		      pRects->x1, pRects->x2, iOffsetX,
+		      pRects->y1, pRects->y2, iOffsetY);
+	    }
+
+	  /* Merge the Windows region with the accumulated region */
+	  if (CombineRgn (hRgn, hRgn, hRgnRect, RGN_OR) == ERROR)
+	    {
+	      ErrorF ("winReshape - CombineRgn () failed: %d\n",
+		      (int) GetLastError ());
+	    }
+
+	  /* Delete the temporary Windows region */
+	  DeleteObject (hRgnRect);
+        }
+      
+      /* Save a handle to the composite region in the window privates */
+      pWinPriv->hRgn = hRgn;
+    }
+
+  REGION_UNINIT(pWin->drawable.pScreen, &rrNewShape);
+  
+  return;
+}
+#endif
diff --git a/hw/xwin/winmultiwindowwindow.c b/hw/xwin/winmultiwindowwindow.c
new file mode 100644
index 0000000..037c881
--- /dev/null
+++ b/hw/xwin/winmultiwindowwindow.c
@@ -0,0 +1,1054 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Kensuke Matsuzaki
+ *		Earle F. Philhower, III
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "dixevents.h"
+#include "winmultiwindowclass.h"
+#include "winprefs.h"
+
+/*
+ * External global variables
+ */
+
+extern HWND			g_hDlgDepthChange;
+
+extern void winSelectIcons(WindowPtr pWin, HICON *pIcon, HICON *pSmallIcon);
+
+/*
+ * Prototypes for local functions
+ */
+
+void
+winCreateWindowsWindow (WindowPtr pWin);
+
+static void
+winDestroyWindowsWindow (WindowPtr pWin);
+
+static void
+winUpdateWindowsWindow (WindowPtr pWin);
+
+static void
+winFindWindow (pointer value, XID id, pointer cdata);
+
+/*
+ * Constant defines
+ */
+
+#define MOUSE_POLLING_INTERVAL		500
+
+
+/*
+ * Macros
+ */
+
+#define SubSend(pWin) \
+    ((pWin->eventMask|wOtherEventMasks(pWin)) & SubstructureNotifyMask)
+
+#define StrSend(pWin) \
+    ((pWin->eventMask|wOtherEventMasks(pWin)) & StructureNotifyMask)
+
+#define SubStrSend(pWin,pParent) (StrSend(pWin) || SubSend(pParent))
+
+
+/*
+ * CreateWindow - See Porting Layer Definition - p. 37
+ */
+
+Bool
+winCreateWindowMultiWindow (WindowPtr pWin)
+{
+  Bool			fResult = TRUE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGMULTIWINDOW_DEBUG
+  winTrace ("winCreateWindowMultiWindow - pWin: %p\n", pWin);
+#endif
+  
+  WIN_UNWRAP(CreateWindow);
+  fResult = (*pScreen->CreateWindow) (pWin);
+  WIN_WRAP(CreateWindow, winCreateWindowMultiWindow);
+  
+  /* Initialize some privates values */
+  pWinPriv->hRgn = NULL;
+  pWinPriv->hWnd = NULL;
+  pWinPriv->pScreenPriv = winGetScreenPriv(pWin->drawable.pScreen);
+  pWinPriv->fXKilled = FALSE;
+ 
+  return fResult;
+}
+
+
+/*
+ * DestroyWindow - See Porting Layer Definition - p. 37
+ */
+
+Bool
+winDestroyWindowMultiWindow (WindowPtr pWin)
+{
+  Bool			fResult = TRUE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winDestroyWindowMultiWindow - pWin: %p\n", pWin);
+#endif
+  
+  WIN_UNWRAP(DestroyWindow); 
+  fResult = (*pScreen->DestroyWindow)(pWin);
+  WIN_WRAP(DestroyWindow, winDestroyWindowMultiWindow);
+  
+  /* Flag that the window has been destroyed */
+  pWinPriv->fXKilled = TRUE;
+  
+  /* Kill the MS Windows window associated with this window */
+  winDestroyWindowsWindow (pWin); 
+
+  return fResult;
+}
+
+
+/*
+ * PositionWindow - See Porting Layer Definition - p. 37
+ *
+ * This function adjusts the position and size of Windows window
+ * with respect to the underlying X window.  This is the inverse
+ * of winAdjustXWindow, which adjusts X window to Windows window.
+ */
+
+Bool
+winPositionWindowMultiWindow (WindowPtr pWin, int x, int y)
+{
+  Bool			fResult = TRUE;
+  int		        iX, iY, iWidth, iHeight;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+  HWND hWnd = pWinPriv->hWnd;
+  RECT rcNew;
+  RECT rcOld;
+#if CYGMULTIWINDOW_DEBUG
+  RECT rcClient;
+  RECT *lpRc;
+#endif
+  DWORD dwExStyle;
+  DWORD dwStyle;
+
+#if CYGMULTIWINDOW_DEBUG
+  winTrace ("winPositionWindowMultiWindow - pWin: %p\n", pWin);
+#endif
+  
+  WIN_UNWRAP(PositionWindow);
+  fResult = (*pScreen->PositionWindow)(pWin, x, y);
+  WIN_WRAP(PositionWindow, winPositionWindowMultiWindow);
+  
+#if CYGWINDOWING_DEBUG
+  ErrorF ("winPositionWindowMultiWindow: (x, y) = (%d, %d)\n",
+	  x, y);
+#endif
+
+  /* Bail out if the Windows window handle is bad */
+  if (!hWnd)
+    {
+#if CYGWINDOWING_DEBUG
+      ErrorF ("\timmediately return since hWnd is NULL\n");
+#endif
+      return fResult;
+    }
+
+  /* Get the Windows window style and extended style */
+  dwExStyle = GetWindowLongPtr (hWnd, GWL_EXSTYLE);
+  dwStyle = GetWindowLongPtr (hWnd, GWL_STYLE);
+
+  /* Get the X and Y location of the X window */
+  iX = pWin->drawable.x + GetSystemMetrics (SM_XVIRTUALSCREEN);
+  iY = pWin->drawable.y + GetSystemMetrics (SM_YVIRTUALSCREEN);
+
+  /* Get the height and width of the X window */
+  iWidth = pWin->drawable.width;
+  iHeight = pWin->drawable.height;
+
+  /* Store the origin, height, and width in a rectangle structure */
+  SetRect (&rcNew, iX, iY, iX + iWidth, iY + iHeight);
+
+#if CYGMULTIWINDOW_DEBUG
+  lpRc = &rcNew;
+  ErrorF ("winPositionWindowMultiWindow - (%d ms)drawable (%d, %d)-(%d, %d)\n",
+	  GetTickCount (), lpRc->left, lpRc->top, lpRc->right, lpRc->bottom);
+#endif
+
+  /*
+   * Calculate the required size of the Windows window rectangle,
+   * given the size of the Windows window client area.
+   */
+  AdjustWindowRectEx (&rcNew, dwStyle, FALSE, dwExStyle);
+
+  /* Get a rectangle describing the old Windows window */
+  GetWindowRect (hWnd, &rcOld);
+
+#if CYGMULTIWINDOW_DEBUG
+  /* Get a rectangle describing the Windows window client area */
+  GetClientRect (hWnd, &rcClient);
+
+  lpRc = &rcNew;
+  ErrorF ("winPositionWindowMultiWindow - (%d ms)rcNew (%d, %d)-(%d, %d)\n",
+	  GetTickCount (), lpRc->left, lpRc->top, lpRc->right, lpRc->bottom);
+      
+  lpRc = &rcOld;
+  ErrorF ("winPositionWindowMultiWindow - (%d ms)rcOld (%d, %d)-(%d, %d)\n",
+	  GetTickCount (), lpRc->left, lpRc->top, lpRc->right, lpRc->bottom);
+      
+  lpRc = &rcClient;
+  ErrorF ("(%d ms)rcClient (%d, %d)-(%d, %d)\n",
+	  GetTickCount (), lpRc->left, lpRc->top, lpRc->right, lpRc->bottom);
+#endif
+
+  /* Check if the old rectangle and new rectangle are the same */
+  if (!EqualRect (&rcNew, &rcOld))
+    {
+#if CYGMULTIWINDOW_DEBUG
+      ErrorF ("winPositionWindowMultiWindow - Need to move\n");
+#endif
+
+#if CYGWINDOWING_DEBUG
+      ErrorF ("\tMoveWindow to (%ld, %ld) - %ldx%ld\n", rcNew.left, rcNew.top,
+	      rcNew.right - rcNew.left, rcNew.bottom - rcNew.top);
+#endif
+      /* Change the position and dimensions of the Windows window */
+      MoveWindow (hWnd,
+		  rcNew.left, rcNew.top,
+		  rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
+		  TRUE);
+    }
+  else
+    {
+#if CYGMULTIWINDOW_DEBUG
+      ErrorF ("winPositionWindowMultiWindow - Not need to move\n");
+#endif
+    }
+
+  return fResult;
+}
+
+
+/*
+ * ChangeWindowAttributes - See Porting Layer Definition - p. 37
+ */
+
+Bool
+winChangeWindowAttributesMultiWindow (WindowPtr pWin, unsigned long mask)
+{
+  Bool			fResult = TRUE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winChangeWindowAttributesMultiWindow - pWin: %08x\n", pWin);
+#endif
+  
+  WIN_UNWRAP(ChangeWindowAttributes); 
+  fResult = (*pScreen->ChangeWindowAttributes)(pWin, mask);
+  WIN_WRAP(ChangeWindowAttributes, winChangeWindowAttributesMultiWindow);
+  
+  /*
+   * NOTE: We do not currently need to do anything here.
+   */
+
+  return fResult;
+}
+
+
+/*
+ * UnmapWindow - See Porting Layer Definition - p. 37
+ * Also referred to as UnrealizeWindow
+ */
+
+Bool
+winUnmapWindowMultiWindow (WindowPtr pWin)
+{
+  Bool			fResult = TRUE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winUnmapWindowMultiWindow - pWin: %08x\n", pWin);
+#endif
+  
+  WIN_UNWRAP(UnrealizeWindow); 
+  fResult = (*pScreen->UnrealizeWindow)(pWin);
+  WIN_WRAP(UnrealizeWindow, winUnmapWindowMultiWindow);
+  
+  /* Flag that the window has been killed */
+  pWinPriv->fXKilled = TRUE;
+ 
+  /* Destroy the Windows window associated with this X window */
+  winDestroyWindowsWindow (pWin);
+
+  return fResult;
+}
+
+
+/*
+ * MapWindow - See Porting Layer Definition - p. 37
+ * Also referred to as RealizeWindow
+ */
+
+Bool
+winMapWindowMultiWindow (WindowPtr pWin)
+{
+  Bool			fResult = TRUE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winMapWindowMultiWindow - pWin: %08x\n", pWin);
+#endif
+  
+  WIN_UNWRAP(RealizeWindow); 
+  fResult = (*pScreen->RealizeWindow)(pWin);
+  WIN_WRAP(RealizeWindow, winMapWindowMultiWindow);
+  
+  /* Flag that this window has not been destroyed */
+  pWinPriv->fXKilled = FALSE;
+
+  /* Refresh/redisplay the Windows window associated with this X window */
+  winUpdateWindowsWindow (pWin);
+
+#ifdef SHAPE
+  /* Update the Windows window's shape */
+  winReshapeMultiWindow (pWin);
+  winUpdateRgnMultiWindow (pWin);
+#endif
+
+  return fResult;
+}
+
+
+/*
+ * ReparentWindow - See Porting Layer Definition - p. 42
+ */
+
+void
+winReparentWindowMultiWindow (WindowPtr pWin, WindowPtr pPriorParent)
+{
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winReparentMultiWindow - pWin: %08x\n", pWin);
+#endif
+
+  WIN_UNWRAP(ReparentWindow);
+  if (pScreen->ReparentWindow) 
+    (*pScreen->ReparentWindow)(pWin, pPriorParent);
+  WIN_WRAP(ReparentWindow, winReparentWindowMultiWindow);
+  
+  /* Update the Windows window associated with this X window */
+  winUpdateWindowsWindow (pWin);
+}
+
+
+/*
+ * RestackWindow - Shuffle the z-order of a window
+ */
+
+void
+winRestackWindowMultiWindow (WindowPtr pWin, WindowPtr pOldNextSib)
+{
+  WindowPtr		pPrevWin;
+  UINT			uFlags;
+  HWND			hInsertAfter;
+  HWND                  hWnd = NULL;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGMULTIWINDOW_DEBUG || CYGWINDOWING_DEBUG
+  winTrace ("winRestackMultiWindow - %08x\n", pWin);
+#endif
+  
+   WIN_UNWRAP(RestackWindow);
+   if (pScreen->RestackWindow) 
+     (*pScreen->RestackWindow)(pWin, pOldNextSib);
+   WIN_WRAP(RestackWindow, winRestackWindowMultiWindow);
+  
+#if 1
+  /*
+   * Calling winReorderWindowsMultiWindow here means our window manager
+   * (i.e. Windows Explorer) has initiative to determine Z order.
+   */
+  if (pWin->nextSib != pOldNextSib)
+    winReorderWindowsMultiWindow ();
+#else
+  /* Bail out if no window privates or window handle is invalid */
+  if (!pWinPriv || !pWinPriv->hWnd)
+    return;
+
+  /* Get a pointer to our previous sibling window */
+  pPrevWin = pWin->prevSib;
+
+  /*
+   * Look for a sibling window with
+   * valid privates and window handle
+   */
+  while (pPrevWin
+	 && !winGetWindowPriv(pPrevWin)
+	 && !winGetWindowPriv(pPrevWin)->hWnd)
+    pPrevWin = pPrevWin->prevSib;
+      
+  /* Check if we found a valid sibling */
+  if (pPrevWin)
+    {
+      /* Valid sibling - get handle to insert window after */
+      hInsertAfter = winGetWindowPriv(pPrevWin)->hWnd;
+      uFlags = SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE;
+  
+      hWnd = GetNextWindow (pWinPriv->hWnd, GW_HWNDPREV);
+
+      do
+	{
+	  if (GetProp (hWnd, WIN_WINDOW_PROP))
+	    {
+	      if (hWnd == winGetWindowPriv(pPrevWin)->hWnd)
+		{
+		  uFlags |= SWP_NOZORDER;
+		}
+	      break;
+	    }
+	  hWnd = GetNextWindow (hWnd, GW_HWNDPREV);
+	}
+      while (hWnd);
+    }
+  else
+    {
+      /* No valid sibling - make this window the top window */
+      hInsertAfter = HWND_TOP;
+      uFlags = SWP_NOMOVE | SWP_NOSIZE;
+    }
+      
+  /* Perform the restacking operation in Windows */
+  SetWindowPos (pWinPriv->hWnd,
+		hInsertAfter,
+		0, 0,
+		0, 0,
+		uFlags);
+#endif
+}
+
+
+/*
+ * winCreateWindowsWindow - Create a Windows window associated with an X window
+ */
+
+void
+winCreateWindowsWindow (WindowPtr pWin)
+{
+  int                   iX, iY;
+  int			iWidth;
+  int			iHeight;
+  HWND			hWnd;
+  WNDCLASSEX		wc;
+  winWindowPriv(pWin);
+  HICON			hIcon;
+  HICON			hIconSmall;
+#define CLASS_NAME_LENGTH 512
+  char                  pszClass[CLASS_NAME_LENGTH], pszWindowID[12];
+  char                  *res_name, *res_class, *res_role;
+  static int		s_iWindowID = 0;
+  winPrivScreenPtr	pScreenPriv = pWinPriv->pScreenPriv;
+  WinXSizeHints         hints;
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winCreateWindowsWindow - pWin: %08x\n", pWin);
+#endif
+
+  iX = pWin->drawable.x + GetSystemMetrics (SM_XVIRTUALSCREEN);
+  iY = pWin->drawable.y + GetSystemMetrics (SM_YVIRTUALSCREEN);
+
+  /* Default positions if none specified */
+  if (!winMultiWindowGetWMNormalHints(pWin, &hints))
+    hints.flags = 0;
+  if ( !(hints.flags & (USPosition|PPosition)) &&
+       !winMultiWindowGetTransientFor (pWin, NULL) &&
+       !pWin->overrideRedirect )
+    {
+      iX = CW_USEDEFAULT;
+      iY = CW_USEDEFAULT;
+    }
+
+  iWidth = pWin->drawable.width;
+  iHeight = pWin->drawable.height;
+
+  winSelectIcons(pWin, &hIcon, &hIconSmall); 
+
+  /* Set standard class name prefix so we can identify window easily */
+  strncpy (pszClass, WINDOW_CLASS_X, sizeof(pszClass));
+
+  if (winMultiWindowGetClassHint (pWin, &res_name, &res_class))
+    {
+      strncat (pszClass, "-", 1);
+      strncat (pszClass, res_name, CLASS_NAME_LENGTH - strlen (pszClass));
+      strncat (pszClass, "-", 1);
+      strncat (pszClass, res_class, CLASS_NAME_LENGTH - strlen (pszClass));
+      
+      /* Check if a window class is provided by the WM_WINDOW_ROLE property,
+       * if not use the WM_CLASS information.
+       * For further information see:
+       * http://tronche.com/gui/x/icccm/sec-5.html
+       */ 
+      if (winMultiWindowGetWindowRole (pWin, &res_role) )
+	{
+	  strcat (pszClass, "-");
+	  strcat (pszClass, res_role);
+	  free (res_role);
+	}
+
+      free (res_name);
+      free (res_class);
+    }
+
+  /* Add incrementing window ID to make unique class name */
+  snprintf (pszWindowID, sizeof(pszWindowID), "-%x", s_iWindowID++);
+  pszWindowID[sizeof(pszWindowID)-1] = 0;
+  strcat (pszClass, pszWindowID);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winCreateWindowsWindow - Creating class: %s\n", pszClass);
+#endif
+
+  /* Setup our window class */
+  wc.cbSize = sizeof(wc);
+  wc.style = CS_HREDRAW | CS_VREDRAW;
+  wc.lpfnWndProc = winTopLevelWindowProc;
+  wc.cbClsExtra = 0;
+  wc.cbWndExtra = 0;
+  wc.hInstance = g_hInstance;
+  wc.hIcon = hIcon;
+  wc.hIconSm = hIconSmall;
+  wc.hCursor = 0;
+  wc.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
+  wc.lpszMenuName = NULL;
+  wc.lpszClassName = pszClass;
+  RegisterClassEx (&wc);
+
+  /* Create the window */
+  /* Make it OVERLAPPED in create call since WS_POPUP doesn't support */
+  /* CW_USEDEFAULT, change back to popup after creation */
+  hWnd = CreateWindowExA (WS_EX_TOOLWINDOW,	/* Extended styles */
+			  pszClass,		/* Class name */
+			  WINDOW_TITLE_X,	/* Window name */
+			  WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
+			  iX,			/* Horizontal position */
+			  iY,			/* Vertical position */
+			  iWidth,		/* Right edge */ 
+			  iHeight,		/* Bottom edge */
+			  (HWND) NULL,		/* No parent or owner window */
+			  (HMENU) NULL,		/* No menu */
+			  GetModuleHandle (NULL), /* Instance handle */
+			  pWin);		/* ScreenPrivates */
+  if (hWnd == NULL)
+    {
+      ErrorF ("winCreateWindowsWindow - CreateWindowExA () failed: %d\n",
+	      (int) GetLastError ());
+    }
+ 
+  /* Change style back to popup, already placed... */
+  SetWindowLong (hWnd, GWL_STYLE, WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
+  SetWindowPos (hWnd, 0, 0, 0, 0, 0,
+		SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
+  /* Make sure it gets the proper system menu for a WS_POPUP, too */
+  GetSystemMenu (hWnd, TRUE);
+
+  pWinPriv->hWnd = hWnd;
+
+  /* Cause any .XWinrc menus to be added in main WNDPROC */
+  PostMessage (hWnd, WM_INIT_SYS_MENU, 0, 0);
+  
+  SetProp (pWinPriv->hWnd, WIN_WID_PROP, (HANDLE) winGetWindowID(pWin));
+
+  /* Flag that this Windows window handles its own activation */
+  SetProp (pWinPriv->hWnd, WIN_NEEDMANAGE_PROP, (HANDLE) 0);
+
+  /* Call engine-specific create window procedure */
+  (*pScreenPriv->pwinFinishCreateWindowsWindow) (pWin);
+}
+
+
+Bool winInDestroyWindowsWindow = FALSE;
+/*
+ * winDestroyWindowsWindow - Destroy a Windows window associated
+ * with an X window
+ */
+static void
+winDestroyWindowsWindow (WindowPtr pWin)
+{
+  MSG			msg;
+  winWindowPriv(pWin);
+  HICON			hiconClass;
+  HICON			hiconSmClass;
+  HMODULE		hInstance;
+  int			iReturn;
+  char			pszClass[512];
+  BOOL			oldstate = winInDestroyWindowsWindow;
+  
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winDestroyWindowsWindow\n");
+#endif
+
+  /* Bail out if the Windows window handle is invalid */
+  if (pWinPriv->hWnd == NULL)
+    return;
+
+  winInDestroyWindowsWindow = TRUE;
+
+  /* Store the info we need to destroy after this window is gone */
+  hInstance = (HINSTANCE) GetClassLong (pWinPriv->hWnd, GCL_HMODULE);
+  hiconClass = (HICON) GetClassLong (pWinPriv->hWnd, GCL_HICON);
+  hiconSmClass = (HICON) GetClassLong (pWinPriv->hWnd, GCL_HICONSM);
+  iReturn = GetClassName (pWinPriv->hWnd, pszClass, 512);
+  
+  SetProp (pWinPriv->hWnd, WIN_WINDOW_PROP, NULL);
+  /* Destroy the Windows window */
+  DestroyWindow (pWinPriv->hWnd);
+
+  /* Null our handle to the Window so referencing it will cause an error */
+  pWinPriv->hWnd = NULL;
+
+  /* Process all messages on our queue */
+  while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
+    {
+      if (g_hDlgDepthChange == 0 || !IsDialogMessage (g_hDlgDepthChange, &msg))
+	{
+	  DispatchMessage (&msg);
+	}
+    }
+
+  /* Only if we were able to get the name */
+  if (iReturn)
+    { 
+#if CYGMULTIWINDOW_DEBUG
+      ErrorF ("winDestroyWindowsWindow - Unregistering %s: ", pszClass);
+#endif
+      iReturn = UnregisterClass (pszClass, hInstance);
+      
+#if CYGMULTIWINDOW_DEBUG
+      ErrorF ("winDestroyWindowsWindow - %d Deleting Icon: ", iReturn);
+#endif
+      
+      winDestroyIcon(hiconClass);
+      winDestroyIcon(hiconSmClass);
+    }
+
+  winInDestroyWindowsWindow = oldstate;
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("-winDestroyWindowsWindow\n");
+#endif
+}
+
+
+/*
+ * winUpdateWindowsWindow - Redisplay/redraw a Windows window
+ * associated with an X window
+ */
+
+static void
+winUpdateWindowsWindow (WindowPtr pWin)
+{
+  winWindowPriv(pWin);
+  HWND			hWnd = pWinPriv->hWnd;
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winUpdateWindowsWindow\n");
+#endif
+
+  /* Check if the Windows window's parents have been destroyed */
+  if (pWin->parent != NULL
+      && pWin->parent->parent == NULL
+      && pWin->mapped)
+    {
+      /* Create the Windows window if it has been destroyed */
+      if (hWnd == NULL)
+	{
+	  winCreateWindowsWindow (pWin);
+	  assert (pWinPriv->hWnd != NULL);
+	}
+
+      /* Display the window without activating it */
+      ShowWindow (pWinPriv->hWnd, SW_SHOWNOACTIVATE);
+
+      /* Send first paint message */
+      UpdateWindow (pWinPriv->hWnd);
+    }
+  else if (hWnd != NULL)
+    {
+      /* Destroy the Windows window if its parents are destroyed */
+      winDestroyWindowsWindow (pWin);
+      assert (pWinPriv->hWnd == NULL);
+    }
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("-winUpdateWindowsWindow\n");
+#endif
+}
+
+
+/*
+ * winGetWindowID - 
+ */
+
+XID
+winGetWindowID (WindowPtr pWin)
+{
+  WindowIDPairRec	wi = {pWin, 0};
+  ClientPtr		c = wClient(pWin);
+  
+  /* */
+  FindClientResourcesByType (c, RT_WINDOW, winFindWindow, &wi);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winGetWindowID - Window ID: %d\n", wi.id);
+#endif
+
+  return wi.id;
+}
+
+
+/*
+ * winFindWindow - 
+ */
+
+static void
+winFindWindow (pointer value, XID id, pointer cdata)
+{
+  WindowIDPairPtr	wi = (WindowIDPairPtr)cdata;
+
+  if (value == wi->value)
+    {
+      wi->id = id;
+    }
+}
+
+
+/*
+ * winReorderWindowsMultiWindow - 
+ */
+
+void
+winReorderWindowsMultiWindow (void)
+{
+  HWND hwnd = NULL;
+  WindowPtr pWin = NULL;
+  WindowPtr pWinSib = NULL;
+  XID vlist[2];
+  static Bool fRestacking = FALSE; /* Avoid recusive calls to this function */
+  DWORD dwCurrentProcessID = GetCurrentProcessId ();
+  DWORD dwWindowProcessID = 0;
+
+#if CYGMULTIWINDOW_DEBUG || CYGWINDOWING_DEBUG
+  winTrace ("winReorderWindowsMultiWindow\n");
+#endif
+
+  if (fRestacking)
+    {
+      /* It is a recusive call so immediately exit */
+#if CYGWINDOWING_DEBUG
+      ErrorF ("winReorderWindowsMultiWindow - "
+	      "exit because fRestacking == TRUE\n");
+#endif
+      return;
+    }
+  fRestacking = TRUE;
+
+  /* Loop through top level Window windows, descending in Z order */
+  for ( hwnd = GetTopWindow (NULL);
+	hwnd;
+	hwnd = GetNextWindow (hwnd, GW_HWNDNEXT) )
+    {
+      /* Don't take care of other Cygwin/X process's windows */
+      GetWindowThreadProcessId (hwnd, &dwWindowProcessID);
+
+      if ( GetProp (hwnd, WIN_WINDOW_PROP)
+	   && (dwWindowProcessID == dwCurrentProcessID)
+	   && !IsIconic (hwnd) ) /* ignore minimized windows */
+	{
+	  pWinSib = pWin;
+	  pWin = GetProp (hwnd, WIN_WINDOW_PROP);
+	      
+	  if (!pWinSib)
+	    { /* 1st window - raise to the top */
+	      vlist[0] = Above;
+		  
+	      ConfigureWindow (pWin, CWStackMode, vlist, wClient(pWin));
+	    }
+	  else
+	    { /* 2nd or deeper windows - just below the previous one */
+	      vlist[0] = winGetWindowID (pWinSib);
+	      vlist[1] = Below;
+
+	      ConfigureWindow (pWin, CWSibling | CWStackMode,
+			       vlist, wClient(pWin));
+	    }
+	}
+    }
+
+  fRestacking = FALSE;
+}
+
+
+/*
+ * winMinimizeWindow - Minimize in response to WM_CHANGE_STATE
+ */
+
+void
+winMinimizeWindow (Window id)
+{
+  WindowPtr		pWin;
+  winPrivWinPtr	pWinPriv;
+#ifdef XWIN_MULTIWINDOWEXTWM
+  win32RootlessWindowPtr pRLWinPriv;
+#endif
+  HWND hWnd;
+  ScreenPtr pScreen = NULL;
+  winPrivScreenPtr pScreenPriv = NULL;
+  winScreenInfo *pScreenInfo = NULL;
+
+#if CYGWINDOWING_DEBUG
+  ErrorF ("winMinimizeWindow\n");
+#endif
+
+  pWin = LookupIDByType (id, RT_WINDOW);
+  if (!pWin) 
+  { 
+      ErrorF("%s: NULL pWin. Leaving\n", __FUNCTION__); 
+      return; 
+  }
+
+  pScreen = pWin->drawable.pScreen;
+  if (pScreen) pScreenPriv = winGetScreenPriv(pScreen);
+  if (pScreenPriv) pScreenInfo = pScreenPriv->pScreenInfo;
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  if (pScreenPriv && pScreenInfo->fInternalWM)
+    {
+      pRLWinPriv  = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, FALSE);
+      hWnd = pRLWinPriv->hWnd;
+    }
+  else
+#else
+  if (pScreenPriv)
+#endif
+    {
+      pWinPriv = winGetWindowPriv (pWin);
+      hWnd = pWinPriv->hWnd;
+    }
+
+  ShowWindow (hWnd, SW_MINIMIZE);
+}
+
+
+/*
+ * CopyWindow - See Porting Layer Definition - p. 39
+ */
+void
+winCopyWindowMultiWindow (WindowPtr pWin, DDXPointRec oldpt,
+			  RegionPtr oldRegion)
+{
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGWINDOWING_DEBUG
+  ErrorF ("CopyWindowMultiWindow\n");
+#endif
+  WIN_UNWRAP(CopyWindow); 
+  (*pScreen->CopyWindow)(pWin, oldpt, oldRegion);
+  WIN_WRAP(CopyWindow, winCopyWindowMultiWindow);
+}
+
+
+/*
+ * MoveWindow - See Porting Layer Definition - p. 42
+ */
+void
+winMoveWindowMultiWindow (WindowPtr pWin, int x, int y,
+			  WindowPtr pSib, VTKind kind)
+{
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGWINDOWING_DEBUG
+  ErrorF ("MoveWindowMultiWindow to (%d, %d)\n", x, y);
+#endif
+
+  WIN_UNWRAP(MoveWindow); 
+  (*pScreen->MoveWindow)(pWin, x, y, pSib, kind);
+  WIN_WRAP(MoveWindow, winMoveWindowMultiWindow);
+}
+
+
+/*
+ * ResizeWindow - See Porting Layer Definition - p. 42
+ */
+void
+winResizeWindowMultiWindow (WindowPtr pWin, int x, int y, unsigned int w,
+			    unsigned int h, WindowPtr pSib)
+{
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGWINDOWING_DEBUG
+  ErrorF ("ResizeWindowMultiWindow to (%d, %d) - %dx%d\n", x, y, w, h);
+#endif
+  WIN_UNWRAP(ResizeWindow); 
+  (*pScreen->ResizeWindow)(pWin, x, y, w, h, pSib);
+  WIN_WRAP(ResizeWindow, winResizeWindowMultiWindow);
+}
+
+
+/*
+ * winAdjustXWindow
+ *
+ * Move and resize X window with respect to corresponding Windows window.
+ * This is called from WM_MOVE/WM_SIZE handlers when the user performs
+ * any windowing operation (move, resize, minimize, maximize, restore).
+ *
+ * The functionality is the inverse of winPositionWindowMultiWindow, which
+ * adjusts Windows window with respect to X window.
+ */
+int
+winAdjustXWindow (WindowPtr pWin, HWND hwnd)
+{
+  RECT rcDraw; /* Rect made from pWin->drawable to be adjusted */
+  RECT rcWin;  /* The source: WindowRect from hwnd */
+  DrawablePtr pDraw;
+  XID vlist[4];
+  LONG dX, dY, dW, dH, x, y;
+  DWORD dwStyle, dwExStyle;
+
+#define WIDTH(rc) (rc.right - rc.left)
+#define HEIGHT(rc) (rc.bottom - rc.top)
+  
+#if CYGWINDOWING_DEBUG
+  ErrorF ("winAdjustXWindow\n");
+#endif
+
+  if (IsIconic (hwnd))
+    {
+#if CYGWINDOWING_DEBUG
+      ErrorF ("\timmediately return because the window is iconized\n");
+#endif
+      /*
+       * If the Windows window is minimized, its WindowRect has
+       * meaningless values so we don't adjust X window to it.
+       */
+      vlist[0] = 0;
+      vlist[1] = 0;
+      return ConfigureWindow (pWin, CWX | CWY, vlist, wClient(pWin));
+    }
+  
+  pDraw = &pWin->drawable;
+
+  /* Calculate the window rect from the drawable */
+  x = pDraw->x + GetSystemMetrics (SM_XVIRTUALSCREEN);
+  y = pDraw->y + GetSystemMetrics (SM_YVIRTUALSCREEN);
+  SetRect (&rcDraw, x, y, x + pDraw->width, y + pDraw->height);
+#ifdef CYGMULTIWINDOW_DEBUG
+          winDebug("\tDrawable extend {%d, %d, %d, %d}, {%d, %d}\n", 
+              rcDraw.left, rcDraw.top, rcDraw.right, rcDraw.bottom,
+              rcDraw.right - rcDraw.left, rcDraw.bottom - rcDraw.top);
+#endif
+  dwExStyle = GetWindowLongPtr (hwnd, GWL_EXSTYLE);
+  dwStyle = GetWindowLongPtr (hwnd, GWL_STYLE);
+#ifdef CYGMULTIWINDOW_DEBUG
+          winDebug("\tWindowStyle: %08x %08x\n", dwStyle, dwExStyle);
+#endif
+  AdjustWindowRectEx (&rcDraw, dwStyle, FALSE, dwExStyle);
+
+  /* The source of adjust */
+  GetWindowRect (hwnd, &rcWin);
+#ifdef CYGMULTIWINDOW_DEBUG
+          winDebug("\tWindow extend {%d, %d, %d, %d}, {%d, %d}\n", 
+              rcWin.left, rcWin.top, rcWin.right, rcWin.bottom,
+              rcWin.right - rcWin.left, rcWin.bottom - rcWin.top);
+          winDebug("\tDraw extend {%d, %d, %d, %d}, {%d, %d}\n", 
+              rcDraw.left, rcDraw.top, rcDraw.right, rcDraw.bottom,
+              rcDraw.right - rcDraw.left, rcDraw.bottom - rcDraw.top);
+#endif
+
+  if (EqualRect (&rcDraw, &rcWin)) {
+    /* Bail if no adjust is needed */
+#if CYGWINDOWING_DEBUG
+    ErrorF ("\treturn because already adjusted\n");
+#endif
+    return 0;
+  }
+  
+  /* Calculate delta values */
+  dX = rcWin.left - rcDraw.left;
+  dY = rcWin.top - rcDraw.top;
+  dW = WIDTH(rcWin) - WIDTH(rcDraw);
+  dH = HEIGHT(rcWin) - HEIGHT(rcDraw);
+
+  /*
+   * Adjust.
+   * We may only need to move (vlist[0] and [1]), or only resize
+   * ([2] and [3]) but currently we set all the parameters and leave
+   * the decision to ConfigureWindow.  The reason is code simplicity.
+  */
+  vlist[0] = pDraw->x + dX - wBorderWidth(pWin);
+  vlist[1] = pDraw->y + dY - wBorderWidth(pWin);
+  vlist[2] = pDraw->width + dW;
+  vlist[3] = pDraw->height + dH;
+#if CYGWINDOWING_DEBUG
+  ErrorF ("\tConfigureWindow to (%ld, %ld) - %ldx%ld\n", vlist[0], vlist[1],
+	  vlist[2], vlist[3]);
+#endif
+  return ConfigureWindow (pWin, CWX | CWY | CWWidth | CWHeight,
+			  vlist, wClient(pWin));
+  
+#undef WIDTH
+#undef HEIGHT
+}
+
diff --git a/hw/xwin/winmultiwindowwm.c b/hw/xwin/winmultiwindowwm.c
new file mode 100644
index 0000000..5401ecd
--- /dev/null
+++ b/hw/xwin/winmultiwindowwm.c
@@ -0,0 +1,1440 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Kensuke Matsuzaki
+ */
+
+/* X headers */
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#ifdef __CYGWIN__
+#include <sys/select.h>
+#endif
+#include <fcntl.h>
+#include <setjmp.h>
+#define HANDLE void *
+#include <pthread.h>
+#undef HANDLE
+#include <X11/X.h>
+#include <X11/Xatom.h>
+#include <X11/Xlib.h>
+#include <X11/Xlocale.h>
+#include <X11/Xproto.h>
+#include <X11/Xutil.h>
+#include <X11/cursorfont.h>
+
+/* Windows headers */
+#ifdef __CYGWIN__
+/* Fixups to prevent collisions between Windows and X headers */
+#define ATOM DWORD
+
+#include <windows.h>
+#else
+#include <Xwindows.h>
+#endif
+
+/* Local headers */
+#include "objbase.h"
+#include "ddraw.h"
+#include "winwindow.h"
+#ifdef XWIN_MULTIWINDOWEXTWM
+#include "windowswmstr.h"
+#endif
+
+extern void winDebug(const char *format, ...);
+
+#ifndef CYGDEBUG
+#define CYGDEBUG NO
+#endif
+
+/*
+ * Constant defines
+ */
+
+#define WIN_CONNECT_RETRIES	5
+#define WIN_CONNECT_DELAY	5
+#ifdef HAS_DEVWINDOWS
+# define WIN_MSG_QUEUE_FNAME	"/dev/windows"
+#endif
+#define WIN_JMP_OKAY		0
+#define WIN_JMP_ERROR_IO	2
+
+
+/*
+ * Local structures
+ */
+
+typedef struct _WMMsgNodeRec {
+  winWMMessageRec	msg;
+  struct _WMMsgNodeRec	*pNext;
+} WMMsgNodeRec, *WMMsgNodePtr;
+
+typedef struct _WMMsgQueueRec {
+  struct _WMMsgNodeRec	*pHead;
+  struct _WMMsgNodeRec	*pTail;
+  pthread_mutex_t	pmMutex;
+  pthread_cond_t	pcNotEmpty;
+  int			nQueueSize;
+} WMMsgQueueRec, *WMMsgQueuePtr;
+
+typedef struct _WMInfo {
+  Display		*pDisplay;
+  WMMsgQueueRec		wmMsgQueue;
+  Atom			atmWmProtos;
+  Atom			atmWmDelete;
+  Atom			atmPrivMap;
+  Bool			fAllowOtherWM;
+} WMInfoRec, *WMInfoPtr;
+
+typedef struct _WMProcArgRec {
+  DWORD			dwScreen;
+  WMInfoPtr		pWMInfo;
+  pthread_mutex_t	*ppmServerStarted;
+} WMProcArgRec, *WMProcArgPtr;
+
+typedef struct _XMsgProcArgRec {
+  Display		*pDisplay;
+  DWORD			dwScreen;
+  WMInfoPtr		pWMInfo;
+  pthread_mutex_t	*ppmServerStarted;
+  HWND			hwndScreen;
+} XMsgProcArgRec, *XMsgProcArgPtr;
+
+
+/*
+ * References to external symbols
+ */
+
+extern char *display;
+extern void ErrorF (const char* /*f*/, ...);
+
+
+/*
+ * Prototypes for local functions
+ */
+
+static void
+PushMessage (WMMsgQueuePtr pQueue, WMMsgNodePtr pNode);
+
+static WMMsgNodePtr
+PopMessage (WMMsgQueuePtr pQueue, WMInfoPtr pWMInfo);
+
+static Bool
+InitQueue (WMMsgQueuePtr pQueue);
+
+static void
+GetWindowName (Display * pDpy, Window iWin, char **ppName);
+
+static int
+SendXMessage (Display *pDisplay, Window iWin, Atom atmType, long nData);
+
+static void
+UpdateName (WMInfoPtr pWMInfo, Window iWindow);
+
+static void*
+winMultiWindowWMProc (void* pArg);
+
+static int
+winMultiWindowWMErrorHandler (Display *pDisplay, XErrorEvent *pErr);
+
+static int
+winMultiWindowWMIOErrorHandler (Display *pDisplay);
+
+static void *
+winMultiWindowXMsgProc (void *pArg);
+
+static int
+winMultiWindowXMsgProcErrorHandler (Display *pDisplay, XErrorEvent *pErr);
+
+static int
+winMultiWindowXMsgProcIOErrorHandler (Display *pDisplay);
+
+static int
+winRedirectErrorHandler (Display *pDisplay, XErrorEvent *pErr);
+
+static void
+winInitMultiWindowWM (WMInfoPtr pWMInfo, WMProcArgPtr pProcArg);
+
+#if 0
+static void
+PreserveWin32Stack(WMInfoPtr pWMInfo, Window iWindow, UINT direction);
+#endif
+
+static Bool
+CheckAnotherWindowManager (Display *pDisplay, DWORD dwScreen);
+
+
+/*
+ * Local globals
+ */
+
+static jmp_buf			g_jmpWMEntry;
+static jmp_buf			g_jmpXMsgProcEntry;
+static Bool			g_shutdown = FALSE;
+static Bool			redirectError = FALSE;
+static Bool			g_fAnotherWMRunnig = FALSE;
+
+/*
+ * PushMessage - Push a message onto the queue
+ */
+
+static void
+PushMessage (WMMsgQueuePtr pQueue, WMMsgNodePtr pNode)
+{
+
+  /* Lock the queue mutex */
+  pthread_mutex_lock (&pQueue->pmMutex);
+
+  pNode->pNext = NULL;
+  
+  if (pQueue->pTail != NULL)
+    {
+      pQueue->pTail->pNext = pNode;
+    }
+  pQueue->pTail = pNode;
+  
+  if (pQueue->pHead == NULL)
+    {
+      pQueue->pHead = pNode;
+    }
+
+
+#if 0
+  switch (pNode->msg.msg)
+    {
+    case WM_WM_MOVE:
+      ErrorF ("\tWM_WM_MOVE\n");
+      break;
+    case WM_WM_SIZE:
+      ErrorF ("\tWM_WM_SIZE\n");
+      break;
+    case WM_WM_RAISE:
+      ErrorF ("\tWM_WM_RAISE\n");
+      break;
+    case WM_WM_LOWER:
+      ErrorF ("\tWM_WM_LOWER\n");
+      break;
+    case WM_WM_MAP:
+      ErrorF ("\tWM_WM_MAP\n");
+      break;
+    case WM_WM_UNMAP:
+      ErrorF ("\tWM_WM_UNMAP\n");
+      break;
+    case WM_WM_KILL:
+      ErrorF ("\tWM_WM_KILL\n");
+      break;
+    case WM_WM_ACTIVATE:
+      ErrorF ("\tWM_WM_ACTIVATE\n");
+      break;
+    default:
+      ErrorF ("\tUnknown Message.\n");
+      break;
+    }
+#endif
+
+  /* Increase the count of elements in the queue by one */
+  ++(pQueue->nQueueSize);
+
+  /* Release the queue mutex */
+  pthread_mutex_unlock (&pQueue->pmMutex);
+
+  /* Signal that the queue is not empty */
+  pthread_cond_signal (&pQueue->pcNotEmpty);
+}
+
+
+#if CYGMULTIWINDOW_DEBUG
+/*
+ * QueueSize - Return the size of the queue
+ */
+
+static int
+QueueSize (WMMsgQueuePtr pQueue)
+{
+  WMMsgNodePtr		pNode;
+  int			nSize = 0;
+  
+  /* Loop through all elements in the queue */
+  for (pNode = pQueue->pHead; pNode != NULL; pNode = pNode->pNext)
+    ++nSize;
+
+  return nSize;
+}
+#endif
+
+
+/*
+ * PopMessage - Pop a message from the queue
+ */
+
+static WMMsgNodePtr
+PopMessage (WMMsgQueuePtr pQueue, WMInfoPtr pWMInfo)
+{
+  WMMsgNodePtr		pNode;
+
+  /* Lock the queue mutex */
+  pthread_mutex_lock (&pQueue->pmMutex);
+
+  /* Wait for --- */
+  while (pQueue->pHead == NULL)
+    {
+      pthread_cond_wait (&pQueue->pcNotEmpty, &pQueue->pmMutex);
+    }
+  
+  pNode = pQueue->pHead;
+  if (pQueue->pHead != NULL)
+    {
+      pQueue->pHead = pQueue->pHead->pNext;
+    }
+
+  if (pQueue->pTail == pNode)
+    {
+      pQueue->pTail = NULL;
+    }
+
+  /* Drop the number of elements in the queue by one */
+  --(pQueue->nQueueSize);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("Queue Size %d %d\n", pQueue->nQueueSize, QueueSize(pQueue));
+#endif
+  
+  /* Release the queue mutex */
+  pthread_mutex_unlock (&pQueue->pmMutex);
+
+  return pNode;
+}
+
+
+#if 0
+/*
+ * HaveMessage - 
+ */
+
+static Bool
+HaveMessage (WMMsgQueuePtr pQueue, UINT msg, Window iWindow)
+{
+  WMMsgNodePtr pNode;
+  
+  for (pNode = pQueue->pHead; pNode != NULL; pNode = pNode->pNext)
+    {
+      if (pNode->msg.msg==msg && pNode->msg.iWindow==iWindow)
+	return True;
+    }
+  
+  return False;
+}
+#endif
+
+
+/*
+ * InitQueue - Initialize the Window Manager message queue
+ */
+
+static
+Bool
+InitQueue (WMMsgQueuePtr pQueue)
+{
+  /* Check if the pQueue pointer is NULL */
+  if (pQueue == NULL)
+    {
+      ErrorF ("InitQueue - pQueue is NULL.  Exiting.\n");
+      return FALSE;
+    }
+
+  /* Set the head and tail to NULL */
+  pQueue->pHead = NULL;
+  pQueue->pTail = NULL;
+
+  /* There are no elements initially */
+  pQueue->nQueueSize = 0;
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("InitQueue - Queue Size %d %d\n", pQueue->nQueueSize,
+	  QueueSize(pQueue));
+#endif
+
+  ErrorF ("InitQueue - Calling pthread_mutex_init\n");
+
+  /* Create synchronization objects */
+  pthread_mutex_init (&pQueue->pmMutex, NULL);
+
+  ErrorF ("InitQueue - pthread_mutex_init returned\n");
+  ErrorF ("InitQueue - Calling pthread_cond_init\n");
+
+  pthread_cond_init (&pQueue->pcNotEmpty, NULL);
+
+  ErrorF ("InitQueue - pthread_cond_init returned\n");
+
+  return TRUE;
+}
+
+
+/*
+ * GetWindowName - Retrieve the title of an X Window
+ */
+
+static void
+GetWindowName (Display *pDisplay, Window iWin, char **ppName)
+{
+  int			nResult, nNum;
+  char			**ppList;
+  XTextProperty		xtpName;
+  
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("GetWindowName\n");
+#endif
+
+  /* Intialize ppName to NULL */
+  *ppName = NULL;
+
+  /* Try to get --- */
+  nResult = XGetWMName (pDisplay, iWin, &xtpName);
+  if (!nResult || !xtpName.value || !xtpName.nitems)
+    {
+#if CYGMULTIWINDOW_DEBUG
+      ErrorF ("GetWindowName - XGetWMName failed.  No name.\n");
+#endif
+      return;
+    }
+  
+  /* */
+  if (xtpName.encoding == XA_STRING)
+    {
+      /* */
+      if (xtpName.value)
+	{
+	  int size = xtpName.nitems * (xtpName.format >> 3);
+	  *ppName = malloc(size + 1);
+	  strncpy(*ppName, xtpName.value, size);
+	  (*ppName)[size] = 0;
+	  XFree (xtpName.value);
+	}
+
+#if CYGMULTIWINDOW_DEBUG
+      ErrorF ("GetWindowName - XA_STRING %s\n", *ppName);
+#endif
+    }
+  else
+    {
+      if (XmbTextPropertyToTextList (pDisplay, &xtpName, &ppList, &nNum) >= Success && nNum > 0 && *ppList)
+	{
+	  *ppName = strdup (*ppList);
+	  XFreeStringList (ppList);
+	}
+      XFree (xtpName.value);
+
+#if CYGMULTIWINDOW_DEBUG
+      ErrorF ("GetWindowName - %s %s\n",
+	      XGetAtomName (pDisplay, xtpName.encoding), *ppName);
+#endif
+    }
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("GetWindowName - Returning\n");
+#endif
+}
+
+
+/*
+ * Send a message to the X server from the WM thread
+ */
+
+static int
+SendXMessage (Display *pDisplay, Window iWin, Atom atmType, long nData)
+{
+  XEvent		e;
+
+  /* Prepare the X event structure */
+  e.type = ClientMessage;
+  e.xclient.window = iWin;
+  e.xclient.message_type = atmType;
+  e.xclient.format = 32;
+  e.xclient.data.l[0] = nData;
+  e.xclient.data.l[1] = CurrentTime;
+
+  /* Send the event to X */
+  return XSendEvent (pDisplay, iWin, False, NoEventMask, &e);
+}
+
+
+/*
+ * Updates the name of a HWND according to its X WM_NAME property
+ */
+
+static void
+UpdateName (WMInfoPtr pWMInfo, Window iWindow)
+{
+  char			*pszName;
+  Atom			atmType;
+  int			fmtRet;
+  unsigned long		items, remain;
+  HWND			*retHwnd, hWnd;
+  XWindowAttributes	attr;
+
+  hWnd = 0;
+
+  /* See if we can get the cached HWND for this window... */
+  if (XGetWindowProperty (pWMInfo->pDisplay,
+			  iWindow,
+			  pWMInfo->atmPrivMap,
+			  0,
+			  1,
+			  False,
+			  XA_INTEGER,//pWMInfo->atmPrivMap,
+			  &atmType,
+			  &fmtRet,
+			  &items,
+			  &remain,
+			  (unsigned char **) &retHwnd) == Success)
+    {
+      if (retHwnd)
+	{
+	  hWnd = *retHwnd;
+	  XFree (retHwnd);
+	}
+    }
+  
+  /* Some sanity checks */
+  if (!hWnd) return;
+  if (!IsWindow (hWnd)) return;
+
+  /* Set the Windows window name */
+  GetWindowName (pWMInfo->pDisplay, iWindow, &pszName);
+  if (pszName)
+    {
+      /* Get the window attributes */
+      XGetWindowAttributes (pWMInfo->pDisplay,
+			    iWindow,
+			    &attr);
+      if (!attr.override_redirect)
+	{
+	  SetWindowText (hWnd, pszName);
+	  winUpdateIcon (iWindow);
+	}
+
+      free (pszName);
+    }
+}
+
+
+#if 0
+/*
+ * Fix up any differences between the X11 and Win32 window stacks
+ * starting at the window passed in
+ */
+static void
+PreserveWin32Stack(WMInfoPtr pWMInfo, Window iWindow, UINT direction)
+{
+  Atom                  atmType;
+  int                   fmtRet;
+  unsigned long         items, remain;
+  HWND                  hWnd, *retHwnd;
+  DWORD                 myWinProcID, winProcID;
+  Window                xWindow;
+  WINDOWPLACEMENT       wndPlace;
+  
+  hWnd = NULL;
+  /* See if we can get the cached HWND for this window... */
+  if (XGetWindowProperty (pWMInfo->pDisplay,
+			  iWindow,
+			  pWMInfo->atmPrivMap,
+			  0,
+			  1,
+			  False,
+			  XA_INTEGER,//pWMInfo->atmPrivMap,
+			  &atmType,
+			  &fmtRet,
+			  &items,
+			  &remain,
+			  (unsigned char **) &retHwnd) == Success)
+    {
+      if (retHwnd)
+	{
+	  hWnd = *retHwnd;
+	  XFree (retHwnd);
+	}
+    }
+  
+  if (!hWnd) return;
+  
+  GetWindowThreadProcessId (hWnd, &myWinProcID);
+  hWnd = GetNextWindow (hWnd, direction);
+  
+  while (hWnd) {
+    GetWindowThreadProcessId (hWnd, &winProcID);
+    if (winProcID == myWinProcID)
+      {
+	wndPlace.length = sizeof(WINDOWPLACEMENT);
+	GetWindowPlacement (hWnd, &wndPlace);
+	if ( !(wndPlace.showCmd==SW_HIDE ||
+	       wndPlace.showCmd==SW_MINIMIZE) )
+	  {
+	    xWindow = (Window)GetProp (hWnd, WIN_WID_PROP);
+	    if (xWindow)
+	      {
+		if (direction==GW_HWNDPREV)
+		  XRaiseWindow (pWMInfo->pDisplay, xWindow);
+		else
+		  XLowerWindow (pWMInfo->pDisplay, xWindow);
+	      }
+	  }
+      }
+    hWnd = GetNextWindow(hWnd, direction);
+  }
+}
+#endif /* PreserveWin32Stack */
+
+
+/*
+ * winMultiWindowWMProc
+ */
+
+static void *
+winMultiWindowWMProc (void *pArg)
+{
+  WMProcArgPtr		pProcArg = (WMProcArgPtr)pArg;
+  WMInfoPtr		pWMInfo = pProcArg->pWMInfo;
+  
+  /* Initialize the Window Manager */
+  winInitMultiWindowWM (pWMInfo, pProcArg);
+  
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winMultiWindowWMProc ()\n");
+#endif
+
+  /* Loop until we explicity break out */
+  for (;;)
+    {
+      WMMsgNodePtr	pNode;
+
+      if(g_fAnotherWMRunnig)/* Another Window manager exists. */
+	{
+	  Sleep (1000);
+	  continue;
+	}
+
+      /* Pop a message off of our queue */
+      pNode = PopMessage (&pWMInfo->wmMsgQueue, pWMInfo);
+      if (pNode == NULL)
+	{
+	  /* Bail if PopMessage returns without a message */
+	  /* NOTE: Remember that PopMessage is a blocking function. */
+	  ErrorF ("winMultiWindowWMProc - Queue is Empty?  Exiting.\n");
+	  pthread_exit (NULL);
+	}
+
+#if CYGMULTIWINDOW_DEBUG
+      ErrorF ("winMultiWindowWMProc - %d ms MSG: %d ID: %d\n",
+	      GetTickCount (), (int)pNode->msg.msg, (int)pNode->msg.dwID);
+#endif
+
+      /* Branch on the message type */
+      switch (pNode->msg.msg)
+	{
+#if 0
+	case WM_WM_MOVE:
+	  ErrorF ("\tWM_WM_MOVE\n");
+	  break;
+
+	case WM_WM_SIZE:
+	  ErrorF ("\tWM_WM_SIZE\n");
+	  break;
+#endif
+
+	case WM_WM_RAISE:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_RAISE\n");
+#endif
+	  /* Raise the window */
+	  XRaiseWindow (pWMInfo->pDisplay, pNode->msg.iWindow);
+#if 0
+	  PreserveWin32Stack (pWMInfo, pNode->msg.iWindow, GW_HWNDPREV);
+#endif
+	  break;
+
+	case WM_WM_LOWER:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_LOWER\n");
+#endif
+
+	  /* Lower the window */
+	  XLowerWindow (pWMInfo->pDisplay, pNode->msg.iWindow);
+	  break;
+
+	case WM_WM_MAP:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_MAP\n");
+#endif
+	  /* Put a note as to the HWND associated with this Window */
+	  XChangeProperty (pWMInfo->pDisplay,
+			   pNode->msg.iWindow,
+			   pWMInfo->atmPrivMap,
+			   XA_INTEGER,//pWMInfo->atmPrivMap,
+			   32,
+			   PropModeReplace,
+			   (unsigned char *) &(pNode->msg.hwndWindow),
+			   1);
+	  UpdateName (pWMInfo, pNode->msg.iWindow);
+	  winUpdateIcon (pNode->msg.iWindow);
+#if 0
+	  /* Handles the case where there are AOT windows above it in W32 */
+	  PreserveWin32Stack (pWMInfo, pNode->msg.iWindow, GW_HWNDPREV);
+#endif
+	  break;
+
+	case WM_WM_UNMAP:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_UNMAP\n");
+#endif
+	  
+	  /* Unmap the window */
+	  XUnmapWindow (pWMInfo->pDisplay, pNode->msg.iWindow);
+	  break;
+
+	case WM_WM_KILL:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_KILL\n");
+#endif
+	  {
+	    int				i, n, found = 0;
+	    Atom			*protocols;
+	    
+	    /* --- */
+	    if (XGetWMProtocols (pWMInfo->pDisplay,
+				 pNode->msg.iWindow,
+				 &protocols,
+				 &n))
+	      {
+		for (i = 0; i < n; ++i)
+		  if (protocols[i] == pWMInfo->atmWmDelete)
+		    ++found;
+		
+		XFree (protocols);
+	      }
+
+	    /* --- */
+	    if (found)
+	      SendXMessage (pWMInfo->pDisplay,
+			    pNode->msg.iWindow,
+			    pWMInfo->atmWmProtos,
+			    pWMInfo->atmWmDelete);
+	    else
+	      XKillClient (pWMInfo->pDisplay,
+			   pNode->msg.iWindow);
+	  }
+	  break;
+
+	case WM_WM_ACTIVATE:
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("\tWM_WM_ACTIVATE\n");
+#endif
+	  
+	  /* Set the input focus */
+	  XSetInputFocus (pWMInfo->pDisplay,
+			  pNode->msg.iWindow,
+			  RevertToPointerRoot,
+			  CurrentTime);
+	  break;
+
+	case WM_WM_NAME_EVENT:
+	  UpdateName (pWMInfo, pNode->msg.iWindow);
+	  break;
+
+	case WM_WM_HINTS_EVENT:
+	  winUpdateIcon (pNode->msg.iWindow);
+	  break;
+
+	case WM_WM_CHANGE_STATE:
+	  /* Minimize the window in Windows */
+	  winMinimizeWindow (pNode->msg.iWindow);
+	  break;
+
+	default:
+	  ErrorF ("winMultiWindowWMProc - Unknown Message.  Exiting.\n");
+	  pthread_exit (NULL);
+	  break;
+	}
+
+      /* Free the retrieved message */
+      free (pNode);
+
+      /* Flush any pending events on our display */
+      XFlush (pWMInfo->pDisplay);
+    }
+
+  /* Free the condition variable */
+  pthread_cond_destroy (&pWMInfo->wmMsgQueue.pcNotEmpty);
+  
+  /* Free the mutex variable */
+  pthread_mutex_destroy (&pWMInfo->wmMsgQueue.pmMutex);
+  
+  /* Free the passed-in argument */
+  free (pProcArg);
+  
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF("-winMultiWindowWMProc ()\n");
+#endif
+}
+
+
+/*
+ * X message procedure
+ */
+
+static void *
+winMultiWindowXMsgProc (void *pArg)
+{
+  winWMMessageRec       msg;
+  XMsgProcArgPtr	pProcArg = (XMsgProcArgPtr) pArg;
+  char			pszDisplay[512];
+  int                   iRetries;
+  XEvent		event;
+  Atom                  atmWmName;
+  Atom                  atmWmHints;
+  Atom			atmWmChange;
+  int			iReturn;
+  XIconSize		*xis;
+
+  ErrorF ("winMultiWindowXMsgProc - Hello\n");
+
+  /* Check that argument pointer is not invalid */
+  if (pProcArg == NULL)
+    {
+      ErrorF ("winMultiWindowXMsgProc - pProcArg is NULL.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  ErrorF ("winMultiWindowXMsgProc - Calling pthread_mutex_lock ()\n");
+
+  /* Grab the server started mutex - pause until we get it */
+  iReturn = pthread_mutex_lock (pProcArg->ppmServerStarted);
+  if (iReturn != 0)
+    {
+      ErrorF ("winMultiWindowXMsgProc - pthread_mutex_lock () failed: %d.  "
+	      "Exiting.\n",
+	      iReturn);
+      pthread_exit (NULL);
+    }
+
+  ErrorF ("winMultiWindowXMsgProc - pthread_mutex_lock () returned.\n");
+
+  /* Allow multiple threads to access Xlib */
+  if (XInitThreads () == 0)
+    {
+      ErrorF ("winMultiWindowXMsgProc - XInitThreads () failed.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* See if X supports the current locale */
+  if (XSupportsLocale () == False)
+    {
+      ErrorF ("winMultiWindowXMsgProc - Locale not supported by X.  "
+	      "Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* Release the server started mutex */
+  pthread_mutex_unlock (pProcArg->ppmServerStarted);
+
+  ErrorF ("winMultiWindowXMsgProc - pthread_mutex_unlock () returned.\n");
+
+  /* Set jump point for IO Error exits */
+  iReturn = setjmp (g_jmpXMsgProcEntry);
+  
+  /* Check if we should continue operations */
+  if (iReturn != WIN_JMP_ERROR_IO
+      && iReturn != WIN_JMP_OKAY)
+    {
+      /* setjmp returned an unknown value, exit */
+      ErrorF ("winInitMultiWindowXMsgProc - setjmp returned: %d.  Exiting.\n",
+	      iReturn);
+      pthread_exit (NULL);
+    }
+  else if (iReturn == WIN_JMP_ERROR_IO)
+    {
+      ErrorF ("winInitMultiWindowXMsgProc - Caught IO Error.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* Install our error handler */
+  XSetErrorHandler (winMultiWindowXMsgProcErrorHandler);
+  XSetIOErrorHandler (winMultiWindowXMsgProcIOErrorHandler);
+
+  /* Setup the display connection string x */
+  snprintf (pszDisplay,
+	    512, "127.0.0.1:%s.%d", display, (int)pProcArg->dwScreen);
+
+  /* Print the display connection string */
+  ErrorF ("winMultiWindowXMsgProc - DISPLAY=%s\n", pszDisplay);
+  
+  /* Initialize retry count */
+  iRetries = 0;
+
+  /* Open the X display */
+  do
+    {
+      /* Try to open the display */
+      pProcArg->pDisplay = XOpenDisplay (pszDisplay);
+      if (pProcArg->pDisplay == NULL)
+	{
+	  ErrorF ("winMultiWindowXMsgProc - Could not open display, try: %d, "
+		  "sleeping: %d\n\f",
+		  iRetries + 1, WIN_CONNECT_DELAY);
+	  ++iRetries;
+	  sleep (WIN_CONNECT_DELAY);
+	  continue;
+	}
+      else
+	break;
+    }
+  while (pProcArg->pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
+  
+  /* Make sure that the display opened */
+  if (pProcArg->pDisplay == NULL)
+    {
+      ErrorF ("winMultiWindowXMsgProc - Failed opening the display.  "
+	      "Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  ErrorF ("winMultiWindowXMsgProc - XOpenDisplay () returned and "
+	  "successfully opened the display.\n");
+
+  /* Check if another window manager is already running */
+  if (pProcArg->pWMInfo->fAllowOtherWM)
+  {
+    g_fAnotherWMRunnig = CheckAnotherWindowManager (pProcArg->pDisplay, pProcArg->dwScreen);
+  } else {
+    redirectError = FALSE;
+    XSetErrorHandler (winRedirectErrorHandler); 	 
+    XSelectInput(pProcArg->pDisplay, 	 
+        RootWindow (pProcArg->pDisplay, pProcArg->dwScreen), 	 
+        SubstructureNotifyMask | ButtonPressMask); 	 
+    XSync (pProcArg->pDisplay, 0); 	 
+    XSetErrorHandler (winMultiWindowXMsgProcErrorHandler); 	 
+    if (redirectError) 	 
+    { 	 
+      ErrorF ("winMultiWindowXMsgProc - " 	 
+          "another window manager is running.  Exiting.\n"); 	 
+      pthread_exit (NULL); 	 
+    }
+    g_fAnotherWMRunnig = FALSE;
+  }
+  
+  /* Set up the supported icon sizes */
+  xis = XAllocIconSize ();
+  if (xis)
+    {
+      xis->min_width = xis->min_height = 16;
+      xis->max_width = xis->max_height = 48;
+      xis->width_inc = xis->height_inc = 16;
+      XSetIconSizes (pProcArg->pDisplay,
+		     RootWindow (pProcArg->pDisplay, pProcArg->dwScreen),
+		     xis,
+		     1);
+      XFree (xis);
+    }
+
+  atmWmName   = XInternAtom (pProcArg->pDisplay,
+			     "WM_NAME",
+			     False);
+  atmWmHints   = XInternAtom (pProcArg->pDisplay,
+			      "WM_HINTS",
+			      False);
+  atmWmChange  = XInternAtom (pProcArg->pDisplay,
+			      "WM_CHANGE_STATE",
+			      False);
+
+  /* Loop until we explicitly break out */
+  while (1)
+    {
+      if (g_shutdown)
+        break;
+
+      if (pProcArg->pWMInfo->fAllowOtherWM && !XPending (pProcArg->pDisplay))
+	{
+	  if (CheckAnotherWindowManager (pProcArg->pDisplay, pProcArg->dwScreen))
+	    {
+	      if (!g_fAnotherWMRunnig)
+		{
+		  g_fAnotherWMRunnig = TRUE;
+		  SendMessage(*(HWND*)pProcArg->hwndScreen, WM_UNMANAGE, 0, 0);
+		}
+	    }
+	  else
+	    {
+	      if (g_fAnotherWMRunnig)
+		{
+		  g_fAnotherWMRunnig = FALSE;
+		  SendMessage(*(HWND*)pProcArg->hwndScreen, WM_MANAGE, 0, 0);
+		}
+	    }
+	  Sleep (500);
+	  continue;
+	}
+
+      /* Fetch next event */
+      XNextEvent (pProcArg->pDisplay, &event);
+
+      /* Branch on event type */
+      if (event.type == CreateNotify)
+	{
+	  XWindowAttributes	attr;
+
+	  XSelectInput (pProcArg->pDisplay,
+			event.xcreatewindow.window,
+			PropertyChangeMask);
+
+	  /* Get the window attributes */
+	  XGetWindowAttributes (pProcArg->pDisplay,
+				event.xcreatewindow.window,
+				&attr);
+
+	  if (!attr.override_redirect)
+	    XSetWindowBorderWidth(pProcArg->pDisplay,
+				  event.xcreatewindow.window,
+				  0);
+	}
+      else if (event.type == PropertyNotify
+	       && event.xproperty.atom == atmWmName)
+	{
+	  memset (&msg, 0, sizeof (msg));
+
+	  msg.msg = WM_WM_NAME_EVENT;
+	  msg.iWindow = event.xproperty.window;
+
+	  /* Other fields ignored */
+	  winSendMessageToWM (pProcArg->pWMInfo, &msg);
+	}
+      else if (event.type == PropertyNotify
+	       && event.xproperty.atom == atmWmHints)
+	{
+	  memset (&msg, 0, sizeof (msg));
+
+	  msg.msg = WM_WM_HINTS_EVENT;
+	  msg.iWindow = event.xproperty.window;
+
+	  /* Other fields ignored */
+	  winSendMessageToWM (pProcArg->pWMInfo, &msg);
+	}
+      else if (event.type == ClientMessage
+	       && event.xclient.message_type == atmWmChange
+	       && event.xclient.data.l[0] == IconicState)
+	{
+	  ErrorF ("winMultiWindowXMsgProc - WM_CHANGE_STATE - IconicState\n");
+
+	  memset (&msg, 0, sizeof (msg));
+
+	  msg.msg = WM_WM_CHANGE_STATE;
+	  msg.iWindow = event.xclient.window;
+
+	  winSendMessageToWM (pProcArg->pWMInfo, &msg);
+	}
+    }
+
+  XCloseDisplay (pProcArg->pDisplay);
+  pthread_exit (NULL);
+ 
+}
+
+
+/*
+ * winInitWM - Entry point for the X server to spawn
+ * the Window Manager thread.  Called from
+ * winscrinit.c/winFinishScreenInitFB ().
+ */
+
+Bool
+winInitWM (void **ppWMInfo,
+	   pthread_t *ptWMProc,
+	   pthread_t *ptXMsgProc,
+	   pthread_mutex_t *ppmServerStarted,
+	   int dwScreen,
+	   HWND hwndScreen,
+	   BOOL allowOtherWM)
+{
+  WMProcArgPtr		pArg = (WMProcArgPtr) malloc (sizeof(WMProcArgRec));
+  WMInfoPtr		pWMInfo = (WMInfoPtr) malloc (sizeof(WMInfoRec));
+  XMsgProcArgPtr	pXMsgArg = (XMsgProcArgPtr) malloc (sizeof(XMsgProcArgRec));
+
+  /* Bail if the input parameters are bad */
+  if (pArg == NULL || pWMInfo == NULL)
+    {
+      ErrorF ("winInitWM - malloc failed.\n");
+      return FALSE;
+    }
+  
+  /* Zero the allocated memory */
+  ZeroMemory (pArg, sizeof (WMProcArgRec));
+  ZeroMemory (pWMInfo, sizeof (WMInfoRec));
+  ZeroMemory (pXMsgArg, sizeof (XMsgProcArgRec));
+
+  /* Set a return pointer to the Window Manager info structure */
+  *ppWMInfo = pWMInfo;
+  pWMInfo->fAllowOtherWM = allowOtherWM;
+
+  /* Setup the argument structure for the thread function */
+  pArg->dwScreen = dwScreen;
+  pArg->pWMInfo = pWMInfo;
+  pArg->ppmServerStarted = ppmServerStarted;
+  
+  /* Intialize the message queue */
+  if (!InitQueue (&pWMInfo->wmMsgQueue))
+    {
+      ErrorF ("winInitWM - InitQueue () failed.\n");
+      return FALSE;
+    }
+  
+  /* Spawn a thread for the Window Manager */
+  if (pthread_create (ptWMProc, NULL, winMultiWindowWMProc, pArg))
+    {
+      /* Bail if thread creation failed */
+      ErrorF ("winInitWM - pthread_create failed for Window Manager.\n");
+      return FALSE;
+    }
+
+  /* Spawn the XNextEvent thread, will send messages to WM */
+  pXMsgArg->dwScreen = dwScreen;
+  pXMsgArg->pWMInfo = pWMInfo;
+  pXMsgArg->ppmServerStarted = ppmServerStarted;
+  pXMsgArg->hwndScreen = hwndScreen;
+  if (pthread_create (ptXMsgProc, NULL, winMultiWindowXMsgProc, pXMsgArg))
+    {
+      /* Bail if thread creation failed */
+      ErrorF ("winInitWM - pthread_create failed on XMSG.\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG || YES
+  winDebug ("winInitWM - Returning.\n");
+#endif
+
+  return TRUE;
+}
+
+
+/*
+ * Window manager thread - setup
+ */
+
+static void
+winInitMultiWindowWM (WMInfoPtr pWMInfo, WMProcArgPtr pProcArg)
+{
+  int                   iRetries = 0;
+  char			pszDisplay[512];
+  int			iReturn;
+
+  ErrorF ("winInitMultiWindowWM - Hello\n");
+
+  /* Check that argument pointer is not invalid */
+  if (pProcArg == NULL)
+    {
+      ErrorF ("winInitMultiWindowWM - pProcArg is NULL.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  ErrorF ("winInitMultiWindowWM - Calling pthread_mutex_lock ()\n");
+
+  /* Grab our garbage mutex to satisfy pthread_cond_wait */
+  iReturn = pthread_mutex_lock (pProcArg->ppmServerStarted);
+  if (iReturn != 0)
+    {
+      ErrorF ("winInitMultiWindowWM - pthread_mutex_lock () failed: %d.  "
+	      "Exiting.\n",
+	      iReturn);
+      pthread_exit (NULL);
+    }
+
+  ErrorF ("winInitMultiWindowWM - pthread_mutex_lock () returned.\n");
+
+  /* Allow multiple threads to access Xlib */
+  if (XInitThreads () == 0)
+    {
+      ErrorF ("winInitMultiWindowWM - XInitThreads () failed.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* See if X supports the current locale */
+  if (XSupportsLocale () == False)
+    {
+      ErrorF ("winInitMultiWindowWM - Locale not supported by X.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* Release the server started mutex */
+  pthread_mutex_unlock (pProcArg->ppmServerStarted);
+
+  ErrorF ("winInitMultiWindowWM - pthread_mutex_unlock () returned.\n");
+
+  /* Set jump point for IO Error exits */
+  iReturn = setjmp (g_jmpWMEntry);
+  
+  /* Check if we should continue operations */
+  if (iReturn != WIN_JMP_ERROR_IO
+      && iReturn != WIN_JMP_OKAY)
+    {
+      /* setjmp returned an unknown value, exit */
+      ErrorF ("winInitMultiWindowWM - setjmp returned: %d.  Exiting.\n",
+	      iReturn);
+      pthread_exit (NULL);
+    }
+  else if (iReturn == WIN_JMP_ERROR_IO)
+    {
+      ErrorF ("winInitMultiWindowWM - Caught IO Error.  Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  /* Install our error handler */
+  XSetErrorHandler (winMultiWindowWMErrorHandler);
+  XSetIOErrorHandler (winMultiWindowWMIOErrorHandler);
+
+  /* Setup the display connection string x */
+  snprintf (pszDisplay,
+	    512,
+	    "127.0.0.1:%s.%d",
+	    display,
+	    (int) pProcArg->dwScreen);
+
+  /* Print the display connection string */
+  ErrorF ("winInitMultiWindowWM - DISPLAY=%s\n", pszDisplay);
+  
+  /* Open the X display */
+  do
+    {
+      /* Try to open the display */
+      pWMInfo->pDisplay = XOpenDisplay (pszDisplay);
+      if (pWMInfo->pDisplay == NULL)
+	{
+	  ErrorF ("winInitMultiWindowWM - Could not open display, try: %d, "
+		  "sleeping: %d\n\f",
+		  iRetries + 1, WIN_CONNECT_DELAY);
+	  ++iRetries;
+	  sleep (WIN_CONNECT_DELAY);
+	  continue;
+	}
+      else
+	break;
+    }
+  while (pWMInfo->pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
+  
+  /* Make sure that the display opened */
+  if (pWMInfo->pDisplay == NULL)
+    {
+      ErrorF ("winInitMultiWindowWM - Failed opening the display.  "
+	      "Exiting.\n");
+      pthread_exit (NULL);
+    }
+
+  ErrorF ("winInitMultiWindowWM - XOpenDisplay () returned and "
+	  "successfully opened the display.\n");
+  
+
+  /* Create some atoms */
+  pWMInfo->atmWmProtos = XInternAtom (pWMInfo->pDisplay,
+				      "WM_PROTOCOLS",
+				      False);
+  pWMInfo->atmWmDelete = XInternAtom (pWMInfo->pDisplay,
+				      "WM_DELETE_WINDOW",
+				      False);
+#ifdef XWIN_MULTIWINDOWEXTWM
+  pWMInfo->atmPrivMap  = XInternAtom (pWMInfo->pDisplay,
+				      WINDOWSWM_NATIVE_HWND,
+				      False);
+#endif
+
+
+  if (1) {
+    Cursor cursor = XCreateFontCursor (pWMInfo->pDisplay, XC_left_ptr);
+    if (cursor)
+    {
+      XDefineCursor (pWMInfo->pDisplay, DefaultRootWindow(pWMInfo->pDisplay), cursor);
+      XFreeCursor (pWMInfo->pDisplay, cursor);
+    }
+  }
+}
+
+
+/*
+ * winSendMessageToWM - Send a message from the X thread to the WM thread
+ */
+
+void
+winSendMessageToWM (void *pWMInfo, winWMMessagePtr pMsg)
+{
+  WMMsgNodePtr pNode;
+  
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winSendMessageToWM ()\n");
+#endif
+  
+  pNode = (WMMsgNodePtr)malloc(sizeof(WMMsgNodeRec));
+  if (pNode != NULL)
+    {
+      memcpy (&pNode->msg, pMsg, sizeof(winWMMessageRec));
+      PushMessage (&((WMInfoPtr)pWMInfo)->wmMsgQueue, pNode);
+    }
+}
+
+
+/*
+ * Window manager error handler
+ */
+
+static int
+winMultiWindowWMErrorHandler (Display *pDisplay, XErrorEvent *pErr)
+{
+  char pszErrorMsg[100];
+
+  if (pErr->request_code == X_ChangeWindowAttributes
+      && pErr->error_code == BadAccess)
+    {
+      ErrorF ("winMultiWindowWMErrorHandler - ChangeWindowAttributes "
+	      "BadAccess.\n");
+      return 0;
+    }
+  
+  XGetErrorText (pDisplay,
+		 pErr->error_code,
+		 pszErrorMsg,
+		 sizeof (pszErrorMsg));
+  ErrorF ("winMultiWindowWMErrorHandler - ERROR: %s\n", pszErrorMsg);
+
+  return 0;
+}
+
+
+/*
+ * Window manager IO error handler
+ */
+
+static int
+winMultiWindowWMIOErrorHandler (Display *pDisplay)
+{
+  ErrorF ("\nwinMultiWindowWMIOErrorHandler!\n\n");
+
+  if (g_shutdown)
+    pthread_exit(NULL);
+
+  /* Restart at the main entry point */
+  longjmp (g_jmpWMEntry, WIN_JMP_ERROR_IO);
+  
+  return 0;
+}
+
+
+/*
+ * X message procedure error handler
+ */
+
+static int
+winMultiWindowXMsgProcErrorHandler (Display *pDisplay, XErrorEvent *pErr)
+{
+  char pszErrorMsg[100];
+  
+  XGetErrorText (pDisplay,
+		 pErr->error_code,
+		 pszErrorMsg,
+		 sizeof (pszErrorMsg));
+  ErrorF ("winMultiWindowXMsgProcErrorHandler - ERROR: %s\n", pszErrorMsg);
+  
+  return 0;
+}
+
+
+/*
+ * X message procedure IO error handler
+ */
+
+static int
+winMultiWindowXMsgProcIOErrorHandler (Display *pDisplay)
+{
+  ErrorF ("\nwinMultiWindowXMsgProcIOErrorHandler!\n\n");
+
+  /* Restart at the main entry point */
+  longjmp (g_jmpXMsgProcEntry, WIN_JMP_ERROR_IO);
+  
+  return 0;
+}
+
+
+/*
+ * Catch RedirectError to detect other window manager running
+ */
+
+static int
+winRedirectErrorHandler (Display *pDisplay, XErrorEvent *pErr)
+{
+  redirectError = TRUE;
+  return 0;
+}
+
+
+/*
+ * Check if another window manager is running
+ */
+
+static Bool
+CheckAnotherWindowManager (Display *pDisplay, DWORD dwScreen)
+{
+  redirectError = FALSE;
+  XSetErrorHandler (winRedirectErrorHandler);
+  XSelectInput(pDisplay, RootWindow (pDisplay, dwScreen),
+	       // SubstructureNotifyMask | ButtonPressMask
+	       ColormapChangeMask | EnterWindowMask | PropertyChangeMask |
+	       SubstructureRedirectMask | KeyPressMask |
+	       ButtonPressMask | ButtonReleaseMask);
+  XSync (pDisplay, 0);
+  XSetErrorHandler (winMultiWindowXMsgProcErrorHandler);
+  XSelectInput(pDisplay, RootWindow (pDisplay, dwScreen),
+	       SubstructureNotifyMask);
+  XSync (pDisplay, 0);
+  if (redirectError)
+    {
+      //ErrorF ("CheckAnotherWindowManager() - another window manager is running.  Exiting.\n");
+      return TRUE;
+    }
+  else
+    {
+      return FALSE;
+    }
+}
+
+/*
+ * Notify the MWM thread we're exiting and not to reconnect
+ */
+
+void
+winDeinitMultiWindowWM ()
+{
+  ErrorF ("winDeinitMultiWindowWM - Noting shutdown in progress\n");
+  g_shutdown = TRUE;
+}
diff --git a/hw/xwin/winmultiwindowwndproc.c b/hw/xwin/winmultiwindowwndproc.c
new file mode 100644
index 0000000..20ff9f7
--- /dev/null
+++ b/hw/xwin/winmultiwindowwndproc.c
@@ -0,0 +1,1049 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Kensuke Matsuzaki
+ *		Earle F. Philhower, III
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "dixevents.h"
+#include "winmultiwindowclass.h"
+#include "winprefs.h"
+#include "winmsg.h"
+#include "inputstr.h"
+
+/*
+ * External global variables
+ */
+
+extern Bool			g_fCursor;
+extern Bool			g_fKeyboardHookLL;
+extern Bool			g_fSoftwareCursor;
+extern Bool			g_fButton[3];
+
+
+/*
+ * Local globals
+ */
+
+static UINT_PTR		g_uipMousePollingTimerID = 0;
+
+
+/*
+ * Constant defines
+ */
+
+#define MOUSE_POLLING_INTERVAL		500
+#define WIN_MULTIWINDOW_SHAPE		YES
+
+
+/*
+ * ConstrainSize - Taken from TWM sources - Respects hints for sizing
+ */
+#define makemult(a,b) ((b==1) ? (a) : (((int)((a)/(b))) * (b)) )
+static void
+ConstrainSize (WinXSizeHints hints, int *widthp, int *heightp)
+{
+  int minWidth, minHeight, maxWidth, maxHeight, xinc, yinc, delta;
+  int baseWidth, baseHeight;
+  int dwidth = *widthp, dheight = *heightp;
+  
+  if (hints.flags & PMinSize)
+    {
+      minWidth = hints.min_width;
+      minHeight = hints.min_height;
+    }
+  else if (hints.flags & PBaseSize)
+    {
+      minWidth = hints.base_width;
+      minHeight = hints.base_height;
+    }
+  else
+    minWidth = minHeight = 1;
+  
+  if (hints.flags & PBaseSize)
+    {
+      baseWidth = hints.base_width;
+      baseHeight = hints.base_height;
+    } 
+  else if (hints.flags & PMinSize)
+    {
+      baseWidth = hints.min_width;
+      baseHeight = hints.min_height;
+    }
+  else
+    baseWidth = baseHeight = 0;
+
+  if (hints.flags & PMaxSize)
+    {
+      maxWidth = hints.max_width;
+      maxHeight = hints.max_height;
+    }
+  else
+    {
+      maxWidth = MAXINT;
+      maxHeight = MAXINT;
+    }
+
+  if (hints.flags & PResizeInc)
+    {
+      xinc = hints.width_inc;
+      yinc = hints.height_inc;
+    }
+  else
+    xinc = yinc = 1;
+
+  /*
+   * First, clamp to min and max values
+   */
+  if (dwidth < minWidth)
+    dwidth = minWidth;
+  if (dheight < minHeight)
+    dheight = minHeight;
+
+  if (dwidth > maxWidth)
+    dwidth = maxWidth;
+  if (dheight > maxHeight)
+    dheight = maxHeight;
+
+  /*
+   * Second, fit to base + N * inc
+   */
+  dwidth = ((dwidth - baseWidth) / xinc * xinc) + baseWidth;
+  dheight = ((dheight - baseHeight) / yinc * yinc) + baseHeight;
+  
+  /*
+   * Third, adjust for aspect ratio
+   */
+
+  /*
+   * The math looks like this:
+   *
+   * minAspectX    dwidth     maxAspectX
+   * ---------- <= ------- <= ----------
+   * minAspectY    dheight    maxAspectY
+   *
+   * If that is multiplied out, then the width and height are
+   * invalid in the following situations:
+   *
+   * minAspectX * dheight > minAspectY * dwidth
+   * maxAspectX * dheight < maxAspectY * dwidth
+   * 
+   */
+  
+  if (hints.flags & PAspect)
+    {
+      if (hints.min_aspect.x * dheight > hints.min_aspect.y * dwidth)
+        {
+	  delta = makemult(hints.min_aspect.x * dheight / hints.min_aspect.y - dwidth, xinc);
+	  if (dwidth + delta <= maxWidth)
+	    dwidth += delta;
+	  else
+            {
+	      delta = makemult(dheight - dwidth*hints.min_aspect.y/hints.min_aspect.x, yinc);
+	      if (dheight - delta >= minHeight)
+		dheight -= delta;
+            }
+        }
+      
+      if (hints.max_aspect.x * dheight < hints.max_aspect.y * dwidth)
+        {
+	  delta = makemult(dwidth * hints.max_aspect.y / hints.max_aspect.x - dheight, yinc);
+	  if (dheight + delta <= maxHeight)
+	    dheight += delta;
+	  else
+            {
+	      delta = makemult(dwidth - hints.max_aspect.x*dheight/hints.max_aspect.y, xinc);
+	      if (dwidth - delta >= minWidth)
+		dwidth -= delta;
+            }
+        }
+    }
+  
+  /* Return computed values */
+  *widthp = dwidth;
+  *heightp = dheight;
+}
+#undef makemult
+
+
+
+/*
+ * ValidateSizing - Ensures size request respects hints
+ */
+static int
+ValidateSizing (HWND hwnd, WindowPtr pWin,
+		WPARAM wParam, LPARAM lParam)
+{
+  WinXSizeHints sizeHints;
+  RECT *rect;
+  int iWidth, iHeight;
+
+  /* Invalid input checking */
+  if (pWin==NULL || lParam==0)
+    return FALSE;
+
+  /* No size hints, no checking */
+  if (!winMultiWindowGetWMNormalHints (pWin, &sizeHints))
+    return FALSE;
+  
+  /* Avoid divide-by-zero */
+  if (sizeHints.flags & PResizeInc)
+    {
+      if (sizeHints.width_inc == 0) sizeHints.width_inc = 1;
+      if (sizeHints.height_inc == 0) sizeHints.height_inc = 1;
+    }
+  
+  rect = (RECT*)lParam;
+  
+  iWidth = rect->right - rect->left;
+  iHeight = rect->bottom - rect->top;
+
+  /* Now remove size of any borders */
+  iWidth -= 2 * GetSystemMetrics(SM_CXSIZEFRAME);
+  iHeight -= (GetSystemMetrics(SM_CYCAPTION)
+	      + 2 * GetSystemMetrics(SM_CYSIZEFRAME));
+	      
+
+  /* Constrain the size to legal values */
+  ConstrainSize (sizeHints, &iWidth, &iHeight);
+
+  /* Add back the borders */
+  iWidth += 2 * GetSystemMetrics(SM_CXSIZEFRAME);
+  iHeight += (GetSystemMetrics(SM_CYCAPTION)
+	      + 2 * GetSystemMetrics(SM_CYSIZEFRAME));
+
+  /* Adjust size according to where we're dragging from */
+  switch(wParam) {
+  case WMSZ_TOP:
+  case WMSZ_TOPRIGHT:
+  case WMSZ_BOTTOM:
+  case WMSZ_BOTTOMRIGHT:
+  case WMSZ_RIGHT:
+    rect->right = rect->left + iWidth;
+    break;
+  default:
+    rect->left = rect->right - iWidth;
+    break;
+  }
+  switch(wParam) {
+  case WMSZ_BOTTOM:
+  case WMSZ_BOTTOMRIGHT:
+  case WMSZ_BOTTOMLEFT:
+  case WMSZ_RIGHT:
+  case WMSZ_LEFT:
+    rect->bottom = rect->top + iHeight;
+    break;
+  default:
+    rect->top = rect->bottom - iHeight;
+    break;
+  }
+  return TRUE;
+}
+
+extern Bool winInDestroyWindowsWindow;
+static Bool winInRaiseWindow = FALSE;
+static void winRaiseWindow(WindowPtr pWin)
+{
+  if (!winInDestroyWindowsWindow && !winInRaiseWindow)
+  {
+    BOOL oldstate = winInRaiseWindow;
+    winInRaiseWindow = TRUE;
+    /* Call configure window directly to make sure it gets processed 
+     * in time
+     */
+    XID vlist[1] = { 0 };
+    ConfigureWindow(pWin, CWStackMode, vlist, serverClient); 
+    winInRaiseWindow = oldstate;
+  }
+}
+
+
+/*
+ * winTopLevelWindowProc - Window procedure for all top-level Windows windows.
+ */
+
+LRESULT CALLBACK
+winTopLevelWindowProc (HWND hwnd, UINT message, 
+		       WPARAM wParam, LPARAM lParam)
+{
+  POINT			ptMouse;
+  HDC			hdcUpdate;
+  PAINTSTRUCT		ps;
+  WindowPtr		pWin = NULL;
+  winPrivWinPtr	        pWinPriv = NULL;
+  ScreenPtr		s_pScreen = NULL;
+  winPrivScreenPtr	s_pScreenPriv = NULL;
+  winScreenInfo		*s_pScreenInfo = NULL;
+  HWND			hwndScreen = NULL;
+  DrawablePtr		pDraw = NULL;
+  winWMMessageRec	wmMsg;
+  Bool                  fWMMsgInitialized = FALSE;
+  static Bool		s_fTracking = FALSE;
+  Bool			needRestack = FALSE;
+  LRESULT		ret;
+
+#if CYGDEBUG
+  winDebugWin32Message("winTopLevelWindowProc", hwnd, message, wParam, lParam);
+#endif
+  
+  /* Check if the Windows window property for our X window pointer is valid */
+  if ((pWin = GetProp (hwnd, WIN_WINDOW_PROP)) != NULL)
+    {
+      /* Our X window pointer is valid */
+
+      /* Get pointers to the drawable and the screen */
+      pDraw		= &pWin->drawable;
+      s_pScreen		= pWin->drawable.pScreen;
+
+      /* Get a pointer to our window privates */
+      pWinPriv		= winGetWindowPriv(pWin);
+
+      /* Get pointers to our screen privates and screen info */
+      s_pScreenPriv	= pWinPriv->pScreenPriv;
+      s_pScreenInfo	= s_pScreenPriv->pScreenInfo;
+
+      /* Get the handle for our screen-sized window */
+      hwndScreen	= s_pScreenPriv->hwndScreen;
+
+      /* */
+      wmMsg.msg		= 0;
+      wmMsg.hwndWindow	= hwnd;
+      wmMsg.iWindow	= (Window)GetProp (hwnd, WIN_WID_PROP);
+
+      wmMsg.iX		= pDraw->x;
+      wmMsg.iY		= pDraw->y;
+      wmMsg.iWidth	= pDraw->width;
+      wmMsg.iHeight	= pDraw->height;
+
+      fWMMsgInitialized = TRUE;
+
+#if 0
+      /*
+       * Print some debugging information
+       */
+
+      ErrorF ("hWnd %08X\n", hwnd);
+      ErrorF ("pWin %08X\n", pWin);
+      ErrorF ("pDraw %08X\n", pDraw);
+      ErrorF ("\ttype %08X\n", pWin->drawable.type);
+      ErrorF ("\tclass %08X\n", pWin->drawable.class);
+      ErrorF ("\tdepth %08X\n", pWin->drawable.depth);
+      ErrorF ("\tbitsPerPixel %08X\n", pWin->drawable.bitsPerPixel);
+      ErrorF ("\tid %08X\n", pWin->drawable.id);
+      ErrorF ("\tx %08X\n", pWin->drawable.x);
+      ErrorF ("\ty %08X\n", pWin->drawable.y);
+      ErrorF ("\twidth %08X\n", pWin->drawable.width);
+      ErrorF ("\thenght %08X\n", pWin->drawable.height);
+      ErrorF ("\tpScreen %08X\n", pWin->drawable.pScreen);
+      ErrorF ("\tserialNumber %08X\n", pWin->drawable.serialNumber);
+      ErrorF ("g_iWindowPrivateKey %p\n", g_iWindowPrivateKey);
+      ErrorF ("pWinPriv %08X\n", pWinPriv);
+      ErrorF ("s_pScreenPriv %08X\n", s_pScreenPriv);
+      ErrorF ("s_pScreenInfo %08X\n", s_pScreenInfo);
+      ErrorF ("hwndScreen %08X\n", hwndScreen);
+#endif
+    }
+
+  /* Branch on message type */
+  switch (message)
+    {
+    case WM_CREATE:
+
+      /* */
+      SetProp (hwnd,
+	       WIN_WINDOW_PROP,
+	       (HANDLE)((LPCREATESTRUCT) lParam)->lpCreateParams);
+      
+      /* */
+      SetProp (hwnd,
+	       WIN_WID_PROP,
+	       (HANDLE)winGetWindowID (((LPCREATESTRUCT) lParam)->lpCreateParams));
+
+      /*
+       * Make X windows' Z orders sync with Windows windows because
+       * there can be AlwaysOnTop windows overlapped on the window
+       * currently being created.
+       */
+      winReorderWindowsMultiWindow ();
+
+      /* Fix a 'round title bar corner background should be transparent not black' problem when first painted */
+      RECT rWindow;
+      HRGN hRgnWindow;
+      GetWindowRect(hwnd, &rWindow);
+      hRgnWindow = CreateRectRgnIndirect(&rWindow);
+      SetWindowRgn (hwnd, hRgnWindow, TRUE);
+      DeleteObject(hRgnWindow);
+
+      return 0;
+
+    case WM_INIT_SYS_MENU:
+      /*
+       * Add whatever the setup file wants to for this window
+       */
+      SetupSysMenu ((unsigned long)hwnd);
+      return 0;
+
+    case WM_SYSCOMMAND:
+      /*
+       * Any window menu items go through here
+       */
+      if (HandleCustomWM_COMMAND ((unsigned long)hwnd, LOWORD(wParam)))
+      {
+        /* Don't pass customized menus to DefWindowProc */
+        return 0;
+      }
+      if (wParam == SC_RESTORE || wParam == SC_MAXIMIZE)
+      {
+        WINDOWPLACEMENT wndpl;
+	wndpl.length = sizeof(wndpl);
+	if (GetWindowPlacement(hwnd, &wndpl) && wndpl.showCmd == SW_SHOWMINIMIZED)
+          needRestack = TRUE;
+      }
+      break;
+
+    case WM_INITMENU:
+      /* Checks/Unchecks any menu items before they are displayed */
+      HandleCustomWM_INITMENU ((unsigned long)hwnd, wParam);
+      break;
+
+    case WM_PAINT:
+      /* Only paint if our window handle is valid */
+      if (hwndScreen == NULL)
+	break;
+
+      /* BeginPaint gives us an hdc that clips to the invalidated region */
+      hdcUpdate = BeginPaint (hwnd, &ps);
+      /* Avoid the BitBlt's if the PAINTSTRUCT is bogus */
+      if (ps.rcPaint.right==0 && ps.rcPaint.bottom==0 && ps.rcPaint.left==0 && ps.rcPaint.top==0)
+      {
+	EndPaint (hwnd, &ps);
+	return 0;
+      }
+
+      /* Try to copy from the shadow buffer */
+      if (!BitBlt (hdcUpdate,
+		   ps.rcPaint.left, ps.rcPaint.top,
+		   ps.rcPaint.right - ps.rcPaint.left, ps.rcPaint.bottom - ps.rcPaint.top,
+		   s_pScreenPriv->hdcShadow,
+		   ps.rcPaint.left + pWin->drawable.x, ps.rcPaint.top + pWin->drawable.y,
+		   SRCCOPY))
+	{
+	  LPVOID lpMsgBuf;
+	  
+	  /* Display a fancy error message */
+	  FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | 
+			 FORMAT_MESSAGE_FROM_SYSTEM | 
+			 FORMAT_MESSAGE_IGNORE_INSERTS,
+			 NULL,
+			 GetLastError (),
+			 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+			 (LPTSTR) &lpMsgBuf,
+			 0, NULL);
+
+	  ErrorF ("winTopLevelWindowProc - BitBlt failed: %s\n",
+		  (LPSTR)lpMsgBuf);
+	  LocalFree (lpMsgBuf);
+	}
+
+      /* EndPaint frees the DC */
+      EndPaint (hwnd, &ps);
+      return 0;
+
+    case WM_MOUSEMOVE:
+      /* Unpack the client area mouse coordinates */
+      ptMouse.x = GET_X_LPARAM(lParam);
+      ptMouse.y = GET_Y_LPARAM(lParam);
+
+      /* Translate the client area mouse coordinates to screen coordinates */
+      ClientToScreen (hwnd, &ptMouse);
+
+      /* Screen Coords from (-X, -Y) -> Root Window (0, 0) */
+      ptMouse.x -= GetSystemMetrics (SM_XVIRTUALSCREEN);
+      ptMouse.y -= GetSystemMetrics (SM_YVIRTUALSCREEN);
+
+      /* We can't do anything without privates */
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+
+      /* Has the mouse pointer crossed screens? */
+      if (s_pScreen != miPointerGetScreen(inputInfo.pointer))
+	miPointerSetScreen (inputInfo.pointer, s_pScreenInfo->dwScreen,
+			       ptMouse.x - s_pScreenInfo->dwXOffset,
+			       ptMouse.y - s_pScreenInfo->dwYOffset);
+
+      /* Are we tracking yet? */
+      if (!s_fTracking)
+	{
+	  TRACKMOUSEEVENT		tme;
+	  
+	  /* Setup data structure */
+	  ZeroMemory (&tme, sizeof (tme));
+	  tme.cbSize = sizeof (tme);
+	  tme.dwFlags = TME_LEAVE;
+	  tme.hwndTrack = hwnd;
+
+	  /* Call the tracking function */
+	  if (!(*g_fpTrackMouseEvent) (&tme))
+	    ErrorF ("winTopLevelWindowProc - _TrackMouseEvent failed\n");
+
+	  /* Flag that we are tracking now */
+	  s_fTracking = TRUE;
+	}
+      
+      /* Hide or show the Windows mouse cursor */
+      if (g_fSoftwareCursor && g_fCursor)
+	{
+	  /* Hide Windows cursor */
+	  g_fCursor = FALSE;
+	  ShowCursor (FALSE);
+	}
+
+      /* Kill the timer used to poll mouse events */
+      if (g_uipMousePollingTimerID != 0)
+	{
+	  KillTimer (s_pScreenPriv->hwndScreen, WIN_POLLING_MOUSE_TIMER_ID);
+	  g_uipMousePollingTimerID = 0;
+	}
+
+      /* Deliver absolute cursor position to X Server */
+      miPointerAbsoluteCursor (ptMouse.x - s_pScreenInfo->dwXOffset,
+			       ptMouse.y - s_pScreenInfo->dwYOffset,
+			       g_c32LastInputEventTime = GetTickCount ());
+      return 0;
+      
+    case WM_NCMOUSEMOVE:
+      /*
+       * We break instead of returning 0 since we need to call
+       * DefWindowProc to get the mouse cursor changes
+       * and min/max/close button highlighting in Windows XP.
+       * The Platform SDK says that you should return 0 if you
+       * process this message, but it fails to mention that you
+       * will give up any default functionality if you do return 0.
+       */
+      
+      /* We can't do anything without privates */
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+
+      /* Non-client mouse movement, show Windows cursor */
+      if (g_fSoftwareCursor && !g_fCursor)
+	{
+	  g_fCursor = TRUE;
+	  ShowCursor (TRUE);
+	}
+
+      /*
+       * Timer to poll mouse events.  This is needed to make
+       * programs like xeyes follow the mouse properly.
+       */
+      if (g_uipMousePollingTimerID == 0)
+	g_uipMousePollingTimerID = SetTimer (s_pScreenPriv->hwndScreen,
+					     WIN_POLLING_MOUSE_TIMER_ID,
+					     MOUSE_POLLING_INTERVAL,
+					     NULL);
+      break;
+
+    case WM_MOUSELEAVE:
+      /* Mouse has left our client area */
+
+      /* Flag that we are no longer tracking */
+      s_fTracking = FALSE;
+
+      /* Show the mouse cursor, if necessary */
+      if (g_fSoftwareCursor && !g_fCursor)
+	{
+	  g_fCursor = TRUE;
+	  ShowCursor (TRUE);
+	}
+
+      /*
+       * Timer to poll mouse events.  This is needed to make
+       * programs like xeyes follow the mouse properly.
+       */
+      if (g_uipMousePollingTimerID == 0)
+	g_uipMousePollingTimerID = SetTimer (s_pScreenPriv->hwndScreen,
+					     WIN_POLLING_MOUSE_TIMER_ID,
+					     MOUSE_POLLING_INTERVAL,
+					     NULL);
+      return 0;
+
+    case WM_LBUTTONDBLCLK:
+    case WM_LBUTTONDOWN:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      g_fButton[0] = TRUE;
+      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button1, wParam);
+      
+    case WM_LBUTTONUP:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      g_fButton[0] = FALSE;
+      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button1, wParam);
+
+    case WM_MBUTTONDBLCLK:
+    case WM_MBUTTONDOWN:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      g_fButton[1] = TRUE;
+      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button2, wParam);
+      
+    case WM_MBUTTONUP:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      g_fButton[1] = FALSE;
+      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button2, wParam);
+      
+    case WM_RBUTTONDBLCLK:
+    case WM_RBUTTONDOWN:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      g_fButton[2] = TRUE;
+      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button3, wParam);
+      
+    case WM_RBUTTONUP:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      g_fButton[2] = FALSE;
+      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button3, wParam);
+
+    case WM_XBUTTONDBLCLK:
+    case WM_XBUTTONDOWN:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      return winMouseButtonsHandle (s_pScreen, ButtonPress, HIWORD(wParam) + 5, wParam);
+    case WM_XBUTTONUP:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      return winMouseButtonsHandle (s_pScreen, ButtonRelease, HIWORD(wParam) + 5, wParam);
+
+    case WM_MOUSEWHEEL:
+      
+      /* Pass the message to the root window */
+      SendMessage (hwndScreen, message, wParam, lParam);
+      return 0;
+
+    case WM_SETFOCUS:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+
+      winRestoreModeKeyStates ();
+
+      /* Add the keyboard hook if possible */
+      if (g_fKeyboardHookLL)
+	g_fKeyboardHookLL = winInstallKeyboardHookLL ();
+      return 0;
+      
+    case WM_KILLFOCUS:
+      /* Pop any pressed keys since we are losing keyboard focus */
+      winKeybdReleaseKeys ();
+
+      /* Remove our keyboard hook if it is installed */
+      winRemoveKeyboardHookLL ();
+      return 0;
+
+    case WM_SYSDEADCHAR:      
+    case WM_DEADCHAR:
+      /*
+       * NOTE: We do nothing with WM_*CHAR messages,
+       * nor does the root window, so we can just toss these messages.
+       */
+      return 0;
+
+    case WM_SYSKEYDOWN:
+    case WM_KEYDOWN:
+
+      /*
+       * Don't pass Alt-F4 key combo to root window,
+       * let Windows translate to WM_CLOSE and close this top-level window.
+       *
+       * NOTE: We purposely don't check the fUseWinKillKey setting because
+       * it should only apply to the key handling for the root window,
+       * not for top-level window-manager windows.
+       *
+       * ALSO NOTE: We do pass Ctrl-Alt-Backspace to the root window
+       * because that is a key combo that no X app should be expecting to
+       * receive, since it has historically been used to shutdown the X server.
+       * Passing Ctrl-Alt-Backspace to the root window preserves that
+       * behavior, assuming that -unixkill has been passed as a parameter.
+       */
+      if (wParam == VK_F4 && (GetKeyState (VK_MENU) & 0x8000))
+	  break;
+
+#if CYGWINDOWING_DEBUG
+      if (wParam == VK_ESCAPE)
+	{
+	  /* Place for debug: put any tests and dumps here */
+	  WINDOWPLACEMENT windPlace;
+	  RECT rc;
+	  LPRECT pRect;
+	  
+	  windPlace.length = sizeof (WINDOWPLACEMENT);
+	  GetWindowPlacement (hwnd, &windPlace);
+	  pRect = &windPlace.rcNormalPosition;
+	  ErrorF ("\nCYGWINDOWING Dump:\n"
+		  "\tdrawable: (%hd, %hd) - %hdx%hd\n", pDraw->x,
+		  pDraw->y, pDraw->width, pDraw->height);
+	  ErrorF ("\twindPlace: (%ld, %ld) - %ldx%ld\n", pRect->left,
+		  pRect->top, pRect->right - pRect->left,
+		  pRect->bottom - pRect->top);
+	  if (GetClientRect (hwnd, &rc))
+	    {
+	      pRect = &rc;
+	      ErrorF ("\tClientRect: (%ld, %ld) - %ldx%ld\n", pRect->left,
+		      pRect->top, pRect->right - pRect->left,
+		      pRect->bottom - pRect->top);
+	    }
+	  if (GetWindowRect (hwnd, &rc))
+	    {
+	      pRect = &rc;
+	      ErrorF ("\tWindowRect: (%ld, %ld) - %ldx%ld\n", pRect->left,
+		      pRect->top, pRect->right - pRect->left,
+		      pRect->bottom - pRect->top);
+	    }
+	  ErrorF ("\n");
+	}
+#endif
+      
+      /* Pass the message to the root window */
+      return winWindowProc(hwndScreen, message, wParam, lParam);
+
+    case WM_SYSKEYUP:
+    case WM_KEYUP:
+
+
+      /* Pass the message to the root window */
+      return winWindowProc(hwndScreen, message, wParam, lParam);
+
+    case WM_HOTKEY:
+
+      /* Pass the message to the root window */
+      SendMessage (hwndScreen, message, wParam, lParam);
+      return 0;
+
+    case WM_ACTIVATE:
+
+      /* Pass the message to the root window */
+      SendMessage (hwndScreen, message, wParam, lParam);
+
+      if (LOWORD(wParam) != WA_INACTIVE)
+	{
+	  /* Raise the window to the top in Z order */
+          /* ago: Activate does not mean putting it to front! */
+          /*
+	  wmMsg.msg = WM_WM_RAISE;
+	  if (fWMMsgInitialized)
+	    winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
+          */
+	  
+	  /* Tell our Window Manager thread to activate the window */
+	  wmMsg.msg = WM_WM_ACTIVATE;
+	  if (fWMMsgInitialized)
+	    if (!pWin || !pWin->overrideRedirect) /* for OOo menus */
+	      winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
+	}
+      return 0;
+
+    case WM_ACTIVATEAPP:
+      /*
+       * This message is also sent to the root window
+       * so we do nothing for individual multiwindow windows
+       */
+      break;
+
+    case WM_CLOSE:
+      /* Branch on if the window was killed in X already */
+      if (pWinPriv->fXKilled)
+        {
+	  /* Window was killed, go ahead and destroy the window */
+	  DestroyWindow (hwnd);
+	}
+      else
+	{
+	  /* Tell our Window Manager thread to kill the window */
+	  wmMsg.msg = WM_WM_KILL;
+	  if (fWMMsgInitialized)
+	    winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
+	}
+      return 0;
+
+    case WM_DESTROY:
+
+      /* Branch on if the window was killed in X already */
+      if (pWinPriv && !pWinPriv->fXKilled)
+	{
+	  ErrorF ("winTopLevelWindowProc - WM_DESTROY - WM_WM_KILL\n");
+	  
+	  /* Tell our Window Manager thread to kill the window */
+	  wmMsg.msg = WM_WM_KILL;
+	  if (fWMMsgInitialized)
+	    winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
+	}
+
+      RemoveProp (hwnd, WIN_WINDOW_PROP);
+      RemoveProp (hwnd, WIN_WID_PROP);
+      RemoveProp (hwnd, WIN_NEEDMANAGE_PROP);
+
+      break;
+
+    case WM_MOVE:
+      /* Adjust the X Window to the moved Windows window */
+      winAdjustXWindow (pWin, hwnd);
+      return 0;
+
+    case WM_SHOWWINDOW:
+      /* Bail out if the window is being hidden */
+      if (!wParam)
+	return 0;
+
+      /* Tell X to map the window */
+      MapWindow (pWin, wClient(pWin));
+
+      /* */
+      if (!pWin->overrideRedirect)
+	{
+	  DWORD		dwExStyle;
+	  DWORD		dwStyle;
+	  RECT		rcNew;
+	  int		iDx, iDy;
+	      
+	  /* Flag that this window needs to be made active when clicked */
+	  SetProp (hwnd, WIN_NEEDMANAGE_PROP, (HANDLE) 1);
+
+	  /* Get the standard and extended window style information */
+	  dwExStyle = GetWindowLongPtr (hwnd, GWL_EXSTYLE);
+	  dwStyle = GetWindowLongPtr (hwnd, GWL_STYLE);
+
+	  /* */
+	  if (dwExStyle != WS_EX_APPWINDOW)
+	    {
+	      /* Setup a rectangle with the X window position and size */
+	      SetRect (&rcNew,
+		       pDraw->x,
+		       pDraw->y,
+		       pDraw->x + pDraw->width,
+		       pDraw->y + pDraw->height);
+
+#if 0
+	      ErrorF ("winTopLevelWindowProc - (%d, %d)-(%d, %d)\n",
+		      rcNew.left, rcNew.top,
+		      rcNew.right, rcNew.bottom);
+#endif
+
+	      /* */
+	      AdjustWindowRectEx (&rcNew,
+				  WS_POPUP | WS_SIZEBOX | WS_OVERLAPPEDWINDOW,
+				  FALSE,
+				  WS_EX_APPWINDOW);
+
+	      /* Calculate position deltas */
+	      iDx = pDraw->x - rcNew.left;
+	      iDy = pDraw->y - rcNew.top;
+
+	      /* Calculate new rectangle */
+	      rcNew.left += iDx;
+	      rcNew.right += iDx;
+	      rcNew.top += iDy;
+	      rcNew.bottom += iDy;
+
+#if 0
+	      ErrorF ("winTopLevelWindowProc - (%d, %d)-(%d, %d)\n",
+		      rcNew.left, rcNew.top,
+		      rcNew.right, rcNew.bottom);
+#endif
+
+	      /* Set the window extended style flags */
+	      SetWindowLongPtr (hwnd, GWL_EXSTYLE, WS_EX_APPWINDOW);
+
+	      /* Set the window standard style flags */
+	      SetWindowLongPtr (hwnd, GWL_STYLE,
+				WS_POPUP | WS_SIZEBOX | WS_OVERLAPPEDWINDOW);
+
+	      /* Position the Windows window */
+	      SetWindowPos (hwnd, HWND_TOP,
+			    rcNew.left, rcNew.top,
+			    rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
+			    SWP_NOMOVE | SWP_FRAMECHANGED
+			    | SWP_SHOWWINDOW | SWP_NOACTIVATE);
+
+	      /* Bring the Windows window to the foreground */
+	      SetForegroundWindow (hwnd);
+	    }
+	}
+      else /* It is an overridden window so make it top of Z stack */
+	{
+#if CYGWINDOWING_DEBUG
+	  ErrorF ("overridden window is shown\n");
+#endif
+	  SetWindowPos (hwnd, HWND_TOPMOST, 0, 0, 0, 0,
+			SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
+	}
+	  
+      /* Setup the Window Manager message */
+      wmMsg.msg = WM_WM_MAP;
+      wmMsg.iWidth = pDraw->width;
+      wmMsg.iHeight = pDraw->height;
+
+      /* Tell our Window Manager thread to map the window */
+      if (fWMMsgInitialized)
+	winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
+
+      return 0;
+
+    case WM_SIZING:
+      /* Need to legalize the size according to WM_NORMAL_HINTS */
+      /* for applications like xterm */
+      return ValidateSizing (hwnd, pWin, wParam, lParam);
+
+    case WM_WINDOWPOSCHANGED:
+      {
+	LPWINDOWPOS pWinPos = (LPWINDOWPOS) lParam;
+
+	if (!(pWinPos->flags & SWP_NOZORDER))
+	  {
+#if CYGWINDOWING_DEBUG
+	    winDebug ("\twindow z order was changed\n");
+#endif
+	    if (pWinPos->hwndInsertAfter == HWND_TOP
+		||pWinPos->hwndInsertAfter == HWND_TOPMOST
+		||pWinPos->hwndInsertAfter == HWND_NOTOPMOST)
+	      {
+#if CYGWINDOWING_DEBUG
+		winDebug ("\traise to top\n");
+#endif
+		/* Raise the window to the top in Z order */
+		winRaiseWindow(pWin);
+	      }
+	    else if (pWinPos->hwndInsertAfter == HWND_BOTTOM)
+	      {
+	      }
+	    else
+	      {
+		/* Check if this window is top of X windows. */
+		HWND hWndAbove = NULL;
+		DWORD dwCurrentProcessID = GetCurrentProcessId ();
+		DWORD dwWindowProcessID = 0;
+
+		for (hWndAbove = pWinPos->hwndInsertAfter;
+		     hWndAbove != NULL;
+		     hWndAbove = GetNextWindow (hWndAbove, GW_HWNDPREV))
+		  {
+		    /* Ignore other XWin process's window */
+		    GetWindowThreadProcessId (hWndAbove, &dwWindowProcessID);
+
+		    if ((dwWindowProcessID == dwCurrentProcessID)
+			&& GetProp (hWndAbove, WIN_WINDOW_PROP)
+			&& !IsWindowVisible (hWndAbove)
+			&& !IsIconic (hWndAbove) ) /* ignore minimized windows */
+		      break;
+		  }
+		/* If this is top of X windows in Windows stack,
+		   raise it in X stack. */
+		if (hWndAbove == NULL)
+		  {
+#if CYGWINDOWING_DEBUG
+		    winDebug ("\traise to top\n");
+#endif
+		    winRaiseWindow(pWin);
+		  }
+	      }
+	  }
+      }
+      /*
+       * Pass the message to DefWindowProc to let the function
+       * break down WM_WINDOWPOSCHANGED to WM_MOVE and WM_SIZE.
+      */
+      break; 
+
+    case WM_SIZE:
+      /* see dix/window.c */
+#if CYGWINDOWING_DEBUG
+      {
+	char buf[64];
+	switch (wParam)
+	  {
+	  case SIZE_MINIMIZED:
+	    strcpy(buf, "SIZE_MINIMIZED");
+	    break;
+	  case SIZE_MAXIMIZED:
+	    strcpy(buf, "SIZE_MAXIMIZED");
+	    break;
+	  case SIZE_RESTORED:
+	    strcpy(buf, "SIZE_RESTORED");
+	    break;
+	  default:
+	    strcpy(buf, "UNKNOWN_FLAG");
+	  }
+	ErrorF ("winTopLevelWindowProc - WM_SIZE to %dx%d (%s) - %d ms\n",
+		(int)LOWORD(lParam), (int)HIWORD(lParam), buf,
+		(int)(GetTickCount ()));
+      }
+#endif
+      /* Adjust the X Window to the moved Windows window */
+      winAdjustXWindow (pWin, hwnd);
+      return 0; /* end of WM_SIZE handler */
+
+    case WM_MOUSEACTIVATE:
+
+      /* Check if this window needs to be made active when clicked */
+      if (!GetProp (pWinPriv->hWnd, WIN_NEEDMANAGE_PROP))
+	{
+#if CYGMULTIWINDOW_DEBUG
+	  ErrorF ("winTopLevelWindowProc - WM_MOUSEACTIVATE - "
+		  "MA_NOACTIVATE\n");
+#endif
+
+	  /* */
+	  return MA_NOACTIVATE;
+	}
+      break;
+
+    case WM_SETCURSOR:
+      if (LOWORD(lParam) == HTCLIENT)
+	{
+	  if (!g_fSoftwareCursor) SetCursor (s_pScreenPriv->cursor.handle);
+	  return TRUE;
+	}
+      break;
+
+    default:
+      break;
+    }
+
+  ret = DefWindowProc (hwnd, message, wParam, lParam);
+  /*
+   * If the window was minized we get the stack change before the window is restored
+   * and so it gets lost. Ensure there stacking order is correct.
+   */
+  if (needRestack)
+    winReorderWindowsMultiWindow();
+  return ret;
+}
diff --git a/hw/xwin/winnativegdi.c b/hw/xwin/winnativegdi.c
new file mode 100644
index 0000000..48a467a
--- /dev/null
+++ b/hw/xwin/winnativegdi.c
@@ -0,0 +1,546 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * External symbols
+ */
+
+extern HWND			g_hDlgExit;
+
+
+/*
+ * Local function prototypes
+ */
+
+static Bool
+winAllocateFBNativeGDI (ScreenPtr pScreen);
+
+static void
+winShadowUpdateNativeGDI (ScreenPtr pScreen, 
+			  shadowBufPtr pBuf);
+
+static Bool
+winCloseScreenNativeGDI (int nIndex, ScreenPtr pScreen);
+
+static Bool
+winInitVisualsNativeGDI (ScreenPtr pScreen);
+
+static Bool
+winAdjustVideoModeNativeGDI (ScreenPtr pScreen);
+
+#if 0
+static Bool
+winBltExposedRegionsNativeGDI (ScreenPtr pScreen);
+#endif
+
+static Bool
+winActivateAppNativeGDI (ScreenPtr pScreen);
+
+static Bool
+winRedrawScreenNativeGDI (ScreenPtr pScreen);
+
+static Bool
+winRealizeInstalledPaletteNativeGDI (ScreenPtr pScreen);
+
+static Bool
+winInstallColormapNativeGDI (ColormapPtr pColormap);
+
+static Bool
+winStoreColorsNativeGDI (ColormapPtr pmap, 
+			 int ndef,
+			 xColorItem *pdefs);
+
+static Bool
+winCreateColormapNativeGDI (ColormapPtr pColormap);
+
+static Bool
+winDestroyColormapNativeGDI (ColormapPtr pColormap);
+
+
+
+static Bool
+winAllocateFBNativeGDI (ScreenPtr pScreen)
+{
+  FatalError ("winAllocateFBNativeGDI\n");
+
+  return TRUE;
+}
+
+
+/*
+ * We wrap whatever CloseScreen procedure was specified by fb;
+ * a pointer to said procedure is stored in our privates.
+ */
+
+static Bool
+winCloseScreenNativeGDI (int nIndex, ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+
+  ErrorF ("winCloseScreenNativeGDI - Freeing screen resources\n");
+
+  /* Flag that the screen is closed */
+  pScreenPriv->fClosed = TRUE;
+  pScreenPriv->fActive = FALSE;
+
+  /* 
+   * NOTE: mi doesn't use a CloseScreen procedure, so we do not
+   * need to call a wrapped procedure here.
+   */
+
+  /* Delete the window property */
+  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
+  
+  ErrorF ("winCloseScreenNativeGDI - Destroying window\n");
+  
+  /* Delete tray icon, if we have one */
+  if (!pScreenInfo->fNoTrayIcon)
+    winDeleteNotifyIcon (pScreenPriv);
+
+  /* Free the exit confirmation dialog box, if it exists */
+  if (g_hDlgExit != NULL)
+    {
+      DestroyWindow (g_hDlgExit);
+      g_hDlgExit = NULL;
+    }
+
+  /* Kill our window */
+  if (pScreenPriv->hwndScreen)
+    {
+      DestroyWindow (pScreenPriv->hwndScreen);
+      pScreenPriv->hwndScreen = NULL;
+    }
+
+  /* Invalidate our screeninfo's pointer to the screen */
+  pScreenInfo->pScreen = NULL;
+
+  /* Free the screen privates for this screen */
+  free (pScreenPriv);
+
+  ErrorF ("winCloseScreenNativeGDI - Returning\n");
+
+  return TRUE;
+}
+
+
+static void
+winShadowUpdateNativeGDI (ScreenPtr pScreen, 
+			  shadowBufPtr pBuf)
+{
+  FatalError ("winShadowUpdateNativeGDI\n");
+  return;
+}
+
+
+static Bool
+winInitVisualsNativeGDI (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+
+  /* Set the bitsPerRGB and bit masks */
+  switch (pScreenInfo->dwDepth)
+    {
+    case 24:
+      pScreenPriv->dwBitsPerRGB = 8;
+      pScreenPriv->dwRedMask = 0x00FF0000;
+      pScreenPriv->dwGreenMask = 0x0000FF00;
+      pScreenPriv->dwBlueMask = 0x000000FF;
+      break;
+      
+    case 16:
+      pScreenPriv->dwBitsPerRGB = 6;
+      pScreenPriv->dwRedMask = 0xF800;
+      pScreenPriv->dwGreenMask = 0x07E0;
+      pScreenPriv->dwBlueMask = 0x001F;
+      break;
+      
+    case 15:
+      pScreenPriv->dwBitsPerRGB = 5;
+      pScreenPriv->dwRedMask = 0x7C00;
+      pScreenPriv->dwGreenMask = 0x03E0;
+      pScreenPriv->dwBlueMask = 0x001F;
+      break;
+      
+    case 8:
+      pScreenPriv->dwBitsPerRGB = 8;
+      pScreenPriv->dwRedMask = 0;
+      pScreenPriv->dwGreenMask = 0;
+      pScreenPriv->dwBlueMask = 0;
+      break;
+
+    default:
+      ErrorF ("winInitVisualsNativeGDI - Unknown screen depth\n");
+      return FALSE;
+      break;
+    }
+
+  /* Tell the user how many bits per RGB we are using */
+  ErrorF ("winInitVisualsNativeGDI - Using dwBitsPerRGB: %d\n",
+	  (int) pScreenPriv->dwBitsPerRGB);
+
+  /* Create a single visual according to the Windows screen depth */
+  switch (pScreenInfo->dwDepth)
+    {
+    case 24:
+    case 16:
+    case 15:
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     TrueColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     TrueColor,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisuals - miSetVisualTypesAndMasks failed\n");
+	  return FALSE;
+	}
+      break;
+
+    case 8:
+      ErrorF ("winInitVisuals - Calling miSetVisualTypesAndMasks\n");
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     StaticColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     StaticColor,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisuals - miSetVisualTypesAndMasks failed\n");
+	  return FALSE;
+	}
+      break;
+
+    default:
+      ErrorF ("winInitVisualsNativeGDI - Unknown screen depth\n");
+      return FALSE;
+    }
+
+#if 1
+  ErrorF ("winInitVisualsNativeGDI - Returning\n");
+#endif
+
+  return TRUE;
+}
+
+
+/* Adjust the video mode */
+static Bool
+winAdjustVideoModeNativeGDI (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  HDC			hdc = NULL;
+  DWORD			dwBPP;
+  
+  hdc = GetDC (NULL);
+
+  /* We're in serious trouble if we can't get a DC */
+  if (hdc == NULL)
+    {
+      ErrorF ("winAdjustVideoModeNativeGDI - GetDC () failed\n");
+      return FALSE;
+    }
+
+  /* Query GDI for current display depth */
+  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
+  pScreenInfo->dwDepth = GetDeviceCaps (hdc, PLANES);
+
+  switch (pScreenInfo->dwDepth) {
+    case 24:
+    case 16:
+    case 15:
+    case 8:
+      break;
+    default:
+      if (dwBPP == 32)
+        pScreenInfo->dwDepth = 24;
+      else
+        pScreenInfo->dwDepth = dwBPP; 
+      break;
+  }
+
+  /* GDI cannot change the screen depth */
+  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
+    {
+      /* No -depth parameter passed, let the user know the depth being used */
+      ErrorF ("winAdjustVideoModeNativeGDI - Using Windows display "
+	      "depth of %d bits per pixel, %d depth\n",
+	      (int) dwBPP, (int) pScreenInfo->dwDepth);
+
+      /* Use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+  else if (dwBPP != pScreenInfo->dwBPP)
+    {
+      /* Warn user if GDI depth is different than -depth parameter */
+      ErrorF ("winAdjustVideoModeNativeGDI - Command line bpp: %d, "\
+	      "using bpp: %d\n",
+	      (int) pScreenInfo->dwBPP, (int) dwBPP);
+
+      /* We'll use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+  
+  /* Release our DC */
+  ReleaseDC (NULL, hdc);
+
+  return TRUE;
+}
+
+
+static Bool
+winActivateAppNativeGDI (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+
+  /*
+   * Are we active?
+   * Are we fullscreen?
+   */
+  if (pScreenPriv != NULL
+      && pScreenPriv->fActive
+      && pScreenInfo->fFullScreen)
+    {
+      /*
+       * Activating, attempt to bring our window 
+       * to the top of the display
+       */
+      ShowWindow (pScreenPriv->hwndScreen, SW_RESTORE);
+    }
+
+  /*
+   * Are we inactive?
+   * Are we fullscreen?
+   */
+  if (pScreenPriv != NULL
+      && !pScreenPriv->fActive
+      && pScreenInfo->fFullScreen)
+    {
+      /*
+       * Deactivating, stuff our window onto the
+       * task bar.
+       */
+      ShowWindow (pScreenPriv->hwndScreen, SW_MINIMIZE);
+    }
+
+  return TRUE;
+}
+
+
+HBITMAP
+winCreateDIBNativeGDI (int iWidth, int iHeight, int iDepth,
+		       BYTE **ppbBits, BITMAPINFO **ppbmi)
+{
+  BITMAPINFOHEADER	*pbmih = NULL;
+  HBITMAP		hBitmap = NULL;
+  BITMAPINFO		*pbmi = NULL;
+
+  /* Don't create an invalid bitmap */
+  if (iWidth == 0
+      || iHeight == 0
+      || iDepth == 0)
+    {
+      ErrorF ("\nwinCreateDIBNativeGDI - Invalid specs w %d h %d d %d\n\n",
+	      iWidth, iHeight, iDepth);
+      return NULL;
+    }
+
+  /* Allocate bitmap info header */
+  pbmih = (BITMAPINFOHEADER*) malloc (sizeof (BITMAPINFOHEADER)
+				      + 256 * sizeof (RGBQUAD));
+  if (pbmih == NULL)
+    {
+      ErrorF ("winCreateDIBNativeGDI - malloc () failed\n");
+      return FALSE;
+    }
+  ZeroMemory (pbmih, sizeof(BITMAPINFOHEADER) + 256 * sizeof (RGBQUAD));
+
+  /* Describe bitmap to be created */
+  pbmih->biSize = sizeof (BITMAPINFOHEADER);
+  pbmih->biWidth = iWidth;
+  pbmih->biHeight = -iHeight;
+  pbmih->biPlanes = 1;
+  pbmih->biBitCount = iDepth;
+  pbmih->biCompression = BI_RGB;
+  pbmih->biSizeImage = 0;
+  pbmih->biXPelsPerMeter = 0;
+  pbmih->biYPelsPerMeter = 0;
+  pbmih->biClrUsed = 0;
+  pbmih->biClrImportant = 0;
+
+  /* Setup color table for mono DIBs */
+  if (iDepth == 1)
+    {
+      pbmi = (BITMAPINFO*) pbmih;
+      pbmi->bmiColors[1].rgbBlue = 255;
+      pbmi->bmiColors[1].rgbGreen = 255;
+      pbmi->bmiColors[1].rgbRed = 255;
+    }
+
+  /* Create a DIB with a bit pointer */
+  hBitmap = CreateDIBSection (NULL,
+			      (BITMAPINFO *) pbmih,
+			      DIB_RGB_COLORS,
+			      (void **) ppbBits,
+			      NULL,
+			      0);
+  if (hBitmap == NULL)
+    {
+      ErrorF ("winCreateDIBNativeGDI - CreateDIBSection () failed\n");
+      return NULL;
+    }
+
+  /* Free the bitmap info header memory */
+  if (ppbmi != NULL)
+    {
+      /* Store the address of the BMIH in the ppbmih parameter */
+      *ppbmi = (BITMAPINFO *) pbmih;
+    }
+  else
+    {
+      free (pbmih);
+      pbmih = NULL;
+    }
+
+  return hBitmap;
+}
+
+
+#if 0
+static Bool
+winBltExposedRegionsNativeGDI (ScreenPtr pScreen)
+{
+  
+  return TRUE;
+}
+#endif
+
+
+static Bool
+winRedrawScreenNativeGDI (ScreenPtr pScreen)
+{
+  FatalError ("winRedrawScreenNativeGDI\n");
+  return TRUE;
+}
+
+
+static Bool
+winRealizeInstalledPaletteNativeGDI (ScreenPtr pScreen)
+{
+  FatalError ("winRealizeInstalledPaletteNativeGDI\n");
+  return TRUE;
+}
+
+
+static Bool
+winInstallColormapNativeGDI (ColormapPtr pColormap)
+{
+  FatalError ("winInstallColormapNativeGDI\n");
+  return TRUE;
+}
+
+
+static Bool
+winStoreColorsNativeGDI (ColormapPtr pmap, 
+			 int ndef,
+			 xColorItem *pdefs)
+{
+  FatalError ("winStoreColorsNativeGDI\n");
+  return TRUE;
+}
+
+
+static Bool
+winCreateColormapNativeGDI (ColormapPtr pColormap)
+{
+  FatalError ("winCreateColormapNativeGDI\n");
+  return TRUE;
+}
+
+
+static Bool
+winDestroyColormapNativeGDI (ColormapPtr pColormap)
+{
+  FatalError ("winDestroyColormapNativeGDI\n");
+  return TRUE;
+}
+
+
+/* Set engine specific funtions */
+Bool
+winSetEngineFunctionsNativeGDI (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  
+  /* Set our pointers */
+  pScreenPriv->pwinAllocateFB = winAllocateFBNativeGDI;
+  pScreenPriv->pwinShadowUpdate = winShadowUpdateNativeGDI;
+  pScreenPriv->pwinCloseScreen = winCloseScreenNativeGDI;
+  pScreenPriv->pwinInitVisuals = winInitVisualsNativeGDI;
+  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModeNativeGDI;
+  if (pScreenInfo->fFullScreen)
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
+  else
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
+  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitNativeGDI;
+  /*
+   * WARNING: Do not set the BltExposedRegions procedure pointer to anything
+   * other than NULL until a working painting procedure is in place.
+   * Else, winWindowProc will get stuck in an infinite loop because
+   * Windows expects the BeginPaint and EndPaint functions to be called
+   * before a WM_PAINT message can be removed from the queue.  We are
+   * using NULL here as a signal for winWindowProc that it should
+   * not signal that the WM_PAINT message has been processed.
+   */
+  pScreenPriv->pwinBltExposedRegions = NULL;
+  pScreenPriv->pwinActivateApp = winActivateAppNativeGDI;
+  pScreenPriv->pwinRedrawScreen = winRedrawScreenNativeGDI;
+  pScreenPriv->pwinRealizeInstalledPalette = 
+    winRealizeInstalledPaletteNativeGDI;
+  pScreenPriv->pwinInstallColormap = winInstallColormapNativeGDI;
+  pScreenPriv->pwinStoreColors = winStoreColorsNativeGDI;
+  pScreenPriv->pwinCreateColormap = winCreateColormapNativeGDI;
+  pScreenPriv->pwinDestroyColormap = winDestroyColormapNativeGDI;
+  pScreenPriv->pwinHotKeyAltTab = (winHotKeyAltTabProcPtr) (void (*)(void))NoopDDA;
+
+  return TRUE;
+}
diff --git a/hw/xwin/winpfbdd.c b/hw/xwin/winpfbdd.c
new file mode 100644
index 0000000..13fc105
--- /dev/null
+++ b/hw/xwin/winpfbdd.c
@@ -0,0 +1,684 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * External symbols
+ */
+
+extern const GUID		_IID_IDirectDraw2;
+extern HWND			g_hDlgExit;
+
+
+/*
+ * Local function prototypes
+ */
+
+static Bool
+winAllocateFBPrimaryDD (ScreenPtr pScreen);
+
+static Bool
+winCloseScreenPrimaryDD (int nIndex, ScreenPtr pScreen);
+
+static Bool
+winInitVisualsPrimaryDD (ScreenPtr pScreen);
+
+static Bool
+winAdjustVideoModePrimaryDD (ScreenPtr pScreen);
+
+static Bool
+winActivateAppPrimaryDD (ScreenPtr pScreen);
+
+static Bool
+winHotKeyAltTabPrimaryDD (ScreenPtr pScreen);
+
+
+/*
+ * Create a DirectDraw primary surface 
+ */
+
+static Bool
+winAllocateFBPrimaryDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;  
+  HRESULT		ddrval = DD_OK;
+  DDSURFACEDESC		ddsd;
+  DDSURFACEDESC		*pddsdPrimary = NULL;
+  DDSURFACEDESC		*pddsdOffscreen = NULL;
+  RECT			rcClient;
+
+  ErrorF ("winAllocateFBPrimaryDD\n");
+
+  /* Get client area location in screen coords */
+  GetClientRect (pScreenPriv->hwndScreen, &rcClient);
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&rcClient, 2);
+
+  /* Create a DirectDraw object, store the address at lpdd */
+  ddrval = (*g_fpDirectDrawCreate) (NULL, &pScreenPriv->pdd, NULL);
+  if (ddrval != DD_OK)
+    FatalError ("winAllocateFBPrimaryDD - Could not start DirectDraw\n");
+  
+  /* Get a DirectDraw2 interface pointer */
+  ddrval = IDirectDraw_QueryInterface (pScreenPriv->pdd,
+				       &IID_IDirectDraw2,
+				       (LPVOID*) &pScreenPriv->pdd2);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDD - Failed DD2 query: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+
+  ErrorF ("winAllocateFBPrimaryDD - Created and initialized DD\n");
+
+  /* Are we windowed or fullscreen? */
+  if (pScreenInfo->fFullScreen)
+    {
+      /* Full screen mode */
+      ddrval = IDirectDraw2_SetCooperativeLevel (pScreenPriv->pdd2,
+						 pScreenPriv->hwndScreen,
+						 DDSCL_FULLSCREEN
+						 | DDSCL_EXCLUSIVE);
+      if (FAILED (ddrval))
+	FatalError ("winAllocateFBPrimaryDD - Could not set "
+		    "cooperative level\n");
+
+      /* Change the video mode to the mode requested */
+      ddrval = IDirectDraw2_SetDisplayMode (pScreenPriv->pdd2,
+					    pScreenInfo->dwWidth,
+					    pScreenInfo->dwHeight,
+					    pScreenInfo->dwBPP,
+					    pScreenInfo->dwRefreshRate,
+					    0);
+       if (FAILED (ddrval))
+	FatalError ("winAllocateFBPrimaryDD - Could not set "
+		    "full screen display mode\n");
+    }
+  else
+    {
+      /* Windowed mode */
+      ddrval = IDirectDraw2_SetCooperativeLevel (pScreenPriv->pdd2,
+						 pScreenPriv->hwndScreen,
+						 DDSCL_NORMAL);
+      if (FAILED (ddrval))
+	FatalError ("winAllocateFBPrimaryDD - Could not set "
+		    "cooperative level\n");
+    }
+
+  /* Describe the primary surface */
+  ZeroMemory (&ddsd, sizeof (ddsd));
+  ddsd.dwSize = sizeof (ddsd);
+  ddsd.dwFlags = DDSD_CAPS;
+  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
+  
+  /* Create the primary surface */
+  ddrval = IDirectDraw2_CreateSurface (pScreenPriv->pdd2,
+				       &ddsd,
+				       &pScreenPriv->pddsPrimary,
+				       NULL);
+  if (FAILED (ddrval))
+       FatalError ("winAllocateFBPrimaryDD - Could not create primary "
+		  "surface %08x\n", (unsigned int) ddrval);
+
+  ErrorF ("winAllocateFBPrimaryDD - Created primary\n");
+
+  /* Allocate a DD surface description for our screen privates */
+  pddsdPrimary = pScreenPriv->pddsdPrimary
+    = malloc (sizeof (DDSURFACEDESC));
+  if (pddsdPrimary == NULL)
+    FatalError ("winAllocateFBPrimaryDD - Could not allocate surface "
+		"description memory\n");
+  ZeroMemory (pddsdPrimary, sizeof (*pddsdPrimary));
+  pddsdPrimary->dwSize = sizeof (*pddsdPrimary);
+
+  /* Describe the offscreen surface to be created */
+  /*
+   * NOTE: Do not use a DDSCAPS_VIDEOMEMORY surface,
+   * as drawing, locking, and unlocking take forever
+   * with video memory surfaces.  In addition,
+   * video memory is a somewhat scarce resource,
+   * so you shouldn't be allocating video memory when
+   * you have the option of using system memory instead.
+   */
+  ZeroMemory (&ddsd, sizeof (ddsd));
+  ddsd.dwSize = sizeof (ddsd);
+  ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
+  ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
+  ddsd.dwHeight = pScreenInfo->dwHeight;
+  ddsd.dwWidth = pScreenInfo->dwWidth;
+
+  /* Create the shadow surface */
+  ddrval = IDirectDraw2_CreateSurface (pScreenPriv->pdd2,
+				       &ddsd,
+				       &pScreenPriv->pddsOffscreen,
+				       NULL);
+  if (ddrval != DD_OK)
+    FatalError ("winAllocateFBPrimaryDD - Could not create shadow "
+		"surface\n");
+  
+  ErrorF ("winAllocateFBPrimaryDD - Created offscreen\n");
+
+  /* Allocate a DD surface description for our screen privates */
+  pddsdOffscreen = pScreenPriv->pddsdOffscreen
+    = malloc (sizeof (DDSURFACEDESC));
+  if (pddsdOffscreen == NULL)
+    FatalError ("winAllocateFBPrimaryDD - Could not allocate surface "
+		"description memory\n");
+  ZeroMemory (pddsdOffscreen, sizeof (*pddsdOffscreen));
+  pddsdOffscreen->dwSize = sizeof (*pddsdOffscreen);
+
+  ErrorF ("winAllocateFBPrimaryDD - Locking primary\n");
+
+  /* Lock the primary surface */
+  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsPrimary,
+				    pScreenInfo->fFullScreen ? NULL:&rcClient,
+				    pddsdPrimary,
+				    DDLOCK_WAIT,
+				    NULL);
+  if (ddrval != DD_OK || pddsdPrimary->lpSurface == NULL)
+    FatalError ("winAllocateFBPrimaryDD - Could not lock "
+		"primary surface\n");
+
+  ErrorF ("winAllocateFBPrimaryDD - Locked primary\n");
+
+  /* We don't know how to deal with anything other than RGB */
+  if (!(pddsdPrimary->ddpfPixelFormat.dwFlags & DDPF_RGB))
+    FatalError ("winAllocateFBPrimaryDD - Color format other than RGB\n");
+
+  /* Grab the pitch from the surface desc */
+  pScreenInfo->dwStride = (pddsdPrimary->u1.lPitch * 8)
+    / pScreenInfo->dwBPP;
+
+  /* Save the pointer to our surface memory */
+  pScreenInfo->pfb = pddsdPrimary->lpSurface;
+  
+  /* Grab the color depth and masks from the surface description */
+  pScreenPriv->dwRedMask = pddsdPrimary->ddpfPixelFormat.u2.dwRBitMask;
+  pScreenPriv->dwGreenMask = pddsdPrimary->ddpfPixelFormat.u3.dwGBitMask;
+  pScreenPriv->dwBlueMask = pddsdPrimary->ddpfPixelFormat.u4.dwBBitMask;
+
+  ErrorF ("winAllocateFBPrimaryDD - Returning\n");
+
+  return TRUE;
+}
+
+
+/*
+ * Call the wrapped CloseScreen function.
+ * 
+ * Free our resources and private structures.
+ */
+
+static Bool
+winCloseScreenPrimaryDD (int nIndex, ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  Bool			fReturn;
+  
+  ErrorF ("winCloseScreenPrimaryDD - Freeing screen resources\n");
+
+  /* Flag that the screen is closed */
+  pScreenPriv->fClosed = TRUE;
+  pScreenPriv->fActive = FALSE;
+
+  /* Call the wrapped CloseScreen procedure */
+  WIN_UNWRAP(CloseScreen);
+  fReturn = (*pScreen->CloseScreen) (nIndex, pScreen);
+
+  /* Delete the window property */
+  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
+
+  /* Free the offscreen surface, if there is one */
+  if (pScreenPriv->pddsOffscreen)
+    {
+      IDirectDrawSurface2_Unlock (pScreenPriv->pddsOffscreen, NULL);
+      IDirectDrawSurface2_Release (pScreenPriv->pddsOffscreen);
+      pScreenPriv->pddsOffscreen = NULL;
+    }
+
+  /* Release the primary surface, if there is one */
+  if (pScreenPriv->pddsPrimary)
+    {
+      IDirectDrawSurface2_Unlock (pScreenPriv->pddsPrimary, NULL);
+      IDirectDrawSurface2_Release (pScreenPriv->pddsPrimary);
+      pScreenPriv->pddsPrimary = NULL;
+    }
+
+  /* Free the DirectDraw object, if there is one */
+  if (pScreenPriv->pdd)
+    {
+      IDirectDraw2_RestoreDisplayMode (pScreenPriv->pdd);
+      IDirectDraw2_Release (pScreenPriv->pdd);
+      pScreenPriv->pdd = NULL;
+    }
+
+  /* Delete tray icon, if we have one */
+  if (!pScreenInfo->fNoTrayIcon)
+    winDeleteNotifyIcon (pScreenPriv);
+
+  /* Free the exit confirmation dialog box, if it exists */
+  if (g_hDlgExit != NULL)
+    {
+      DestroyWindow (g_hDlgExit);
+      g_hDlgExit = NULL;
+    }
+
+  /* Kill our window */
+  if (pScreenPriv->hwndScreen)
+    {
+      DestroyWindow (pScreenPriv->hwndScreen);
+      pScreenPriv->hwndScreen = NULL;
+    }
+
+  /* Kill our screeninfo's pointer to the screen */
+  pScreenInfo->pScreen = NULL;
+
+  /* Invalidate the ScreenInfo's fb pointer */
+  pScreenInfo->pfb = NULL;
+
+  /* Free the screen privates for this screen */
+  free ((pointer) pScreenPriv);
+
+  return fReturn;
+}
+
+
+/*
+ * Tell mi what sort of visuals we need.
+ * 
+ * Generally we only need one visual, as our screen can only
+ * handle one format at a time, I believe.  You may want
+ * to verify that last sentence.
+ */
+
+static Bool
+winInitVisualsPrimaryDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  DWORD			dwRedBits, dwGreenBits, dwBlueBits;
+
+  /* Count the number of ones in each color mask */
+  dwRedBits = winCountBits (pScreenPriv->dwRedMask);
+  dwGreenBits = winCountBits (pScreenPriv->dwGreenMask);
+  dwBlueBits = winCountBits (pScreenPriv->dwBlueMask);
+  
+  /* Store the maximum number of ones in a color mask as the bitsPerRGB */
+  if (dwRedBits > dwGreenBits && dwRedBits > dwBlueBits)
+    pScreenPriv->dwBitsPerRGB = dwRedBits;
+  else if (dwGreenBits > dwRedBits && dwGreenBits > dwBlueBits)
+    pScreenPriv->dwBitsPerRGB = dwGreenBits;
+  else
+    pScreenPriv->dwBitsPerRGB = dwBlueBits;
+  
+  ErrorF ("winInitVisualsPrimaryDD - Masks: %08x %08x %08x bpRGB: %d\n",
+	  (unsigned int) pScreenPriv->dwRedMask,
+	  (unsigned int) pScreenPriv->dwGreenMask,
+	  (unsigned int) pScreenPriv->dwBlueMask,
+	  (int) pScreenPriv->dwBitsPerRGB);
+
+  /* Create a single visual according to the Windows screen depth */
+  switch (pScreenInfo->dwDepth)
+    {
+    case 24:
+    case 16:
+    case 15:
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     TrueColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     TrueColor,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsPrimaryDD - " 
+		  "miSetVisualTypesAndMasks failed\n");
+	  return FALSE;
+	}
+      break;
+
+    case 8:
+#if CYGDEBUG
+      winDebug ("winInitVisuals - Calling miSetVisualTypesAndMasks\n");
+#endif /* CYGDEBUG */
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     PseudoColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     PseudoColor,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsPrimaryDD - "
+		  "miSetVisualTypesAndMasks failed\n");
+	  return FALSE;
+	}
+#if CYGDEBUG
+      winDebug ("winInitVisualsPrimaryDD - Returned from "
+	      "miSetVisualTypesAndMasks\n");
+#endif /* CYGDEBUG */
+      break;
+
+    default:
+      ErrorF ("winInitVisualsPrimaryDD - Unknown screen depth\n");
+      return FALSE;
+    }
+
+  ErrorF ("winInitVisualsPrimaryDD - Returning\n");
+
+  return TRUE;
+}
+
+
+static Bool
+winAdjustVideoModePrimaryDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  HDC			hdc = NULL;
+  DWORD			dwBPP;
+
+  /* We're in serious trouble if we can't get a DC */
+  hdc = GetDC (NULL);
+  if (hdc == NULL)
+    {
+      ErrorF ("winAdjustVideoModePrimaryDD - GetDC failed\n");
+      return FALSE;
+    }
+
+  /* Query GDI for current display depth */
+  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
+
+  /* DirectDraw can only change the depth in fullscreen mode */
+  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
+    {
+      /* No -depth parameter passed, let the user know the depth being used */
+      ErrorF ("winAdjustVideoModePrimaryDD - Using Windows display "
+	      "depth of %d bits per pixel\n", (int) dwBPP);
+
+      /* Use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+  else if (pScreenInfo->fFullScreen
+	   && pScreenInfo->dwBPP != dwBPP)
+    {
+      /* FullScreen, and GDI depth differs from -depth parameter */
+      ErrorF ("winAdjustVideoModePrimaryDD - FullScreen, using command "
+	      "line depth: %d\n", (int) pScreenInfo->dwBPP);
+    }
+  else if (dwBPP != pScreenInfo->dwBPP)
+    {
+      /* Windowed, and GDI depth differs from -depth parameter */
+      ErrorF ("winAdjustVideoModePrimaryDD - Windowed, command line "
+	      "depth: %d, using depth: %d\n",
+	      (int) pScreenInfo->dwBPP, (int) dwBPP);
+
+      /* We'll use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+  
+  /* Release our DC */
+  ReleaseDC (NULL, hdc);
+
+  return TRUE;
+}
+
+
+/*
+ * We need to blit our offscreen fb to
+ * the screen when we are activated, and we need to point
+ * the fb code back to the primary surface memory.
+ */
+
+static Bool
+winActivateAppPrimaryDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  RECT			rcSrc, rcClient;
+  HRESULT		ddrval = DD_OK;
+
+  /* Check for errors */
+  if (pScreenPriv == NULL
+      || pScreenPriv->pddsPrimary == NULL
+      || pScreenPriv->pddsOffscreen == NULL)
+    return FALSE;
+
+  /* Check for do-nothing */
+  if (!pScreenPriv->fActive)
+    return TRUE;
+  
+  /* We are activating */
+  ddrval = IDirectDrawSurface2_IsLost (pScreenPriv->pddsOffscreen);
+  if (ddrval == DD_OK)
+    {
+      IDirectDrawSurface2_Unlock (pScreenPriv->pddsOffscreen,
+				  NULL);
+      /*
+       * We don't check for an error from Unlock, because it
+       * doesn't matter if the Unlock failed.
+       */
+    }
+
+  /* Restore both surfaces, just cause I like it that way */
+  IDirectDrawSurface2_Restore (pScreenPriv->pddsOffscreen);
+  IDirectDrawSurface2_Restore (pScreenPriv->pddsPrimary);
+			      
+  /* Get client area in screen coords */
+  GetClientRect (pScreenPriv->hwndScreen, &rcClient);
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&rcClient, 2);
+
+  /* Setup a source rectangle */
+  rcSrc.left = 0;
+  rcSrc.top = 0;
+  rcSrc.right = pScreenInfo->dwWidth;
+  rcSrc.bottom = pScreenInfo->dwHeight;
+
+  ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
+				    &rcClient,
+				    pScreenPriv->pddsOffscreen,
+				    &rcSrc,
+				    DDBLT_WAIT,
+				    NULL);
+  if (ddrval != DD_OK)
+    FatalError ("winActivateAppPrimaryDD () - Failed blitting offscreen "
+		"surface to primary surface %08x\n", (unsigned int) ddrval);
+  
+  /* Lock the primary surface */
+  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsPrimary,
+				     &rcClient,
+				     pScreenPriv->pddsdPrimary,
+				     DDLOCK_WAIT,
+				     NULL);
+  if (ddrval != DD_OK
+      || pScreenPriv->pddsdPrimary->lpSurface == NULL)
+    FatalError ("winActivateAppPrimaryDD () - Could not lock "
+		"primary surface\n");
+
+  /* Notify FB of the new memory pointer */
+  winUpdateFBPointer (pScreen,
+		      pScreenPriv->pddsdPrimary->lpSurface);
+
+  /*
+   * Register the Alt-Tab combo as a hotkey so we can copy
+   * the primary framebuffer before the display mode changes
+   */
+  RegisterHotKey (pScreenPriv->hwndScreen, 1, MOD_ALT, 9);
+
+  return TRUE;
+}
+
+
+/*
+ * Handle the Alt+Tab hotkey.
+ *
+ * We need to save the primary fb to an offscreen fb when
+ * we get deactivated, and point the fb code at the offscreen
+ * fb for the duration of the deactivation.
+ */
+
+static Bool
+winHotKeyAltTabPrimaryDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  RECT			rcClient, rcSrc;
+  HRESULT		ddrval = DD_OK;
+
+  ErrorF ("\nwinHotKeyAltTabPrimaryDD\n\n");
+
+  /* Alt+Tab was pressed, we will lose focus very soon */
+  pScreenPriv->fActive = FALSE;
+  
+  /* Check for error conditions */
+  if (pScreenPriv->pddsPrimary == NULL
+      || pScreenPriv->pddsOffscreen == NULL)
+    return FALSE;
+
+  /* Get client area in screen coords */
+  GetClientRect (pScreenPriv->hwndScreen, &rcClient);
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&rcClient, 2);
+
+  /* Did we loose the primary surface? */
+  ddrval = IDirectDrawSurface2_IsLost (pScreenPriv->pddsPrimary);
+  if (ddrval == DD_OK)
+    {
+      ddrval = IDirectDrawSurface2_Unlock (pScreenPriv->pddsPrimary,
+					   NULL);
+      if (FAILED (ddrval))
+	FatalError ("winHotKeyAltTabPrimaryDD - Failed unlocking primary "
+		    "surface\n");
+    }
+
+  /* Setup a source rectangle */
+  rcSrc.left = 0;
+  rcSrc.top = 0;
+  rcSrc.right = pScreenInfo->dwWidth;
+  rcSrc.bottom = pScreenInfo->dwHeight;
+
+      /* Blit the primary surface to the offscreen surface */
+  ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsOffscreen,
+				    NULL, /* should be rcDest */
+				    pScreenPriv->pddsPrimary,
+				    NULL,
+				    DDBLT_WAIT,
+				    NULL);
+  if (ddrval == DDERR_SURFACELOST)
+    {
+      IDirectDrawSurface2_Restore (pScreenPriv->pddsOffscreen);  
+      IDirectDrawSurface2_Restore (pScreenPriv->pddsPrimary);
+		  		  
+      /* Blit the primary surface to the offscreen surface */
+      ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsOffscreen,
+					NULL,
+					pScreenPriv->pddsPrimary,
+					NULL,
+					DDBLT_WAIT,
+					NULL);
+      if (FAILED (ddrval))
+	FatalError ("winHotKeyAltTabPrimaryDD - Failed blitting primary "
+		    "surface to offscreen surface: %08x\n",
+		    (unsigned int) ddrval);
+    }
+  else
+    {
+      FatalError ("winHotKeyAltTabPrimaryDD - Unknown error from "
+		  "Blt: %08dx\n", (unsigned int) ddrval);
+    }
+
+  /* Lock the offscreen surface */
+  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsOffscreen,
+				     NULL,
+				     pScreenPriv->pddsdOffscreen,
+				     DDLOCK_WAIT,
+				     NULL);
+  if (ddrval != DD_OK
+      || pScreenPriv->pddsdPrimary->lpSurface == NULL)
+    FatalError ("winHotKeyAltTabPrimaryDD - Could not lock "
+		"offscreen surface\n");
+
+  /* Notify FB of the new memory pointer */
+  winUpdateFBPointer (pScreen,
+		      pScreenPriv->pddsdOffscreen->lpSurface);
+
+  /* Unregister our hotkey */
+  UnregisterHotKey (pScreenPriv->hwndScreen, 1);
+
+  return TRUE;
+}
+
+
+/* Set engine specific functions */
+Bool
+winSetEngineFunctionsPrimaryDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  
+  /* Set our pointers */
+  pScreenPriv->pwinAllocateFB = winAllocateFBPrimaryDD;
+  pScreenPriv->pwinShadowUpdate
+    = (winShadowUpdateProcPtr) (void (*)(void))NoopDDA;
+  pScreenPriv->pwinCloseScreen = winCloseScreenPrimaryDD;
+  pScreenPriv->pwinInitVisuals = winInitVisualsPrimaryDD;
+  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModePrimaryDD;
+  if (pScreenInfo->fFullScreen)
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
+  else
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
+  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitFB;
+  pScreenPriv->pwinBltExposedRegions
+    = (winBltExposedRegionsProcPtr) (void (*)(void))NoopDDA;
+  pScreenPriv->pwinActivateApp = winActivateAppPrimaryDD;
+  pScreenPriv->pwinHotKeyAltTab = winHotKeyAltTabPrimaryDD;
+#ifdef XWIN_MULTIWINDOW
+  pScreenPriv->pwinFinishCreateWindowsWindow =
+    (winFinishCreateWindowsWindowProcPtr) (void (*)(void))NoopDDA;
+#endif
+
+  return TRUE;
+}
diff --git a/hw/xwin/winpixmap.c b/hw/xwin/winpixmap.c
new file mode 100644
index 0000000..050c71a
--- /dev/null
+++ b/hw/xwin/winpixmap.c
@@ -0,0 +1,235 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	drewry, september 1986
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * Local prototypes
+ */
+
+#if 0
+static void
+winXRotatePixmapNativeGDI (PixmapPtr pPix, int rw);
+
+static void
+winYRotatePixmapNativeGDI (PixmapPtr pPix, int rh);
+
+static void
+winCopyRotatePixmapNativeGDI (PixmapPtr psrcPix, PixmapPtr *ppdstPix,
+			      int xrot, int yrot);
+#endif
+
+
+/* See Porting Layer Definition - p. 34 */
+/* See mfb/mfbpixmap.c - mfbCreatePixmap() */
+PixmapPtr
+winCreatePixmapNativeGDI (ScreenPtr pScreen,
+			  int iWidth, int iHeight,
+			  int iDepth, unsigned usage_hint)
+{
+  winPrivPixmapPtr	pPixmapPriv = NULL;
+  PixmapPtr		pPixmap = NULL;
+
+  /* Allocate pixmap memory */
+  pPixmap = AllocatePixmap (pScreen, 0);
+  if (!pPixmap)
+    {
+      ErrorF ("winCreatePixmapNativeGDI () - Couldn't allocate a pixmap\n");
+      return NullPixmap;
+    }
+
+#if CYGDEBUG
+  winDebug ("winCreatePixmap () - w %d h %d d %d uh %d bw %d\n",
+	  iWidth, iHeight, iDepth, usage_hint,
+	  PixmapBytePad (iWidth, iDepth));
+#endif
+
+  /* Setup pixmap values */
+  pPixmap->drawable.type = DRAWABLE_PIXMAP;
+  pPixmap->drawable.class = 0;
+  pPixmap->drawable.pScreen = pScreen;
+  pPixmap->drawable.depth = iDepth;
+  pPixmap->drawable.bitsPerPixel = BitsPerPixel (iDepth);
+  pPixmap->drawable.id = 0;
+  pPixmap->drawable.serialNumber = NEXT_SERIAL_NUMBER;
+  pPixmap->drawable.x = 0;
+  pPixmap->drawable.y = 0;
+  pPixmap->drawable.width = iWidth;
+  pPixmap->drawable.height = iHeight;
+  pPixmap->devKind = 0;
+  pPixmap->refcnt = 1;
+  pPixmap->devPrivate.ptr = NULL;
+  pPixmap->usage_hint = usage_hint;
+
+  /* Pixmap privates are allocated by AllocatePixmap */
+  pPixmapPriv = winGetPixmapPriv (pPixmap);
+
+  /* Initialize pixmap privates */
+  pPixmapPriv->hBitmap = NULL;
+  pPixmapPriv->hdcSelected = NULL;
+  pPixmapPriv->pbBits = NULL;
+  pPixmapPriv->dwScanlineBytes = PixmapBytePad (iWidth, iDepth);
+
+  /* Check for zero width or height pixmaps */
+  if (iWidth == 0 || iHeight == 0)
+    {
+      /* Don't allocate a real pixmap, just set fields and return */
+      return pPixmap;
+    }
+
+  /* Create a DIB for the pixmap */
+  pPixmapPriv->hBitmap = winCreateDIBNativeGDI (iWidth, iHeight, iDepth,
+						&pPixmapPriv->pbBits,
+						(BITMAPINFO **) &pPixmapPriv->pbmih);
+
+#if CYGDEBUG
+  winDebug ("winCreatePixmap () - Created a pixmap %08x, %dx%dx%d, for " \
+	  "screen: %08x\n",
+	  pPixmapPriv->hBitmap, iWidth, iHeight, iDepth, pScreen);
+#endif
+
+  return pPixmap;
+}
+
+
+/* 
+ * See Porting Layer Definition - p. 35
+ *
+ * See mfb/mfbpixmap.c - mfbDestroyPixmap()
+ */
+
+Bool
+winDestroyPixmapNativeGDI (PixmapPtr pPixmap)
+{
+  winPrivPixmapPtr		pPixmapPriv = NULL;
+  
+#if CYGDEBUG
+  winDebug ("winDestroyPixmapNativeGDI ()\n");
+#endif
+
+  /* Bail early if there is not a pixmap to destroy */
+  if (pPixmap == NULL)
+    {
+      ErrorF ("winDestroyPixmapNativeGDI () - No pixmap to destroy\n");
+      return TRUE;
+    }
+
+  /* Get a handle to the pixmap privates */
+  pPixmapPriv = winGetPixmapPriv (pPixmap);
+
+#if CYGDEBUG
+  winDebug ("winDestroyPixmapNativeGDI - pPixmapPriv->hBitmap: %08x\n",
+	  pPixmapPriv->hBitmap);
+#endif
+
+  /* Decrement reference count, return if nonzero */
+  --pPixmap->refcnt;
+  if (pPixmap->refcnt != 0)
+    return TRUE;
+
+  /* Free GDI bitmap */
+  if (pPixmapPriv->hBitmap) DeleteObject (pPixmapPriv->hBitmap);
+  
+  /* Free the bitmap info header memory */
+  if (pPixmapPriv->pbmih != NULL)
+    {
+      free (pPixmapPriv->pbmih);
+      pPixmapPriv->pbmih = NULL;
+    }
+
+  /* Free the pixmap memory */
+  free (pPixmap);
+  pPixmap = NULL;
+
+  return TRUE;
+}
+
+
+/* 
+ * Not used yet
+ */
+
+Bool
+winModifyPixmapHeaderNativeGDI (PixmapPtr pPixmap,
+				int iWidth, int iHeight,
+				int iDepth,
+				int iBitsPerPixel,
+				int devKind,
+				pointer pPixData)
+{
+  FatalError ("winModifyPixmapHeaderNativeGDI ()\n");
+  return TRUE;
+}
+
+
+#if 0
+/* 
+ * Not used yet.
+ * See cfb/cfbpixmap.c
+ */
+
+static void
+winXRotatePixmapNativeGDI (PixmapPtr pPix, int rw)
+{
+  ErrorF ("winXRotatePixmap()\n");
+  /* fill in this function, look at CFB */
+}
+
+
+/*
+ * Not used yet.
+ * See cfb/cfbpixmap.c
+ */
+static void
+winYRotatePixmapNativeGDI (PixmapPtr pPix, int rh)
+{
+  ErrorF ("winYRotatePixmap()\n");
+  /* fill in this function, look at CFB */
+}
+
+
+/* 
+ * Not used yet.
+ * See cfb/cfbpixmap.c
+ */
+
+static void
+winCopyRotatePixmapNativeGDI (PixmapPtr psrcPix, PixmapPtr *ppdstPix,
+			      int xrot, int yrot)
+{
+  ErrorF ("winCopyRotatePixmap()\n");
+  /* fill in this function, look at CFB */
+}
+#endif
diff --git a/hw/xwin/winpolyline.c b/hw/xwin/winpolyline.c
new file mode 100644
index 0000000..db9dd34
--- /dev/null
+++ b/hw/xwin/winpolyline.c
@@ -0,0 +1,57 @@
+/*
+ *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+/* See Porting Layer Definition - p. 50 */
+void
+winPolyLineNativeGDI (DrawablePtr	pDrawable,
+		      GCPtr		pGC,
+		      int		mode,
+		      int		npt,
+		      DDXPointPtr	ppt)
+{
+  switch (pGC->lineStyle)
+    {
+    case LineSolid:
+      if (pGC->lineWidth == 0)
+	return miZeroLine (pDrawable, pGC, mode, npt, ppt);
+      else
+	miWideLine (pDrawable, pGC, mode, npt, ppt);
+      break;
+    case LineOnOffDash:
+    case LineDoubleDash:
+      miWideDash (pDrawable, pGC, mode, npt, ppt);
+      break;
+    }
+}
diff --git a/hw/xwin/winprefs.c b/hw/xwin/winprefs.c
new file mode 100644
index 0000000..30e587d
--- /dev/null
+++ b/hw/xwin/winprefs.c
@@ -0,0 +1,822 @@
+/*
+ * Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name of the XFree86 Project
+ * shall not be used in advertising or otherwise to promote the sale, use
+ * or other dealings in this Software without prior written authorization
+ * from the XFree86 Project.
+ *
+ * Authors:     Earle F. Philhower, III
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef __CYGWIN__
+#include <sys/resource.h>
+#endif
+#include "win.h"
+
+#include <X11/Xwindows.h>
+#include <shellapi.h>
+
+#include "winprefs.h"
+#include "winmultiwindowclass.h"
+
+/* Where will the custom menu commands start counting from? */
+#define STARTMENUID WM_USER
+
+/* External global variables */
+#ifdef XWIN_MULTIWINDOW
+extern DWORD g_dwCurrentThreadID;
+#endif
+
+extern const char *winGetBaseDir(void);
+
+/* From winmultiwindowflex.l, the real parser */
+extern void parse_file (FILE *fp);
+
+/* From winprefyacc.y, the pref structure loaded by the parser */
+extern WINPREFS pref;
+
+/* The global X default icon */
+extern HICON		g_hIconX;
+extern HICON		g_hSmallIconX;
+
+/* Currently in use command ID, incremented each new menu item created */
+static int g_cmdid = STARTMENUID;
+
+
+/* Defined in DIX */
+extern char *display;
+
+/* Local function to handle comma-ified icon names */
+static HICON
+LoadImageComma (char *fname, int sx, int sy, int flags);
+
+
+/*
+ * Creates or appends a menu from a MENUPARSED structure
+ */
+static HMENU
+MakeMenu (char *name,
+	  HMENU editMenu,
+	  int editItem)
+{
+  int i;
+  int item;
+  MENUPARSED *m;
+  HMENU hmenu, hsub;
+
+  for (i=0; i<pref.menuItems; i++)
+    {
+      if (!strcmp(name, pref.menu[i].menuName))
+	break;
+    }
+  
+  /* Didn't find a match, bummer */
+  if (i==pref.menuItems)
+    {
+      ErrorF("MakeMenu: Can't find menu %s\n", name);
+      return NULL;
+    }
+  
+  m = &(pref.menu[i]);
+
+  if (editMenu)
+    {
+      hmenu = editMenu;
+      item = editItem;
+    }
+  else
+    {
+      hmenu = CreatePopupMenu();
+      if (!hmenu)
+	{
+	  ErrorF("MakeMenu: Unable to CreatePopupMenu() %s\n", name);
+	  return NULL;
+	}
+      item = 0;
+    }
+
+  /* Add the menu items */
+  for (i=0; i<m->menuItems; i++)
+    {
+      /* Only assign IDs one time... */
+      if ( m->menuItem[i].commandID == 0 )
+	m->menuItem[i].commandID = g_cmdid++;
+
+      switch (m->menuItem[i].cmd)
+	{
+	case CMD_EXEC:
+	case CMD_ALWAYSONTOP:
+	case CMD_RELOAD:
+	  InsertMenu (hmenu,
+		      item,
+		      MF_BYPOSITION|MF_ENABLED|MF_STRING,
+		      m->menuItem[i].commandID,
+		      m->menuItem[i].text);
+	  break;
+	  
+	case CMD_SEPARATOR:
+	  InsertMenu (hmenu,
+		      item,
+		      MF_BYPOSITION|MF_SEPARATOR,
+		      0,
+		      NULL);
+	  break;
+	  
+	case CMD_MENU:
+	  /* Recursive! */
+	  hsub = MakeMenu (m->menuItem[i].param, 0, 0);
+	  if (hsub)
+	    InsertMenu (hmenu,
+			item,
+			MF_BYPOSITION|MF_POPUP|MF_ENABLED|MF_STRING,
+			(UINT_PTR)hsub,
+			m->menuItem[i].text);
+	  break;
+	}
+
+      /* If item==-1 (means to add at end of menu) don't increment) */
+      if (item>=0)
+	item++;
+    }
+
+  return hmenu;
+}
+
+
+#ifdef XWIN_MULTIWINDOW
+/*
+ * Callback routine that is executed once per window class.
+ * Removes or creates custom window settings depending on LPARAM
+ */
+static wBOOL CALLBACK
+ReloadEnumWindowsProc (HWND hwnd, LPARAM lParam)
+{
+  HICON   hicon;
+  Window  wid;
+
+  if (!hwnd) {
+    ErrorF("ReloadEnumWindowsProc: hwnd==NULL!\n");
+    return FALSE;
+  }
+
+  /* It's our baby, either clean or dirty it */
+  if (lParam==FALSE) 
+    {
+      hicon = (HICON)GetClassLong(hwnd, GCL_HICON);
+
+      /* Unselect any icon in the class structure */
+      SetClassLong (hwnd, GCL_HICON, (LONG)LoadIcon (NULL, IDI_APPLICATION));
+
+      /* If it's generated on-the-fly, get rid of it, will regen */
+      winDestroyIcon (hicon);
+     
+      hicon = (HICON)GetClassLong(hwnd, GCL_HICONSM);
+
+      /* Unselect any icon in the class structure */
+      SetClassLong (hwnd, GCL_HICONSM, 0);
+
+      /* If it's generated on-the-fly, get rid of it, will regen */
+      winDestroyIcon (hicon);
+      
+      /* Remove any menu additions, use bRevert flag */
+      GetSystemMenu (hwnd, TRUE);
+      
+      /* This window is now clean of our taint */
+    }
+  else
+    {
+      /* Make the icon default, dynamic, or from xwinrc */
+      SetClassLong (hwnd, GCL_HICON, (LONG)g_hIconX);
+      SetClassLong (hwnd, GCL_HICONSM, (LONG)g_hSmallIconX);
+      wid = (Window)GetProp (hwnd, WIN_WID_PROP);
+      if (wid)
+	winUpdateIcon (wid);
+      /* Update the system menu for this window */
+      SetupSysMenu ((unsigned long)hwnd);
+
+      /* That was easy... */
+    }
+
+  return TRUE;
+}
+#endif
+
+
+/*
+ * Removes any custom icons in classes, custom menus, etc.
+ * Frees all members in pref structure.
+ * Reloads the preferences file.
+ * Set custom icons and menus again.
+ */
+static void
+ReloadPrefs (void)
+{
+  int i;
+
+#ifdef XWIN_MULTIWINDOW
+  /* First, iterate over all windows replacing their icon with system */
+  /* default one and deleting any custom system menus                 */
+  EnumThreadWindows (g_dwCurrentThreadID, ReloadEnumWindowsProc, FALSE);
+#endif
+  
+  /* Now, free/clear all info from our prefs structure */
+  for (i=0; i<pref.menuItems; i++)
+    free (pref.menu[i].menuItem);
+  free (pref.menu);
+  pref.menu = NULL;
+  pref.menuItems = 0;
+
+  pref.rootMenuName[0] = 0;
+
+  free (pref.sysMenu);
+  pref.sysMenuItems = 0;
+
+  pref.defaultSysMenuName[0] = 0;
+  pref.defaultSysMenuPos = 0;
+
+  pref.iconDirectory[0] = 0;
+  pref.defaultIconName[0] = 0;
+  pref.trayIconName[0] = 0;
+
+  for (i=0; i<pref.iconItems; i++)
+    if (pref.icon[i].hicon)
+      DestroyIcon ((HICON)pref.icon[i].hicon);
+  free (pref.icon);
+  pref.icon = NULL;
+  pref.iconItems = 0;
+  
+  /* Free global default X icon */
+  if (g_hIconX) 
+    DestroyIcon (g_hIconX);
+  if (g_hSmallIconX)
+    DestroyIcon (g_hSmallIconX);  
+
+  /* Reset the custom command IDs */
+  g_cmdid = STARTMENUID;
+
+  /* Load the updated resource file */
+  LoadPreferences();
+
+  g_hIconX = NULL;
+  g_hSmallIconX = NULL;
+
+#ifdef XWIN_MULTIWINDOW
+  winInitGlobalIcons();
+#endif
+  
+#ifdef XWIN_MULTIWINDOW
+  /* Rebuild the icons and menus */
+  EnumThreadWindows (g_dwCurrentThreadID, ReloadEnumWindowsProc, TRUE);
+#endif
+
+  /* Whew, done */
+}
+
+/*
+ * Check/uncheck the ALWAYSONTOP items in this menu
+ */
+void
+HandleCustomWM_INITMENU(unsigned long hwndIn,
+			unsigned long hmenuIn)
+{
+  HWND    hwnd;
+  HMENU   hmenu;
+  DWORD   dwExStyle;
+  int     i, j;
+
+  hwnd = (HWND)hwndIn;
+  hmenu = (HMENU)hmenuIn;
+  if (!hwnd || !hmenu) 
+    return;
+  
+  if (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_TOPMOST)
+    dwExStyle = MF_BYCOMMAND | MF_CHECKED;
+  else
+    dwExStyle = MF_BYCOMMAND | MF_UNCHECKED;
+
+  for (i=0; i<pref.menuItems; i++)
+    for (j=0; j<pref.menu[i].menuItems; j++)
+      if (pref.menu[i].menuItem[j].cmd==CMD_ALWAYSONTOP)
+	CheckMenuItem (hmenu, pref.menu[i].menuItem[j].commandID, dwExStyle );
+  
+}
+    
+/*
+ * Searches for the custom WM_COMMAND command ID and performs action.
+ * Return TRUE if command is proccessed, FALSE otherwise.
+ */
+Bool
+HandleCustomWM_COMMAND (unsigned long hwndIn,
+			int           command)
+{
+  HWND hwnd;
+  int i, j;
+  MENUPARSED *m;
+  DWORD			dwExStyle;
+
+  hwnd = (HWND)hwndIn;
+
+  if (!command)
+    return FALSE;
+
+  for (i=0; i<pref.menuItems; i++)
+    {
+      m = &(pref.menu[i]);
+      for (j=0; j<m->menuItems; j++)
+	{
+	  if (command==m->menuItem[j].commandID)
+	    {
+	      /* Match! */
+	      switch(m->menuItem[j].cmd)
+		{
+#ifdef __CYGWIN__
+		case CMD_EXEC:
+		  if (fork()==0)
+		    {
+		      struct rlimit rl;
+		      unsigned long i;
+
+		      /* Close any open descriptors except for STD* */
+		      getrlimit (RLIMIT_NOFILE, &rl);
+		      for (i = STDERR_FILENO+1; i < rl.rlim_cur; i++)
+			close(i);
+
+		      /* Disassociate any TTYs */
+		      setsid();
+
+		      execl ("/bin/sh",
+			     "/bin/sh",
+			     "-c",
+			     m->menuItem[j].param,
+			     NULL);
+		      exit (0);
+		    }
+		  else
+		    return TRUE;
+		  break;
+#else
+		case CMD_EXEC:
+                  {
+		    /* Start process without console window */
+		    STARTUPINFO start;
+		    PROCESS_INFORMATION child;
+
+		    memset (&start, 0, sizeof (start));
+		    start.cb = sizeof (start);
+		    start.dwFlags = STARTF_USESHOWWINDOW;
+		    start.wShowWindow = SW_HIDE;
+
+		    memset (&child, 0, sizeof (child));
+
+		    if (CreateProcess (NULL, m->menuItem[j].param, NULL, NULL, FALSE, 0,
+				       NULL, NULL, &start, &child))
+		    {
+			CloseHandle (child.hThread);
+			CloseHandle (child.hProcess);
+		    }
+		    else
+			MessageBox(NULL, m->menuItem[j].param, "Mingrc Exec Command Error!", MB_OK | MB_ICONEXCLAMATION);
+                  }
+		  return TRUE;
+#endif
+		case CMD_ALWAYSONTOP:
+		  if (!hwnd)
+		    return FALSE;
+
+		  /* Get extended window style */
+		  dwExStyle = GetWindowLong (hwnd, GWL_EXSTYLE);
+		  
+		  /* Handle topmost windows */
+		  if (dwExStyle & WS_EX_TOPMOST)
+		    SetWindowPos (hwnd,
+				  HWND_NOTOPMOST,
+				  0, 0,
+				  0, 0,
+				  SWP_NOSIZE | SWP_NOMOVE);
+		  else
+		    SetWindowPos (hwnd,
+				  HWND_TOPMOST,
+				  0, 0,
+				  0, 0,
+				  SWP_NOSIZE | SWP_NOMOVE);
+#if XWIN_MULTIWINDOW
+		  /* Reflect the changed Z order */
+		  winReorderWindowsMultiWindow ();
+#endif
+		  return TRUE;
+		  
+		case CMD_RELOAD:
+		  ReloadPrefs();
+		  return TRUE;
+
+		default:
+		  return FALSE;
+	      }
+	    } /* match */
+	} /* for j */
+    } /* for i */
+
+  return FALSE;
+}
+
+
+#ifdef XWIN_MULTIWINDOW
+/*
+ * Add the default or a custom menu depending on the class match
+ */
+void
+SetupSysMenu (unsigned long hwndIn)
+{
+  HWND    hwnd;
+  HMENU	  sys;
+  int     i;
+  WindowPtr pWin;
+  char *res_name, *res_class;
+
+  hwnd = (HWND)hwndIn;
+  if (!hwnd)
+    return;
+
+  pWin = GetProp (hwnd, WIN_WINDOW_PROP);
+  
+  sys = GetSystemMenu (hwnd, FALSE);
+  if (!sys)
+    return;
+
+  if (pWin)
+    {
+      /* First see if there's a class match... */
+      if (winMultiWindowGetClassHint (pWin, &res_name, &res_class))
+	{
+	  for (i=0; i<pref.sysMenuItems; i++)
+	    {
+	      if (!strcmp(pref.sysMenu[i].match, res_name) ||
+		  !strcmp(pref.sysMenu[i].match, res_class) ) 
+		{
+		  free(res_name);
+		  free(res_class);
+  
+		  MakeMenu (pref.sysMenu[i].menuName, sys,
+			    pref.sysMenu[i].menuPos==AT_START?0:-1);
+		  return;
+		}
+	    }
+	  
+	  /* No match, just free alloc'd strings */
+	  free(res_name);
+	  free(res_class);
+	} /* Found wm_class */
+    } /* if pwin */
+
+  /* Fallback to system default */
+  if (pref.defaultSysMenuName[0])
+    {
+      if (pref.defaultSysMenuPos==AT_START)
+	MakeMenu (pref.defaultSysMenuName, sys, 0);
+      else
+	MakeMenu (pref.defaultSysMenuName, sys, -1);
+    }
+}
+#endif
+
+
+/*
+ * Possibly add a menu to the toolbar icon
+ */
+void
+SetupRootMenu (unsigned long hmenuRoot)
+{
+  HMENU root;
+
+  root = (HMENU)hmenuRoot;
+  if (!root)
+    return;
+
+  if (pref.rootMenuName[0])
+    {
+      MakeMenu(pref.rootMenuName, root, 0);
+    }
+}
+
+
+/*
+ * Check for and return an overridden default ICON specified in the prefs
+ */
+unsigned long
+winOverrideDefaultIcon(int size)
+{
+  HICON hicon;
+  
+  if (pref.defaultIconName[0])
+    {
+      hicon = LoadImageComma (pref.defaultIconName, size, size, 0);
+      if (hicon==NULL)
+        ErrorF ("winOverrideDefaultIcon: LoadImageComma(%s) failed\n",
+		pref.defaultIconName);
+
+      return (unsigned long)hicon;
+    }
+
+  return 0;
+}
+
+
+/*
+ * Return the HICON to use in the taskbar notification area
+ */
+unsigned long
+winTaskbarIcon(void)
+{
+  HICON hicon;
+
+  hicon = 0;
+  /* First try and load an overridden, if success then return it */
+  if (pref.trayIconName[0])
+    {
+      hicon = LoadImageComma (pref.trayIconName,
+			      GetSystemMetrics (SM_CXSMICON),
+			      GetSystemMetrics (SM_CYSMICON),
+			      0 );
+    }
+
+  /* Otherwise return the default */
+  if (!hicon)
+    hicon =  (HICON) LoadImage (g_hInstance,
+				MAKEINTRESOURCE(IDI_XWIN),
+				IMAGE_ICON,
+				GetSystemMetrics (SM_CXSMICON),
+				GetSystemMetrics (SM_CYSMICON),
+				0);
+
+  return (unsigned long)hicon;
+}
+
+
+/*
+ * Parse a filename to extract an icon:
+ *  If fname is exactly ",nnn" then extract icon from our resource
+ *  else if it is "file,nnn" then extract icon nnn from that file
+ *  else try to load it as an .ico file and if that fails return NULL
+ */
+static HICON
+LoadImageComma (char *fname, int sx, int sy, int flags)
+{
+  HICON  hicon;
+  int    index;
+  char   file[PATH_MAX+NAME_MAX+2];
+
+  /* Some input error checking */
+  if (!fname || !fname[0])
+    return NULL;
+
+  index = 0;
+  hicon = NULL;
+
+  if (fname[0]==',')
+    {
+      /* It's the XWIN.EXE resource they want */
+      index = atoi (fname+1);
+      hicon = LoadImage (g_hInstance,
+                        MAKEINTRESOURCE(index),
+                        IMAGE_ICON,
+                        sx,
+                        sy,
+                        flags);
+    }
+  else
+    {
+      file[0] = 0;
+      /* Prepend path if not given a "X:\" filename */
+      if ( !(fname[0] && fname[1]==':' && fname[2]=='\\') )
+        {
+         strcpy (file, pref.iconDirectory);
+         if (pref.iconDirectory[0])
+           if (fname[strlen(fname)-1]!='\\')
+             strcat (file, "\\");
+        }
+      strcat (file, fname);
+
+      if (strrchr (file, ','))
+       {
+         /* Specified as <fname>,<index> */
+
+         *(strrchr (file, ',')) = 0; /* End string at comma */
+         index = atoi (strrchr (fname, ',') + 1);
+         hicon = ExtractIcon (g_hInstance, file, index);
+       }
+      else
+       {
+         /* Just an .ico file... */
+
+         hicon = (HICON)LoadImage (NULL,
+                                   file,
+                                   IMAGE_ICON,
+                                   sx,
+                                   sy,
+                                   LR_LOADFROMFILE|flags);
+       }
+    }
+  return hicon;
+}
+
+/*
+ * Check for a match of the window class to one specified in the
+ * ICONS{} section in the prefs file, and load the icon from a file
+ */
+unsigned long
+winOverrideIcon (unsigned long longWin)
+{
+  WindowPtr pWin = (WindowPtr) longWin;
+  char *res_name, *res_class;
+  int i;
+  HICON hicon;
+  char *wmName;
+
+  if (pWin==NULL)
+    return 0;
+
+  /* If we can't find the class, we can't override from default! */
+  if (!winMultiWindowGetClassHint (pWin, &res_name, &res_class))
+    return 0;
+
+  winMultiWindowGetWMName (pWin, &wmName);
+  
+  for (i=0; i<pref.iconItems; i++) {
+    if (!strcmp(pref.icon[i].match, res_name) ||
+	!strcmp(pref.icon[i].match, res_class) ||
+	(wmName && strstr(wmName, pref.icon[i].match))) 
+      {
+	free (res_name);
+	free (res_class);
+	if (wmName)
+	  free (wmName);
+
+	if (pref.icon[i].hicon)
+	  return pref.icon[i].hicon;
+
+       hicon = LoadImageComma (pref.icon[i].iconFile, 0, 0, LR_DEFAULTSIZE);
+       if (hicon==NULL)
+         ErrorF ("winOverrideIcon: LoadImageComma(%s) failed\n",
+                  pref.icon[i].iconFile);
+
+	pref.icon[i].hicon = (unsigned long)hicon;
+	return (unsigned long)hicon;
+      }
+  }
+  
+  /* Didn't find the icon, fail gracefully */
+  free (res_name);
+  free (res_class);
+  if (wmName)
+    free (wmName);
+
+  return 0;
+}
+
+
+/*
+ * Should we free this icon or leave it in memory (is it part of our
+ * ICONS{} overrides)?
+ */
+int
+winIconIsOverride(unsigned hiconIn)
+{
+  HICON hicon;
+  int i;
+
+  hicon = (HICON)hiconIn;
+
+  if (!hicon)
+    return 0;
+  
+  for (i=0; i<pref.iconItems; i++)
+    if ((HICON)pref.icon[i].hicon == hicon)
+      return 1;
+  
+  return 0;
+}
+
+
+
+/*
+ * Try and open ~/.XWinrc and /usr/X11R6/lib/X11/system.XWinrc
+ * Load it into prefs structure for use by other functions
+ */
+void
+LoadPreferences ()
+{
+  char *home;
+  char fname[PATH_MAX+NAME_MAX+2];
+  FILE *prefFile;
+  char szDisplay[512];
+  char *szEnvDisplay;
+  int i, j;
+  char param[PARAM_MAX+1];
+  char *srcParam, *dstParam;
+
+  /* First, clear all preference settings */
+  memset (&pref, 0, sizeof(pref));
+  prefFile = NULL;
+
+  /* Now try and find a ~/.xwinrc file */
+  home = getenv ("HOME");
+  if (home)
+    {
+      strcpy (fname, home);
+      if (fname[strlen(fname)-1]!='/')
+	strcat (fname, "/");
+      strcat (fname, ".XWinrc");
+      
+      prefFile = fopen (fname, "r");
+      if (prefFile)
+	ErrorF ("winPrefsLoadPreferences: %s\n", fname);
+    }
+
+  /* No home file found, check system default */
+  if (!prefFile)
+    {
+      char buffer[MAX_PATH];
+#ifdef RELOCATE_PROJECTROOT
+      snprintf(buffer, sizeof(buffer), "%s\\system.XWinrc", winGetBaseDir());
+#else
+      strncpy(buffer, PROJECTROOT"/lib/X11/system.XWinrc", sizeof(buffer));
+#endif
+      buffer[sizeof(buffer)-1] = 0;
+      prefFile = fopen (buffer, "r");
+      if (prefFile)
+	ErrorF ("winPrefsLoadPreferences: %s\n", buffer);
+    }
+
+  /* If we could open it, then read the settings and close it */
+  if (prefFile)
+    {
+      parse_file (prefFile);
+      fclose (prefFile);
+    }
+
+  /* Setup a DISPLAY environment variable, need to allocate on heap */
+  /* because putenv doesn't copy the argument... */
+  snprintf (szDisplay, 512, "DISPLAY=127.0.0.1:%s.0", display);
+  szEnvDisplay = (char *)(malloc (strlen(szDisplay)+1));
+  if (szEnvDisplay)
+    {
+      strcpy (szEnvDisplay, szDisplay);
+      putenv (szEnvDisplay);
+    }
+
+  /* Replace any "%display%" in menu commands with display string */
+  snprintf (szDisplay, 512, "127.0.0.1:%s.0", display);
+  for (i=0; i<pref.menuItems; i++)
+    {
+      for (j=0; j<pref.menu[i].menuItems; j++)
+	{
+	  if (pref.menu[i].menuItem[j].cmd==CMD_EXEC)
+	    {
+	      srcParam = pref.menu[i].menuItem[j].param;
+	      dstParam = param;
+	      while (*srcParam) {
+		if (!strncmp(srcParam, "%display%", 9))
+		  {
+		    memcpy (dstParam, szDisplay, strlen(szDisplay));
+		    dstParam += strlen(szDisplay);
+		    srcParam += 9;
+		  }
+		else
+		  {
+		    *dstParam = *srcParam;
+		    dstParam++;
+		    srcParam++;
+		  }
+	      }
+	      *dstParam = 0;
+	      strcpy (pref.menu[i].menuItem[j].param, param);
+	    } /* cmd==cmd_exec */
+	} /* for all menuitems */
+    } /* for all menus */
+
+}
diff --git a/hw/xwin/winprefs.h b/hw/xwin/winprefs.h
new file mode 100644
index 0000000..d9e09de
--- /dev/null
+++ b/hw/xwin/winprefs.h
@@ -0,0 +1,162 @@
+#if !defined(WINPREFS_H)
+#define WINPREFS_H
+/*
+ * Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name of the XFree86 Project
+ * shall not be used in advertising or otherwise to promote the sale, use
+ * or other dealings in this Software without prior written authorization
+ * from the XFree86 Project.
+ *
+ * Authors:     Earle F. Philhower, III
+ */
+
+/* Need Bool */
+#include <X11/Xdefs.h>
+/* Need TRUE */
+#include "misc.h"
+
+/* Need to know how long paths can be... */
+#include <limits.h>
+/* Xwindows redefines PATH_MAX to at least 1024 */
+#include <X11/Xwindows.h>
+
+#ifndef NAME_MAX
+#define NAME_MAX PATH_MAX
+#endif
+#define MENU_MAX 128   /* Maximum string length of a menu name or item */
+#define PARAM_MAX (4*PATH_MAX)  /* Maximum length of a parameter to a MENU */
+
+
+/* Supported commands in a MENU {} statement */
+typedef enum MENUCOMMANDTYPE
+{
+  CMD_EXEC,         /* /bin/sh -c the parameter            */
+  CMD_MENU,         /* Display a popup menu named param    */
+  CMD_SEPARATOR,    /* Menu separator                      */
+  CMD_ALWAYSONTOP,  /* Toggle always-on-top mode           */
+  CMD_RELOAD        /* Reparse the .XWINRC file            */
+} MENUCOMMANDTYPE;
+
+/* Where to place a system menu */
+typedef enum MENUPOSITION
+{
+  AT_START,   /* Place menu at the top of the system menu   */
+  AT_END      /* Put it at the bottom of the menu (default) */
+} MENUPOSITION;
+
+/* Menu item definitions */
+typedef struct MENUITEM
+{
+  char text[MENU_MAX+1];   /* To be displayed in menu */
+  MENUCOMMANDTYPE cmd;     /* What should it do? */
+  char param[PARAM_MAX+1]; /* Any parameters? */
+  unsigned long commandID; /* Windows WM_COMMAND ID assigned at runtime */
+} MENUITEM;
+
+/* A completely read in menu... */
+typedef struct MENUPARSED
+{
+  char menuName[MENU_MAX+1]; /* What's it called in the text? */
+  MENUITEM *menuItem;        /* Array of items */
+  int menuItems;             /* How big's the array? */
+} MENUPARSED;
+
+/* To map between a window and a system menu to add for it */
+typedef struct SYSMENUITEM
+{
+  char match[MENU_MAX+1];    /* String to look for to apply this sysmenu */
+  char menuName[MENU_MAX+1]; /* Which menu to show? Used to set *menu */
+  MENUPOSITION menuPos;      /* Where to place it (ignored in root) */
+} SYSMENUITEM;
+
+/* To redefine icons for certain window types */
+typedef struct ICONITEM
+{
+  char match[MENU_MAX+1];             /* What string to search for? */
+  char iconFile[PATH_MAX+NAME_MAX+2]; /* Icon location, WIN32 path */
+  unsigned long hicon;                /* LoadImage() result */
+} ICONITEM;
+
+typedef struct WINPREFS
+{
+  /* Menu information */
+  MENUPARSED *menu; /* Array of created menus */
+  int menuItems;      /* How big? */
+
+  /* Taskbar menu settings */
+  char rootMenuName[MENU_MAX+1];  /* Menu for taskbar icon */
+
+  /* System menu addition menus */
+  SYSMENUITEM *sysMenu;
+  int sysMenuItems;
+
+  /* Which menu to add to unmatched windows? */
+  char defaultSysMenuName[MENU_MAX+1];
+  MENUPOSITION defaultSysMenuPos;   /* Where to place it */
+
+  /* Icon information */
+  char iconDirectory[PATH_MAX+1]; /* Where do the .icos lie? (Win32 path) */
+  char defaultIconName[NAME_MAX+1];   /* Replacement for x.ico */
+  char trayIconName[NAME_MAX+1]; /* Replacement for tray icon */
+
+  ICONITEM *icon;
+  int iconItems;
+
+  /* Silent exit flag */
+  Bool fSilentExit;
+
+} WINPREFS;
+
+
+
+
+/* Functions */
+void
+LoadPreferences(void);
+
+void
+SetupRootMenu (unsigned long hmenuRoot);
+
+void
+SetupSysMenu (unsigned long hwndIn);
+
+void
+HandleCustomWM_INITMENU(unsigned long hwndIn,
+			unsigned long hmenuIn);
+
+Bool
+HandleCustomWM_COMMAND (unsigned long hwndIn,
+			int           command);
+
+int
+winIconIsOverride (unsigned hiconIn);
+
+unsigned long
+winOverrideIcon (unsigned long longpWin);
+
+unsigned long
+winTaskbarIcon(void);
+
+unsigned long
+winOverrideDefaultIcon(int size);
+#endif
diff --git a/hw/xwin/winprefslex.l b/hw/xwin/winprefslex.l
new file mode 100644
index 0000000..a4c1abc
--- /dev/null
+++ b/hw/xwin/winprefslex.l
@@ -0,0 +1,116 @@
+%{ # -*- C -*-
+/*
+ * Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name of the XFree86 Project
+ * shall not be used in advertising or otherwise to promote the sale, use
+ * or other dealings in this Software without prior written authorization
+ * from the XFree86 Project.
+ *
+ * Authors:     Earle F. Philhower, III
+ */
+/* $XFree86: $ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "winprefsyacc.h"
+
+extern YYSTYPE yylval;
+extern char *yytext;
+extern int yyparse(void);
+
+extern void ErrorF (const char* /*f*/, ...);
+
+int yylineno;
+
+/* Copy the parsed string, must be free()d in yacc parser */
+static char *makestr(char *str)
+{
+  char *ptr;
+  ptr = (char*)malloc (strlen(str)+1);
+  if (!ptr)
+    {
+      ErrorF ("winMultiWindowLex:makestr() out of memory\n");
+      exit (-1);
+    }
+  strcpy(ptr, str);
+  return ptr;
+}
+
+%}
+
+%option yylineno
+
+%%
+\#.*[\r\n]              { /* comment */ return NEWLINE; }
+\/\/.*[\r\n]            { /* comment */ return NEWLINE; }
+[\r\n]                  { return NEWLINE; }
+[ \t]+                  { /* ignore whitespace */ }
+MENU                    { return MENU; }
+ICONDIRECTORY           { return ICONDIRECTORY; }
+DEFAULTICON             { return DEFAULTICON; }
+ICONS                   { return ICONS; }
+ROOTMENU                { return ROOTMENU; }
+DEFAULTSYSMENU          { return DEFAULTSYSMENU; }
+SYSMENU                 { return SYSMENU; }
+SEPARATOR               { return SEPARATOR; }
+ATSTART                 { return ATSTART; }
+ATEND                   { return ATEND; }
+EXEC                    { return EXEC; }
+ALWAYSONTOP             { return ALWAYSONTOP; }
+DEBUG                   { return DEBUG; }
+RELOAD                  { return RELOAD; }
+TRAYICON                { return TRAYICON; }
+SILENTEXIT		{ return SILENTEXIT; }
+"{"                     { return LB; }
+"}"                     { return RB; }
+"\""[^\"\r\n]+"\""      { yylval.sVal = makestr(yytext+1); \
+                          yylval.sVal[strlen(yylval.sVal)-1] = 0; \
+                          return STRING; }
+[^ \t\r\n]+             { yylval.sVal = makestr(yytext); \
+                          return STRING; }
+%%
+
+/*
+ * Run-of-the mill requirement for yacc
+ */
+int
+yywrap ()
+{
+  return 1;
+}
+
+/*
+ * Run a file through the yacc parser
+ */
+void
+parse_file (FILE *file)
+{
+  if (!file)
+    return; 
+  
+  yylineno = 1;
+  yyin = file;
+  yyparse ();
+}
+
diff --git a/hw/xwin/winprefsyacc.y b/hw/xwin/winprefsyacc.y
new file mode 100644
index 0000000..2a54ff2
--- /dev/null
+++ b/hw/xwin/winprefsyacc.y
@@ -0,0 +1,353 @@
+%{
+/*
+ * Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name of the XFree86 Project
+ * shall not be used in advertising or otherwise to promote the sale, use
+ * or other dealings in this Software without prior written authorization
+ * from the XFree86 Project.
+ *
+ * Authors:     Earle F. Philhower, III
+ */
+/* $XFree86: $ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "winprefs.h"
+
+/* The following give better error messages in bison at the cost of a few KB */
+#define YYERROR_VERBOSE 1
+
+/* The global pref settings */
+WINPREFS pref;
+
+/* The working menu */  
+static MENUPARSED menu;
+
+/* Functions for parsing the tokens into out structure */
+/* Defined at the end section of this file */
+
+static void SetIconDirectory (char *path);
+static void SetDefaultIcon (char *fname);
+static void SetRootMenu (char *menu);
+static void SetDefaultSysMenu (char *menu, int pos);
+static void SetTrayIcon (char *fname);
+
+static void OpenMenu(char *menuname);
+static void AddMenuLine(char *name, MENUCOMMANDTYPE cmd, char *param);
+static void CloseMenu(void);
+
+static void OpenIcons(void);
+static void AddIconLine(char *matchstr, char *iconfile);
+static void CloseIcons(void);
+
+static void OpenSysMenu(void);
+static void AddSysMenuLine(char *matchstr, char *menuname, int pos);
+static void CloseSysMenu(void);
+
+static int yyerror (char *s);
+
+extern void ErrorF (const char* /*f*/, ...);
+extern char *yytext;
+extern int yylex(void);
+
+%}
+
+%union {
+  char *sVal;
+  int iVal;
+}
+
+%token NEWLINE MENU LB RB ICONDIRECTORY DEFAULTICON ICONS DEFAULTSYSMENU
+%token SYSMENU ROOTMENU SEPARATOR ATSTART ATEND EXEC ALWAYSONTOP DEBUG
+%token RELOAD TRAYICON SILENTEXIT
+
+%token <sVal> STRING
+%type <iVal>  atspot
+
+%%
+
+input:	/* empty */
+	| input line
+	;
+
+line:	NEWLINE
+	| command
+	;
+
+
+newline_or_nada:	
+	| NEWLINE newline_or_nada
+	;
+
+command:	defaulticon
+	| icondirectory
+	| menu
+	| icons
+	| sysmenu
+	| rootmenu
+	| defaultsysmenu
+	| debug
+	| trayicon
+	| silentexit
+	;
+
+trayicon:	TRAYICON STRING NEWLINE { SetTrayIcon($2); free($2); }
+	;
+
+rootmenu:	ROOTMENU STRING NEWLINE { SetRootMenu($2); free($2); }
+	;
+
+defaultsysmenu:	DEFAULTSYSMENU STRING atspot NEWLINE { SetDefaultSysMenu($2, $3); free($2); }
+	;
+
+defaulticon:	DEFAULTICON STRING NEWLINE { SetDefaultIcon($2); free($2); }
+	;
+
+icondirectory:	ICONDIRECTORY STRING NEWLINE { SetIconDirectory($2); free($2); }
+	;
+
+menuline:	SEPARATOR NEWLINE newline_or_nada  { AddMenuLine("-", CMD_SEPARATOR, ""); }
+	| STRING ALWAYSONTOP NEWLINE newline_or_nada  { AddMenuLine($1, CMD_ALWAYSONTOP, ""); free($1); }
+	| STRING EXEC STRING NEWLINE newline_or_nada  { AddMenuLine($1, CMD_EXEC, $3); free($1); free($3); }
+	| STRING MENU STRING NEWLINE newline_or_nada  { AddMenuLine($1, CMD_MENU, $3); free($1); free($3); }
+	| STRING RELOAD NEWLINE newline_or_nada  { AddMenuLine($1, CMD_RELOAD, ""); free($1); }
+	;
+
+menulist:	menuline
+	| menuline menulist
+	;
+
+menu:	MENU STRING LB { OpenMenu($2); free($2); } newline_or_nada menulist RB {CloseMenu();}
+	;
+
+iconline:	STRING STRING NEWLINE newline_or_nada { AddIconLine($1, $2); free($1); free($2); }
+	;
+
+iconlist:	iconline
+	| iconline iconlist
+	;
+
+icons:	ICONS LB {OpenIcons();} newline_or_nada iconlist RB {CloseIcons();}
+	;
+
+atspot:	{ $$=AT_END; }
+	| ATSTART { $$=AT_START; }
+	| ATEND { $$=AT_END; }
+	;
+
+sysmenuline:	STRING STRING atspot NEWLINE newline_or_nada { AddSysMenuLine($1, $2, $3); free($1); free($2); }
+	;
+
+sysmenulist:	sysmenuline
+	| sysmenuline sysmenulist
+	;
+
+sysmenu:	SYSMENU LB NEWLINE {OpenSysMenu();} newline_or_nada sysmenulist RB {CloseSysMenu();}
+	;
+
+silentexit:	SILENTEXIT NEWLINE { pref.fSilentExit = TRUE; }
+	;
+
+debug: 	DEBUG STRING NEWLINE { ErrorF("LoadPreferences: %s\n", $2); free($2); }
+	;
+
+
+%%
+/*
+ * Errors in parsing abort and print log messages
+ */
+static int
+yyerror (char *s) 
+{
+  extern int yylineno; /* Handled by flex internally */
+
+  ErrorF("LoadPreferences: %s line %d\n", s, yylineno);
+  return 1;
+}
+
+/* Miscellaneous functions to store TOKENs into the structure */
+static void
+SetIconDirectory (char *path)
+{
+  strncpy (pref.iconDirectory, path, PATH_MAX);
+  pref.iconDirectory[PATH_MAX] = 0;
+}
+
+static void
+SetDefaultIcon (char *fname)
+{
+  strncpy (pref.defaultIconName, fname, NAME_MAX);
+  pref.defaultIconName[NAME_MAX] = 0;
+}
+
+static void
+SetTrayIcon (char *fname)
+{
+  strncpy (pref.trayIconName, fname, NAME_MAX);
+  pref.trayIconName[NAME_MAX] = 0;
+}
+
+static void
+SetRootMenu (char *menu)
+{
+  strncpy (pref.rootMenuName, menu, MENU_MAX);
+  pref.rootMenuName[MENU_MAX] = 0;
+}
+
+static void
+SetDefaultSysMenu (char *menu, int pos)
+{
+  strncpy (pref.defaultSysMenuName, menu, MENU_MAX);
+  pref.defaultSysMenuName[MENU_MAX] = 0;
+  pref.defaultSysMenuPos = pos;
+}
+
+static void
+OpenMenu (char *menuname)
+{
+  if (menu.menuItem) free(menu.menuItem);
+  menu.menuItem = NULL;
+  strncpy(menu.menuName, menuname, MENU_MAX);
+  menu.menuName[MENU_MAX] = 0;
+  menu.menuItems = 0;
+}
+
+static void
+AddMenuLine (char *text, MENUCOMMANDTYPE cmd, char *param)
+{
+  if (menu.menuItem==NULL)
+    menu.menuItem = (MENUITEM*)malloc(sizeof(MENUITEM));
+  else
+    menu.menuItem = (MENUITEM*)
+      realloc(menu.menuItem, sizeof(MENUITEM)*(menu.menuItems+1));
+
+  strncpy (menu.menuItem[menu.menuItems].text, text, MENU_MAX);
+  menu.menuItem[menu.menuItems].text[MENU_MAX] = 0;
+
+  menu.menuItem[menu.menuItems].cmd = cmd;
+
+  strncpy(menu.menuItem[menu.menuItems].param, param, PARAM_MAX);
+  menu.menuItem[menu.menuItems].param[PARAM_MAX] = 0;
+
+  menu.menuItem[menu.menuItems].commandID = 0;
+
+  menu.menuItems++;
+}
+
+static void
+CloseMenu (void)
+{
+  if (menu.menuItem==NULL || menu.menuItems==0)
+    {
+      ErrorF("LoadPreferences: Empty menu detected\n");
+      return;
+    }
+  
+  if (pref.menuItems)
+    pref.menu = (MENUPARSED*)
+      realloc (pref.menu, (pref.menuItems+1)*sizeof(MENUPARSED));
+  else
+    pref.menu = (MENUPARSED*)malloc (sizeof(MENUPARSED));
+  
+  memcpy (pref.menu+pref.menuItems, &menu, sizeof(MENUPARSED));
+  pref.menuItems++;
+
+  memset (&menu, 0, sizeof(MENUPARSED));
+}
+
+static void 
+OpenIcons (void)
+{
+  if (pref.icon != NULL) {
+    ErrorF("LoadPreferences: Redefining icon mappings\n");
+    free(pref.icon);
+    pref.icon = NULL;
+  }
+  pref.iconItems = 0;
+}
+
+static void
+AddIconLine (char *matchstr, char *iconfile)
+{
+  if (pref.icon==NULL)
+    pref.icon = (ICONITEM*)malloc(sizeof(ICONITEM));
+  else
+    pref.icon = (ICONITEM*)
+      realloc(pref.icon, sizeof(ICONITEM)*(pref.iconItems+1));
+
+  strncpy(pref.icon[pref.iconItems].match, matchstr, MENU_MAX);
+  pref.icon[pref.iconItems].match[MENU_MAX] = 0;
+
+  strncpy(pref.icon[pref.iconItems].iconFile, iconfile, PATH_MAX+NAME_MAX+1);
+  pref.icon[pref.iconItems].iconFile[PATH_MAX+NAME_MAX+1] = 0;
+
+  pref.icon[pref.iconItems].hicon = 0;
+
+  pref.iconItems++;
+}
+
+static void 
+CloseIcons (void)
+{
+}
+
+static void
+OpenSysMenu (void)
+{
+  if (pref.sysMenu != NULL) {
+    ErrorF("LoadPreferences: Redefining system menu\n");
+    free(pref.sysMenu);
+    pref.sysMenu = NULL;
+  }
+  pref.sysMenuItems = 0;
+}
+
+static void
+AddSysMenuLine (char *matchstr, char *menuname, int pos)
+{
+  if (pref.sysMenu==NULL)
+    pref.sysMenu = (SYSMENUITEM*)malloc(sizeof(SYSMENUITEM));
+  else
+    pref.sysMenu = (SYSMENUITEM*)
+      realloc(pref.sysMenu, sizeof(SYSMENUITEM)*(pref.sysMenuItems+1));
+
+  strncpy (pref.sysMenu[pref.sysMenuItems].match, matchstr, MENU_MAX);
+  pref.sysMenu[pref.sysMenuItems].match[MENU_MAX] = 0;
+
+  strncpy (pref.sysMenu[pref.sysMenuItems].menuName, menuname, MENU_MAX);
+  pref.sysMenu[pref.sysMenuItems].menuName[MENU_MAX] = 0;
+
+  pref.sysMenu[pref.sysMenuItems].menuPos = pos;
+
+  pref.sysMenuItems++;
+}
+
+static void
+CloseSysMenu (void)
+{
+}
+
diff --git a/hw/xwin/winpriv.c b/hw/xwin/winpriv.c
new file mode 100644
index 0000000..29221cf
--- /dev/null
+++ b/hw/xwin/winpriv.c
@@ -0,0 +1,134 @@
+/*
+ * Export window information for the Windows-OpenGL GLX implementation.
+ *
+ * Authors: Alexander Gottwald
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winpriv.h"
+#include "winwindow.h"
+
+void
+winCreateWindowsWindow (WindowPtr pWin);
+/**
+ * Return size and handles of a window.
+ * If pWin is NULL, then the information for the root window is requested.
+ */ 
+extern void winGetWindowInfo(WindowPtr pWin, winWindowInfoPtr pWinInfo)
+{
+    /* Sanity check */
+    if (pWinInfo == NULL)
+        return;
+
+    winDebug("%s:%d pWin=%p\n", __FUNCTION__, __LINE__, pWin);
+
+    /* a real window was requested */
+    if (pWin != NULL) 
+    {
+        /* Initialize the size information */
+        RECT rect = {
+            pWin->drawable.x,
+            pWin->drawable.y,
+            pWin->drawable.x + pWin->drawable.width,
+            pWin->drawable.y + pWin->drawable.height
+        }, rect_extends;
+        /* Get the window and screen privates */
+        ScreenPtr pScreen = pWin->drawable.pScreen;
+        winPrivScreenPtr pWinScreen = winGetScreenPriv(pScreen);
+        winScreenInfoPtr pScreenInfo = NULL;
+
+        rect_extends = rect;
+        OffsetRect(&rect_extends, -pWin->drawable.x, -pWin->drawable.y);
+
+        if (pWinScreen == NULL) 
+        {
+            ErrorF("winGetWindowInfo: screen has no privates\n");
+            return;
+        }
+        
+        pWinInfo->hwnd = pWinScreen->hwndScreen;
+        pWinInfo->hrgn = NULL;
+        pWinInfo->rect = rect;
+    
+
+        pScreenInfo = pWinScreen->pScreenInfo;
+#ifdef XWIN_MULTIWINDOW
+        /* check for multiwindow mode */
+        if (pScreenInfo->fMultiWindow)
+        {
+            winWindowPriv(pWin);
+
+            if (pWinPriv == NULL)
+            {
+                ErrorF("winGetWindowInfo: window has no privates\n");
+                return;
+            }
+
+            if (pWinPriv->hWnd == NULL)
+            {
+                winCreateWindowsWindow(pWin);
+            }
+            if (pWinPriv->hWnd != NULL) { 
+                
+                /* copy size and window handle */
+                pWinInfo->rect = rect_extends;
+                pWinInfo->hwnd = pWinPriv->hWnd;
+
+                /* Copy window region */
+                if (pWinInfo->hrgn)
+                    DeleteObject(pWinInfo->hrgn);
+                pWinInfo->hrgn = CreateRectRgn(0,0,0,0);
+                CombineRgn(pWinInfo->hrgn, pWinPriv->hRgn, pWinPriv->hRgn, 
+                        RGN_COPY);
+            }
+            
+            return;
+        }
+#endif
+#ifdef XWIN_MULTIWINDOWEXTWM
+        /* check for multiwindow external wm mode */
+        if (pScreenInfo->fMWExtWM)
+        {
+            win32RootlessWindowPtr pRLWinPriv
+                = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, FALSE);
+
+            if (pRLWinPriv == NULL) {
+                ErrorF("winGetWindowInfo: window has no privates\n");
+                return;
+            }
+            
+            if (pRLWinPriv->hWnd != NULL)
+            {
+                /* copy size and window handle */
+                pWinInfo->rect = rect_extends;
+                pWinInfo->hwnd = pRLWinPriv->hWnd;
+            }
+            return;
+        }
+#endif
+    } 
+    else 
+    {
+        RECT rect = {0, 0, 0, 0};
+        ScreenPtr pScreen = g_ScreenInfo[0].pScreen;
+        winPrivScreenPtr pWinScreen = winGetScreenPriv(pScreen);
+
+        pWinInfo->hwnd = NULL;
+        pWinInfo->hrgn = NULL;
+        pWinInfo->rect = rect;
+        
+        if (pWinScreen == NULL)
+        {
+            ErrorF("winGetWindowInfo: screen has no privates\n");
+            return;
+        }
+
+        ErrorF("winGetWindowInfo: returning root window\n");
+
+        pWinInfo->hwnd = pWinScreen->hwndScreen;
+    }
+    return;
+}
diff --git a/hw/xwin/winpriv.h b/hw/xwin/winpriv.h
new file mode 100644
index 0000000..d4505c8
--- /dev/null
+++ b/hw/xwin/winpriv.h
@@ -0,0 +1,15 @@
+/*
+ * Export window information for the Windows-OpenGL GLX implementation.
+ *
+ * Authors: Alexander Gottwald
+ */
+#include <windows.h>
+
+typedef struct
+{
+    HWND    hwnd;
+    HRGN    hrgn;
+    RECT    rect;
+} winWindowInfoRec, *winWindowInfoPtr;
+
+extern void winGetWindowInfo(WindowPtr pWin, winWindowInfoPtr pWinInfo);
diff --git a/hw/xwin/winprocarg.c b/hw/xwin/winprocarg.c
new file mode 100755
index 0000000..7139cba
--- /dev/null
+++ b/hw/xwin/winprocarg.c
@@ -0,0 +1,1551 @@
+/*
+
+Copyright 1993, 1998  The Open Group
+
+Permission to use, copy, modify, distribute, and sell this software and its
+documentation for any purpose is hereby granted without fee, provided that
+the above copyright notice appear in all copies and that both that
+copyright notice and this permission notice appear in supporting
+documentation.
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of The Open Group shall
+not be used in advertising or otherwise to promote the sale, use or
+other dealings in this Software without prior written authorization
+from The Open Group.
+
+*/
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#ifdef XVENDORNAME
+#define VENDOR_STRING XVENDORNAME
+#define VERSION_STRING XORG_RELEASE
+#define VENDOR_CONTACT BUILDERADDR
+#endif
+#include "win.h"
+#include "winconfig.h"
+#include "winprefs.h"
+#include "winmsg.h"
+
+/*
+ * References to external symbols
+ */
+
+extern int			g_iNumScreens;
+extern winScreenInfo		g_ScreenInfo[];
+extern int			g_iLastScreen;
+extern Bool			g_fInitializedDefaultScreens;
+#ifdef XWIN_CLIPBOARD
+extern Bool			g_fUnicodeClipboard;
+extern Bool			g_fClipboard;
+#endif
+extern int			g_iLogVerbose;
+extern char *			g_pszLogFile;
+#ifdef RELOCATE_PROJECTROOT
+extern Bool			g_fLogFileChanged;
+#endif
+extern Bool			g_fXdmcpEnabled;
+extern char *			g_pszCommandLine;
+extern Bool			g_fKeyboardHookLL;
+extern Bool			g_fNoHelpMessageBox;                     
+extern Bool			g_fSoftwareCursor;
+extern Bool			g_fSilentDupError;
+
+/* globals required by callback function for monitor information */
+struct GetMonitorInfoData {
+    int  requestedMonitor;
+    int  monitorNum;
+    Bool bUserSpecifiedMonitor;
+    Bool bMonitorSpecifiedExists;
+    int  monitorOffsetX;
+    int  monitorOffsetY;
+    int  monitorHeight;
+    int  monitorWidth;
+};
+
+typedef wBOOL (*ENUMDISPLAYMONITORSPROC)(HDC,LPCRECT,MONITORENUMPROC,LPARAM);
+ENUMDISPLAYMONITORSPROC _EnumDisplayMonitors;
+
+wBOOL CALLBACK getMonitorInfo(HMONITOR hMonitor, HDC hdc, LPRECT rect, LPARAM _data);
+
+static Bool QueryMonitor(int index, struct GetMonitorInfoData *data)
+{
+    /* Load EnumDisplayMonitors from DLL */
+    HMODULE user32;
+    FARPROC func;
+    user32 = LoadLibrary("user32.dll");
+    if (user32 == NULL)
+    {
+        winW32Error(2, "Could not open user32.dll");
+        return FALSE;
+    }
+    func = GetProcAddress(user32, "EnumDisplayMonitors");
+    if (func == NULL)
+    {
+        winW32Error(2, "Could not resolve EnumDisplayMonitors: ");
+        return FALSE;
+    }
+    _EnumDisplayMonitors = (ENUMDISPLAYMONITORSPROC)func;
+    
+    /* prepare data */
+    if (data == NULL)
+        return FALSE;
+    memset(data, 0, sizeof(*data));
+    data->requestedMonitor = index;
+
+    /* query information */
+    _EnumDisplayMonitors(NULL, NULL, getMonitorInfo, (LPARAM) data);
+
+    /* cleanup */
+    FreeLibrary(user32);
+    return TRUE;
+}
+
+/*
+ * Function prototypes
+ */
+
+void
+winLogCommandLine (int argc, char *argv[]);
+
+void
+winLogVersionInfo (void);
+
+#ifdef DDXOSVERRORF
+void OsVendorVErrorF (const char *pszFormat, va_list va_args);
+#endif
+
+void
+winInitializeDefaultScreens (void);
+
+/*
+ * Process arguments on the command line
+ */
+
+void
+winInitializeDefaultScreens (void)
+{
+  int                   i;
+  DWORD			dwWidth, dwHeight;
+
+  /* Bail out early if default screens have already been initialized */
+  if (g_fInitializedDefaultScreens)
+    return;
+
+  /* Zero the memory used for storing the screen info */
+  ZeroMemory (g_ScreenInfo, MAXSCREENS * sizeof (winScreenInfo));
+
+  /* Get default width and height */
+  /*
+   * NOTE: These defaults will cause the window to cover only
+   * the primary monitor in the case that we have multiple monitors.
+   */
+  dwWidth = GetSystemMetrics (SM_CXSCREEN);
+  dwHeight = GetSystemMetrics (SM_CYSCREEN);
+
+  winErrorFVerb (2, "winInitializeDefaultScreens - w %d h %d\n",
+	  (int) dwWidth, (int) dwHeight);
+
+  /* Set a default DPI, if no parameter was passed */
+  if (monitorResolution == 0)
+    monitorResolution = WIN_DEFAULT_DPI;
+
+  for (i = 0; i < MAXSCREENS; ++i)
+    {
+      g_ScreenInfo[i].dwScreen = i;
+      g_ScreenInfo[i].dwWidth  = dwWidth;
+      g_ScreenInfo[i].dwHeight = dwHeight;
+      g_ScreenInfo[i].dwUserWidth  = dwWidth;
+      g_ScreenInfo[i].dwUserHeight = dwHeight;
+      g_ScreenInfo[i].fUserGaveHeightAndWidth
+	=  WIN_DEFAULT_USER_GAVE_HEIGHT_AND_WIDTH;
+      g_ScreenInfo[i].fUserGavePosition = FALSE;
+      g_ScreenInfo[i].dwBPP = WIN_DEFAULT_BPP;
+      g_ScreenInfo[i].dwClipUpdatesNBoxes = WIN_DEFAULT_CLIP_UPDATES_NBOXES;
+#ifdef XWIN_EMULATEPSEUDO
+      g_ScreenInfo[i].fEmulatePseudo = WIN_DEFAULT_EMULATE_PSEUDO;
+#endif
+      g_ScreenInfo[i].dwRefreshRate = WIN_DEFAULT_REFRESH;
+      g_ScreenInfo[i].pfb = NULL;
+      g_ScreenInfo[i].fFullScreen = FALSE;
+      g_ScreenInfo[i].fDecoration = TRUE;
+#ifdef XWIN_MULTIWINDOWEXTWM
+      g_ScreenInfo[i].fMWExtWM = FALSE;
+      g_ScreenInfo[i].fInternalWM = FALSE;
+#endif
+      g_ScreenInfo[i].fRootless = FALSE;
+#ifdef XWIN_MULTIWINDOW
+      g_ScreenInfo[i].fMultiWindow = FALSE;
+#endif
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+      g_ScreenInfo[i].fMultiMonitorOverride = FALSE;
+#endif
+      g_ScreenInfo[i].fMultipleMonitors = FALSE;
+      g_ScreenInfo[i].fLessPointer = FALSE;
+      g_ScreenInfo[i].fScrollbars = FALSE;
+      g_ScreenInfo[i].fNoTrayIcon = FALSE;
+      g_ScreenInfo[i].iE3BTimeout = WIN_E3B_OFF;
+      g_ScreenInfo[i].dwWidth_mm = (dwWidth / WIN_DEFAULT_DPI)
+	* 25.4;
+      g_ScreenInfo[i].dwHeight_mm = (dwHeight / WIN_DEFAULT_DPI)
+	* 25.4;
+      g_ScreenInfo[i].fUseWinKillKey = WIN_DEFAULT_WIN_KILL;
+      g_ScreenInfo[i].fUseUnixKillKey = WIN_DEFAULT_UNIX_KILL;
+      g_ScreenInfo[i].fIgnoreInput = FALSE;
+      g_ScreenInfo[i].fExplicitScreen = FALSE;
+    }
+
+  /* Signal that the default screens have been initialized */
+  g_fInitializedDefaultScreens = TRUE;
+
+  winErrorFVerb (2, "winInitializeDefaultScreens - Returning\n");
+}
+
+/* See Porting Layer Definition - p. 57 */
+/*
+ * INPUT
+ * argv: pointer to an array of null-terminated strings, one for
+ *   each token in the X Server command line; the first token
+ *   is 'XWin.exe', or similar.
+ * argc: a count of the number of tokens stored in argv.
+ * i: a zero-based index into argv indicating the current token being
+ *   processed.
+ *
+ * OUTPUT
+ * return: return the number of tokens processed correctly.
+ *
+ * NOTE
+ * When looking for n tokens, check that i + n is less than argc.  Or,
+ *   you may check if i is greater than or equal to argc, in which case
+ *   you should display the UseMsg () and return 0.
+ */
+
+/* Check if enough arguments are given for the option */
+#define CHECK_ARGS(count) if (i + count >= argc) { UseMsg (); return 0; }
+
+/* Compare the current option with the string. */ 
+#define IS_OPTION(name) (strcmp (argv[i], name) == 0)
+
+int
+ddxProcessArgument (int argc, char *argv[], int i)
+{
+  static Bool		s_fBeenHere = FALSE;
+
+  /* Initialize once */
+  if (!s_fBeenHere)
+    {
+#ifdef DDXOSVERRORF
+      /*
+       * This initialises our hook into VErrorF () for catching log messages
+       * that are generated before OsInit () is called.
+       */
+      OsVendorVErrorFProc = OsVendorVErrorF;
+#endif
+
+      s_fBeenHere = TRUE;
+
+      /* Initialize only if option is not -help */
+      if (!IS_OPTION("-help") && !IS_OPTION("-h") && !IS_OPTION("--help") &&
+          !IS_OPTION("-version") && !IS_OPTION("--version"))
+	{
+
+          /* Log the version information */
+          winLogVersionInfo ();
+
+          /* Log the command line */
+          winLogCommandLine (argc, argv);
+
+	  /*
+	   * Initialize default screen settings.  We have to do this before
+	   * OsVendorInit () gets called, otherwise we will overwrite
+	   * settings changed by parameters such as -fullscreen, etc.
+	   */
+	  winErrorFVerb (2, "ddxProcessArgument - Initializing default "
+			 "screens\n");
+	  winInitializeDefaultScreens ();
+	}
+    }
+
+#if CYGDEBUG
+  winDebug ("ddxProcessArgument - arg: %s\n", argv[i]);
+#endif
+
+  /*
+   * Look for the '-help' and similar options
+   */ 
+  if (IS_OPTION ("-help") || IS_OPTION("-h") || IS_OPTION("--help"))
+    {
+      /* Reset logfile. We don't need that helpmessage in the logfile */  
+      g_pszLogFile = NULL;
+      g_fNoHelpMessageBox = TRUE;
+      UseMsg();
+      exit (0);
+      return 1;
+    }
+
+  if (IS_OPTION ("-version") || IS_OPTION("--version"))
+    {
+      /* Reset logfile. We don't need that versioninfo in the logfile */  
+      g_pszLogFile = NULL;
+      winLogVersionInfo ();
+      exit (0);
+      return 1;
+    }
+
+  /*
+   * Look for the '-screen scr_num [width height]' argument
+   */
+  if (IS_OPTION ("-screen"))
+    {
+      int		iArgsProcessed = 1;
+      int		nScreenNum;
+      int		iWidth, iHeight, iX, iY;
+      int		iMonitor;
+
+#if CYGDEBUG
+      winDebug ("ddxProcessArgument - screen - argc: %d i: %d\n",
+	      argc, i);
+#endif
+
+      /* Display the usage message if the argument is malformed */
+      if (i + 1 >= argc)
+	{
+	  return 0;
+	}
+      
+      /* Grab screen number */
+      nScreenNum = atoi (argv[i + 1]);
+
+      /* Validate the specified screen number */
+      if (nScreenNum < 0 || nScreenNum >= MAXSCREENS)
+        {
+          ErrorF ("ddxProcessArgument - screen - Invalid screen number %d\n",
+		  nScreenNum);
+          UseMsg ();
+	  return 0;
+        }
+
+	  /* look for @m where m is monitor number */
+	  if (i + 2 < argc
+		  && 1 == sscanf(argv[i + 2], "@%d", (int *) &iMonitor)) 
+      {
+        struct GetMonitorInfoData data;
+        if (!QueryMonitor(iMonitor, &data))
+        {
+            ErrorF ("ddxProcessArgument - screen - "
+                    "Querying monitors is not supported on NT4 and Win95\n");
+        } else if (data.bMonitorSpecifiedExists == TRUE) 
+        {
+		  winErrorFVerb(2, "ddxProcessArgument - screen - Found Valid ``@Monitor'' = %d arg\n", iMonitor);
+		  iArgsProcessed = 3;
+		  g_ScreenInfo[nScreenNum].fUserGaveHeightAndWidth = FALSE;
+		  g_ScreenInfo[nScreenNum].fUserGavePosition = TRUE;
+		  g_ScreenInfo[nScreenNum].dwWidth = data.monitorWidth;
+		  g_ScreenInfo[nScreenNum].dwHeight = data.monitorHeight;
+		  g_ScreenInfo[nScreenNum].dwUserWidth = data.monitorWidth;
+		  g_ScreenInfo[nScreenNum].dwUserHeight = data.monitorHeight;
+		  g_ScreenInfo[nScreenNum].dwInitialX = data.monitorOffsetX;
+		  g_ScreenInfo[nScreenNum].dwInitialY = data.monitorOffsetY;
+		}
+		else 
+        {
+		  /* monitor does not exist, error out */
+		  ErrorF ("ddxProcessArgument - screen - Invalid monitor number %d\n",
+				  iMonitor);
+		  UseMsg ();
+		  exit (0);
+		  return 0;
+		}
+	  }
+
+      /* Look for 'WxD' or 'W D' */
+      else if (i + 2 < argc
+	  && 2 == sscanf (argv[i + 2], "%dx%d",
+			  (int *) &iWidth,
+			  (int *) &iHeight))
+	{
+	  winErrorFVerb (2, "ddxProcessArgument - screen - Found ``WxD'' arg\n");
+	  iArgsProcessed = 3;
+	  g_ScreenInfo[nScreenNum].fUserGaveHeightAndWidth = TRUE;
+	  g_ScreenInfo[nScreenNum].dwWidth = iWidth;
+	  g_ScreenInfo[nScreenNum].dwHeight = iHeight;
+	  g_ScreenInfo[nScreenNum].dwUserWidth = iWidth;
+	  g_ScreenInfo[nScreenNum].dwUserHeight = iHeight;
+	  /* Look for WxD+X+Y */
+	  if (2 == sscanf (argv[i + 2], "%*dx%*d+%d+%d",
+			   (int *) &iX,
+			   (int *) &iY))
+	  {
+	    winErrorFVerb (2, "ddxProcessArgument - screen - Found ``X+Y'' arg\n");
+	    g_ScreenInfo[nScreenNum].fUserGavePosition = TRUE;
+	    g_ScreenInfo[nScreenNum].dwInitialX = iX;
+	    g_ScreenInfo[nScreenNum].dwInitialY = iY;
+
+		/* look for WxD+X+Y at m where m is monitor number. take X,Y to be offsets from monitor's root position */
+		if (1 == sscanf (argv[i + 2], "%*dx%*d+%*d+%*d@%d",
+						 (int *) &iMonitor)) 
+        {
+          struct GetMonitorInfoData data;
+          if (!QueryMonitor(iMonitor, &data))
+          {
+              ErrorF ("ddxProcessArgument - screen - "
+                      "Querying monitors is not supported on NT4 and Win95\n");
+          } else if (data.bMonitorSpecifiedExists == TRUE) 
+          {
+			g_ScreenInfo[nScreenNum].dwInitialX += data.monitorOffsetX;
+			g_ScreenInfo[nScreenNum].dwInitialY += data.monitorOffsetY;
+		  }
+		  else 
+          {
+			/* monitor does not exist, error out */
+			ErrorF ("ddxProcessArgument - screen - Invalid monitor number %d\n",
+					iMonitor);
+			UseMsg ();
+			exit (0);
+			return 0;
+		  }
+
+		}
+	  }
+
+	  /* look for WxD at m where m is monitor number */
+	  else if (1 == sscanf(argv[i + 2], "%*dx%*d@%d",
+						   (int *) &iMonitor)) 
+      {
+        struct GetMonitorInfoData data;
+        if (!QueryMonitor(iMonitor, &data))
+        {
+		  ErrorF ("ddxProcessArgument - screen - "
+                  "Querying monitors is not supported on NT4 and Win95\n");
+        } else if (data.bMonitorSpecifiedExists == TRUE) 
+        {
+		  winErrorFVerb (2, "ddxProcessArgument - screen - Found Valid ``@Monitor'' = %d arg\n", iMonitor);
+		  g_ScreenInfo[nScreenNum].fUserGavePosition = TRUE;
+		  g_ScreenInfo[nScreenNum].dwInitialX = data.monitorOffsetX;
+		  g_ScreenInfo[nScreenNum].dwInitialY = data.monitorOffsetY;
+		}
+		else 
+        {
+		  /* monitor does not exist, error out */
+		  ErrorF ("ddxProcessArgument - screen - Invalid monitor number %d\n",
+				  iMonitor);
+		  UseMsg ();
+		  exit (0);
+		  return 0;
+		}
+
+	  }
+	}
+      else if (i + 3 < argc
+	       && 1 == sscanf (argv[i + 2], "%d",
+			       (int *) &iWidth)
+	       && 1 == sscanf (argv[i + 3], "%d",
+			       (int *) &iHeight))
+	{
+	  winErrorFVerb (2, "ddxProcessArgument - screen - Found ``W D'' arg\n");
+	  iArgsProcessed = 4;
+	  g_ScreenInfo[nScreenNum].fUserGaveHeightAndWidth = TRUE;
+	  g_ScreenInfo[nScreenNum].dwWidth = iWidth;
+	  g_ScreenInfo[nScreenNum].dwHeight = iHeight;
+	  g_ScreenInfo[nScreenNum].dwUserWidth = iWidth;
+	  g_ScreenInfo[nScreenNum].dwUserHeight = iHeight;
+	  if (i + 5 < argc
+	      && 1 == sscanf (argv[i + 4], "%d",
+			      (int *) &iX)
+	      && 1 == sscanf (argv[i + 5], "%d",
+			      (int *) &iY))
+	  {
+	    winErrorFVerb (2, "ddxProcessArgument - screen - Found ``X Y'' arg\n");
+	    iArgsProcessed = 6;
+	    g_ScreenInfo[nScreenNum].fUserGavePosition = TRUE;
+	    g_ScreenInfo[nScreenNum].dwInitialX = iX;
+	    g_ScreenInfo[nScreenNum].dwInitialY = iY;
+	  }
+	}
+      else
+	{
+	  winErrorFVerb (2, "ddxProcessArgument - screen - Did not find size arg. "
+		  "dwWidth: %d dwHeight: %d\n",
+		  (int) g_ScreenInfo[nScreenNum].dwWidth,
+		  (int) g_ScreenInfo[nScreenNum].dwHeight);
+	  iArgsProcessed = 2;
+	  g_ScreenInfo[nScreenNum].fUserGaveHeightAndWidth = FALSE;
+	}
+
+      /* Calculate the screen width and height in millimeters */
+      if (g_ScreenInfo[nScreenNum].fUserGaveHeightAndWidth)
+	{
+	  g_ScreenInfo[nScreenNum].dwWidth_mm
+	    = (g_ScreenInfo[nScreenNum].dwWidth
+	       / monitorResolution) * 25.4;
+	  g_ScreenInfo[nScreenNum].dwHeight_mm
+	    = (g_ScreenInfo[nScreenNum].dwHeight
+	       / monitorResolution) * 25.4;
+	}
+
+      /* Flag that this screen was explicity specified by the user */
+      g_ScreenInfo[nScreenNum].fExplicitScreen = TRUE;
+
+      /*
+       * Keep track of the last screen number seen, as parameters seen
+       * before a screen number apply to all screens, whereas parameters
+       * seen after a screen number apply to that screen number only.
+       */
+      g_iLastScreen = nScreenNum;
+
+      /* Keep a count of the number of screens */
+      ++g_iNumScreens;
+
+      return iArgsProcessed;
+    }
+
+  /*
+   * Look for the '-engine n' argument
+   */
+  if (IS_OPTION ("-engine"))
+    {
+      DWORD		dwEngine = 0;
+      CARD8		c8OnBits = 0;
+      
+      /* Display the usage message if the argument is malformed */
+      if (++i >= argc)
+	{
+	  UseMsg ();
+	  return 0;
+	}
+
+      /* Grab the argument */
+      dwEngine = atoi (argv[i]);
+
+      /* Count the one bits in the engine argument */
+      c8OnBits = winCountBits (dwEngine);
+
+      /* Argument should only have a single bit on */
+      if (c8OnBits != 1)
+	{
+	  UseMsg ();
+	  return 0;
+	}
+
+      /* Is this parameter attached to a screen or global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int		j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].dwEnginePreferred = dwEngine;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].dwEnginePreferred = dwEngine;
+	}
+      
+      /* Indicate that we have processed the argument */
+      return 2;
+    }
+
+  /*
+   * Look for the '-fullscreen' argument
+   */
+  if (IS_OPTION ("-fullscreen"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+              if (!g_ScreenInfo[j].fMultiMonitorOverride)
+                g_ScreenInfo[j].fMultipleMonitors = FALSE;
+#endif
+	      g_ScreenInfo[j].fFullScreen = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+          if (!g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride)
+            g_ScreenInfo[g_iLastScreen].fMultipleMonitors = FALSE;
+#endif
+	  g_ScreenInfo[g_iLastScreen].fFullScreen = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+  /*
+   * Look for the '-lesspointer' argument
+   */
+  if (IS_OPTION ("-lesspointer"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].fLessPointer = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+          g_ScreenInfo[g_iLastScreen].fLessPointer = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+  /*
+   * Look for the '-nodecoration' argument
+   */
+  if (IS_OPTION ("-nodecoration"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+              if (!g_ScreenInfo[j].fMultiMonitorOverride)
+                g_ScreenInfo[j].fMultipleMonitors = FALSE;
+#endif
+	      g_ScreenInfo[j].fDecoration = FALSE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+          if (!g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride)
+            g_ScreenInfo[g_iLastScreen].fMultipleMonitors = FALSE;
+#endif
+	  g_ScreenInfo[g_iLastScreen].fDecoration = FALSE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  /*
+   * Look for the '-mwextwm' argument
+   */
+  if (IS_OPTION ("-mwextwm"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+              if (!g_ScreenInfo[j].fMultiMonitorOverride)
+                g_ScreenInfo[j].fMultipleMonitors = TRUE;
+	      g_ScreenInfo[j].fMWExtWM = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+          if (!g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride)
+            g_ScreenInfo[g_iLastScreen].fMultipleMonitors = TRUE;
+	  g_ScreenInfo[g_iLastScreen].fMWExtWM = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+  /*
+   * Look for the '-internalwm' argument
+   */
+  if (IS_OPTION ("-internalwm"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      if (!g_ScreenInfo[j].fMultiMonitorOverride)
+	        g_ScreenInfo[j].fMultipleMonitors = TRUE;
+	      g_ScreenInfo[j].fMWExtWM = TRUE;
+	      g_ScreenInfo[j].fInternalWM = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  if (!g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride)
+	    g_ScreenInfo[g_iLastScreen].fMultipleMonitors = TRUE;
+	  g_ScreenInfo[g_iLastScreen].fMWExtWM = TRUE;
+	  g_ScreenInfo[g_iLastScreen].fInternalWM = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+#endif
+
+  /*
+   * Look for the '-rootless' argument
+   */
+  if (IS_OPTION ("-rootless"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+              if (!g_ScreenInfo[j].fMultiMonitorOverride)
+                g_ScreenInfo[j].fMultipleMonitors = FALSE;
+#endif
+	      g_ScreenInfo[j].fRootless = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+          if (!g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride)
+            g_ScreenInfo[g_iLastScreen].fMultipleMonitors = FALSE;
+#endif
+	  g_ScreenInfo[g_iLastScreen].fRootless = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+#ifdef XWIN_MULTIWINDOW
+  /*
+   * Look for the '-multiwindow' argument
+   */
+  if (IS_OPTION ("-multiwindow"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+              if (!g_ScreenInfo[j].fMultiMonitorOverride)
+                g_ScreenInfo[j].fMultipleMonitors = TRUE;
+#endif
+	      g_ScreenInfo[j].fMultiWindow = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+          if (!g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride)
+            g_ScreenInfo[g_iLastScreen].fMultipleMonitors = TRUE;
+#endif
+	  g_ScreenInfo[g_iLastScreen].fMultiWindow = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+#endif
+
+  /*
+   * Look for the '-multiplemonitors' argument
+   */
+  if (IS_OPTION ("-multiplemonitors")
+      || IS_OPTION ("-multimonitors"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+              g_ScreenInfo[j].fMultiMonitorOverride = TRUE;
+#endif
+	      g_ScreenInfo[j].fMultipleMonitors = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+          g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride = TRUE;
+#endif
+	  g_ScreenInfo[g_iLastScreen].fMultipleMonitors = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+  /*
+   * Look for the '-nomultiplemonitors' argument
+   */
+  if (IS_OPTION ("-nomultiplemonitors")
+      || IS_OPTION ("-nomultimonitors"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+              g_ScreenInfo[j].fMultiMonitorOverride = TRUE;
+#endif
+	      g_ScreenInfo[j].fMultipleMonitors = FALSE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+          g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride = TRUE;
+#endif
+	  g_ScreenInfo[g_iLastScreen].fMultipleMonitors = FALSE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+
+  /*
+   * Look for the '-scrollbars' argument
+   */
+  if (IS_OPTION ("-scrollbars"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].fScrollbars = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].fScrollbars = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+
+#ifdef XWIN_CLIPBOARD
+  /*
+   * Look for the '-clipboard' argument
+   */
+  if (IS_OPTION ("-clipboard"))
+    {
+      g_fClipboard = TRUE;
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+#endif
+
+
+  /*
+   * Look for the '-ignoreinput' argument
+   */
+  if (IS_OPTION ("-ignoreinput"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].fIgnoreInput = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].fIgnoreInput = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+  /*
+   * Look for the '-emulate3buttons' argument
+   */
+  if (IS_OPTION ("-emulate3buttons"))
+    {
+      int	iArgsProcessed = 1;
+      int	iE3BTimeout = WIN_DEFAULT_E3B_TIME;
+
+      /* Grab the optional timeout value */
+      if (i + 1 < argc
+	  && 1 == sscanf (argv[i + 1], "%d",
+			  &iE3BTimeout))
+        {
+	  /* Indicate that we have processed the next argument */
+	  iArgsProcessed++;
+        }
+      else
+	{
+	  /*
+	   * sscanf () won't modify iE3BTimeout if it doesn't find
+	   * the specified format; however, I want to be explicit
+	   * about setting the default timeout in such cases to
+	   * prevent some programs (me) from getting confused.
+	   */
+	  iE3BTimeout = WIN_DEFAULT_E3B_TIME;
+	}
+
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].iE3BTimeout = iE3BTimeout;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].iE3BTimeout = iE3BTimeout;
+	}
+
+      /* Indicate that we have processed this argument */
+      return iArgsProcessed;
+    }
+
+  /*
+   * Look for the '-depth n' argument
+   */
+  if (IS_OPTION ("-depth"))
+    {
+      DWORD		dwBPP = 0;
+      
+      /* Display the usage message if the argument is malformed */
+      if (++i >= argc)
+	{
+	  UseMsg ();
+	  return 0;
+	}
+
+      /* Grab the argument */
+      dwBPP = atoi (argv[i]);
+
+      /* Is this parameter attached to a screen or global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int		j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].dwBPP = dwBPP;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].dwBPP = dwBPP;
+	}
+      
+      /* Indicate that we have processed the argument */
+      return 2;
+    }
+
+  /*
+   * Look for the '-refresh n' argument
+   */
+  if (IS_OPTION ("-refresh"))
+    {
+      DWORD		dwRefreshRate = 0;
+      
+      /* Display the usage message if the argument is malformed */
+      if (++i >= argc)
+	{
+	  UseMsg ();
+	  return 0;
+	}
+
+      /* Grab the argument */
+      dwRefreshRate = atoi (argv[i]);
+
+      /* Is this parameter attached to a screen or global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int		j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].dwRefreshRate = dwRefreshRate;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].dwRefreshRate = dwRefreshRate;
+	}
+      
+      /* Indicate that we have processed the argument */
+      return 2;
+    }
+
+  /*
+   * Look for the '-clipupdates num_boxes' argument
+   */
+  if (IS_OPTION ("-clipupdates"))
+    {
+      DWORD		dwNumBoxes = 0;
+      
+      /* Display the usage message if the argument is malformed */
+      if (++i >= argc)
+	{
+	  UseMsg ();
+	  return 0;
+	}
+
+      /* Grab the argument */
+      dwNumBoxes = atoi (argv[i]);
+
+      /* Is this parameter attached to a screen or global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int		j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].dwClipUpdatesNBoxes = dwNumBoxes;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].dwClipUpdatesNBoxes = dwNumBoxes;
+	}
+      
+      /* Indicate that we have processed the argument */
+      return 2;
+    }
+
+#ifdef XWIN_EMULATEPSEUDO
+  /*
+   * Look for the '-emulatepseudo' argument
+   */
+  if (IS_OPTION ("-emulatepseudo"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].fEmulatePseudo = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+          g_ScreenInfo[g_iLastScreen].fEmulatePseudo = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+#endif
+
+  /*
+   * Look for the '-nowinkill' argument
+   */
+  if (IS_OPTION ("-nowinkill"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].fUseWinKillKey = FALSE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].fUseWinKillKey = FALSE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+  /*
+   * Look for the '-winkill' argument
+   */
+  if (IS_OPTION ("-winkill"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].fUseWinKillKey = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].fUseWinKillKey = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+  /*
+   * Look for the '-nounixkill' argument
+   */
+  if (IS_OPTION ("-nounixkill"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].fUseUnixKillKey = FALSE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].fUseUnixKillKey = FALSE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+  /*
+   * Look for the '-unixkill' argument
+   */
+  if (IS_OPTION ("-unixkill"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].fUseUnixKillKey = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].fUseUnixKillKey = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+  /*
+   * Look for the '-notrayicon' argument
+   */
+  if (IS_OPTION ("-notrayicon"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].fNoTrayIcon = TRUE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].fNoTrayIcon = TRUE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+  /*
+   * Look for the '-trayicon' argument
+   */
+  if (IS_OPTION ("-trayicon"))
+    {
+      /* Is this parameter attached to a screen or is it global? */
+      if (-1 == g_iLastScreen)
+	{
+	  int			j;
+
+	  /* Parameter is for all screens */
+	  for (j = 0; j < MAXSCREENS; j++)
+	    {
+	      g_ScreenInfo[j].fNoTrayIcon = FALSE;
+	    }
+	}
+      else
+	{
+	  /* Parameter is for a single screen */
+	  g_ScreenInfo[g_iLastScreen].fNoTrayIcon = FALSE;
+	}
+
+      /* Indicate that we have processed this argument */
+      return 1;
+    }
+
+  /*
+   * Look for the '-fp' argument
+   */
+  if (IS_OPTION ("-fp"))
+    {
+      CHECK_ARGS (1);
+      g_cmdline.fontPath = argv[++i];
+      return 0; /* Let DIX parse this again */
+    }
+
+  /*
+   * Look for the '-query' argument
+   */
+  if (IS_OPTION ("-query"))
+    {
+      CHECK_ARGS (1);
+      g_fXdmcpEnabled = TRUE;
+      g_pszQueryHost = argv[++i];
+      return 0; /* Let DIX parse this again */
+    }
+
+  /*
+   * Look for the '-indirect' or '-broadcast' arguments
+   */
+  if (IS_OPTION ("-indirect")
+      || IS_OPTION ("-broadcast"))
+    {
+      g_fXdmcpEnabled = TRUE;
+      return 0; /* Let DIX parse this again */
+    }
+
+  /*
+   * Look for the '-config' argument
+   */
+  if (IS_OPTION ("-config")
+      || IS_OPTION ("-xf86config"))
+    {
+      CHECK_ARGS (1);
+#ifdef XWIN_XF86CONFIG
+      g_cmdline.configFile = argv[++i];
+#else
+      winMessageBoxF ("The %s option is not supported in this "
+		      "release.\n"
+		      "Ignoring this option and continuing.\n",
+		      MB_ICONINFORMATION,
+		      argv[i]);
+#endif
+      return 2;
+    }
+
+  /*
+   * Look for the '-keyboard' argument
+   */
+  if (IS_OPTION ("-keyboard"))
+    {
+#ifdef XWIN_XF86CONFIG
+      CHECK_ARGS (1);
+      g_cmdline.keyboard = argv[++i];
+#else
+      winMessageBoxF ("The -keyboard option is not supported in this "
+		      "release.\n"
+		      "Ignoring this option and continuing.\n",
+		      MB_ICONINFORMATION);
+#endif
+      return 2;
+    }
+
+  /*
+   * Look for the '-logfile' argument
+   */
+  if (IS_OPTION ("-logfile"))
+    {
+      CHECK_ARGS (1);
+      g_pszLogFile = argv[++i];
+#ifdef RELOCATE_PROJECTROOT
+      g_fLogFileChanged = TRUE;
+#endif
+      return 2;
+    }
+
+  /*
+   * Look for the '-logverbose' argument
+   */
+  if (IS_OPTION ("-logverbose"))
+    {
+      CHECK_ARGS (1);
+      g_iLogVerbose = atoi(argv[++i]);
+      return 2;
+    }
+
+#ifdef XWIN_CLIPBOARD
+  /*
+   * Look for the '-nounicodeclipboard' argument
+   */
+  if (IS_OPTION ("-nounicodeclipboard"))
+    {
+      g_fUnicodeClipboard = FALSE;
+      /* Indicate that we have processed the argument */
+      return 1;
+    }
+#endif
+
+#ifdef XKB
+  /*
+   * Look for the '-kb' argument
+   */
+  if (IS_OPTION ("-kb"))
+    {
+      g_cmdline.noXkbExtension = TRUE;  
+      return 0; /* Let DIX parse this again */
+    }
+
+  if (IS_OPTION ("-xkbrules"))
+    {
+      CHECK_ARGS (1);
+      g_cmdline.xkbRules = argv[++i];
+      return 2;
+    }
+  if (IS_OPTION ("-xkbmodel"))
+    {
+      CHECK_ARGS (1);
+      g_cmdline.xkbModel = argv[++i];
+      return 2;
+    }
+  if (IS_OPTION ("-xkblayout"))
+    {
+      CHECK_ARGS (1);
+      g_cmdline.xkbLayout = argv[++i];
+      return 2;
+    }
+  if (IS_OPTION ("-xkbvariant"))
+    {
+      CHECK_ARGS (1);
+      g_cmdline.xkbVariant = argv[++i];
+      return 2;
+    }
+  if (IS_OPTION ("-xkboptions"))
+    {
+      CHECK_ARGS (1);
+      g_cmdline.xkbOptions = argv[++i];
+      return 2;
+    }
+#endif
+
+  if (IS_OPTION ("-keyhook"))
+    {
+      g_fKeyboardHookLL = TRUE;
+      return 1;
+    }
+  
+  if (IS_OPTION ("-nokeyhook"))
+    {
+      g_fKeyboardHookLL = FALSE;
+      return 1;
+    }
+  
+  if (IS_OPTION ("-swcursor"))
+    {
+      g_fSoftwareCursor = TRUE;
+      return 1;
+    }
+  
+  if (IS_OPTION ("-silent-dup-error"))
+    {
+      g_fSilentDupError = TRUE;
+      return 1;
+    }
+  return 0;
+}
+
+
+/*
+ * winLogCommandLine - Write entire command line to the log file
+ */
+
+void
+winLogCommandLine (int argc, char *argv[])
+{
+  int		i;
+  int		iSize = 0;
+  int		iCurrLen = 0;
+
+#define CHARS_PER_LINE 60
+
+  /* Bail if command line has already been logged */
+  if (g_pszCommandLine)
+    return;
+
+  /* Count how much memory is needed for concatenated command line */
+  for (i = 0, iCurrLen = 0; i < argc; ++i)
+    if (argv[i])
+      {
+	/* Add a character for lines that overflow */
+	if ((strlen (argv[i]) < CHARS_PER_LINE
+	    && iCurrLen + strlen (argv[i]) > CHARS_PER_LINE)
+	    || strlen (argv[i]) > CHARS_PER_LINE)
+	  {
+	    iCurrLen = 0;
+	    ++iSize;
+	  }
+	
+	/* Add space for item and trailing space */
+	iSize += strlen (argv[i]) + 1;
+
+	/* Update current line length */
+	iCurrLen += strlen (argv[i]);
+      }
+
+  /* Allocate memory for concatenated command line */
+  g_pszCommandLine = malloc (iSize + 1);
+  if (!g_pszCommandLine)
+    FatalError ("winLogCommandLine - Could not allocate memory for "
+		"command line string.  Exiting.\n");
+  
+  /* Set first character to concatenated command line to null */
+  g_pszCommandLine[0] = '\0';
+
+  /* Loop through all args */
+  for (i = 0, iCurrLen = 0; i < argc; ++i)
+    {
+      /* Add a character for lines that overflow */
+      if ((strlen (argv[i]) < CHARS_PER_LINE
+	   && iCurrLen + strlen (argv[i]) > CHARS_PER_LINE)
+	  || strlen (argv[i]) > CHARS_PER_LINE)
+      {
+	iCurrLen = 0;
+	
+	/* Add line break if it fits */
+	strncat (g_pszCommandLine, "\n", iSize - strlen (g_pszCommandLine));
+      }
+      
+      strncat (g_pszCommandLine, argv[i], iSize - strlen (g_pszCommandLine));
+      strncat (g_pszCommandLine, " ", iSize - strlen (g_pszCommandLine));
+
+      /* Save new line length */
+      iCurrLen += strlen (argv[i]);
+    }
+
+  ErrorF ("XWin was started with the following command line:\n\n"
+	  "%s\n\n", g_pszCommandLine);
+}
+
+
+/*
+ * winLogVersionInfo - Log Cygwin/X version information
+ */
+
+void
+winLogVersionInfo (void)
+{
+  static Bool		s_fBeenHere = FALSE;
+
+  if (s_fBeenHere)
+    return;
+  s_fBeenHere = TRUE;
+
+  ErrorF ("Welcome to the XWin X Server\n");
+  ErrorF ("Vendor: %s\n", VENDOR_STRING);
+  ErrorF ("Release: %s\n\n", VERSION_STRING);
+  ErrorF ("Contact: %s\n\n", VENDOR_CONTACT);
+}
+
+/*
+ * getMonitorInfo - callback function used to return information from the enumeration of monitors attached
+ */
+
+wBOOL CALLBACK getMonitorInfo(HMONITOR hMonitor, HDC hdc, LPRECT rect, LPARAM _data) 
+{
+  struct GetMonitorInfoData* data = (struct GetMonitorInfoData*)_data;
+  // only get data for monitor number specified in <data>
+  data->monitorNum++;
+  if (data->monitorNum == data->requestedMonitor) 
+  {
+	data->bMonitorSpecifiedExists = TRUE;
+	data->monitorOffsetX = rect->left;
+	data->monitorOffsetY = rect->top;
+	data->monitorHeight  = rect->bottom - rect->top;
+	data->monitorWidth   = rect->right  - rect->left;
+    return FALSE;
+  }
+  return TRUE;
+}
diff --git a/hw/xwin/winpushpxl.c b/hw/xwin/winpushpxl.c
new file mode 100644
index 0000000..72ef2d5
--- /dev/null
+++ b/hw/xwin/winpushpxl.c
@@ -0,0 +1,225 @@
+/***********************************************************
+
+Copyright 1987, 1998  The Open Group
+
+Permission to use, copy, modify, distribute, and sell this software and its
+documentation for any purpose is hereby granted without fee, provided that
+the above copyright notice appear in all copies and that both that
+copyright notice and this permission notice appear in supporting
+documentation.
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of The Open Group shall not be
+used in advertising or otherwise to promote the sale, use or other dealings
+in this Software without prior written authorization from The Open Group.
+
+
+Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
+
+                        All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and its 
+documentation for any purpose and without fee is hereby granted, 
+provided that the above copyright notice appear in all copies and that
+both that copyright notice and this permission notice appear in 
+supporting documentation, and that the name of Digital not be
+used in advertising or publicity pertaining to distribution of the
+software without specific, written prior permission.  
+
+DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
+ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
+DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
+ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
+SOFTWARE.
+
+******************************************************************/
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include <X11/X.h>
+#include "gcstruct.h"
+#include "scrnintstr.h"
+#include "pixmapstr.h"
+#include "miscstruct.h"
+#include "../mfb/maskbits.h"
+#include "mi.h"
+
+#define NPT 128
+
+/* winPushPixels -- squeegees the fill style of pGC through pBitMap
+ * into pDrawable.  pBitMap is a stencil (dx by dy of it is used, it may
+ * be bigger) which is placed on the drawable at xOrg, yOrg.  Where a 1 bit
+ * is set in the bitmap, the fill style is put onto the drawable using
+ * the GC's logical function. The drawable is not changed where the bitmap
+ * has a zero bit or outside the area covered by the stencil.
+
+WARNING:
+    this code works if the 1-bit deep pixmap format returned by GetSpans
+is the same as the format defined by the mfb code (i.e. 32-bit padding
+per scanline, scanline unit = 32 bits; later, this might mean
+bitsizeof(int) padding and sacnline unit == bitsizeof(int).)
+
+ */
+
+/*
+ * in order to have both (MSB_FIRST and LSB_FIRST) versions of this
+ * in the server, we need to rename one of them
+ */
+void
+winPushPixels (GCPtr pGC, PixmapPtr pBitMap, DrawablePtr pDrawable,
+	       int dx, int dy, int xOrg, int yOrg)
+{
+    int		h, dxDivPPW, ibEnd;
+    MiBits *pwLineStart;
+    register MiBits	*pw, *pwEnd;
+    register MiBits msk;
+    register int ib, w;
+    register int ipt;		/* index into above arrays */
+    Bool 	fInBox;
+    DDXPointRec	pt[NPT], ptThisLine;
+    int		width[NPT];
+    PixelType	startmask;
+
+
+    startmask = (MiBits)(-1) ^
+            LONG2CHARSDIFFORDER((MiBits)(-1) >> 1);
+
+    pwLineStart = (MiBits *)xalloc(BitmapBytePad(dx));
+    if (!pwLineStart)
+	return;
+    ipt = 0;
+    dxDivPPW = dx/PPW;
+
+    for(h = 0, ptThisLine.x = 0, ptThisLine.y = 0; 
+	h < dy; 
+	h++, ptThisLine.y++)
+    {
+
+	(*pBitMap->drawable.pScreen->GetSpans)((DrawablePtr)pBitMap, dx,
+			&ptThisLine, &dx, 1, (char *)pwLineStart);
+
+	pw = pwLineStart;
+	/* Process all words which are fully in the pixmap */
+	
+	fInBox = FALSE;
+	pwEnd = pwLineStart + dxDivPPW;
+	while(pw  < pwEnd)
+	{
+	    w = *pw;
+#ifdef XFree86Server
+	    msk = startmask;
+#else
+	    msk = (MiBits)(-1) ^ SCRRIGHT((MiBits)(-1), 1);
+#endif
+	    for(ib = 0; ib < PPW; ib++)
+	    {
+		if(w & msk)
+		{
+		    if(!fInBox)
+		    {
+			pt[ipt].x = ((pw - pwLineStart) << PWSH) + ib + xOrg;
+			pt[ipt].y = h + yOrg;
+			/* start new box */
+			fInBox = TRUE;
+		    }
+		}
+		else
+		{
+		    if(fInBox)
+		    {
+			width[ipt] = ((pw - pwLineStart) << PWSH) + 
+				     ib + xOrg - pt[ipt].x;
+			if (++ipt >= NPT)
+			{
+			    (*pGC->ops->FillSpans)(pDrawable, pGC, 
+					      NPT, pt, width, TRUE);
+			    ipt = 0;
+			}
+			/* end box */
+			fInBox = FALSE;
+		    }
+		}
+#ifdef XFree86Server
+    		/* This is not quite right, but it'll do for now */
+		msk = LONG2CHARSDIFFORDER(LONG2CHARSDIFFORDER(msk) >> 1);
+#else
+		msk = SCRRIGHT(msk, 1);
+#endif
+	    }
+	    pw++;
+	}
+	ibEnd = dx & PIM;
+	if(ibEnd)
+	{
+	    /* Process final partial word on line */
+	    w = *pw;
+#ifdef XFree86Server
+	    msk = startmask;
+#else
+	    msk = (MiBits)(-1) ^ SCRRIGHT((MiBits)(-1), 1);
+#endif
+	    for(ib = 0; ib < ibEnd; ib++)
+	    {
+		if(w & msk)
+		{
+		    if(!fInBox)
+		    {
+			/* start new box */
+			pt[ipt].x = ((pw - pwLineStart) << PWSH) + ib + xOrg;
+			pt[ipt].y = h + yOrg;
+			fInBox = TRUE;
+		    }
+		}
+		else
+		{
+		    if(fInBox)
+		    {
+			/* end box */
+			width[ipt] = ((pw - pwLineStart) << PWSH) + 
+				     ib + xOrg - pt[ipt].x;
+			if (++ipt >= NPT)
+			{
+			    (*pGC->ops->FillSpans)(pDrawable, 
+					      pGC, NPT, pt, width, TRUE);
+			    ipt = 0;
+			}
+			fInBox = FALSE;
+		    }
+		}
+#ifdef XFree86Server
+    		/* This is not quite right, but it'll do for now */
+		msk = LONG2CHARSDIFFORDER(LONG2CHARSDIFFORDER(msk) >> 1);
+#else
+		msk = SCRRIGHT(msk, 1);
+#endif
+	    }
+	}
+	/* If scanline ended with last bit set, end the box */
+	if(fInBox)
+	{
+	    width[ipt] = dx + xOrg - pt[ipt].x;
+	    if (++ipt >= NPT)
+	    {
+		(*pGC->ops->FillSpans)(pDrawable, pGC, NPT, pt, width, TRUE);
+		ipt = 0;
+	    }
+	}
+    }
+    xfree(pwLineStart);
+    /* Flush any remaining spans */
+    if (ipt)
+    {
+	(*pGC->ops->FillSpans)(pDrawable, pGC, ipt, pt, width, TRUE);
+    }
+}
diff --git a/hw/xwin/winrandr.c b/hw/xwin/winrandr.c
new file mode 100755
index 0000000..7b5b135
--- /dev/null
+++ b/hw/xwin/winrandr.c
@@ -0,0 +1,141 @@
+/*
+ *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * Local prototypes
+ */
+
+static Bool
+winRandRGetInfo (ScreenPtr pScreen, Rotation *pRotations);
+
+static Bool
+winRandRSetConfig (ScreenPtr		pScreen,
+		   Rotation		rotateKind,
+		   int			rate,
+		   RRScreenSizePtr	pSize);
+
+Bool
+winRandRInit (ScreenPtr pScreen);
+
+
+/*
+ * Answer queries about the RandR features supported.
+ */
+
+static Bool
+winRandRGetInfo (ScreenPtr pScreen, Rotation *pRotations)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo			*pScreenInfo = pScreenPriv->pScreenInfo;
+  int				n;
+  Rotation			rotateKind;
+  RRScreenSizePtr		pSize;
+
+  winDebug ("winRandRGetInfo ()\n");
+
+  /* Don't support rotations, yet */
+  *pRotations = RR_Rotate_0;
+
+  /* Bail if no depth has a visual associated with it */
+  for (n = 0; n < pScreen->numDepths; n++)
+    if (pScreen->allowedDepths[n].numVids)
+      break;
+  if (n == pScreen->numDepths)
+    return FALSE;
+
+  /* Only one allowed rotation for now */
+  rotateKind = RR_Rotate_0;
+
+  /*
+   * Register supported sizes.  This can be called many times, but
+   * we only support one size for now.
+   */
+  pSize = RRRegisterSize (pScreen,
+			  pScreenInfo->dwWidth,
+			  pScreenInfo->dwHeight,
+			  pScreenInfo->dwWidth_mm,
+			  pScreenInfo->dwHeight_mm);
+
+  /* Tell RandR what the current config is */
+  RRSetCurrentConfig (pScreen,
+		      rotateKind,
+		      0, /* refresh rate, not needed */
+		      pSize);
+  
+  return TRUE;
+}
+
+
+/*
+ * Respond to resize/rotate request from either X Server or X client app
+ */
+
+static Bool
+winRandRSetConfig (ScreenPtr		pScreen,
+		   Rotation		rotateKind,
+		   int			rate,
+		   RRScreenSizePtr	pSize)
+{
+  winDebug ("winRandRSetConfig ()\n");
+
+  return TRUE;
+}
+
+
+/*
+ * Initialize the RandR layer.
+ */
+
+Bool
+winRandRInit (ScreenPtr pScreen)
+{
+  rrScrPrivPtr		pRRScrPriv;
+
+  winDebug ("winRandRInit ()\n");
+
+  if (!RRScreenInit (pScreen))
+    {
+      ErrorF ("winRandRInit () - RRScreenInit () failed\n");
+      return FALSE;
+    }
+
+  /* Set some RandR function pointers */
+  pRRScrPriv = rrGetScrPriv (pScreen);
+  pRRScrPriv->rrGetInfo = winRandRGetInfo;
+  pRRScrPriv->rrSetConfig = winRandRSetConfig;
+
+  return TRUE;
+}
diff --git a/hw/xwin/winregistry.c b/hw/xwin/winregistry.c
new file mode 100644
index 0000000..3571b14
--- /dev/null
+++ b/hw/xwin/winregistry.c
@@ -0,0 +1,71 @@
+/*
+ *Copyright (C) 2002-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+/* Prototypes */
+DWORD
+winGetRegistryDWORD (HKEY hkey, char *pszRegistryKey);
+
+DWORD
+winGetRegistryDWORD (HKEY hkey, char *pszRegistryKey)
+{
+  HKEY		hkResult;
+  DWORD		dwDisposition;
+
+  RegCreateKeyEx (hkey,
+		  pszRegistryKey,
+		  0,
+		  '\0',
+		  REG_OPTION_NON_VOLATILE,
+		  KEY_READ,
+		  NULL,
+		  &hkResult,
+		  &dwDisposition);
+
+  if (dwDisposition == REG_CREATED_NEW_KEY)
+    {
+      ErrorF ("winGetRegistryDWORD - Created new key: %s\n", pszRegistryKey);
+    }
+  else if (dwDisposition == REG_OPENED_EXISTING_KEY)
+    {
+      ErrorF ("winGetRegistryDWORD - Opened existing key: %s\n",
+	      pszRegistryKey);
+    }
+
+  /* Free the registry key handle */
+  RegCloseKey (hkResult);
+  hkResult = NULL;
+
+  return 0;
+}
diff --git a/hw/xwin/winresource.h b/hw/xwin/winresource.h
new file mode 100644
index 0000000..5aa8840
--- /dev/null
+++ b/hw/xwin/winresource.h
@@ -0,0 +1,55 @@
+#if !defined(WINRESOURCE_H)
+#define WINRESOURCE_H
+/*
+ *Copyright (C) 2002-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+
+/*
+ * Local defines
+ */
+
+#define IDC_STATIC		-1
+#define IDI_XWIN		101
+#define IDI_XWIN_BOXED		102
+#define IDM_TRAYICON_MENU	103
+#define IDC_CLIENTS_CONNECTED	104
+
+
+#define ID_APP_EXIT		200
+#define ID_APP_HIDE_ROOT	201
+#define ID_APP_ALWAYS_ON_TOP	202
+#define ID_APP_ABOUT		203
+
+#define ID_ABOUT_UG		300
+#define ID_ABOUT_FAQ		301
+#define ID_ABOUT_CHANGELOG	302
+#define ID_ABOUT_WEBSITE	303
+
+#endif
diff --git a/hw/xwin/winrop.c b/hw/xwin/winrop.c
new file mode 100644
index 0000000..f481892
--- /dev/null
+++ b/hw/xwin/winrop.c
@@ -0,0 +1,144 @@
+/*
+ *Copyright (C) 1994-2002 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * 	Authors:	Alan Hourihane <alanh at fairlite.demon.co.uk>
+ */
+
+/*
+ * Raster operations used by Windows translated to X's 16 rop codes...
+ */
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+void
+ROP16 (HDC hdc, int rop);
+
+int g_copyROP[16] = { 	0xFF0062, /* GXclear 		- 0 */
+		 	0x8800C6, /* GXand 		- S & D */
+		 	0x440328, /* GXandReverse  	- S & !D */
+		 	0xCC0020, /* GXcopy 		- S */
+		 	0x220326, /* GXandInverted 	- !S & D */
+		 	0xAA0029, /* GXnoop		- D */
+		 	0x660046, /* GXxor 		- S ^ D */
+		 	0xEE0086, /* GXor		- S | D */
+		 	0x1100A6, /* GXnor 		- !S & !D */
+		 	0x990126, /* GXequiv		- !S ^ D */
+		 	0x550009, /* GXinvert		- !D */
+		 	0xDD0228, /* GXorReverse	- S | !D */
+		 	0x330008, /* GXcopyInverted	- !S */
+		 	0xBB0226, /* GXorInverted	- !S | D */
+		 	0x7700C6, /* GXnand		- !S | !D */
+		 	0x000042  /* GXset		- 1 */
+};
+
+int g_patternROP[16] = {0xFF0062, /* GXclear		- 0 */
+		 	0xA000C9, /* GXand 		- P & D */
+		 	0xF50225, /* GXandReverse	- P & !D */
+		 	0xF00021, /* GXcopy 		- P */
+		 	0x5F00E9, /* GXandInverted 	- !P & D */
+		 	0xAA0029, /* GXnoop		- D */
+		 	0xA50065, /* GXxor		- P ^ D */
+		 	0xA000C9, /* GXor		- P | D */
+		 	0x5F00E9, /* GXnor		- !P & !D */
+		 	0x5A0049, /* GXequiv		- !P ^ D */
+		 	0x550009, /* GXinvert		- !D */
+		 	0x500325, /* GXorReverse	- P | !D */
+		 	0x0F0001, /* GXcopyInverted	- !P */
+		 	0x0A0329, /* GXorInverted	- !P | D */
+		 	0x0500A9, /* GXnand		- !P | !D */
+		 	0x000042  /* GXset		- 1 */
+};
+
+
+void
+ROP16 (HDC hdc, int rop)
+{
+  switch (rop)
+    {
+    case GXclear:
+      SetROP2 (hdc, R2_BLACK);
+      break;
+
+    case GXand:
+      SetROP2 (hdc, R2_MASKPEN);
+      break;
+
+    case GXandReverse:
+      SetROP2 (hdc, R2_MASKPENNOT);
+      break;
+
+    case GXcopy:
+      SetROP2 (hdc, R2_COPYPEN);
+      break;
+
+    case GXnoop:
+      SetROP2 (hdc, R2_NOP);
+      break;
+
+    case GXxor:
+      SetROP2 (hdc, R2_XORPEN);
+      break;
+
+    case GXor:
+      SetROP2 (hdc, R2_MERGEPEN);
+      break;
+
+    case GXnor:
+      SetROP2 (hdc, R2_NOTMERGEPEN);
+      break;
+
+    case GXequiv:
+      SetROP2 (hdc, R2_NOTXORPEN);
+      break;
+
+    case GXinvert:
+      SetROP2 (hdc, R2_NOT);
+      break;
+
+    case GXorReverse:
+      SetROP2 (hdc, R2_MERGEPENNOT);
+      break;
+
+    case GXcopyInverted:
+      SetROP2 (hdc, R2_NOTCOPYPEN);
+      break;
+
+    case GXorInverted:
+      SetROP2 (hdc, R2_MERGENOTPEN);
+      break;
+
+    case GXnand:
+      SetROP2 (hdc, R2_NOTMASKPEN);
+      break;
+
+    case GXset:
+      SetROP2 (hdc, R2_WHITE);
+      break;
+    }
+}
diff --git a/hw/xwin/winscrinit.c b/hw/xwin/winscrinit.c
new file mode 100644
index 0000000..9dc4c3d
--- /dev/null
+++ b/hw/xwin/winscrinit.c
@@ -0,0 +1,781 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ *		Kensuke Matsuzaki
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winmsg.h"
+#include "safeAlpha.h"	
+
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+static RootlessFrameProcsRec
+winMWExtWMProcs = {	
+  winMWExtWMCreateFrame,
+  winMWExtWMDestroyFrame,
+  
+  winMWExtWMMoveFrame,
+  winMWExtWMResizeFrame,
+  winMWExtWMRestackFrame,
+  winMWExtWMReshapeFrame,
+  winMWExtWMUnmapFrame,
+  
+  winMWExtWMStartDrawing,
+  winMWExtWMStopDrawing,
+  winMWExtWMUpdateRegion,
+#ifndef ROOTLESS_TRACK_DAMAGE
+  winMWExtWMDamageRects,
+#endif
+  winMWExtWMRootlessSwitchWindow,
+  NULL,//winWMExtWMDoReorderWindow,
+  
+  NULL,//winMWExtWMCopyBytes,
+  NULL,//winMWExtWMFillBytes,
+  NULL,//winMWExtWMCompositePixels,
+  winMWExtWMCopyWindow
+};
+#endif
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool                     g_fSoftwareCursor;
+
+
+/*
+ * Prototypes
+ */
+
+Bool
+winRandRInit (ScreenPtr pScreen);
+
+
+/*
+ * Local functions
+ */
+
+static Bool
+winSaveScreen (ScreenPtr pScreen, int on);
+
+
+/*
+ * Determine what type of screen we are initializing
+ * and call the appropriate procedure to intiailize
+ * that type of screen.
+ */
+
+Bool
+winScreenInit (int index,
+	       ScreenPtr pScreen,
+	       int argc, char **argv)
+{
+  winScreenInfoPtr      pScreenInfo = &g_ScreenInfo[index];
+  winPrivScreenPtr	pScreenPriv;
+  HDC			hdc;
+
+#if CYGDEBUG || YES
+  winDebug ("winScreenInit - dwWidth: %ld dwHeight: %ld\n",
+	  pScreenInfo->dwWidth, pScreenInfo->dwHeight);
+#endif
+
+  /* Allocate privates for this screen */
+  if (!winAllocatePrivates (pScreen))
+    {
+      ErrorF ("winScreenInit - Couldn't allocate screen privates\n");
+      return FALSE;
+    }
+
+  /* Get a pointer to the privates structure that was allocated */
+  pScreenPriv = winGetScreenPriv (pScreen);
+
+  /* Save a pointer to this screen in the screen info structure */
+  pScreenInfo->pScreen = pScreen;
+
+  /* Save a pointer to the screen info in the screen privates structure */
+  /* This allows us to get back to the screen info from a screen pointer */
+  pScreenPriv->pScreenInfo = pScreenInfo;
+
+  /*
+   * Determine which engine to use.
+   *
+   * NOTE: This is done once per screen because each screen possibly has
+   * a preferred engine specified on the command line.
+   */
+  if (!winSetEngine (pScreen))
+    {
+      ErrorF ("winScreenInit - winSetEngine () failed\n");
+      return FALSE;
+    }
+
+  /* Adjust the video mode for our engine type */
+  if (!(*pScreenPriv->pwinAdjustVideoMode) (pScreen))
+    {
+      ErrorF ("winScreenInit - winAdjustVideoMode () failed\n");
+      return FALSE;
+    }
+
+  /* Check for supported display depth */
+  if (!(WIN_SUPPORTED_BPPS & (1 << (pScreenInfo->dwBPP - 1))))
+    {
+      ErrorF ("winScreenInit - Unsupported display depth: %d\n" \
+	      "Change your Windows display depth to 15, 16, 24, or 32 bits "
+	      "per pixel.\n",
+	      (int) pScreenInfo->dwBPP);
+      ErrorF ("winScreenInit - Supported depths: %08x\n",
+	      WIN_SUPPORTED_BPPS);
+#if WIN_CHECK_DEPTH
+      return FALSE;
+#endif
+    }
+
+  /*
+   * Check that all monitors have the same display depth if we are using
+   * multiple monitors
+   */
+  if (pScreenInfo->fMultipleMonitors 
+      && !GetSystemMetrics (SM_SAMEDISPLAYFORMAT))
+    {
+      ErrorF ("winScreenInit - Monitors do not all have same pixel format / "
+	      "display depth.\n"
+	      "Using primary display only.\n");
+      pScreenInfo->fMultipleMonitors = FALSE;
+    }
+
+  /* Create display window */
+  if (!(*pScreenPriv->pwinCreateBoundingWindow) (pScreen))
+    {
+      ErrorF ("winScreenInit - pwinCreateBoundingWindow () "
+	      "failed\n");
+      return FALSE;
+    }
+
+  /* Get a device context */
+  hdc = GetDC (pScreenPriv->hwndScreen);
+
+  /* Store the initial height, width, and depth of the display */
+  /* Are we using multiple monitors? */
+  if (pScreenInfo->fMultipleMonitors)
+    {
+      pScreenPriv->dwLastWindowsWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
+      pScreenPriv->dwLastWindowsHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
+
+      /* 
+       * In this case, some of the defaults set in
+       * winInitializeDefaultScreens () are not correct ...
+       */
+      if (!pScreenInfo->fUserGaveHeightAndWidth)
+	{
+	  pScreenInfo->dwWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
+	  pScreenInfo->dwHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
+	  pScreenInfo->dwWidth_mm = (pScreenInfo->dwWidth /
+				     WIN_DEFAULT_DPI) * 25.4;
+	  pScreenInfo->dwHeight_mm = (pScreenInfo->dwHeight /
+				      WIN_DEFAULT_DPI) * 25.4;
+	}
+    }
+  else
+    {
+      pScreenPriv->dwLastWindowsWidth = GetSystemMetrics (SM_CXSCREEN);
+      pScreenPriv->dwLastWindowsHeight = GetSystemMetrics (SM_CYSCREEN);
+    }
+
+  /* Save the original bits per pixel */
+  pScreenPriv->dwLastWindowsBitsPixel = GetDeviceCaps (hdc, BITSPIXEL);
+
+  /* Release the device context */
+  ReleaseDC (pScreenPriv->hwndScreen, hdc);
+    
+  /* Clear the visuals list */
+  miClearVisualTypes ();
+  
+  /* Set the padded screen width */
+  pScreenInfo->dwPaddedWidth = PixmapBytePad (pScreenInfo->dwWidth,
+					      pScreenInfo->dwBPP);
+
+  /* Call the engine dependent screen initialization procedure */
+  if (!((*pScreenPriv->pwinFinishScreenInit) (index, pScreen, argc, argv)))
+    {
+      ErrorF ("winScreenInit - winFinishScreenInit () failed\n");
+      return FALSE;
+    }
+
+  if (!g_fSoftwareCursor)
+    winInitCursor(pScreen);
+  else
+    winErrorFVerb(2, "winScreenInit - Using software cursor\n");  
+
+#if CYGDEBUG || YES
+  winDebug ("winScreenInit - returning\n");
+#endif
+
+  return TRUE;
+}
+
+
+/* See Porting Layer Definition - p. 20 */
+Bool
+winFinishScreenInitFB (int index,
+		       ScreenPtr pScreen,
+		       int argc, char **argv)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  VisualPtr		pVisual = NULL;
+  char			*pbits = NULL;
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  int			iReturn;
+#endif
+
+  /* Create framebuffer */
+  if (!(*pScreenPriv->pwinAllocateFB) (pScreen))
+    {
+      ErrorF ("winFinishScreenInitFB - Could not allocate framebuffer\n");
+      return FALSE;
+    }
+
+  /*
+   * Grab the number of bits that are used to represent color in each pixel.
+   */
+  if (pScreenInfo->dwBPP == 8)
+    pScreenInfo->dwDepth = 8;
+  else
+    pScreenInfo->dwDepth = winCountBits (pScreenPriv->dwRedMask)
+      + winCountBits (pScreenPriv->dwGreenMask)
+      + winCountBits (pScreenPriv->dwBlueMask);
+  
+  winErrorFVerb (2, "winFinishScreenInitFB - Masks: %08x %08x %08x\n",
+	  (unsigned int) pScreenPriv->dwRedMask,
+	  (unsigned int) pScreenPriv->dwGreenMask,
+	  (unsigned int) pScreenPriv->dwBlueMask);
+
+  /* Init visuals */
+  if (!(*pScreenPriv->pwinInitVisuals) (pScreen))
+    {
+      ErrorF ("winFinishScreenInitFB - winInitVisuals failed\n");
+      return FALSE;
+    }
+
+  /* Setup a local variable to point to the framebuffer */
+  pbits = pScreenInfo->pfb;
+  
+  /* Apparently we need this for the render extension */
+  miSetPixmapDepths ();
+
+  /* Start fb initialization */
+  if (!fbSetupScreen (pScreen,
+		      pScreenInfo->pfb,
+		      pScreenInfo->dwWidth, pScreenInfo->dwHeight,
+		      monitorResolution, monitorResolution,
+		      pScreenInfo->dwStride,
+		      pScreenInfo->dwBPP))
+    {
+      ErrorF ("winFinishScreenInitFB - fbSetupScreen failed\n");
+      return FALSE;
+    }
+
+  /* Override default colormap routines if visual class is dynamic */
+  if (pScreenInfo->dwDepth == 8
+      && (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_GDI
+	  || (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL
+	      && pScreenInfo->fFullScreen)
+	  || (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
+	      && pScreenInfo->fFullScreen)))
+    {
+      winSetColormapFunctions (pScreen);
+
+      /*
+       * NOTE: Setting whitePixel to 255 causes Magic 7.1 to allocate its
+       * own colormap, as it cannot allocate 7 planes in the default
+       * colormap.  Setting whitePixel to 1 allows Magic to get 7
+       * planes in the default colormap, so it doesn't create its
+       * own colormap.  This latter situation is highly desireable,
+       * as it keeps the Magic window viewable when switching to
+       * other X clients that use the default colormap.
+       */
+      pScreen->blackPixel = 0;
+      pScreen->whitePixel = 1;
+    }
+
+  /* Place our save screen function */
+  pScreen->SaveScreen = winSaveScreen;
+
+  /* Finish fb initialization */
+  if (!fbFinishScreenInit (pScreen,
+			   pScreenInfo->pfb,
+			   pScreenInfo->dwWidth, pScreenInfo->dwHeight,
+			   monitorResolution, monitorResolution,
+			   pScreenInfo->dwStride,
+			   pScreenInfo->dwBPP))
+    {
+      ErrorF ("winFinishScreenInitFB - fbFinishScreenInit failed\n");
+      return FALSE;
+    }
+
+  /* Save a pointer to the root visual */
+  for (pVisual = pScreen->visuals;
+       pVisual->vid != pScreen->rootVisual;
+       pVisual++);
+  pScreenPriv->pRootVisual = pVisual;
+
+  /* 
+   * Setup points to the block and wakeup handlers.  Pass a pointer
+   * to the current screen as pWakeupdata.
+   */
+  pScreen->BlockHandler = winBlockHandler;
+  pScreen->WakeupHandler = winWakeupHandler;
+  pScreen->blockData = pScreen;
+  pScreen->wakeupData = pScreen;
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  /*
+   * Setup acceleration for multi-window external window manager mode.
+   * To be compatible with the Damage extension, this must be done
+   * before calling miDCInitialize, which calls DamageSetup.
+   */
+  if (pScreenInfo->fMWExtWM)
+    {
+      if (!RootlessAccelInit (pScreen))
+        {
+          ErrorF ("winFinishScreenInitFB - RootlessAccelInit () failed\n");
+          return FALSE;
+        }
+    }
+#endif
+
+#ifdef RENDER
+  /* Render extension initialization, calls miPictureInit */
+  if (!fbPictureInit (pScreen, NULL, 0))
+    {
+      ErrorF ("winFinishScreenInitFB - fbPictureInit () failed\n");
+      return FALSE;
+    }
+#endif
+
+#ifdef RANDR
+  /* Initialize resize and rotate support */
+  if (!winRandRInit (pScreen))
+    {
+      ErrorF ("winFinishScreenInitFB - winRandRInit () failed\n");
+      return FALSE;
+    }
+#endif
+
+  /*
+   * Backing store support should reduce network traffic and increase
+   * performance.
+   */
+  miInitializeBackingStore (pScreen);
+
+  /* KDrive does miDCInitialize right after miInitializeBackingStore */
+  /* Setup the cursor routines */
+#if CYGDEBUG
+  winDebug ("winFinishScreenInitFB - Calling miDCInitialize ()\n");
+#endif
+  miDCInitialize (pScreen, &g_winPointerCursorFuncs);
+
+  /* KDrive does winCreateDefColormap right after miDCInitialize */
+  /* Create a default colormap */
+#if CYGDEBUG
+  winDebug ("winFinishScreenInitFB - Calling winCreateDefColormap ()\n");
+#endif
+  if (!winCreateDefColormap (pScreen))
+    {
+      ErrorF ("winFinishScreenInitFB - Could not create colormap\n");
+      return FALSE;
+    }
+
+  /* Initialize the shadow framebuffer layer */
+  if ((pScreenInfo->dwEngine == WIN_SERVER_SHADOW_GDI
+       || pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
+       || pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL)
+#ifdef XWIN_MULTIWINDOWEXTWM
+      && !pScreenInfo->fMWExtWM
+#endif
+      )
+    {
+#if CYGDEBUG
+      winDebug ("winFinishScreenInitFB - Calling shadowInit ()\n");
+#endif
+      if (!shadowInit (pScreen,
+		       pScreenPriv->pwinShadowUpdate,
+		       NULL))
+	{
+	  ErrorF ("winFinishScreenInitFB - shadowInit () failed\n");
+	  return FALSE;
+	}
+    }
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  /* Handle multi-window external window manager mode */
+  if (pScreenInfo->fMWExtWM)
+    {
+      winDebug ("winScreenInit - MultiWindowExtWM - Calling RootlessInit\n");
+      
+      RootlessInit(pScreen, &winMWExtWMProcs);
+      
+      winDebug ("winScreenInit - MultiWindowExtWM - RootlessInit returned\n");
+      
+      rootless_CopyBytes_threshold = 0;
+      rootless_FillBytes_threshold = 0;
+      rootless_CompositePixels_threshold = 0;
+      /* FIXME: How many? Profiling needed? */
+      rootless_CopyWindow_threshold = 1;
+
+      winWindowsWMExtensionInit ();
+    }
+#endif
+
+  /* Handle rootless mode */
+  if (pScreenInfo->fRootless)
+    {
+      /* Define the WRAP macro temporarily for local use */
+#define WRAP(a) \
+    if (pScreen->a) { \
+        pScreenPriv->a = pScreen->a; \
+    } else { \
+        ErrorF("null screen fn " #a "\n"); \
+        pScreenPriv->a = NULL; \
+    }
+
+      /* Save a pointer to each lower-level window procedure */
+      WRAP(CreateWindow);
+      WRAP(DestroyWindow);
+      WRAP(RealizeWindow);
+      WRAP(UnrealizeWindow);
+      WRAP(PositionWindow);
+      WRAP(ChangeWindowAttributes);
+#ifdef SHAPE
+      WRAP(SetShape);
+#endif
+
+      /* Assign rootless window procedures to be top level procedures */
+      pScreen->CreateWindow = winCreateWindowRootless;
+      pScreen->DestroyWindow = winDestroyWindowRootless;
+      pScreen->PositionWindow = winPositionWindowRootless;
+      /*pScreen->ChangeWindowAttributes = winChangeWindowAttributesRootless;*/
+      pScreen->RealizeWindow = winMapWindowRootless;
+      pScreen->UnrealizeWindow = winUnmapWindowRootless;
+#ifdef SHAPE
+      pScreen->SetShape = winSetShapeRootless;
+#endif
+
+      /* Undefine the WRAP macro, as it is not needed elsewhere */
+#undef WRAP
+    }
+
+
+#ifdef XWIN_MULTIWINDOW
+  /* Handle multi window mode */
+  else if (pScreenInfo->fMultiWindow)
+    {
+      /* Define the WRAP macro temporarily for local use */
+#define WRAP(a) \
+    if (pScreen->a) { \
+        pScreenPriv->a = pScreen->a; \
+    } else { \
+        ErrorF("null screen fn " #a "\n"); \
+        pScreenPriv->a = NULL; \
+    }
+
+      /* Save a pointer to each lower-level window procedure */
+      WRAP(CreateWindow);
+      WRAP(DestroyWindow);
+      WRAP(RealizeWindow);
+      WRAP(UnrealizeWindow);
+      WRAP(PositionWindow);
+      WRAP(ChangeWindowAttributes);
+      WRAP(ReparentWindow);
+      WRAP(RestackWindow);
+      WRAP(ResizeWindow);
+      WRAP(MoveWindow);
+      WRAP(CopyWindow);
+#ifdef SHAPE
+      WRAP(SetShape);
+#endif
+
+      /* Assign multi-window window procedures to be top level procedures */
+      pScreen->CreateWindow = winCreateWindowMultiWindow;
+      pScreen->DestroyWindow = winDestroyWindowMultiWindow;
+      pScreen->PositionWindow = winPositionWindowMultiWindow;
+      /*pScreen->ChangeWindowAttributes = winChangeWindowAttributesMultiWindow;*/
+      pScreen->RealizeWindow = winMapWindowMultiWindow;
+      pScreen->UnrealizeWindow = winUnmapWindowMultiWindow;
+      pScreen->ReparentWindow = winReparentWindowMultiWindow;
+      pScreen->RestackWindow = winRestackWindowMultiWindow;
+      pScreen->ResizeWindow = winResizeWindowMultiWindow;
+      pScreen->MoveWindow = winMoveWindowMultiWindow;
+      pScreen->CopyWindow = winCopyWindowMultiWindow;
+#ifdef SHAPE
+      pScreen->SetShape = winSetShapeMultiWindow;
+#endif
+
+      /* Undefine the WRAP macro, as it is not needed elsewhere */
+#undef WRAP
+    }
+#endif
+
+  /* Wrap either fb's or shadow's CloseScreen with our CloseScreen */
+  pScreenPriv->CloseScreen = pScreen->CloseScreen;
+  pScreen->CloseScreen = pScreenPriv->pwinCloseScreen;
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  /* Create a mutex for modules in separate threads to wait for */
+  iReturn = pthread_mutex_init (&pScreenPriv->pmServerStarted, NULL);
+  if (iReturn != 0)
+    {
+      ErrorF ("winFinishScreenInitFB - pthread_mutex_init () failed: %d\n",
+	      iReturn);
+      return FALSE;
+    }
+
+  /* Own the mutex for modules in separate threads */
+  iReturn = pthread_mutex_lock (&pScreenPriv->pmServerStarted);
+  if (iReturn != 0)
+    {
+      ErrorF ("winFinishScreenInitFB - pthread_mutex_lock () failed: %d\n",
+	      iReturn);
+      return FALSE;
+    }
+
+  /* Set the ServerStarted flag to false */
+  pScreenPriv->fServerStarted = FALSE;
+#endif
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+  pScreenPriv->fRestacking = FALSE;
+#endif
+
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+  if (FALSE
+#ifdef XWIN_MULTIWINDOW
+      || pScreenInfo->fMultiWindow
+#endif
+#ifdef XWIN_MULTIWINDOWEXTWM
+      || pScreenInfo->fInternalWM
+#endif
+      )
+    { 
+#if CYGDEBUG || YES
+      winDebug ("winFinishScreenInitFB - Calling winInitWM.\n");
+#endif
+
+      /* Initialize multi window mode */
+      if (!winInitWM (&pScreenPriv->pWMInfo,
+		      &pScreenPriv->ptWMProc,
+		      &pScreenPriv->ptXMsgProc,
+		      &pScreenPriv->pmServerStarted,
+		      pScreenInfo->dwScreen,
+		      (HWND)&pScreenPriv->hwndScreen,
+#ifdef XWIN_MULTIWINDOWEXTWM
+		      pScreenInfo->fInternalWM ||
+#endif
+		      FALSE))
+        {
+          ErrorF ("winFinishScreenInitFB - winInitWM () failed.\n");
+          return FALSE;
+        }
+    }      
+#endif
+
+  /* Tell the server that we are enabled */
+  pScreenPriv->fEnabled = TRUE;
+
+  /* Tell the server that we have a valid depth */
+  pScreenPriv->fBadDepth = FALSE;
+
+#if CYGDEBUG || YES
+  winDebug ("winFinishScreenInitFB - returning\n");
+#endif
+
+  return TRUE;
+}
+
+#ifdef XWIN_NATIVEGDI
+/* See Porting Layer Definition - p. 20 */
+
+Bool
+winFinishScreenInitNativeGDI (int index,
+			      ScreenPtr pScreen,
+			      int argc, char **argv)
+{
+  winScreenPriv(pScreen);
+  winScreenInfoPtr      pScreenInfo = &g_ScreenInfo[index];
+  VisualPtr		pVisuals = NULL;
+  DepthPtr		pDepths = NULL;
+  VisualID		rootVisual = 0;
+  int			nVisuals = 0, nDepths = 0, nRootDepth = 0;
+
+  /* Ignore user input (mouse, keyboard) */
+  pScreenInfo->fIgnoreInput = FALSE;
+
+  /* Get device contexts for the screen and shadow bitmap */
+  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
+  if (pScreenPriv->hdcScreen == NULL)
+    FatalError ("winFinishScreenInitNativeGDI - Couldn't get a DC\n");
+
+  /* Init visuals */
+  if (!(*pScreenPriv->pwinInitVisuals) (pScreen))
+    {
+      ErrorF ("winFinishScreenInitNativeGDI - pwinInitVisuals failed\n");
+      return FALSE;
+    }
+
+  /* Initialize the mi visuals */
+  if (!miInitVisuals (&pVisuals, &pDepths, &nVisuals, &nDepths, &nRootDepth,
+		      &rootVisual,
+		      ((unsigned long)1 << (pScreenInfo->dwDepth - 1)), 8,
+		      TrueColor))
+    {
+      ErrorF ("winFinishScreenInitNativeGDI - miInitVisuals () failed\n");
+      return FALSE;
+    }
+
+  /* Initialize the CloseScreen procedure pointer */
+  pScreen->CloseScreen = NULL;
+
+  /* Initialize the mi code */
+  if (!miScreenInit (pScreen,
+		     NULL, /* No framebuffer */
+		     pScreenInfo->dwWidth, pScreenInfo->dwHeight,
+		     monitorResolution, monitorResolution,
+		     pScreenInfo->dwStride,
+		     nRootDepth, nDepths, pDepths, rootVisual,
+		     nVisuals, pVisuals))
+    {
+      ErrorF ("winFinishScreenInitNativeGDI - miScreenInit failed\n");
+      return FALSE;
+    }
+
+  pScreen->defColormap = FakeClientID(0);
+
+  /*
+   * Register our block and wakeup handlers; these procedures
+   * process messages in our Windows message queue; specifically,
+   * they process mouse and keyboard input.
+   */
+  pScreen->BlockHandler = winBlockHandler;
+  pScreen->WakeupHandler = winWakeupHandler;
+  pScreen->blockData = pScreen;
+  pScreen->wakeupData = pScreen;
+
+  /* Place our save screen function */
+  pScreen->SaveScreen = winSaveScreen;
+
+  /* Pixmaps */
+  pScreen->CreatePixmap = winCreatePixmapNativeGDI;
+  pScreen->DestroyPixmap = winDestroyPixmapNativeGDI;
+
+  /* Other Screen Routines */
+  pScreen->QueryBestSize = winQueryBestSizeNativeGDI;
+  pScreen->SaveScreen = winSaveScreen;  
+  pScreen->GetImage = miGetImage;
+  pScreen->GetSpans = winGetSpansNativeGDI;
+
+  /* Window Procedures */
+  pScreen->CreateWindow = winCreateWindowNativeGDI;
+  pScreen->DestroyWindow = winDestroyWindowNativeGDI;
+  pScreen->PositionWindow = winPositionWindowNativeGDI;
+  /*pScreen->ChangeWindowAttributes = winChangeWindowAttributesNativeGDI;*/
+  pScreen->RealizeWindow = winMapWindowNativeGDI;
+  pScreen->UnrealizeWindow = winUnmapWindowNativeGDI;
+
+  /* Paint window */
+  pScreen->CopyWindow = winCopyWindowNativeGDI;
+
+  /* Fonts */
+  pScreen->RealizeFont = winRealizeFontNativeGDI;
+  pScreen->UnrealizeFont = winUnrealizeFontNativeGDI;
+
+  /* GC */
+  pScreen->CreateGC = winCreateGCNativeGDI;
+
+  /* Colormap Routines */
+  pScreen->CreateColormap = miInitializeColormap;
+  pScreen->DestroyColormap = (DestroyColormapProcPtr) (void (*)(void)) NoopDDA;
+  pScreen->InstallColormap = miInstallColormap;
+  pScreen->UninstallColormap = miUninstallColormap;
+  pScreen->ListInstalledColormaps = miListInstalledColormaps;
+  pScreen->StoreColors = (StoreColorsProcPtr) (void (*)(void)) NoopDDA;
+  pScreen->ResolveColor = miResolveColor;
+
+  /* Bitmap */
+  pScreen->BitmapToRegion = winPixmapToRegionNativeGDI;
+
+  ErrorF ("winFinishScreenInitNativeGDI - calling miDCInitialize\n");
+
+  /* Set the default white and black pixel positions */
+  pScreen->whitePixel = pScreen->blackPixel = (Pixel) 0;
+
+  /* Initialize the cursor */
+  if (!miDCInitialize (pScreen, &g_winPointerCursorFuncs))
+    {
+      ErrorF ("winFinishScreenInitNativeGDI - miDCInitialize failed\n");
+      return FALSE;
+    }
+  
+  /* Create a default colormap */
+  if (!miCreateDefColormap (pScreen))
+    {
+        ErrorF ("winFinishScreenInitNativeGDI - miCreateDefColormap () "
+		"failed\n");
+	return FALSE;
+    }
+
+  ErrorF ("winFinishScreenInitNativeGDI - miCreateDefColormap () "
+	  "returned\n");
+  
+  /* mi doesn't use a CloseScreen procedure, so no need to wrap */
+  pScreen->CloseScreen = pScreenPriv->pwinCloseScreen;
+
+  /* Tell the server that we are enabled */
+  pScreenPriv->fEnabled = TRUE;
+
+  ErrorF ("winFinishScreenInitNativeGDI - Successful addition of "
+	  "screen %08x\n",
+	  (unsigned int) pScreen);
+
+  return TRUE;
+}
+#endif
+
+
+/* See Porting Layer Definition - p. 33 */
+static Bool
+winSaveScreen (ScreenPtr pScreen, int on)
+{
+  return TRUE;
+}
diff --git a/hw/xwin/winsetsp.c b/hw/xwin/winsetsp.c
new file mode 100644
index 0000000..f894d6c
--- /dev/null
+++ b/hw/xwin/winsetsp.c
@@ -0,0 +1,186 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Harold L Hunt II
+ * 		Alan Hourihane <alanh at fairlite.demon.co.uk>
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/* See Porting Layer Definition - p. 55 */
+void
+winSetSpansNativeGDI (DrawablePtr	pDrawable,
+		      GCPtr		pGC,
+		      char		*pSrcs,
+		      DDXPointPtr	pPoints,
+		      int		*piWidths,
+		      int		iSpans,
+		      int		fSorted)
+{
+  winGCPriv(pGC);
+  PixmapPtr		pPixmap = NULL;
+  winPrivPixmapPtr	pPixmapPriv = NULL;
+  HBITMAP		hbmpOrig = NULL;
+  BITMAPINFO		bmi;
+  HRGN			hrgn = NULL, combined = NULL;
+  int			nbox;
+  BoxPtr	 	pbox;
+
+  nbox = REGION_NUM_RECTS (pGC->pCompositeClip);
+  pbox = REGION_RECTS (pGC->pCompositeClip);
+
+  if (!nbox) return;
+
+  combined = CreateRectRgn (pbox->x1, pbox->y1, pbox->x2, pbox->y2);
+  nbox--; pbox++;
+  while (nbox--)
+    {
+      hrgn = CreateRectRgn (pbox->x1, pbox->y1, pbox->x2, pbox->y2);
+      CombineRgn (combined, combined, hrgn, RGN_OR);
+      DeleteObject (hrgn);
+      hrgn = NULL;
+      pbox++;
+    }
+
+  /* Branch on the drawable type */
+  switch (pDrawable->type)
+    {
+    case DRAWABLE_PIXMAP:
+
+      SelectClipRgn (pGCPriv->hdcMem, combined);
+      DeleteObject (combined);
+      combined = NULL;
+
+      pPixmap = (PixmapPtr) pDrawable;
+      pPixmapPriv = winGetPixmapPriv (pPixmap);
+      
+      /* Select the drawable pixmap into a DC */
+      hbmpOrig = SelectObject (pGCPriv->hdcMem, pPixmapPriv->hBitmap);
+      if (hbmpOrig == NULL)
+	FatalError ("winSetSpans - DRAWABLE_PIXMAP - SelectObject () "
+		    "failed on pPixmapPriv->hBitmap\n");
+
+      while (iSpans--)
+        {
+	  ZeroMemory (&bmi, sizeof (BITMAPINFO));
+	  bmi.bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
+	  bmi.bmiHeader.biWidth = *piWidths;
+	  bmi.bmiHeader.biHeight = 1;
+	  bmi.bmiHeader.biPlanes = 1;
+	  bmi.bmiHeader.biBitCount = pDrawable->depth;
+	  bmi.bmiHeader.biCompression = BI_RGB;
+
+  	  /* Setup color table for mono DIBs */
+  	  if (pDrawable->depth == 1)
+    	    {
+      	      bmi.bmiColors[1].rgbBlue = 255;
+      	      bmi.bmiColors[1].rgbGreen = 255;
+      	      bmi.bmiColors[1].rgbRed = 255;
+    	    }
+
+	  StretchDIBits (pGCPriv->hdcMem, 
+			 pPoints->x, pPoints->y,
+			 *piWidths, 1,
+			 0, 0,
+			 *piWidths, 1,
+			 pSrcs,
+			 (BITMAPINFO *) &bmi,
+			 DIB_RGB_COLORS,
+			 g_copyROP[pGC->alu]);
+
+	  pSrcs += PixmapBytePad (*piWidths, pDrawable->depth);
+	  pPoints++;
+	  piWidths++;
+        }
+      
+      /* Reset the clip region */
+      SelectClipRgn (pGCPriv->hdcMem, NULL);
+
+      /* Push the drawable pixmap out of the GC HDC */
+      SelectObject (pGCPriv->hdcMem, hbmpOrig);
+      break;
+
+    case DRAWABLE_WINDOW:
+
+      SelectClipRgn (pGCPriv->hdc, combined);
+      DeleteObject (combined);
+      combined = NULL;
+
+      while (iSpans--)
+        {
+	  ZeroMemory (&bmi, sizeof (BITMAPINFO));
+	  bmi.bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
+	  bmi.bmiHeader.biWidth = *piWidths;
+	  bmi.bmiHeader.biHeight = 1;
+	  bmi.bmiHeader.biPlanes = 1;
+	  bmi.bmiHeader.biBitCount = pDrawable->depth;
+	  bmi.bmiHeader.biCompression = BI_RGB;
+
+  	  /* Setup color table for mono DIBs */
+  	  if (pDrawable->depth == 1)
+    	    {
+      	      bmi.bmiColors[1].rgbBlue = 255;
+      	      bmi.bmiColors[1].rgbGreen = 255;
+      	      bmi.bmiColors[1].rgbRed = 255;
+    	    }
+
+	  StretchDIBits (pGCPriv->hdc, 
+			 pPoints->x, pPoints->y,
+			 *piWidths, 1,
+			 0, 0,
+			 *piWidths, 1,
+			 pSrcs,
+			 (BITMAPINFO *) &bmi,
+			 DIB_RGB_COLORS,
+			 g_copyROP[pGC->alu]);
+
+	  pSrcs += PixmapBytePad (*piWidths, pDrawable->depth);
+	  pPoints++;
+	  piWidths++;
+        }
+
+      /* Reset the clip region */
+      SelectClipRgn (pGCPriv->hdc, NULL);
+      break;
+
+    case UNDRAWABLE_WINDOW:
+      FatalError ("\nwinSetSpansNativeGDI - UNDRAWABLE_WINDOW\n\n");
+      break;
+
+    case DRAWABLE_BUFFER:
+      FatalError ("\nwinSetSpansNativeGDI - DRAWABLE_BUFFER\n\n");
+      break;
+      
+    default:
+      FatalError ("\nwinSetSpansNativeGDI - Unknown drawable type\n\n");
+      break;
+    }
+}
diff --git a/hw/xwin/winshaddd.c b/hw/xwin/winshaddd.c
new file mode 100644
index 0000000..a2c1dc9
--- /dev/null
+++ b/hw/xwin/winshaddd.c
@@ -0,0 +1,1442 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * External symbols
+ */
+
+extern HWND			g_hDlgExit;
+
+
+/*
+ * FIXME: Headers are broken, DEFINE_GUID doesn't work correctly,
+ * so we have to redefine it here.
+ */
+#ifdef DEFINE_GUID
+#undef DEFINE_GUID
+#define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
+#endif /* DEFINE_GUID */
+
+
+/*
+ * FIXME: Headers are broken, IID_IDirectDraw4 has to be defined
+ * here manually.  Should be handled by ddraw.h
+ */
+#ifndef IID_IDirectDraw2
+DEFINE_GUID( IID_IDirectDraw2,0xB3A6F3E0,0x2B43,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xB9,0x33,0x56 );
+#endif /* IID_IDirectDraw2 */
+
+
+/*
+ * Local prototypes
+ */
+
+static Bool
+winAllocateFBShadowDD (ScreenPtr pScreen);
+
+static void
+winShadowUpdateDD (ScreenPtr pScreen, 
+		   shadowBufPtr pBuf);
+
+static Bool
+winCloseScreenShadowDD (int nIndex, ScreenPtr pScreen);
+
+static Bool
+winInitVisualsShadowDD (ScreenPtr pScreen);
+
+static Bool
+winAdjustVideoModeShadowDD (ScreenPtr pScreen);
+
+static Bool
+winBltExposedRegionsShadowDD (ScreenPtr pScreen);
+
+static Bool
+winActivateAppShadowDD (ScreenPtr pScreen);
+
+static Bool
+winRedrawScreenShadowDD (ScreenPtr pScreen);
+
+static Bool
+winRealizeInstalledPaletteShadowDD (ScreenPtr pScreen);
+
+static Bool
+winInstallColormapShadowDD (ColormapPtr pColormap);
+
+static Bool
+winStoreColorsShadowDD (ColormapPtr pmap, 
+			int ndef,
+			xColorItem *pdefs);
+
+static Bool
+winCreateColormapShadowDD (ColormapPtr pColormap);
+
+static Bool
+winDestroyColormapShadowDD (ColormapPtr pColormap);
+
+static Bool
+winCreatePrimarySurfaceShadowDD (ScreenPtr pScreen);
+
+static Bool
+winReleasePrimarySurfaceShadowDD (ScreenPtr pScreen);
+
+
+/*
+ * Create the primary surface and attach the clipper.
+ * Used for both the initial surface creation and during
+ * WM_DISPLAYCHANGE messages.
+ */
+
+static Bool
+winCreatePrimarySurfaceShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  HRESULT		ddrval = DD_OK;
+  DDSURFACEDESC		ddsd;
+
+  /* Describe the primary surface */
+  ZeroMemory (&ddsd, sizeof (ddsd));
+  ddsd.dwSize = sizeof (ddsd);
+  ddsd.dwFlags = DDSD_CAPS;
+  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
+  
+  /* Create the primary surface */
+  ddrval = IDirectDraw2_CreateSurface (pScreenPriv->pdd2,
+				       &ddsd,
+				       &pScreenPriv->pddsPrimary,
+				       NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winCreatePrimarySurfaceShadowDD - Could not create primary "
+	      "surface: %08x\n", (unsigned int) ddrval);
+      return FALSE;
+    }
+  
+#if CYGDEBUG
+  winDebug ("winCreatePrimarySurfaceShadowDD - Created primary surface\n");
+#endif
+
+  /*
+   * Attach a clipper to the primary surface that will clip our blits to our
+   * display window.
+   */
+  ddrval = IDirectDrawSurface2_SetClipper (pScreenPriv->pddsPrimary,
+					   pScreenPriv->pddcPrimary);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winCreatePrimarySurfaceShadowDD - Primary attach clipper "
+	      "failed: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winCreatePrimarySurfaceShadowDD - Attached clipper to "
+	  "primary surface\n");
+#endif
+
+  /* Everything was correct */
+  return TRUE;
+}
+
+
+/*
+ * Detach the clipper and release the primary surface.
+ * Called from WM_DISPLAYCHANGE.
+ */
+
+static Bool
+winReleasePrimarySurfaceShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+
+  ErrorF ("winReleasePrimarySurfaceShadowDD - Hello\n");
+
+  /* Release the primary surface and clipper, if they exist */
+  if (pScreenPriv->pddsPrimary)
+    {
+      /*
+       * Detach the clipper from the primary surface.
+       * NOTE: We do this explicity for clarity.  The Clipper is not released.
+       */
+      IDirectDrawSurface2_SetClipper (pScreenPriv->pddsPrimary,
+				      NULL);
+
+      ErrorF ("winReleasePrimarySurfaceShadowDD - Detached clipper\n");
+
+      /* Release the primary surface */
+      IDirectDrawSurface2_Release (pScreenPriv->pddsPrimary);
+      pScreenPriv->pddsPrimary = NULL;
+    }
+
+  ErrorF ("winReleasePrimarySurfaceShadowDD - Released primary surface\n");
+
+  return TRUE;
+}
+
+
+/*
+ * Create a DirectDraw surface for the shadow framebuffer; also create
+ * a primary surface object so we can blit to the display.
+ * 
+ * Install a DirectDraw clipper on our primary surface object
+ * that clips our blits to the unobscured client area of our display window.
+ */
+
+static Bool
+winAllocateFBShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;  
+  HRESULT		ddrval = DD_OK;
+  DDSURFACEDESC		ddsd;
+  DDSURFACEDESC		*pddsdShadow = NULL;
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD\n");
+#endif
+
+  /* Create a clipper */
+  ddrval = (*g_fpDirectDrawCreateClipper) (0,
+					   &pScreenPriv->pddcPrimary,
+					   NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDD - Could not create clipper: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD - Created a clipper\n");
+#endif
+
+  /* Get a device context for the screen  */
+  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
+
+  /* Attach the clipper to our display window */
+  ddrval = IDirectDrawClipper_SetHWnd (pScreenPriv->pddcPrimary,
+				       0,
+				       pScreenPriv->hwndScreen);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDD - Clipper not attached to "
+	      "window: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD - Attached clipper to window\n");
+#endif
+
+  /* Create a DirectDraw object, store the address at lpdd */
+  ddrval = (*g_fpDirectDrawCreate) (NULL, &pScreenPriv->pdd, NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDD - Could not start DirectDraw: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD () - Created and initialized DD\n");
+#endif
+
+  /* Get a DirectDraw2 interface pointer */
+  ddrval = IDirectDraw_QueryInterface (pScreenPriv->pdd,
+				       &IID_IDirectDraw2,
+				       (LPVOID*) &pScreenPriv->pdd2);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDD - Failed DD2 query: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+  /* Are we full screen? */
+  if (pScreenInfo->fFullScreen)
+    {
+      DDSURFACEDESC	ddsdCurrent;
+      DWORD		dwRefreshRateCurrent = 0;
+      HDC		hdc = NULL;
+
+      /* Set the cooperative level to full screen */
+      ddrval = IDirectDraw2_SetCooperativeLevel (pScreenPriv->pdd2,
+						 pScreenPriv->hwndScreen,
+						 DDSCL_EXCLUSIVE
+						 | DDSCL_FULLSCREEN);
+      if (FAILED (ddrval))
+	{
+	  ErrorF ("winAllocateFBShadowDD - Could not set "
+		  "cooperative level: %08x\n",
+		  (unsigned int) ddrval);
+	  return FALSE;
+	}
+
+      /*
+       * We only need to get the current refresh rate for comparison
+       * if a refresh rate has been passed on the command line.
+       */
+      if (pScreenInfo->dwRefreshRate != 0)
+	{
+	  ZeroMemory (&ddsdCurrent, sizeof (ddsdCurrent));
+	  ddsdCurrent.dwSize = sizeof (ddsdCurrent);
+	  
+	  /* Get information about current display settings */
+	  ddrval = IDirectDraw2_GetDisplayMode (pScreenPriv->pdd2,
+						&ddsdCurrent);
+	  if (FAILED (ddrval))
+	    {
+	      ErrorF ("winAllocateFBShadowDD - Could not get current "
+		      "refresh rate: %08x.  Continuing.\n",
+		      (unsigned int) ddrval);
+	      dwRefreshRateCurrent = 0;
+	    }
+	  else
+	    {
+	      /* Grab the current refresh rate */
+	      dwRefreshRateCurrent = ddsdCurrent.u2.dwRefreshRate;
+	    }
+	}
+
+      /* Clean up the refresh rate */
+      if (dwRefreshRateCurrent == pScreenInfo->dwRefreshRate)
+	{
+	  /*
+	   * Refresh rate is non-specified or equal to current.
+	   */
+	  pScreenInfo->dwRefreshRate = 0;
+	}
+
+      /* Grab a device context for the screen */
+      hdc = GetDC (NULL);
+      if (hdc == NULL)
+	{
+	  ErrorF ("winAllocateFBShadowDD - GetDC () failed\n");
+	  return FALSE;
+	}
+
+      /* Only change the video mode when different than current mode */
+      if (!pScreenInfo->fMultipleMonitors
+	  && (pScreenInfo->dwWidth != GetSystemMetrics (SM_CXSCREEN)
+	      || pScreenInfo->dwHeight != GetSystemMetrics (SM_CYSCREEN)
+	      || pScreenInfo->dwBPP != GetDeviceCaps (hdc, BITSPIXEL)
+	      || pScreenInfo->dwRefreshRate != 0))
+	{
+	  ErrorF ("winAllocateFBShadowDD - Changing video mode\n");
+
+	  /* Change the video mode to the mode requested */
+	  ddrval = IDirectDraw2_SetDisplayMode (pScreenPriv->pdd2,
+						pScreenInfo->dwWidth,
+						pScreenInfo->dwHeight,
+						pScreenInfo->dwBPP,
+						pScreenInfo->dwRefreshRate,
+						0);
+	  if (FAILED (ddrval))
+	    {
+	      ErrorF ("winAllocateFBShadowDD - Could not set "\
+		      "full screen display mode: %08x\n",
+		      (unsigned int) ddrval);
+	      return FALSE;
+	    }
+	}
+      else
+	{
+	  ErrorF ("winAllocateFBShadowDD - Not changing video mode\n");
+	}
+
+      /* Release our DC */
+      ReleaseDC (NULL, hdc);
+      hdc = NULL;
+    }
+  else
+    {
+      /* Set the cooperative level for windowed mode */
+      ddrval = IDirectDraw2_SetCooperativeLevel (pScreenPriv->pdd2,
+						 pScreenPriv->hwndScreen,
+						 DDSCL_NORMAL);
+      if (FAILED (ddrval))
+	{
+	  ErrorF ("winAllocateFBShadowDD - Could not set "\
+		  "cooperative level: %08x\n",
+		  (unsigned int) ddrval);
+	  return FALSE;
+	}
+    }
+
+  /* Create the primary surface */
+  if (!winCreatePrimarySurfaceShadowDD (pScreen))
+    {
+      ErrorF ("winAllocateFBShadowDD - winCreatePrimarySurfaceShadowDD "
+	      "failed\n");
+      return FALSE;
+    }
+
+  /* Describe the shadow surface to be created */
+  /* NOTE: Do not use a DDSCAPS_VIDEOMEMORY surface,
+   * as drawing, locking, and unlocking take forever
+   * with video memory surfaces.  In addition,
+   * video memory is a somewhat scarce resource,
+   * so you shouldn't be allocating video memory when
+   * you have the option of using system memory instead.
+   */
+  ZeroMemory (&ddsd, sizeof (ddsd));
+  ddsd.dwSize = sizeof (ddsd);
+  ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
+  ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
+  ddsd.dwHeight = pScreenInfo->dwHeight;
+  ddsd.dwWidth = pScreenInfo->dwWidth;
+
+  /* Create the shadow surface */
+  ddrval = IDirectDraw2_CreateSurface (pScreenPriv->pdd2,
+				       &ddsd,
+				       &pScreenPriv->pddsShadow,
+				       NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDD - Could not create shadow "\
+	      "surface: %08x\n", (unsigned int) ddrval);
+      return FALSE;
+    }
+  
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD - Created shadow\n");
+#endif
+
+  /* Allocate a DD surface description for our screen privates */
+  pddsdShadow = pScreenPriv->pddsdShadow = malloc (sizeof (DDSURFACEDESC));
+  if (pddsdShadow == NULL)
+    {
+      ErrorF ("winAllocateFBShadowDD - Could not allocate surface "\
+	      "description memory\n");
+      return FALSE;
+    }
+  ZeroMemory (pddsdShadow, sizeof (*pddsdShadow));
+  pddsdShadow->dwSize = sizeof (*pddsdShadow);
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD - Locking shadow\n");
+#endif
+
+  /* Lock the shadow surface */
+  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
+				     NULL,
+				     pddsdShadow,
+				     DDLOCK_WAIT,
+				     NULL);
+  if (FAILED (ddrval) || pddsdShadow->lpSurface == NULL)
+    {
+      ErrorF ("winAllocateFBShadowDD - Could not lock shadow "\
+	      "surface: %08x\n", (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD - Locked shadow\n");
+#endif
+
+  /* We don't know how to deal with anything other than RGB */
+  if (!(pddsdShadow->ddpfPixelFormat.dwFlags & DDPF_RGB))
+    {
+      ErrorF ("winAllocateFBShadowDD - Color format other than RGB\n");
+      return FALSE;
+    }
+
+  /* Grab the pitch from the surface desc */
+  pScreenInfo->dwStride = (pddsdShadow->u1.lPitch * 8)
+    / pScreenInfo->dwBPP;
+
+  /* Save the pointer to our surface memory */
+  pScreenInfo->pfb = pddsdShadow->lpSurface;
+  
+  /* Grab the color depth and masks from the surface description */
+  pScreenPriv->dwRedMask = pddsdShadow->ddpfPixelFormat.u2.dwRBitMask;
+  pScreenPriv->dwGreenMask = pddsdShadow->ddpfPixelFormat.u3.dwGBitMask;
+  pScreenPriv->dwBlueMask = pddsdShadow->ddpfPixelFormat.u4.dwBBitMask;
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDD - Returning\n");
+#endif
+
+  return TRUE;
+}
+
+
+/*
+ * Transfer the damaged regions of the shadow framebuffer to the display.
+ */
+
+static void
+winShadowUpdateDD (ScreenPtr pScreen, 
+		   shadowBufPtr pBuf)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  RegionPtr		damage = &pBuf->damage;
+  HRESULT		ddrval = DD_OK;
+  RECT			rcDest, rcSrc;
+  POINT			ptOrigin;
+  DWORD			dwBox = REGION_NUM_RECTS (damage);
+  BoxPtr		pBox = REGION_RECTS (damage);
+  HRGN			hrgnTemp = NULL, hrgnCombined = NULL;
+
+  /*
+   * Return immediately if the app is not active
+   * and we are fullscreen, or if we have a bad display depth
+   */
+  if ((!pScreenPriv->fActive && pScreenInfo->fFullScreen)
+      || pScreenPriv->fBadDepth) return;
+
+  /* Get the origin of the window in the screen coords */
+  ptOrigin.x = pScreenInfo->dwXOffset;
+  ptOrigin.y = pScreenInfo->dwYOffset;
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&ptOrigin, 1);
+
+  /* Unlock the shadow surface, so we can blit */
+  ddrval = IDirectDrawSurface2_Unlock (pScreenPriv->pddsShadow, NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winShadowUpdateProcDD - Unlock failed\n");
+      return;
+    }
+
+  /*
+   * Handle small regions with multiple blits,
+   * handle large regions by creating a clipping region and 
+   * doing a single blit constrained to that clipping region.
+   */
+  if (pScreenInfo->dwClipUpdatesNBoxes == 0
+      || dwBox < pScreenInfo->dwClipUpdatesNBoxes)
+    {
+      /* Loop through all boxes in the damaged region */
+      while (dwBox--)
+	{
+	  /* Assign damage box to source rectangle */
+	  rcSrc.left = pBox->x1;
+	  rcSrc.top = pBox->y1;
+	  rcSrc.right = pBox->x2;
+	  rcSrc.bottom = pBox->y2;
+	  
+	  /* Calculate destination rectange */
+	  rcDest.left = ptOrigin.x + rcSrc.left;
+	  rcDest.top = ptOrigin.y + rcSrc.top;
+	  rcDest.right = ptOrigin.x + rcSrc.right;
+	  rcDest.bottom = ptOrigin.y + rcSrc.bottom;
+	  
+	  /* Blit the damaged areas */
+	  ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
+					    &rcDest,
+					    pScreenPriv->pddsShadow,
+					    &rcSrc,
+					    DDBLT_WAIT,
+					    NULL);
+	  
+	  /* Get a pointer to the next box */
+	  ++pBox;
+	}
+    }
+  else
+    {
+      BoxPtr		pBoxExtents = REGION_EXTENTS (pScreen, damage);
+
+      /* Compute a GDI region from the damaged region */
+      hrgnCombined = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
+      dwBox--;
+      pBox++;
+      while (dwBox--)
+	{
+	  hrgnTemp = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
+	  CombineRgn (hrgnCombined, hrgnCombined, hrgnTemp, RGN_OR);
+	  DeleteObject (hrgnTemp);
+	  pBox++;
+	}  
+
+      /* Install the GDI region as a clipping region */
+      SelectClipRgn (pScreenPriv->hdcScreen, hrgnCombined);
+      DeleteObject (hrgnCombined);
+      hrgnCombined = NULL;
+
+      /* Calculating a bounding box for the source is easy */
+      rcSrc.left = pBoxExtents->x1;
+      rcSrc.top = pBoxExtents->y1;
+      rcSrc.right = pBoxExtents->x2;
+      rcSrc.bottom = pBoxExtents->y2;
+
+      /* Calculating a bounding box for the destination is trickier */
+      rcDest.left = ptOrigin.x + rcSrc.left;
+      rcDest.top = ptOrigin.y + rcSrc.top;
+      rcDest.right = ptOrigin.x + rcSrc.right;
+      rcDest.bottom = ptOrigin.y + rcSrc.bottom;
+      
+      /* Our Blt should be clipped to the invalidated region */
+      ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
+					&rcDest,
+					pScreenPriv->pddsShadow,
+					&rcSrc,
+					DDBLT_WAIT,
+					NULL);
+
+      /* Reset the clip region */
+      SelectClipRgn (pScreenPriv->hdcScreen, NULL);
+    }
+
+  /* Relock the shadow surface */
+  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
+				     NULL,
+				     pScreenPriv->pddsdShadow,
+				     DDLOCK_WAIT,
+				     NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winShadowUpdateProcDD - Lock failed\n");
+      return;
+    }
+
+  /* Has our memory pointer changed? */
+  if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface)
+    {
+      ErrorF ("winShadowUpdateProcDD - Memory location of the shadow "
+	      "surface has changed, trying to update the root window "
+	      "pixmap header to point to the new address.  If you get "
+	      "this message and "PROJECT_NAME" freezes or crashes "
+	      "after this message then send a problem report and your "
+	      "/tmp/XWin.log file to cygwin-xfree at cygwin.com\n");
+
+      /* Location of shadow framebuffer has changed */
+      pScreenInfo->pfb = pScreenPriv->pddsdShadow->lpSurface;
+      
+      /* Update the screen pixmap */
+      if (!(*pScreen->ModifyPixmapHeader)(pScreen->devPrivate,
+					  pScreen->width,
+					  pScreen->height,
+					  pScreen->rootDepth,
+					  BitsPerPixel (pScreen->rootDepth),
+					  PixmapBytePad (pScreenInfo->dwStride,
+							 pScreenInfo->dwBPP),
+					  pScreenInfo->pfb))
+	{
+	  ErrorF ("winShadowUpdateProcDD - Bits changed, could not "
+		  "notify fb.\n");
+	  return;
+	}
+    }
+}
+
+
+/*
+ * Call the wrapped CloseScreen function.
+ * 
+ * Free our resources and private structures.
+ */
+
+static Bool
+winCloseScreenShadowDD (int nIndex, ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  Bool			fReturn;
+  
+#if CYGDEBUG
+  winDebug ("winCloseScreenShadowDD - Freeing screen resources\n");
+#endif
+
+  /* Flag that the screen is closed */
+  pScreenPriv->fClosed = TRUE;
+  pScreenPriv->fActive = FALSE;
+
+  /* Call the wrapped CloseScreen procedure */
+  WIN_UNWRAP(CloseScreen);
+  fReturn = (*pScreen->CloseScreen) (nIndex, pScreen);
+
+  /* Free the screen DC */
+  ReleaseDC (pScreenPriv->hwndScreen, pScreenPriv->hdcScreen);
+
+  /* Delete the window property */
+  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
+
+  /* Free the shadow surface, if there is one */
+  if (pScreenPriv->pddsShadow)
+    {
+      IDirectDrawSurface2_Unlock (pScreenPriv->pddsShadow, NULL);
+      IDirectDrawSurface2_Release (pScreenPriv->pddsShadow);
+      pScreenPriv->pddsShadow = NULL;
+    }
+
+  /* Detach the clipper from the primary surface and release the clipper. */
+  if (pScreenPriv->pddcPrimary)
+    {
+      /* Detach the clipper */
+      IDirectDrawSurface2_SetClipper (pScreenPriv->pddsPrimary,
+				      NULL);
+
+      /* Release the clipper object */
+      IDirectDrawClipper_Release (pScreenPriv->pddcPrimary);
+      pScreenPriv->pddcPrimary = NULL;
+    }
+
+  /* Release the primary surface, if there is one */
+  if (pScreenPriv->pddsPrimary)
+    {
+      IDirectDrawSurface2_Release (pScreenPriv->pddsPrimary);
+      pScreenPriv->pddsPrimary = NULL;
+    }
+
+  /* Free the DirectDraw2 object, if there is one */
+  if (pScreenPriv->pdd2)
+    {
+      IDirectDraw2_RestoreDisplayMode (pScreenPriv->pdd2);
+      IDirectDraw2_Release (pScreenPriv->pdd2);
+      pScreenPriv->pdd2 = NULL;
+    }
+
+  /* Free the DirectDraw object, if there is one */
+  if (pScreenPriv->pdd)
+    {
+      IDirectDraw_Release (pScreenPriv->pdd);
+      pScreenPriv->pdd = NULL;
+    }
+
+  /* Delete tray icon, if we have one */
+  if (!pScreenInfo->fNoTrayIcon)
+    winDeleteNotifyIcon (pScreenPriv);
+  
+  /* Free the exit confirmation dialog box, if it exists */
+  if (g_hDlgExit != NULL)
+    {
+      DestroyWindow (g_hDlgExit);
+      g_hDlgExit = NULL;
+    }
+
+  /* Kill our window */
+  if (pScreenPriv->hwndScreen)
+    {
+      DestroyWindow (pScreenPriv->hwndScreen);
+      pScreenPriv->hwndScreen = NULL;
+    }
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  /* Destroy the thread startup mutex */
+  pthread_mutex_destroy (&pScreenPriv->pmServerStarted);
+#endif
+
+  /* Kill our screeninfo's pointer to the screen */
+  pScreenInfo->pScreen = NULL;
+
+  /* Invalidate the ScreenInfo's fb pointer */
+  pScreenInfo->pfb = NULL;
+
+  /* Free the screen privates for this screen */
+  free ((pointer) pScreenPriv);
+
+  return fReturn;
+}
+
+
+/*
+ * Tell mi what sort of visuals we need.
+ * 
+ * Generally we only need one visual, as our screen can only
+ * handle one format at a time, I believe.  You may want
+ * to verify that last sentence.
+ */
+
+static Bool
+winInitVisualsShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  DWORD			dwRedBits, dwGreenBits, dwBlueBits;
+
+  /* Count the number of ones in each color mask */
+  dwRedBits = winCountBits (pScreenPriv->dwRedMask);
+  dwGreenBits = winCountBits (pScreenPriv->dwGreenMask);
+  dwBlueBits = winCountBits (pScreenPriv->dwBlueMask);
+  
+  /* Store the maximum number of ones in a color mask as the bitsPerRGB */
+  if (dwRedBits == 0 || dwGreenBits == 0 || dwBlueBits == 0)
+    pScreenPriv->dwBitsPerRGB = 8;
+  else if (dwRedBits > dwGreenBits && dwRedBits > dwBlueBits)
+    pScreenPriv->dwBitsPerRGB = dwRedBits;
+  else if (dwGreenBits > dwRedBits && dwGreenBits > dwBlueBits)
+    pScreenPriv->dwBitsPerRGB = dwGreenBits;
+  else
+    pScreenPriv->dwBitsPerRGB = dwBlueBits;
+  
+  ErrorF ("winInitVisualsShadowDD - Masks %08x %08x %08x BPRGB %d d %d "
+	  "bpp %d\n",
+	  (unsigned int) pScreenPriv->dwRedMask,
+	  (unsigned int) pScreenPriv->dwGreenMask,
+	  (unsigned int) pScreenPriv->dwBlueMask,
+	  (int) pScreenPriv->dwBitsPerRGB,
+	  (int) pScreenInfo->dwDepth,
+	  (int) pScreenInfo->dwBPP);
+
+  /* Create a single visual according to the Windows screen depth */
+  switch (pScreenInfo->dwDepth)
+    {
+    case 24:
+    case 16:
+    case 15:
+#if defined(XFree86Server)
+      /* Create the real visual */
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     TrueColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     TrueColor,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDD - miSetVisualTypesAndMasks "
+		  "failed for TrueColor\n");
+	  return FALSE;
+	}
+
+#ifdef XWIN_EMULATEPSEUDO
+      if (!pScreenInfo->fEmulatePseudo)
+	break;
+
+      /* Setup a pseudocolor visual */
+      if (!miSetVisualTypesAndMasks (8,
+				     PseudoColorMask,
+				     8,
+				     -1,
+				     0,
+				     0,
+				     0))
+	{
+	  ErrorF ("winInitVisualsShadowDD - miSetVisualTypesAndMasks "
+		  "failed for PseudoColor\n");
+	  return FALSE;
+	}
+#endif
+#else /* XFree86Server */
+      /* Create the real visual */
+      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     TrueColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDD - fbSetVisualTypesAndMasks "
+		  "failed for TrueColor\n");
+	  return FALSE;
+	}
+
+#ifdef XWIN_EMULATEPSEUDO
+      if (!pScreenInfo->fEmulatePseudo)
+	break;
+
+      /* Setup a pseudocolor visual */
+      if (!fbSetVisualTypesAndMasks (8,
+				     PseudoColorMask,
+				     8,
+				     0,
+				     0,
+				     0))
+	{
+	  ErrorF ("winInitVisualsShadowDD - fbSetVisualTypesAndMasks "
+		  "failed for PseudoColor\n");
+	  return FALSE;
+	}
+#endif
+#endif /* XFree86Server */
+      break;
+
+    case 8:
+#if defined(XFree86Server)
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     pScreenInfo->fFullScreen 
+				     ? PseudoColorMask : StaticColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenInfo->fFullScreen 
+				     ? PseudoColor : StaticColor,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDD - miSetVisualTypesAndMasks "
+		  "failed\n");
+	  return FALSE;
+	}
+#else /* XFree86Server */
+      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     pScreenInfo->fFullScreen 
+				     ? PseudoColorMask : StaticColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDD - fbSetVisualTypesAndMasks "
+		  "failed\n");
+	  return FALSE;
+	}
+#endif /* XFree86Server */
+      break;
+
+    default:
+      ErrorF ("winInitVisualsShadowDD - Unknown screen depth\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winInitVisualsShadowDD - Returning\n");
+#endif
+
+  return TRUE;
+}
+
+
+/*
+ * Adjust the user proposed video mode
+ */
+
+static Bool
+winAdjustVideoModeShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  HDC			hdc = NULL;
+  DWORD			dwBPP;
+
+  /* We're in serious trouble if we can't get a DC */
+  hdc = GetDC (NULL);
+  if (hdc == NULL)
+    {
+      ErrorF ("winAdjustVideoModeShadowDD - GetDC () failed\n");
+      return FALSE;
+    }
+
+  /* Query GDI for current display depth */
+  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
+
+  /* DirectDraw can only change the depth in fullscreen mode */
+  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
+    {
+      /* No -depth parameter passed, let the user know the depth being used */
+      ErrorF ("winAdjustVideoModeShadowDD - Using Windows display "
+	      "depth of %d bits per pixel\n", (int) dwBPP);
+
+      /* Use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+  else if (pScreenInfo->fFullScreen
+	   && pScreenInfo->dwBPP != dwBPP)
+    {
+      /* FullScreen, and GDI depth differs from -depth parameter */
+      ErrorF ("winAdjustVideoModeShadowDD - FullScreen, using command line "
+	      "bpp: %d\n", (int) pScreenInfo->dwBPP);
+    }
+  else if (dwBPP != pScreenInfo->dwBPP)
+    {
+      /* Windowed, and GDI depth differs from -depth parameter */
+      ErrorF ("winAdjustVideoModeShadowDD - Windowed, command line bpp: "
+	      "%d, using bpp: %d\n", (int) pScreenInfo->dwBPP, (int) dwBPP);
+
+      /* We'll use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+  
+  /* See if the shadow bitmap will be larger than the DIB size limit */
+  if (pScreenInfo->dwWidth * pScreenInfo->dwHeight * pScreenInfo->dwBPP
+      >= WIN_DIB_MAXIMUM_SIZE)
+    {
+      ErrorF ("winAdjustVideoModeShadowDD - Requested DirectDraw surface "
+	      "will be larger than %d MB.  The surface may fail to be "
+	      "allocated on Windows 95, 98, or Me, due to a %d MB limit in "
+	      "DIB size.  This limit does not apply to Windows NT/2000, and "
+	      "this message may be ignored on those platforms.\n",
+	      WIN_DIB_MAXIMUM_SIZE_MB, WIN_DIB_MAXIMUM_SIZE_MB);
+    }
+
+  /* Release our DC */
+  ReleaseDC (NULL, hdc);
+  return TRUE;
+}
+
+
+/*
+ * Blt exposed regions to the screen
+ */
+
+static Bool
+winBltExposedRegionsShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  RECT			rcSrc, rcDest;
+  POINT			ptOrigin;
+  HDC			hdcUpdate = NULL;
+  PAINTSTRUCT		ps;
+  HRESULT		ddrval = DD_OK;
+  Bool			fReturn = TRUE;
+  Bool			fLocked = TRUE;
+  int			i;
+
+  /* BeginPaint gives us an hdc that clips to the invalidated region */
+  hdcUpdate = BeginPaint (pScreenPriv->hwndScreen, &ps);
+  if (hdcUpdate == NULL)
+    {
+      ErrorF ("winBltExposedRegionsShadowDD - BeginPaint () returned "
+	      "a NULL device context handle.  Aborting blit attempt.\n");
+      return FALSE;
+    }
+  
+  /* Unlock the shadow surface, so we can blit */
+  ddrval = IDirectDrawSurface2_Unlock (pScreenPriv->pddsShadow, NULL);
+  if (FAILED (ddrval))
+    {
+      fReturn = FALSE;
+      goto winBltExposedRegionsShadowDD_Exit;
+    }
+  else
+    {
+      /* Flag that we have unlocked the shadow surface */
+      fLocked = FALSE;
+    }
+
+  /* Get the origin of the window in the screen coords */
+  ptOrigin.x = pScreenInfo->dwXOffset;
+  ptOrigin.y = pScreenInfo->dwYOffset;
+
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&ptOrigin, 1);
+  rcDest.left = ptOrigin.x;
+  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
+  rcDest.top = ptOrigin.y;
+  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
+
+  /* Source can be enter shadow surface, as Blt should clip */
+  rcSrc.left = 0;
+  rcSrc.top = 0;
+  rcSrc.right = pScreenInfo->dwWidth;
+  rcSrc.bottom = pScreenInfo->dwHeight;
+
+  /* Try to regain the primary surface and blit again if we've lost it */
+  for (i = 0; i <= WIN_REGAIN_SURFACE_RETRIES; ++i)
+    {
+      /* Our Blt should be clipped to the invalidated region */
+      ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
+					&rcDest,
+					pScreenPriv->pddsShadow,
+					&rcSrc,
+					DDBLT_WAIT,
+					NULL);
+      if (ddrval == DDERR_SURFACELOST)
+	{
+	  /* Surface was lost */
+	  ErrorF ("winBltExposedRegionsShadowDD - IDirectDrawSurface2_Blt "
+		  "reported that the primary surface was lost, "
+		  "trying to restore, retry: %d\n", i + 1);
+
+	  /* Try to restore the surface, once */
+	  ddrval = IDirectDrawSurface2_Restore (pScreenPriv->pddsPrimary);
+	  ErrorF ("winBltExposedRegionsShadowDD - "
+		  "IDirectDrawSurface2_Restore returned: ");
+	  if (ddrval == DD_OK)
+	    ErrorF ("DD_OK\n");
+	  else if (ddrval == DDERR_WRONGMODE)
+	    ErrorF ("DDERR_WRONGMODE\n");
+	  else if (ddrval == DDERR_INCOMPATIBLEPRIMARY)
+	    ErrorF ("DDERR_INCOMPATIBLEPRIMARY\n");
+	  else if (ddrval == DDERR_UNSUPPORTED)
+	    ErrorF ("DDERR_UNSUPPORTED\n");
+	  else if (ddrval == DDERR_INVALIDPARAMS)
+	    ErrorF ("DDERR_INVALIDPARAMS\n");
+	  else if (ddrval == DDERR_INVALIDOBJECT)
+	    ErrorF ("DDERR_INVALIDOBJECT\n");
+	  else
+	    ErrorF ("unknown error: %08x\n", (unsigned int) ddrval);
+
+	  /* Loop around to try the blit one more time */
+	  continue;
+	}
+      else if (FAILED (ddrval))
+	{
+	  fReturn = FALSE;
+	  ErrorF ("winBltExposedRegionsShadowDD - IDirectDrawSurface2_Blt "
+		  "failed, but surface not lost: %08x %d\n",
+		  (unsigned int) ddrval, (int) ddrval);
+	  goto winBltExposedRegionsShadowDD_Exit;
+	}
+      else
+	{
+	  /* Success, stop looping */
+	  break;
+	}
+    }
+
+  /* Relock the shadow surface */
+  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
+				     NULL,
+				     pScreenPriv->pddsdShadow,
+				     DDLOCK_WAIT,
+				     NULL);
+  if (FAILED (ddrval))
+    {
+      fReturn = FALSE;
+      ErrorF ("winBltExposedRegionsShadowDD - IDirectDrawSurface2_Lock "
+	      "failed\n");
+      goto winBltExposedRegionsShadowDD_Exit;
+    }
+  else
+    {
+      /* Indicate that we have relocked the shadow surface */
+      fLocked = TRUE;
+    }
+
+  /* Has our memory pointer changed? */
+  if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface)
+    winUpdateFBPointer (pScreen,
+			pScreenPriv->pddsdShadow->lpSurface);
+
+ winBltExposedRegionsShadowDD_Exit:
+  /* EndPaint frees the DC */
+  if (hdcUpdate != NULL)
+    EndPaint (pScreenPriv->hwndScreen, &ps);
+
+  /*
+   * Relock the surface if it is not locked.  We don't care if locking fails,
+   * as it will cause the server to shutdown within a few more operations.
+   */
+  if (!fLocked)
+    {
+      IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
+				NULL,
+				pScreenPriv->pddsdShadow,
+				DDLOCK_WAIT,
+				NULL);
+
+      /* Has our memory pointer changed? */
+      if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface)
+	winUpdateFBPointer (pScreen,
+			    pScreenPriv->pddsdShadow->lpSurface);
+      
+      fLocked = TRUE;
+    }
+  return fReturn;
+}
+
+
+/*
+ * Do any engine-specific appliation-activation processing
+ */
+
+static Bool
+winActivateAppShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+
+  /*
+   * Do we have a surface?
+   * Are we active?
+   * Are we fullscreen?
+   */
+  if (pScreenPriv != NULL
+      && pScreenPriv->pddsPrimary != NULL
+      && pScreenPriv->fActive)
+    {
+      /* Primary surface was lost, restore it */
+      IDirectDrawSurface2_Restore (pScreenPriv->pddsPrimary);
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Reblit the shadow framebuffer to the screen.
+ */
+
+static Bool
+winRedrawScreenShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  HRESULT		ddrval = DD_OK;
+  RECT			rcSrc, rcDest;
+  POINT			ptOrigin;
+
+  /* Get the origin of the window in the screen coords */
+  ptOrigin.x = pScreenInfo->dwXOffset;
+  ptOrigin.y = pScreenInfo->dwYOffset;
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&ptOrigin, 1);
+  rcDest.left = ptOrigin.x;
+  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
+  rcDest.top = ptOrigin.y;
+  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
+
+  /* Source can be entire shadow surface, as Blt should clip for us */
+  rcSrc.left = 0;
+  rcSrc.top = 0;
+  rcSrc.right = pScreenInfo->dwWidth;
+  rcSrc.bottom = pScreenInfo->dwHeight;
+
+  /* Redraw the whole window, to take account for the new colors */
+  ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
+				    &rcDest,
+				    pScreenPriv->pddsShadow,
+				    &rcSrc,
+				    DDBLT_WAIT,
+				    NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winRedrawScreenShadowDD - IDirectDrawSurface_Blt () "
+	      "failed: %08x\n",
+	      (unsigned int) ddrval);
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Realize the currently installed colormap
+ */
+
+static Bool
+winRealizeInstalledPaletteShadowDD (ScreenPtr pScreen)
+{
+  return TRUE;
+}
+
+
+/*
+ * Install the specified colormap
+ */
+
+static Bool
+winInstallColormapShadowDD (ColormapPtr pColormap)
+{
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  HRESULT		ddrval = DD_OK;
+
+  /* Install the DirectDraw palette on the primary surface */
+  ddrval = IDirectDrawSurface2_SetPalette (pScreenPriv->pddsPrimary,
+					   pCmapPriv->lpDDPalette);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winInstallColormapShadowDD - Failed installing the "
+	      "DirectDraw palette.\n");
+      return FALSE;
+    }
+
+  /* Save a pointer to the newly installed colormap */
+  pScreenPriv->pcmapInstalled = pColormap;
+
+  return TRUE;
+}
+
+
+/*
+ * Store the specified colors in the specified colormap
+ */
+
+static Bool
+winStoreColorsShadowDD (ColormapPtr pColormap, 
+			int ndef,
+			xColorItem *pdefs)
+{
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  ColormapPtr		curpmap = pScreenPriv->pcmapInstalled;
+  HRESULT		ddrval = DD_OK;
+  
+  /* Put the X colormap entries into the Windows logical palette */
+  ddrval = IDirectDrawPalette_SetEntries (pCmapPriv->lpDDPalette,
+					  0,
+					  pdefs[0].pixel,
+					  ndef,
+					  pCmapPriv->peColors 
+					  + pdefs[0].pixel);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winStoreColorsShadowDD - SetEntries () failed\n");
+      return FALSE;
+    }
+
+  /* Don't install the DirectDraw palette if the colormap is not installed */
+  if (pColormap != curpmap)
+    {
+      return TRUE;
+    }
+
+  if (!winInstallColormapShadowDD (pColormap))
+    {
+      ErrorF ("winStoreColorsShadowDD - Failed installing colormap\n");
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Colormap initialization procedure
+ */
+
+static Bool
+winCreateColormapShadowDD (ColormapPtr pColormap)
+{
+  HRESULT		ddrval = DD_OK;
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  
+  /* Create a DirectDraw palette */
+  ddrval = IDirectDraw2_CreatePalette (pScreenPriv->pdd,
+				       DDPCAPS_8BIT | DDPCAPS_ALLOW256,
+				       pCmapPriv->peColors,
+				       &pCmapPriv->lpDDPalette,
+				       NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winCreateColormapShadowDD - CreatePalette failed\n");
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Colormap destruction procedure
+ */
+
+static Bool
+winDestroyColormapShadowDD (ColormapPtr pColormap)
+{
+  winScreenPriv(pColormap->pScreen);
+  winCmapPriv(pColormap);
+  HRESULT		ddrval = DD_OK;
+
+  /*
+   * Is colormap to be destroyed the default?
+   *
+   * Non-default colormaps should have had winUninstallColormap
+   * called on them before we get here.  The default colormap
+   * will not have had winUninstallColormap called on it.  Thus,
+   * we need to handle the default colormap in a special way.
+   */
+  if (pColormap->flags & IsDefault)
+    {
+#if CYGDEBUG
+      winDebug ("winDestroyColormapShadowDD - Destroying default "
+	      "colormap\n");
+#endif
+      
+      /*
+       * FIXME: Walk the list of all screens, popping the default
+       * palette out of each screen device context.
+       */
+      
+      /* Pop the palette out of the primary surface */
+      ddrval = IDirectDrawSurface2_SetPalette (pScreenPriv->pddsPrimary,
+					       NULL);
+      if (FAILED (ddrval))
+	{
+	  ErrorF ("winDestroyColormapShadowDD - Failed freeing the "
+		  "default colormap DirectDraw palette.\n");
+	  return FALSE;
+	}
+
+      /* Clear our private installed colormap pointer */
+      pScreenPriv->pcmapInstalled = NULL;
+    }
+  
+  /* Release the palette */
+  IDirectDrawPalette_Release (pCmapPriv->lpDDPalette);
+ 
+  /* Invalidate the colormap privates */
+  pCmapPriv->lpDDPalette = NULL;
+
+  return TRUE;
+}
+
+
+/*
+ * Set engine specific functions
+ */
+
+Bool
+winSetEngineFunctionsShadowDD (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  
+  /* Set our pointers */
+  pScreenPriv->pwinAllocateFB = winAllocateFBShadowDD;
+  pScreenPriv->pwinShadowUpdate = winShadowUpdateDD;
+  pScreenPriv->pwinCloseScreen = winCloseScreenShadowDD;
+  pScreenPriv->pwinInitVisuals = winInitVisualsShadowDD;
+  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModeShadowDD;
+  if (pScreenInfo->fFullScreen)
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
+  else
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
+  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitFB;
+  pScreenPriv->pwinBltExposedRegions = winBltExposedRegionsShadowDD;
+  pScreenPriv->pwinActivateApp = winActivateAppShadowDD;
+  pScreenPriv->pwinRedrawScreen = winRedrawScreenShadowDD;
+  pScreenPriv->pwinRealizeInstalledPalette
+    = winRealizeInstalledPaletteShadowDD;
+  pScreenPriv->pwinInstallColormap = winInstallColormapShadowDD;
+  pScreenPriv->pwinStoreColors = winStoreColorsShadowDD;
+  pScreenPriv->pwinCreateColormap = winCreateColormapShadowDD;
+  pScreenPriv->pwinDestroyColormap = winDestroyColormapShadowDD;
+  pScreenPriv->pwinHotKeyAltTab = (winHotKeyAltTabProcPtr) (void (*)(void))NoopDDA;
+  pScreenPriv->pwinCreatePrimarySurface = winCreatePrimarySurfaceShadowDD;
+  pScreenPriv->pwinReleasePrimarySurface = winReleasePrimarySurfaceShadowDD;
+#ifdef XWIN_MULTIWINDOW
+  pScreenPriv->pwinFinishCreateWindowsWindow =
+    (winFinishCreateWindowsWindowProcPtr) (void (*)(void))NoopDDA;
+#endif
+
+  return TRUE;
+}
diff --git a/hw/xwin/winshadddnl.c b/hw/xwin/winshadddnl.c
new file mode 100644
index 0000000..47cc382
--- /dev/null
+++ b/hw/xwin/winshadddnl.c
@@ -0,0 +1,1454 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * External symbols
+ */
+
+extern HWND			g_hDlgExit;
+
+
+/*
+ * FIXME: Headers are broken, DEFINE_GUID doesn't work correctly,
+ * so we have to redefine it here.
+ */
+#ifdef DEFINE_GUID
+#undef DEFINE_GUID
+#define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
+#endif /* DEFINE_GUID */
+
+/*
+ * FIXME: Headers are broken, IID_IDirectDraw4 has to be defined
+ * here manually.  Should be handled by ddraw.h
+ */
+#ifndef IID_IDirectDraw4
+DEFINE_GUID( IID_IDirectDraw4, 0x9c59509a,0x39bd,0x11d1,0x8c,0x4a,0x00,0xc0,0x4f,0xd9,0x30,0xc5 );
+#endif /* IID_IDirectDraw4 */
+
+#define FAIL_MSG_MAX_BLT	10
+
+
+/*
+ * Local prototypes
+ */
+
+static Bool
+winAllocateFBShadowDDNL (ScreenPtr pScreen);
+
+static void
+winShadowUpdateDDNL (ScreenPtr pScreen, 
+		     shadowBufPtr pBuf);
+
+static Bool
+winCloseScreenShadowDDNL (int nIndex, ScreenPtr pScreen);
+
+static Bool
+winInitVisualsShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winAdjustVideoModeShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winBltExposedRegionsShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winActivateAppShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winRedrawScreenShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winRealizeInstalledPaletteShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winInstallColormapShadowDDNL (ColormapPtr pColormap);
+
+static Bool
+winStoreColorsShadowDDNL (ColormapPtr pmap, 
+			  int ndef,
+			  xColorItem *pdefs);
+
+static Bool
+winCreateColormapShadowDDNL (ColormapPtr pColormap);
+
+static Bool
+winDestroyColormapShadowDDNL (ColormapPtr pColormap);
+
+static Bool
+winCreatePrimarySurfaceShadowDDNL (ScreenPtr pScreen);
+
+static Bool
+winReleasePrimarySurfaceShadowDDNL (ScreenPtr pScreen);
+
+
+/*
+ * Create the primary surface and attach the clipper.
+ * Used for both the initial surface creation and during
+ * WM_DISPLAYCHANGE messages.
+ */
+
+static Bool
+winCreatePrimarySurfaceShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  HRESULT		ddrval = DD_OK;
+  DDSURFACEDESC2	ddsd;
+
+  winDebug ("winCreatePrimarySurfaceShadowDDNL - Creating primary surface\n");
+
+  /* Describe the primary surface */
+  ZeroMemory (&ddsd, sizeof (ddsd));
+  ddsd.dwSize = sizeof (ddsd);
+  ddsd.dwFlags = DDSD_CAPS;
+  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
+  
+  /* Create the primary surface */
+  ddrval = IDirectDraw4_CreateSurface (pScreenPriv->pdd4,
+				       &ddsd,
+				       &pScreenPriv->pddsPrimary4,
+				       NULL);
+  pScreenPriv->fRetryCreateSurface = FALSE;
+  if (FAILED (ddrval))
+    {
+      if (ddrval == DDERR_NOEXCLUSIVEMODE)
+        {
+          /* Recreating the surface failed. Mark screen to retry later */ 
+          pScreenPriv->fRetryCreateSurface = TRUE;
+          winDebug ("winCreatePrimarySurfaceShadowDDNL - Could not create "
+	          "primary surface: DDERR_NOEXCLUSIVEMODE\n");
+        }
+      else
+        {
+          ErrorF ("winCreatePrimarySurfaceShadowDDNL - Could not create "
+	          "primary surface: %08x\n", (unsigned int) ddrval);
+        }
+      return FALSE;
+    }
+  
+#if 1
+  winDebug ("winCreatePrimarySurfaceShadowDDNL - Created primary surface\n");
+#endif
+
+  /* Attach our clipper to our primary surface handle */
+  ddrval = IDirectDrawSurface4_SetClipper (pScreenPriv->pddsPrimary4,
+					   pScreenPriv->pddcPrimary);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winCreatePrimarySurfaceShadowDDNL - Primary attach clipper "
+	      "failed: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if 1
+  winDebug ("winCreatePrimarySurfaceShadowDDNL - Attached clipper to primary "
+	  "surface\n");
+#endif
+
+  /* Everything was correct */
+  return TRUE;
+}
+
+
+/*
+ * Detach the clipper and release the primary surface.
+ * Called from WM_DISPLAYCHANGE.
+ */
+
+static Bool
+winReleasePrimarySurfaceShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+
+  winDebug ("winReleasePrimarySurfaceShadowDDNL - Hello\n");
+
+  /* Release the primary surface and clipper, if they exist */
+  if (pScreenPriv->pddsPrimary4)
+    {
+      /*
+       * Detach the clipper from the primary surface.
+       * NOTE: We do this explicity for clarity.  The Clipper is not released.
+       */
+      IDirectDrawSurface4_SetClipper (pScreenPriv->pddsPrimary4,
+				      NULL);
+  
+      winDebug ("winReleasePrimarySurfaceShadowDDNL - Detached clipper\n");
+
+      /* Release the primary surface */
+      IDirectDrawSurface4_Release (pScreenPriv->pddsPrimary4);
+      pScreenPriv->pddsPrimary4 = NULL;
+    }
+
+  winDebug ("winReleasePrimarySurfaceShadowDDNL - Released primary surface\n");
+  
+  return TRUE;
+}
+
+
+/*
+ * Create a DirectDraw surface for the shadow framebuffer; also create
+ * a primary surface object so we can blit to the display.
+ * 
+ * Install a DirectDraw clipper on our primary surface object
+ * that clips our blits to the unobscured client area of our display window.
+ */
+
+Bool
+winAllocateFBShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;  
+  HRESULT		ddrval = DD_OK;
+  DDSURFACEDESC2	ddsdShadow;
+  char			*lpSurface = NULL;
+  DDPIXELFORMAT		ddpfPrimary;
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDDNL - w %d h %d d %d\n",
+	  pScreenInfo->dwWidth, pScreenInfo->dwHeight, pScreenInfo->dwDepth);
+#endif
+
+  /* Allocate memory for our shadow surface */
+  lpSurface = malloc (pScreenInfo->dwPaddedWidth * pScreenInfo->dwHeight);
+  if (lpSurface == NULL)
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Could not allocate bits\n");
+      return FALSE;
+    }
+
+  /*
+   * Initialize the framebuffer memory so we don't get a 
+   * strange display at startup
+   */
+  ZeroMemory (lpSurface, pScreenInfo->dwPaddedWidth * pScreenInfo->dwHeight);
+  
+  /* Create a clipper */
+  ddrval = (*g_fpDirectDrawCreateClipper) (0,
+					   &pScreenPriv->pddcPrimary,
+					   NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Could not attach clipper: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDDNL - Created a clipper\n");
+#endif
+
+  /* Get a device context for the screen  */
+  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
+
+  /* Attach the clipper to our display window */
+  ddrval = IDirectDrawClipper_SetHWnd (pScreenPriv->pddcPrimary,
+				       0,
+				       pScreenPriv->hwndScreen);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Clipper not attached "
+	      "to window: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDDNL - Attached clipper to window\n");
+#endif
+
+  /* Create a DirectDraw object, store the address at lpdd */
+  ddrval = (*g_fpDirectDrawCreate) (NULL,
+				    (LPDIRECTDRAW*) &pScreenPriv->pdd,
+				    NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Could not start "
+	      "DirectDraw: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDDNL - Created and initialized DD\n");
+#endif
+
+  /* Get a DirectDraw4 interface pointer */
+  ddrval = IDirectDraw_QueryInterface (pScreenPriv->pdd,
+				       &IID_IDirectDraw4,
+				       (LPVOID*) &pScreenPriv->pdd4);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Failed DD4 query: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+  /* Are we full screen? */
+  if (pScreenInfo->fFullScreen)
+    {
+      DDSURFACEDESC2	ddsdCurrent;
+      DWORD		dwRefreshRateCurrent = 0;
+      HDC		hdc = NULL;
+
+      /* Set the cooperative level to full screen */
+      ddrval = IDirectDraw4_SetCooperativeLevel (pScreenPriv->pdd4,
+						 pScreenPriv->hwndScreen,
+						 DDSCL_EXCLUSIVE
+						 | DDSCL_FULLSCREEN);
+      if (FAILED (ddrval))
+	{
+	  ErrorF ("winAllocateFBShadowDDNL - Could not set "
+		  "cooperative level: %08x\n",
+		  (unsigned int) ddrval);
+	  return FALSE;
+	}
+
+      /*
+       * We only need to get the current refresh rate for comparison
+       * if a refresh rate has been passed on the command line.
+       */
+      if (pScreenInfo->dwRefreshRate != 0)
+	{
+	  ZeroMemory (&ddsdCurrent, sizeof (ddsdCurrent));
+	  ddsdCurrent.dwSize = sizeof (ddsdCurrent);
+
+	  /* Get information about current display settings */
+	  ddrval = IDirectDraw4_GetDisplayMode (pScreenPriv->pdd4,
+						&ddsdCurrent);
+	  if (FAILED (ddrval))
+	    {
+	      ErrorF ("winAllocateFBShadowDDNL - Could not get current "
+		      "refresh rate: %08x.  Continuing.\n",
+		      (unsigned int) ddrval);
+	      dwRefreshRateCurrent = 0;
+	    }
+	  else
+	    {
+	      /* Grab the current refresh rate */
+	      dwRefreshRateCurrent = ddsdCurrent.u2.dwRefreshRate;
+	    }
+	}
+
+      /* Clean up the refresh rate */
+      if (dwRefreshRateCurrent == pScreenInfo->dwRefreshRate)
+	{
+	  /*
+	   * Refresh rate is non-specified or equal to current.
+	   */
+	  pScreenInfo->dwRefreshRate = 0;
+	}
+
+      /* Grab a device context for the screen */
+      hdc = GetDC (NULL);
+      if (hdc == NULL)
+	{
+	  ErrorF ("winAllocateFBShadowDDNL - GetDC () failed\n");
+	  return FALSE;
+	}
+
+      /* Only change the video mode when different than current mode */
+      if (!pScreenInfo->fMultipleMonitors
+	  && (pScreenInfo->dwWidth != GetSystemMetrics (SM_CXSCREEN)
+	      || pScreenInfo->dwHeight != GetSystemMetrics (SM_CYSCREEN)
+	      || pScreenInfo->dwBPP != GetDeviceCaps (hdc, BITSPIXEL)
+	      || pScreenInfo->dwRefreshRate != 0))
+	{
+	  winDebug ("winAllocateFBShadowDDNL - Changing video mode\n");
+
+	  /* Change the video mode to the mode requested */
+	  ddrval = IDirectDraw4_SetDisplayMode (pScreenPriv->pdd4,
+						pScreenInfo->dwWidth,
+						pScreenInfo->dwHeight,
+						pScreenInfo->dwBPP,
+						pScreenInfo->dwRefreshRate,
+						0);	       
+	  if (FAILED (ddrval))
+	    {
+	      ErrorF ("winAllocateFBShadowDDNL - Could not set "
+		      "full screen display mode: %08x\n",
+		      (unsigned int) ddrval);
+	      return FALSE;
+	    }
+	}
+      else
+	{
+	  winDebug ("winAllocateFBShadowDDNL - Not changing video mode\n");
+	}
+
+      /* Release our DC */
+      ReleaseDC (NULL, hdc);
+      hdc = NULL;
+    }
+  else
+    {
+      /* Set the cooperative level for windowed mode */
+      ddrval = IDirectDraw4_SetCooperativeLevel (pScreenPriv->pdd4,
+						 pScreenPriv->hwndScreen,
+						 DDSCL_NORMAL);
+      if (FAILED (ddrval))
+	{
+	  ErrorF ("winAllocateFBShadowDDNL - Could not set "
+		  "cooperative level: %08x\n",
+		  (unsigned int) ddrval);
+	  return FALSE;
+	}
+    }
+
+  /* Create the primary surface */
+  if (!winCreatePrimarySurfaceShadowDDNL (pScreen))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - winCreatePrimarySurfaceShadowDDNL "
+	      "failed\n");
+      return FALSE;
+    }
+
+  /* Get primary surface's pixel format */
+  ZeroMemory (&ddpfPrimary, sizeof (ddpfPrimary));
+  ddpfPrimary.dwSize = sizeof (ddpfPrimary);
+  ddrval = IDirectDrawSurface4_GetPixelFormat (pScreenPriv->pddsPrimary4,
+					       &ddpfPrimary);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Could not get primary "
+	      "pixformat: %08x\n",
+	      (unsigned int) ddrval);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDDNL - Primary masks: %08x %08x %08x "
+	  "dwRGBBitCount: %d\n",
+	  ddpfPrimary.u2.dwRBitMask,
+	  ddpfPrimary.u3.dwGBitMask,
+	  ddpfPrimary.u4.dwBBitMask,
+	  ddpfPrimary.u1.dwRGBBitCount);
+#endif
+
+  /* Describe the shadow surface to be created */
+  /*
+   * NOTE: Do not use a DDSCAPS_VIDEOMEMORY surface,
+   * as drawing, locking, and unlocking take forever
+   * with video memory surfaces.  In addition,
+   * video memory is a somewhat scarce resource,
+   * so you shouldn't be allocating video memory when
+   * you have the option of using system memory instead.
+   */
+  ZeroMemory (&ddsdShadow, sizeof (ddsdShadow));
+  ddsdShadow.dwSize = sizeof (ddsdShadow);
+  ddsdShadow.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH
+    | DDSD_LPSURFACE | DDSD_PITCH | DDSD_PIXELFORMAT;
+  ddsdShadow.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
+  ddsdShadow.dwHeight = pScreenInfo->dwHeight;
+  ddsdShadow.dwWidth = pScreenInfo->dwWidth;
+  ddsdShadow.u1.lPitch = pScreenInfo->dwPaddedWidth;
+  ddsdShadow.lpSurface = lpSurface;
+  ddsdShadow.u4.ddpfPixelFormat = ddpfPrimary;
+  
+  winDebug ("winAllocateFBShadowDDNL - lPitch: %d\n",
+	  (int) pScreenInfo->dwPaddedWidth);
+
+  /* Create the shadow surface */
+  ddrval = IDirectDraw4_CreateSurface (pScreenPriv->pdd4,
+				       &ddsdShadow,
+				       &pScreenPriv->pddsShadow4,
+				       NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winAllocateFBShadowDDNL - Could not create shadow "
+	      "surface: %08x\n", (unsigned int) ddrval);
+      return FALSE;
+    }
+  
+#if CYGDEBUG || YES
+  winDebug ("winAllocateFBShadowDDNL - Created shadow pitch: %d\n",
+	  (int) ddsdShadow.u1.lPitch);
+#endif
+
+  /* Grab the pitch from the surface desc */
+  pScreenInfo->dwStride = (ddsdShadow.u1.lPitch * 8)
+    / pScreenInfo->dwBPP;
+
+#if CYGDEBUG || YES
+  winDebug ("winAllocateFBShadowDDNL - Created shadow stride: %d\n",
+	  (int) pScreenInfo->dwStride);
+#endif
+
+  /* Save the pointer to our surface memory */
+  pScreenInfo->pfb = lpSurface;
+  
+  /* Grab the masks from the surface description */
+  pScreenPriv->dwRedMask = ddsdShadow.u4.ddpfPixelFormat.u2.dwRBitMask;
+  pScreenPriv->dwGreenMask = ddsdShadow.u4.ddpfPixelFormat.u3.dwGBitMask;
+  pScreenPriv->dwBlueMask = ddsdShadow.u4.ddpfPixelFormat.u4.dwBBitMask;
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowDDNL - Returning\n");
+#endif
+
+  return TRUE;
+}
+
+
+#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
+/*
+ * Create a DirectDraw surface for the new multi-window window
+ */
+
+static
+Bool
+winFinishCreateWindowsWindowDDNL (WindowPtr pWin)
+{
+  winWindowPriv(pWin);
+  winPrivScreenPtr	pScreenPriv = pWinPriv->pScreenPriv;
+  HRESULT		ddrval = DD_OK;
+  DDSURFACEDESC2	ddsd;
+  int			iWidth, iHeight;
+  int			iX, iY;
+
+  winDebug ("\nwinFinishCreateWindowsWindowDDNL!\n\n");
+
+  iX = pWin->drawable.x + GetSystemMetrics (SM_XVIRTUALSCREEN);
+  iY = pWin->drawable.y + GetSystemMetrics (SM_YVIRTUALSCREEN);
+  
+  iWidth = pWin->drawable.width;
+  iHeight = pWin->drawable.height;
+
+  /* Describe the primary surface */
+  ZeroMemory (&ddsd, sizeof (ddsd));
+  ddsd.dwSize = sizeof (ddsd);
+  ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
+  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
+  ddsd.dwHeight = iHeight;
+  ddsd.dwWidth = iWidth;
+
+  /* Create the primary surface */
+  ddrval = IDirectDraw4_CreateSurface (pScreenPriv->pdd4,
+				       &ddsd,
+				       &pWinPriv->pddsPrimary4,
+				       NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winFinishCreateWindowsWindowDDNL - Could not create primary "
+	      "surface: %08x\n",
+	      (unsigned int)ddrval);
+      return FALSE;
+    }
+  return TRUE;
+}
+#endif
+
+
+/*
+ * Transfer the damaged regions of the shadow framebuffer to the display.
+ */
+
+static void
+winShadowUpdateDDNL (ScreenPtr pScreen, 
+		     shadowBufPtr pBuf)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  RegionPtr		damage = &pBuf->damage;
+  HRESULT		ddrval = DD_OK;
+  RECT			rcDest, rcSrc;
+  POINT			ptOrigin;
+  DWORD			dwBox = REGION_NUM_RECTS (damage);
+  BoxPtr		pBox = REGION_RECTS (damage);
+  HRGN			hrgnTemp = NULL, hrgnCombined = NULL;
+
+  /*
+   * Return immediately if the app is not active
+   * and we are fullscreen, or if we have a bad display depth
+   */
+  if ((!pScreenPriv->fActive && pScreenInfo->fFullScreen)
+      || pScreenPriv->fBadDepth) return;
+
+  /* Get the origin of the window in the screen coords */
+  ptOrigin.x = pScreenInfo->dwXOffset;
+  ptOrigin.y = pScreenInfo->dwYOffset;
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&ptOrigin, 1);
+
+  /*
+   * Handle small regions with multiple blits,
+   * handle large regions by creating a clipping region and 
+   * doing a single blit constrained to that clipping region.
+   */
+  if (pScreenInfo->dwClipUpdatesNBoxes == 0
+      || dwBox < pScreenInfo->dwClipUpdatesNBoxes)
+    {
+      /* Loop through all boxes in the damaged region */
+      while (dwBox--)
+	{
+	  /* Assign damage box to source rectangle */
+	  rcSrc.left = pBox->x1;
+	  rcSrc.top = pBox->y1;
+	  rcSrc.right = pBox->x2;
+	  rcSrc.bottom = pBox->y2;
+	  
+	  /* Calculate destination rectangle */
+	  rcDest.left = ptOrigin.x + rcSrc.left;
+	  rcDest.top = ptOrigin.y + rcSrc.top;
+	  rcDest.right = ptOrigin.x + rcSrc.right;
+	  rcDest.bottom = ptOrigin.y + rcSrc.bottom;
+	  
+	  /* Blit the damaged areas */
+	  ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
+					    &rcDest,
+					    pScreenPriv->pddsShadow4,
+					    &rcSrc,
+					    DDBLT_WAIT,
+					    NULL);
+	  if (FAILED (ddrval))
+	    {
+	      static int	s_iFailCount = 0;
+	      
+	      if (s_iFailCount < FAIL_MSG_MAX_BLT)
+		{
+		  ErrorF ("winShadowUpdateDDNL - IDirectDrawSurface4_Blt () "
+			  "failed: %08x\n",
+			  (unsigned int) ddrval);
+		  
+		  ++s_iFailCount;
+
+		  if (s_iFailCount == FAIL_MSG_MAX_BLT)
+		    {
+		      ErrorF ("winShadowUpdateDDNL - IDirectDrawSurface4_Blt "
+			      "failure message maximum (%d) reached.  No "
+			      "more failure messages will be printed.\n",
+			      FAIL_MSG_MAX_BLT);
+		    }
+		}
+	    }
+	  
+	  /* Get a pointer to the next box */
+	  ++pBox;
+	}
+    }
+  else
+    {
+      BoxPtr		pBoxExtents = REGION_EXTENTS (pScreen, damage);
+
+      /* Compute a GDI region from the damaged region */
+      hrgnCombined = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
+      dwBox--;
+      pBox++;
+      while (dwBox--)
+	{
+	  hrgnTemp = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
+	  CombineRgn (hrgnCombined, hrgnCombined, hrgnTemp, RGN_OR);
+	  DeleteObject (hrgnTemp);
+	  pBox++;
+	}
+
+      /* Install the GDI region as a clipping region */
+      SelectClipRgn (pScreenPriv->hdcScreen, hrgnCombined);
+      DeleteObject (hrgnCombined);
+      hrgnCombined = NULL;
+
+#if CYGDEBUG
+      winDebug ("winShadowUpdateDDNL - be x1 %d y1 %d x2 %d y2 %d\n",
+	      pBoxExtents->x1, pBoxExtents->y1,
+	      pBoxExtents->x2, pBoxExtents->y2);
+#endif
+
+      /* Calculating a bounding box for the source is easy */
+      rcSrc.left = pBoxExtents->x1;
+      rcSrc.top = pBoxExtents->y1;
+      rcSrc.right = pBoxExtents->x2;
+      rcSrc.bottom = pBoxExtents->y2;
+
+      /* Calculating a bounding box for the destination is trickier */
+      rcDest.left = ptOrigin.x + rcSrc.left;
+      rcDest.top = ptOrigin.y + rcSrc.top;
+      rcDest.right = ptOrigin.x + rcSrc.right;
+      rcDest.bottom = ptOrigin.y + rcSrc.bottom;
+
+      /* Our Blt should be clipped to the invalidated region */
+      ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
+					&rcDest,
+					pScreenPriv->pddsShadow4,
+					&rcSrc,
+					DDBLT_WAIT,
+					NULL);
+
+      /* Reset the clip region */
+      SelectClipRgn (pScreenPriv->hdcScreen, NULL);
+    }
+}
+
+
+/*
+ * Call the wrapped CloseScreen function.
+ *
+ * Free our resources and private structures.
+ */
+
+static Bool
+winCloseScreenShadowDDNL (int nIndex, ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  Bool			fReturn;
+
+#if CYGDEBUG
+  winDebug ("winCloseScreenShadowDDNL - Freeing screen resources\n");
+#endif
+
+  /* Flag that the screen is closed */
+  pScreenPriv->fClosed = TRUE;
+  pScreenPriv->fActive = FALSE;
+
+  /* Call the wrapped CloseScreen procedure */
+  WIN_UNWRAP(CloseScreen);
+  fReturn = (*pScreen->CloseScreen) (nIndex, pScreen);
+
+  /* Free the screen DC */
+  ReleaseDC (pScreenPriv->hwndScreen, pScreenPriv->hdcScreen);
+
+  /* Delete the window property */
+  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
+
+  /* Free the shadow surface, if there is one */
+  if (pScreenPriv->pddsShadow4)
+    {
+      IDirectDrawSurface4_Release (pScreenPriv->pddsShadow4);
+      free (pScreenInfo->pfb);
+      pScreenInfo->pfb = NULL;
+      pScreenPriv->pddsShadow4 = NULL;
+    }
+
+  /* Detach the clipper from the primary surface and release the clipper. */
+  if (pScreenPriv->pddcPrimary)
+    {
+      /* Detach the clipper */
+      IDirectDrawSurface4_SetClipper (pScreenPriv->pddsPrimary4,
+				      NULL);
+
+      /* Release the clipper object */
+      IDirectDrawClipper_Release (pScreenPriv->pddcPrimary);
+      pScreenPriv->pddcPrimary = NULL;
+    }
+
+  /* Release the primary surface, if there is one */
+  if (pScreenPriv->pddsPrimary4)
+    {
+      IDirectDrawSurface4_Release (pScreenPriv->pddsPrimary4);
+      pScreenPriv->pddsPrimary4 = NULL;
+    }
+
+  /* Free the DirectDraw4 object, if there is one */
+  if (pScreenPriv->pdd4)
+    {
+      IDirectDraw4_RestoreDisplayMode (pScreenPriv->pdd4);
+      IDirectDraw4_Release (pScreenPriv->pdd4);
+      pScreenPriv->pdd4 = NULL;
+    }
+
+  /* Free the DirectDraw object, if there is one */
+  if (pScreenPriv->pdd)
+    {
+      IDirectDraw_Release (pScreenPriv->pdd);
+      pScreenPriv->pdd = NULL;
+    }
+
+  /* Delete tray icon, if we have one */
+  if (!pScreenInfo->fNoTrayIcon)
+    winDeleteNotifyIcon (pScreenPriv);
+
+  /* Free the exit confirmation dialog box, if it exists */
+  if (g_hDlgExit != NULL)
+    {
+      DestroyWindow (g_hDlgExit);
+      g_hDlgExit = NULL;
+    }
+
+  /* Kill our window */
+  if (pScreenPriv->hwndScreen)
+    {
+      DestroyWindow (pScreenPriv->hwndScreen);
+      pScreenPriv->hwndScreen = NULL;
+    }
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  /* Destroy the thread startup mutex */
+  pthread_mutex_destroy (&pScreenPriv->pmServerStarted);
+#endif
+
+  /* Kill our screeninfo's pointer to the screen */
+  pScreenInfo->pScreen = NULL;
+
+  /* Invalidate the ScreenInfo's fb pointer */
+  pScreenInfo->pfb = NULL;
+
+  /* Free the screen privates for this screen */
+  free ((pointer) pScreenPriv);
+
+  return fReturn;
+}
+
+
+/*
+ * Tell mi what sort of visuals we need.
+ *
+ * Generally we only need one visual, as our screen can only
+ * handle one format at a time, I believe.  You may want
+ * to verify that last sentence.
+ */
+
+static Bool
+winInitVisualsShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  DWORD			dwRedBits, dwGreenBits, dwBlueBits;
+
+  /* Count the number of ones in each color mask */
+  dwRedBits = winCountBits (pScreenPriv->dwRedMask);
+  dwGreenBits = winCountBits (pScreenPriv->dwGreenMask);
+  dwBlueBits = winCountBits (pScreenPriv->dwBlueMask);
+  
+  /* Store the maximum number of ones in a color mask as the bitsPerRGB */
+  if (dwRedBits == 0 || dwGreenBits == 0 || dwBlueBits == 0)
+    pScreenPriv->dwBitsPerRGB = 8;
+  else if (dwRedBits > dwGreenBits && dwRedBits > dwBlueBits)
+    pScreenPriv->dwBitsPerRGB = dwRedBits;
+  else if (dwGreenBits > dwRedBits && dwGreenBits > dwBlueBits)
+    pScreenPriv->dwBitsPerRGB = dwGreenBits;
+  else
+    pScreenPriv->dwBitsPerRGB = dwBlueBits;
+
+  winDebug ("winInitVisualsShadowDDNL - Masks %08x %08x %08x BPRGB %d d %d "
+	  "bpp %d\n",
+	  (unsigned int) pScreenPriv->dwRedMask,
+	  (unsigned int) pScreenPriv->dwGreenMask,
+	  (unsigned int) pScreenPriv->dwBlueMask,
+	  (int) pScreenPriv->dwBitsPerRGB,
+	  (int) pScreenInfo->dwDepth,
+	  (int) pScreenInfo->dwBPP);
+
+  /* Create a single visual according to the Windows screen depth */
+  switch (pScreenInfo->dwDepth)
+    {
+    case 24:
+    case 16:
+    case 15:
+#if defined(XFree86Server)
+      /* Setup the real visual */
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     TrueColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     -1,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDDNL - miSetVisualTypesAndMasks "
+		  "failed for TrueColor\n");
+	  return FALSE;
+	}
+
+#ifdef XWIN_EMULATEPSEUDO
+      if (!pScreenInfo->fEmulatePseudo)
+	break;
+
+      /* Setup a pseudocolor visual */
+      if (!miSetVisualTypesAndMasks (8,
+				     PseudoColorMask,
+				     8,
+				     -1,
+				     0,
+				     0,
+				     0))
+	{
+	  ErrorF ("winInitVisualsShadowDDNL - miSetVisualTypesAndMasks "
+		  "failed for PseudoColor\n");
+	  return FALSE;
+	}
+#endif
+#else /* XFree86Server */
+      /* Setup the real visual */
+      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     TrueColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDDNL - fbSetVisualTypesAndMasks "
+		  "failed for TrueColor\n");
+	  return FALSE;
+	}
+
+#ifdef XWIN_EMULATEPSEUDO
+      if (!pScreenInfo->fEmulatePseudo)
+	break;
+
+      /* Setup a pseudocolor visual */
+      if (!fbSetVisualTypesAndMasks (8,
+				     PseudoColorMask,
+				     8,
+				     0,
+				     0,
+				     0))
+	{
+	  ErrorF ("winInitVisualsShadowDDNL - fbSetVisualTypesAndMasks "
+		  "failed for PseudoColor\n");
+	  return FALSE;
+	}
+#endif
+#endif /* XFree86Server */
+      break;
+
+    case 8:
+#if defined(XFree86Server)
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     pScreenInfo->fFullScreen 
+				     ? PseudoColorMask : StaticColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenInfo->fFullScreen 
+				     ? PseudoColor : StaticColor,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDDNL - miSetVisualTypesAndMasks "
+		  "failed\n");
+	  return FALSE;
+	}
+#else /* XFree86Server */
+        if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     pScreenInfo->fFullScreen 
+				     ? PseudoColorMask : StaticColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowDDNL - fbSetVisualTypesAndMasks "
+		  "failed\n");
+	  return FALSE;
+	}    
+#endif /* XFree86Server */
+      break;
+
+    default:
+      ErrorF ("winInitVisualsShadowDDNL - Unknown screen depth\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winInitVisualsShadowDDNL - Returning\n");
+#endif
+
+  return TRUE;
+}
+
+
+/*
+ * Adjust the user proposed video mode
+ */
+
+static Bool
+winAdjustVideoModeShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  HDC			hdc = NULL;
+  DWORD			dwBPP;
+
+  /* We're in serious trouble if we can't get a DC */
+  hdc = GetDC (NULL);
+  if (hdc == NULL)
+    {
+      ErrorF ("winAdjustVideoModeShadowDDNL - GetDC () failed\n");
+      return FALSE;
+    }
+
+  /* Query GDI for current display depth */
+  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
+
+  /* DirectDraw can only change the depth in fullscreen mode */
+  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
+    {
+      /* No -depth parameter passed, let the user know the depth being used */
+      winErrorFVerb (2, "winAdjustVideoModeShadowDDNL - Using Windows display "
+	      "depth of %d bits per pixel\n", (int) dwBPP);
+
+      /* Use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+  else if (pScreenInfo->fFullScreen
+	   && pScreenInfo->dwBPP != dwBPP)
+    {
+      /* FullScreen, and GDI depth differs from -depth parameter */
+      winErrorFVerb (2, "winAdjustVideoModeShadowDDNL - FullScreen, using command "
+	      "line bpp: %d\n", (int) pScreenInfo->dwBPP);
+    }
+  else if (dwBPP != pScreenInfo->dwBPP)
+    {
+      /* Windowed, and GDI depth differs from -depth parameter */
+      winErrorFVerb (2, "winAdjustVideoModeShadowDDNL - Windowed, command line "
+	      "bpp: %d, using bpp: %d\n",
+	      (int) pScreenInfo->dwBPP, (int) dwBPP);
+
+      /* We'll use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+
+  /* See if the shadow bitmap will be larger than the DIB size limit */
+  if (pScreenInfo->dwWidth * pScreenInfo->dwHeight * pScreenInfo->dwBPP
+      >= WIN_DIB_MAXIMUM_SIZE)
+    {
+      winErrorFVerb (1, "winAdjustVideoModeShadowDDNL - Requested DirectDraw surface "
+	      "will be larger than %d MB.  The surface may fail to be "
+	      "allocated on Windows 95, 98, or Me, due to a %d MB limit in "
+	      "DIB size.  This limit does not apply to Windows NT/2000, and "
+	      "this message may be ignored on those platforms.\n",
+	      WIN_DIB_MAXIMUM_SIZE_MB, WIN_DIB_MAXIMUM_SIZE_MB);
+    }
+  
+  /* Release our DC */
+  ReleaseDC (NULL, hdc);
+
+  return TRUE;
+}
+
+
+/*
+ * Blt exposed regions to the screen
+ */
+
+static Bool
+winBltExposedRegionsShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  RECT			rcSrc, rcDest;
+  POINT			ptOrigin;
+  HDC			hdcUpdate;
+  PAINTSTRUCT		ps;
+  HRESULT		ddrval = DD_OK;
+  Bool			fReturn = TRUE;
+  int			i;
+
+  /* Quite common case. The primary surface was lost (maybe because of depth
+   * change). Try to create a new primary surface. Bail out if this fails */
+  if (pScreenPriv->pddsPrimary4 == NULL && pScreenPriv->fRetryCreateSurface &&
+      !winCreatePrimarySurfaceShadowDDNL(pScreen))
+    {
+      Sleep(100);
+      return FALSE;
+    }
+  if (pScreenPriv->pddsPrimary4 == NULL)
+    return FALSE;  
+  
+  /* BeginPaint gives us an hdc that clips to the invalidated region */
+  hdcUpdate = BeginPaint (pScreenPriv->hwndScreen, &ps);
+  if (hdcUpdate == NULL)
+    {
+      fReturn = FALSE;
+      ErrorF ("winBltExposedRegionsShadowDDNL - BeginPaint () returned "
+	      "a NULL device context handle.  Aborting blit attempt.\n");
+      goto winBltExposedRegionsShadowDDNL_Exit;
+    }
+
+  /* Get the origin of the window in the screen coords */
+  ptOrigin.x = pScreenInfo->dwXOffset;
+  ptOrigin.y = pScreenInfo->dwYOffset;
+
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&ptOrigin, 1);
+  rcDest.left = ptOrigin.x;
+  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
+  rcDest.top = ptOrigin.y;
+  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
+
+  /* Source can be entire shadow surface, as Blt should clip for us */
+  rcSrc.left = 0;
+  rcSrc.top = 0;
+  rcSrc.right = pScreenInfo->dwWidth;
+  rcSrc.bottom = pScreenInfo->dwHeight;
+
+  /* Try to regain the primary surface and blit again if we've lost it */
+  for (i = 0; i <= WIN_REGAIN_SURFACE_RETRIES; ++i)
+    {
+      /* Our Blt should be clipped to the invalidated region */
+      ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
+					&rcDest,
+					pScreenPriv->pddsShadow4,
+					&rcSrc,
+					DDBLT_WAIT,
+					NULL);
+      if (ddrval == DDERR_SURFACELOST)
+	{
+	  /* Surface was lost */
+	  winErrorFVerb (1, "winBltExposedRegionsShadowDDNL - "
+          "IDirectDrawSurface4_Blt reported that the primary "
+          "surface was lost, trying to restore, retry: %d\n", i + 1);
+
+	  /* Try to restore the surface, once */
+	  
+	  ddrval = IDirectDrawSurface4_Restore (pScreenPriv->pddsPrimary4);
+	  winDebug ("winBltExposedRegionsShadowDDNL - "
+		  "IDirectDrawSurface4_Restore returned: ");
+	  if (ddrval == DD_OK)
+	    winDebug ("DD_OK\n");
+	  else if (ddrval == DDERR_WRONGMODE)
+	    winDebug ("DDERR_WRONGMODE\n");
+	  else if (ddrval == DDERR_INCOMPATIBLEPRIMARY)
+	    winDebug ("DDERR_INCOMPATIBLEPRIMARY\n");
+	  else if (ddrval == DDERR_UNSUPPORTED)
+	    winDebug ("DDERR_UNSUPPORTED\n");
+	  else if (ddrval == DDERR_INVALIDPARAMS)
+	    winDebug ("DDERR_INVALIDPARAMS\n");
+	  else if (ddrval == DDERR_INVALIDOBJECT)
+	    winDebug ("DDERR_INVALIDOBJECT\n");
+	  else
+	    winDebug ("unknown error: %08x\n", (unsigned int) ddrval);
+	  
+	  /* Loop around to try the blit one more time */
+	  continue;
+	}  
+      else if (FAILED (ddrval))
+	{
+	  fReturn = FALSE;
+	  winErrorFVerb (1, "winBltExposedRegionsShadowDDNL - "
+		  "IDirectDrawSurface4_Blt failed, but surface not "
+		  "lost: %08x %d\n",
+		  (unsigned int) ddrval, (int) ddrval);
+	  goto winBltExposedRegionsShadowDDNL_Exit;
+	}
+      else
+	{
+	  /* Success, stop looping */
+	  break;
+	}
+    }
+
+ winBltExposedRegionsShadowDDNL_Exit:
+  /* EndPaint frees the DC */
+  if (hdcUpdate != NULL)
+    EndPaint (pScreenPriv->hwndScreen, &ps);
+  return fReturn;
+}
+
+
+/*
+ * Do any engine-specific application-activation processing
+ */
+
+static Bool
+winActivateAppShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+
+  /*
+   * Do we have a surface?
+   * Are we active?
+   * Are we full screen?
+   */
+  if (pScreenPriv != NULL
+      && pScreenPriv->pddsPrimary4 != NULL
+      && pScreenPriv->fActive)
+    {
+      /* Primary surface was lost, restore it */
+      IDirectDrawSurface4_Restore (pScreenPriv->pddsPrimary4);
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Reblit the shadow framebuffer to the screen.
+ */
+
+static Bool
+winRedrawScreenShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  HRESULT		ddrval = DD_OK;
+  RECT			rcSrc, rcDest;
+  POINT			ptOrigin;
+
+  /* Get the origin of the window in the screen coords */
+  ptOrigin.x = pScreenInfo->dwXOffset;
+  ptOrigin.y = pScreenInfo->dwYOffset;
+  MapWindowPoints (pScreenPriv->hwndScreen,
+		   HWND_DESKTOP,
+		   (LPPOINT)&ptOrigin, 1);
+  rcDest.left = ptOrigin.x;
+  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
+  rcDest.top = ptOrigin.y;
+  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
+
+  /* Source can be entire shadow surface, as Blt should clip for us */
+  rcSrc.left = 0;
+  rcSrc.top = 0;
+  rcSrc.right = pScreenInfo->dwWidth;
+  rcSrc.bottom = pScreenInfo->dwHeight;
+
+  /* Redraw the whole window, to take account for the new colors */
+  ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
+				    &rcDest,
+				    pScreenPriv->pddsShadow4,
+				    &rcSrc,
+				    DDBLT_WAIT,
+				    NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winRedrawScreenShadowDDNL - IDirectDrawSurface4_Blt () "
+	      "failed: %08x\n",
+	      (unsigned int) ddrval);
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Realize the currently installed colormap
+ */
+
+static Bool
+winRealizeInstalledPaletteShadowDDNL (ScreenPtr pScreen)
+{
+  return TRUE;
+}
+
+
+/*
+ * Install the specified colormap
+ */
+
+static Bool
+winInstallColormapShadowDDNL (ColormapPtr pColormap)
+{
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  HRESULT		ddrval = DD_OK;
+
+  /* Install the DirectDraw palette on the primary surface */
+  ddrval = IDirectDrawSurface4_SetPalette (pScreenPriv->pddsPrimary4,
+					   pCmapPriv->lpDDPalette);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winInstallColormapShadowDDNL - Failed installing the "
+	      "DirectDraw palette.\n");
+      return FALSE;
+    }
+
+  /* Save a pointer to the newly installed colormap */
+  pScreenPriv->pcmapInstalled = pColormap;
+
+  return TRUE;
+}
+
+
+/*
+ * Store the specified colors in the specified colormap
+ */
+
+static Bool
+winStoreColorsShadowDDNL (ColormapPtr pColormap, 
+			  int ndef,
+			  xColorItem *pdefs)
+{
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  ColormapPtr		curpmap = pScreenPriv->pcmapInstalled;
+  HRESULT		ddrval = DD_OK;
+  
+  /* Put the X colormap entries into the Windows logical palette */
+  ddrval = IDirectDrawPalette_SetEntries (pCmapPriv->lpDDPalette,
+					  0,
+					  pdefs[0].pixel,
+					  ndef,
+					  pCmapPriv->peColors 
+					  + pdefs[0].pixel);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winStoreColorsShadowDDNL - SetEntries () failed: %08x\n", ddrval);
+      return FALSE;
+    }
+
+  /* Don't install the DirectDraw palette if the colormap is not installed */
+  if (pColormap != curpmap)
+    {
+      return TRUE;
+    }
+
+  if (!winInstallColormapShadowDDNL (pColormap))
+    {
+      ErrorF ("winStoreColorsShadowDDNL - Failed installing colormap\n");
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Colormap initialization procedure
+ */
+
+static Bool
+winCreateColormapShadowDDNL (ColormapPtr pColormap)
+{
+  HRESULT		ddrval = DD_OK;
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  
+  /* Create a DirectDraw palette */
+  ddrval = IDirectDraw4_CreatePalette (pScreenPriv->pdd4,
+				       DDPCAPS_8BIT | DDPCAPS_ALLOW256,
+				       pCmapPriv->peColors,
+				       &pCmapPriv->lpDDPalette,
+				       NULL);
+  if (FAILED (ddrval))
+    {
+      ErrorF ("winCreateColormapShadowDDNL - CreatePalette failed\n");
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Colormap destruction procedure
+ */
+
+static Bool
+winDestroyColormapShadowDDNL (ColormapPtr pColormap)
+{
+  winScreenPriv(pColormap->pScreen);
+  winCmapPriv(pColormap);
+  HRESULT		ddrval = DD_OK;
+
+  /*
+   * Is colormap to be destroyed the default?
+   *
+   * Non-default colormaps should have had winUninstallColormap
+   * called on them before we get here.  The default colormap
+   * will not have had winUninstallColormap called on it.  Thus,
+   * we need to handle the default colormap in a special way.
+   */
+  if (pColormap->flags & IsDefault)
+    {
+#if CYGDEBUG
+      winDebug ("winDestroyColormapShadowDDNL - Destroying default colormap\n");
+#endif
+      
+      /*
+       * FIXME: Walk the list of all screens, popping the default
+       * palette out of each screen device context.
+       */
+      
+      /* Pop the palette out of the primary surface */
+      ddrval = IDirectDrawSurface4_SetPalette (pScreenPriv->pddsPrimary4,
+					       NULL);
+      if (FAILED (ddrval))
+	{
+	  ErrorF ("winDestroyColormapShadowDDNL - Failed freeing the "
+		  "default colormap DirectDraw palette.\n");
+	  return FALSE;
+	}
+
+      /* Clear our private installed colormap pointer */
+      pScreenPriv->pcmapInstalled = NULL;
+    }
+  
+  /* Release the palette */
+  IDirectDrawPalette_Release (pCmapPriv->lpDDPalette);
+ 
+  /* Invalidate the colormap privates */
+  pCmapPriv->lpDDPalette = NULL;
+
+  return TRUE;
+}
+
+
+/*
+ * Set pointers to our engine specific functions
+ */
+
+Bool
+winSetEngineFunctionsShadowDDNL (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  
+  /* Set our pointers */
+  pScreenPriv->pwinAllocateFB = winAllocateFBShadowDDNL;
+  pScreenPriv->pwinShadowUpdate = winShadowUpdateDDNL;
+  pScreenPriv->pwinCloseScreen = winCloseScreenShadowDDNL;
+  pScreenPriv->pwinInitVisuals = winInitVisualsShadowDDNL;
+  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModeShadowDDNL;
+  if (pScreenInfo->fFullScreen)
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
+  else
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
+  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitFB;
+  pScreenPriv->pwinBltExposedRegions = winBltExposedRegionsShadowDDNL;
+  pScreenPriv->pwinActivateApp = winActivateAppShadowDDNL;
+  pScreenPriv->pwinRedrawScreen = winRedrawScreenShadowDDNL;
+  pScreenPriv->pwinRealizeInstalledPalette
+    = winRealizeInstalledPaletteShadowDDNL;
+  pScreenPriv->pwinInstallColormap = winInstallColormapShadowDDNL;
+  pScreenPriv->pwinStoreColors = winStoreColorsShadowDDNL;
+  pScreenPriv->pwinCreateColormap = winCreateColormapShadowDDNL;
+  pScreenPriv->pwinDestroyColormap = winDestroyColormapShadowDDNL;
+  pScreenPriv->pwinHotKeyAltTab = (winHotKeyAltTabProcPtr) (void (*)(void))NoopDDA;
+  pScreenPriv->pwinCreatePrimarySurface = winCreatePrimarySurfaceShadowDDNL;
+  pScreenPriv->pwinReleasePrimarySurface = winReleasePrimarySurfaceShadowDDNL;
+#ifdef XWIN_MULTIWINDOW
+  pScreenPriv->pwinFinishCreateWindowsWindow
+    = winFinishCreateWindowsWindowDDNL;
+#endif
+
+  return TRUE;
+}
diff --git a/hw/xwin/winshadgdi.c b/hw/xwin/winshadgdi.c
new file mode 100644
index 0000000..04cc2f7
--- /dev/null
+++ b/hw/xwin/winshadgdi.c
@@ -0,0 +1,1324 @@
+/*
+ *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * External symbols
+ */
+
+#ifdef XWIN_MULTIWINDOW
+extern DWORD			g_dwCurrentThreadID;
+#endif
+extern HWND			g_hDlgExit;
+
+
+/*
+ * Local function prototypes
+ */
+
+#ifdef XWIN_MULTIWINDOW
+static wBOOL CALLBACK
+winRedrawAllProcShadowGDI (HWND hwnd, LPARAM lParam);
+
+static wBOOL CALLBACK
+winRedrawDamagedWindowShadowGDI (HWND hwnd, LPARAM lParam);
+#endif
+
+static Bool
+winAllocateFBShadowGDI (ScreenPtr pScreen);
+
+static void
+winShadowUpdateGDI (ScreenPtr pScreen, 
+		    shadowBufPtr pBuf);
+
+static Bool
+winCloseScreenShadowGDI (int nIndex, ScreenPtr pScreen);
+
+static Bool
+winInitVisualsShadowGDI (ScreenPtr pScreen);
+
+static Bool
+winAdjustVideoModeShadowGDI (ScreenPtr pScreen);
+
+static Bool
+winBltExposedRegionsShadowGDI (ScreenPtr pScreen);
+
+static Bool
+winActivateAppShadowGDI (ScreenPtr pScreen);
+
+static Bool
+winRedrawScreenShadowGDI (ScreenPtr pScreen);
+
+static Bool
+winRealizeInstalledPaletteShadowGDI (ScreenPtr pScreen);
+
+static Bool
+winInstallColormapShadowGDI (ColormapPtr pColormap);
+
+static Bool
+winStoreColorsShadowGDI (ColormapPtr pmap, 
+			 int ndef,
+			 xColorItem *pdefs);
+
+static Bool
+winCreateColormapShadowGDI (ColormapPtr pColormap);
+
+static Bool
+winDestroyColormapShadowGDI (ColormapPtr pColormap);
+
+
+/*
+ * Internal function to get the DIB format that is compatible with the screen
+ */
+
+static
+Bool
+winQueryScreenDIBFormat (ScreenPtr pScreen, BITMAPINFOHEADER *pbmih)
+{
+  winScreenPriv(pScreen);
+  HBITMAP		hbmp;
+#if CYGDEBUG
+  LPDWORD		pdw = NULL;
+#endif
+  
+  /* Create a memory bitmap compatible with the screen */
+  hbmp = CreateCompatibleBitmap (pScreenPriv->hdcScreen, 1, 1);
+  if (hbmp == NULL)
+    {
+      ErrorF ("winQueryScreenDIBFormat - CreateCompatibleBitmap failed\n");
+      return FALSE;
+    }
+  
+  /* Initialize our bitmap info header */
+  ZeroMemory (pbmih, sizeof (BITMAPINFOHEADER) + 256 * sizeof (RGBQUAD));
+  pbmih->biSize = sizeof (BITMAPINFOHEADER);
+
+  /* Get the biBitCount */
+  if (!GetDIBits (pScreenPriv->hdcScreen,
+		  hbmp,
+		  0, 1,
+		  NULL,
+		  (BITMAPINFO*) pbmih,
+		  DIB_RGB_COLORS))
+    {
+      ErrorF ("winQueryScreenDIBFormat - First call to GetDIBits failed\n");
+      DeleteObject (hbmp);
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  /* Get a pointer to bitfields */
+  pdw = (DWORD*) ((CARD8*)pbmih + sizeof (BITMAPINFOHEADER));
+
+  winDebug ("winQueryScreenDIBFormat - First call masks: %08x %08x %08x\n",
+	  pdw[0], pdw[1], pdw[2]);
+#endif
+
+  /* Get optimal color table, or the optimal bitfields */
+  if (!GetDIBits (pScreenPriv->hdcScreen,
+		  hbmp,
+		  0, 1,
+		  NULL,
+		  (BITMAPINFO*)pbmih,
+		  DIB_RGB_COLORS))
+    {
+      ErrorF ("winQueryScreenDIBFormat - Second call to GetDIBits "
+	      "failed\n");
+      DeleteObject (hbmp);
+      return FALSE;
+    }
+
+  /* Free memory */
+  DeleteObject (hbmp);
+  
+  return TRUE;
+}
+
+
+/*
+ * Internal function to determine the GDI bits per rgb and bit masks
+ */
+
+static
+Bool
+winQueryRGBBitsAndMasks (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  BITMAPINFOHEADER	*pbmih = NULL;
+  Bool			fReturn = TRUE;
+  LPDWORD		pdw = NULL;
+  DWORD			dwRedBits, dwGreenBits, dwBlueBits;
+
+  /* Color masks for 8 bpp are standardized */
+  if (GetDeviceCaps (pScreenPriv->hdcScreen, RASTERCAPS) & RC_PALETTE)
+    {
+      /* 
+       * RGB BPP for 8 bit palletes is always 8
+       * and the color masks are always 0.
+       */
+      pScreenPriv->dwBitsPerRGB = 8;
+      pScreenPriv->dwRedMask = 0x0L;
+      pScreenPriv->dwGreenMask = 0x0L;
+      pScreenPriv->dwBlueMask = 0x0L;
+      return TRUE;
+    }
+
+  /* Color masks for 24 bpp are standardized */
+  if (GetDeviceCaps (pScreenPriv->hdcScreen, PLANES)
+      * GetDeviceCaps (pScreenPriv->hdcScreen, BITSPIXEL) == 24)
+    {
+      ErrorF ("winQueryRGBBitsAndMasks - GetDeviceCaps (BITSPIXEL) "
+	      "returned 24 for the screen.  Using default 24bpp masks.\n");
+
+      /* 8 bits per primary color */
+      pScreenPriv->dwBitsPerRGB = 8;
+
+      /* Set screen privates masks */
+      pScreenPriv->dwRedMask = WIN_24BPP_MASK_RED;
+      pScreenPriv->dwGreenMask = WIN_24BPP_MASK_GREEN;
+      pScreenPriv->dwBlueMask = WIN_24BPP_MASK_BLUE;
+      
+      return TRUE;
+    }
+
+  /* Allocate a bitmap header and color table */
+  pbmih = (BITMAPINFOHEADER*) malloc (sizeof (BITMAPINFOHEADER)
+				      + 256  * sizeof (RGBQUAD));
+  if (pbmih == NULL)
+    {
+      ErrorF ("winQueryRGBBitsAndMasks - malloc failed\n");
+      return FALSE;
+    }
+
+  /* Get screen description */
+  if (winQueryScreenDIBFormat (pScreen, pbmih))
+    {
+      /* Get a pointer to bitfields */
+      pdw = (DWORD*) ((CARD8*)pbmih + sizeof (BITMAPINFOHEADER));
+      
+#if CYGDEBUG
+      winDebug ("%s - Masks: %08x %08x %08x\n", __FUNCTION__,
+	      pdw[0], pdw[1], pdw[2]);
+      winDebug ("%s - Bitmap: %dx%d %d bpp %d planes\n", __FUNCTION__,
+              pbmih->biWidth, pbmih->biHeight, pbmih->biBitCount, pbmih->biPlanes);
+      winDebug ("%s - Compression: %d %s\n", __FUNCTION__,
+              pbmih->biCompression,
+              (pbmih->biCompression == BI_RGB?"(BI_RGB)":
+               (pbmih->biCompression == BI_RLE8?"(BI_RLE8)":
+                (pbmih->biCompression == BI_RLE4?"(BI_RLE4)":
+                 (pbmih->biCompression == BI_BITFIELDS?"(BI_BITFIELDS)":""
+                 )))));
+#endif
+
+      /* Handle BI_RGB case, which is returned by Wine */
+      if (pbmih->biCompression == BI_RGB)
+        {
+	  dwRedBits = 5;
+	  dwGreenBits = 5;
+	  dwBlueBits = 5;
+	  
+	  pScreenPriv->dwBitsPerRGB = 5;
+	  
+	  /* Set screen privates masks */
+	  pScreenPriv->dwRedMask = 0x7c00;
+	  pScreenPriv->dwGreenMask = 0x03e0;
+	  pScreenPriv->dwBlueMask = 0x001f;
+        }
+      else 
+        {
+          /* Count the number of bits in each mask */
+          dwRedBits = winCountBits (pdw[0]);
+          dwGreenBits = winCountBits (pdw[1]);
+          dwBlueBits = winCountBits (pdw[2]);
+
+	  /* Find maximum bits per red, green, blue */
+	  if (dwRedBits > dwGreenBits && dwRedBits > dwBlueBits)
+	    pScreenPriv->dwBitsPerRGB = dwRedBits;
+	  else if (dwGreenBits > dwRedBits && dwGreenBits > dwBlueBits)
+	    pScreenPriv->dwBitsPerRGB = dwGreenBits;
+	  else
+	    pScreenPriv->dwBitsPerRGB = dwBlueBits;
+
+	  /* Set screen privates masks */
+	  pScreenPriv->dwRedMask = pdw[0];
+	  pScreenPriv->dwGreenMask = pdw[1];
+	  pScreenPriv->dwBlueMask = pdw[2];
+	}
+    }
+  else
+    {
+      ErrorF ("winQueryRGBBitsAndMasks - winQueryScreenDIBFormat failed\n");
+      free (pbmih);
+      fReturn = FALSE;
+    }
+
+  /* Free memory */
+  free (pbmih);
+
+  return fReturn;
+}
+
+
+#ifdef XWIN_MULTIWINDOW
+/*
+ * Redraw all ---?
+ */
+
+static wBOOL CALLBACK
+winRedrawAllProcShadowGDI (HWND hwnd, LPARAM lParam)
+{
+  if (hwnd == (HWND)lParam)
+    return TRUE;  
+  InvalidateRect (hwnd, NULL, FALSE);
+  UpdateWindow (hwnd);
+  return TRUE;
+}
+
+static wBOOL CALLBACK
+winRedrawDamagedWindowShadowGDI (HWND hwnd, LPARAM lParam)
+{
+  BoxPtr pDamage = (BoxPtr)lParam;
+  RECT rcClient, rcDamage, rcRedraw;
+  POINT topLeft, bottomRight;
+  
+  if (IsIconic (hwnd))
+    return TRUE; /* Don't care minimized windows */
+  
+  /* Convert the damaged area from Screen coords to Client coords */
+  topLeft.x = pDamage->x1; topLeft.y = pDamage->y1;
+  bottomRight.x = pDamage->x2; bottomRight.y = pDamage->y2;
+  topLeft.x += GetSystemMetrics (SM_XVIRTUALSCREEN);
+  bottomRight.x += GetSystemMetrics (SM_XVIRTUALSCREEN);
+  topLeft.y += GetSystemMetrics (SM_YVIRTUALSCREEN);
+  bottomRight.y += GetSystemMetrics (SM_YVIRTUALSCREEN);
+  ScreenToClient (hwnd, &topLeft);
+  ScreenToClient (hwnd, &bottomRight);
+  SetRect (&rcDamage, topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
+
+  GetClientRect (hwnd, &rcClient);
+
+  if (IntersectRect (&rcRedraw, &rcClient, &rcDamage))
+    {
+      InvalidateRect (hwnd, &rcRedraw, FALSE);
+      UpdateWindow (hwnd);
+    }
+  return TRUE;
+}
+#endif
+
+
+/*
+ * Allocate a DIB for the shadow framebuffer GDI server
+ */
+
+static Bool
+winAllocateFBShadowGDI (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  BITMAPINFOHEADER	*pbmih = NULL;
+  DIBSECTION		dibsection;
+  Bool			fReturn = TRUE;
+
+  /* Get device contexts for the screen and shadow bitmap */
+  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
+  pScreenPriv->hdcShadow = CreateCompatibleDC (pScreenPriv->hdcScreen);
+
+  /* Allocate bitmap info header */
+  pbmih = (BITMAPINFOHEADER*) malloc (sizeof (BITMAPINFOHEADER)
+				      + 256 * sizeof (RGBQUAD));
+  if (pbmih == NULL)
+    {
+      ErrorF ("winAllocateFBShadowGDI - malloc () failed\n");
+      return FALSE;
+    }
+
+  /* Query the screen format */
+  fReturn = winQueryScreenDIBFormat (pScreen, pbmih);
+
+  /* Describe shadow bitmap to be created */
+  pbmih->biWidth = pScreenInfo->dwWidth;
+  pbmih->biHeight = -pScreenInfo->dwHeight;
+  
+  ErrorF ("winAllocateFBShadowGDI - Creating DIB with width: %d height: %d "
+	  "depth: %d\n",
+	  (int) pbmih->biWidth, (int) -pbmih->biHeight, pbmih->biBitCount);
+
+  /* Create a DI shadow bitmap with a bit pointer */
+  pScreenPriv->hbmpShadow = CreateDIBSection (pScreenPriv->hdcScreen,
+					      (BITMAPINFO *) pbmih,
+					      DIB_RGB_COLORS,
+					      (VOID**) &pScreenInfo->pfb,
+					      NULL,
+					      0);
+  if (pScreenPriv->hbmpShadow == NULL || pScreenInfo->pfb == NULL)
+    {
+      winW32Error (2, "winAllocateFBShadowGDI - CreateDIBSection failed:");
+      return FALSE;
+    }
+  else
+    {
+#if CYGDEBUG
+      winDebug ("winAllocateFBShadowGDI - Shadow buffer allocated\n");
+#endif
+    }
+
+  /* Get information about the bitmap that was allocated */
+  GetObject (pScreenPriv->hbmpShadow,
+	     sizeof (dibsection),
+	     &dibsection);
+
+#if CYGDEBUG || YES
+  /* Print information about bitmap allocated */
+  winDebug ("winAllocateFBShadowGDI - Dibsection width: %d height: %d "
+	  "depth: %d size image: %d\n",
+	  (int) dibsection.dsBmih.biWidth, (int) dibsection.dsBmih.biHeight,
+	  dibsection.dsBmih.biBitCount,
+	  (int) dibsection.dsBmih.biSizeImage);
+#endif
+
+  /* Select the shadow bitmap into the shadow DC */
+  SelectObject (pScreenPriv->hdcShadow,
+		pScreenPriv->hbmpShadow);
+
+#if CYGDEBUG
+  winDebug ("winAllocateFBShadowGDI - Attempting a shadow blit\n");
+#endif
+
+  /* Do a test blit from the shadow to the screen, I think */
+  fReturn = BitBlt (pScreenPriv->hdcScreen,
+		    0, 0,
+		    pScreenInfo->dwWidth, pScreenInfo->dwHeight,
+		    pScreenPriv->hdcShadow,
+		    0, 0,
+		    SRCCOPY);
+  if (fReturn)
+    {
+#if CYGDEBUG
+      winDebug ("winAllocateFBShadowGDI - Shadow blit success\n");
+#endif
+    }
+  else
+    {
+      winW32Error (2, "winAllocateFBShadowGDI - Shadow blit failure\n");
+#if 0      
+      return FALSE;
+#else 
+      /* ago: ignore this error. The blit fails with wine, but does not 
+       * cause any problems later. */
+
+      fReturn = TRUE;
+#endif      
+    }
+
+  /* Look for height weirdness */
+  if (dibsection.dsBmih.biHeight < 0)
+    {
+      dibsection.dsBmih.biHeight = -dibsection.dsBmih.biHeight;
+    }
+
+  /* Set screeninfo stride */
+  pScreenInfo->dwStride = ((dibsection.dsBmih.biSizeImage
+			    / dibsection.dsBmih.biHeight)
+			   * 8) / pScreenInfo->dwBPP;
+
+#if CYGDEBUG || YES
+  winDebug ("winAllocateFBShadowGDI - Created shadow stride: %d\n",
+	  (int) pScreenInfo->dwStride);
+#endif
+
+  /* See if the shadow bitmap will be larger than the DIB size limit */
+  if (pScreenInfo->dwWidth * pScreenInfo->dwHeight * pScreenInfo->dwBPP
+      >= WIN_DIB_MAXIMUM_SIZE)
+    {
+      ErrorF ("winAllocateFBShadowGDI - Requested DIB (bitmap) "
+	      "will be larger than %d MB.  The surface may fail to be "
+	      "allocated on Windows 95, 98, or Me, due to a %d MB limit in "
+	      "DIB size.  This limit does not apply to Windows NT/2000, and "
+	      "this message may be ignored on those platforms.\n",
+	      WIN_DIB_MAXIMUM_SIZE_MB, WIN_DIB_MAXIMUM_SIZE_MB);
+    }
+
+  /* Determine our color masks */
+  if (!winQueryRGBBitsAndMasks (pScreen))
+    {
+      ErrorF ("winAllocateFBShadowGDI - winQueryRGBBitsAndMasks failed\n");
+      return FALSE;
+    }
+
+#ifdef XWIN_MULTIWINDOW
+  /* Redraw all windows */
+  if (pScreenInfo->fMultiWindow)
+    EnumThreadWindows (g_dwCurrentThreadID, winRedrawAllProcShadowGDI, 0);
+#endif
+
+  return fReturn;
+}
+
+
+/*
+ * Blit the damaged regions of the shadow fb to the screen
+ */
+
+static void
+winShadowUpdateGDI (ScreenPtr pScreen, 
+		    shadowBufPtr pBuf)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  RegionPtr		damage = &pBuf->damage;
+  DWORD			dwBox = REGION_NUM_RECTS (damage);
+  BoxPtr		pBox = REGION_RECTS (damage);
+  int			x, y, w, h;
+  HRGN			hrgnTemp = NULL, hrgnCombined = NULL;
+#ifdef XWIN_UPDATESTATS
+  static DWORD		s_dwNonUnitRegions = 0;
+  static DWORD		s_dwTotalUpdates = 0;
+  static DWORD		s_dwTotalBoxes = 0;
+#endif
+  BoxPtr		pBoxExtents = REGION_EXTENTS (pScreen, damage);
+
+  /*
+   * Return immediately if the app is not active
+   * and we are fullscreen, or if we have a bad display depth
+   */
+  if ((!pScreenPriv->fActive && pScreenInfo->fFullScreen)
+      || pScreenPriv->fBadDepth) return;
+
+#ifdef XWIN_UPDATESTATS
+  ++s_dwTotalUpdates;
+  s_dwTotalBoxes += dwBox;
+
+  if (dwBox != 1)
+    {
+      ++s_dwNonUnitRegions;
+      ErrorF ("winShadowUpdatGDI - dwBox: %d\n", dwBox);
+    }
+  
+  if ((s_dwTotalUpdates % 100) == 0)
+    ErrorF ("winShadowUpdateGDI - %d%% non-unity regions, avg boxes: %d "
+	    "nu: %d tu: %d\n",
+	    (s_dwNonUnitRegions * 100) / s_dwTotalUpdates,
+	    s_dwTotalBoxes / s_dwTotalUpdates,
+	    s_dwNonUnitRegions, s_dwTotalUpdates);
+#endif /* XWIN_UPDATESTATS */
+
+  /*
+   * Handle small regions with multiple blits,
+   * handle large regions by creating a clipping region and 
+   * doing a single blit constrained to that clipping region.
+   */
+  if (!pScreenInfo->fMultiWindow &&
+      (pScreenInfo->dwClipUpdatesNBoxes == 0 ||
+      dwBox < pScreenInfo->dwClipUpdatesNBoxes))
+    {
+      /* Loop through all boxes in the damaged region */
+      while (dwBox--)
+	{
+	  /*
+	   * Calculate x offset, y offset, width, and height for
+	   * current damage box
+	   */
+	  x = pBox->x1;
+	  y = pBox->y1;
+	  w = pBox->x2 - pBox->x1;
+	  h = pBox->y2 - pBox->y1;
+	  
+	  BitBlt (pScreenPriv->hdcScreen,
+		  x, y,
+		  w, h,
+		  pScreenPriv->hdcShadow,
+		  x, y,
+		  SRCCOPY);
+	  
+	  /* Get a pointer to the next box */
+	  ++pBox;
+	}
+    }
+  else if (!pScreenInfo->fMultiWindow)
+    {
+      /* Compute a GDI region from the damaged region */
+      hrgnCombined = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
+      dwBox--;
+      pBox++;
+      while (dwBox--)
+	{
+	  hrgnTemp = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
+	  CombineRgn (hrgnCombined, hrgnCombined, hrgnTemp, RGN_OR);
+	  DeleteObject (hrgnTemp);
+	  pBox++;
+	}
+      
+      /* Install the GDI region as a clipping region */
+      SelectClipRgn (pScreenPriv->hdcScreen, hrgnCombined);
+      DeleteObject (hrgnCombined);
+      hrgnCombined = NULL;
+      
+      /*
+       * Blit the shadow buffer to the screen,
+       * constrained to the clipping region.
+       */
+      BitBlt (pScreenPriv->hdcScreen,
+	      pBoxExtents->x1, pBoxExtents->y1,
+	      pBoxExtents->x2 - pBoxExtents->x1,
+	      pBoxExtents->y2 - pBoxExtents->y1,
+	      pScreenPriv->hdcShadow,
+	      pBoxExtents->x1, pBoxExtents->y1,
+	      SRCCOPY);
+
+      /* Reset the clip region */
+      SelectClipRgn (pScreenPriv->hdcScreen, NULL);
+    }
+
+#ifdef XWIN_MULTIWINDOW
+  /* Redraw all multiwindow windows */
+  if (pScreenInfo->fMultiWindow)
+    EnumThreadWindows (g_dwCurrentThreadID,
+		       winRedrawDamagedWindowShadowGDI,
+		       (LPARAM)pBoxExtents);
+#endif
+}
+
+
+/* See Porting Layer Definition - p. 33 */
+/*
+ * We wrap whatever CloseScreen procedure was specified by fb;
+ * a pointer to said procedure is stored in our privates.
+ */
+
+static Bool
+winCloseScreenShadowGDI (int nIndex, ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  Bool			fReturn;
+
+#if CYGDEBUG
+  winDebug ("winCloseScreenShadowGDI - Freeing screen resources\n");
+#endif
+
+  /* Flag that the screen is closed */
+  pScreenPriv->fClosed = TRUE;
+  pScreenPriv->fActive = FALSE;
+
+  /* Call the wrapped CloseScreen procedure */
+  WIN_UNWRAP(CloseScreen);
+  fReturn = (*pScreen->CloseScreen) (nIndex, pScreen);
+
+  /* Delete the window property */
+  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
+
+  /* Free the shadow DC; which allows the bitmap to be freed */
+  DeleteDC (pScreenPriv->hdcShadow);
+  
+  /* Free the shadow bitmap */
+  DeleteObject (pScreenPriv->hbmpShadow);
+
+  /* Free the screen DC */
+  ReleaseDC (pScreenPriv->hwndScreen, pScreenPriv->hdcScreen);
+
+  /* Delete tray icon, if we have one */
+  if (!pScreenInfo->fNoTrayIcon)
+    winDeleteNotifyIcon (pScreenPriv);
+
+  /* Free the exit confirmation dialog box, if it exists */
+  if (g_hDlgExit != NULL)
+    {
+      DestroyWindow (g_hDlgExit);
+      g_hDlgExit = NULL;
+    }
+
+  /* Kill our window */
+  if (pScreenPriv->hwndScreen)
+    {
+      DestroyWindow (pScreenPriv->hwndScreen);
+      pScreenPriv->hwndScreen = NULL;
+    }
+
+#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
+  /* Destroy the thread startup mutex */
+  pthread_mutex_destroy (&pScreenPriv->pmServerStarted);
+#endif
+
+  /* Invalidate our screeninfo's pointer to the screen */
+  pScreenInfo->pScreen = NULL;
+
+  /* Invalidate the ScreenInfo's fb pointer */
+  pScreenInfo->pfb = NULL;
+
+  /* Free the screen privates for this screen */
+  free ((pointer) pScreenPriv);
+
+  return fReturn;
+}
+
+
+/*
+ * Tell mi what sort of visuals we need.
+ * 
+ * Generally we only need one visual, as our screen can only
+ * handle one format at a time, I believe.  You may want
+ * to verify that last sentence.
+ */
+
+static Bool
+winInitVisualsShadowGDI (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+
+  /* Display debugging information */
+  ErrorF ("winInitVisualsShadowGDI - Masks %08x %08x %08x BPRGB %d d %d "
+	  "bpp %d\n",
+	  (unsigned int) pScreenPriv->dwRedMask,
+	  (unsigned int) pScreenPriv->dwGreenMask,
+	  (unsigned int) pScreenPriv->dwBlueMask,
+	  (int) pScreenPriv->dwBitsPerRGB,
+	  (int) pScreenInfo->dwDepth,
+	  (int) pScreenInfo->dwBPP);
+
+  /* Create a single visual according to the Windows screen depth */
+  switch (pScreenInfo->dwDepth)
+    {
+    case 24:
+    case 16:
+    case 15:
+#if defined(XFree86Server)
+      /* Setup the real visual */
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     TrueColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     -1,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowGDI - miSetVisualTypesAndMasks "
+		  "failed\n");
+	  return FALSE;
+	}
+
+#ifdef XWIN_EMULATEPSEUDO
+      if (!pScreenInfo->fEmulatePseudo)
+	break;
+
+      /* Setup a pseudocolor visual */
+      if (!miSetVisualTypesAndMasks (8,
+				     PseudoColorMask,
+				     8,
+				     -1,
+				     0,
+				     0,
+				     0))
+	{
+	  ErrorF ("winInitVisualsShadowGDI - miSetVisualTypesAndMasks "
+		  "failed for PseudoColor\n");
+	  return FALSE;
+	}
+#endif
+#else /* XFree86Server */
+      /* Setup the real visual */
+      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     TrueColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowGDI - fbSetVisualTypesAndMasks "
+		  "failed for TrueColor\n");
+	  return FALSE;
+	}
+
+#ifdef XWIN_EMULATEPSEUDO
+      if (!pScreenInfo->fEmulatePseudo)
+	break;
+
+      /* Setup a pseudocolor visual */
+      if (!fbSetVisualTypesAndMasks (8,
+				     PseudoColorMask,
+				     8,
+				     0,
+				     0,
+				     0))
+	{
+	  ErrorF ("winInitVisualsShadowGDI - fbSetVisualTypesAndMasks "
+		  "failed for PseudoColor\n");
+	  return FALSE;
+	}
+#endif
+#endif /* XFree86Server */
+      break;
+
+    case 8:
+#if defined(XFree86Server)
+      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     PseudoColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     PseudoColor,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowGDI - miSetVisualTypesAndMasks "
+		  "failed\n");
+	  return FALSE;
+	}
+#else /* XFree86Server */
+      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
+				     PseudoColorMask,
+				     pScreenPriv->dwBitsPerRGB,
+				     pScreenPriv->dwRedMask,
+				     pScreenPriv->dwGreenMask,
+				     pScreenPriv->dwBlueMask))
+	{
+	  ErrorF ("winInitVisualsShadowGDI - fbSetVisualTypesAndMasks "
+		  "failed\n");
+	  return FALSE;
+	}
+#endif
+      break;
+
+    default:
+      ErrorF ("winInitVisualsShadowGDI - Unknown screen depth\n");
+      return FALSE;
+    }
+
+#if CYGDEBUG
+  winDebug ("winInitVisualsShadowGDI - Returning\n");
+#endif
+
+  return TRUE;
+}
+
+
+/*
+ * Adjust the proposed video mode
+ */
+
+static Bool
+winAdjustVideoModeShadowGDI (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  HDC			hdc;
+  DWORD			dwBPP;
+  
+  hdc = GetDC (NULL);
+
+  /* We're in serious trouble if we can't get a DC */
+  if (hdc == NULL)
+    {
+      ErrorF ("winAdjustVideoModeShadowGDI - GetDC () failed\n");
+      return FALSE;
+    }
+
+  /* Query GDI for current display depth */
+  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
+
+  /* GDI cannot change the screen depth */
+  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
+    {
+      /* No -depth parameter passed, let the user know the depth being used */
+      ErrorF ("winAdjustVideoModeShadowGDI - Using Windows display "
+	      "depth of %d bits per pixel\n", (int) dwBPP);
+
+      /* Use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+  else if (dwBPP != pScreenInfo->dwBPP)
+    {
+      /* Warn user if GDI depth is different than -depth parameter */
+      ErrorF ("winAdjustVideoModeShadowGDI - Command line bpp: %d, "\
+	      "using bpp: %d\n", (int) pScreenInfo->dwBPP, (int) dwBPP);
+
+      /* We'll use GDI's depth */
+      pScreenInfo->dwBPP = dwBPP;
+    }
+  
+  /* Release our DC */
+  ReleaseDC (NULL, hdc);
+  hdc = NULL;
+
+  return TRUE;
+}
+
+
+/*
+ * Blt exposed regions to the screen
+ */
+
+static Bool
+winBltExposedRegionsShadowGDI (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  winPrivCmapPtr	pCmapPriv = NULL;
+  HDC			hdcUpdate;
+  PAINTSTRUCT		ps;
+
+  /* BeginPaint gives us an hdc that clips to the invalidated region */
+  hdcUpdate = BeginPaint (pScreenPriv->hwndScreen, &ps);
+
+  /* Realize the palette, if we have one */
+  if (pScreenPriv->pcmapInstalled != NULL)
+    {
+      pCmapPriv = winGetCmapPriv (pScreenPriv->pcmapInstalled);
+      
+      SelectPalette (hdcUpdate, pCmapPriv->hPalette, FALSE);
+      RealizePalette (hdcUpdate);
+    }
+
+  /* Our BitBlt will be clipped to the invalidated region */
+  BitBlt (hdcUpdate,
+	  0, 0,
+	  pScreenInfo->dwWidth, pScreenInfo->dwHeight,
+	  pScreenPriv->hdcShadow,
+	  0, 0,
+	  SRCCOPY);
+
+  /* EndPaint frees the DC */
+  EndPaint (pScreenPriv->hwndScreen, &ps);
+
+#ifdef XWIN_MULTIWINDOW
+  /* Redraw all windows */
+  if (pScreenInfo->fMultiWindow)
+    EnumThreadWindows(g_dwCurrentThreadID, winRedrawAllProcShadowGDI, 
+            (LPARAM)pScreenPriv->hwndScreen);
+#endif
+
+  return TRUE;
+}
+
+
+/*
+ * Do any engine-specific appliation-activation processing
+ */
+
+static Bool
+winActivateAppShadowGDI (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+
+  /*
+   * 2004/04/12 - Harold - We perform the restoring or minimizing
+   * manually for ShadowGDI in fullscreen modes so that this engine
+   * will perform just like ShadowDD and ShadowDDNL in fullscreen mode;
+   * if we do not do this then our fullscreen window will appear in the
+   * z-order when it is deactivated and it can be uncovered by resizing
+   * or minimizing another window that is on top of it, which is not how
+   * the DirectDraw engines work.  Therefore we keep this code here to
+   * make sure that all engines work the same in fullscreen mode.
+   */
+
+  /*
+   * Are we active?
+   * Are we fullscreen?
+   */
+  if (pScreenPriv->fActive
+      && pScreenInfo->fFullScreen)
+    {
+      /*
+       * Activating, attempt to bring our window 
+       * to the top of the display
+       */
+      ShowWindow (pScreenPriv->hwndScreen, SW_RESTORE);
+    }
+  else if (!pScreenPriv->fActive
+	   && pScreenInfo->fFullScreen)
+    {
+      /*
+       * Deactivating, stuff our window onto the
+       * task bar.
+       */
+      ShowWindow (pScreenPriv->hwndScreen, SW_MINIMIZE);
+    }
+
+  return TRUE;
+}
+
+
+/*
+ * Reblit the shadow framebuffer to the screen.
+ */
+
+static Bool
+winRedrawScreenShadowGDI (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+
+  /* Redraw the whole window, to take account for the new colors */
+  BitBlt (pScreenPriv->hdcScreen,
+	  0, 0,
+	  pScreenInfo->dwWidth, pScreenInfo->dwHeight,
+	  pScreenPriv->hdcShadow,
+	  0, 0,
+	  SRCCOPY);
+
+#ifdef XWIN_MULTIWINDOW
+  /* Redraw all windows */
+  if (pScreenInfo->fMultiWindow)
+    EnumThreadWindows(g_dwCurrentThreadID, winRedrawAllProcShadowGDI, 0);
+#endif
+
+  return TRUE;
+}
+
+
+
+/*
+ * Realize the currently installed colormap
+ */
+
+static Bool
+winRealizeInstalledPaletteShadowGDI (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winPrivCmapPtr	pCmapPriv = NULL;
+
+#if CYGDEBUG
+  winDebug ("winRealizeInstalledPaletteShadowGDI\n");
+#endif
+
+  /* Don't do anything if there is not a colormap */
+  if (pScreenPriv->pcmapInstalled == NULL)
+    {
+#if CYGDEBUG
+      winDebug ("winRealizeInstalledPaletteShadowGDI - No colormap "
+	      "installed\n");
+#endif
+      return TRUE;
+    }
+
+  pCmapPriv = winGetCmapPriv (pScreenPriv->pcmapInstalled);
+  
+  /* Realize our palette for the screen */
+  if (RealizePalette (pScreenPriv->hdcScreen) == GDI_ERROR)
+    {
+      ErrorF ("winRealizeInstalledPaletteShadowGDI - RealizePalette () "
+	      "failed\n");
+      return FALSE;
+    }
+  
+  /* Set the DIB color table */
+  if (SetDIBColorTable (pScreenPriv->hdcShadow,
+			0,
+			WIN_NUM_PALETTE_ENTRIES,
+			pCmapPriv->rgbColors) == 0)
+    {
+      ErrorF ("winRealizeInstalledPaletteShadowGDI - SetDIBColorTable () "
+	      "failed\n");
+      return FALSE;
+    }
+  
+  return TRUE;
+}
+
+
+/*
+ * Install the specified colormap
+ */
+
+static Bool
+winInstallColormapShadowGDI (ColormapPtr pColormap)
+{
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  winCmapPriv(pColormap);
+
+  /*
+   * Tell Windows to install the new colormap
+   */
+  if (SelectPalette (pScreenPriv->hdcScreen,
+		     pCmapPriv->hPalette,
+		     FALSE) == NULL)
+    {
+      ErrorF ("winInstallColormapShadowGDI - SelectPalette () failed\n");
+      return FALSE;
+    }
+      
+  /* Realize the palette */
+  if (GDI_ERROR == RealizePalette (pScreenPriv->hdcScreen))
+    {
+      ErrorF ("winInstallColormapShadowGDI - RealizePalette () failed\n");
+      return FALSE;
+    }
+
+  /* Set the DIB color table */
+  if (SetDIBColorTable (pScreenPriv->hdcShadow,
+			0,
+			WIN_NUM_PALETTE_ENTRIES,
+			pCmapPriv->rgbColors) == 0)
+    {
+      ErrorF ("winInstallColormapShadowGDI - SetDIBColorTable () failed\n");
+      return FALSE;
+    }
+
+  /* Redraw the whole window, to take account for the new colors */
+  BitBlt (pScreenPriv->hdcScreen,
+	  0, 0,
+	  pScreenInfo->dwWidth, pScreenInfo->dwHeight,
+	  pScreenPriv->hdcShadow,
+	  0, 0,
+	  SRCCOPY);
+
+  /* Save a pointer to the newly installed colormap */
+  pScreenPriv->pcmapInstalled = pColormap;
+
+#ifdef XWIN_MULTIWINDOW
+  /* Redraw all windows */
+  if (pScreenInfo->fMultiWindow)
+    EnumThreadWindows (g_dwCurrentThreadID, winRedrawAllProcShadowGDI, 0);
+#endif
+
+  return TRUE;
+}
+
+
+/*
+ * Store the specified colors in the specified colormap
+ */
+
+static Bool
+winStoreColorsShadowGDI (ColormapPtr pColormap,
+			 int ndef,
+			 xColorItem *pdefs)
+{
+  ScreenPtr		pScreen = pColormap->pScreen;
+  winScreenPriv(pScreen);
+  winCmapPriv(pColormap);
+  ColormapPtr curpmap = pScreenPriv->pcmapInstalled;
+  
+  /* Put the X colormap entries into the Windows logical palette */
+  if (SetPaletteEntries (pCmapPriv->hPalette,
+			 pdefs[0].pixel,
+			 ndef,
+			 pCmapPriv->peColors + pdefs[0].pixel) == 0)
+    {
+      ErrorF ("winStoreColorsShadowGDI - SetPaletteEntries () failed\n");
+      return FALSE;
+    }
+
+  /* Don't install the Windows palette if the colormap is not installed */
+  if (pColormap != curpmap)
+    {
+      return TRUE;
+    }
+
+  /* Try to install the newly modified colormap */
+  if (!winInstallColormapShadowGDI (pColormap))
+    {
+      ErrorF ("winInstallColormapShadowGDI - winInstallColormapShadowGDI "
+	      "failed\n");
+      return FALSE;
+    }
+
+#if 0
+  /* Tell Windows that the palette has changed */
+  RealizePalette (pScreenPriv->hdcScreen);
+  
+  /* Set the DIB color table */
+  if (SetDIBColorTable (pScreenPriv->hdcShadow,
+			pdefs[0].pixel,
+			ndef,
+			pCmapPriv->rgbColors + pdefs[0].pixel) == 0)
+    {
+      ErrorF ("winInstallColormapShadowGDI - SetDIBColorTable () failed\n");
+      return FALSE;
+    }
+
+  /* Save a pointer to the newly installed colormap */
+  pScreenPriv->pcmapInstalled = pColormap;
+#endif
+
+  return TRUE;
+}
+
+
+/*
+ * Colormap initialization procedure
+ */
+
+static Bool
+winCreateColormapShadowGDI (ColormapPtr pColormap)
+{
+  LPLOGPALETTE		lpPaletteNew = NULL;
+  DWORD			dwEntriesMax;
+  VisualPtr		pVisual;
+  HPALETTE		hpalNew = NULL;
+  winCmapPriv(pColormap);
+
+  /* Get a pointer to the visual that the colormap belongs to */
+  pVisual = pColormap->pVisual;
+
+  /* Get the maximum number of palette entries for this visual */
+  dwEntriesMax = pVisual->ColormapEntries;
+
+  /* Allocate a Windows logical color palette with max entries */
+  lpPaletteNew = malloc (sizeof (LOGPALETTE)
+			 + (dwEntriesMax - 1) * sizeof (PALETTEENTRY));
+  if (lpPaletteNew == NULL)
+    {
+      ErrorF ("winCreateColormapShadowGDI - Couldn't allocate palette "
+	      "with %d entries\n",
+	      (int) dwEntriesMax);
+      return FALSE;
+    }
+
+  /* Zero out the colormap */
+  ZeroMemory (lpPaletteNew, sizeof (LOGPALETTE)
+	      + (dwEntriesMax - 1) * sizeof (PALETTEENTRY));
+  
+  /* Set the logical palette structure */
+  lpPaletteNew->palVersion = 0x0300;
+  lpPaletteNew->palNumEntries = dwEntriesMax;
+
+  /* Tell Windows to create the palette */
+  hpalNew = CreatePalette (lpPaletteNew);
+  if (hpalNew == NULL)
+    {
+      ErrorF ("winCreateColormapShadowGDI - CreatePalette () failed\n");
+      free (lpPaletteNew);
+      return FALSE;
+    }
+
+  /* Save the Windows logical palette handle in the X colormaps' privates */
+  pCmapPriv->hPalette = hpalNew;
+
+  /* Free the palette initialization memory */
+  free (lpPaletteNew);
+
+  return TRUE;
+}
+
+
+/*
+ * Colormap destruction procedure
+ */
+
+static Bool
+winDestroyColormapShadowGDI (ColormapPtr pColormap)
+{
+  winScreenPriv(pColormap->pScreen);
+  winCmapPriv(pColormap);
+
+  /*
+   * Is colormap to be destroyed the default?
+   *
+   * Non-default colormaps should have had winUninstallColormap
+   * called on them before we get here.  The default colormap
+   * will not have had winUninstallColormap called on it.  Thus,
+   * we need to handle the default colormap in a special way.
+   */
+  if (pColormap->flags & IsDefault)
+    {
+#if CYGDEBUG
+      winDebug ("winDestroyColormapShadowGDI - Destroying default "
+	      "colormap\n");
+#endif
+      
+      /*
+       * FIXME: Walk the list of all screens, popping the default
+       * palette out of each screen device context.
+       */
+      
+      /* Pop the palette out of the device context */
+      SelectPalette (pScreenPriv->hdcScreen,
+		     GetStockObject (DEFAULT_PALETTE),
+		     FALSE);
+
+      /* Clear our private installed colormap pointer */
+      pScreenPriv->pcmapInstalled = NULL;
+    }
+  
+  /* Try to delete the logical palette */
+  if (DeleteObject (pCmapPriv->hPalette) == 0)
+    {
+      ErrorF ("winDestroyColormap - DeleteObject () failed\n");
+      return FALSE;
+    }
+  
+  /* Invalidate the colormap privates */
+  pCmapPriv->hPalette = NULL;
+
+  return TRUE;
+}
+
+
+/*
+ * Set engine specific funtions
+ */
+
+Bool
+winSetEngineFunctionsShadowGDI (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  
+  /* Set our pointers */
+  pScreenPriv->pwinAllocateFB = winAllocateFBShadowGDI;
+  pScreenPriv->pwinShadowUpdate = winShadowUpdateGDI;
+  pScreenPriv->pwinCloseScreen = winCloseScreenShadowGDI;
+  pScreenPriv->pwinInitVisuals = winInitVisualsShadowGDI;
+  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModeShadowGDI;
+  if (pScreenInfo->fFullScreen)
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
+  else
+    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
+  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitFB;
+  pScreenPriv->pwinBltExposedRegions = winBltExposedRegionsShadowGDI;
+  pScreenPriv->pwinActivateApp = winActivateAppShadowGDI;
+  pScreenPriv->pwinRedrawScreen = winRedrawScreenShadowGDI;
+  pScreenPriv->pwinRealizeInstalledPalette = 
+    winRealizeInstalledPaletteShadowGDI;
+  pScreenPriv->pwinInstallColormap = winInstallColormapShadowGDI;
+  pScreenPriv->pwinStoreColors = winStoreColorsShadowGDI;
+  pScreenPriv->pwinCreateColormap = winCreateColormapShadowGDI;
+  pScreenPriv->pwinDestroyColormap = winDestroyColormapShadowGDI;
+  pScreenPriv->pwinHotKeyAltTab = (winHotKeyAltTabProcPtr) (void (*)(void))NoopDDA;
+  pScreenPriv->pwinCreatePrimarySurface
+    = (winCreatePrimarySurfaceProcPtr) (void (*)(void))NoopDDA;
+  pScreenPriv->pwinReleasePrimarySurface
+    = (winReleasePrimarySurfaceProcPtr) (void (*)(void))NoopDDA;
+#ifdef XWIN_MULTIWINDOW
+  pScreenPriv->pwinFinishCreateWindowsWindow =
+    (winFinishCreateWindowsWindowProcPtr) (void (*)(void))NoopDDA;
+#endif
+
+  return TRUE;
+}
diff --git a/hw/xwin/wintrayicon.c b/hw/xwin/wintrayicon.c
new file mode 100755
index 0000000..054a8e9
--- /dev/null
+++ b/hw/xwin/wintrayicon.c
@@ -0,0 +1,210 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Early Ehlinger
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include <shellapi.h>
+#include "winprefs.h"
+
+/*
+ * Initialize the tray icon
+ */
+
+void
+winInitNotifyIcon (winPrivScreenPtr pScreenPriv)
+{
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  NOTIFYICONDATA	nid = {0};
+  
+  nid.cbSize = sizeof (NOTIFYICONDATA);
+  nid.hWnd = pScreenPriv->hwndScreen;
+  nid.uID = pScreenInfo->dwScreen;
+  nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
+  nid.uCallbackMessage = WM_TRAYICON;
+  nid.hIcon = (HICON)winTaskbarIcon ();
+
+  /* Save handle to the icon so it can be freed later */
+  pScreenPriv->hiconNotifyIcon = nid.hIcon;
+
+  /* Set display and screen-specific tooltip text */
+  snprintf (nid.szTip,
+	    sizeof (nid.szTip),
+	    PROJECT_NAME " Server - %s:%d",
+	    display, 
+	    (int) pScreenInfo->dwScreen);
+
+  /* Add the tray icon */
+  if (!Shell_NotifyIcon (NIM_ADD, &nid))
+    ErrorF ("winInitNotifyIcon - Shell_NotifyIcon Failed\n");
+}
+
+
+/*
+ * Delete the tray icon
+ */
+
+void
+winDeleteNotifyIcon (winPrivScreenPtr pScreenPriv)
+{
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+  NOTIFYICONDATA	nid = {0};
+  
+#if 0
+  ErrorF ("winDeleteNotifyIcon\n");
+#endif
+
+  nid.cbSize = sizeof (NOTIFYICONDATA);
+  nid.hWnd = pScreenPriv->hwndScreen;
+  nid.uID = pScreenInfo->dwScreen;
+  
+  /* Delete the tray icon */
+  if (!Shell_NotifyIcon (NIM_DELETE, &nid))
+    {
+      ErrorF ("winDeleteNotifyIcon - Shell_NotifyIcon failed\n");
+      return;
+    }
+
+  /* Free the icon that was loaded */
+  if (pScreenPriv->hiconNotifyIcon != NULL
+      && DestroyIcon (pScreenPriv->hiconNotifyIcon) == 0)
+    {
+      ErrorF ("winDeleteNotifyIcon - DestroyIcon failed\n");
+    }
+  pScreenPriv->hiconNotifyIcon = NULL;
+}
+
+
+/*
+ * Process messages intended for the tray icon
+ */
+
+LRESULT
+winHandleIconMessage (HWND hwnd, UINT message,
+		      WPARAM wParam, LPARAM lParam,
+		      winPrivScreenPtr pScreenPriv)
+{
+#if defined(XWIN_MULTIWINDOWEXTWM) || defined(XWIN_MULTIWINDOW)
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
+#endif
+
+  switch (lParam)
+    {
+    case WM_LBUTTONUP:
+      /* Restack and bring all windows to top */
+      SetForegroundWindow (hwnd);
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+      if (pScreenInfo->fMWExtWM)
+	winMWExtWMRestackWindows (pScreenInfo->pScreen);
+#endif
+      break;
+
+    case WM_LBUTTONDBLCLK:
+      /* Display Exit dialog box */
+      winDisplayExitDialog (pScreenPriv);
+      break;
+
+    case WM_RBUTTONUP:
+      {
+	POINT		ptCursor;
+	HMENU		hmenuPopup;
+	HMENU		hmenuTray;
+
+	/* Get cursor position */
+	GetCursorPos (&ptCursor);
+
+	/* Load tray icon menu resource */
+	hmenuPopup = LoadMenu (g_hInstance,
+			       MAKEINTRESOURCE(IDM_TRAYICON_MENU));
+	if (!hmenuPopup)
+	  ErrorF ("winHandleIconMessage - LoadMenu failed\n");
+
+	/* Get actual tray icon menu */
+	hmenuTray = GetSubMenu (hmenuPopup, 0);
+
+#ifdef XWIN_MULTIWINDOW
+	/* Check for MultiWindow mode */
+	if (pScreenInfo->fMultiWindow)
+	  {
+	    MENUITEMINFO		mii = {0};
+	    
+	    /* Root is shown, remove the check box */
+	    
+	    /* Setup menu item info structure */
+	    mii.cbSize = sizeof (MENUITEMINFO);
+	    mii.fMask = MIIM_STATE;
+	    mii.fState = MFS_CHECKED;
+	    
+	    /* Unheck box if root is shown */
+	    if (pScreenPriv->fRootWindowShown)
+	      mii.fState = MFS_UNCHECKED;
+
+	    /* Set menu state */
+	    SetMenuItemInfo (hmenuTray, ID_APP_HIDE_ROOT, FALSE, &mii);
+	  }
+	else
+#endif
+	  {
+	    /* Remove Hide Root Window button */
+	    RemoveMenu (hmenuTray,
+			ID_APP_HIDE_ROOT,
+			MF_BYCOMMAND);
+	  }
+
+	SetupRootMenu ((unsigned long)hmenuTray);
+
+	/*
+	 * NOTE: This three-step procedure is required for
+	 * proper popup menu operation.  Without the
+	 * call to SetForegroundWindow the
+	 * popup menu will often not disappear when you click
+	 * outside of it.  Without the PostMessage the second
+	 * time you display the popup menu it might immediately
+	 * disappear.
+	 */
+	SetForegroundWindow (hwnd);
+	TrackPopupMenuEx (hmenuTray,
+			  TPM_LEFTALIGN | TPM_BOTTOMALIGN | TPM_RIGHTBUTTON,
+			  ptCursor.x, ptCursor.y,
+			  hwnd,
+			  NULL);
+	PostMessage (hwnd, WM_NULL, 0, 0);
+
+	/* Free menu */
+	DestroyMenu (hmenuPopup);
+      }
+      break;
+    }
+
+  return 0;
+}
diff --git a/hw/xwin/winvalargs.c b/hw/xwin/winvalargs.c
new file mode 100755
index 0000000..038e097
--- /dev/null
+++ b/hw/xwin/winvalargs.c
@@ -0,0 +1,188 @@
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winmsg.h"
+
+
+/*
+ * References to external symbols
+ */
+
+extern int			g_iNumScreens;
+extern winScreenInfo		g_ScreenInfo[];
+extern Bool			g_fXdmcpEnabled;
+
+
+/*
+ * Prototypes
+ */
+
+Bool
+winValidateArgs (void);
+
+
+/*
+ * winValidateArgs - Look for invalid argument combinations
+ */
+
+Bool
+winValidateArgs (void)
+{
+  int		i;
+  int		iMaxConsecutiveScreen = 0;
+  BOOL		fHasNormalScreen0 = FALSE;
+
+  /*
+   * Check for a malformed set of -screen parameters.
+   * Examples of malformed parameters:
+   *	XWin -screen 1
+   *	XWin -screen 0 -screen 2
+   *	XWin -screen 1 -screen 2
+   */
+  for (i = 0; i < MAXSCREENS; i++)
+    {
+      if (g_ScreenInfo[i].fExplicitScreen)
+	iMaxConsecutiveScreen = i + 1;
+    }
+  winErrorFVerb (2, "winValidateArgs - g_iNumScreens: %d "
+		 "iMaxConsecutiveScreen: %d\n",
+		 g_iNumScreens, iMaxConsecutiveScreen);
+  if (g_iNumScreens < iMaxConsecutiveScreen)
+    {
+      ErrorF ("winValidateArgs - Malformed set of screen parameter(s).  "
+	      "Screens must be specified consecutively starting with "
+	      "screen 0.  That is, you cannot have only a screen 1, nor "
+	      "could you have screen 0 and screen 2.  You instead must "
+	      "have screen 0, or screen 0 and screen 1, respectively.  Of "
+	      "you can specify as many screens as you want from 0 up to "
+	      "%d.\n", MAXSCREENS - 1);
+      return FALSE;
+    }
+
+  /* Loop through all screens */
+  for (i = 0; i < g_iNumScreens; ++i)
+    {
+      /*
+       * Check for any combination of
+       * -multiwindow, -mwextwm, and -rootless.
+       */
+      {
+	int		iCount = 0;
+
+	/* Count conflicting options */
+#ifdef XWIN_MULTIWINDOW
+	if (g_ScreenInfo[i].fMultiWindow)
+	  ++iCount;
+#endif
+#ifdef XWIN_MULTIWINDOWEXTWM
+	if (g_ScreenInfo[i].fMWExtWM)
+	  ++iCount;
+#endif
+	if (g_ScreenInfo[i].fRootless)
+	  ++iCount;
+
+	/* Check if the first screen is without rootless and multiwindow */ 
+	if (iCount == 0 && i == 0)
+	  fHasNormalScreen0 = TRUE;  
+
+	/* Fail if two or more conflicting options */
+	if (iCount > 1)
+	  {
+	    ErrorF ("winValidateArgs - Only one of -multiwindow, -mwextwm, "
+		    "and -rootless can be specific at a time.\n");
+	    return FALSE;
+	  }
+      }
+
+      /* Check for -multiwindow or -mwextwm and Xdmcp */
+      /* allow xdmcp if screen 0 is normal. */
+      if (g_fXdmcpEnabled && !fHasNormalScreen0
+	  && (FALSE
+#ifdef XWIN_MULTIWINDOW
+	      || g_ScreenInfo[i].fMultiWindow
+#endif
+#ifdef XWIN_MULTIWINDOWEXTWM
+	      || g_ScreenInfo[i].fMWExtWM
+#endif
+	      )
+	  )
+	{
+	  ErrorF ("winValidateArgs - Xdmcp (-query, -broadcast, or -indirect) "
+		  "is invalid with -multiwindow or -mwextwm.\n");
+	  return FALSE;
+	}
+
+      /* Check for -multiwindow, -mwextwm, or -rootless and fullscreen */
+      if (g_ScreenInfo[i].fFullScreen
+	  && (FALSE
+#ifdef XWIN_MULTIWINDOW
+	      || g_ScreenInfo[i].fMultiWindow
+#endif
+#ifdef XWIN_MULTIWINDOWEXTWM
+	      || g_ScreenInfo[i].fMWExtWM
+#endif
+	      || g_ScreenInfo[i].fRootless)
+	  )
+	{
+	  ErrorF ("winValidateArgs - -fullscreen is invalid with "
+		  "-multiwindow, -mwextwm, or -rootless.\n");
+	  return FALSE;
+	}
+      
+      /* Check for !fullscreen and any fullscreen-only parameters */
+      if (!g_ScreenInfo[i].fFullScreen
+	  && (g_ScreenInfo[i].dwRefreshRate != WIN_DEFAULT_BPP
+	      || g_ScreenInfo[i].dwBPP != WIN_DEFAULT_REFRESH))
+	{
+	  ErrorF ("winValidateArgs - -refresh and -depth are only valid "
+		  "with -fullscreen.\n");
+	  return FALSE;
+	}
+
+      /* Check for fullscreen and any non-fullscreen parameters */
+      if (g_ScreenInfo[i].fFullScreen
+	  && (g_ScreenInfo[i].fScrollbars
+	      || !g_ScreenInfo[i].fDecoration
+	      || g_ScreenInfo[i].fLessPointer))
+	{
+	  ErrorF ("winValidateArgs - -fullscreen is invalid with "
+		  "-scrollbars, -nodecoration, or -lesspointer.\n");
+	  return FALSE;
+	}
+    }
+
+  winDebug ("winValidateArgs - Returning.\n");
+
+  return TRUE;
+}
diff --git a/hw/xwin/winvideo.c b/hw/xwin/winvideo.c
new file mode 100755
index 0000000..529ca76
--- /dev/null
+++ b/hw/xwin/winvideo.c
@@ -0,0 +1,210 @@
+/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of Harold L Hunt II
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from Harold L Hunt II.
+ *
+ * Authors:	Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include <X11/extensions/Xv.h>
+#include <X11/extensions/Xvproto.h>
+
+void
+winInitVideo (ScreenPtr pScreen);
+
+/*
+ * winInitVideo - Initialize support for the X Video (Xv) Extension.
+ */
+
+void
+winInitVideo (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo; 
+
+  if (pScreenInfo->dwBPP > 8) 
+    {
+      
+    }
+  
+
+}
+
+
+
+
+
+
+
+#if 0
+#include "../xfree86/common/xf86.h"
+#include "../Xext/xvdix.h"
+#include "../xfree86/common/xf86xv.h"
+#include <X11/extensions/Xv.h>
+#endif
+
+#include "win.h"
+
+
+
+#if 0
+/* client libraries expect an encoding */
+static XF86VideoEncodingRec DummyEncoding[1] =
+{
+ {
+   0,
+   "XV_IMAGE",
+   IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT,
+   {1, 1}
+ }
+};
+
+#define NUM_FORMATS 3
+
+static XF86VideoFormatRec Formats[NUM_FORMATS] = 
+{
+  {15, TrueColor}, {16, TrueColor}, {24, TrueColor}
+};
+
+#define NUM_ATTRIBUTES 3
+
+static XF86AttributeRec Attributes[NUM_ATTRIBUTES] =
+{
+   {XvSettable | XvGettable, 0, (1 << 24) - 1, "XV_COLORKEY"},
+   {XvSettable | XvGettable, -128, 127, "XV_BRIGHTNESS"},
+   {XvSettable | XvGettable, 0, 255, "XV_CONTRAST"}
+};
+
+#define NUM_IMAGES 4
+
+static XF86ImageRec Images[NUM_IMAGES] =
+{
+	XVIMAGE_YUY2,
+	XVIMAGE_YV12,
+	XVIMAGE_I420,
+	XVIMAGE_UYVY
+};
+
+
+
+/*
+ * winInitVideo - Initialize support for the X Video (Xv) Extension.
+ */
+
+void
+winInitVideo (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo; 
+  XF86VideoAdaptorPtr	newAdaptor = NULL;
+
+  if (pScreenInfo->dwBPP > 8) 
+    {
+      newAdaptor = I810SetupImageVideo (pScreen);
+      I810InitOffscreenImages (pScreen);
+    }
+  
+    xf86XVScreenInit (pScreen, adaptors, 1);
+}
+
+
+static XF86VideoAdaptorPtr 
+winSetupImageVideo (ScreenPtr pScreen)
+{
+    ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
+#if 0
+    I810Ptr pI810 = I810PTR(pScrn);
+#endif
+    XF86VideoAdaptorPtr adapt;
+
+    if (!(adapt = xcalloc (1, sizeof(XF86VideoAdaptorRec))))
+      return NULL;
+
+    adapt->type = XvWindowMask | XvInputMask | XvImageMask;
+    adapt->flags = VIDEO_OVERLAID_IMAGES | VIDEO_CLIP_TO_VIEWPORT;
+    adapt->name = PROJECT_NAME " Video Overlay";
+    adapt->nEncodings = 1;
+    adapt->pEncodings = DummyEncoding;
+    adapt->nFormats = NUM_FORMATS;
+    adapt->pFormats = Formats;
+    adapt->nPorts = 1;
+    adapt->pPortPrivates = NULL;
+
+    adapt->pPortPrivates[0].ptr = NULL;
+    adapt->pAttributes = Attributes;
+    adapt->nImages = NUM_IMAGES;
+    adapt->nAttributes = NUM_ATTRIBUTES;
+    adapt->pImages = Images;
+    adapt->PutVideo = NULL;
+    adapt->PutStill = NULL;
+    adapt->GetVideo = NULL;
+    adapt->GetStill = NULL;
+#if 0
+    adapt->StopVideo = I810StopVideo;
+    adapt->SetPortAttribute = I810SetPortAttribute;
+    adapt->GetPortAttribute = I810GetPortAttribute;
+    adapt->QueryBestSize = I810QueryBestSize;
+    adapt->PutImage = I810PutImage;
+    adapt->QueryImageAttributes = I810QueryImageAttributes;
+#endif
+
+#if 0
+    pPriv->colorKey = pI810->colorKey & ((1 << pScrn->depth) - 1);
+#endif
+    pPriv->videoStatus = 0;
+    pPriv->brightness = 0;
+    pPriv->contrast = 64;
+    pPriv->linear = NULL;
+    pPriv->currentBuf = 0;
+
+#if 0
+    /* gotta uninit this someplace */
+    REGION_NULL(pScreen, &pPriv->clip);
+#endif
+
+#if 0
+    pI810->adaptor = adapt;
+
+    pI810->BlockHandler = pScreen->BlockHandler;
+    pScreen->BlockHandler = I810BlockHandler;
+#endif
+
+#if 0
+    xvBrightness = MAKE_ATOM("XV_BRIGHTNESS");
+    xvContrast   = MAKE_ATOM("XV_CONTRAST");
+    xvColorKey   = MAKE_ATOM("XV_COLORKEY");
+#endif
+
+#if 0
+    I810ResetVideo(pScrn);
+#endif
+
+    return adapt;
+}
+#endif
diff --git a/hw/xwin/winwakeup.c b/hw/xwin/winwakeup.c
new file mode 100644
index 0000000..e1eece3
--- /dev/null
+++ b/hw/xwin/winwakeup.c
@@ -0,0 +1,71 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * References to external symbols
+ */
+
+extern HWND			g_hDlgDepthChange;
+extern HWND			g_hDlgExit;
+extern HWND			g_hDlgAbout;
+
+
+/* See Porting Layer Definition - p. 7 */
+void
+winWakeupHandler (int nScreen,
+		  pointer pWakeupData,
+		  unsigned long ulResult,
+		  pointer pReadmask)
+{
+  MSG			msg;
+
+  /* Process all messages on our queue */
+  while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
+    {
+      if ((g_hDlgDepthChange == 0
+	   || !IsDialogMessage (g_hDlgDepthChange, &msg))
+	  && (g_hDlgExit == 0
+	      || !IsDialogMessage (g_hDlgExit, &msg))
+	  && (g_hDlgAbout == 0
+	      || !IsDialogMessage (g_hDlgAbout, &msg)))
+	{
+	  DispatchMessage (&msg);
+	}
+    }
+}
diff --git a/hw/xwin/winwin32rootless.c b/hw/xwin/winwin32rootless.c
new file mode 100755
index 0000000..6f4e2c9
--- /dev/null
+++ b/hw/xwin/winwin32rootless.c
@@ -0,0 +1,1092 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Kensuke Matsuzaki
+ *		Earle F. Philhower, III
+ *		Harold L Hunt II
+ */
+/*
+ * Look at hw/darwin/quartz/xpr/xprFrame.c and hw/darwin/quartz/cr/crFrame.c
+ */
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include <winuser.h>
+#define _WINDOWSWM_SERVER_
+#include "windowswmstr.h"
+#include "dixevents.h"
+#include "winmultiwindowclass.h"
+#include "winprefs.h"
+#include <X11/Xatom.h>
+
+
+/*
+ * Constant defines
+ */
+
+#define MOUSE_POLLING_INTERVAL		500
+
+#define ULW_COLORKEY	0x00000001
+#define ULW_ALPHA	0x00000002
+#define ULW_OPAQUE	0x00000004
+#define AC_SRC_ALPHA	0x01
+
+/*
+ * Local function
+ */
+
+DEFINE_ATOM_HELPER(AtmWindowsWmNativeHwnd, WINDOWSWM_NATIVE_HWND)
+static void
+winMWExtWMSetNativeProperty (RootlessWindowPtr pFrame);
+
+/*
+ * Global variables
+ */
+
+Bool			g_fNoConfigureWindow = FALSE;
+
+
+extern void winSelectIcons(WindowPtr pWin, HICON *pIcon, HICON *pSmallIcon);
+
+/*
+ * Internal function to get the DIB format that is compatible with the screen
+ * Fixme: Share code with winshadgdi.c
+ */
+
+static
+Bool
+winMWExtWMQueryDIBFormat (win32RootlessWindowPtr pRLWinPriv, BITMAPINFOHEADER *pbmih)
+{
+  HBITMAP		hbmp;
+#if CYGMULTIWINDOW_DEBUG
+  LPDWORD		pdw = NULL;
+#endif
+  
+  /* Create a memory bitmap compatible with the screen */
+  hbmp = CreateCompatibleBitmap (pRLWinPriv->hdcScreen, 1, 1);
+  if (hbmp == NULL)
+    {
+      ErrorF ("winMWExtWMQueryDIBFormat - CreateCompatibleBitmap failed\n");
+      return FALSE;
+    }
+  
+  /* Initialize our bitmap info header */
+  ZeroMemory (pbmih, sizeof (BITMAPINFOHEADER) + 256 * sizeof (RGBQUAD));
+  pbmih->biSize = sizeof (BITMAPINFOHEADER);
+
+  /* Get the biBitCount */
+  if (!GetDIBits (pRLWinPriv->hdcScreen,
+		  hbmp,
+		  0, 1,
+		  NULL,
+		  (BITMAPINFO*) pbmih,
+		  DIB_RGB_COLORS))
+    {
+      ErrorF ("winMWExtWMQueryDIBFormat - First call to GetDIBits failed\n");
+      DeleteObject (hbmp);
+      return FALSE;
+    }
+
+#if CYGMULTIWINDOW_DEBUG
+  /* Get a pointer to bitfields */
+  pdw = (DWORD*) ((CARD8*)pbmih + sizeof (BITMAPINFOHEADER));
+
+  winDebug ("winMWExtWMQueryDIBFormat - First call masks: %08x %08x %08x\n",
+	  (unsigned int)pdw[0], (unsigned int)pdw[1], (unsigned int)pdw[2]);
+#endif
+
+  /* Get optimal color table, or the optimal bitfields */
+  if (!GetDIBits (pRLWinPriv->hdcScreen,
+		  hbmp,
+		  0, 1,
+		  NULL,
+		  (BITMAPINFO*)pbmih,
+		  DIB_RGB_COLORS))
+    {
+      ErrorF ("winMWExtWMQueryDIBFormat - Second call to GetDIBits "
+	      "failed\n");
+      DeleteObject (hbmp);
+      return FALSE;
+    }
+
+  /* Free memory */
+  DeleteObject (hbmp);
+  
+  return TRUE;
+}
+
+static HRGN
+winMWExtWMCreateRgnFromRegion (RegionPtr pShape)
+{
+  int		nRects;
+  BoxPtr	pRects, pEnd;
+  HRGN		hRgn, hRgnRect;
+
+  if (pShape == NULL) return NULL;
+
+  nRects = REGION_NUM_RECTS(pShape);
+  pRects = REGION_RECTS(pShape);
+  
+  hRgn = CreateRectRgn (0, 0, 0, 0);
+  if (hRgn == NULL)
+    {
+      ErrorF ("winReshape - Initial CreateRectRgn (%d, %d, %d, %d) "
+	      "failed: %d\n",
+	      0, 0, 0, 0, (int) GetLastError ());
+    }
+
+  /* Loop through all rectangles in the X region */
+  for (pEnd = pRects + nRects; pRects < pEnd; pRects++)
+    {
+      /* Create a Windows region for the X rectangle */
+      hRgnRect = CreateRectRgn (pRects->x1,
+				pRects->y1,
+				pRects->x2,
+				pRects->y2);
+      if (hRgnRect == NULL)
+	{
+	  ErrorF ("winReshape - Loop CreateRectRgn (%d, %d, %d, %d) "
+		  "failed: %d\n",
+		  pRects->x1,
+		  pRects->y1,
+		  pRects->x2,
+		  pRects->y2,
+		  (int) GetLastError ());
+	}
+      
+      /* Merge the Windows region with the accumulated region */
+      if (CombineRgn (hRgn, hRgn, hRgnRect, RGN_OR) == ERROR)
+	{
+	  ErrorF ("winReshape - CombineRgn () failed: %d\n",
+		  (int) GetLastError ());
+	}
+      
+      /* Delete the temporary Windows region */
+      DeleteObject (hRgnRect);
+    }
+  
+  return hRgn;
+}
+
+static void
+InitWin32RootlessEngine (win32RootlessWindowPtr pRLWinPriv)
+{
+  pRLWinPriv->hdcScreen = GetDC (pRLWinPriv->hWnd);
+  pRLWinPriv->hdcShadow = CreateCompatibleDC (pRLWinPriv->hdcScreen);
+  pRLWinPriv->hbmpShadow = NULL;
+
+  /* Allocate bitmap info header */
+  pRLWinPriv->pbmihShadow = (BITMAPINFOHEADER*) malloc (sizeof (BITMAPINFOHEADER)
+							+ 256 * sizeof (RGBQUAD));
+  if (pRLWinPriv->pbmihShadow == NULL)
+    {
+      ErrorF ("InitWin32RootlessEngine - malloc () failed\n");
+      return;
+    }
+  
+  /* Query the screen format */
+  winMWExtWMQueryDIBFormat (pRLWinPriv,
+				  pRLWinPriv->pbmihShadow);
+}
+
+Bool
+winMWExtWMCreateFrame (RootlessWindowPtr pFrame, ScreenPtr pScreen,
+			     int newX, int newY, RegionPtr pShape)
+{
+#define CLASS_NAME_LENGTH 512
+  Bool				fResult = TRUE;
+  win32RootlessWindowPtr	pRLWinPriv;
+  WNDCLASSEX			wc;
+  char				pszClass[CLASS_NAME_LENGTH], pszWindowID[12];
+  HICON				hIcon;
+  HICON				hIconSmall;
+  char				*res_name, *res_class, *res_role;
+  static int			s_iWindowID = 0;
+ 
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMCreateFrame %d %d - %d %d\n",
+	  newX, newY, pFrame->width, pFrame->height);
+#endif
+
+  pRLWinPriv = (win32RootlessWindowPtr) malloc (sizeof (win32RootlessWindowRec));
+  pRLWinPriv->pFrame = pFrame;
+  pRLWinPriv->pfb = NULL;
+  pRLWinPriv->hbmpShadow = NULL;
+  pRLWinPriv->hdcShadow = NULL;
+  pRLWinPriv->hdcScreen = NULL;
+  pRLWinPriv->pbmihShadow = NULL;
+  pRLWinPriv->fResized = TRUE;
+  pRLWinPriv->fClose = FALSE;
+  pRLWinPriv->fRestackingNow = FALSE;
+  pRLWinPriv->fDestroyed = FALSE;
+  pRLWinPriv->fMovingOrSizing = FALSE;
+  
+  // Store the implementation private frame ID
+  pFrame->wid = (RootlessFrameID) pRLWinPriv;
+
+  winSelectIcons(pFrame->win, &hIcon, &hIconSmall); 
+  
+  /* Set standard class name prefix so we can identify window easily */
+  strncpy (pszClass, WINDOW_CLASS_X, sizeof(pszClass));
+
+  if (winMultiWindowGetClassHint (pFrame->win, &res_name, &res_class))
+    {
+      strncat (pszClass, "-", 1);
+      strncat (pszClass, res_name, CLASS_NAME_LENGTH - strlen (pszClass));
+      strncat (pszClass, "-", 1);
+      strncat (pszClass, res_class, CLASS_NAME_LENGTH - strlen (pszClass));
+      
+      /* Check if a window class is provided by the WM_WINDOW_ROLE property,
+       * if not use the WM_CLASS information.
+       * For further information see:
+       * http://tronche.com/gui/x/icccm/sec-5.html
+       */
+      if (winMultiWindowGetWindowRole (pFrame->win, &res_role) )
+	{
+	  strcat (pszClass, "-");
+	  strcat (pszClass, res_role);
+	  free (res_role);
+	}
+
+      free (res_name);
+      free (res_class);
+    }
+
+  /* Add incrementing window ID to make unique class name */
+  snprintf (pszWindowID, sizeof(pszWindowID), "-%x", s_iWindowID++);
+  pszWindowID[sizeof(pszWindowID)-1] = 0;
+  strcat (pszClass, pszWindowID);
+
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winCreateWindowsWindow - Creating class: %s\n", pszClass);
+#endif
+
+  /* Setup our window class */
+  wc.cbSize = sizeof(wc);
+  wc.style = CS_HREDRAW | CS_VREDRAW;
+  wc.lpfnWndProc = winMWExtWMWindowProc;
+  wc.cbClsExtra = 0;
+  wc.cbWndExtra = 0;
+  wc.hInstance = g_hInstance;
+  wc.hIcon = hIcon;
+  wc.hIconSm = hIconSmall;
+  wc.hCursor = 0;
+  wc.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
+  wc.lpszMenuName = NULL;
+  wc.lpszClassName = pszClass;
+  RegisterClassEx (&wc);
+
+  /* Create the window */
+  g_fNoConfigureWindow = TRUE;
+  pRLWinPriv->hWnd = CreateWindowExA (WS_EX_TOOLWINDOW,		/* Extended styles */
+				      pszClass,			/* Class name */
+				      WINDOW_TITLE_X,		/* Window name */
+				      WS_POPUP | WS_CLIPCHILDREN,
+				      newX,			/* Horizontal position */
+				      newY,			/* Vertical position */
+				      pFrame->width,		/* Right edge */ 
+				      pFrame->height,		/* Bottom edge */
+				      (HWND) NULL,		/* No parent or owner window */
+				      (HMENU) NULL,		/* No menu */
+				      GetModuleHandle (NULL),	/* Instance handle */
+				      pRLWinPriv);		/* ScreenPrivates */
+  if (pRLWinPriv->hWnd == NULL)
+    {
+      ErrorF ("winMWExtWMCreateFrame - CreateWindowExA () failed: %d\n",
+	      (int) GetLastError ());
+      fResult = FALSE;
+    }
+
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMCreateFrame - ShowWindow\n");
+#endif
+
+  //ShowWindow (pRLWinPriv->hWnd, SW_SHOWNOACTIVATE);
+  g_fNoConfigureWindow = FALSE;
+  
+  if (pShape != NULL)
+    {
+      winMWExtWMReshapeFrame (pFrame->wid, pShape);
+    }
+
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMCreateFrame - (%08x) %08x\n",
+	  (int) pFrame->wid, (int) pRLWinPriv->hWnd);
+#if 0
+  {
+   WindowPtr		pWin2 = NULL;
+   win32RootlessWindowPtr pRLWinPriv2 = NULL;
+
+   /* Check if the Windows window property for our X window pointer is valid */
+   if ((pWin2 = (WindowPtr)GetProp (pRLWinPriv->hWnd, WIN_WINDOW_PROP)) != NULL)
+     {
+       pRLWinPriv2 = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin2, FALSE);
+     }
+   winDebug ("winMWExtWMCreateFrame2 (%08x) %08x\n",
+	   pRLWinPriv2, pRLWinPriv2->hWnd);
+   if (pRLWinPriv != pRLWinPriv2 || pRLWinPriv->hWnd != pRLWinPriv2->hWnd)
+     {
+       winDebug ("Error param missmatch\n");
+     }
+ }
+#endif
+#endif
+
+  winMWExtWMSetNativeProperty (pFrame);
+
+  return fResult;
+}
+
+void
+winMWExtWMDestroyFrame (RootlessFrameID wid)
+{
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
+  HICON			hiconClass;
+  HICON			hiconSmClass;
+  HMODULE		hInstance;
+  int			iReturn;
+  char			pszClass[CLASS_NAME_LENGTH];
+
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMDestroyFrame (%08x) %08x\n",
+	  (int) pRLWinPriv, (int) pRLWinPriv->hWnd);
+#if 0
+ {
+   WindowPtr		pWin2 = NULL;
+   win32RootlessWindowPtr pRLWinPriv2 = NULL;
+
+   /* Check if the Windows window property for our X window pointer is valid */
+   if ((pWin2 = (WindowPtr)GetProp (pRLWinPriv->hWnd, WIN_WINDOW_PROP)) != NULL)
+     {
+       pRLWinPriv2 = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin2, FALSE);
+     }
+   winDebug ("winMWExtWMDestroyFrame2 (%08x) %08x\n",
+	   pRLWinPriv2, pRLWinPriv2->hWnd);
+   if (pRLWinPriv != pRLWinPriv2 || pRLWinPriv->hWnd != pRLWinPriv2->hWnd)
+     {
+       winDebug ("Error param missmatch\n");
+       *(int*)0 = 1;//raise exseption
+     }
+ }
+#endif
+#endif
+
+  /* Store the info we need to destroy after this window is gone */
+  hInstance = (HINSTANCE) GetClassLong (pRLWinPriv->hWnd, GCL_HMODULE);
+  hiconClass = (HICON) GetClassLong (pRLWinPriv->hWnd, GCL_HICON);
+  hiconSmClass = (HICON) GetClassLong (pRLWinPriv->hWnd, GCL_HICONSM);
+  iReturn = GetClassName (pRLWinPriv->hWnd, pszClass, CLASS_NAME_LENGTH);
+
+  pRLWinPriv->fClose = TRUE;
+  pRLWinPriv->fDestroyed = TRUE;
+
+  /* Destroy the Windows window */
+  DestroyWindow (pRLWinPriv->hWnd);
+
+  /* Only if we were able to get the name */
+  if (iReturn)
+    { 
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMDestroyFrame - Unregistering %s: ", pszClass);
+#endif
+      iReturn = UnregisterClass (pszClass, hInstance);
+      
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMDestroyFramew - %d Deleting Icon: ", iReturn);
+#endif
+      
+      winDestroyIcon(hiconClass);
+      winDestroyIcon(hiconSmClass);
+    }
+
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMDestroyFrame - done\n");
+#endif
+}
+
+void
+winMWExtWMMoveFrame (RootlessFrameID wid, ScreenPtr pScreen, int iNewX, int iNewY)
+{
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
+  RECT rcNew;
+  DWORD dwExStyle;
+  DWORD dwStyle;
+  int iX, iY, iWidth, iHeight;
+
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMMoveFrame (%08x) (%d %d)\n", (int) pRLWinPriv, iNewX, iNewY);
+#endif
+
+  /* Get the Windows window style and extended style */
+  dwExStyle = GetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE);
+  dwStyle = GetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE);
+
+  /* Get the X and Y location of the X window */
+  iX = iNewX + GetSystemMetrics (SM_XVIRTUALSCREEN);
+  iY = iNewY + GetSystemMetrics (SM_YVIRTUALSCREEN);
+
+  /* Get the height and width of the X window */
+  iWidth = pRLWinPriv->pFrame->width;
+  iHeight = pRLWinPriv->pFrame->height;
+
+  /* Store the origin, height, and width in a rectangle structure */
+  SetRect (&rcNew, iX, iY, iX + iWidth, iY + iHeight);
+
+#ifdef CYGMULTIWINDOW_DEBUG
+          winDebug("\tWindow {%d, %d, %d, %d}, {%d, %d}\n", 
+              rcNew.left, rcNew.top, rcNew.right, rcNew.bottom,
+              rcNew.right - rcNew.left, rcNew.bottom - rcNew.top);
+#endif
+  /*
+   * Calculate the required size of the Windows window rectangle,
+   * given the size of the Windows window client area.
+   */
+  AdjustWindowRectEx (&rcNew, dwStyle, FALSE, dwExStyle);
+
+#ifdef CYGMULTIWINDOW_DEBUG
+          winDebug("\tAdjusted {%d, %d, %d, %d}, {%d, %d}\n", 
+              rcNew.left, rcNew.top, rcNew.right, rcNew.bottom,
+              rcNew.right - rcNew.left, rcNew.bottom - rcNew.top);
+#endif
+  g_fNoConfigureWindow = TRUE;
+  SetWindowPos (pRLWinPriv->hWnd, NULL, rcNew.left, rcNew.top, 0, 0,
+		SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER);
+  g_fNoConfigureWindow = FALSE;
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMMoveFrame (%08x) done\n", (int) pRLWinPriv);
+#endif
+}
+
+void
+winMWExtWMResizeFrame (RootlessFrameID wid, ScreenPtr pScreen,
+			     int iNewX, int iNewY,
+			     unsigned int uiNewWidth, unsigned int uiNewHeight,
+			     unsigned int uiGravity)
+{
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
+  RECT rcNew;
+  RECT rcOld;
+  DWORD dwExStyle;
+  DWORD dwStyle;
+  int iX, iY;
+
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMResizeFrame (%08x) (%d %d)-(%d %d)\n",
+	  (int) pRLWinPriv, iNewX, iNewY, uiNewWidth, uiNewHeight);
+#endif
+
+  pRLWinPriv->fResized = TRUE;
+
+  /* Get the Windows window style and extended style */
+  dwExStyle = GetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE);
+  dwStyle = GetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE);
+
+  /* Get the X and Y location of the X window */
+  iX = iNewX + GetSystemMetrics (SM_XVIRTUALSCREEN);
+  iY = iNewY + GetSystemMetrics (SM_YVIRTUALSCREEN);
+
+  /* Store the origin, height, and width in a rectangle structure */
+  SetRect (&rcNew, iX, iY, iX + uiNewWidth, iY + uiNewHeight);
+
+  /*
+   * Calculate the required size of the Windows window rectangle,
+   * given the size of the Windows window client area.
+   */
+  AdjustWindowRectEx (&rcNew, dwStyle, FALSE, dwExStyle);
+
+  /* Get a rectangle describing the old Windows window */
+  GetWindowRect (pRLWinPriv->hWnd, &rcOld);
+
+  /* Check if the old rectangle and new rectangle are the same */
+  if (!EqualRect (&rcNew, &rcOld))
+    {
+
+      g_fNoConfigureWindow = TRUE;
+      MoveWindow (pRLWinPriv->hWnd,
+		  rcNew.left, rcNew.top,
+		  rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
+		  TRUE);
+      g_fNoConfigureWindow = FALSE;
+    }
+}
+
+void
+winMWExtWMRestackFrame (RootlessFrameID wid, RootlessFrameID nextWid)
+{
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
+  win32RootlessWindowPtr pRLNextWinPriv = (win32RootlessWindowPtr) nextWid;
+  winScreenPriv(pRLWinPriv->pFrame->win->drawable.pScreen);
+  winScreenInfo *pScreenInfo = NULL;
+  DWORD dwCurrentProcessID = GetCurrentProcessId ();
+  DWORD dwWindowProcessID = 0;
+  HWND hWnd;
+  Bool fFirst = TRUE;
+  Bool fNeedRestack = TRUE;
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMRestackFrame (%08x)\n", (int) pRLWinPriv);
+#endif
+
+  if (pScreenPriv->fRestacking) return;
+
+  if (pScreenPriv) pScreenInfo = pScreenPriv->pScreenInfo;
+
+  pRLWinPriv->fRestackingNow = TRUE;
+
+  /* Show window */
+  if(!IsWindowVisible (pRLWinPriv->hWnd))
+    ShowWindow (pRLWinPriv->hWnd, SW_SHOWNOACTIVATE);
+
+  if (pRLNextWinPriv == NULL)
+    {
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("Win %08x is top\n", pRLWinPriv);
+#endif
+      pScreenPriv->widTop = wid;
+      SetWindowPos (pRLWinPriv->hWnd, HWND_TOP,
+		    0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
+    }
+  else if (winIsInternalWMRunning(pScreenInfo))
+    {
+      /* using mulwinidow wm */
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("Win %08x is not top\n", pRLWinPriv);
+#endif
+      for (hWnd = GetNextWindow (pRLWinPriv->hWnd, GW_HWNDPREV);
+	   fNeedRestack && hWnd != NULL;
+	   hWnd = GetNextWindow (hWnd, GW_HWNDPREV))
+	{
+	  GetWindowThreadProcessId (hWnd, &dwWindowProcessID);
+
+	  if ((dwWindowProcessID == dwCurrentProcessID)
+	      && GetProp (hWnd, WIN_WINDOW_PROP))
+	    {
+	      if (hWnd == pRLNextWinPriv->hWnd)
+		{
+		  /* Enable interleave X window and Windows window */
+		  if (!fFirst)
+		    {
+#if CYGMULTIWINDOW_DEBUG
+		      winDebug ("raise: Insert after Win %08x\n", pRLNextWinPriv);
+#endif
+		      SetWindowPos (pRLWinPriv->hWnd, pRLNextWinPriv->hWnd,
+				    0, 0, 0, 0,
+				    SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
+		    }
+		  else
+		    {
+#if CYGMULTIWINDOW_DEBUG
+		      winDebug ("No change\n");
+#endif
+		    }
+		  fNeedRestack = FALSE;
+		  break;
+		}
+	      if (fFirst) fFirst = FALSE;
+	    }
+	}
+
+      for (hWnd = GetNextWindow (pRLWinPriv->hWnd, GW_HWNDNEXT);
+	   fNeedRestack && hWnd != NULL;
+	   hWnd = GetNextWindow (hWnd, GW_HWNDNEXT))
+	{
+	  GetWindowThreadProcessId (hWnd, &dwWindowProcessID);
+
+	  if ((dwWindowProcessID == dwCurrentProcessID)
+	      && GetProp (hWnd, WIN_WINDOW_PROP))
+	    {
+	      if (hWnd == pRLNextWinPriv->hWnd)
+		{
+#if CYGMULTIWINDOW_DEBUG
+		  winDebug ("lower: Insert after Win %08x\n", pRLNextWinPriv);
+#endif
+		  SetWindowPos (pRLWinPriv->hWnd, pRLNextWinPriv->hWnd,
+				0, 0, 0, 0,
+				SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
+		  fNeedRestack = FALSE;
+		  break;
+		}
+	    }
+	}
+    }
+  else
+    {
+      /* using general wm like twm, wmaker etc.
+	 Interleave X window and Windows window will cause problem. */
+      SetWindowPos (pRLWinPriv->hWnd, pRLNextWinPriv->hWnd,
+		    0, 0, 0, 0,
+		    SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
+#if 0
+#endif
+    }
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMRestackFrame - done (%08x)\n", (int) pRLWinPriv);
+#endif
+
+  pRLWinPriv->fRestackingNow = FALSE;
+}
+
+void
+winMWExtWMReshapeFrame (RootlessFrameID wid, RegionPtr pShape)
+{
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
+  HRGN hRgn, hRgnWindow, hRgnClient;
+  RECT rcWindow, rcClient;
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMReshapeFrame (%08x)\n", (int) pRLWinPriv);
+#endif
+
+  hRgn = winMWExtWMCreateRgnFromRegion (pShape);
+  
+  /* Create region for non-client area */
+  GetWindowRect (pRLWinPriv->hWnd, &rcWindow);
+  GetClientRect (pRLWinPriv->hWnd, &rcClient);
+  MapWindowPoints (pRLWinPriv->hWnd, HWND_DESKTOP, (LPPOINT)&rcClient, 2);
+  OffsetRgn (hRgn, rcClient.left - rcWindow.left, rcClient.top - rcWindow.top);
+  OffsetRect (&rcClient, -rcWindow.left, -rcWindow.top);
+  OffsetRect (&rcWindow, -rcWindow.left, -rcWindow.top);
+  hRgnWindow = CreateRectRgnIndirect (&rcWindow);
+  hRgnClient = CreateRectRgnIndirect (&rcClient);
+  CombineRgn (hRgnWindow, hRgnWindow, hRgnClient, RGN_DIFF);
+  CombineRgn (hRgn, hRgnWindow, hRgn, RGN_OR);
+
+
+  SetWindowRgn (pRLWinPriv->hWnd, hRgn, TRUE);
+
+  DeleteObject (hRgnWindow);
+  DeleteObject (hRgnClient);
+}
+
+void
+winMWExtWMUnmapFrame (RootlessFrameID wid)
+{
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMUnmapFrame (%08x)\n", (int) pRLWinPriv);
+#endif
+
+  g_fNoConfigureWindow = TRUE;
+  //ShowWindow (pRLWinPriv->hWnd, SW_MINIMIZE);
+  ShowWindow (pRLWinPriv->hWnd, SW_HIDE);
+  g_fNoConfigureWindow = FALSE;
+}
+
+/*
+ * Fixme: Code sharing with winshadgdi.c and other engine support
+ */
+void
+winMWExtWMStartDrawing (RootlessFrameID wid, char **pixelData, int *bytesPerRow)
+{
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
+  winPrivScreenPtr	pScreenPriv = NULL;
+  winScreenInfo		*pScreenInfo = NULL;
+  ScreenPtr		pScreen = NULL;
+  DIBSECTION		dibsection;
+  Bool			fReturn = TRUE;
+  HDC			hdcNew;
+  HBITMAP		hbmpNew;
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMStartDrawing (%08x) %08x\n", (int) pRLWinPriv, pRLWinPriv->fDestroyed);
+#endif
+
+  if (!pRLWinPriv->fDestroyed)
+    {
+      pScreen = pRLWinPriv->pFrame->win->drawable.pScreen;
+      if (pScreen) pScreenPriv = winGetScreenPriv(pScreen);
+      if (pScreenPriv) pScreenInfo = pScreenPriv->pScreenInfo;
+      
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("\tpScreenPriv %08X\n", (int) pScreenPriv);
+      winDebug ("\tpScreenInfo %08X\n", (int) pScreenInfo);
+      winDebug ("\t(%d, %d)\n", (int)pRLWinPriv->pFrame->width,
+		(int) pRLWinPriv->pFrame->height);
+#endif
+      if (pRLWinPriv->hdcScreen == NULL)
+	{
+	  InitWin32RootlessEngine (pRLWinPriv);
+	}
+      
+      if (pRLWinPriv->fResized)
+	{
+          /* width * bpp must be multiple of 4 to match 32bit alignment */
+	  int stridesize;
+	  int misalignment;
+         
+	  pRLWinPriv->pbmihShadow->biWidth = pRLWinPriv->pFrame->width;
+	  pRLWinPriv->pbmihShadow->biHeight = -pRLWinPriv->pFrame->height;
+ 
+	  stridesize = pRLWinPriv->pFrame->width * (pScreenInfo->dwBPP >> 3);
+	  misalignment = stridesize & 3; 
+	  if (misalignment != 0)
+	  {
+	    stridesize += 4 - misalignment;
+	    pRLWinPriv->pbmihShadow->biWidth = stridesize / (pScreenInfo->dwBPP >> 3);
+	    winDebug("\tresizing to %d (was %d)\n", 
+		    pRLWinPriv->pbmihShadow->biWidth, pRLWinPriv->pFrame->width);
+	  }
+	  
+	  hdcNew = CreateCompatibleDC (pRLWinPriv->hdcScreen);
+	  /* Create a DI shadow bitmap with a bit pointer */
+	  hbmpNew = CreateDIBSection (pRLWinPriv->hdcScreen,
+				      (BITMAPINFO *) pRLWinPriv->pbmihShadow,
+				      DIB_RGB_COLORS,
+				      (VOID**) &pRLWinPriv->pfb,
+				      NULL,
+				      0);
+	  if (hbmpNew == NULL || pRLWinPriv->pfb == NULL)
+	    {
+	      ErrorF ("winMWExtWMStartDrawing - CreateDIBSection failed\n");
+	      //return FALSE;
+	    }
+	  else
+	    {
+#if CYGMULTIWINDOW_DEBUG
+	      winDebug ("winMWExtWMStartDrawing - Shadow buffer allocated\n");
+#endif
+	    }
+	  
+	  /* Get information about the bitmap that was allocated */
+	  GetObject (hbmpNew, sizeof (dibsection), &dibsection);
+	  
+#if CYGMULTIWINDOW_DEBUG
+	  /* Print information about bitmap allocated */
+	  winDebug ("winMWExtWMStartDrawing - Dibsection width: %d height: %d "
+		    "depth: %d size image: %d\n",
+		    (unsigned int)dibsection.dsBmih.biWidth,
+		    (unsigned int)dibsection.dsBmih.biHeight,
+		    (unsigned int)dibsection.dsBmih.biBitCount,
+		    (unsigned int)dibsection.dsBmih.biSizeImage);
+#endif
+	  
+	  /* Select the shadow bitmap into the shadow DC */
+	  SelectObject (hdcNew, hbmpNew);
+	  
+#if CYGMULTIWINDOW_DEBUG
+	  winDebug ("winMWExtWMStartDrawing - Attempting a shadow blit\n");
+#endif
+	  
+	  /* Blit from the old shadow to the new shadow */
+	  fReturn = BitBlt (hdcNew,
+			    0, 0,
+			    pRLWinPriv->pFrame->width, pRLWinPriv->pFrame->height,
+			    pRLWinPriv->hdcShadow,
+			    0, 0,
+			    SRCCOPY);
+	  if (fReturn)
+	    {
+#if CYGMULTIWINDOW_DEBUG
+	      winDebug ("winMWExtWMStartDrawing - Shadow blit success\n");
+#endif
+	    }
+	  else
+	    {
+	      ErrorF ("winMWExtWMStartDrawing - Shadow blit failure\n");
+	    }
+	  
+	  /* Look for height weirdness */
+	  if (dibsection.dsBmih.biHeight < 0)
+	    {
+	      /* FIXME: Figure out why biHeight is sometimes negative */
+	      ErrorF ("winMWExtWMStartDrawing - WEIRDNESS - "
+                  "biHeight still negative: %d\n", 
+                  (int) dibsection.dsBmih.biHeight);
+	      ErrorF ("winMWExtWMStartDrawing - WEIRDNESS - "
+                  "Flipping biHeight sign\n");
+	      dibsection.dsBmih.biHeight = -dibsection.dsBmih.biHeight;
+	    }
+	  
+	  pRLWinPriv->dwWidthBytes = dibsection.dsBm.bmWidthBytes;
+	  
+#if CYGMULTIWINDOW_DEBUG
+	  winDebug ("winMWExtWMStartDrawing - bytesPerRow: %d\n",
+		    (unsigned int)dibsection.dsBm.bmWidthBytes);
+#endif
+	  
+	  /* Free the old shadow bitmap */
+	  DeleteObject (pRLWinPriv->hdcShadow);
+	  DeleteObject (pRLWinPriv->hbmpShadow);
+	  
+	  pRLWinPriv->hdcShadow = hdcNew;
+	  pRLWinPriv->hbmpShadow = hbmpNew;
+	  
+	  pRLWinPriv->fResized = FALSE;
+#if CYGMULTIWINDOW_DEBUG && FALSE
+	  winDebug ("winMWExtWMStartDrawing - 0x%08x %d\n",
+		(unsigned int)pRLWinPriv->pfb, 
+		(unsigned int)dibsection.dsBm.bmWidthBytes);
+#endif
+	}
+    }
+  else
+    {
+      ErrorF ("winMWExtWMStartDrawing - Already window was destroyed \n"); 
+    }
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMStartDrawing - done (0x%08x) 0x%08x %d\n",
+	    (int) pRLWinPriv,
+	    (unsigned int)pRLWinPriv->pfb, (unsigned int)pRLWinPriv->dwWidthBytes);
+#endif
+  *pixelData = pRLWinPriv->pfb;
+  *bytesPerRow = pRLWinPriv->dwWidthBytes;
+}
+
+void
+winMWExtWMStopDrawing (RootlessFrameID wid, Bool fFlush)
+{
+#if 0
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
+  BLENDFUNCTION bfBlend;
+  SIZE szWin;
+  POINT ptSrc;
+#if CYGMULTIWINDOW_DEBUG || TRUE
+  winDebug ("winMWExtWMStopDrawing (%08x)\n", pRLWinPriv);
+#endif
+  szWin.cx = pRLWinPriv->dwWidth;
+  szWin.cy = pRLWinPriv->dwHeight;
+  ptSrc.x = 0;
+  ptSrc.y = 0;
+  bfBlend.BlendOp = AC_SRC_OVER;
+  bfBlend.BlendFlags = 0;
+  bfBlend.SourceConstantAlpha = 255;
+  bfBlend.AlphaFormat = AC_SRC_ALPHA;
+
+  if (!UpdateLayeredWindow (pRLWinPriv->hWnd,
+			    NULL, NULL, &szWin,
+			    pRLWinPriv->hdcShadow, &ptSrc,
+			    0, &bfBlend, ULW_ALPHA))
+    {
+      ErrorF ("winMWExtWMStopDrawing - UpdateLayeredWindow failed\n");
+    }
+#endif
+}
+
+void
+winMWExtWMUpdateRegion (RootlessFrameID wid, RegionPtr pDamage)
+{
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
+#if 0
+  BLENDFUNCTION bfBlend;
+  SIZE szWin;
+  POINT ptSrc;
+#endif
+#if CYGMULTIWINDOW_DEBUG && 0
+  winDebug ("winMWExtWMUpdateRegion (%08x)\n", pRLWinPriv);
+#endif
+#if 0
+  szWin.cx = pRLWinPriv->dwWidth;
+  szWin.cy = pRLWinPriv->dwHeight;
+  ptSrc.x = 0;
+  ptSrc.y = 0;
+  bfBlend.BlendOp = AC_SRC_OVER;
+  bfBlend.BlendFlags = 0;
+  bfBlend.SourceConstantAlpha = 255;
+  bfBlend.AlphaFormat = AC_SRC_ALPHA;
+
+  if (!UpdateLayeredWindow (pRLWinPriv->hWnd,
+			    NULL, NULL, &szWin,
+			    pRLWinPriv->hdcShadow, &ptSrc,
+			    0, &bfBlend, ULW_ALPHA))
+    {
+      LPVOID lpMsgBuf;
+      
+      /* Display a fancy error message */
+      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | 
+		     FORMAT_MESSAGE_FROM_SYSTEM | 
+		     FORMAT_MESSAGE_IGNORE_INSERTS,
+		     NULL,
+		     GetLastError (),
+		     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+		     (LPTSTR) &lpMsgBuf,
+		     0, NULL);
+      
+      ErrorF ("winMWExtWMUpdateRegion - UpdateLayeredWindow failed: %s\n",
+	      (LPSTR)lpMsgBuf);
+      LocalFree (lpMsgBuf);
+    }
+#endif
+  if (!g_fNoConfigureWindow) UpdateWindow (pRLWinPriv->hWnd);
+}
+
+void
+winMWExtWMDamageRects (RootlessFrameID wid, int nCount, const BoxRec *pRects,
+			     int shift_x, int shift_y)
+{
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
+  const BoxRec *pEnd;
+#if CYGMULTIWINDOW_DEBUG && 0
+  winDebug ("winMWExtWMDamageRects (%08x, %d, %08x, %d, %d)\n",
+	    pRLWinPriv, nCount, pRects, shift_x, shift_y);
+#endif
+
+  for (pEnd = pRects + nCount; pRects < pEnd; pRects++) {
+        RECT rcDmg;
+        rcDmg.left = pRects->x1 + shift_x;
+        rcDmg.top = pRects->y1 + shift_y;
+        rcDmg.right = pRects->x2 + shift_x;
+        rcDmg.bottom = pRects->y2 + shift_y;
+
+	InvalidateRect (pRLWinPriv->hWnd, &rcDmg, FALSE);
+    }
+}
+
+void
+winMWExtWMRootlessSwitchWindow (RootlessWindowPtr pFrame, WindowPtr oldWin)
+{
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) pFrame->wid;
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMRootlessSwitchWindow (%08x) %08x\n",
+	    (int) pRLWinPriv, (int) pRLWinPriv->hWnd);
+#endif
+  pRLWinPriv->pFrame = pFrame;
+  pRLWinPriv->fResized = TRUE;
+
+  /* Set the window extended style flags */
+  SetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE, WS_EX_TOOLWINDOW);
+
+  /* Set the window standard style flags */
+  SetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE,
+		    WS_POPUP | WS_CLIPCHILDREN);
+
+  DeleteProperty (serverClient, oldWin, AtmWindowsWmNativeHwnd ());
+  winMWExtWMSetNativeProperty (pFrame);
+#if CYGMULTIWINDOW_DEBUG
+#if 0
+ {
+   WindowPtr		pWin2 = NULL;
+   win32RootlessWindowPtr pRLWinPriv2 = NULL;
+
+   /* Check if the Windows window property for our X window pointer is valid */
+   if ((pWin2 = (WindowPtr)GetProp (pRLWinPriv->hWnd, WIN_WINDOW_PROP)) != NULL)
+     {
+       pRLWinPriv2 = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin2, FALSE);
+     }
+   winDebug ("winMWExtWMSwitchFrame2 (%08x) %08x\n",
+	   pRLWinPriv2, pRLWinPriv2->hWnd);
+   if (pRLWinPriv != pRLWinPriv2 || pRLWinPriv->hWnd != pRLWinPriv2->hWnd)
+     {
+       winDebug ("Error param missmatch\n");
+     }
+ }
+#endif
+#endif
+}
+
+void
+winMWExtWMCopyBytes (unsigned int width, unsigned int height,
+			   const void *src, unsigned int srcRowBytes,
+			   void *dst, unsigned int dstRowBytes)
+{
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMCopyBytes - Not implemented\n");
+#endif
+}
+
+void
+winMWExtWMFillBytes (unsigned int width, unsigned int height, unsigned int value,
+			   void *dst, unsigned int dstRowBytes)
+{
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMFillBytes - Not implemented\n");
+#endif
+}
+
+int
+winMWExtWMCompositePixels (unsigned int width, unsigned int height, unsigned int function,
+				 void *src[2], unsigned int srcRowBytes[2],
+				 void *mask, unsigned int maskRowBytes,
+				 void *dst[2], unsigned int dstRowBytes[2])
+{
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMCompositePixels - Not implemented\n");
+#endif
+  return 0;
+}
+
+
+void
+winMWExtWMCopyWindow (RootlessFrameID wid, int nDstRects, const BoxRec *pDstRects,
+			    int nDx, int nDy)
+{
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
+  const BoxRec *pEnd;
+  RECT rcDmg;
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMCopyWindow (%08x, %d, %08x, %d, %d)\n",
+	  (int) pRLWinPriv, nDstRects, (int) pDstRects, nDx, nDy);
+#endif
+
+  for (pEnd = pDstRects + nDstRects; pDstRects < pEnd; pDstRects++)
+    {
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("BitBlt (%d, %d, %d, %d) (%d, %d)\n",
+	      pDstRects->x1, pDstRects->y1,
+	      pDstRects->x2 - pDstRects->x1,
+	      pDstRects->y2 - pDstRects->y1,
+	      pDstRects->x1 + nDx,
+	      pDstRects->y1 + nDy);
+#endif
+
+      if (!BitBlt (pRLWinPriv->hdcShadow,
+		   pDstRects->x1, pDstRects->y1,
+		   pDstRects->x2 - pDstRects->x1,
+		   pDstRects->y2 - pDstRects->y1,
+		   pRLWinPriv->hdcShadow,
+		   pDstRects->x1 + nDx,  pDstRects->y1 + nDy,
+		   SRCCOPY))
+	{
+	  ErrorF ("winMWExtWMCopyWindow - BitBlt failed.\n");
+	}
+      
+      rcDmg.left = pDstRects->x1;
+      rcDmg.top = pDstRects->y1;
+      rcDmg.right = pDstRects->x2;
+      rcDmg.bottom = pDstRects->y2;
+      
+      InvalidateRect (pRLWinPriv->hWnd, &rcDmg, FALSE);
+    }
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMCopyWindow - done\n");
+#endif
+}
+
+
+/*
+ * winMWExtWMSetNativeProperty
+ */
+
+static void
+winMWExtWMSetNativeProperty (RootlessWindowPtr pFrame)
+{
+  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) pFrame->wid;
+  long lData;
+
+  /* FIXME: move this to WindowsWM extension */
+
+  lData = (long) pRLWinPriv->hWnd;
+  dixChangeWindowProperty(serverClient, pFrame->win, AtmWindowsWmNativeHwnd(),
+			  XA_INTEGER, 32, PropModeReplace, 1, &lData, TRUE);
+}
diff --git a/hw/xwin/winwin32rootlesswindow.c b/hw/xwin/winwin32rootlesswindow.c
new file mode 100755
index 0000000..dedcd7a
--- /dev/null
+++ b/hw/xwin/winwin32rootlesswindow.c
@@ -0,0 +1,476 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Kensuke Matsuzaki
+ *		Earle F. Philhower, III
+ *		Harold L Hunt II
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include "winprefs.h"
+
+#if 0
+/*
+ * winMWExtWMReorderWindows
+ */
+
+void
+winMWExtWMReorderWindows (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  HWND hwnd = NULL;
+  win32RootlessWindowPtr pRLWin = NULL;
+  win32RootlessWindowPtr pRLWinSib = NULL;
+  DWORD dwCurrentProcessID = GetCurrentProcessId ();
+  DWORD dwWindowProcessID = 0;
+  XID vlist[2];
+
+#if CYGMULTIWINDOW_DEBUG && FALSE
+  winDebug ("winMWExtWMReorderWindows\n");
+#endif
+
+  pScreenPriv->fRestacking = TRUE;
+
+  if (pScreenPriv->fWindowOrderChanged)
+    {
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMReorderWindows - Need to restack\n");
+#endif
+      hwnd = GetTopWindow (NULL);
+
+      while (hwnd)
+	{
+	  GetWindowThreadProcessId (hwnd, &dwWindowProcessID);
+
+	  if ((dwWindowProcessID == dwCurrentProcessID)
+	      && GetProp (hwnd, WIN_WINDOW_PROP))
+	    {
+	      pRLWinSib = pRLWin;
+	      pRLWin = (win32RootlessWindowPtr)GetProp (hwnd, WIN_WINDOW_PROP);
+	      
+	      if (pRLWinSib)
+		{
+		  vlist[0] = pRLWinSib->pFrame->win->drawable.id;
+		  vlist[1] = Below;
+
+		  ConfigureWindow (pRLWin->pFrame->win, CWSibling | CWStackMode,
+				   vlist, wClient(pRLWin->pFrame->win));
+		}
+	      else
+		{
+		  /* 1st window - raise to the top */
+		  vlist[0] = Above;
+
+		  ConfigureWindow (pRLWin->pFrame->win, CWStackMode,
+				   vlist, wClient(pRLWin->pFrame->win));
+		}
+	    }
+	  hwnd = GetNextWindow (hwnd, GW_HWNDNEXT);
+	}
+    }
+
+  pScreenPriv->fRestacking = FALSE;
+  pScreenPriv->fWindowOrderChanged = FALSE;
+}
+#endif
+
+
+/*
+ * winMWExtWMMoveXWindow
+ */
+
+void
+winMWExtWMMoveXWindow (WindowPtr pWin, int x, int y)
+{
+  CARD32 *vlist = malloc(sizeof(CARD32)*2);
+
+  vlist[0] = x;
+  vlist[1] = y;
+  ConfigureWindow (pWin, CWX | CWY, vlist, wClient(pWin));
+  free(vlist);
+}
+
+
+/*
+ * winMWExtWMResizeXWindow
+ */
+
+void
+winMWExtWMResizeXWindow (WindowPtr pWin, int w, int h)
+{
+  CARD32 *vlist = malloc(sizeof(CARD32)*2);
+
+  vlist[0] = w;
+  vlist[1] = h;
+  ConfigureWindow (pWin, CWWidth | CWHeight, vlist, wClient(pWin));
+  free(vlist);
+}
+
+
+/*
+ * winMWExtWMMoveResizeXWindow
+ */
+
+void
+winMWExtWMMoveResizeXWindow (WindowPtr pWin, int x, int y, int w, int h)
+{
+  CARD32 *vlist = malloc(sizeof(long)*4);
+
+  vlist[0] = x;
+  vlist[1] = y;
+  vlist[2] = w;
+  vlist[3] = h;
+
+  ConfigureWindow (pWin, CWX | CWY | CWWidth | CWHeight, vlist, wClient(pWin));
+  free(vlist);
+}
+
+
+/*
+ * winMWExtWMUpdateIcon
+ * Change the Windows window icon
+ */
+
+void
+winMWExtWMUpdateIcon (Window id)
+{
+  WindowPtr		pWin;
+  HICON			hIcon, hiconOld;
+
+  pWin = (WindowPtr) LookupIDByType (id, RT_WINDOW);
+  hIcon = (HICON)winOverrideIcon ((unsigned long)pWin);
+
+  if (!hIcon)
+    hIcon = winXIconToHICON (pWin, GetSystemMetrics(SM_CXICON));
+
+  if (hIcon)
+    {
+      win32RootlessWindowPtr pRLWinPriv
+	= (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, FALSE);
+
+      if (pRLWinPriv->hWnd)
+	{
+	  hiconOld = (HICON) SetClassLong (pRLWinPriv->hWnd,
+					   GCL_HICON,
+					   (int) hIcon);
+	  
+          winDestroyIcon(hiconOld);
+	}
+    }
+}
+
+
+/*
+ * winMWExtWMDecorateWindow - Update window style. Called by EnumWindows.
+ */
+
+wBOOL CALLBACK
+winMWExtWMDecorateWindow (HWND hwnd, LPARAM lParam)
+{
+  win32RootlessWindowPtr pRLWinPriv = NULL;
+  ScreenPtr		pScreen = NULL;
+  winPrivScreenPtr	pScreenPriv = NULL;
+  winScreenInfo		*pScreenInfo = NULL;
+
+  /* Check if the Windows window property for our X window pointer is valid */
+  if ((pRLWinPriv = (win32RootlessWindowPtr)GetProp (hwnd, WIN_WINDOW_PROP)) != NULL)
+    {
+      pScreen				= pRLWinPriv->pFrame->win->drawable.pScreen;
+      if (pScreen) pScreenPriv		= winGetScreenPriv(pScreen);
+      if (pScreenPriv) pScreenInfo	= pScreenPriv->pScreenInfo;
+      if (pRLWinPriv && pScreenInfo) winMWExtWMUpdateWindowDecoration (pRLWinPriv, pScreenInfo);
+    }
+  return TRUE;
+}
+
+
+/*
+ * winMWExtWMUpdateWindowDecoration - Update window style.
+ */
+
+void
+winMWExtWMUpdateWindowDecoration (win32RootlessWindowPtr pRLWinPriv,
+				  winScreenInfoPtr pScreenInfo)
+{
+  Bool		fDecorate = FALSE;
+  DWORD		dwExStyle = 0;
+  DWORD		dwStyle = 0;
+  WINDOWPLACEMENT wndPlace;
+  UINT		showCmd = 0;
+
+  wndPlace.length = sizeof (WINDOWPLACEMENT);
+
+  /* Get current window placement */
+  GetWindowPlacement (pRLWinPriv->hWnd, &wndPlace);
+
+  if (winIsInternalWMRunning(pScreenInfo))
+    {
+      if (!pRLWinPriv->pFrame->win->overrideRedirect)
+	fDecorate = TRUE;
+    }
+#if 0
+  if (wndPlace.showCmd == SW_HIDE)
+    return;//showCmd = SWP_HIDEWINDOW;
+  else
+    showCmd = SWP_SHOWWINDOW;
+#else
+  if (wndPlace.showCmd == SW_HIDE)
+    return;
+
+  if (IsWindowVisible (pRLWinPriv->hWnd))
+    showCmd = SWP_SHOWWINDOW;
+#endif
+
+  showCmd |= SWP_NOMOVE | SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOZORDER;
+
+  winDebug ("winMWExtWMUpdateWindowDecoration %08x %s\n",
+	    (int)pRLWinPriv, fDecorate?"Decorate":"Bare");
+
+  /* Get the standard and extended window style information */
+  dwExStyle = GetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE);
+  dwStyle = GetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE);
+
+  if (fDecorate)
+    {
+      RECT		rcNew;
+      int		iDx, iDy;
+      winWMMessageRec	wmMsg;
+      winScreenPriv(pScreenInfo->pScreen);
+
+      /* */
+      if (!(dwExStyle & WS_EX_APPWINDOW))
+	{
+	  winDebug ("\tBare=>Decorate\n");
+	  /* Setup a rectangle with the X window position and size */
+	  SetRect (&rcNew,
+		   pRLWinPriv->pFrame->x,
+		   pRLWinPriv->pFrame->y,
+		   pRLWinPriv->pFrame->x + pRLWinPriv->pFrame->width,
+		   pRLWinPriv->pFrame->y + pRLWinPriv->pFrame->height);
+
+#ifdef CYGMULTIWINDOW_DEBUG
+          winDebug("\tWindow extend {%d, %d, %d, %d}, {%d, %d}\n", 
+              rcNew.left, rcNew.top, rcNew.right, rcNew.bottom,
+              rcNew.right - rcNew.left, rcNew.bottom - rcNew.top);
+#endif
+	  /* */
+	  AdjustWindowRectEx (&rcNew,
+			      WS_POPUP | WS_SIZEBOX | WS_OVERLAPPEDWINDOW,
+			      FALSE,
+			      WS_EX_APPWINDOW);
+
+#ifdef CYGMULTIWINDOW_DEBUG
+          winDebug("\tAdjusted {%d, %d, %d, %d}, {%d, %d}\n", 
+              rcNew.left, rcNew.top, rcNew.right, rcNew.bottom,
+              rcNew.right - rcNew.left, rcNew.bottom - rcNew.top);
+#endif
+	  /* Calculate position deltas */
+	  iDx = pRLWinPriv->pFrame->x - rcNew.left;
+	  iDy = pRLWinPriv->pFrame->y - rcNew.top;
+
+	  /* Calculate new rectangle */
+	  rcNew.left += iDx;
+	  rcNew.right += iDx;
+	  rcNew.top += iDy;
+	  rcNew.bottom += iDy;
+
+	  /* Set the window extended style flags */
+	  SetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE, WS_EX_APPWINDOW);
+
+	  /* Set the window standard style flags */
+	  SetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE,
+			    WS_POPUP | WS_SIZEBOX | WS_OVERLAPPEDWINDOW);
+
+#ifdef CYGMULTIWINDOW_DEBUG
+          winDebug("\tWindowStyle: %08x %08x\n",
+              WS_POPUP | WS_SIZEBOX | WS_OVERLAPPEDWINDOW,
+              WS_EX_APPWINDOW);
+#endif
+	  /* Position the Windows window */
+#ifdef CYGMULTIWINDOW_DEBUG
+          winDebug("\tMoved {%d, %d, %d, %d}, {%d, %d}\n", 
+              rcNew.left, rcNew.top, rcNew.right, rcNew.bottom,
+              rcNew.right - rcNew.left, rcNew.bottom - rcNew.top);
+#endif
+	  SetWindowPos (pRLWinPriv->hWnd, NULL,
+			rcNew.left, rcNew.top,
+			rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
+			showCmd);
+            
+
+	  wmMsg.hwndWindow = pRLWinPriv->hWnd;
+	  wmMsg.iWindow	= (Window)pRLWinPriv->pFrame->win->drawable.id;
+	  wmMsg.msg = WM_WM_NAME_EVENT;
+	  winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
+
+	  winMWExtWMReshapeFrame ((RootlessFrameID)pRLWinPriv ,
+				  wBoundingShape(pRLWinPriv->pFrame->win));
+	}
+    }
+  else
+    {
+      RECT		rcNew;
+
+      /* */
+      if (dwExStyle & WS_EX_APPWINDOW)
+	{
+	  winDebug ("\tDecorate=>Bare\n");
+	  /* Setup a rectangle with the X window position and size */
+	  SetRect (&rcNew,
+		   pRLWinPriv->pFrame->x,
+		   pRLWinPriv->pFrame->y,
+		   pRLWinPriv->pFrame->x + pRLWinPriv->pFrame->width,
+		   pRLWinPriv->pFrame->y + pRLWinPriv->pFrame->height);
+#if 0
+	  /* */
+	  AdjustWindowRectEx (&rcNew,
+			      WS_POPUP | WS_CLIPCHILDREN,
+			      FALSE,
+			      WS_EX_TOOLWINDOW);
+
+	  /* Calculate position deltas */
+	  iDx = pRLWinPriv->pFrame->x - rcNew.left;
+	  iDy = pRLWinPriv->pFrame->y - rcNew.top;
+
+	  /* Calculate new rectangle */
+	  rcNew.left += iDx;
+	  rcNew.right += iDx;
+	  rcNew.top += iDy;
+	  rcNew.bottom += iDy;
+#endif
+
+	  /* Hide window temporary to remove from taskbar. */
+	  ShowWindow( pRLWinPriv->hWnd, SW_HIDE );
+
+	  /* Set the window extended style flags */
+	  SetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE, WS_EX_TOOLWINDOW);
+
+	  /* Set the window standard style flags */
+	  SetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE,
+			    WS_POPUP | WS_CLIPCHILDREN);
+
+	  /* Position the Windows window */
+	  SetWindowPos (pRLWinPriv->hWnd, NULL,
+			rcNew.left, rcNew.top,
+			rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
+			showCmd);
+
+	  winMWExtWMReshapeFrame ((RootlessFrameID)pRLWinPriv ,
+				  wBoundingShape(pRLWinPriv->pFrame->win));
+	}
+    }
+}
+
+
+/*
+ * winIsInternalWMRunning (winScreenInfoPtr pScreenInfo)
+ */
+Bool
+winIsInternalWMRunning (winScreenInfoPtr pScreenInfo)
+{
+  return pScreenInfo->fInternalWM && !pScreenInfo->fAnotherWMRunning;
+}
+
+
+/*
+ * winMWExtWMRestackWindows
+ */
+
+void
+winMWExtWMRestackWindows (ScreenPtr pScreen)
+{
+  winScreenPriv(pScreen);
+  WindowPtr pRoot = WindowTable[pScreen->myNum];
+  WindowPtr pWin = NULL;
+  WindowPtr pWinPrev = NULL;
+  win32RootlessWindowPtr pRLWin = NULL;
+  win32RootlessWindowPtr pRLWinPrev = NULL;
+  int  nWindow = 0;
+  HDWP hWinPosInfo = NULL;
+
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMRestackWindows\n");
+#endif
+
+  pScreenPriv->fRestacking = TRUE;
+
+  if (pRoot != NULL)
+    {
+      for (pWin = pRoot->firstChild; pWin; pWin = pWin->nextSib)
+	nWindow ++;
+
+      hWinPosInfo = BeginDeferWindowPos(nWindow);
+
+      for (pWin = pRoot->firstChild; pWin; pWin = pWin->nextSib)
+	{
+	  if (pWin->realized)
+	    {
+	      UINT uFlags;
+
+	      pRLWin = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, FALSE);
+	      if (pRLWin == NULL) continue;
+
+	      if (pWinPrev)
+		pRLWinPrev = (win32RootlessWindowPtr) RootlessFrameForWindow (pWinPrev, FALSE);
+
+	      uFlags = SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW;
+	      if (pRLWinPrev != NULL) uFlags |= SWP_NOACTIVATE;
+
+#if CYGMULTIWINDOW_DEBUG
+	      winDebug ("winMWExtWMRestackWindows - DeferWindowPos (%08x, %08x)\n",
+			pRLWin->hWnd,
+			pRLWinPrev ? pRLWinPrev->hWnd : HWND_TOP);
+#endif
+	      hWinPosInfo = DeferWindowPos (hWinPosInfo, pRLWin->hWnd,
+					    pRLWinPrev ? pRLWinPrev->hWnd : HWND_TOP,
+					    0, 0, 0, 0,
+					    uFlags);
+	      if (hWinPosInfo == NULL)
+		{
+		  ErrorF ("winMWExtWMRestackWindows - DeferWindowPos () failed: %d\n",
+			  (int) GetLastError ());
+		  return;
+		}
+	      pWinPrev = pWin;
+	    }
+	}
+      if (!EndDeferWindowPos (hWinPosInfo))
+	{
+	  ErrorF ("winMWExtWMRestackWindows - EndDeferWindowPos () failed: %d\n",
+		  (int) GetLastError ());
+	  return;
+	}
+    }
+
+#if CYGMULTIWINDOW_DEBUG
+  winDebug ("winMWExtWMRestackWindows - done\n");
+#endif
+  pScreenPriv->fRestacking = FALSE;
+}
diff --git a/hw/xwin/winwin32rootlesswndproc.c b/hw/xwin/winwin32rootlesswndproc.c
new file mode 100755
index 0000000..859aafd
--- /dev/null
+++ b/hw/xwin/winwin32rootlesswndproc.c
@@ -0,0 +1,1325 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Kensuke Matsuzaki
+ *		Earle F. Philhower, III
+ *		Harold L Hunt II
+ */
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include <winuser.h>
+#define _WINDOWSWM_SERVER_
+#include "windowswmstr.h"
+#include "dixevents.h"
+#include "propertyst.h"
+#include <X11/Xatom.h>
+#include "winmultiwindowclass.h"
+#include "winmsg.h"
+#include "inputstr.h"
+
+
+/*
+ * Constant defines
+ */
+
+#define MOUSE_POLLING_INTERVAL		500
+#define MOUSE_ACTIVATE_DEFAULT		TRUE
+#define RAISE_ON_CLICK_DEFAULT		FALSE
+
+
+/*
+ * Global variables
+ */
+
+extern Bool			g_fNoConfigureWindow;
+extern Bool			g_fSoftwareCursor;
+
+
+/*
+ * Local globals
+ */
+
+static UINT_PTR		g_uipMousePollingTimerID = 0;
+
+
+/*
+ * Local function
+ */
+
+DEFINE_ATOM_HELPER(AtmWindowsWmRaiseOnClick, WINDOWSWM_RAISE_ON_CLICK)
+DEFINE_ATOM_HELPER(AtmWindowsWMMouseActivate, WINDOWSWM_MOUSE_ACTIVATE)
+/* DEFINE_ATOM_HELPER(AtmWindowsWMClientWindow, WINDOWSWM_CLIENT_WINDOW) */
+
+/*
+ * ConstrainSize - Taken from TWM sources - Respects hints for sizing
+ */
+#define makemult(a,b) ((b==1) ? (a) : (((int)((a)/(b))) * (b)) )
+static void
+ConstrainSize (WinXSizeHints hints, int *widthp, int *heightp)
+{
+  int minWidth, minHeight, maxWidth, maxHeight, xinc, yinc, delta;
+  int baseWidth, baseHeight;
+  int dwidth = *widthp, dheight = *heightp;
+  
+  if (hints.flags & PMinSize)
+    {
+      minWidth = hints.min_width;
+      minHeight = hints.min_height;
+    }
+  else if (hints.flags & PBaseSize)
+    {
+      minWidth = hints.base_width;
+      minHeight = hints.base_height;
+    }
+  else
+    minWidth = minHeight = 1;
+  
+  if (hints.flags & PBaseSize)
+    {
+      baseWidth = hints.base_width;
+      baseHeight = hints.base_height;
+    } 
+  else if (hints.flags & PMinSize)
+    {
+      baseWidth = hints.min_width;
+      baseHeight = hints.min_height;
+    }
+  else
+    baseWidth = baseHeight = 0;
+
+  if (hints.flags & PMaxSize)
+    {
+      maxWidth = hints.max_width;
+      maxHeight = hints.max_height;
+    }
+  else
+    {
+      maxWidth = MAXINT;
+      maxHeight = MAXINT;
+    }
+
+  if (hints.flags & PResizeInc)
+    {
+      xinc = hints.width_inc;
+      yinc = hints.height_inc;
+    }
+  else
+    xinc = yinc = 1;
+
+  /*
+   * First, clamp to min and max values
+   */
+  if (dwidth < minWidth)
+    dwidth = minWidth;
+  if (dheight < minHeight)
+    dheight = minHeight;
+
+  if (dwidth > maxWidth)
+    dwidth = maxWidth;
+  if (dheight > maxHeight)
+    dheight = maxHeight;
+
+  /*
+   * Second, fit to base + N * inc
+   */
+  dwidth = ((dwidth - baseWidth) / xinc * xinc) + baseWidth;
+  dheight = ((dheight - baseHeight) / yinc * yinc) + baseHeight;
+  
+  /*
+   * Third, adjust for aspect ratio
+   */
+
+  /*
+   * The math looks like this:
+   *
+   * minAspectX    dwidth     maxAspectX
+   * ---------- <= ------- <= ----------
+   * minAspectY    dheight    maxAspectY
+   *
+   * If that is multiplied out, then the width and height are
+   * invalid in the following situations:
+   *
+   * minAspectX * dheight > minAspectY * dwidth
+   * maxAspectX * dheight < maxAspectY * dwidth
+   * 
+   */
+  
+  if (hints.flags & PAspect)
+    {
+      if (hints.min_aspect.x * dheight > hints.min_aspect.y * dwidth)
+        {
+	  delta = makemult(hints.min_aspect.x * dheight / hints.min_aspect.y - dwidth, xinc);
+	  if (dwidth + delta <= maxWidth)
+	    dwidth += delta;
+	  else
+            {
+	      delta = makemult(dheight - dwidth*hints.min_aspect.y/hints.min_aspect.x, yinc);
+	      if (dheight - delta >= minHeight)
+		dheight -= delta;
+            }
+        }
+      
+      if (hints.max_aspect.x * dheight < hints.max_aspect.y * dwidth)
+        {
+	  delta = makemult(dwidth * hints.max_aspect.y / hints.max_aspect.x - dheight, yinc);
+	  if (dheight + delta <= maxHeight)
+	    dheight += delta;
+	  else
+            {
+	      delta = makemult(dwidth - hints.max_aspect.x*dheight/hints.max_aspect.y, xinc);
+	      if (dwidth - delta >= minWidth)
+		dwidth -= delta;
+            }
+        }
+    }
+  
+  /* Return computed values */
+  *widthp = dwidth;
+  *heightp = dheight;
+}
+#undef makemult
+
+
+
+/*
+ * ValidateSizing - Ensures size request respects hints
+ */
+static int
+ValidateSizing (HWND hwnd, WindowPtr pWin,
+		WPARAM wParam, LPARAM lParam)
+{
+  WinXSizeHints sizeHints;
+  RECT *rect;
+  int iWidth, iHeight, iTopBorder;
+  POINT pt;
+
+  /* Invalid input checking */
+  if (pWin==NULL || lParam==0)
+    {
+      ErrorF ("Invalid input checking\n");
+      return FALSE;
+    }
+
+  /* No size hints, no checking */
+  if (!winMultiWindowGetWMNormalHints (pWin, &sizeHints))
+    {
+      ErrorF ("No size hints, no checking\n");
+      return FALSE;
+    }
+  
+  /* Avoid divide-by-zero */
+  if (sizeHints.flags & PResizeInc)
+    {
+      if (sizeHints.width_inc == 0) sizeHints.width_inc = 1;
+      if (sizeHints.height_inc == 0) sizeHints.height_inc = 1;
+    }
+  
+  rect = (RECT*)lParam;
+  
+  iWidth = rect->right - rect->left;
+  iHeight = rect->bottom - rect->top;
+
+  /* Get title bar height, there must be an easier way?! */
+  pt.x = pt.y = 0;
+  ClientToScreen(hwnd, &pt);
+  iTopBorder = pt.y - rect->top;
+  
+  /* Now remove size of any borders */
+  iWidth -= 2 * GetSystemMetrics(SM_CXSIZEFRAME);
+  iHeight -= GetSystemMetrics(SM_CYSIZEFRAME) + iTopBorder;
+
+  /* Constrain the size to legal values */
+  ConstrainSize (sizeHints, &iWidth, &iHeight);
+
+  /* Add back the borders */
+  iWidth += 2 * GetSystemMetrics(SM_CXSIZEFRAME);
+  iHeight += GetSystemMetrics(SM_CYSIZEFRAME) + iTopBorder;
+
+  /* Adjust size according to where we're dragging from */
+  switch(wParam) {
+  case WMSZ_TOP:
+  case WMSZ_TOPRIGHT:
+  case WMSZ_BOTTOM:
+  case WMSZ_BOTTOMRIGHT:
+  case WMSZ_RIGHT:
+    rect->right = rect->left + iWidth;
+    break;
+  default:
+    rect->left = rect->right - iWidth;
+    break;
+  }
+  switch(wParam) {
+  case WMSZ_BOTTOM:
+  case WMSZ_BOTTOMRIGHT:
+  case WMSZ_BOTTOMLEFT:
+  case WMSZ_RIGHT:
+  case WMSZ_LEFT:
+    rect->bottom = rect->top + iHeight;
+    break;
+  default:
+    rect->top = rect->bottom - iHeight;
+    break;
+  }
+  return TRUE;
+}
+
+
+/*
+ * IsRaiseOnClick
+ */
+
+static Bool
+IsRaiseOnClick (WindowPtr pWin)
+{
+
+  struct _Window	*pwin;
+  struct _Property	*prop;  
+  WindowPtr		pRoot = GetCurrentRootWindow ();
+
+  if (!pWin)
+    {
+      ErrorF ("IsRaiseOnClick - no prop use default value:%d\n",
+	      RAISE_ON_CLICK_DEFAULT);
+      return RAISE_ON_CLICK_DEFAULT;
+    } 
+
+  pwin = (struct _Window*) pWin;
+
+  if (pwin->optional)
+    prop = (struct _Property *) pwin->optional->userProps;
+  else
+    prop = NULL;
+
+  while (prop)
+    {
+      if (prop->propertyName == AtmWindowsWmRaiseOnClick ()
+	  && prop->type == XA_INTEGER
+	  && prop->format == 32)
+	{
+	  return *(int*)prop->data;
+	}
+      else
+	prop = prop->next;
+    }
+
+  if (pWin != pRoot)
+    {
+      return IsRaiseOnClick (pRoot);
+    }
+  else
+    {
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("IsRaiseOnClick - no prop use default value:%d\n",
+		RAISE_ON_CLICK_DEFAULT);
+#endif
+      return RAISE_ON_CLICK_DEFAULT;
+    }
+}
+
+
+/*
+ * IsMouseActive
+ */
+
+static Bool
+IsMouseActive (WindowPtr pWin)
+{
+
+  struct _Window	*pwin;
+  struct _Property	*prop;
+  WindowPtr		pRoot = GetCurrentRootWindow ();
+
+  if (!pWin)
+    {
+      ErrorF ("IsMouseActive - pWin was NULL use default value:%d\n",
+	      MOUSE_ACTIVATE_DEFAULT);
+      return MOUSE_ACTIVATE_DEFAULT;
+    } 
+
+  pwin = (struct _Window*) pWin;
+
+  if (pwin->optional)
+    prop = (struct _Property *) pwin->optional->userProps;
+  else
+    prop = NULL;
+
+  while (prop)
+    {
+      if (prop->propertyName == AtmWindowsWMMouseActivate ()
+	  && prop->type == XA_INTEGER
+	  && prop->format == 32)
+	{
+	  return *(int*)prop->data;
+	}
+      else
+	prop = prop->next;
+    }
+
+  if (pWin != pRoot)
+    {
+      return IsMouseActive (pRoot);
+    }
+  else
+    {
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("IsMouseActive - no prop use default value:%d\n",
+		MOUSE_ACTIVATE_DEFAULT);
+#endif
+      return MOUSE_ACTIVATE_DEFAULT;
+    }
+}
+
+
+/*
+ * winMWExtWMWindowProc - Window procedure
+ */
+
+LRESULT CALLBACK
+winMWExtWMWindowProc (HWND hwnd, UINT message, 
+			    WPARAM wParam, LPARAM lParam)
+{
+  WindowPtr		pWin = NULL;
+  win32RootlessWindowPtr pRLWinPriv = NULL;
+  ScreenPtr		pScreen = NULL;
+  winPrivScreenPtr	pScreenPriv = NULL;
+  winScreenInfo		*pScreenInfo = NULL;
+  HWND			hwndScreen = NULL;
+  POINT			ptMouse;
+  static Bool		s_fTracking = FALSE;
+  HDC			hdcUpdate;
+  PAINTSTRUCT		ps;
+  LPWINDOWPOS		pWinPos = NULL;
+  RECT			rcClient;
+  winWMMessageRec	wmMsg;
+  Bool			fWMMsgInitialized = FALSE;
+
+  /* Check if the Windows window property for our X window pointer is valid */
+  if ((pRLWinPriv = (win32RootlessWindowPtr)GetProp (hwnd, WIN_WINDOW_PROP)) != NULL)
+    {
+      pWin = pRLWinPriv->pFrame->win;
+      pScreen				= pWin->drawable.pScreen;
+      if (pScreen) pScreenPriv		= winGetScreenPriv(pScreen);
+      if (pScreenPriv) pScreenInfo	= pScreenPriv->pScreenInfo;
+      if (pScreenPriv) hwndScreen	= pScreenPriv->hwndScreen;
+
+      wmMsg.msg		= 0;
+      wmMsg.hwndWindow	= hwnd;
+      wmMsg.iWindow	= (Window)pWin->drawable.id;
+
+      wmMsg.iX		= pRLWinPriv->pFrame->x;
+      wmMsg.iY		= pRLWinPriv->pFrame->y;
+      wmMsg.iWidth	= pRLWinPriv->pFrame->width;
+      wmMsg.iHeight	= pRLWinPriv->pFrame->height;
+
+      fWMMsgInitialized = TRUE;
+#if CYGDEBUG
+      winDebugWin32Message("winMWExtWMWindowProc", hwnd, message, wParam, lParam);
+
+      winDebug ("\thWnd %08X\n", hwnd);
+      winDebug ("\tpScreenPriv %08X\n", pScreenPriv);
+      winDebug ("\tpScreenInfo %08X\n", pScreenInfo);
+      winDebug ("\thwndScreen %08X\n", hwndScreen);
+      winDebug ("winMWExtWMWindowProc (%08x) %08x %08x %08x\n",
+	      pRLWinPriv, message, wParam, lParam);
+#endif
+    }
+  /* Branch on message type */
+  switch (message)
+    {
+    case WM_CREATE:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_CREATE\n");
+#endif
+      /* */
+      SetProp (hwnd,
+	       WIN_WINDOW_PROP,
+	       (HANDLE)((LPCREATESTRUCT) lParam)->lpCreateParams);
+      return 0;
+
+    case WM_CLOSE:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_CLOSE %d\n", pRLWinPriv->fClose);
+#endif
+      /* Tell window-manager to close window */
+      if (pRLWinPriv->fClose)
+	{
+	  DestroyWindow (hwnd);
+	}
+      else
+	{
+	  if (winIsInternalWMRunning(pScreenInfo))
+	    {
+	      /* Tell our Window Manager thread to kill the window */
+	      wmMsg.msg = WM_WM_KILL;
+	      if (fWMMsgInitialized)
+		winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
+	    }
+	  winWindowsWMSendEvent(WindowsWMControllerNotify,
+				WindowsWMControllerNotifyMask,
+				1,
+				WindowsWMCloseWindow,
+				pWin->drawable.id,
+				0, 0, 0, 0);
+	}
+      return 0;
+
+    case WM_DESTROY:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_DESTROY\n");
+#endif
+      /* Free the shaodw DC; which allows the bitmap to be freed */
+      DeleteDC (pRLWinPriv->hdcShadow);
+      pRLWinPriv->hdcShadow = NULL;
+      
+      /* Free the shadow bitmap */
+      DeleteObject (pRLWinPriv->hbmpShadow);
+      pRLWinPriv->hbmpShadow = NULL;
+      
+      /* Free the screen DC */
+      ReleaseDC (pRLWinPriv->hWnd, pRLWinPriv->hdcScreen);
+      pRLWinPriv->hdcScreen = NULL;
+
+      /* Free shadow buffer info header */
+      free (pRLWinPriv->pbmihShadow);
+      pRLWinPriv->pbmihShadow = NULL;
+      
+      pRLWinPriv->fResized = FALSE;
+      pRLWinPriv->pfb = NULL;
+      free (pRLWinPriv);
+      RemoveProp (hwnd, WIN_WINDOW_PROP);
+      break;
+
+    case WM_MOUSEMOVE:
+#if CYGMULTIWINDOW_DEBUG && 0
+      winDebug ("winMWExtWMWindowProc - WM_MOUSEMOVE\n");
+#endif
+      /* Unpack the client area mouse coordinates */
+      ptMouse.x = GET_X_LPARAM(lParam);
+      ptMouse.y = GET_Y_LPARAM(lParam);
+
+      /* Translate the client area mouse coordinates to screen coordinates */
+      ClientToScreen (hwnd, &ptMouse);
+
+      /* Screen Coords from (-X, -Y) -> Root Window (0, 0) */
+      ptMouse.x -= GetSystemMetrics (SM_XVIRTUALSCREEN);
+      ptMouse.y -= GetSystemMetrics (SM_YVIRTUALSCREEN);
+
+      /* We can't do anything without privates */
+      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
+	break;
+
+      /* Has the mouse pointer crossed screens? */
+      if (pScreen != miPointerGetScreen(inputInfo.pointer))
+	miPointerSetScreen (inputInfo.pointer, pScreenInfo->dwScreen,
+			       ptMouse.x - pScreenInfo->dwXOffset,
+			       ptMouse.y - pScreenInfo->dwYOffset);
+
+      /* Are we tracking yet? */
+      if (!s_fTracking)
+	{
+	  TRACKMOUSEEVENT		tme;
+	  
+	  /* Setup data structure */
+	  ZeroMemory (&tme, sizeof (tme));
+	  tme.cbSize = sizeof (tme);
+	  tme.dwFlags = TME_LEAVE;
+	  tme.hwndTrack = hwnd;
+
+	  /* Call the tracking function */
+	  if (!(*g_fpTrackMouseEvent) (&tme))
+	    ErrorF ("winMWExtWMWindowProc - _TrackMouseEvent failed\n");
+
+	  /* Flag that we are tracking now */
+	  s_fTracking = TRUE;
+	}
+      
+      /* Kill the timer used to poll mouse events */
+      if (g_uipMousePollingTimerID != 0)
+	{
+	  KillTimer (pScreenPriv->hwndScreen, WIN_POLLING_MOUSE_TIMER_ID);
+	  g_uipMousePollingTimerID = 0;
+	}
+
+      /* Deliver absolute cursor position to X Server */
+      miPointerAbsoluteCursor (ptMouse.x - pScreenInfo->dwXOffset,
+			       ptMouse.y - pScreenInfo->dwYOffset,
+			       g_c32LastInputEventTime = GetTickCount ());
+      return 0;
+      
+    case WM_NCMOUSEMOVE:
+#if CYGMULTIWINDOW_DEBUG && 0
+      winDebug ("winMWExtWMWindowProc - WM_NCMOUSEMOVE\n");
+#endif
+      /*
+       * We break instead of returning 0 since we need to call
+       * DefWindowProc to get the mouse cursor changes
+       * and min/max/close button highlighting in Windows XP.
+       * The Platform SDK says that you should return 0 if you
+       * process this message, but it fails to mention that you
+       * will give up any default functionality if you do return 0.
+       */
+      
+      /* We can't do anything without privates */
+      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
+	break;
+
+      /*
+       * Timer to poll mouse events.  This is needed to make
+       * programs like xeyes follow the mouse properly.
+       */
+      if (g_uipMousePollingTimerID == 0)
+	g_uipMousePollingTimerID = SetTimer (pScreenPriv->hwndScreen,
+					     WIN_POLLING_MOUSE_TIMER_ID,
+					     MOUSE_POLLING_INTERVAL,
+					     NULL);
+      break;
+
+    case WM_MOUSELEAVE:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_MOUSELEAVE\n");
+#endif
+      /* Mouse has left our client area */
+
+      /* Flag that we are no longer tracking */
+      s_fTracking = FALSE;
+
+      /*
+       * Timer to poll mouse events.  This is needed to make
+       * programs like xeyes follow the mouse properly.
+       */
+      if (g_uipMousePollingTimerID == 0)
+	g_uipMousePollingTimerID = SetTimer (pScreenPriv->hwndScreen,
+					     WIN_POLLING_MOUSE_TIMER_ID,
+					     MOUSE_POLLING_INTERVAL,
+					     NULL);
+      return 0;
+
+    case WM_LBUTTONDBLCLK:
+    case WM_LBUTTONDOWN:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_LBUTTONDBLCLK\n");
+#endif
+      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
+	break;
+      SetCapture (hwnd);
+      return winMouseButtonsHandle (pScreen, ButtonPress, Button1, wParam);
+      
+    case WM_LBUTTONUP:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_LBUTTONUP\n");
+#endif
+      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
+	break;
+      ReleaseCapture ();
+      return winMouseButtonsHandle (pScreen, ButtonRelease, Button1, wParam);
+
+    case WM_MBUTTONDBLCLK:
+    case WM_MBUTTONDOWN:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_MBUTTONDBLCLK\n");
+#endif
+      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
+	break;
+      SetCapture (hwnd);
+      return winMouseButtonsHandle (pScreen, ButtonPress, Button2, wParam);
+      
+    case WM_MBUTTONUP:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_MBUTTONUP\n");
+#endif
+      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
+	break;
+      ReleaseCapture ();
+      return winMouseButtonsHandle (pScreen, ButtonRelease, Button2, wParam);
+      
+    case WM_RBUTTONDBLCLK:
+    case WM_RBUTTONDOWN:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_RBUTTONDBLCLK\n");
+#endif
+      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
+	break;
+      SetCapture (hwnd);
+      return winMouseButtonsHandle (pScreen, ButtonPress, Button3, wParam);
+      
+    case WM_RBUTTONUP:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_RBUTTONUP\n");
+#endif
+      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
+	break;
+      ReleaseCapture ();
+      return winMouseButtonsHandle (pScreen, ButtonRelease, Button3, wParam);
+
+    case WM_XBUTTONDBLCLK:
+    case WM_XBUTTONDOWN:
+      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
+	break;
+      SetCapture (hwnd);
+      return winMouseButtonsHandle (pScreen, ButtonPress, HIWORD(wParam) + 5, wParam);
+    case WM_XBUTTONUP:
+      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
+	break;
+      ReleaseCapture ();
+      return winMouseButtonsHandle (pScreen, ButtonRelease, HIWORD(wParam) + 5, wParam);
+
+    case WM_MOUSEWHEEL:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_MOUSEWHEEL\n");
+#endif
+      
+      /* Pass the message to the root window */
+      SendMessage (hwndScreen, message, wParam, lParam);
+      return 0;
+
+    case WM_MOUSEACTIVATE:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_MOUSEACTIVATE\n");
+#endif
+#if 1
+      /* Check if this window needs to be made active when clicked */
+      if (winIsInternalWMRunning(pScreenInfo) && pWin->overrideRedirect)
+	{
+#if CYGMULTIWINDOW_DEBUG
+	  winDebug ("winMWExtWMWindowProc - WM_MOUSEACTIVATE - "
+		    "MA_NOACTIVATE\n");
+#endif
+
+	  /* */
+	  return MA_NOACTIVATE;
+	}
+#endif
+      if (!winIsInternalWMRunning(pScreenInfo) && !IsMouseActive (pWin))
+	return MA_NOACTIVATE;
+
+      break;
+
+    case WM_KILLFOCUS:
+      /* Pop any pressed keys since we are losing keyboard focus */
+      winKeybdReleaseKeys ();
+      return 0;
+
+    case WM_SYSDEADCHAR:
+    case WM_DEADCHAR:
+      /*
+       * NOTE: We do nothing with WM_*CHAR messages,
+       * nor does the root window, so we can just toss these messages.
+       */
+      return 0;
+
+    case WM_SYSKEYDOWN:
+    case WM_KEYDOWN:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_*KEYDOWN\n");
+#endif
+
+      /*
+       * Don't pass Alt-F4 key combo to root window,
+       * let Windows translate to WM_CLOSE and close this top-level window.
+       *
+       * NOTE: We purposely don't check the fUseWinKillKey setting because
+       * it should only apply to the key handling for the root window,
+       * not for top-level window-manager windows.
+       *
+       * ALSO NOTE: We do pass Ctrl-Alt-Backspace to the root window
+       * because that is a key combo that no X app should be expecting to
+       * receive, since it has historically been used to shutdown the X server.
+       * Passing Ctrl-Alt-Backspace to the root window preserves that
+       * behavior, assuming that -unixkill has been passed as a parameter.
+       */
+      if (wParam == VK_F4 && (GetKeyState (VK_MENU) & 0x8000))
+	  break;
+
+      /* Pass the message to the root window */
+      SendMessage (hwndScreen, message, wParam, lParam);
+      return 0;
+
+    case WM_SYSKEYUP:
+    case WM_KEYUP:
+
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_*KEYUP\n");
+#endif
+
+      /* Pass the message to the root window */
+      SendMessage (hwndScreen, message, wParam, lParam);
+      return 0;
+
+    case WM_HOTKEY:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_HOTKEY\n");
+#endif
+
+      /* Pass the message to the root window */
+      SendMessage (hwndScreen, message, wParam, lParam);
+      return 0;
+
+    case WM_PAINT:
+    
+      /* BeginPaint gives us an hdc that clips to the invalidated region */
+      hdcUpdate = BeginPaint (hwnd, &ps);
+
+      /* Try to copy from the shadow buffer */
+      if (!BitBlt (hdcUpdate,
+		   ps.rcPaint.left, ps.rcPaint.top,
+		   ps.rcPaint.right - ps.rcPaint.left,
+		   ps.rcPaint.bottom - ps.rcPaint.top,
+		   pRLWinPriv->hdcShadow,
+		   ps.rcPaint.left, ps.rcPaint.top,
+		   SRCCOPY))
+	{
+	  LPVOID lpMsgBuf;
+	  
+	  /* Display a fancy error message */
+	  FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | 
+			 FORMAT_MESSAGE_FROM_SYSTEM | 
+			 FORMAT_MESSAGE_IGNORE_INSERTS,
+			 NULL,
+			 GetLastError (),
+			 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+			 (LPTSTR) &lpMsgBuf,
+			 0, NULL);
+
+	  ErrorF ("winMWExtWMWindowProc - BitBlt failed: %s\n",
+		  (LPSTR)lpMsgBuf);
+	  LocalFree (lpMsgBuf);
+	}
+
+      /* EndPaint frees the DC */
+      EndPaint (hwnd, &ps);
+      break;
+
+    case WM_ACTIVATE:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_ACTIVATE\n");
+#endif
+      if (LOWORD(wParam) != WA_INACTIVE)
+	{
+	  if (winIsInternalWMRunning(pScreenInfo))
+	    {
+#if 0
+	      /* Raise the window to the top in Z order */
+	      wmMsg.msg = WM_WM_RAISE;
+	      if (fWMMsgInitialized)
+		winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
+#endif
+	      /* Tell our Window Manager thread to activate the window */
+	      wmMsg.msg = WM_WM_ACTIVATE;
+	      if (fWMMsgInitialized)
+		if (!pWin || !pWin->overrideRedirect) /* for OOo menus */
+		  winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
+	    }
+	  winWindowsWMSendEvent(WindowsWMControllerNotify,
+				WindowsWMControllerNotifyMask,
+				1,
+				WindowsWMActivateWindow,
+				pWin->drawable.id,
+				0, 0,
+				0, 0);
+	}
+      return 0;
+
+#if 1
+    case WM_WINDOWPOSCHANGING:
+      pWinPos = (LPWINDOWPOS)lParam;
+      if (!(pWinPos->flags & SWP_NOZORDER))
+	{
+	  if (pRLWinPriv->fRestackingNow || pScreenPriv->fRestacking)
+	    {
+#if CYGMULTIWINDOW_DEBUG
+	      winDebug ("Win %08x is now restacking.\n", (unsigned int)pRLWinPriv);
+#endif
+	      break;
+	    }
+
+	  if (winIsInternalWMRunning(pScreenInfo) || IsRaiseOnClick (pWin))
+	    {
+#if CYGMULTIWINDOW_DEBUG
+	      winDebug ("Win %08x has WINDOWSWM_RAISE_ON_CLICK.\n", (unsigned int)pRLWinPriv);
+#endif
+	      break;
+	    }
+
+#if CYGMULTIWINDOW_DEBUG
+	  winDebug ("Win %08x forbid to change z order (%08x).\n",
+		    (unsigned int)pRLWinPriv, (unsigned int)pWinPos->hwndInsertAfter);
+#endif
+	  pWinPos->flags |= SWP_NOZORDER;
+	}
+      break;
+#endif
+
+    case WM_MOVE:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_MOVE - %d ms\n",
+		(unsigned int)GetTickCount ());
+#endif
+      if (g_fNoConfigureWindow) break;
+#if 0
+      /* Bail if Windows window is not actually moving */
+      if (pRLWinPriv->dwX == (short) LOWORD(lParam)
+	  && pRLWinPriv->dwY == (short) HIWORD(lParam))
+	break;
+
+      /* Also bail if we're maximizing, we'll do the whole thing in WM_SIZE */
+      {
+	WINDOWPLACEMENT windPlace;
+	windPlace.length = sizeof (WINDOWPLACEMENT);
+
+	/* Get current window placement */
+	GetWindowPlacement (hwnd, &windPlace);
+
+	/* Bail if maximizing */
+	if (windPlace.showCmd == SW_MAXIMIZE
+	    || windPlace.showCmd == SW_SHOWMAXIMIZED)
+	  break;
+      }
+#endif
+
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("\t(%d, %d)\n", (short) LOWORD(lParam), (short) HIWORD(lParam));
+#endif
+      if (!pRLWinPriv->fMovingOrSizing)
+	{
+	  if (winIsInternalWMRunning(pScreenInfo))
+	    winAdjustXWindow (pWin, hwnd);
+
+	  winMWExtWMMoveXWindow (pWin,
+				 (LOWORD(lParam) - wBorderWidth (pWin)
+				  - GetSystemMetrics (SM_XVIRTUALSCREEN)),
+				 (HIWORD(lParam) - wBorderWidth (pWin)
+				  - GetSystemMetrics (SM_YVIRTUALSCREEN)));
+	}
+      return 0;
+
+    case WM_SHOWWINDOW:
+#if CYGMULTIWINDOW_DEBUG || TRUE
+      winDebug ("winMWExtWMWindowProc - WM_SHOWWINDOW - %d ms\n",
+		(unsigned int)GetTickCount ());
+#endif
+      /* Bail out if the window is being hidden */
+      if (!wParam)
+	return 0;
+
+      if (!pScreenInfo->fInternalWM)//XXXX
+	return 0;
+
+      winMWExtWMUpdateWindowDecoration (pRLWinPriv, pScreenInfo);
+
+      if (winIsInternalWMRunning(pScreenInfo))
+	{
+#if CYGMULTIWINDOW_DEBUG || TRUE
+	  winDebug ("\tMapWindow\n");
+#endif
+	  /* Tell X to map the window */
+	   MapWindow (pWin, wClient(pWin));
+
+	  if (!pRLWinPriv->pFrame->win->overrideRedirect)
+	    /* Bring the Windows window to the foreground */
+	    SetForegroundWindow (hwnd);
+
+	  /* Setup the Window Manager message */
+	  wmMsg.msg = WM_WM_MAP;
+	  wmMsg.iWidth = pRLWinPriv->pFrame->width;
+	  wmMsg.iHeight = pRLWinPriv->pFrame->height;
+
+	  /* Tell our Window Manager thread to map the window */
+	  if (fWMMsgInitialized)
+	    winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
+	}
+      break;
+
+    case WM_SIZING:
+      /* Need to legalize the size according to WM_NORMAL_HINTS */
+      /* for applications like xterm */
+      return ValidateSizing (hwnd, pWin, wParam, lParam);
+
+    case WM_WINDOWPOSCHANGED:
+      {
+	pWinPos = (LPWINDOWPOS) lParam;
+#if CYGMULTIWINDOW_DEBUG
+        winDebug("winMWExtWMWindowProc - WM_WINDOWPOSCHANGED\n");
+	winDebug("\tflags: %s%s%s%s%s%s%s%s%s%s%s%s\n",
+	(pWinPos->flags & SWP_DRAWFRAME)?"SWP_DRAWFRAME ":"",
+	(pWinPos->flags & SWP_FRAMECHANGED)?"SWP_FRAMECHANGED ":"",
+	(pWinPos->flags & SWP_HIDEWINDOW)?"SWP_HIDEWINDOW ":"",
+	(pWinPos->flags & SWP_NOACTIVATE)?"SWP_NOACTIVATE ":"",
+	(pWinPos->flags & SWP_NOCOPYBITS)?"SWP_NOCOPYBITS ":"",
+	(pWinPos->flags & SWP_NOMOVE)?"SWP_NOMOVE ":"",
+	(pWinPos->flags & SWP_NOOWNERZORDER)?"SWP_NOOWNERZORDER ":"",
+	(pWinPos->flags & SWP_NOSIZE)?"SWP_NOSIZE ":"",
+	(pWinPos->flags & SWP_NOREDRAW)?"SWP_NOREDRAW ":"",
+	(pWinPos->flags & SWP_NOSENDCHANGING)?"SWP_NOSENDCHANGING ":"",
+	(pWinPos->flags & SWP_NOZORDER)?"SWP_NOZORDER ":"",
+	(pWinPos->flags & SWP_SHOWWINDOW)?"SWP_SHOWWINDOW ":"");
+	winDebug("\tno_configure: %s\n", (g_fNoConfigureWindow?"Yes":"No"));
+	winDebug("\textend: (%d, %d, %d, %d)\n",
+            pWinPos->x, pWinPos->y, pWinPos->cx, pWinPos->cy);
+
+#endif
+	if (pWinPos->flags & SWP_HIDEWINDOW) break;
+
+	/* Reorder if window z order was changed */
+	if ((pScreenPriv != NULL)
+	    && !(pWinPos->flags & SWP_NOZORDER)
+	    && !(pWinPos->flags & SWP_SHOWWINDOW)
+	    && winIsInternalWMRunning(pScreenInfo))
+	  {
+#if CYGMULTIWINDOW_DEBUG
+	    winDebug ("\twindow z order was changed\n");
+#endif
+	    if (pWinPos->hwndInsertAfter == HWND_TOP
+		||pWinPos->hwndInsertAfter == HWND_TOPMOST
+		||pWinPos->hwndInsertAfter == HWND_NOTOPMOST)
+	      {
+#if CYGMULTIWINDOW_DEBUG
+		winDebug ("\traise to top\n");
+#endif
+		/* Raise the window to the top in Z order */
+		wmMsg.msg = WM_WM_RAISE;
+		if (fWMMsgInitialized)
+		  winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
+	      }
+#if 1
+	    else if (pWinPos->hwndInsertAfter == HWND_BOTTOM)
+	      {
+	      }
+	    else
+	      {
+		/* Check if this window is top of X windows. */
+		HWND hWndAbove = NULL;
+		DWORD dwCurrentProcessID = GetCurrentProcessId ();
+		DWORD dwWindowProcessID = 0;
+
+		for (hWndAbove = pWinPos->hwndInsertAfter;
+		     hWndAbove != NULL;
+		     hWndAbove = GetNextWindow (hWndAbove, GW_HWNDPREV))
+		  {
+		    /* Ignore other XWin process's window */
+		    GetWindowThreadProcessId (hWndAbove, &dwWindowProcessID);
+
+		    if ((dwWindowProcessID == dwCurrentProcessID)
+			&& GetProp (hWndAbove, WIN_WINDOW_PROP)
+			&& !IsWindowVisible (hWndAbove)
+			&& !IsIconic (hWndAbove) ) /* ignore minimized windows */
+		      break;
+		  }
+		/* If this is top of X windows in Windows stack,
+		   raise it in X stack. */
+		if (hWndAbove == NULL)
+		  {
+#if CYGMULTIWINDOW_DEBUG
+		    winDebug ("\traise to top\n");
+#endif
+		    /* Raise the window to the top in Z order */
+		    wmMsg.msg = WM_WM_RAISE;
+		    if (fWMMsgInitialized)
+		      winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
+		  }
+	      }
+#endif
+	  }
+
+	if (!(pWinPos->flags & SWP_NOSIZE)) {
+	  if (IsIconic(hwnd)){
+#if CYGMULTIWINDOW_DEBUG
+	    winDebug ("\tIconic -> MINIMIZED\n");
+#endif
+	    if (winIsInternalWMRunning(pScreenInfo))
+	      {
+	      /* Raise the window to the top in Z order */
+		wmMsg.msg = WM_WM_LOWER;
+		if (fWMMsgInitialized)
+		  winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
+	      }
+	    winWindowsWMSendEvent(WindowsWMControllerNotify,
+				  WindowsWMControllerNotifyMask,
+				  1,
+				  WindowsWMMinimizeWindow,
+				  pWin->drawable.id,
+				  0, 0, 0, 0);
+	  } else if (IsZoomed(hwnd)){
+#if CYGMULTIWINDOW_DEBUG
+	    winDebug ("\tZoomed -> MAXIMIZED\n");
+#endif
+	    winWindowsWMSendEvent(WindowsWMControllerNotify,
+				  WindowsWMControllerNotifyMask,
+				  1,
+				  WindowsWMMaximizeWindow,
+				  pWin->drawable.id,
+				  0, 0, 0, 0);
+	  } else {
+#if CYGMULTIWINDOW_DEBUG
+	    winDebug ("\tnone -> RESTORED\n");
+#endif
+	    winWindowsWMSendEvent(WindowsWMControllerNotify,
+				  WindowsWMControllerNotifyMask,
+				  1,
+				  WindowsWMRestoreWindow,
+				  pWin->drawable.id,
+				  0, 0, 0, 0);
+	  }
+	}
+	if (!g_fNoConfigureWindow ) {
+
+	  if (!pRLWinPriv->fMovingOrSizing
+	      /*&& (pWinPos->flags & SWP_SHOWWINDOW)*/) {
+	    GetClientRect (hwnd, &rcClient);
+	    MapWindowPoints (hwnd, HWND_DESKTOP, (LPPOINT)&rcClient, 2);
+
+	    if (!(pWinPos->flags & SWP_NOMOVE)
+		&&!(pWinPos->flags & SWP_NOSIZE)) {
+#if CYGMULTIWINDOW_DEBUG
+	      winDebug ("\tmove & resize\n");
+#endif
+	      if (winIsInternalWMRunning(pScreenInfo))
+                winAdjustXWindow (pWin, hwnd);
+
+	      winMWExtWMMoveResizeXWindow (pWin,
+					   rcClient.left - wBorderWidth (pWin)
+					   - GetSystemMetrics (SM_XVIRTUALSCREEN),
+					   rcClient.top - wBorderWidth (pWin)
+					   - GetSystemMetrics (SM_YVIRTUALSCREEN),
+					   rcClient.right - rcClient.left
+					   - wBorderWidth (pWin)*2,
+					   rcClient.bottom - rcClient.top
+					   - wBorderWidth (pWin)*2);
+	    } else if (!(pWinPos->flags & SWP_NOMOVE)) {
+#if CYGMULTIWINDOW_DEBUG
+	      winDebug ("\tmove\n");
+#endif
+	      if (winIsInternalWMRunning(pScreenInfo))
+                winAdjustXWindow (pWin, hwnd);
+
+	      winMWExtWMMoveResizeXWindow (pWin,
+					   rcClient.left - wBorderWidth (pWin)
+					   - GetSystemMetrics (SM_XVIRTUALSCREEN),
+					   rcClient.top - wBorderWidth (pWin)
+					   - GetSystemMetrics (SM_YVIRTUALSCREEN),
+					   rcClient.right - rcClient.left
+					   - wBorderWidth (pWin)*2,
+					   rcClient.bottom - rcClient.top
+					   - wBorderWidth (pWin)*2);
+	    } else if (!(pWinPos->flags & SWP_NOMOVE)) {
+#if CYGMULTIWINDOW_DEBUG
+	      winDebug ("\tmove\n");
+#endif
+	      if (winIsInternalWMRunning(pScreenInfo))
+                winAdjustXWindow (pWin, hwnd); 
+
+	      winMWExtWMMoveXWindow (pWin,
+				     rcClient.left - wBorderWidth (pWin)
+				     - GetSystemMetrics (SM_XVIRTUALSCREEN),
+				     rcClient.top - wBorderWidth (pWin)
+				     - GetSystemMetrics (SM_YVIRTUALSCREEN));
+	    } else if (!(pWinPos->flags & SWP_NOSIZE)) {
+#if CYGMULTIWINDOW_DEBUG
+	      winDebug ("\tresize\n");
+#endif
+	      if (winIsInternalWMRunning(pScreenInfo))
+                winAdjustXWindow (pWin, hwnd); 
+
+	      winMWExtWMResizeXWindow (pWin,
+				       rcClient.right - rcClient.left
+				       - wBorderWidth (pWin)*2,
+				       rcClient.bottom - rcClient.top
+				       - wBorderWidth (pWin)*2);
+	    }
+	  }
+	}
+      }
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_WINDOWPOSCHANGED - done.\n");
+#endif
+      return 0;
+
+    case WM_SIZE:
+      /* see dix/window.c */
+      /* FIXME: Maximize/Restore? */
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_SIZE - %d ms\n",
+		(unsigned int)GetTickCount ());
+#endif
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("\t(%d, %d) %d\n", (short) LOWORD(lParam), (short) HIWORD(lParam), g_fNoConfigureWindow);
+#endif
+      if (g_fNoConfigureWindow) break;
+
+      /* Branch on type of resizing occurring */
+      switch (wParam)
+	{
+	case SIZE_MINIMIZED:
+#if CYGMULTIWINDOW_DEBUG
+	  winDebug ("\tSIZE_MINIMIZED\n");
+#endif
+	  if (winIsInternalWMRunning(pScreenInfo))
+	    {
+	      /* Raise the window to the top in Z order */
+	      wmMsg.msg = WM_WM_LOWER;
+	      if (fWMMsgInitialized)
+		winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
+	    }
+	  winWindowsWMSendEvent(WindowsWMControllerNotify,
+				WindowsWMControllerNotifyMask,
+				1,
+				WindowsWMMinimizeWindow,
+				pWin->drawable.id,
+				0, 0,
+				LOWORD(lParam), HIWORD(lParam));
+	  break;
+
+	case SIZE_RESTORED:
+#if CYGMULTIWINDOW_DEBUG
+	  winDebug ("\tSIZE_RESTORED\n");
+#endif
+	  winWindowsWMSendEvent(WindowsWMControllerNotify,
+				WindowsWMControllerNotifyMask,
+				1,
+				WindowsWMRestoreWindow,
+				pWin->drawable.id,
+				0, 0,
+				LOWORD(lParam), HIWORD(lParam));
+	  break;
+
+	case SIZE_MAXIMIZED:
+#if CYGMULTIWINDOW_DEBUG
+	  winDebug ("\tSIZE_MAXIMIZED\n");
+#endif
+	  winWindowsWMSendEvent(WindowsWMControllerNotify,
+				WindowsWMControllerNotifyMask,
+				1,
+				WindowsWMMaximizeWindow,
+				pWin->drawable.id,
+				0, 0,
+				LOWORD(lParam), HIWORD(lParam));
+	  break;
+	}
+
+      /* Perform the resize and notify the X client */
+      if (!pRLWinPriv->fMovingOrSizing)
+	{
+	  if (winIsInternalWMRunning(pScreenInfo))
+            winAdjustXWindow (pWin, hwnd);
+
+	  winMWExtWMResizeXWindow (pWin,
+				   (short) LOWORD(lParam)
+				   - wBorderWidth (pWin)*2,
+				   (short) HIWORD(lParam)
+				   - wBorderWidth (pWin)*2);
+	}
+      break;
+
+    case WM_ACTIVATEAPP:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_ACTIVATEAPP - %d ms\n",
+		(unsigned int)GetTickCount ());
+#endif
+      if (wParam)
+	{
+	  if (winIsInternalWMRunning(pScreenInfo))
+	    {
+	    }
+	  else
+	    {
+	    }
+	  winWindowsWMSendEvent(WindowsWMActivationNotify,
+				WindowsWMActivationNotifyMask,
+				1,
+				WindowsWMIsActive,
+				pWin->drawable.id,
+				0, 0,
+				0, 0);
+	}
+      else
+	{
+	  winWindowsWMSendEvent(WindowsWMActivationNotify,
+				WindowsWMActivationNotifyMask,
+				1,
+				WindowsWMIsInactive,
+				pWin->drawable.id,
+				0, 0,
+				0, 0);
+	}
+      break;
+
+    case WM_SETCURSOR:
+      if (LOWORD(lParam) == HTCLIENT)
+	{
+	  if (!g_fSoftwareCursor) SetCursor (pScreenPriv->cursor.handle);
+	  return TRUE;
+	}
+      break;
+
+    case WM_ENTERSIZEMOVE:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_ENTERSIZEMOVE - %d ms\n",
+		(unsigned int)GetTickCount ());
+#endif
+      pRLWinPriv->fMovingOrSizing = TRUE;
+      break;
+
+    case WM_EXITSIZEMOVE:
+#if CYGMULTIWINDOW_DEBUG
+      winDebug ("winMWExtWMWindowProc - WM_EXITSIZEMOVE - %d ms\n",
+		(unsigned int)GetTickCount ());
+#endif
+      pRLWinPriv->fMovingOrSizing = FALSE;
+
+      GetClientRect (hwnd, &rcClient);
+
+      MapWindowPoints (hwnd, HWND_DESKTOP, (LPPOINT)&rcClient, 2);
+
+      if (winIsInternalWMRunning(pScreenInfo))
+        winAdjustXWindow (pWin, hwnd); 
+
+      winMWExtWMMoveResizeXWindow (pWin,
+				   rcClient.left - wBorderWidth (pWin)
+				   - GetSystemMetrics (SM_XVIRTUALSCREEN),
+				   rcClient.top - wBorderWidth (pWin)
+				   - GetSystemMetrics (SM_YVIRTUALSCREEN),
+				   rcClient.right - rcClient.left
+				   - wBorderWidth (pWin)*2,
+				   rcClient.bottom - rcClient.top
+				   - wBorderWidth (pWin)*2);
+      break;
+
+    case WM_MANAGE:
+      ErrorF ("winMWExtWMWindowProc - WM_MANAGE\n");
+      break;
+
+    case WM_UNMANAGE:
+      ErrorF ("winMWExtWMWindowProc - WM_UNMANAGE\n");
+      break;
+
+    default:
+      break;
+    }
+
+  return DefWindowProc (hwnd, message, wParam, lParam);
+}
diff --git a/hw/xwin/winwindow.c b/hw/xwin/winwindow.c
new file mode 100644
index 0000000..1600996
--- /dev/null
+++ b/hw/xwin/winwindow.c
@@ -0,0 +1,649 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Harold L Hunt II
+ *		Kensuke Matsuzaki
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+
+/*
+ * Prototypes for local functions
+ */
+
+static int
+winAddRgn (WindowPtr pWindow, pointer data);
+
+static
+void
+winUpdateRgnRootless (WindowPtr pWindow);
+
+#ifdef SHAPE
+static
+void
+winReshapeRootless (WindowPtr pWin);
+#endif
+
+
+#ifdef XWIN_NATIVEGDI
+/* See Porting Layer Definition - p. 37 */
+/* See mfb/mfbwindow.c - mfbCreateWindow() */
+
+Bool
+winCreateWindowNativeGDI (WindowPtr pWin)
+{
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winTrace ("winCreateWindowNativeGDI (%p)\n", pWin);
+#endif
+
+  WIN_UNWRAP(CreateWindow);
+  fResult = (*pScreen->CreateWindow) (pWin);
+  WIN_WRAP(CreateWindow, winCreateWindowNativeGDI);
+
+  return fResult;
+}
+
+
+/* See Porting Layer Definition - p. 37 */
+/* See mfb/mfbwindow.c - mfbDestroyWindow() */
+
+Bool
+winDestroyWindowNativeGDI (WindowPtr pWin)
+{
+  Bool			fResult = TRUE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winTrace ("winDestroyWindowNativeGDI (%p)\n", pWin);
+#endif
+
+  WIN_UNWRAP(DestroyWindow); 
+  fResult = (*pScreen->DestroyWindow)(pWin);
+  WIN_WRAP(DestroyWindow, winDestroyWindowNativeGDI);
+
+  return fResult;
+}
+
+
+/* See Porting Layer Definition - p. 37 */
+/* See mfb/mfbwindow.c - mfbPositionWindow() */
+
+Bool
+winPositionWindowNativeGDI (WindowPtr pWin, int x, int y)
+{
+  Bool			fResult = TRUE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winTrace ("winPositionWindowNativeGDI (%p)\n", pWin);
+#endif
+
+  WIN_UNWRAP(PositionWindow);
+  fResult = (*pScreen->PositionWindow)(pWin, x, y);
+  WIN_WRAP(PositionWindow, winPositionWindowNativeGDI);
+
+  return fResult;
+}
+
+
+/* See Porting Layer Definition - p. 39 */
+/* See mfb/mfbwindow.c - mfbCopyWindow() */
+
+void 
+winCopyWindowNativeGDI (WindowPtr pWin,
+			DDXPointRec ptOldOrg,
+			RegionPtr prgnSrc)
+{
+  DDXPointPtr		pptSrc;
+  DDXPointPtr		ppt;
+  RegionPtr		prgnDst;
+  BoxPtr		pBox;
+  int			dx, dy;
+  int			i, nbox;
+  WindowPtr		pwinRoot;
+  BoxPtr		pBoxDst;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winScreenPriv(pScreen);
+
+#if 0
+  ErrorF ("winCopyWindow\n");
+#endif
+
+  /* Get a pointer to the root window */
+  pwinRoot = WindowTable[pWin->drawable.pScreen->myNum];
+
+  /* Create a region for the destination */
+  prgnDst = REGION_CREATE(pWin->drawable.pScreen, NULL, 1);
+
+  /* Calculate the shift from the source to the destination */
+  dx = ptOldOrg.x - pWin->drawable.x;
+  dy = ptOldOrg.y - pWin->drawable.y;
+
+  /* Translate the region from the destination to the source? */
+  REGION_TRANSLATE(pWin->drawable.pScreen, prgnSrc, -dx, -dy);
+  REGION_INTERSECT(pWin->drawable.pScreen, prgnDst, &pWin->borderClip,
+		   prgnSrc);
+
+  /* Get a pointer to the first box in the region to be copied */
+  pBox = REGION_RECTS(prgnDst);
+  
+  /* Get the number of boxes in the region */
+  nbox = REGION_NUM_RECTS(prgnDst);
+
+  /* Allocate source points for each box */
+  if(!(pptSrc = (DDXPointPtr )xalloc(nbox * sizeof(DDXPointRec))))
+    return;
+
+  /* Set an iterator pointer */
+  ppt = pptSrc;
+
+  /* Calculate the source point of each box? */
+  for (i = nbox; --i >= 0; ppt++, pBox++)
+    {
+      ppt->x = pBox->x1 + dx;
+      ppt->y = pBox->y1 + dy;
+    }
+
+  /* Setup loop pointers again */
+  pBoxDst = REGION_RECTS(prgnDst);
+  ppt = pptSrc;
+
+#if 0
+  ErrorF ("winCopyWindow - x1\tx2\ty1\ty2\tx\ty\n");
+#endif
+
+  /* BitBlt each source to the destination point */
+  for (i = nbox; --i >= 0; pBoxDst++, ppt++)
+    {
+#if 0
+      ErrorF ("winCopyWindow - %d\t%d\t%d\t%d\t%d\t%d\n",
+	      pBoxDst->x1, pBoxDst->x2, pBoxDst->y1, pBoxDst->y2,
+	      ppt->x, ppt->y);
+#endif
+
+      BitBlt (pScreenPriv->hdcScreen,
+	      pBoxDst->x1, pBoxDst->y1,
+	      pBoxDst->x2 - pBoxDst->x1, pBoxDst->y2 - pBoxDst->y1,
+	      pScreenPriv->hdcScreen,
+	      ppt->x, ppt->y,
+	      SRCCOPY);
+    }
+
+  /* Cleanup the regions, etc. */
+  xfree(pptSrc);
+  REGION_DESTROY(pWin->drawable.pScreen, prgnDst);
+}
+
+
+/* See Porting Layer Definition - p. 37 */
+/* See mfb/mfbwindow.c - mfbChangeWindowAttributes() */
+
+Bool
+winChangeWindowAttributesNativeGDI (WindowPtr pWin, unsigned long mask)
+{
+  Bool			fResult = TRUE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winTrace ("winChangeWindowAttributesNativeGDI (%p)\n", pWin);
+#endif
+  
+  WIN_UNWRAP(ChangeWindowAttributes); 
+  fResult = (*pScreen->ChangeWindowAttributes)(pWin, mask);
+  WIN_WRAP(ChangeWindowAttributes, winChangeWindowAttributesNativeGDI);
+  
+  /*
+   * NOTE: We do not currently need to do anything here.
+   */
+
+  return fResult;
+}
+
+
+/* See Porting Layer Definition - p. 37
+ * Also referred to as UnrealizeWindow
+ */
+
+Bool
+winUnmapWindowNativeGDI (WindowPtr pWin)
+{
+  Bool			fResult = TRUE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winTrace ("winUnmapWindowNativeGDI (%p)\n", pWin);
+#endif
+
+  WIN_UNWRAP(UnrealizeWindow); 
+  fResult = (*pScreen->UnrealizeWindow)(pWin);
+  WIN_WRAP(UnrealizeWindow, winUnmapWindowNativeGDI);
+  
+  return fResult;
+}
+
+
+/* See Porting Layer Definition - p. 37
+ * Also referred to as RealizeWindow
+ */
+
+Bool
+winMapWindowNativeGDI (WindowPtr pWin)
+{
+  Bool			fResult = TRUE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winTrace ("winMapWindowNativeGDI (%p)\n", pWin);
+#endif
+
+  WIN_UNWRAP(RealizeWindow); 
+  fResult = (*pScreen->RealizeWindow)(pWin);
+  WIN_WRAP(RealizeWindow, winMapWindowMultiWindow);
+  
+  return fResult;
+
+}
+#endif
+
+
+/* See Porting Layer Definition - p. 37 */
+/* See mfb/mfbwindow.c - mfbCreateWindow() */
+
+Bool
+winCreateWindowRootless (WindowPtr pWin)
+{
+  Bool			fResult = FALSE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winTrace ("winCreateWindowRootless (%p)\n", pWin);
+#endif
+
+  WIN_UNWRAP(CreateWindow);
+  fResult = (*pScreen->CreateWindow) (pWin);
+  WIN_WRAP(CreateWindow, winCreateWindowRootless);
+  
+  pWinPriv->hRgn = NULL;
+  
+  return fResult;
+}
+
+
+/* See Porting Layer Definition - p. 37 */
+/* See mfb/mfbwindow.c - mfbDestroyWindow() */
+
+Bool
+winDestroyWindowRootless (WindowPtr pWin)
+{
+  Bool			fResult = FALSE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winTrace ("winDestroyWindowRootless (%p)\n", pWin);
+#endif
+
+  WIN_UNWRAP(DestroyWindow); 
+  fResult = (*pScreen->DestroyWindow)(pWin);
+  WIN_WRAP(DestroyWindow, winDestroyWindowRootless);
+  
+  if (pWinPriv->hRgn != NULL)
+    {
+      DeleteObject(pWinPriv->hRgn);
+      pWinPriv->hRgn = NULL;
+    }
+  
+  winUpdateRgnRootless (pWin);
+  
+  return fResult;
+}
+
+
+/* See Porting Layer Definition - p. 37 */
+/* See mfb/mfbwindow.c - mfbPositionWindow() */
+
+Bool
+winPositionWindowRootless (WindowPtr pWin, int x, int y)
+{
+  Bool			fResult = FALSE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+
+#if CYGDEBUG
+  winTrace ("winPositionWindowRootless (%p)\n", pWin);
+#endif
+
+  WIN_UNWRAP(PositionWindow);
+  fResult = (*pScreen->PositionWindow)(pWin, x, y);
+  WIN_WRAP(PositionWindow, winPositionWindowRootless);
+  
+  winUpdateRgnRootless (pWin);
+  
+  return fResult;
+}
+
+
+/* See Porting Layer Definition - p. 37 */
+/* See mfb/mfbwindow.c - mfbChangeWindowAttributes() */
+
+Bool
+winChangeWindowAttributesRootless (WindowPtr pWin, unsigned long mask)
+{
+  Bool			fResult = FALSE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winTrace ("winChangeWindowAttributesRootless (%p)\n", pWin);
+#endif
+
+  WIN_UNWRAP(ChangeWindowAttributes); 
+  fResult = (*pScreen->ChangeWindowAttributes)(pWin, mask);
+  WIN_WRAP(ChangeWindowAttributes, winChangeWindowAttributesRootless);
+
+  winUpdateRgnRootless (pWin);
+  
+  return fResult;
+}
+
+
+/* See Porting Layer Definition - p. 37
+ * Also referred to as UnrealizeWindow
+ */
+
+Bool
+winUnmapWindowRootless (WindowPtr pWin)
+{
+  Bool			fResult = FALSE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winTrace ("winUnmapWindowRootless (%p)\n", pWin);
+#endif
+
+  WIN_UNWRAP(UnrealizeWindow); 
+  fResult = (*pScreen->UnrealizeWindow)(pWin);
+  WIN_WRAP(UnrealizeWindow, winUnmapWindowRootless);
+  
+  if (pWinPriv->hRgn != NULL)
+    {
+      DeleteObject(pWinPriv->hRgn);
+      pWinPriv->hRgn = NULL;
+    }
+  
+  winUpdateRgnRootless (pWin);
+  
+  return fResult;
+}
+
+
+/* See Porting Layer Definition - p. 37
+ * Also referred to as RealizeWindow
+ */
+
+Bool
+winMapWindowRootless (WindowPtr pWin)
+{
+  Bool			fResult = FALSE;
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winTrace ("winMapWindowRootless (%p)\n", pWin);
+#endif
+
+  WIN_UNWRAP(RealizeWindow); 
+  fResult = (*pScreen->RealizeWindow)(pWin);
+  WIN_WRAP(RealizeWindow, winMapWindowRootless);
+
+#ifdef SHAPE
+  winReshapeRootless (pWin);
+#endif
+  
+  winUpdateRgnRootless (pWin);
+  
+  return fResult;
+}
+
+
+#ifdef SHAPE
+void
+winSetShapeRootless (WindowPtr pWin)
+{
+  ScreenPtr		pScreen = pWin->drawable.pScreen;
+  winWindowPriv(pWin);
+  winScreenPriv(pScreen);
+
+#if CYGDEBUG
+  winTrace ("winSetShapeRootless (%p)\n", pWin);
+#endif
+
+  WIN_UNWRAP(SetShape); 
+  (*pScreen->SetShape)(pWin);
+  WIN_WRAP(SetShape, winSetShapeRootless);
+  
+  winReshapeRootless (pWin);
+  winUpdateRgnRootless (pWin);
+  
+  return;
+}
+#endif
+
+
+/*
+ * Local function for adding a region to the Windows window region
+ */
+
+static
+int
+winAddRgn (WindowPtr pWin, pointer data)
+{
+  int		iX, iY, iWidth, iHeight, iBorder;
+  HRGN		hRgn = *(HRGN*)data;
+  HRGN		hRgnWin;
+  winWindowPriv(pWin);
+  
+  /* If pWin is not Root */
+  if (pWin->parent != NULL) 
+    {
+#if CYGDEBUG
+      winDebug ("winAddRgn ()\n");
+#endif
+      if (pWin->mapped)
+	{
+	  iBorder = wBorderWidth (pWin);
+	  
+	  iX = pWin->drawable.x - iBorder;
+	  iY = pWin->drawable.y - iBorder;
+	  
+	  iWidth = pWin->drawable.width + iBorder * 2;
+	  iHeight = pWin->drawable.height + iBorder * 2;
+	  
+	  hRgnWin = CreateRectRgn (0, 0, iWidth, iHeight);
+	  
+	  if (hRgnWin == NULL)
+	    {
+	      ErrorF ("winAddRgn - CreateRectRgn () failed\n");
+	      ErrorF ("  Rect %d %d %d %d\n",
+		      iX, iY, iX + iWidth, iY + iHeight);
+	    }
+	  
+	  if (pWinPriv->hRgn)
+	    {
+	      if (CombineRgn (hRgnWin, hRgnWin, pWinPriv->hRgn, RGN_AND)
+		  == ERROR)
+		{
+		  ErrorF ("winAddRgn - CombineRgn () failed\n");
+		}
+	    }
+	  
+	  OffsetRgn (hRgnWin, iX, iY);
+
+	  if (CombineRgn (hRgn, hRgn, hRgnWin, RGN_OR) == ERROR)
+	    {
+	      ErrorF ("winAddRgn - CombineRgn () failed\n");
+	    }
+	  
+	  DeleteObject (hRgnWin);
+	}
+      return WT_DONTWALKCHILDREN;
+    }
+  else
+    {
+      return WT_WALKCHILDREN;
+    }
+}
+
+
+/*
+ * Local function to update the Windows window's region
+ */
+
+static
+void
+winUpdateRgnRootless (WindowPtr pWin)
+{
+  HRGN		hRgn = CreateRectRgn (0, 0, 0, 0);
+  
+  if (hRgn != NULL)
+    {
+      WalkTree (pWin->drawable.pScreen, winAddRgn, &hRgn);
+      SetWindowRgn (winGetScreenPriv(pWin->drawable.pScreen)->hwndScreen,
+		    hRgn, TRUE);
+    }
+  else
+    {
+      ErrorF ("winUpdateRgnRootless - CreateRectRgn failed.\n");
+    }
+}
+
+
+#ifdef SHAPE
+static
+void
+winReshapeRootless (WindowPtr pWin)
+{
+  int		nRects;
+  /* ScreenPtr	pScreen = pWin->drawable.pScreen;*/
+  RegionRec	rrNewShape;
+  BoxPtr	pShape, pRects, pEnd;
+  HRGN		hRgn, hRgnRect;
+  winWindowPriv(pWin);
+
+#if CYGDEBUG
+  winDebug ("winReshapeRootless ()\n");
+#endif
+
+  /* Bail if the window is the root window */
+  if (pWin->parent == NULL)
+    return;
+
+  /* Bail if the window is not top level */
+  if (pWin->parent->parent != NULL)
+    return;
+
+  /* Free any existing window region stored in the window privates */
+  if (pWinPriv->hRgn != NULL)
+    {
+      DeleteObject (pWinPriv->hRgn);
+      pWinPriv->hRgn = NULL;
+    }
+  
+  /* Bail if the window has no bounding region defined */
+  if (!wBoundingShape (pWin))
+    return;
+
+  REGION_NULL(pScreen, &rrNewShape);
+  REGION_COPY(pScreen, &rrNewShape, wBoundingShape(pWin));
+  REGION_TRANSLATE(pScreen, &rrNewShape, pWin->borderWidth,
+                   pWin->borderWidth);
+  
+  nRects = REGION_NUM_RECTS(&rrNewShape);
+  pShape = REGION_RECTS(&rrNewShape);
+  
+  if (nRects > 0)
+    {
+      /* Create initial empty Windows region */
+      hRgn = CreateRectRgn (0, 0, 0, 0);
+
+      /* Loop through all rectangles in the X region */
+      for (pRects = pShape, pEnd = pShape + nRects; pRects < pEnd; pRects++)
+        {
+	  /* Create a Windows region for the X rectangle */
+	  hRgnRect = CreateRectRgn (pRects->x1, pRects->y1,
+				    pRects->x2, pRects->y2);
+	  if (hRgnRect == NULL)
+	    {
+	      ErrorF("winReshapeRootless - CreateRectRgn() failed\n");
+	    }
+
+	  /* Merge the Windows region with the accumulated region */
+	  if (CombineRgn (hRgn, hRgn, hRgnRect, RGN_OR) == ERROR)
+	    {
+	      ErrorF("winReshapeRootless - CombineRgn() failed\n");
+	    }
+
+	  /* Delete the temporary Windows region */
+	  DeleteObject (hRgnRect);
+        }
+      
+      /* Save a handle to the composite region in the window privates */
+      pWinPriv->hRgn = hRgn;
+    }
+
+  REGION_UNINIT(pScreen, &rrNewShape);
+  
+  return;
+}
+#endif
diff --git a/hw/xwin/winwindow.h b/hw/xwin/winwindow.h
new file mode 100644
index 0000000..9c49d64
--- /dev/null
+++ b/hw/xwin/winwindow.h
@@ -0,0 +1,150 @@
+#if !defined(_WINWINDOW_H_)
+#define _WINWINDOW_H_
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Kensuke Matsuzaki
+ */
+
+#ifndef NO
+#define NO			0
+#endif
+#ifndef YES
+#define YES			1
+#endif
+
+/* Constant strings */
+#ifndef PROJECT_NAME
+#  define PROJECT_NAME		"Cygwin/X"
+#endif
+#define WINDOW_CLASS		"cygwin/x"
+#define WINDOW_TITLE		PROJECT_NAME " - %s:%d"
+#define WINDOW_TITLE_XDMCP	PROJECT_NAME " - %s"
+#define WIN_SCR_PROP		"cyg_screen_prop rl"
+#define WINDOW_CLASS_X		"cygwin/x X rl"
+#define WINDOW_TITLE_X		PROJECT_NAME " X"
+#define WIN_WINDOW_PROP		"cyg_window_prop_rl"
+#ifdef HAS_DEVWINDOWS
+# define WIN_MSG_QUEUE_FNAME	"/dev/windows"
+#endif
+#define WIN_WID_PROP		"cyg_wid_prop_rl"
+#define WIN_NEEDMANAGE_PROP	"cyg_override_redirect_prop_rl"
+#ifndef CYGMULTIWINDOW_DEBUG
+#define CYGMULTIWINDOW_DEBUG    NO
+#endif
+#ifndef CYGWINDOWING_DEBUG
+#define CYGWINDOWING_DEBUG	NO
+#endif
+
+typedef struct _winPrivScreenRec *winPrivScreenPtr;
+
+
+/*
+ * Window privates
+ */
+
+typedef struct
+{
+  DWORD			dwDummy;
+  HRGN			hRgn;
+  HWND			hWnd;
+  winPrivScreenPtr	pScreenPriv;
+  Bool			fXKilled;
+
+  /* Privates used by primary fb DirectDraw server */
+  LPDDSURFACEDESC	pddsdPrimary;
+
+  /* Privates used by shadow fb DirectDraw Nonlocking server */
+  LPDIRECTDRAWSURFACE4	pddsPrimary4;
+
+  /* Privates used by both shadow fb DirectDraw servers */
+  LPDIRECTDRAWCLIPPER	pddcPrimary;
+} winPrivWinRec, *winPrivWinPtr;
+
+#ifdef XWIN_MULTIWINDOW
+typedef struct _winWMMessageRec{
+  DWORD			dwID;
+  DWORD			msg;
+  int			iWindow;
+  HWND			hwndWindow;
+  int			iX, iY;
+  int			iWidth, iHeight;
+} winWMMessageRec, *winWMMessagePtr;
+
+
+/*
+ * winmultiwindowwm.c
+ */
+
+#define		WM_WM_MOVE		(WM_USER + 1)
+#define		WM_WM_SIZE		(WM_USER + 2)
+#define		WM_WM_RAISE		(WM_USER + 3)
+#define		WM_WM_LOWER		(WM_USER + 4)
+#define		WM_WM_MAP		(WM_USER + 5)
+#define		WM_WM_UNMAP		(WM_USER + 6)
+#define		WM_WM_KILL		(WM_USER + 7)
+#define		WM_WM_ACTIVATE		(WM_USER + 8)
+#define		WM_WM_NAME_EVENT	(WM_USER + 9)
+#define		WM_WM_HINTS_EVENT	(WM_USER + 10)
+#define		WM_WM_CHANGE_STATE	(WM_USER + 11)
+#define		WM_MANAGE		(WM_USER + 100)
+#define		WM_UNMANAGE		(WM_USER + 102)
+
+void
+winSendMessageToWM (void *pWMInfo, winWMMessagePtr msg);
+
+Bool
+winInitWM (void **ppWMInfo,
+	   pthread_t *ptWMProc,
+	   pthread_t *ptXMsgProc,
+	   pthread_mutex_t *ppmServerStarted,
+	   int dwScreen,
+	   HWND hwndScreen,
+	   BOOL allowOtherWM);
+
+void
+winDeinitMultiWindowWM (void);
+
+void
+winMinimizeWindow (Window id);
+
+
+/*
+ * winmultiwindowicons.c
+ */
+
+void
+winUpdateIcon (Window id);
+
+void 
+winInitGlobalIcons (void);
+
+void 
+winDestroyIcon(HICON hIcon);
+
+#endif /* XWIN_MULTIWINDOW */
+#endif
diff --git a/hw/xwin/winwindowswm.c b/hw/xwin/winwindowswm.c
new file mode 100755
index 0000000..e1994de
--- /dev/null
+++ b/hw/xwin/winwindowswm.c
@@ -0,0 +1,663 @@
+/* WindowsWM extension is based on AppleWM extension */
+/**************************************************************************
+
+Copyright (c) 2002 Apple Computer, Inc. All Rights Reserved.
+Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sub license, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice (including the
+next paragraph) shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
+IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
+ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+**************************************************************************/
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+
+#define NEED_REPLIES
+#define NEED_EVENTS
+#include "misc.h"
+#include "dixstruct.h"
+#include "extnsionst.h"
+#include "colormapst.h"
+#include "cursorstr.h"
+#include "scrnintstr.h"
+#include "servermd.h"
+#include "swaprep.h"
+#define _WINDOWSWM_SERVER_
+#include "windowswmstr.h"
+
+static int WMErrorBase;
+
+static DISPATCH_PROC(ProcWindowsWMDispatch);
+static DISPATCH_PROC(SProcWindowsWMDispatch);
+
+static void WindowsWMResetProc(ExtensionEntry* extEntry);
+
+static unsigned char WMReqCode = 0;
+static int WMEventBase = 0;
+
+static RESTYPE ClientType, EventType; /* resource types for event masks */
+static XID eventResource;
+
+/* Currently selected events */
+static unsigned int eventMask = 0;
+
+static int WMFreeClient (pointer data, XID id);
+static int WMFreeEvents (pointer data, XID id);
+static void SNotifyEvent(xWindowsWMNotifyEvent *from, xWindowsWMNotifyEvent *to);
+
+typedef struct _WMEvent *WMEventPtr;
+typedef struct _WMEvent {
+  WMEventPtr      next;
+  ClientPtr	    client;
+  XID		    clientResource;
+  unsigned int    mask;
+} WMEventRec;
+
+static inline BoxRec
+make_box (int x, int y, int w, int h)
+{
+  BoxRec r;
+  r.x1 = x;
+  r.y1 = y;
+  r.x2 = x + w;
+  r.y2 = y + h;
+  return r;
+}
+
+void
+winWindowsWMExtensionInit ()
+{
+  ExtensionEntry* extEntry;
+
+  ClientType = CreateNewResourceType(WMFreeClient);
+  EventType = CreateNewResourceType(WMFreeEvents);
+  eventResource = FakeClientID(0);
+
+  if (ClientType && EventType &&
+      (extEntry = AddExtension(WINDOWSWMNAME,
+			       WindowsWMNumberEvents,
+			       WindowsWMNumberErrors,
+			       ProcWindowsWMDispatch,
+			       SProcWindowsWMDispatch,
+			       WindowsWMResetProc,
+			       StandardMinorOpcode)))
+    {
+      WMReqCode = (unsigned char)extEntry->base;
+      WMErrorBase = extEntry->errorBase;
+      WMEventBase = extEntry->eventBase;
+      EventSwapVector[WMEventBase] = (EventSwapPtr) SNotifyEvent;
+    }
+}
+
+/*ARGSUSED*/
+static void
+WindowsWMResetProc (ExtensionEntry* extEntry)
+{
+}
+
+static int
+ProcWindowsWMQueryVersion(register ClientPtr client)
+{
+  xWindowsWMQueryVersionReply rep;
+  register int n;
+
+  REQUEST_SIZE_MATCH(xWindowsWMQueryVersionReq);
+  rep.type = X_Reply;
+  rep.length = 0;
+  rep.sequenceNumber = client->sequence;
+  rep.majorVersion = WINDOWS_WM_MAJOR_VERSION;
+  rep.minorVersion = WINDOWS_WM_MINOR_VERSION;
+  rep.patchVersion = WINDOWS_WM_PATCH_VERSION;
+  if (client->swapped)
+    {
+      swaps(&rep.sequenceNumber, n);
+      swapl(&rep.length, n);
+    }
+  WriteToClient(client, sizeof(xWindowsWMQueryVersionReply), (char *)&rep);
+  return (client->noClientException);
+}
+
+
+/* events */
+
+static inline void
+updateEventMask (WMEventPtr *pHead)
+{
+  WMEventPtr pCur;
+
+  eventMask = 0;
+  for (pCur = *pHead; pCur != NULL; pCur = pCur->next)
+    eventMask |= pCur->mask;
+}
+
+/*ARGSUSED*/
+static int
+WMFreeClient (pointer data, XID id)
+{
+  WMEventPtr   pEvent;
+  WMEventPtr   *pHead, pCur, pPrev;
+
+  pEvent = (WMEventPtr) data;
+  pHead = (WMEventPtr *) LookupIDByType(eventResource, EventType);
+  if (pHead)
+    {
+      pPrev = 0;
+      for (pCur = *pHead; pCur && pCur != pEvent; pCur=pCur->next)
+	pPrev = pCur;
+      if (pCur)
+	{
+	  if (pPrev)
+	    pPrev->next = pEvent->next;
+	  else
+	    *pHead = pEvent->next;
+	}
+      updateEventMask (pHead);
+    }
+  xfree ((pointer) pEvent);
+  return 1;
+}
+
+/*ARGSUSED*/
+static int
+WMFreeEvents (pointer data, XID id)
+{
+  WMEventPtr   *pHead, pCur, pNext;
+  
+  pHead = (WMEventPtr *) data;
+  for (pCur = *pHead; pCur; pCur = pNext)
+    {
+      pNext = pCur->next;
+      FreeResource (pCur->clientResource, ClientType);
+      xfree ((pointer) pCur);
+    }
+  xfree ((pointer) pHead);
+  eventMask = 0;
+  return 1;
+}
+
+static int
+ProcWindowsWMSelectInput (register ClientPtr client)
+{
+  REQUEST(xWindowsWMSelectInputReq);
+  WMEventPtr		pEvent, pNewEvent, *pHead;
+  XID			clientResource;
+
+  REQUEST_SIZE_MATCH (xWindowsWMSelectInputReq);
+  pHead = (WMEventPtr *)SecurityLookupIDByType(client, eventResource,
+					       EventType, DixWriteAccess);
+  if (stuff->mask != 0)
+    {
+      if (pHead)
+	{
+	  /* check for existing entry. */
+	  for (pEvent = *pHead; pEvent; pEvent = pEvent->next)
+	    {
+	      if (pEvent->client == client)
+		{
+		  pEvent->mask = stuff->mask;
+		  updateEventMask (pHead);
+		  return Success;
+		}
+	    }
+	}
+      
+      /* build the entry */
+      pNewEvent = (WMEventPtr) xalloc (sizeof (WMEventRec));
+      if (!pNewEvent)
+	return BadAlloc;
+      pNewEvent->next = 0;
+      pNewEvent->client = client;
+      pNewEvent->mask = stuff->mask;
+      /*
+       * add a resource that will be deleted when
+       * the client goes away
+       */
+      clientResource = FakeClientID (client->index);
+      pNewEvent->clientResource = clientResource;
+      if (!AddResource (clientResource, ClientType, (pointer)pNewEvent))
+	return BadAlloc;
+      /*
+       * create a resource to contain a pointer to the list
+       * of clients selecting input.  This must be indirect as
+       * the list may be arbitrarily rearranged which cannot be
+       * done through the resource database.
+       */
+      if (!pHead)
+	{
+	  pHead = (WMEventPtr *) xalloc (sizeof (WMEventPtr));
+	  if (!pHead ||
+	      !AddResource (eventResource, EventType, (pointer)pHead))
+	    {
+	      FreeResource (clientResource, RT_NONE);
+	      return BadAlloc;
+	    }
+	  *pHead = 0;
+	}
+      pNewEvent->next = *pHead;
+      *pHead = pNewEvent;
+      updateEventMask (pHead);
+    }
+  else if (stuff->mask == 0)
+    {
+      /* delete the interest */
+      if (pHead)
+	{
+	  pNewEvent = 0;
+	  for (pEvent = *pHead; pEvent; pEvent = pEvent->next)
+	    {
+	      if (pEvent->client == client)
+		break;
+	      pNewEvent = pEvent;
+	    }
+	  if (pEvent)
+	    {
+	      FreeResource (pEvent->clientResource, ClientType);
+	      if (pNewEvent)
+		pNewEvent->next = pEvent->next;
+	      else
+		*pHead = pEvent->next;
+	      xfree (pEvent);
+	      updateEventMask (pHead);
+	    }
+	}
+    }
+  else
+    {
+      client->errorValue = stuff->mask;
+      return BadValue;
+    }
+  return Success;
+}
+
+/*
+ * deliver the event
+ */
+
+void
+winWindowsWMSendEvent (int type, unsigned int mask, int which, int arg,
+		       Window window, int x, int y, int w, int h)
+{
+  WMEventPtr		*pHead, pEvent;
+  ClientPtr		client;
+  xWindowsWMNotifyEvent se;
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("winWindowsWMSendEvent %d %d %d %d,  %d %d - %d %d\n",
+	  type, mask, which, arg, x, y, w, h);
+#endif
+  pHead = (WMEventPtr *) LookupIDByType(eventResource, EventType);
+  if (!pHead)
+    return;
+  for (pEvent = *pHead; pEvent; pEvent = pEvent->next)
+    {
+      client = pEvent->client;
+#if CYGMULTIWINDOW_DEBUG
+      ErrorF ("winWindowsWMSendEvent - x%08x\n", (int) client);
+#endif
+      if ((pEvent->mask & mask) == 0
+	  || client == serverClient || client->clientGone)
+	{
+	  continue;
+	}
+#if CYGMULTIWINDOW_DEBUG 
+      ErrorF ("winWindowsWMSendEvent - send\n");
+#endif
+      se.type = type + WMEventBase;
+      se.kind = which;
+      se.window = window;
+      se.arg = arg;
+      se.x = x;
+      se.y = y;
+      se.w = w;
+      se.h = h;
+      se.sequenceNumber = client->sequence;
+      se.time = currentTime.milliseconds;
+      WriteEventsToClient (client, 1, (xEvent *) &se);
+    }
+}
+
+/* Safe to call from any thread. */
+unsigned int
+WindowsWMSelectedEvents (void)
+{
+  return eventMask;
+}
+
+
+/* general utility functions */
+
+static int
+ProcWindowsWMDisableUpdate (register ClientPtr client)
+{
+  REQUEST_SIZE_MATCH(xWindowsWMDisableUpdateReq);
+
+  //winDisableUpdate();
+
+  return (client->noClientException);
+}
+
+static int
+ProcWindowsWMReenableUpdate (register ClientPtr client)
+{
+  REQUEST_SIZE_MATCH(xWindowsWMReenableUpdateReq);
+
+  //winEnableUpdate(); 
+
+  return (client->noClientException);
+}
+
+
+/* window functions */
+
+static int
+ProcWindowsWMSetFrontProcess (register ClientPtr client)
+{
+  REQUEST_SIZE_MATCH(xWindowsWMSetFrontProcessReq);
+  
+  //QuartzMessageMainThread(kWindowsSetFrontProcess, NULL, 0);
+  
+  return (client->noClientException);
+}
+
+
+/* frame functions */
+
+static int
+ProcWindowsWMFrameGetRect (register ClientPtr client)
+{
+  xWindowsWMFrameGetRectReply rep;
+  BoxRec ir;
+  RECT rcNew;
+  REQUEST(xWindowsWMFrameGetRectReq);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameGetRect %d %d\n",
+	  (sizeof(xWindowsWMFrameGetRectReq) >> 2), (int) client->req_len);
+#endif
+  
+  REQUEST_SIZE_MATCH(xWindowsWMFrameGetRectReq);
+  rep.type = X_Reply;
+  rep.length = 0;
+  rep.sequenceNumber = client->sequence;
+
+  ir = make_box (stuff->ix, stuff->iy, stuff->iw, stuff->ih);
+
+  if (stuff->frame_rect != 0)
+    {
+      ErrorF ("ProcWindowsWMFrameGetRect - stuff->frame_rect != 0\n");
+      return BadValue;
+    }
+
+  /* Store the origin, height, and width in a rectangle structure */
+  SetRect (&rcNew, stuff->ix, stuff->iy,
+	   stuff->ix + stuff->iw, stuff->iy + stuff->ih);
+    
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameGetRect - %d %d %d %d\n",
+	  stuff->ix, stuff->iy, stuff->ix + stuff->iw, stuff->iy + stuff->ih);
+#endif
+
+  /*
+   * Calculate the required size of the Windows window rectangle,
+   * given the size of the Windows window client area.
+   */
+  AdjustWindowRectEx (&rcNew, stuff->frame_style, FALSE, stuff->frame_style_ex);
+  rep.x = rcNew.left;
+  rep.y = rcNew.top;
+  rep.w = rcNew.right - rcNew.left;
+  rep.h = rcNew.bottom - rcNew.top;
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameGetRect - %d %d %d %d\n",
+	  rep.x, rep.y, rep.w, rep.h);
+#endif
+
+  WriteToClient(client, sizeof(xWindowsWMFrameGetRectReply), (char *)&rep);
+  return (client->noClientException);
+}
+
+
+static int
+ProcWindowsWMFrameDraw (register ClientPtr client)
+{
+  REQUEST(xWindowsWMFrameDrawReq);
+  WindowPtr pWin;
+  win32RootlessWindowPtr pRLWinPriv;
+  RECT rcNew;
+  int nCmdShow, rc;
+  RegionRec newShape;
+  ScreenPtr pScreen;
+
+  REQUEST_SIZE_MATCH (xWindowsWMFrameDrawReq);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameDraw\n");
+#endif
+  rc = dixLookupWindow(&pWin, stuff->window, client, DixReadAccess);
+  if (rc != Success)
+      return rc;
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameDraw - Window found\n");
+#endif
+
+  pRLWinPriv = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, TRUE);
+  if (pRLWinPriv == 0) return BadWindow;
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameDraw - HWND 0x%08x 0x%08x 0x%08x\n",
+	  (int) pRLWinPriv->hWnd, (int) stuff->frame_style,
+	  (int) stuff->frame_style_ex);
+  ErrorF ("ProcWindowsWMFrameDraw - %d %d %d %d\n",
+	  stuff->ix, stuff->iy, stuff->iw, stuff->ih);
+#endif
+
+  /* Store the origin, height, and width in a rectangle structure */
+  SetRect (&rcNew, stuff->ix, stuff->iy,
+	   stuff->ix + stuff->iw, stuff->iy + stuff->ih);
+
+  /*
+   * Calculate the required size of the Windows window rectangle,
+   * given the size of the Windows window client area.
+   */
+  AdjustWindowRectEx (&rcNew, stuff->frame_style, FALSE, stuff->frame_style_ex);
+  
+  /* Set the window extended style flags */
+  if (!SetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE, stuff->frame_style_ex))
+    {
+      return BadValue;
+    }
+
+  /* Set the window standard style flags */
+  if (!SetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE, stuff->frame_style))
+    {
+      return BadValue;
+    }
+
+  /* Flush the window style */
+  if (!SetWindowPos (pRLWinPriv->hWnd, NULL,
+		     rcNew.left, rcNew.top,
+		     rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
+		     SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE))
+    {
+      return BadValue;
+    }
+  if (!IsWindowVisible(pRLWinPriv->hWnd))
+    nCmdShow = SW_HIDE;
+  else 
+    nCmdShow = SW_SHOWNA;
+
+  ShowWindow (pRLWinPriv->hWnd, nCmdShow);
+
+  winMWExtWMUpdateIcon (pWin->drawable.id);
+
+  if (wBoundingShape(pWin) != NULL)
+    {
+      pScreen = pWin->drawable.pScreen;
+      /* wBoundingShape is relative to *inner* origin of window.
+	 Translate by borderWidth to get the outside-relative position. */
+      
+      REGION_NULL(pScreen, &newShape);
+      REGION_COPY(pScreen, &newShape, wBoundingShape(pWin));
+      REGION_TRANSLATE(pScreen, &newShape, pWin->borderWidth, pWin->borderWidth);
+      winMWExtWMReshapeFrame (pRLWinPriv, &newShape);
+      REGION_UNINIT(pScreen, &newShape);
+    }
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameDraw - done\n");
+#endif
+
+  return (client->noClientException);
+}
+
+static int
+ProcWindowsWMFrameSetTitle(
+			   register ClientPtr client
+			   )
+{
+  unsigned int title_length, title_max;
+  unsigned char *title_bytes;
+  REQUEST(xWindowsWMFrameSetTitleReq);
+  WindowPtr pWin;
+  win32RootlessWindowPtr pRLWinPriv;
+  int rc;
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameSetTitle\n");
+#endif
+
+  REQUEST_AT_LEAST_SIZE(xWindowsWMFrameSetTitleReq);
+
+  rc = dixLookupWindow(&pWin, stuff->window, client, DixReadAccess);
+  if (rc != Success)
+      return rc;
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameSetTitle - Window found\n");
+#endif
+
+  title_length = stuff->title_length;
+  title_max = (stuff->length << 2) - sizeof(xWindowsWMFrameSetTitleReq);
+
+  if (title_max < title_length)
+    return BadValue;
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameSetTitle - length is valid\n");
+#endif
+
+  title_bytes = malloc (title_length+1);
+  strncpy (title_bytes, (unsigned char *) &stuff[1], title_length);
+  title_bytes[title_length] = '\0';
+
+  pRLWinPriv = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, FALSE);
+
+  if (pRLWinPriv == 0)
+    {
+      free (title_bytes);
+      return BadWindow;
+    }
+    
+  /* Flush the window style */
+  SetWindowText (pRLWinPriv->hWnd, title_bytes);
+
+  free (title_bytes);
+
+#if CYGMULTIWINDOW_DEBUG
+  ErrorF ("ProcWindowsWMFrameSetTitle - done\n");
+#endif
+
+  return (client->noClientException);
+}
+
+
+/* dispatch */
+
+static int
+ProcWindowsWMDispatch (register ClientPtr client)
+{
+  REQUEST(xReq);
+
+  switch (stuff->data)
+    {
+    case X_WindowsWMQueryVersion:
+      return ProcWindowsWMQueryVersion(client);
+    }
+
+  if (!LocalClient(client))
+    return WMErrorBase + WindowsWMClientNotLocal;
+
+  switch (stuff->data)
+    {
+    case X_WindowsWMSelectInput:
+      return ProcWindowsWMSelectInput(client);
+    case X_WindowsWMDisableUpdate:
+      return ProcWindowsWMDisableUpdate(client);
+    case X_WindowsWMReenableUpdate:
+      return ProcWindowsWMReenableUpdate(client);
+    case X_WindowsWMSetFrontProcess:
+      return ProcWindowsWMSetFrontProcess(client);
+    case X_WindowsWMFrameGetRect:
+      return ProcWindowsWMFrameGetRect(client);
+    case X_WindowsWMFrameDraw:
+      return ProcWindowsWMFrameDraw(client);
+    case X_WindowsWMFrameSetTitle:
+      return ProcWindowsWMFrameSetTitle(client);
+    default:
+      return BadRequest;
+    }
+}
+
+static void
+SNotifyEvent (xWindowsWMNotifyEvent *from, xWindowsWMNotifyEvent *to)
+{
+  to->type = from->type;
+  to->kind = from->kind;
+  cpswaps (from->sequenceNumber, to->sequenceNumber);
+  cpswapl (from->window, to->window);
+  cpswapl (from->time, to->time);
+  cpswapl (from->arg, to->arg);
+}
+
+static int
+SProcWindowsWMQueryVersion (register ClientPtr client)
+{
+  register int n;
+  REQUEST(xWindowsWMQueryVersionReq);
+  swaps(&stuff->length, n);
+  return ProcWindowsWMQueryVersion(client);
+}
+
+static int
+SProcWindowsWMDispatch (register ClientPtr client)
+{
+  REQUEST(xReq);
+
+  /* It is bound to be non-local when there is byte swapping */
+  if (!LocalClient(client))
+    return WMErrorBase + WindowsWMClientNotLocal;
+
+  /* only local clients are allowed WM access */
+  switch (stuff->data)
+    {
+    case X_WindowsWMQueryVersion:
+      return SProcWindowsWMQueryVersion(client);
+    default:
+      return BadRequest;
+    }
+}
diff --git a/hw/xwin/winwndproc.c b/hw/xwin/winwndproc.c
new file mode 100644
index 0000000..29ea81f
--- /dev/null
+++ b/hw/xwin/winwndproc.c
@@ -0,0 +1,1288 @@
+/*
+ *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of the XFree86 Project
+ *shall not be used in advertising or otherwise to promote the sale, use
+ *or other dealings in this Software without prior written authorization
+ *from the XFree86 Project.
+ *
+ * Authors:	Dakshinamurthy Karra
+ *		Suhaib M Siddiqi
+ *		Peter Busch
+ *		Harold L Hunt II
+ *		MATSUZAKI Kensuke
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "win.h"
+#include <commctrl.h>
+#include "winprefs.h"
+#include "winconfig.h"
+#include "winmsg.h"
+#include "inputstr.h"
+
+#ifdef XKB
+extern BOOL winCheckKeyPressed(WPARAM wParam, LPARAM lParam);
+#endif
+extern void winFixShiftKeys (int iScanCode);
+
+
+/*
+ * Global variables
+ */
+
+Bool				g_fCursor = TRUE;
+Bool				g_fButton[3] = { FALSE, FALSE, FALSE };
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool			g_fClipboard;
+extern HWND			g_hDlgDepthChange;
+extern Bool			g_fKeyboardHookLL;
+extern HWND			g_hwndKeyboardFocus;
+extern Bool			g_fSoftwareCursor;
+extern DWORD			g_dwCurrentThreadID;
+
+
+/*
+ * Called by winWakeupHandler
+ * Processes current Windows message
+ */
+
+LRESULT CALLBACK
+winWindowProc (HWND hwnd, UINT message, 
+	       WPARAM wParam, LPARAM lParam)
+{
+  static winPrivScreenPtr	s_pScreenPriv = NULL;
+  static winScreenInfo		*s_pScreenInfo = NULL;
+  static ScreenPtr		s_pScreen = NULL;
+  static HWND			s_hwndLastPrivates = NULL;
+  static HINSTANCE		s_hInstance;
+  static Bool			s_fTracking = FALSE;
+  static unsigned long		s_ulServerGeneration = 0;
+  static UINT			s_uTaskbarRestart = 0;
+  int				iScanCode;
+  int				i;
+
+#if CYGDEBUG
+  winDebugWin32Message("winWindowProc", hwnd, message, wParam, lParam);
+#endif
+  
+  /* Watch for server regeneration */
+  if (g_ulServerGeneration != s_ulServerGeneration)
+    {
+      /* Store new server generation */
+      s_ulServerGeneration = g_ulServerGeneration;
+    }
+
+  /* Only retrieve new privates pointers if window handle is null or changed */
+  if ((s_pScreenPriv == NULL || hwnd != s_hwndLastPrivates)
+      && (s_pScreenPriv = GetProp (hwnd, WIN_SCR_PROP)) != NULL)
+    {
+#if CYGDEBUG
+      winDebug ("winWindowProc - Setting privates handle\n");
+#endif
+      s_pScreenInfo = s_pScreenPriv->pScreenInfo;
+      s_pScreen = s_pScreenInfo->pScreen;
+      s_hwndLastPrivates = hwnd;
+    }
+  else if (s_pScreenPriv == NULL)
+    {
+      /* For safety, handle case that should never happen */
+      s_pScreenInfo = NULL;
+      s_pScreen = NULL;
+      s_hwndLastPrivates = NULL;
+    }
+
+  /* Branch on message type */
+  switch (message)
+    {
+    case WM_TRAYICON:
+      return winHandleIconMessage (hwnd, message, wParam, lParam,
+				   s_pScreenPriv);
+
+    case WM_CREATE:
+#if CYGDEBUG
+      winDebug ("winWindowProc - WM_CREATE\n");
+#endif
+      
+      /*
+       * Add a property to our display window that references
+       * this screens' privates.
+       *
+       * This allows the window procedure to refer to the
+       * appropriate window DC and shadow DC for the window that
+       * it is processing.  We use this to repaint exposed
+       * areas of our display window.
+       */
+      s_pScreenPriv = ((LPCREATESTRUCT) lParam)->lpCreateParams;
+      s_hInstance = ((LPCREATESTRUCT) lParam)->hInstance;
+      s_pScreenInfo = s_pScreenPriv->pScreenInfo;
+      s_pScreen = s_pScreenInfo->pScreen;
+      s_hwndLastPrivates = hwnd;
+      s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
+      SetProp (hwnd, WIN_SCR_PROP, s_pScreenPriv);
+
+      /* Setup tray icon */
+      if (!s_pScreenInfo->fNoTrayIcon)
+	{
+	  /*
+	   * NOTE: The WM_CREATE message is processed before CreateWindowEx
+	   * returns, so s_pScreenPriv->hwndScreen is invalid at this point.
+	   * We go ahead and copy our hwnd parameter over top of the screen
+	   * privates hwndScreen so that we have a valid value for
+	   * that member.  Otherwise, the tray icon will disappear
+	   * the first time you move the mouse over top of it.
+	   */
+	  
+	  s_pScreenPriv->hwndScreen = hwnd;
+
+	  winInitNotifyIcon (s_pScreenPriv);
+	}
+      return 0;
+
+    case WM_DISPLAYCHANGE:
+      /* We cannot handle a display mode change during initialization */
+      if (s_pScreenInfo == NULL)
+	FatalError ("winWindowProc - WM_DISPLAYCHANGE - The display "
+		    "mode changed while we were intializing.  This is "
+		    "very bad and unexpected.  Exiting.\n");
+
+      /*
+       * We do not care about display changes with
+       * fullscreen DirectDraw engines, because those engines set
+       * their own mode when they become active.
+       */
+      if (s_pScreenInfo->fFullScreen
+	  && (s_pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
+	      || s_pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL
+#ifdef XWIN_PRIMARYFB
+	      || s_pScreenInfo->dwEngine == WIN_SERVER_PRIMARY_DD
+#endif
+	      ))
+	{
+	  /* 
+	   * Store the new display dimensions and depth.
+	   * We do this here for future compatibility in case we
+	   * ever allow switching from fullscreen to windowed mode.
+	   */
+	  s_pScreenPriv->dwLastWindowsWidth = GetSystemMetrics (SM_CXSCREEN);
+	  s_pScreenPriv->dwLastWindowsHeight = GetSystemMetrics (SM_CYSCREEN);
+	  s_pScreenPriv->dwLastWindowsBitsPixel
+	    = GetDeviceCaps (s_pScreenPriv->hdcScreen, BITSPIXEL);	  
+	  break;
+	}
+      
+      ErrorF ("winWindowProc - WM_DISPLAYCHANGE - orig bpp: %d, last bpp: %d, "
+	      "new bpp: %d\n",
+	      (int) s_pScreenInfo->dwBPP,
+	      (int) s_pScreenPriv->dwLastWindowsBitsPixel,
+	      wParam);
+
+      ErrorF ("winWindowProc - WM_DISPLAYCHANGE - new width: %d "
+	      "new height: %d\n",
+	      LOWORD (lParam), HIWORD (lParam));
+
+      /*
+       * TrueColor --> TrueColor depth changes are disruptive for:
+       *	Windowed:
+       *		Shadow DirectDraw
+       *		Shadow DirectDraw Non-Locking
+       *		Primary DirectDraw
+       *
+       * TrueColor --> TrueColor depth changes are non-optimal for:
+       *	Windowed:
+       *		Shadow GDI
+       *
+       *	FullScreen:
+       *		Shadow GDI
+       *
+       * TrueColor --> PseudoColor or vice versa are disruptive for:
+       *	Windowed:
+       *		Shadow DirectDraw
+       *		Shadow DirectDraw Non-Locking
+       *		Primary DirectDraw
+       *		Shadow GDI
+       */
+
+      /*
+       * Check for a disruptive change in depth.
+       * We can only display a message for a disruptive depth change,
+       * we cannot do anything to correct the situation.
+       */
+      if ((s_pScreenInfo->dwBPP != wParam)
+	  && (s_pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
+	      || s_pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL
+#ifdef XWIN_PRIMARYFB
+	      || s_pScreenInfo->dwEngine == WIN_SERVER_PRIMARY_DD
+#endif
+	      ))
+	{
+	  /* Cannot display the visual until the depth is restored */
+	  ErrorF ("winWindowProc - Disruptive change in depth\n");
+
+	  /* Display Exit dialog */
+	  winDisplayDepthChangeDialog (s_pScreenPriv);
+
+	  /* Flag that we have an invalid screen depth */
+	  s_pScreenPriv->fBadDepth = TRUE;
+
+	  /* Minimize the display window */
+	  ShowWindow (hwnd, SW_MINIMIZE);
+	}
+      else
+	{
+	  /* Flag that we have a valid screen depth */
+	  s_pScreenPriv->fBadDepth = FALSE;
+	}
+      
+      /*
+       * Check for a change in display dimensions.
+       * We can simply recreate the same-sized primary surface when
+       * the display dimensions change.
+       */
+      if (s_pScreenPriv->dwLastWindowsWidth != LOWORD (lParam)
+	  || s_pScreenPriv->dwLastWindowsHeight != HIWORD (lParam))
+	{
+	  /*
+	   * NOTE: The non-DirectDraw engines set the ReleasePrimarySurface
+	   * and CreatePrimarySurface function pointers to point
+	   * to the no operation function, NoopDDA.  This allows us
+	   * to blindly call these functions, even if they are not
+	   * relevant to the current engine (e.g., Shadow GDI).
+	   */
+
+#if CYGDEBUG
+	  winDebug ("winWindowProc - WM_DISPLAYCHANGE - Dimensions changed\n");
+#endif
+	  
+	  /* Release the old primary surface */
+	  (*s_pScreenPriv->pwinReleasePrimarySurface) (s_pScreen);
+
+#if CYGDEBUG
+	  winDebug ("winWindowProc - WM_DISPLAYCHANGE - Released "
+		  "primary surface\n");
+#endif
+
+	  /* Create the new primary surface */
+	  (*s_pScreenPriv->pwinCreatePrimarySurface) (s_pScreen);
+
+#if CYGDEBUG
+	  winDebug ("winWindowProc - WM_DISPLAYCHANGE - Recreated "
+		  "primary surface\n");
+#endif
+
+#if 0
+	  /* Multi-Window mode uses RandR for resizes */
+	  if (s_pScreenInfo->fMultiWindow)
+	    {
+	      RRSetScreenConfig ();
+	    }
+#endif
+	}
+      else
+	{
+#if CYGDEBUG
+	  winDebug ("winWindowProc - WM_DISPLAYCHANGE - Dimensions did not "
+		  "change\n");
+#endif
+	}
+
+      /* Store the new display dimensions and depth */
+      if (s_pScreenInfo->fMultipleMonitors)
+	{
+	  s_pScreenPriv->dwLastWindowsWidth
+	    = GetSystemMetrics (SM_CXVIRTUALSCREEN);
+	  s_pScreenPriv->dwLastWindowsHeight
+	    = GetSystemMetrics (SM_CYVIRTUALSCREEN);
+	}
+      else
+	{
+	  s_pScreenPriv->dwLastWindowsWidth
+	    = GetSystemMetrics (SM_CXSCREEN);
+	  s_pScreenPriv->dwLastWindowsHeight
+	    = GetSystemMetrics (SM_CYSCREEN);
+	}
+      s_pScreenPriv->dwLastWindowsBitsPixel
+	= GetDeviceCaps (s_pScreenPriv->hdcScreen, BITSPIXEL);
+      break;
+
+    case WM_SIZE:
+      {
+	SCROLLINFO		si;
+	RECT			rcWindow;
+	int			iWidth, iHeight;
+
+#if CYGDEBUG
+	winDebug ("winWindowProc - WM_SIZE\n");
+#endif
+
+	/* Break if we do not use scrollbars */
+	if (!s_pScreenInfo->fScrollbars
+	    || !s_pScreenInfo->fDecoration
+#ifdef XWIN_MULTIWINDOWEXTWM
+	    || s_pScreenInfo->fMWExtWM
+#endif
+	    || s_pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOW
+	    || s_pScreenInfo->fMultiWindow
+#endif
+	    || s_pScreenInfo->fFullScreen)
+	  break;
+
+	/* No need to resize if we get minimized */
+	if (wParam == SIZE_MINIMIZED)
+	  return 0;
+
+	/*
+	 * Get the size of the whole window, including client area,
+	 * scrollbars, and non-client area decorations (caption, borders).
+	 * We do this because we need to check if the client area
+	 * without scrollbars is large enough to display the whole visual.
+	 * The new client area size passed by lParam already subtracts
+	 * the size of the scrollbars if they are currently displayed.
+	 * So checking is LOWORD(lParam) == visual_width and
+	 * HIWORD(lParam) == visual_height will never tell us to hide
+	 * the scrollbars because the client area would always be too small.
+	 * GetClientRect returns the same sizes given by lParam, so we
+	 * cannot use GetClientRect either.
+	 */
+	GetWindowRect (hwnd, &rcWindow);
+	iWidth = rcWindow.right - rcWindow.left;
+	iHeight = rcWindow.bottom - rcWindow.top;
+
+	ErrorF ("winWindowProc - WM_SIZE - window w: %d h: %d, "
+		"new client area w: %d h: %d\n",
+		iWidth, iHeight, LOWORD (lParam), HIWORD (lParam));
+
+	/* Subtract the frame size from the window size. */
+	iWidth -= 2 * GetSystemMetrics (SM_CXSIZEFRAME);
+	iHeight -= (2 * GetSystemMetrics (SM_CYSIZEFRAME)
+		    + GetSystemMetrics (SM_CYCAPTION));
+
+	/*
+	 * Update scrollbar page sizes.
+	 * NOTE: If page size == range, then the scrollbar is
+	 * automatically hidden.
+	 */
+
+	/* Is the naked client area large enough to show the whole visual? */
+	if (iWidth < s_pScreenInfo->dwWidth
+	    || iHeight < s_pScreenInfo->dwHeight)
+	  {
+	    /* Client area too small to display visual, use scrollbars */
+	    iWidth -= GetSystemMetrics (SM_CXVSCROLL);
+	    iHeight -= GetSystemMetrics (SM_CYHSCROLL);
+	  }
+	
+	/* Set the horizontal scrollbar page size */
+	si.cbSize = sizeof (si);
+	si.fMask = SIF_PAGE | SIF_RANGE;
+	si.nMin = 0;
+	si.nMax = s_pScreenInfo->dwWidth - 1;
+	si.nPage = iWidth;
+	SetScrollInfo (hwnd, SB_HORZ, &si, TRUE);
+	
+	/* Set the vertical scrollbar page size */
+	si.cbSize = sizeof (si);
+	si.fMask = SIF_PAGE | SIF_RANGE;
+	si.nMin = 0;
+	si.nMax = s_pScreenInfo->dwHeight - 1;
+	si.nPage = iHeight;
+	SetScrollInfo (hwnd, SB_VERT, &si, TRUE);
+
+	/*
+	 * NOTE: Scrollbars may have moved if they were at the 
+	 * far right/bottom, so we query their current position.
+	 */
+	
+	/* Get the horizontal scrollbar position and set the offset */
+	si.cbSize = sizeof (si);
+	si.fMask = SIF_POS;
+	GetScrollInfo (hwnd, SB_HORZ, &si);
+	s_pScreenInfo->dwXOffset = -si.nPos;
+	
+	/* Get the vertical scrollbar position and set the offset */
+	si.cbSize = sizeof (si);
+	si.fMask = SIF_POS;
+	GetScrollInfo (hwnd, SB_VERT, &si);
+	s_pScreenInfo->dwYOffset = -si.nPos;
+      }
+      return 0;
+
+    case WM_VSCROLL:
+      {
+	SCROLLINFO		si;
+	int			iVertPos;
+
+#if CYGDEBUG
+	winDebug ("winWindowProc - WM_VSCROLL\n");
+#endif
+      
+	/* Get vertical scroll bar info */
+	si.cbSize = sizeof (si);
+	si.fMask = SIF_ALL;
+	GetScrollInfo (hwnd, SB_VERT, &si);
+
+	/* Save the vertical position for comparison later */
+	iVertPos = si.nPos;
+
+	/*
+	 * Don't forget:
+	 * moving the scrollbar to the DOWN, scroll the content UP
+	 */
+	switch (LOWORD(wParam))
+	  {
+	  case SB_TOP:
+	    si.nPos = si.nMin;
+	    break;
+	  
+	  case SB_BOTTOM:
+	    si.nPos = si.nMax - si.nPage + 1;
+	    break;
+
+	  case SB_LINEUP:
+	    si.nPos -= 1;
+	    break;
+	  
+	  case SB_LINEDOWN:
+	    si.nPos += 1;
+	    break;
+	  
+	  case SB_PAGEUP:
+	    si.nPos -= si.nPage;
+	    break;
+	  
+	  case SB_PAGEDOWN:
+	    si.nPos += si.nPage;
+	    break;
+
+	  case SB_THUMBTRACK:
+	    si.nPos = si.nTrackPos;
+	    break;
+
+	  default:
+	    break;
+	  }
+
+	/*
+	 * We retrieve the position after setting it,
+	 * because Windows may adjust it.
+	 */
+	si.fMask = SIF_POS;
+	SetScrollInfo (hwnd, SB_VERT, &si, TRUE);
+	GetScrollInfo (hwnd, SB_VERT, &si);
+      
+	/* Scroll the window if the position has changed */
+	if (si.nPos != iVertPos)
+	  {
+	    /* Save the new offset for bit block transfers, etc. */
+	    s_pScreenInfo->dwYOffset = -si.nPos;
+
+	    /* Change displayed region in the window */
+	    ScrollWindowEx (hwnd,
+			    0,
+			    iVertPos - si.nPos,
+			    NULL,
+			    NULL,
+			    NULL,
+			    NULL,
+			    SW_INVALIDATE);
+	  
+	    /* Redraw the window contents */
+	    UpdateWindow (hwnd);
+	  }
+      }
+      return 0;
+
+    case WM_HSCROLL:
+      {
+	SCROLLINFO		si;
+	int			iHorzPos;
+
+#if CYGDEBUG
+	winDebug ("winWindowProc - WM_HSCROLL\n");
+#endif
+      
+	/* Get horizontal scroll bar info */
+	si.cbSize = sizeof (si);
+	si.fMask = SIF_ALL;
+	GetScrollInfo (hwnd, SB_HORZ, &si);
+
+	/* Save the horizontal position for comparison later */
+	iHorzPos = si.nPos;
+
+	/*
+	 * Don't forget:
+	 * moving the scrollbar to the RIGHT, scroll the content LEFT
+	 */
+	switch (LOWORD(wParam))
+	  {
+	  case SB_LEFT:
+	    si.nPos = si.nMin;
+	    break;
+	  
+	  case SB_RIGHT:
+	    si.nPos = si.nMax - si.nPage + 1;
+	    break;
+
+	  case SB_LINELEFT:
+	    si.nPos -= 1;
+	    break;
+	  
+	  case SB_LINERIGHT:
+	    si.nPos += 1;
+	    break;
+	  
+	  case SB_PAGELEFT:
+	    si.nPos -= si.nPage;
+	    break;
+	  
+	  case SB_PAGERIGHT:
+	    si.nPos += si.nPage;
+	    break;
+
+	  case SB_THUMBTRACK:
+	    si.nPos = si.nTrackPos;
+	    break;
+
+	  default:
+	    break;
+	  }
+
+	/*
+	 * We retrieve the position after setting it,
+	 * because Windows may adjust it.
+	 */
+	si.fMask = SIF_POS;
+	SetScrollInfo (hwnd, SB_HORZ, &si, TRUE);
+	GetScrollInfo (hwnd, SB_HORZ, &si);
+      
+	/* Scroll the window if the position has changed */
+	if (si.nPos != iHorzPos)
+	  {
+	    /* Save the new offset for bit block transfers, etc. */
+	    s_pScreenInfo->dwXOffset = -si.nPos;
+
+	    /* Change displayed region in the window */
+	    ScrollWindowEx (hwnd,
+			    iHorzPos - si.nPos,
+			    0,
+			    NULL,
+			    NULL,
+			    NULL,
+			    NULL,
+			    SW_INVALIDATE);
+	  
+	    /* Redraw the window contents */
+	    UpdateWindow (hwnd);
+	  }
+      }
+      return 0;
+
+    case WM_GETMINMAXINFO:
+      {
+	MINMAXINFO		*pMinMaxInfo = (MINMAXINFO *) lParam;
+	int			iCaptionHeight;
+	int			iBorderHeight, iBorderWidth;
+
+#if CYGDEBUG	
+	winDebug ("winWindowProc - WM_GETMINMAXINFO - pScreenInfo: %08x\n",
+		s_pScreenInfo);
+#endif
+
+	/* Can't do anything without screen info */
+	if (s_pScreenInfo == NULL
+	    || !s_pScreenInfo->fScrollbars
+	    || s_pScreenInfo->fFullScreen
+	    || !s_pScreenInfo->fDecoration
+#ifdef XWIN_MULTIWINDOWEXTWM
+	    || s_pScreenInfo->fMWExtWM
+#endif
+	    || s_pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOW
+	    || s_pScreenInfo->fMultiWindow
+#endif
+	    )
+	  break;
+
+	/*
+	 * Here we can override the maximum tracking size, which
+	 * is the largest size that can be assigned to our window
+	 * via the sizing border.
+	 */
+
+	/*
+	 * FIXME: Do we only need to do this once, since our visual size
+	 * does not change?  Does Windows store this value statically
+	 * once we have set it once?
+	 */
+
+	/* Get the border and caption sizes */
+	iCaptionHeight = GetSystemMetrics (SM_CYCAPTION);
+	iBorderWidth = 2 * GetSystemMetrics (SM_CXSIZEFRAME);
+	iBorderHeight = 2 * GetSystemMetrics (SM_CYSIZEFRAME);
+	
+	/* Allow the full visual to be displayed */
+	pMinMaxInfo->ptMaxTrackSize.x
+	  = s_pScreenInfo->dwWidth + iBorderWidth;
+	pMinMaxInfo->ptMaxTrackSize.y
+	  = s_pScreenInfo->dwHeight + iBorderHeight + iCaptionHeight;
+      }
+      return 0;
+
+    case WM_ERASEBKGND:
+#if CYGDEBUG
+      winDebug ("winWindowProc - WM_ERASEBKGND\n");
+#endif
+      /*
+       * Pretend that we did erase the background but we don't care,
+       * the application uses the full window estate. This avoids some
+       * flickering when resizing.
+       */
+      return TRUE;
+
+    case WM_PAINT:
+#if CYGDEBUG
+      winDebug ("winWindowProc - WM_PAINT\n");
+#endif
+      /* Only paint if we have privates and the server is enabled */
+      if (s_pScreenPriv == NULL
+	  || !s_pScreenPriv->fEnabled
+	  || (s_pScreenInfo->fFullScreen && !s_pScreenPriv->fActive)
+	  || s_pScreenPriv->fBadDepth)
+	{
+	  /* We don't want to paint */
+	  break;
+	}
+
+      /* Break out here if we don't have a valid paint routine */
+      if (s_pScreenPriv->pwinBltExposedRegions == NULL)
+	break;
+      
+      /* Call the engine dependent repainter */
+      (*s_pScreenPriv->pwinBltExposedRegions) (s_pScreen);
+      return 0;
+
+    case WM_PALETTECHANGED:
+      {
+#if CYGDEBUG
+	winDebug ("winWindowProc - WM_PALETTECHANGED\n");
+#endif
+	/*
+	 * Don't process if we don't have privates or a colormap,
+	 * or if we have an invalid depth.
+	 */
+	if (s_pScreenPriv == NULL
+	    || s_pScreenPriv->pcmapInstalled == NULL
+	    || s_pScreenPriv->fBadDepth)
+	  break;
+
+	/* Return if we caused the palette to change */
+	if ((HWND) wParam == hwnd)
+	  {
+	    /* Redraw the screen */
+	    (*s_pScreenPriv->pwinRedrawScreen) (s_pScreen);
+	    return 0;
+	  }
+	
+	/* Reinstall the windows palette */
+	(*s_pScreenPriv->pwinRealizeInstalledPalette) (s_pScreen);
+	
+	/* Redraw the screen */
+	(*s_pScreenPriv->pwinRedrawScreen) (s_pScreen);
+	return 0;
+      }
+
+    case WM_MOUSEMOVE:
+      /* We can't do anything without privates */
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+
+      /* Has the mouse pointer crossed screens? */
+      if (s_pScreen != miPointerGetScreen(inputInfo.pointer))
+	miPointerSetScreen (inputInfo.pointer, s_pScreenInfo->dwScreen,
+			       GET_X_LPARAM(lParam)-s_pScreenInfo->dwXOffset,
+			       GET_Y_LPARAM(lParam)-s_pScreenInfo->dwYOffset);
+
+      /* Are we tracking yet? */
+      if (!s_fTracking)
+	{
+	  TRACKMOUSEEVENT		tme;
+	  
+	  /* Setup data structure */
+	  ZeroMemory (&tme, sizeof (tme));
+	  tme.cbSize = sizeof (tme);
+	  tme.dwFlags = TME_LEAVE;
+	  tme.hwndTrack = hwnd;
+
+	  /* Call the tracking function */
+	  if (!(*g_fpTrackMouseEvent) (&tme))
+	    ErrorF ("winWindowProc - _TrackMouseEvent failed\n");
+
+	  /* Flag that we are tracking now */
+	  s_fTracking = TRUE;
+	}
+
+      /* Hide or show the Windows mouse cursor */
+      if (g_fSoftwareCursor && g_fCursor && (s_pScreenPriv->fActive || s_pScreenInfo->fLessPointer))
+	{
+	  /* Hide Windows cursor */
+	  g_fCursor = FALSE;
+	  ShowCursor (FALSE);
+	}
+      else if (g_fSoftwareCursor && !g_fCursor && !s_pScreenPriv->fActive
+	       && !s_pScreenInfo->fLessPointer)
+	{
+	  /* Show Windows cursor */
+	  g_fCursor = TRUE;
+	  ShowCursor (TRUE);
+	}
+      
+      /* Deliver absolute cursor position to X Server */
+      miPointerAbsoluteCursor (GET_X_LPARAM(lParam)-s_pScreenInfo->dwXOffset,
+			       GET_Y_LPARAM(lParam)-s_pScreenInfo->dwYOffset,
+			       g_c32LastInputEventTime = GetTickCount ());
+      return 0;
+
+    case WM_NCMOUSEMOVE:
+      /*
+       * We break instead of returning 0 since we need to call
+       * DefWindowProc to get the mouse cursor changes
+       * and min/max/close button highlighting in Windows XP.
+       * The Platform SDK says that you should return 0 if you
+       * process this message, but it fails to mention that you
+       * will give up any default functionality if you do return 0.
+       */
+      
+      /* We can't do anything without privates */
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      
+      /* Non-client mouse movement, show Windows cursor */
+      if (g_fSoftwareCursor && !g_fCursor)
+	{
+	  g_fCursor = TRUE;
+	  ShowCursor (TRUE);
+	}
+      break;
+
+    case WM_MOUSELEAVE:
+      /* Mouse has left our client area */
+
+      /* Flag that we are no longer tracking */
+      s_fTracking = FALSE;
+
+      /* Show the mouse cursor, if necessary */
+      if (g_fSoftwareCursor && !g_fCursor)
+	{
+	  g_fCursor = TRUE;
+	  ShowCursor (TRUE);
+	}
+      return 0;
+
+    case WM_LBUTTONDBLCLK:
+    case WM_LBUTTONDOWN:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      if (s_pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOWEXTWM
+	  || s_pScreenInfo->fMWExtWM
+#endif
+	  )
+	SetCapture (hwnd);
+      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button1, wParam);
+      
+    case WM_LBUTTONUP:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      if (s_pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOWEXTWM
+	  || s_pScreenInfo->fMWExtWM
+#endif
+	  )
+	ReleaseCapture ();
+      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button1, wParam);
+
+    case WM_MBUTTONDBLCLK:
+    case WM_MBUTTONDOWN:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      if (s_pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOWEXTWM
+	  || s_pScreenInfo->fMWExtWM
+#endif
+	  )
+	SetCapture (hwnd);
+      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button2, wParam);
+      
+    case WM_MBUTTONUP:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      if (s_pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOWEXTWM
+	  || s_pScreenInfo->fMWExtWM
+#endif
+	  )
+	ReleaseCapture ();
+      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button2, wParam);
+      
+    case WM_RBUTTONDBLCLK:
+    case WM_RBUTTONDOWN:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      if (s_pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOWEXTWM
+	  || s_pScreenInfo->fMWExtWM
+#endif
+	  )
+	SetCapture (hwnd);
+      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button3, wParam);
+      
+    case WM_RBUTTONUP:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      if (s_pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOWEXTWM
+	  || s_pScreenInfo->fMWExtWM
+#endif
+	  )
+	ReleaseCapture ();
+      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button3, wParam);
+
+    case WM_XBUTTONDBLCLK:
+    case WM_XBUTTONDOWN:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      if (s_pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOWEXTWM
+	  || s_pScreenInfo->fMWExtWM
+#endif
+	  )
+	SetCapture (hwnd);
+      return winMouseButtonsHandle (s_pScreen, ButtonPress, HIWORD(wParam) + 5, wParam);
+    case WM_XBUTTONUP:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+      if (s_pScreenInfo->fRootless
+#ifdef XWIN_MULTIWINDOWEXTWM
+	  || s_pScreenInfo->fMWExtWM
+#endif
+	  )
+	ReleaseCapture ();
+      return winMouseButtonsHandle (s_pScreen, ButtonRelease, HIWORD(wParam) + 5, wParam);
+
+    case WM_TIMER:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+
+      /* Branch on the timer id */
+      switch (wParam)
+	{
+	case WIN_E3B_TIMER_ID:
+	  /* Send delayed button press */
+	  winMouseButtonsSendEvent (ButtonPress,
+				    s_pScreenPriv->iE3BCachedPress);
+
+	  /* Kill this timer */
+	  KillTimer (s_pScreenPriv->hwndScreen, WIN_E3B_TIMER_ID);
+
+	  /* Clear screen privates flags */
+	  s_pScreenPriv->iE3BCachedPress = 0;
+	  break;
+
+	case WIN_POLLING_MOUSE_TIMER_ID:
+	  {
+	    POINT		point;
+	    WPARAM		wL, wM, wR, wShift, wCtrl;
+	    LPARAM		lPos;
+	    
+	    /* Get the current position of the mouse cursor */
+	    GetCursorPos (&point);
+	    
+	    /* Map from screen (-X, -Y) to root (0, 0) */
+	    point.x -= GetSystemMetrics (SM_XVIRTUALSCREEN);
+	    point.y -= GetSystemMetrics (SM_YVIRTUALSCREEN);
+	    
+	    /* Deliver absolute cursor position to X Server */
+	    miPointerAbsoluteCursor (point.x, point.y,
+				     g_c32LastInputEventTime = GetTickCount());
+
+	    /* Check if a button was released but we didn't see it */
+	    GetCursorPos (&point);
+	    wL = (GetKeyState (VK_LBUTTON) & 0x8000)?MK_LBUTTON:0;
+	    wM = (GetKeyState (VK_MBUTTON) & 0x8000)?MK_MBUTTON:0;
+	    wR = (GetKeyState (VK_RBUTTON) & 0x8000)?MK_RBUTTON:0;
+	    wShift = (GetKeyState (VK_SHIFT) & 0x8000)?MK_SHIFT:0;
+	    wCtrl = (GetKeyState (VK_CONTROL) & 0x8000)?MK_CONTROL:0;
+	    lPos = MAKELPARAM(point.x, point.y);
+	    if (g_fButton[0] & !wL)
+	    PostMessage (hwnd, WM_LBUTTONUP, wCtrl|wM|wR|wShift, lPos);
+	    if (g_fButton[1] & !wM)
+	      PostMessage (hwnd, WM_MBUTTONUP, wCtrl|wL|wR|wShift, lPos);
+	    if (g_fButton[2] & !wR)
+	      PostMessage (hwnd, WM_RBUTTONUP, wCtrl|wL|wM|wShift, lPos);
+	  }
+	}
+      return 0;
+
+    case WM_CTLCOLORSCROLLBAR:
+      FatalError ("winWindowProc - WM_CTLCOLORSCROLLBAR - We are not "
+		  "supposed to get this message.  Exiting.\n");
+      return 0;
+
+    case WM_MOUSEWHEEL:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+#if CYGDEBUG
+      winDebug ("winWindowProc - WM_MOUSEWHEEL\n");
+#endif
+      winMouseWheel (s_pScreen, GET_WHEEL_DELTA_WPARAM(wParam));
+      break;
+
+    case WM_SETFOCUS:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+
+      /* Save handle of our main window that last received focus */
+      g_hwndKeyboardFocus = hwnd;
+
+      /* Restore the state of all mode keys */
+      winRestoreModeKeyStates ();
+
+      /* Add the keyboard hook if possible */
+      if (g_fKeyboardHookLL)
+	g_fKeyboardHookLL = winInstallKeyboardHookLL ();
+      return 0;
+
+    case WM_KILLFOCUS:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+
+      /* Clear handle of our main window that last received focus */
+      g_hwndKeyboardFocus = NULL;
+
+      /* Release any pressed keys */
+      winKeybdReleaseKeys ();
+
+      /* Remove our keyboard hook if it is installed */
+      winRemoveKeyboardHookLL ();
+      return 0;
+
+    case WM_SYSKEYDOWN:
+    case WM_KEYDOWN:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+
+      /*
+       * FIXME: Catching Alt-F4 like this is really terrible.  This should
+       * be generalized to handle other Windows keyboard signals.  Actually,
+       * the list keys to catch and the actions to perform when caught should
+       * be configurable; that way user's can customize the keys that they
+       * need to have passed through to their window manager or apps, or they
+       * can remap certain actions to new key codes that do not conflict
+       * with the X apps that they are using.  Yeah, that'll take awhile.
+       */
+      if ((s_pScreenInfo->fUseWinKillKey && wParam == VK_F4
+	   && (GetKeyState (VK_MENU) & 0x8000))
+	  || (s_pScreenInfo->fUseUnixKillKey && wParam == VK_BACK
+	      && (GetKeyState (VK_MENU) & 0x8000)
+	      && (GetKeyState (VK_CONTROL) & 0x8000)))
+	{
+	  /*
+	   * Better leave this message here, just in case some unsuspecting
+	   * user enters Alt + F4 and is surprised when the application
+	   * quits.
+	   */
+	  ErrorF ("winWindowProc - WM_*KEYDOWN - Closekey hit, quitting\n");
+	  
+	  /* Display Exit dialog */
+	  winDisplayExitDialog (s_pScreenPriv);
+	  return 0;
+	}
+      
+      /*
+       * Don't do anything for the Windows keys, as focus will soon
+       * be returned to Windows.  We may be able to trap the Windows keys,
+       * but we should determine if that is desirable before doing so.
+       */
+      if ((wParam == VK_LWIN || wParam == VK_RWIN) && !g_fKeyboardHookLL)
+	break;
+
+#ifdef XKB
+      /* 
+       * Discard presses generated from Windows auto-repeat
+       * ago: Only discard them if XKB is not disabled 
+       */
+      if (!g_winInfo.xkb.disable && (lParam & (1<<30)))
+      {
+        switch (wParam)
+        {
+          /* ago: Pressing LControl while RControl is pressed is 
+           * Indicated as repeat. Fix this!
+           */
+          case VK_CONTROL:
+          case VK_SHIFT:
+            if (winCheckKeyPressed(wParam, lParam))
+              return 0;
+            break;
+          default:
+            return 0;
+        }
+      } 
+#endif 
+      
+      /* Discard fake Ctrl_L presses that precede AltGR on non-US keyboards */
+      if (winIsFakeCtrl_L (message, wParam, lParam))
+	return 0;
+      
+      /* Translate Windows key code to X scan code */
+      winTranslateKey (wParam, lParam, &iScanCode);
+
+      /* Ignore repeats for CapsLock */
+      if (wParam == VK_CAPITAL)
+	lParam = 1;
+
+      /* Send the key event(s) */
+      for (i = 0; i < LOWORD(lParam); ++i)
+	winSendKeyEvent (iScanCode, TRUE);
+      return 0;
+
+    case WM_SYSKEYUP:
+    case WM_KEYUP:
+      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+	break;
+
+      /*
+       * Don't do anything for the Windows keys, as focus will soon
+       * be returned to Windows.  We may be able to trap the Windows keys,
+       * but we should determine if that is desirable before doing so.
+       */
+      if ((wParam == VK_LWIN || wParam == VK_RWIN) && !g_fKeyboardHookLL)
+	break;
+
+      /* Ignore the fake Ctrl_L that follows an AltGr release */
+      if (winIsFakeCtrl_L (message, wParam, lParam))
+	return 0;
+
+      /* Enqueue a keyup event */
+      winTranslateKey (wParam, lParam, &iScanCode);
+      winSendKeyEvent (iScanCode, FALSE);
+
+      /* Release all pressed shift keys */
+      if (wParam == VK_SHIFT) 
+        winFixShiftKeys (iScanCode);
+      return 0;
+
+    case WM_HOTKEY:
+      if (s_pScreenPriv == NULL)
+	break;
+
+      /* Call the engine-specific hot key handler */
+      (*s_pScreenPriv->pwinHotKeyAltTab) (s_pScreen);
+      return 0;
+
+    case WM_ACTIVATE:
+      if (s_pScreenPriv == NULL
+	  || s_pScreenInfo->fIgnoreInput)
+	break;
+
+      /* TODO: Override display of window when we have a bad depth */
+      if (LOWORD(wParam) != WA_INACTIVE && s_pScreenPriv->fBadDepth)
+	{
+	  ErrorF ("winWindowProc - WM_ACTIVATE - Bad depth, trying "
+		  "to override window activation\n");
+
+	  /* Minimize the window */
+	  ShowWindow (hwnd, SW_MINIMIZE);
+
+	  /* Display dialog box */
+	  if (g_hDlgDepthChange != NULL)
+	    {
+	      /* Make the existing dialog box active */
+	      SetActiveWindow (g_hDlgDepthChange);
+	    }
+	  else
+	    {
+	      /* TODO: Recreate the dialog box and bring to the top */
+	      ShowWindow (g_hDlgDepthChange, SW_SHOWDEFAULT);
+	    }
+
+	  /* Don't do any other processing of this message */
+	  return 0;
+	}
+
+#if CYGDEBUG
+      winDebug ("winWindowProc - WM_ACTIVATE\n");
+#endif
+
+      /*
+       * Focus is being changed to another window.
+       * The other window may or may not belong to
+       * our process.
+       */
+
+      /* Clear any lingering wheel delta */
+      s_pScreenPriv->iDeltaZ = 0;
+
+      /* Reshow the Windows mouse cursor if we are being deactivated */
+      if (g_fSoftwareCursor && LOWORD(wParam) == WA_INACTIVE
+	  && !g_fCursor)
+	{
+	  /* Show Windows cursor */
+	  g_fCursor = TRUE;
+	  ShowCursor (TRUE);
+	}
+      return 0;
+
+    case WM_ACTIVATEAPP:
+      if (s_pScreenPriv == NULL
+	  || s_pScreenInfo->fIgnoreInput)
+	break;
+
+#if CYGDEBUG || TRUE
+      winDebug ("winWindowProc - WM_ACTIVATEAPP\n");
+#endif
+
+      /* Activate or deactivate */
+      s_pScreenPriv->fActive = wParam;
+
+      /* Reshow the Windows mouse cursor if we are being deactivated */
+      if (g_fSoftwareCursor && !s_pScreenPriv->fActive
+	  && !g_fCursor)
+	{
+	  /* Show Windows cursor */
+	  g_fCursor = TRUE;
+	  ShowCursor (TRUE);
+	}
+
+#ifdef XWIN_CLIPBOARD
+      /* Make sure the clipboard chain is ok. */
+      winFixClipboardChain ();
+#endif
+
+      /* Call engine specific screen activation/deactivation function */
+      (*s_pScreenPriv->pwinActivateApp) (s_pScreen);
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+      if (s_pScreenPriv->fActive)
+	{
+	  /* Restack all window unless using built-in wm. */
+	  if (s_pScreenInfo->fInternalWM && s_pScreenInfo->fAnotherWMRunning)
+	    winMWExtWMRestackWindows (s_pScreen);
+	}
+#endif
+
+      return 0;
+
+    case WM_COMMAND:
+      switch (LOWORD (wParam))
+	{
+	case ID_APP_EXIT:
+	  /* Display Exit dialog */
+	  winDisplayExitDialog (s_pScreenPriv);
+	  return 0;
+
+#ifdef XWIN_MULTIWINDOW
+	case ID_APP_HIDE_ROOT:
+	  if (s_pScreenPriv->fRootWindowShown)
+	    ShowWindow (s_pScreenPriv->hwndScreen, SW_HIDE);
+	  else
+	    ShowWindow (s_pScreenPriv->hwndScreen, SW_SHOW);
+	  s_pScreenPriv->fRootWindowShown = !s_pScreenPriv->fRootWindowShown;
+	  return 0;
+#endif
+
+	case ID_APP_ABOUT:
+	  /* Display the About box */
+	  winDisplayAboutDialog (s_pScreenPriv);
+	  return 0;
+
+	default:
+	  /* It's probably one of the custom menus... */
+	  if (HandleCustomWM_COMMAND (0, LOWORD (wParam)))
+	    return 0;
+	}
+      break;
+
+    case WM_ENDSESSION:
+    case WM_GIVEUP:
+      /* Tell X that we are giving up */
+#ifdef XWIN_MULTIWINDOW
+      if (s_pScreenInfo->fMultiWindow)
+	winDeinitMultiWindowWM ();
+#endif
+      GiveUp (0);
+      return 0;
+
+    case WM_CLOSE:
+      /* Display Exit dialog */
+      winDisplayExitDialog (s_pScreenPriv);
+      return 0;
+
+    case WM_SETCURSOR:
+      if (LOWORD(lParam) == HTCLIENT)
+	{
+	  if (!g_fSoftwareCursor) SetCursor (s_pScreenPriv->cursor.handle);
+	  return TRUE;
+	}
+      break;
+
+#ifdef XWIN_MULTIWINDOWEXTWM
+    case WM_MANAGE:
+      ErrorF ("winWindowProc - WM_MANAGE\n");
+      s_pScreenInfo->fAnotherWMRunning = FALSE;
+
+      if (s_pScreenInfo->fInternalWM)
+	{
+	  EnumThreadWindows (g_dwCurrentThreadID, winMWExtWMDecorateWindow, 0);
+	  //RootlessRepositionWindows (s_pScreen);
+	}
+      break;
+
+    case WM_UNMANAGE:
+      ErrorF ("winWindowProc - WM_UNMANAGE\n");
+      s_pScreenInfo->fAnotherWMRunning = TRUE;
+
+      if (s_pScreenInfo->fInternalWM)
+	{
+	  EnumThreadWindows (g_dwCurrentThreadID, winMWExtWMDecorateWindow, 0);
+	  winMWExtWMRestackWindows (s_pScreen);
+	}
+      break;
+#endif
+
+    default:
+      if(message == s_uTaskbarRestart)
+	{
+	  winInitNotifyIcon (s_pScreenPriv);
+	}
+      break;
+    }
+
+  return DefWindowProc (hwnd, message, wParam, lParam);
+}
diff --git a/hw/xwin/xlaunch/COPYING b/hw/xwin/xlaunch/COPYING
new file mode 100755
index 0000000..c7fa844
--- /dev/null
+++ b/hw/xwin/xlaunch/COPYING
@@ -0,0 +1,25 @@
+
+ Copyright (c) 2005 Alexander Gottwald
+
+ Permission is hereby granted, free of charge, to any person obtaining a
+ copy of this software and associated documentation files (the "Software"),
+ to deal in the Software without restriction, including without limitation
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ and/or sell copies of the Software, and to permit persons to whom the
+ Software is furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ Except as contained in this notice, the name(s) of the above copyright
+ holders shall not be used in advertising or otherwise to promote the sale,
+ use or other dealings in this Software without prior written authorization.
+
diff --git a/hw/xwin/xlaunch/Makefile b/hw/xwin/xlaunch/Makefile
new file mode 100755
index 0000000..f7cf923
--- /dev/null
+++ b/hw/xwin/xlaunch/Makefile
@@ -0,0 +1,79 @@
+#
+# Copyright (c) 2005 Alexander Gottwald
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the "Software"),
+# to deal in the Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish, distribute, sublicense,
+# and/or sell copies of the Software, and to permit persons to whom the
+# Software is furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+# THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+# DEALINGS IN THE SOFTWARE.
+#
+# Except as contained in this notice, the name(s) of the above copyright
+# holders shall not be used in advertising or otherwise to promote the sale,
+# use or other dealings in this Software without prior written authorization.
+#
+WINDRES=windres
+
+TARGET=mingw
+#DEBUG_FLAGS=-D_DEBUG
+
+OS_FLAGS_mingw=-mno-cygwin
+OS_FLAGS=$(OS_FLAGS_$(TARGET)) $(DEBUG_FLAGS)
+
+X11_DIR_$(TARGET)=/usr/X11R6
+X11_DIR_mingw=../../../../../exports
+X11_DIR=$(X11_DIR_$(TARGET))
+X11_INCLUDE=-I$(X11_DIR)/include
+X11_LIBDIR=-L$(X11_DIR)/lib
+X11_LIBS_$(TARGET)=-lX11
+X11_LIBS_mingw=-lX11 -lwsock32
+X11_LIBS=$(X11_LIBS_$(TARGET))
+
+PROGRAMFILES:=$(shell cygpath -u $(PROGRAMFILES))
+#MSXML_DIR=$(PROGRAMFILES)/MSXML 4.0
+MSXML_DIR=$(PROGRAMFILES)/Microsoft XML Parser SDK
+MSXML_INCLUDE="-I$(MSXML_DIR)/inc"
+MSXML_LIBDIR="-L$(MSXML_DIR)/lib"
+MSXML_LIBS=
+
+
+CXXFLAGS=-g $(OS_FLAGS) $(X11_INCLUDE) $(MSXML_INCLUDE)
+LDFLAGS=-mwindows $(X11_LIBDIR) $(MSXML_LIBDIR)
+LIBS=-lcomctl32 -lole32 -loleaut32 $(X11_LIBS) $(MSXML_LIBS)
+all:xlaunch.exe
+%.res: %.rc
+	$(WINDRES) -O coff -o $@ $<
+
+WINDOW_PARTS=window util dialog wizard
+WINDOW_OBJECTS=$(foreach file,$(WINDOW_PARTS),window/$(file).o) 
+
+RESOURCES_IMAGES=resources/multiwindow.bmp resources/fullscreen.bmp \
+	resources/windowed.bmp resources/nodecoration.bmp
+
+resources/resources.res: resources/resources.rc resources/resources.h \
+	resources/images.rc resources/dialog.rc resources/strings.rc \
+	$(RESOURCES_IMAGES)
+xlaunch.exe: $(WINDOW_OBJECTS) main.o config.o resources/resources.res
+	$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ $^ $(LIBS)
+
+
+window/dialog.o: window/dialog.cc window/dialog.h window/window.h window/util.h
+window/frame.o: window/frame.cc window/frame.h window/window.h
+window/util.o: window/util.cc window/util.h
+window/window.o: window/window.cc window/window.h window/util.h
+window/wizard.o: window/wizard.cc window/wizard.h window/dialog.h \
+  window/window.h window/util.h
+main.o: main.cc window/util.h window/wizard.h window/dialog.h \
+  window/window.h resources/resources.h config.h
+config.o: config.cc config.h
diff --git a/hw/xwin/xlaunch/config.cc b/hw/xwin/xlaunch/config.cc
new file mode 100644
index 0000000..b6bf65a
--- /dev/null
+++ b/hw/xwin/xlaunch/config.cc
@@ -0,0 +1,282 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+#include "config.h"
+#include "window/util.h"
+#include <msxml2.h>
+#include <stdexcept>
+
+const CLSID CLSID_DOMDocument40 = {0x88d969c0,0xf192,0x11d4,0xa6,0x5f,0x00,0x40,0x96,0x32,0x51,0xe5};
+const CLSID CLSID_DOMDocument30 = {0xf5078f32,0xc551,0x11d3,0x89,0xb9,0x00,0x00,0xf8,0x1f,0xe2,0x21};
+const IID IID_IXMLDOMDocument2 = {0x2933BF95,0x7B36,0x11d2,0xB2,0x0E,0x00,0xC0,0x4F,0x98,0x3E,0x60};
+
+#define HRCALL(x, msg) if (FAILED(x)) { throw std::runtime_error("OLE Error:" msg " failed"); };
+
+char *wcconvert(const wchar_t *wstr)
+{
+    int chars = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
+    if (chars == 0)
+	throw win32_error("WideCharToMultiByte");
+    char *mbstr = new char[chars];
+    chars = WideCharToMultiByte(CP_ACP, 0, wstr, -1, mbstr, chars, NULL, NULL);
+    if (chars == 0)
+	throw win32_error("WideCharToMultiByte");
+    return mbstr;
+}
+
+wchar_t *mbconvert(const char *mbstr)
+{
+    int chars = MultiByteToWideChar(CP_ACP, 0, mbstr, -1, NULL, 0);
+    if (chars == 0)
+	throw win32_error("MultiByteToWideChar");
+    wchar_t *wstr = new wchar_t[chars];
+    chars = MultiByteToWideChar(CP_ACP, 0, mbstr, -1, wstr, chars);
+    if (chars == 0)
+	throw win32_error("MultiByteToWideChar");
+    return wstr;
+}
+
+VARIANT VariantString(const char *filename)
+{
+
+    wchar_t *str = mbconvert(filename);
+
+    VARIANT var;
+    VariantInit(&var);
+    V_BSTR(&var) = SysAllocString(str);
+    V_VT(&var) = VT_BSTR;
+
+    delete [] str;
+    return var;
+}
+
+VARIANT VariantString(const wchar_t *str)
+{
+   VARIANT var;
+   VariantInit(&var);
+   V_BSTR(&var) = SysAllocString(str);
+   V_VT(&var) = VT_BSTR;
+   return var;
+}
+
+IXMLDOMDocument2 *CreateDocument()
+{
+    IXMLDOMDocument2 *doc = NULL;
+    
+    CoInitialize(NULL);
+
+    HRCALL(CoCreateInstance(CLSID_DOMDocument40, NULL, CLSCTX_INPROC_SERVER,
+                      IID_IXMLDOMDocument2, (void**)&doc), "CoCreateInstance");
+
+    try {
+      	HRCALL(doc->put_async(VARIANT_FALSE), "put_async");
+	HRCALL(doc->put_validateOnParse(VARIANT_FALSE), "put_validateOnParse");
+	HRCALL(doc->put_resolveExternals(VARIANT_FALSE), "put_resolveExternals");
+
+	IXMLDOMProcessingInstruction *pi = NULL;
+	IXMLDOMElement *root = NULL;
+     	BSTR xml = SysAllocString(L"xml");
+	BSTR ver = SysAllocString(L"version='1.0'");
+	HRCALL(doc->createProcessingInstruction(xml,ver, &pi), 
+		"createProcessingInstruction");
+	HRCALL(doc->appendChild(pi, NULL),
+		"appendChild");
+	pi->Release();
+	SysFreeString(xml);
+	SysFreeString(ver);
+
+	BSTR elemname = SysAllocString(L"XLaunch");
+	HRCALL(doc->createElement(elemname, &root), "createElement");
+	HRCALL(doc->appendChild(root, NULL), "appendChild");
+	SysFreeString(elemname);
+    } catch (...)
+    {
+	doc->Release();
+	throw;
+    }
+    return doc;
+}
+
+void setAttribute(IXMLDOMElement *elem, const wchar_t *name, const wchar_t *value)
+{
+    BSTR str = SysAllocString(name);
+    VARIANT var = VariantString(value);
+    HRCALL(elem->setAttribute(str, var), "setAttribute");
+    VariantClear(&var);
+    SysFreeString(str);
+}
+
+void setAttribute(IXMLDOMElement *elem, const wchar_t *name, const char *value)
+{
+    wchar_t *wstr = mbconvert(value);
+    setAttribute(elem, name, wstr);
+    delete [] wstr;
+    return;
+}
+
+void CConfig::Save(const char *filename)
+{
+    IXMLDOMDocument2 *doc = CreateDocument();
+    IXMLDOMElement *root = NULL;
+
+    HRCALL(doc->get_documentElement(&root), "get_documentElement");
+
+    switch (window)
+    {
+	case MultiWindow:
+	    setAttribute(root, L"WindowMode", L"MultiWindow");
+	    break;
+	case Fullscreen:
+	    setAttribute(root, L"WindowMode", L"Fullscreen");
+	    break;
+	default:
+	case Windowed:
+	    setAttribute(root, L"WindowMode", L"Windowed");
+	    break;
+	case Nodecoration:
+	    setAttribute(root, L"WindowMode", L"Nodecoration");
+	    break;
+    }
+    switch (client)
+    {
+	default:
+	case NoClient:
+	    setAttribute(root, L"ClientMode", L"NoClient");
+	    break;
+	case StartProgram:
+	    setAttribute(root, L"ClientMode", L"StartProgram");
+	    break;
+	case XDMCP:
+	    setAttribute(root, L"ClientMode", L"XDMCP");
+	    break;
+    }
+    setAttribute(root, L"LocalClient", local?L"True":L"False");
+    setAttribute(root, L"Display", display.c_str());
+    setAttribute(root, L"Program", program.c_str());
+    setAttribute(root, L"RemoteProtocol", protocol.c_str());
+    setAttribute(root, L"RemoteHost", host.c_str());
+    setAttribute(root, L"RemoteUser", user.c_str());
+    setAttribute(root, L"XDMCPHost", xdmcp_host.c_str());
+    setAttribute(root, L"XDMCPBroadcast", broadcast?L"True":L"False");
+    setAttribute(root, L"XDMCPIndirect", indirect?L"True":L"False");
+    setAttribute(root, L"Clipboard", clipboard?L"True":L"False");
+    setAttribute(root, L"ExtraParams", extra_params.c_str());
+
+    VARIANT var = VariantString(filename);
+    HRCALL(doc->save(var), "save");
+    VariantClear(&var);
+
+
+    root->Release();
+    doc->Release();
+}
+
+BOOL getAttribute(IXMLDOMElement *elem, const wchar_t *name, std::string &ret)
+{
+    VARIANT var;
+    HRCALL(elem->getAttribute((OLECHAR*)name, &var), "getAttribute"); 
+    if (V_VT(&var) != VT_NULL && V_VT(&var) == VT_BSTR)
+    {
+	char *str = wcconvert(V_BSTR(&var));
+	ret = str;
+	delete [] str;
+	return true;
+    }
+    return false;
+}
+
+BOOL getAttributeBool(IXMLDOMElement *elem, const wchar_t *name, bool &ret)
+{
+    std::string str;
+    if (getAttribute(elem, name, str))
+    {
+	if (str == "True")
+	    ret = true;
+	else
+	    ret = false;
+	return true;
+    }
+    return false;
+}
+
+
+void CConfig::Load(const char *filename)
+{
+    IXMLDOMDocument2 *doc = CreateDocument();
+    IXMLDOMElement *root = NULL;
+
+    VARIANT var = VariantString(filename);
+    VARIANT_BOOL status;
+    HRCALL(doc->load(var, &status), "load");
+    VariantClear(&var);
+
+    if (status == VARIANT_FALSE)
+    {
+	doc->Release();
+	return;
+    }
+
+    HRCALL(doc->get_documentElement(&root), "get_documentElement");
+
+    std::string windowMode;
+    std::string clientMode;
+
+    if (getAttribute(root, L"WindowMode", windowMode))
+    {
+	if (windowMode == "MultiWindow")
+	    window = MultiWindow;
+	else if (windowMode == "Fullscreen")
+	    window = Fullscreen;
+	else if (windowMode == "Windowed")
+	    window = Windowed;
+	else if (windowMode == "Nodecoration")
+	    window = Nodecoration;
+    }
+    if (getAttribute(root, L"ClientMode", clientMode))
+    {
+	if (clientMode == "NoClient")
+	    client = NoClient;
+	else if (clientMode == "StartProgram")
+	    client = StartProgram;
+	else if (clientMode == "XDMCP")
+	    client = XDMCP;
+    }
+    
+    getAttributeBool(root, L"LocalClient", local);
+    getAttribute(root, L"Display", display);
+    getAttribute(root, L"Program", program);
+    getAttribute(root, L"RemoteProtocol", protocol);
+    getAttribute(root, L"RemoteHost", host);
+    getAttribute(root, L"RemoteUser", user);
+    getAttribute(root, L"XDMCPHost", xdmcp_host);
+    getAttributeBool(root, L"XDMCPBroadcast", broadcast);
+    getAttributeBool(root, L"XDMCPIndirect", indirect);
+    getAttributeBool(root, L"Clipboard", clipboard);
+    getAttribute(root, L"ExtraParams", extra_params);
+    
+
+    doc->Release();
+}
+
diff --git a/hw/xwin/xlaunch/config.h b/hw/xwin/xlaunch/config.h
new file mode 100644
index 0000000..f0aed3c
--- /dev/null
+++ b/hw/xwin/xlaunch/config.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+#ifndef __CONFIG_H__
+#define __CONFIG_H__
+
+#include <string>
+struct CConfig
+{
+    enum {MultiWindow, Fullscreen, Windowed, Nodecoration} window;
+    enum {NoClient, StartProgram, XDMCP} client;
+    bool local;
+    std::string display;
+    std::string protocol;
+    std::string program;
+    std::string host;
+    std::string user;
+    bool broadcast;
+    bool indirect;
+    std::string xdmcp_host;
+    bool clipboard;
+    std::string extra_params;
+#ifdef _DEBUG
+    CConfig() : window(MultiWindow), client(StartProgram), local(false), display("1"), 
+                protocol("Putty"), program("xterm"), host("lupus"), user("ago"),
+                broadcast(false), indirect(false), xdmcp_host("lupus"),
+                clipboard(true), extra_params() {};
+#else
+    CConfig() : window(MultiWindow), client(StartProgram), local(false), display("0"), 
+                protocol("Putty"), program("xterm"), host(""), user(""), 
+                broadcast(true), indirect(false), xdmcp_host(""),
+                clipboard(true), extra_params() {};
+#endif
+    void Load(const char* filename);
+    void Save(const char* filename);
+};
+
+#endif
diff --git a/hw/xwin/xlaunch/main.cc b/hw/xwin/xlaunch/main.cc
new file mode 100755
index 0000000..2247d3a
--- /dev/null
+++ b/hw/xwin/xlaunch/main.cc
@@ -0,0 +1,700 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+#include "window/util.h"
+#include "window/wizard.h"
+#include "resources/resources.h"
+#include "config.h"
+#include <prsht.h>
+#include <commctrl.h>
+
+#include <stdexcept>
+
+#include <X11/Xlib.h>
+
+/// @brief Send WM_ENDSESSION to all program windows.
+/// This will shutdown the started xserver
+BOOL CALLBACK KillWindowsProc(HWND hwnd, LPARAM lParam)
+{
+    SendMessage(hwnd, WM_ENDSESSION, 0, 0);
+    return TRUE;
+}
+
+/// @brief Actual wizard implementation.
+/// This is based on generic CWizard but handles the special dialogs
+class CMyWizard : public CWizard 
+{
+    public:
+    private:
+	CConfig config; /// Storage for config options.
+    public:
+        /// @brief Constructor.
+        /// Set wizard pages.
+        CMyWizard() : CWizard() 
+        {
+            AddPage(IDD_DISPLAY, IDS_DISPLAY_TITLE, IDS_DISPLAY_SUBTITLE);
+            AddPage(IDD_CLIENTS, IDS_CLIENTS_TITLE, IDS_CLIENTS_SUBTITLE);
+            AddPage(IDD_PROGRAM, IDS_PROGRAM_TITLE, IDS_PROGRAM_SUBTITLE);
+            AddPage(IDD_XDMCP, IDS_XDMCP_TITLE, IDS_XDMCP_SUBTITLE);
+            //AddPage(IDD_FONTPATH, IDS_FONTPATH_TITLE, IDS_FONTPATH_SUBTITLE);
+            AddPage(IDD_CLIPBOARD, IDS_CLIPBOARD_TITLE, IDS_CLIPBOARD_SUBTITLE);
+            AddPage(IDD_FINISH, IDS_FINISH_TITLE, IDS_FINISH_SUBTITLE);
+        }
+
+	virtual void LoadConfig(const char *filename)
+	{
+	    try {
+		config.Load(filename);
+	    } catch (std::runtime_error &e)
+	    {
+		printf("Fehler: %s\n", e.what());
+	    }
+	}
+
+        /// @brief Handle the PSN_WIZNEXT message.
+        /// @param hwndDlg Handle to active page dialog.
+        /// @param index Index of current page.
+        /// @return TRUE if the message was handled. FALSE otherwise. 
+	virtual BOOL WizardNext(HWND hwndDlg, unsigned index)
+	{
+#ifdef _DEBUG
+	    printf("%s %d\n", __FUNCTION__, index);
+#endif
+	    switch (PageID(index))
+	    {
+		case IDD_DISPLAY:
+                    // Check for select window mode
+		    if (IsDlgButtonChecked(hwndDlg, IDC_MULTIWINDOW))
+			config.window = CConfig::MultiWindow;
+		    else if (IsDlgButtonChecked(hwndDlg, IDC_FULLSCREEN))
+			config.window = CConfig::Fullscreen;
+		    else if (IsDlgButtonChecked(hwndDlg, IDC_WINDOWED))
+			config.window = CConfig::Windowed;
+		    else if (IsDlgButtonChecked(hwndDlg, IDC_NODECORATION))
+			config.window = CConfig::Nodecoration;
+		    else
+		    {
+			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
+			return TRUE;
+		    }
+                    // Get selected display number
+		    {
+			char buffer[512];
+			GetDlgItemText(hwndDlg, IDC_DISPLAY, buffer, 512);
+			buffer[511] = 0;
+			config.display = buffer;
+                    }
+                    // Check for valid input
+                    if (config.display.empty())
+			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
+                    else
+                        SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIENTS);
+		    return TRUE;
+		case IDD_CLIENTS:
+                    // Check for select client startup method
+		    if (IsDlgButtonChecked(hwndDlg, IDC_CLIENT))
+		    {
+			config.client = CConfig::StartProgram;
+			SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_PROGRAM);
+		    } else if (IsDlgButtonChecked(hwndDlg, IDC_XDMCP))
+		    {
+			config.client = CConfig::XDMCP;
+			SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_XDMCP);
+		    } else if (IsDlgButtonChecked(hwndDlg, IDC_CLIENT_NONE))
+		    {
+			config.client = CConfig::NoClient;
+			SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIPBOARD);
+		    } else
+			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
+		    return TRUE;
+		case IDD_PROGRAM:
+                    // Check wether local or remote client should be started
+		    if (IsDlgButtonChecked(hwndDlg, IDC_CLIENT_LOCAL))
+			config.local = true;
+		    else if (IsDlgButtonChecked(hwndDlg, IDC_CLIENT_REMOTE))
+			config.local = false;
+		    else
+		    {
+			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
+			return TRUE;
+		    }
+                    // Read program, user and host name
+		    {
+			char buffer[512];
+			GetDlgItemText(hwndDlg, IDC_CLIENT_USER, buffer, 512);
+			buffer[511] = 0;
+			config.user = buffer;
+			GetDlgItemText(hwndDlg, IDC_CLIENT_HOST, buffer, 512);
+			buffer[511] = 0;
+			config.host = buffer;
+			GetDlgItemText(hwndDlg, IDC_CLIENT_PROGRAM, buffer, 512);
+			buffer[511] = 0;
+			config.program = buffer;
+		    }
+                    // Check for valid input
+		    if (!config.local && (config.host.empty() || config.program.empty()))
+			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
+		    else
+			SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIPBOARD);
+		    return TRUE;
+		case IDD_XDMCP:
+                    // Check for broadcast
+		    if (IsDlgButtonChecked(hwndDlg, IDC_XDMCP_BROADCAST))
+			config.broadcast = true;
+		    else if (IsDlgButtonChecked(hwndDlg, IDC_XDMCP_QUERY))
+			config.broadcast = false;
+		    else
+		    {
+			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
+			return TRUE;
+		    }
+                    // Check for indirect mode
+		    if (IsDlgButtonChecked(hwndDlg, IDC_XDMCP_INDIRECT))
+			config.indirect = true;
+		    else
+			config.indirect = false;
+                    // Read hostname
+		    {
+			char buffer[512];
+			GetDlgItemText(hwndDlg, IDC_XDMCP_HOST, buffer, 512);
+			buffer[511] = 0;
+			config.xdmcp_host = buffer;
+		    }
+                    // Check for valid input
+		    if (!config.broadcast && config.xdmcp_host.empty())
+			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
+		    else	
+			SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIPBOARD);
+		    return TRUE;
+                case IDD_CLIPBOARD:
+                    // check for clipboard
+                    if (IsDlgButtonChecked(hwndDlg, IDC_CLIPBOARD))
+                        config.clipboard = true;
+                    else
+                        config.clipboard = false;
+                    // read parameters
+		    {
+			char buffer[512];
+			GetDlgItemText(hwndDlg, IDC_EXTRA_PARAMS, buffer, 512);
+			buffer[511] = 0;
+			config.extra_params = buffer;
+		    }
+                    SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_FINISH);
+                    return TRUE;
+		default:
+		    break;
+	    }
+	    return FALSE;
+	}
+        /// @brief Handle PSN_WIZFINISH message.
+        /// @param hwndDlg Handle to active page dialog.
+        /// @param index Index of current page.
+        /// @return TRUE if the message was handled. FALSE otherwise. 
+	virtual BOOL WizardFinish(HWND hwndDlg, unsigned index)
+	{
+#ifdef _DEBUG
+	    printf("finish %d\n", index);
+#endif
+	    return FALSE;
+	}
+        /// @brief Handle PSN_WIZBACK message.
+        /// Basicly handles switching to proper page (skipping XDMCP or program page
+        /// if required).
+        /// @param hwndDlg Handle to active page dialog.
+        /// @param index Index of current page.
+        /// @return TRUE if the message was handled. FALSE otherwise. 
+	virtual BOOL WizardBack(HWND hwndDlg, unsigned index)
+	{
+	    switch (PageID(index))
+	    {
+		case IDD_PROGRAM:
+		case IDD_XDMCP:
+		    SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIENTS);
+		    return TRUE;
+		case IDD_FONTPATH:
+                case IDD_CLIPBOARD: // temporary. fontpath is disabled
+		    switch (config.client)
+		    {
+			case CConfig::NoClient:	
+			    SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIENTS);
+			    return TRUE;
+			case CConfig::StartProgram:
+			    SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_PROGRAM);
+			    return TRUE;
+			case CConfig::XDMCP:
+			    SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_XDMCP);
+			    return TRUE;
+		    }
+		    break;
+	    }
+	    return FALSE;
+	}
+        /// @brief Handle PSN_SETACTIVE message.
+        /// @param hwndDlg Handle to active page dialog.
+        /// @param index Index of current page.
+        /// @return TRUE if the message was handled. FALSE otherwise. 
+	virtual BOOL WizardActivate(HWND hwndDlg, unsigned index)
+	{
+#ifdef _DEBUG
+	    printf("%s %d\n", __FUNCTION__, index);
+#endif
+	    switch (PageID(index))
+	    {
+		case IDD_CLIENTS:
+                    // Enable or disable XDMCP radiobutton and text
+		    EnableWindow(GetDlgItem(hwndDlg, IDC_XDMCP), config.window != CConfig::MultiWindow);
+		    EnableWindow(GetDlgItem(hwndDlg, IDC_XDMCP_DESC), config.window != CConfig::MultiWindow);
+		    break;
+	    }
+	    return FALSE;
+	}
+    protected:
+        /// @brief Enable or disable the control for remote clients.
+        /// @param hwndDlg Handle to active page dialog.
+        /// @param state State of control group.
+	void EnableRemoteProgramGroup(HWND hwndDlg, BOOL state)
+	{
+	    EnableWindow(GetDlgItem(hwndDlg, IDC_CLIENT_PROTOCOL), state);
+	    EnableWindow(GetDlgItem(hwndDlg, IDC_CLIENT_HOST), state);
+	    EnableWindow(GetDlgItem(hwndDlg, IDC_CLIENT_USER), state);
+	    EnableWindow(GetDlgItem(hwndDlg, IDC_CLIENT_PROTOCOL_DESC), state);
+	    EnableWindow(GetDlgItem(hwndDlg, IDC_CLIENT_HOST_DESC), state);
+	    EnableWindow(GetDlgItem(hwndDlg, IDC_CLIENT_USER_DESC), state);
+	}
+        /// @brief Enable or disable the control for XDMCP connection.
+        /// @param hwndDlg Handle to active page dialog.
+        /// @param state State of control group.
+	void EnableXDMCPQueryGroup(HWND hwndDlg, BOOL state)
+	{
+	    EnableWindow(GetDlgItem(hwndDlg, IDC_XDMCP_HOST), state);
+	    EnableWindow(GetDlgItem(hwndDlg, IDC_XDMCP_INDIRECT), state);
+	}
+        /// @brief Fill program box with default values.
+        /// @param hwndDlg Handle to active page dialog.
+	void FillProgramBox(HWND hwndDlg)
+	{
+	    HWND cbwnd = GetDlgItem(hwndDlg, IDC_CLIENT_PROGRAM);
+	    if (cbwnd == NULL)
+		return;
+	    SendMessage(cbwnd, CB_RESETCONTENT, 0, 0);
+	    SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) "xterm");
+	    SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) "startkde");
+	    SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) "gnome-session");
+	    SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) ".xinitrc");
+	    SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) "wmaker");
+	    SendMessage(cbwnd, CB_SETCURSEL, 0, 0);
+	}
+        /// @brief Fill protocol box with default values.
+        /// @param hwndDlg Handle to active page dialog.
+	void FillProtocolBox(HWND hwndDlg)
+	{
+	    HWND cbwnd = GetDlgItem(hwndDlg, IDC_CLIENT_PROTOCOL);
+	    if (cbwnd == NULL)
+		return;
+	    SendMessage(cbwnd, CB_RESETCONTENT, 0, 0);
+	    SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) "Putty");
+	    //SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) "OpenSSH");
+	    SendMessage(cbwnd, CB_SETCURSEL, 0, 0);
+	}
+	void ShowSaveDialog(HWND parent)
+	{
+	    char szTitle[512];
+	    char szFilter[512];
+	    char szFileTitle[512];
+	    char szFile[MAX_PATH];
+	    HINSTANCE hInst = GetModuleHandle(NULL);
+	    
+	    LoadString(hInst, IDS_SAVE_TITLE, szTitle, sizeof(szTitle));
+	    LoadString(hInst, IDS_SAVE_FILETITLE, szFileTitle, sizeof(szFileTitle));
+	    LoadString(hInst, IDS_SAVE_FILTER, szFilter, sizeof(szFilter));
+	    for (unsigned i=0; szFilter[i]; i++) 
+		if (szFilter[i] == '%') 
+		    szFilter[i] = '\0'; 
+
+	    strcpy(szFile, "config.xlaunch");
+
+	    OPENFILENAME ofn;
+	    memset(&ofn, 0, sizeof(OPENFILENAME));
+	    ofn.lStructSize = sizeof(OPENFILENAME); 
+	    ofn.hwndOwner = parent; 
+	    ofn.lpstrFilter = szFilter; 
+	    ofn.lpstrFile= szFile; 
+	    ofn.nMaxFile = sizeof(szFile)/ sizeof(*szFile); 
+	    ofn.lpstrFileTitle = szFileTitle; 
+	    ofn.nMaxFileTitle = sizeof(szFileTitle); 
+	    ofn.lpstrInitialDir = (LPSTR)NULL; 
+	    ofn.Flags = OFN_SHOWHELP | OFN_OVERWRITEPROMPT; 
+	    ofn.lpstrTitle = szTitle;
+
+	    if (GetSaveFileName(&ofn))
+	    {
+		try {
+      		    config.Save(ofn.lpstrFile);
+		} catch (std::runtime_error &e)
+		{
+		    printf("Fehler: %s\n", e.what());
+		}
+	    } 
+	}
+    public:
+	   
+        /// @brief Handle messages fo the dialog pages.
+        /// @param hwndDlg Handle of active dialog.
+        /// @param uMsg Message code.
+        /// @param wParam Message parameter.
+        /// @param lParam Message parameter.
+        /// @param psp Handle to sheet paramters. 
+        virtual INT_PTR PageDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam, PROPSHEETPAGE *psp)
+        {
+            HWND hwnd;
+            switch (uMsg)
+            {
+                case WM_INITDIALOG:
+                    switch (PageID(PageIndex(psp)))
+                    {
+                        case IDD_DISPLAY:
+                            // Init display dialog. Enable correct check buttons
+			    switch (config.window)
+			    {
+				default:
+				case CConfig::MultiWindow:
+				    CheckRadioButton(hwndDlg, IDC_MULTIWINDOW, IDC_NODECORATION, IDC_MULTIWINDOW);
+				    break;
+				case  CConfig::Fullscreen:
+				    CheckRadioButton(hwndDlg, IDC_MULTIWINDOW, IDC_NODECORATION, IDC_FULLSCREEN);
+				    break;
+				case  CConfig::Windowed:
+				    CheckRadioButton(hwndDlg, IDC_MULTIWINDOW, IDC_NODECORATION, IDC_WINDOWED);
+				    break;
+				case  CConfig::Nodecoration:
+				    CheckRadioButton(hwndDlg, IDC_MULTIWINDOW, IDC_NODECORATION, IDC_NODECORATION);
+				    break;
+			    }
+                            // Set display number
+                            SetDlgItemText(hwndDlg, IDC_DISPLAY, config.display.c_str());
+                            break;
+                        case IDD_CLIENTS:
+                            // Init client dialog. Enable correct check buttons
+			    switch (config.client)
+			    {
+				default:
+				case CConfig::NoClient:
+				    CheckRadioButton(hwndDlg, IDC_CLIENT_NONE, IDC_CLIENT, IDC_CLIENT_NONE);
+				    break;
+				case CConfig::StartProgram:
+				    CheckRadioButton(hwndDlg, IDC_CLIENT_NONE, IDC_CLIENT, IDC_CLIENT);
+				    break;
+				case CConfig::XDMCP:
+				    CheckRadioButton(hwndDlg, IDC_CLIENT_NONE, IDC_CLIENT, IDC_XDMCP);
+				    break;
+			    }
+                            break;
+			case IDD_PROGRAM:
+                            // Init program dialog. Check local and remote buttons 
+                            CheckRadioButton(hwndDlg, IDC_CLIENT_LOCAL, IDC_CLIENT_REMOTE, config.local?IDC_CLIENT_LOCAL:IDC_CLIENT_REMOTE);
+			    EnableRemoteProgramGroup(hwndDlg, config.local?FALSE:TRUE);
+                            // Fill combo boxes
+			    FillProgramBox(hwndDlg);
+			    FillProtocolBox(hwndDlg);
+                            // Set edit fields
+			    if (!config.program.empty())
+			       	SetDlgItemText(hwndDlg, IDC_CLIENT_PROGRAM, config.program.c_str());
+			    SetDlgItemText(hwndDlg, IDC_CLIENT_USER, config.user.c_str());
+			    SetDlgItemText(hwndDlg, IDC_CLIENT_HOST, config.host.c_str());
+			    break;
+			case IDD_XDMCP:
+                            // Init XDMCP dialog. Check broadcast and indirect button
+                            CheckRadioButton(hwndDlg, IDC_XDMCP_QUERY, IDC_XDMCP_BROADCAST, config.broadcast?IDC_XDMCP_BROADCAST:IDC_XDMCP_QUERY);
+                            CheckDlgButton(hwndDlg, IDC_XDMCP_INDIRECT, config.indirect?BST_CHECKED:BST_UNCHECKED);
+			    EnableXDMCPQueryGroup(hwndDlg, config.broadcast?FALSE:TRUE);
+                            // Set hostname
+			    SetDlgItemText(hwndDlg, IDC_XDMCP_HOST, config.xdmcp_host.c_str());
+			    break;
+                        case IDD_CLIPBOARD:
+                            CheckDlgButton(hwndDlg, IDC_CLIPBOARD, config.clipboard?BST_CHECKED:BST_UNCHECKED);
+                            SetDlgItemText(hwndDlg, IDC_EXTRA_PARAMS, config.extra_params.c_str());
+                            break;
+
+                    }
+                case WM_COMMAND:
+                    // Handle control messages
+                    switch (LOWORD(wParam))
+                    {
+                        // Handle clicks on images. Check proper radiobutton
+                        case IDC_MULTIWINDOW_IMG:
+                        case IDC_FULLSCREEN_IMG:
+                        case IDC_WINDOWED_IMG:
+                        case IDC_NODECORATION_IMG:
+                            CheckRadioButton(hwndDlg, IDC_MULTIWINDOW, IDC_NODECORATION, LOWORD(wParam)-4);
+                            SetFocus(GetDlgItem(hwndDlg, LOWORD(wParam)-4));
+                            break;
+                        // Disable unavailable controls 
+                        case IDC_CLIENT_REMOTE:
+                        case IDC_CLIENT_LOCAL:
+			    EnableRemoteProgramGroup(hwndDlg, LOWORD(wParam) == IDC_CLIENT_REMOTE);
+                            break;
+			case IDC_XDMCP_QUERY:
+			case IDC_XDMCP_BROADCAST:
+			    EnableXDMCPQueryGroup(hwndDlg, LOWORD(wParam) == IDC_XDMCP_QUERY);
+			    break;
+			case IDC_FINISH_SAVE:
+			    ShowSaveDialog(hwndDlg);
+			    break;
+                    }
+            }
+            // pass messages to parent
+            return CWizard::PageDispatch(hwndDlg, uMsg, wParam, lParam, psp);
+        }
+        
+        /// @brief Try to connect to server.
+        /// Repeat until successful, server died or maximum number of retries
+        /// reached.
+        Display *WaitForServer(HANDLE serverProcess)
+        {
+            int     ncycles  = 120;         /* # of cycles to wait */
+            int     cycles;                 /* Wait cycle count */
+            Display *xd;
+
+            for (cycles = 0; cycles < ncycles; cycles++) {
+                if ((xd = XOpenDisplay(NULL))) {
+                    return xd;
+                }
+                else {
+                    if (WaitForSingleObject(serverProcess, 1000) == WAIT_TIMEOUT)
+                        continue;
+                }
+            }
+            return NULL;
+        }
+               
+        /// @brief Do the actual start of Xming and clients
+	void StartUp()
+	{
+	    std::string buffer;
+	    std::string client;
+
+            // Construct display strings
+	    std::string display_id = ":" + config.display;
+	    std::string display = "localhost" + display_id + ":0";
+
+#ifdef _DEBUG
+            // Debug only: Switch to Xming installation directory
+	    SetCurrentDirectory("C:\\Programme\\Xming");
+#endif	    
+
+            // Build Xming commandline
+	    buffer = "Xming " + display_id + " ";
+	    switch (config.window)
+	    {
+		case CConfig::MultiWindow:
+		    buffer += "-multiwindow ";
+		    break;
+		case CConfig::Fullscreen:
+		    buffer += "-fullscreen ";
+		    break;
+		case CConfig::Nodecoration:
+		    buffer += "-nodecoration ";
+		    break;
+		default:
+		    break;
+	    }
+            // Add XDMCP parameter
+	    if (config.client == CConfig::XDMCP)
+	    {
+		if (config.broadcast)
+		    buffer += "-broadcast ";
+		else 
+		{
+		    if (config.indirect)
+			buffer += "-indirect ";
+		    else
+			buffer += "-query ";
+		    buffer += config.xdmcp_host;
+            buffer += " ";
+		}
+	    }
+            if (config.clipboard)
+                buffer += "-clipboard ";
+            if (!config.extra_params.empty())
+            {
+                buffer += config.extra_params;
+                buffer += " ";
+            }
+            
+            // Construct client commandline
+	    if (config.client == CConfig::StartProgram)
+	    {
+		if (!config.local)
+		{
+		    char cmdline[512];
+                    std::string host = config.host;
+                    if (!config.user.empty())
+                        host = config.user + "@" + config.host;
+		    if (config.protocol == "Putty")
+			snprintf(cmdline,512,"plink -X %s %s", 
+                                host.c_str(),config.program.c_str());
+		    else
+			snprintf(cmdline,512,"ssh -Y %s %s", 
+                                host.c_str(),config.program.c_str());
+		    client += cmdline;
+		} else
+		    client += config.program.c_str();
+	    }
+
+            // Prepare program startup
+     	    STARTUPINFO si, sic;
+	    PROCESS_INFORMATION pi, pic;
+	    HANDLE handles[2];
+	    DWORD hcount = 0; 
+            Display *dpy = NULL;
+
+	    ZeroMemory( &si, sizeof(si) );
+	    si.cb = sizeof(si);
+	    ZeroMemory( &pi, sizeof(pi) );
+	    ZeroMemory( &sic, sizeof(sic) );
+	    sic.cb = sizeof(sic);
+	    ZeroMemory( &pic, sizeof(pic) );
+
+	    // Start Xming process. 
+#ifdef _DEBUG
+	    printf("%s\n", buffer.c_str());
+#endif
+	    if( !CreateProcess( NULL, (CHAR*)buffer.c_str(), NULL, NULL, 
+                        FALSE, 0, NULL, NULL, &si, &pi )) 
+		throw win32_error("CreateProcess failed");
+	    handles[hcount++] = pi.hProcess;
+
+	    if (!client.empty())
+	    {
+                // Set DISPLAY variable
+		SetEnvironmentVariable("DISPLAY",display.c_str());
+
+                // Wait for server to startup
+                dpy = WaitForServer(pi.hProcess);
+                if (dpy == NULL)
+                {
+                    while (hcount--)
+                        TerminateProcess(handles[hcount], (DWORD)-1);
+		    throw std::runtime_error("Connection to server failed");
+                }
+                
+#ifdef _DEBUG
+		printf("%s\n", client.c_str());
+#endif
+
+                // Hide a console window 
+                // FIXME: This may make it impossible to enter the password
+		sic.dwFlags = STARTF_USESHOWWINDOW;
+		sic.wShowWindow = SW_HIDE;
+
+		// Start the child process. 
+		if( !CreateProcess( NULL, (CHAR*)client.c_str(), NULL, NULL,
+                            FALSE, 0, NULL, NULL, &sic, &pic )) 
+		{
+                    DWORD err = GetLastError();
+                    while (hcount--)
+                        TerminateProcess(handles[hcount], (DWORD)-1);
+		    throw win32_error("CreateProcess failed", err);
+		}
+		handles[hcount++] = pic.hProcess;
+	    }
+
+	    // Wait until any child process exits.
+	    DWORD ret = WaitForMultipleObjects(hcount, handles, FALSE, INFINITE );
+
+#ifdef _DEBUG
+	    printf("killing process!\n");
+#endif
+            // Check if Xming is still running
+	    DWORD exitcode;
+	    GetExitCodeProcess(pi.hProcess, &exitcode);
+	    unsigned counter = 0;
+	    while (exitcode == STILL_ACTIVE)
+	    {
+		if (++counter > 10)
+		    TerminateProcess(pi.hProcess, (DWORD)-1);
+		else
+		    // Shutdown Xming (the soft way!)
+		    EnumThreadWindows(pi.dwThreadId, KillWindowsProc, 0);
+		Sleep(500);
+		GetExitCodeProcess(pi.hProcess, &exitcode);
+	    }
+	    // Kill the client
+    	    TerminateProcess(pic.hProcess, (DWORD)-1);
+
+	    // Close process and thread handles. 
+	    CloseHandle( pi.hProcess );
+	    CloseHandle( pi.hThread );
+	    CloseHandle( pic.hProcess );
+	    CloseHandle( pic.hThread );
+	}
+};
+
+int main(int argc, char **argv)
+{
+    try {
+        InitCommonControls();
+        CMyWizard dialog;
+
+	bool skip_wizard = false;
+
+	for (int i = 1; i < argc; i++)
+	{
+	    if (argv[i] == NULL)
+		continue;
+	    
+	    std::string arg(argv[i]);
+	    if (arg == "-load" && i + 1 < argc)
+	    {
+		i++;
+		dialog.LoadConfig(argv[i]);
+		continue;
+	    }
+	    if (arg == "-run" && i + 1 < argc)
+	    {
+		i++;
+		dialog.LoadConfig(argv[i]);
+		skip_wizard = true;
+		continue;
+	    }
+	}
+
+	int ret = 0; 
+        if (skip_wizard || (ret =dialog.ShowModal()) != 0)
+	    dialog.StartUp();
+#ifdef _DEBUG
+	printf("return %d\n", ret);
+#endif
+	return 0;
+    } catch (std::runtime_error &e)
+    {
+        printf("Fehler: %s\n", e.what());
+        return -1;
+    }
+}
+
+
+
+
diff --git a/hw/xwin/xlaunch/resources/dialog.rc b/hw/xwin/xlaunch/resources/dialog.rc
new file mode 100755
index 0000000..8b00df4
--- /dev/null
+++ b/hw/xwin/xlaunch/resources/dialog.rc
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+#include <windows.h>
+#include "resources.h"
+
+#ifndef STR_CAPTION_DISPLAY
+#include "strings.rc"
+#endif
+
+IDD_DISPLAY DIALOGEX 0, 0, 317, 143
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_CENTERMOUSE
+CAPTION STR_CAPTION_DISPLAY
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+    AUTORADIOBUTTON STR_MULTIWINDOW,IDC_MULTIWINDOW,7,25,70,24,BS_MULTILINE|BS_TOP
+    AUTORADIOBUTTON STR_FULLSCREEN,IDC_FULLSCREEN,157,25,70,24,BS_MULTILINE|BS_TOP
+    AUTORADIOBUTTON STR_WINDOWED,IDC_WINDOWED,7,75,70,24,BS_MULTILINE|BS_TOP
+    AUTORADIOBUTTON STR_NODECORATION,IDC_NODECORATION,157,75,70,24,BS_MULTILINE|BS_TOP
+
+    CONTROL         "IMG_MULTIWINDOW",IDC_MULTIWINDOW_IMG,"Static",SS_BITMAP | SS_NOTIFY,80,10,0,0
+    CONTROL         "IMG_FULLSCREEN",IDC_FULLSCREEN_IMG,"Static",SS_BITMAP | SS_NOTIFY,230,10,0,0
+    CONTROL         "IMG_WINDOWED",IDC_WINDOWED_IMG,"Static",SS_BITMAP | SS_NOTIFY,80,60,0,0
+    CONTROL         "IMG_NODECORATION",IDC_NODECORATION_IMG,"Static",SS_BITMAP | SS_NOTIFY,230,60,0,0
+
+    LTEXT           STR_DISPLAY_DESC,IDC_DISPLAY_DESC,7,120,64,12
+    EDITTEXT        IDC_DISPLAY,80,118,67,12,ES_NUMBER
+END
+
+IDD_CLIENTS DIALOGEX 0, 0, 317, 143
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_CENTERMOUSE
+CAPTION STR_CAPTION_CLIENTS
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+    AUTORADIOBUTTON STR_CLIENT_NONE,IDC_CLIENT_NONE,7,14,300,10
+    AUTORADIOBUTTON STR_CLIENT,IDC_CLIENT,7,56,300,10
+    AUTORADIOBUTTON STR_XDMCP,IDC_XDMCP,7,98,300,10
+
+    LTEXT           STR_CLIENT_NONE_DESC,IDC_CLIENT_NONE_DESC,19,28,280,27
+    LTEXT           STR_CLIENT_DESC,IDC_CLIENT_DESC,19,70,280,27
+    LTEXT           STR_XDMCP_DESC,IDC_XDMCP_DESC,19,112,280,27
+END
+
+IDD_PROGRAM DIALOGEX 0, 0, 317, 143
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_CENTERMOUSE
+CAPTION STR_CAPTION_PROGRAM
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+    LTEXT           STR_CLIENT_PROGRAM_DESC,IDC_CLIENT_PROGRAM_DESC,7,14,64,10
+    COMBOBOX        IDC_CLIENT_PROGRAM,70,12,64,54,CBS_DROPDOWN | WS_VSCROLL
+
+    AUTORADIOBUTTON STR_CLIENT_LOCAL,IDC_CLIENT_LOCAL,7,28,300,10
+    AUTORADIOBUTTON STR_CLIENT_REMOTE,IDC_CLIENT_REMOTE,7,42,300,10
+    
+    LTEXT           STR_CLIENT_PROTOCOL_DESC,IDC_CLIENT_PROTOCOL_DESC,19,56,70,10
+    COMBOBOX        IDC_CLIENT_PROTOCOL,100,54,64,54,CBS_DROPDOWNLIST | WS_VSCROLL
+    
+    LTEXT           STR_CLIENT_HOST_DESC,IDC_CLIENT_HOST_DESC,19,70,70,10
+    LTEXT           STR_CLIENT_USER_DESC,IDC_CLIENT_USER_DESC,19,84,70,10
+    EDITTEXT        IDC_CLIENT_HOST,100,68,64,12
+    EDITTEXT        IDC_CLIENT_USER,100,82,64,12
+END
+
+IDD_XDMCP DIALOGEX 0, 0, 317, 143
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_CENTERMOUSE
+CAPTION STR_CAPTION_XDMCP
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+    AUTORADIOBUTTON STR_XDMCP_QUERY, IDC_XDMCP_QUERY,7,14,64,10
+    EDITTEXT        IDC_XDMCP_HOST,78,12,64,12
+    AUTOCHECKBOX    STR_XDMCP_INDIRECT,IDC_XDMCP_INDIRECT,19,28,280,10
+    AUTORADIOBUTTON STR_XDMCP_BROADCAST, IDC_XDMCP_BROADCAST,7,42,300,10
+    LTEXT           STR_XDMCP_QUERY_DESC,IDC_XDMCP_QUERY_DESC,7,56,300,42
+END
+
+IDD_CLIPBOARD DIALOGEX 0, 0, 317, 143
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_CENTERMOUSE
+CAPTION STR_CAPTION_CLIPBOARD
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+    AUTOCHECKBOX    STR_CLIPBOARD,IDC_CLIPBOARD,7,14,300,10
+    LTEXT           STR_CLIPBOARD_DESC,IDC_CLIPBOARD_DESC,19,28,280,27
+
+    LTEXT           STR_EXTRA_PARAMS_DESC,IDC_EXTRA_PARAMS_DESC,7,56,280,10
+    EDITTEXT        IDC_EXTRA_PARAMS,7,70,128,12
+END
+
+IDD_FINISH DIALOGEX 0, 0, 317, 143
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_CENTERMOUSE
+CAPTION STR_CAPTION_FINISH
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+    LTEXT           STR_FINISH_DESC,IDC_FINISH_DESC,7,14,300,28
+    LTEXT           STR_FINISH_SAVE_DESC,IDC_FINISH_SAVE_DESC,7,56,300,12
+    PUSHBUTTON      STR_FINISH_SAVE,IDC_FINISH_SAVE,7,68,75,14 
+END
diff --git a/hw/xwin/xlaunch/resources/fullscreen.bmp b/hw/xwin/xlaunch/resources/fullscreen.bmp
new file mode 100755
index 0000000..0d051f0
Binary files /dev/null and b/hw/xwin/xlaunch/resources/fullscreen.bmp differ
diff --git a/hw/xwin/xlaunch/resources/images.rc b/hw/xwin/xlaunch/resources/images.rc
new file mode 100755
index 0000000..2eac53c
--- /dev/null
+++ b/hw/xwin/xlaunch/resources/images.rc
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+IMG_MULTIWINDOW BITMAP "resources\\multiwindow.bmp"
+IMG_WINDOWED BITMAP "resources\\windowed.bmp"
+IMG_FULLSCREEN BITMAP "resources\\fullscreen.bmp"
+IMG_NODECORATION BITMAP "resources\\nodecoration.bmp"
diff --git a/hw/xwin/xlaunch/resources/multiwindow.bmp b/hw/xwin/xlaunch/resources/multiwindow.bmp
new file mode 100755
index 0000000..0755c87
Binary files /dev/null and b/hw/xwin/xlaunch/resources/multiwindow.bmp differ
diff --git a/hw/xwin/xlaunch/resources/nodecoration.bmp b/hw/xwin/xlaunch/resources/nodecoration.bmp
new file mode 100755
index 0000000..e9e1ce6
Binary files /dev/null and b/hw/xwin/xlaunch/resources/nodecoration.bmp differ
diff --git a/hw/xwin/xlaunch/resources/resources.h b/hw/xwin/xlaunch/resources/resources.h
new file mode 100755
index 0000000..4700051
--- /dev/null
+++ b/hw/xwin/xlaunch/resources/resources.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+
+#define IDC_STATIC -1
+
+#define IDD_WELCOME             100
+#define IDD_FINISH              101
+#define IDD_DISPLAY             102
+#define IDD_CLIENTS             103
+#define IDD_PROGRAM             104
+#define IDD_XDMCP               105
+#define IDD_FONTPATH            106
+#define IDD_CLIPBOARD           107
+
+#define IDS_DISPLAY_TITLE       300
+#define IDS_DISPLAY_SUBTITLE    301
+#define IDS_CLIENTS_TITLE       302
+#define IDS_CLIENTS_SUBTITLE    303
+#define IDS_PROGRAM_TITLE       304
+#define IDS_PROGRAM_SUBTITLE    305
+#define IDS_XDMCP_TITLE         306
+#define IDS_XDMCP_SUBTITLE      307
+#define IDS_FONTPATH_TITLE      308
+#define IDS_FONTPATH_SUBTITLE   309
+#define IDS_FINISH_TITLE        310
+#define IDS_FINISH_SUBTITLE     311
+#define IDS_CLIPBOARD_TITLE     312
+#define IDS_CLIPBOARD_SUBTITLE  313
+#define IDS_SAVE_TITLE          320
+#define IDS_SAVE_FILETITLE      321
+#define IDS_SAVE_FILTER         322
+                
+#define IDC_MULTIWINDOW         200
+#define IDC_WINDOWED            201
+#define IDC_FULLSCREEN          202
+#define IDC_NODECORATION        203
+#define IDC_MULTIWINDOW_IMG     204
+#define IDC_WINDOWED_IMG        205
+#define IDC_FULLSCREEN_IMG      206
+#define IDC_NODECORATION_IMG    207
+#define IDC_DISPLAY             208
+#define IDC_DISPLAY_DESC        209
+
+#define IDC_CLIENT_NONE         210
+#define IDC_XDMCP               211
+#define IDC_CLIENT              212
+#define IDC_CLIENT_LOCAL        213
+#define IDC_CLIENT_REMOTE       214
+#define IDC_CLIENT_HOST         215
+#define IDC_CLIENT_USER         216
+#define IDC_CLIENT_PROTOCOL     217
+#define IDC_CLIENT_CONFIGURE    218
+#define IDC_CLIENT_PROGRAM      219
+#define IDC_XDMCP_QUERY         220
+#define IDC_XDMCP_BROADCAST     221
+#define IDC_XDMCP_INDIRECT      222
+#define IDC_XDMCP_HOST          223
+#define IDC_CLIENT_NONE_DESC    224
+#define IDC_XDMCP_DESC          225
+#define IDC_CLIENT_DESC         226
+#define IDC_XDMCP_QUERY_DESC    227
+#define IDC_CLIENT_PROGRAM_DESC 228
+#define IDC_CLIENT_HOST_DESC    229
+#define IDC_CLIENT_USER_DESC    230
+#define IDC_CLIENT_PROTOCOL_DESC 231
+
+#define IDC_FONTPATH_DESC        240
+
+#define IDC_FINISH_DESC		 250
+#define IDC_FINISH_SAVE		 251
+#define IDC_FINISH_SAVE_DESC     252
+
+#define IDC_CLIPBOARD            260
+#define IDC_CLIPBOARD_DESC       261
+#define IDC_EXTRA_PARAMS         262
+#define IDC_EXTRA_PARAMS_DESC    263
diff --git a/hw/xwin/xlaunch/resources/resources.rc b/hw/xwin/xlaunch/resources/resources.rc
new file mode 100755
index 0000000..07fd52f
--- /dev/null
+++ b/hw/xwin/xlaunch/resources/resources.rc
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+#include <windows.h>
+
+#include "resources.h"
+#include "images.rc"
+#include "dialog.rc"
diff --git a/hw/xwin/xlaunch/resources/strings.rc b/hw/xwin/xlaunch/resources/strings.rc
new file mode 100644
index 0000000..5a9cd28
--- /dev/null
+++ b/hw/xwin/xlaunch/resources/strings.rc
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+
+#define STR_CAPTION_DISPLAY         "Display settings"
+#define STR_MULTIWINDOW             "Multiple windows"
+#define STR_FULLSCREEN              "Fullscreen"
+#define STR_WINDOWED                "One large window"
+#define STR_NODECORATION            "One window without titlebar"
+#define STR_DISPLAY_DESC            "Display number"
+
+#define STR_CAPTION_CLIENTS         "Client startup"
+#define STR_CLIENT_NONE             "Start no client"
+#define STR_CLIENT_NONE_DESC		"This will just start the xserver. You will be able to start local clients later."
+#define STR_CLIENT					"Start a program"
+#define STR_CLIENT_DESC				"This will start a local or remote program which will connect to the xserver. You will be able to start local clients later too. Remote programs are started using SSH."
+#define STR_XDMCP					"Open session via XDMCP"
+#define STR_XDMCP_DESC				"This will start a remote XDMCP session. Starting local clients later is limited. This option is not available with the ""Multiple windows"" mode."
+
+#define STR_CAPTION_PROGRAM         "Start program"
+#define STR_CLIENT_PROGRAM_DESC     "Start program"
+#define STR_CLIENT_LOCAL            "Start program on this computer"
+#define STR_CLIENT_REMOTE           "Start program on remote computer"
+#define STR_CLIENT_PROTOCOL_DESC    "Connect using"
+#define STR_CLIENT_HOST_DESC        "Connect to computer"
+#define STR_CLIENT_USER_DESC        "Login as user"
+
+
+#define STR_CAPTION_XDMCP           "XDMCP settings"
+#define STR_XDMCP_QUERY             "Connect to host"
+#define STR_XDMCP_INDIRECT          "Use indirect connect"
+#define STR_XDMCP_BROADCAST         "Search for hosts (broadcast)"
+#define STR_XDMCP_QUERY_DESC        "Some XDMCP servers must be configured to allow remote connections. Please check the documentation about configuring XDMCP servers."
+
+
+#define STR_CAPTION_FONTPATH        "Fontpath settings"
+
+#define STR_CAPTION_CLIPBOARD       "Clipboard settings"
+#define STR_CLIPBOARD               "Clipboard"
+#define STR_CLIPBOARD_DESC          "Start the integrated clipboard manager"
+#define STR_EXTRA_PARAMS_DESC       "Additional parameters for Xming"
+
+#define STR_CAPTION_FINISH          "Finish configuration"
+#define STR_FINISH_DESC	            "Configuration is complete. Clish Finish to start Xming."
+#define STR_FINISH_SAVE_DESC        "You may also save the configuration for later use."
+#define STR_FINISH_SAVE	            "Save configuration"
+
+#define STR_DISPLAY_TITLE           "Select display settings"
+#define STR_DISPLAY_SUBTITLE        "Choose how Xming display programs"
+#define STR_CLIENTS_TITLE           "Select how to start clients"
+#define STR_CLIENTS_SUBTITLE        ""
+#define STR_PROGRAM_TITLE           "Specify the program to start"
+#define STR_PROGRAM_SUBTITLE        ""
+#define STR_XDMCP_TITLE             "Configure a remote XDMCP connection"
+#define STR_XDMCP_SUBTITLE          ""
+#define STR_FONTPATH_TITLE          "Define font locations"
+#define STR_FONTPATH_SUBTITLE       ""
+#define STR_FINISH_TITLE            "Configuration complete"
+#define STR_FINISH_SUBTITLE         ""
+#define STR_CLIPBOARD_TITLE         "Clipboard settings"
+#define STR_CLIPBOARD_SUBTITLE      ""
+
+#define STR_SAVE_TITLE              "Save configuration"
+#define STR_SAVE_FILETITLE          "Filename"
+#define STR_SAVE_FILTER             "Xlaunch Files (*.xlaunch)%*.xlaunch%%"
+
+STRINGTABLE
+BEGIN
+    IDS_DISPLAY_TITLE       STR_DISPLAY_TITLE       
+    IDS_DISPLAY_SUBTITLE    STR_DISPLAY_SUBTITLE    
+    IDS_CLIENTS_TITLE       STR_CLIENTS_TITLE       
+    IDS_CLIENTS_SUBTITLE    STR_CLIENTS_SUBTITLE    
+    IDS_PROGRAM_TITLE       STR_PROGRAM_TITLE       
+    IDS_PROGRAM_SUBTITLE    STR_PROGRAM_SUBTITLE    
+    IDS_XDMCP_TITLE         STR_XDMCP_TITLE         
+    IDS_XDMCP_SUBTITLE      STR_XDMCP_SUBTITLE      
+    IDS_FONTPATH_TITLE      STR_FONTPATH_TITLE      
+    IDS_FONTPATH_SUBTITLE   STR_FONTPATH_SUBTITLE   
+    IDS_FINISH_TITLE        STR_FINISH_TITLE      
+    IDS_FINISH_SUBTITLE     STR_FINISH_SUBTITLE   
+    IDS_CLIPBOARD_TITLE     STR_CLIPBOARD_TITLE      
+    IDS_CLIPBOARD_SUBTITLE  STR_CLIPBOARD_SUBTITLE   
+    IDS_SAVE_TITLE	    STR_SAVE_TITLE
+    IDS_SAVE_FILETITLE      STR_SAVE_FILETITLE
+    IDS_SAVE_FILTER         STR_SAVE_FILTER
+END
diff --git a/hw/xwin/xlaunch/resources/windowed.bmp b/hw/xwin/xlaunch/resources/windowed.bmp
new file mode 100755
index 0000000..9eff2bf
Binary files /dev/null and b/hw/xwin/xlaunch/resources/windowed.bmp differ
diff --git a/hw/xwin/xlaunch/window/dialog.cc b/hw/xwin/xlaunch/window/dialog.cc
new file mode 100755
index 0000000..76e5c35
--- /dev/null
+++ b/hw/xwin/xlaunch/window/dialog.cc
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+#include <stdio.h>
+#include "dialog.h"
+#include "util.h"
+
+CBaseDialog::CBaseDialog() : CWindow(""), result(0)
+{
+}
+
+CDialog::CDialog(const char *res) : CBaseDialog(), resourcename(res) 
+{
+}
+
+HWND CDialog::CreateWindowHandle()
+{
+    HWND ret = CreateDialog(
+            GetModuleHandle(NULL),
+            resourcename.c_str(),
+            NULL,
+            DialogProc);
+    if (ret == NULL)
+        throw win32_error("CreateDialog failed");
+    return ret;
+}
+
+INT_PTR CALLBACK CBaseDialog::DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+    MessageDebug::debug(hwndDlg, uMsg, wParam, lParam, __FUNCTION__);
+	CBaseDialog* dialog = (CDialog*)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+	if (dialog != NULL)
+	    return dialog->DlgDispatch(hwndDlg, uMsg, wParam, lParam);
+    return FALSE;
+}
+
+INT_PTR CBaseDialog::DlgDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+    switch (uMsg)
+    {
+        case WM_COMMAND:
+            switch (LOWORD(wParam))
+            {
+                case IDOK:
+                case IDCANCEL:
+                    result = wParam;
+                    EndDialog(hwndDlg, wParam);
+                    DestroyWindow(hwndDlg);
+                    return TRUE;
+            }
+            break;
+    }
+    return FALSE;
+}
+
+INT_PTR CDialog::DlgDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+    return CBaseDialog::DlgDispatch(hwndDlg, uMsg, wParam, lParam);
+}
+
+int CBaseDialog::Execute()
+{
+    return CWindow::ShowModal();
+}
diff --git a/hw/xwin/xlaunch/window/dialog.h b/hw/xwin/xlaunch/window/dialog.h
new file mode 100755
index 0000000..073394b
--- /dev/null
+++ b/hw/xwin/xlaunch/window/dialog.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+#ifndef __DIALOG_H__
+#define __DIALOG_H__
+
+#include "window.h"
+class CBaseDialog : public CWindow
+{
+    private:
+        int result;
+    protected:
+        static INT_PTR CALLBACK DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
+        virtual INT_PTR DlgDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
+    public:
+        CBaseDialog();
+        int Execute();
+};
+
+class CDialog : public CBaseDialog
+{
+    private:
+        std::string resourcename;
+    protected:
+        virtual INT_PTR DlgDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
+        virtual HWND CreateWindowHandle();
+    public:
+        CDialog(const char *res);
+};
+
+
+#endif
diff --git a/hw/xwin/xlaunch/window/util.cc b/hw/xwin/xlaunch/window/util.cc
new file mode 100644
index 0000000..fb7e872
--- /dev/null
+++ b/hw/xwin/xlaunch/window/util.cc
@@ -0,0 +1,1112 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+#include "util.h"
+
+std::string win32_error::message(DWORD errorcode)
+{
+    LPVOID lpMsgBuf;
+    if (!FormatMessage( 
+                FORMAT_MESSAGE_ALLOCATE_BUFFER | 
+                FORMAT_MESSAGE_FROM_SYSTEM | 
+                FORMAT_MESSAGE_IGNORE_INSERTS,
+                NULL,
+                errorcode,
+                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
+                (LPTSTR) &lpMsgBuf,
+                0,
+                NULL ))
+    {
+        return "Unknown error in FormatMessage";
+    }
+
+    std::string ret((LPCTSTR)lpMsgBuf);
+    LocalFree( lpMsgBuf );
+    return ret;
+}
+
+void MessageDebug::debug(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, const char *prefix)
+{
+#ifdef _DEBUG
+    static const char *psn_notify[] = {
+        "PSN_SETACTIVE",
+        "PSN_KILLACTIVE",
+        "PSN_APPLY",
+        "PSN_RESET",
+        NULL,
+        "PSN_HELP",
+        "PSN_WIZBACK",
+        "PSN_WIZNEXT",
+        "PSN_WIZFINISH",
+        "PSN_QUERYCANCEL" };
+    if (uMsg == WM_NOTIFY)
+    {
+        LPNMHDR pnmh = (LPNMHDR)lParam;
+        int psn_index = -(int)pnmh->code - 200;
+        if (psn_index >= 0 && psn_index < 10 && psn_notify[psn_index])
+            printf("%s: %08x %04x WM_NOTIFY (%s)\n", prefix, hwnd, wParam, psn_notify[psn_index]);
+        else if (pnmh->code < NOTIFY_NAMES_LEN && notify_names[pnmh->code])
+            printf("%s: %08x %04x WM_NOTIFY (%s)\n", prefix, hwnd, wParam, notify_names[pnmh->code]);
+        else
+            printf("%s: %08x %04x WM_NOTIFY (%u)\n", prefix, hwnd, wParam, pnmh->code);
+    }   
+    else if (uMsg >= MESSAGE_NAMES_LEN)
+        if (uMsg >= WM_USER)
+            printf("%s: %08x %04x %08x WM_USER + %d\n", prefix, hwnd, wParam, lParam, uMsg - WM_USER); 
+        else
+            printf("%s: %08x %04x %08x %d\n", prefix, hwnd, wParam, lParam, uMsg);
+    else if (uMsg >= 0 && uMsg < MESSAGE_NAMES_LEN && message_names[uMsg])
+        printf("%s: %08x %04x %08x %s\n", prefix, hwnd, wParam, lParam, message_names[uMsg]);
+#endif
+}
+
+
+const char * MessageDebug::message_names[MESSAGE_NAMES_LEN] = {
+	"WM_NULL",
+	"WM_CREATE",
+	"WM_DESTROY",
+	"WM_MOVE",
+	"4",
+	"WM_SIZE",
+	"WM_ACTIVATE",
+	"WM_SETFOCUS",
+	"WM_KILLFOCUS",
+	"9",
+	"WM_ENABLE",
+	"WM_SETREDRAW",
+	"WM_SETTEXT",
+	"WM_GETTEXT",
+	"WM_GETTEXTLENGTH",
+	"WM_PAINT",
+	"WM_CLOSE",
+	"WM_QUERYENDSESSION",
+	"WM_QUIT",
+	"WM_QUERYOPEN",
+	"WM_ERASEBKGND",
+	"WM_SYSCOLORCHANGE",
+	"WM_ENDSESSION",
+	"23",
+	"WM_SHOWWINDOW",
+	"25",
+	"WM_WININICHANGE",
+	"WM_DEVMODECHANGE",
+	"WM_ACTIVATEAPP",
+	"WM_FONTCHANGE",
+	"WM_TIMECHANGE",
+	"WM_CANCELMODE",
+	NULL /* WM_SETCURSOR */,
+	"WM_MOUSEACTIVATE",
+	"WM_CHILDACTIVATE",
+	"WM_QUEUESYNC",
+	"WM_GETMINMAXINFO",
+	"37",
+	"WM_PAINTICON",
+	"WM_ICONERASEBKGND",
+	"WM_NEXTDLGCTL",
+	"41",
+	"WM_SPOOLERSTATUS",
+	"WM_DRAWITEM",
+	"WM_MEASUREITEM",
+	"WM_DELETEITEM",
+	"WM_VKEYTOITEM",
+	"WM_CHARTOITEM",
+	"WM_SETFONT",
+	"WM_GETFONT",
+	"WM_SETHOTKEY",
+	"WM_GETHOTKEY",
+	"52",
+	"53",
+	"54",
+	"WM_QUERYDRAGICON",
+	"56",
+	"WM_COMPAREITEM",
+	"58",
+	"59",
+	"60",
+	"61",
+	"62",
+	"63",
+	"64",
+	"WM_COMPACTING",
+	"66",
+	"67",
+	"WM_COMMNOTIFY",
+	"69",
+	"WM_WINDOWPOSCHANGING",
+	"WM_WINDOWPOSCHANGED",
+	"WM_POWER",
+	"73",
+	"WM_COPYDATA",
+	"WM_CANCELJOURNAL",
+	"76",
+	"77",
+	"WM_NOTIFY",
+	"79",
+	"WM_INPUTLANGCHANGEREQUEST",
+	"WM_INPUTLANGCHANGE",
+	"WM_TCARD",
+	"WM_HELP",
+	"WM_USERCHANGED",
+	"WM_NOTIFYFORMAT",
+	"86",
+	"87",
+	"88",
+	"89",
+	"90",
+	"91",
+	"92",
+	"93",
+	"94",
+	"95",
+	"96",
+	"97",
+	"98",
+	"99",
+	"100",
+	"101",
+	"102",
+	"103",
+	"104",
+	"105",
+	"106",
+	"107",
+	"108",
+	"109",
+	"110",
+	"111",
+	"112",
+	"113",
+	"114",
+	"115",
+	"116",
+	"117",
+	"118",
+	"119",
+	"120",
+	"121",
+	"122",
+	"WM_CONTEXTMENU",
+	"WM_STYLECHANGING",
+	"WM_STYLECHANGED",
+	"WM_DISPLAYCHANGE",
+	"WM_GETICON",
+	"WM_SETICON",
+	"WM_NCCREATE",
+	"WM_NCDESTROY",
+	"WM_NCCALCSIZE",
+	NULL /* WM_NCHITTEST */,
+	"WM_NCPAINT",
+	"WM_NCACTIVATE",
+	"WM_GETDLGCODE",
+	"WM_SYNCPAINT",
+	"137",
+	"138",
+	"139",
+	"140",
+	"141",
+	"142",
+	"143",
+	"144",
+	"145",
+	"146",
+	"147",
+	"148",
+	"149",
+	"150",
+	"151",
+	"152",
+	"153",
+	"154",
+	"155",
+	"156",
+	"157",
+	"158",
+	"159",
+	NULL /* WM_NCMOUSEMOVE */,
+	"WM_NCLBUTTONDOWN",
+	"WM_NCLBUTTONUP",
+	"WM_NCLBUTTONDBLCLK",
+	"WM_NCRBUTTONDOWN",
+	"WM_NCRBUTTONUP",
+	"WM_NCRBUTTONDBLCLK",
+	"WM_NCMBUTTONDOWN",
+	"WM_NCMBUTTONUP",
+	"WM_NCMBUTTONDBLCLK",
+	"170",
+	"171",
+	"172",
+	"173",
+	"174",
+	"175",
+	"176",
+	"177",
+	"178",
+	"179",
+	"180",
+	"181",
+	"182",
+	"183",
+	"184",
+	"185",
+	"186",
+	"187",
+	"188",
+	"189",
+	"190",
+	"191",
+	"192",
+	"193",
+	"194",
+	"195",
+	"196",
+	"197",
+	"198",
+	"199",
+	"200",
+	"201",
+	"202",
+	"203",
+	"204",
+	"205",
+	"206",
+	"207",
+	"208",
+	"209",
+	"210",
+	"211",
+	"212",
+	"213",
+	"214",
+	"215",
+	"216",
+	"217",
+	"218",
+	"219",
+	"220",
+	"221",
+	"222",
+	"223",
+	"224",
+	"225",
+	"226",
+	"227",
+	"228",
+	"229",
+	"230",
+	"231",
+	"232",
+	"233",
+	"234",
+	"235",
+	"236",
+	"237",
+	"238",
+	"239",
+	"240",
+	"241",
+	"242",
+	"243",
+	"244",
+	"245",
+	"246",
+	"247",
+	"248",
+	"249",
+	"250",
+	"251",
+	"252",
+	"253",
+	"254",
+	"255",
+	"WM_KEYDOWN",
+	"WM_KEYUP",
+	"WM_CHAR",
+	"WM_DEADCHAR",
+	"WM_SYSKEYDOWN",
+	"WM_SYSKEYUP",
+	"WM_SYSCHAR",
+	"WM_SYSDEADCHAR",
+	"WM_CONVERTREQUESTEX",
+	"265",
+	"266",
+	"267",
+	"268",
+	"WM_IME_STARTCOMPOSITION",
+	"WM_IME_ENDCOMPOSITION",
+	"WM_IME_KEYLAST",
+	"WM_INITDIALOG",
+	"WM_COMMAND",
+	"WM_SYSCOMMAND",
+	NULL /* WM_TIMER */,
+	"WM_HSCROLL",
+	"WM_VSCROLL",
+	"WM_INITMENU",
+	"WM_INITMENUPOPUP",
+	"280",
+	"281",
+	"282",
+	"283",
+	"284",
+	"285",
+	"286",
+	"WM_MENUSELECT",
+	"WM_MENUCHAR",
+	"WM_ENTERIDLE",
+	"290",
+	"291",
+	"292",
+	"293",
+	"294",
+	"295",
+	"296",
+	"297",
+	"298",
+	"299",
+	"300",
+	"301",
+	"302",
+	"303",
+	"304",
+	"305",
+	"WM_CTLCOLORMSGBOX",
+	"WM_CTLCOLOREDIT",
+	"WM_CTLCOLORLISTBOX",
+	"WM_CTLCOLORBTN",
+	"WM_CTLCOLORDLG",
+	"WM_CTLCOLORSCROLLBAR",
+	"WM_CTLCOLORSTATIC",
+	"313",
+	"314",
+	"315",
+	"316",
+	"317",
+	"318",
+	"319",
+	"320",
+	"321",
+	"322",
+	"323",
+	"324",
+	"325",
+	"326",
+	"327",
+	"328",
+	"329",
+	"330",
+	"331",
+	"332",
+	"333",
+	"334",
+	"335",
+	"336",
+	"337",
+	"338",
+	"339",
+	"340",
+	"341",
+	"342",
+	"343",
+	"344",
+	"345",
+	"346",
+	"347",
+	"348",
+	"349",
+	"350",
+	"351",
+	"352",
+	"353",
+	"354",
+	"355",
+	"356",
+	"357",
+	"358",
+	"359",
+	"360",
+	"361",
+	"362",
+	"363",
+	"364",
+	"365",
+	"366",
+	"367",
+	"368",
+	"369",
+	"370",
+	"371",
+	"372",
+	"373",
+	"374",
+	"375",
+	"376",
+	"377",
+	"378",
+	"379",
+	"380",
+	"381",
+	"382",
+	"383",
+	"384",
+	"385",
+	"386",
+	"387",
+	"388",
+	"389",
+	"390",
+	"391",
+	"392",
+	"393",
+	"394",
+	"395",
+	"396",
+	"397",
+	"398",
+	"399",
+	"400",
+	"401",
+	"402",
+	"403",
+	"404",
+	"405",
+	"406",
+	"407",
+	"408",
+	"409",
+	"410",
+	"411",
+	"412",
+	"413",
+	"414",
+	"415",
+	"416",
+	"417",
+	"418",
+	"419",
+	"420",
+	"421",
+	"422",
+	"423",
+	"424",
+	"425",
+	"426",
+	"427",
+	"428",
+	"429",
+	"430",
+	"431",
+	"432",
+	"433",
+	"434",
+	"435",
+	"436",
+	"437",
+	"438",
+	"439",
+	"440",
+	"441",
+	"442",
+	"443",
+	"444",
+	"445",
+	"446",
+	"447",
+	"448",
+	"449",
+	"450",
+	"451",
+	"452",
+	"453",
+	"454",
+	"455",
+	"456",
+	"457",
+	"458",
+	"459",
+	"460",
+	"461",
+	"462",
+	"463",
+	"464",
+	"465",
+	"466",
+	"467",
+	"468",
+	"469",
+	"470",
+	"471",
+	"472",
+	"473",
+	"474",
+	"475",
+	"476",
+	"477",
+	"478",
+	"479",
+	"480",
+	"481",
+	"482",
+	"483",
+	"484",
+	"485",
+	"486",
+	"487",
+	"488",
+	"489",
+	"490",
+	"491",
+	"492",
+	"493",
+	"494",
+	"495",
+	"496",
+	"497",
+	"498",
+	"499",
+	"500",
+	"501",
+	"502",
+	"503",
+	"504",
+	"505",
+	"506",
+	"507",
+	"508",
+	"509",
+	"510",
+	"511",
+	NULL /* WM_MOUSEMOVE */,
+	"WM_LBUTTONDOWN",
+	"WM_LBUTTONUP",
+	"WM_LBUTTONDBLCLK",
+	"WM_RBUTTONDOWN",
+	"WM_RBUTTONUP",
+	"WM_RBUTTONDBLCLK",
+	"WM_MBUTTONDOWN",
+	"WM_MBUTTONUP",
+	"WM_MBUTTONDBLCLK",
+	"WM_MOUSEWHEEL",
+	"WM_XBUTTONDOWN",
+	"WM_XBUTTONUP",
+	"WM_XBUTTONDBLCLK",
+	"526",
+	"527",
+	"WM_PARENTNOTIFY",
+	"WM_ENTERMENULOOP",
+	"WM_EXITMENULOOP",
+	"WM_NEXTMENU",
+	"WM_SIZING",
+	"WM_CAPTURECHANGED",
+	"WM_MOVING",
+	"535",
+	"WM_POWERBROADCAST",
+	"WM_DEVICECHANGE",
+	"538",
+	"539",
+	"540",
+	"541",
+	"542",
+	"543",
+	"WM_MDICREATE",
+	"WM_MDIDESTROY",
+	"WM_MDIACTIVATE",
+	"WM_MDIRESTORE",
+	"WM_MDINEXT",
+	"WM_MDIMAXIMIZE",
+	"WM_MDITILE",
+	"WM_MDICASCADE",
+	"WM_MDIICONARRANGE",
+	"WM_MDIGETACTIVE",
+	"554",
+	"555",
+	"556",
+	"557",
+	"558",
+	"559",
+	"WM_MDISETMENU",
+	"WM_ENTERSIZEMOVE",
+	"WM_EXITSIZEMOVE",
+	"WM_DROPFILES",
+	"WM_MDIREFRESHMENU",
+	"565",
+	"566",
+	"567",
+	"568",
+	"569",
+	"570",
+	"571",
+	"572",
+	"573",
+	"574",
+	"575",
+	"576",
+	"577",
+	"578",
+	"579",
+	"580",
+	"581",
+	"582",
+	"583",
+	"584",
+	"585",
+	"586",
+	"587",
+	"588",
+	"589",
+	"590",
+	"591",
+	"592",
+	"593",
+	"594",
+	"595",
+	"596",
+	"597",
+	"598",
+	"599",
+	"600",
+	"601",
+	"602",
+	"603",
+	"604",
+	"605",
+	"606",
+	"607",
+	"608",
+	"609",
+	"610",
+	"611",
+	"612",
+	"613",
+	"614",
+	"615",
+	"616",
+	"617",
+	"618",
+	"619",
+	"620",
+	"621",
+	"622",
+	"623",
+	"624",
+	"625",
+	"626",
+	"627",
+	"628",
+	"629",
+	"630",
+	"631",
+	"632",
+	"633",
+	"634",
+	"635",
+	"636",
+	"637",
+	"638",
+	"639",
+	"640",
+	"WM_IME_SETCONTEXT",
+	"WM_IME_NOTIFY",
+	"WM_IME_CONTROL",
+	"WM_IME_COMPOSITIONFULL",
+	"WM_IME_SELECT",
+	"WM_IME_CHAR",
+	"647",
+	"648",
+	"649",
+	"650",
+	"651",
+	"652",
+	"653",
+	"654",
+	"655",
+	"WM_IME_KEYDOWN",
+	"WM_IME_KEYUP",
+	"658",
+	"659",
+	"660",
+	"661",
+	"662",
+	"663",
+	"664",
+	"665",
+	"666",
+	"667",
+	"668",
+	"669",
+	"670",
+	"671",
+	"672",
+	"WM_MOUSEHOVER",
+	"674",
+	"WM_MOUSELEAVE",
+	"676",
+	"677",
+	"678",
+	"679",
+	"680",
+	"681",
+	"682",
+	"683",
+	"684",
+	"685",
+	"686",
+	"687",
+	"688",
+	"689",
+	"690",
+	"691",
+	"692",
+	"693",
+	"694",
+	"695",
+	"696",
+	"697",
+	"698",
+	"699",
+	"700",
+	"701",
+	"702",
+	"703",
+	"704",
+	"705",
+	"706",
+	"707",
+	"708",
+	"709",
+	"710",
+	"711",
+	"712",
+	"713",
+	"714",
+	"715",
+	"716",
+	"717",
+	"718",
+	"719",
+	"720",
+	"721",
+	"722",
+	"723",
+	"724",
+	"725",
+	"726",
+	"727",
+	"728",
+	"729",
+	"730",
+	"731",
+	"732",
+	"733",
+	"734",
+	"735",
+	"736",
+	"737",
+	"738",
+	"739",
+	"740",
+	"741",
+	"742",
+	"743",
+	"744",
+	"745",
+	"746",
+	"747",
+	"748",
+	"749",
+	"750",
+	"751",
+	"752",
+	"753",
+	"754",
+	"755",
+	"756",
+	"757",
+	"758",
+	"759",
+	"760",
+	"761",
+	"762",
+	"763",
+	"764",
+	"765",
+	"766",
+	"767",
+	"WM_CUT",
+	"WM_COPY",
+	"WM_PASTE",
+	"WM_CLEAR",
+	"WM_UNDO",
+	"WM_RENDERFORMAT",
+	"WM_RENDERALLFORMATS",
+	"WM_DESTROYCLIPBOARD",
+	"WM_DRAWCLIPBOARD",
+	"WM_PAINTCLIPBOARD",
+	"WM_VSCROLLCLIPBOARD",
+	"WM_SIZECLIPBOARD",
+	"WM_ASKCBFORMATNAME",
+	"WM_CHANGECBCHAIN",
+	"WM_HSCROLLCLIPBOARD",
+	"WM_QUERYNEWPALETTE",
+	"WM_PALETTEISCHANGING",
+	"WM_PALETTECHANGED",
+	"WM_HOTKEY",
+	"787",
+	"788",
+	"789",
+	"790",
+	"WM_PRINT",
+	"WM_PRINTCLIENT",
+	"793",
+	"794",
+	"795",
+	"796",
+	"797",
+	"798",
+	"799",
+	"800",
+	"801",
+	"802",
+	"803",
+	"804",
+	"805",
+	"806",
+	"807",
+	"808",
+	"809",
+	"810",
+	"811",
+	"812",
+	"813",
+	"814",
+	"815",
+	"816",
+	"817",
+	"818",
+	"819",
+	"820",
+	"821",
+	"822",
+	"823",
+	"824",
+	"825",
+	"826",
+	"827",
+	"828",
+	"829",
+	"830",
+	"831",
+	"832",
+	"833",
+	"834",
+	"835",
+	"836",
+	"837",
+	"838",
+	"839",
+	"840",
+	"841",
+	"842",
+	"843",
+	"844",
+	"845",
+	"846",
+	"847",
+	"848",
+	"849",
+	"850",
+	"851",
+	"852",
+	"853",
+	"854",
+	"855",
+	"856",
+	"857",
+	"858",
+	"859",
+	"860",
+	"861",
+	"862",
+	"863",
+	"864",
+	"865",
+	"866",
+	"867",
+	"868",
+	"869",
+	"870",
+	"871",
+	"872",
+	"873",
+	"874",
+	"875",
+	"876",
+	"877",
+	"878",
+	"879",
+	"880",
+	"881",
+	"882",
+	"883",
+	"884",
+	"885",
+	"886",
+	"887",
+	"888",
+	"889",
+	"890",
+	"891",
+	"892",
+	"893",
+	"894",
+	"895",
+	"896",
+	"897",
+	"898",
+	"899",
+	"900",
+	"901",
+	"902",
+	"903",
+	"904",
+	"905",
+	"906",
+	"907",
+	"908",
+	"909",
+	"910",
+	"911",
+	"912",
+	"913",
+	"914",
+	"915",
+	"916",
+	"917",
+	"918",
+	"919",
+	"920",
+	"921",
+	"922",
+	"923",
+	"924",
+	"925",
+	"926",
+	"927",
+	"928",
+	"929",
+	"930",
+	"931",
+	"932",
+	"933",
+	"934",
+	"935",
+	"936",
+	"937",
+	"938",
+	"939",
+	"940",
+	"941",
+	"942",
+	"943",
+	"944",
+	"945",
+	"946",
+	"947",
+	"948",
+	"949",
+	"950",
+	"951",
+	"952",
+	"953",
+	"954",
+	"955",
+	"956",
+	"957",
+	"958",
+	"959",
+	"960",
+	"961",
+	"962",
+	"963",
+	"964",
+	"965",
+	"966",
+	"967",
+	"968",
+	"969",
+	"970",
+	"971",
+	"972",
+	"973",
+	"974",
+	"975",
+	"976",
+	"977",
+	"978",
+	"979",
+	"980",
+	"981",
+	"982",
+	"983",
+	"984",
+	"985",
+	"986",
+	"987",
+	"988",
+	"989",
+	"990",
+	"991",
+	"992",
+	"993",
+	"994",
+	"995",
+	"996",
+	"997",
+	"998",
+	"999",
+	"1000",
+	"1001",
+	"1002",
+	"1003",
+	"1004",
+	"1005",
+	"1006",
+	"1007",
+	"1008",
+	"1009",
+	"1010",
+	"1011",
+	"1012",
+	"1013",
+	"1014",
+	"1015",
+	"1016",
+	"1017",
+	"1018",
+	"1019",
+	"1020",
+	"1021",
+	"1022",
+	"1023"
+};
+
diff --git a/hw/xwin/xlaunch/window/util.h b/hw/xwin/xlaunch/window/util.h
new file mode 100644
index 0000000..cd21da6
--- /dev/null
+++ b/hw/xwin/xlaunch/window/util.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+#ifndef __UTIL_H__
+#define __UTIL_H__
+
+#include <windows.h>
+#include <stdexcept>
+
+
+class win32_error : public std::runtime_error
+{
+    public:
+        static std::string message(DWORD code);
+        DWORD errorcode;
+        win32_error(const std::string &msg,DWORD code = GetLastError()) : std::runtime_error(msg + ":" + message(code)), errorcode(code) {};
+};
+
+#define MESSAGE_NAMES_LEN 1024
+#define NOTIFY_NAMES_LEN 0
+class MessageDebug
+{
+    protected:
+        static const char * message_names[MESSAGE_NAMES_LEN];
+        static const char * notify_names[NOTIFY_NAMES_LEN];
+    public:
+        static void debug(HWND handle, UINT uMsg, WPARAM wParam, LPARAM lParam, const char *prefix);
+};
+
+
+#endif
diff --git a/hw/xwin/xlaunch/window/window.cc b/hw/xwin/xlaunch/window/window.cc
new file mode 100755
index 0000000..cca3a48
--- /dev/null
+++ b/hw/xwin/xlaunch/window/window.cc
@@ -0,0 +1,284 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+
+#include "window.h"
+#include "util.h"
+#include <stdio.h>
+#include <stdexcept>
+
+CWindow::CWindowClass CWindow::windowClass("CWINDOWCLASS", DefWindowProc);
+
+CWindow::CWindowClass::CWindowClass(const char *_name, WNDPROC _wndproc) : 
+    wndproc(_wndproc), atom(0), classname(_name)
+{
+    Register();
+}
+
+CWindow::CWindowClass::~CWindowClass()
+{
+    UnregisterClass(classname.c_str(), GetModuleHandle(NULL));
+}
+
+void CWindow::CWindowClass::Register()
+{
+    WNDCLASSEX wndclass;
+    memset(&wndclass, 0, sizeof(wndclass));
+    wndclass.cbSize = sizeof(wndclass);
+    wndclass.style = 0;
+    wndclass.lpfnWndProc = wndproc;
+    wndclass.cbClsExtra = 0;
+    wndclass.cbWndExtra = 0;
+    wndclass.hInstance = GetModuleHandle(NULL); 
+    wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
+    wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
+    wndclass.hbrBackground = (HBRUSH)(1 + COLOR_BTNFACE);
+    wndclass.lpszMenuName = NULL;
+    wndclass.lpszClassName = classname.c_str();
+    wndclass.hIconSm = NULL;
+    atom = RegisterClassEx(&wndclass);
+    if (atom == 0)
+        throw win32_error("RegisterClassEx failed");
+}
+
+CWindow::CWindow(const char *_title) : title(_title), hwnd(NULL), parent(NULL), bounds(), owndproc(NULL), showing(FALSE)
+{
+    style = WS_CHILD;
+    exstyle = 0;
+}
+
+HWND CWindow::CreateWindowHandle()
+{
+    HWND ret = CreateWindowEx(
+            exstyle,
+            GetClassName(),
+            title.c_str(),
+            style,
+            bounds.left,
+            bounds.top,
+            bounds.width,
+            bounds.height,
+            parent,
+            NULL,
+            GetModuleHandle(NULL),
+            0
+            );
+    if (ret == NULL)
+        throw win32_error("CreateWindowEx failed");
+    return ret;
+}
+
+void CWindow::Create()
+{
+    if (hwnd != NULL)
+        return;
+    hwnd = CreateWindowHandle();
+    if (hwnd == NULL)
+        throw win32_error("Could not create window");
+
+    // Reset the error code
+    DWORD err = 0;
+    SetLastError(err);
+    
+    // Attach the object reference to the window handle
+    SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)this);
+    err = GetLastError();
+    if (err != 0)
+        throw win32_error("SetWindowLongPtr failed",err);
+    
+    // Set the window proc
+    owndproc = (WNDPROC)SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)WindowProc);
+    err = GetLastError();
+    if (err != 0)
+        throw win32_error("SetWindowLongPtr failed",err);
+}
+
+const char *CWindow::GetClassName()
+{
+    return windowClass.GetClassName();
+}
+
+LRESULT CALLBACK CWindow::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+    MessageDebug::debug(hwnd, uMsg, wParam, lParam, __FUNCTION__);
+    CWindow* window = (CWindow*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
+    if (window != NULL)
+        return window->Dispatch(hwnd, uMsg, wParam, lParam);
+    return DefWindowProc(hwnd, uMsg, wParam, lParam);
+}
+
+LRESULT CWindow::Dispatch(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+    switch (uMsg)
+    {
+        case WM_SIZE:
+            bounds.width = LOWORD(lParam);
+            bounds.height = LOWORD(lParam);
+            break;
+        case WM_MOVE:
+            bounds.left = LOWORD(lParam);
+            bounds.top = LOWORD(lParam);
+            break;
+        case WM_DESTROY:
+            showing = FALSE;
+            break;
+    }
+    if (owndproc)
+        return CallWindowProc(owndproc, hwnd, uMsg, wParam, lParam);
+    else
+        return DefWindowProc(hwnd, uMsg, wParam, lParam);
+}
+
+void CWindow::Show()
+{
+    if (hwnd == NULL)
+        Create();
+    ShowWindow(hwnd, SW_SHOWNORMAL);
+}
+
+int CWindow::ShowModal()
+{
+    MSG msg;
+    BOOL bRet;
+    showing = TRUE;
+    Show();
+
+    while( showing && (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
+    { 
+        if (bRet == -1)
+        {
+            // handle the error and possibly exit
+        }
+        else
+        {
+            TranslateMessage(&msg); 
+            DispatchMessage(&msg); 
+        }
+    }
+    return 0; 
+}
+
+void CWindow::SetLeft(int left)
+{
+    bounds.left = left;
+    if (hwnd)
+        if (!SetWindowPos(hwnd, NULL, 
+                bounds.left, bounds.top,
+                0, 0, 
+                SWP_NOZORDER |  SWP_NOSIZE))
+            throw win32_error("SetWindowPos failed");
+}
+
+void CWindow::SetTop(int top)
+{
+    bounds.top = top;
+    if (hwnd)
+        if (!SetWindowPos(hwnd, NULL, 
+                bounds.left, bounds.top,
+                0, 0, 
+                SWP_NOZORDER |  SWP_NOSIZE))
+            throw win32_error("SetWindowPos failed");
+}
+
+void CWindow::SetWidth(int width)
+{
+    bounds.width = width;
+    if (hwnd)
+        if (!SetWindowPos(hwnd, NULL,
+                0, 0, 
+                bounds.width, bounds.height, 
+                SWP_NOZORDER |  SWP_NOMOVE))
+            throw win32_error("SetWindowPos failed");
+}
+void CWindow::SetHeight(int height)
+{
+    bounds.height = height;
+    if (hwnd)
+        if (!SetWindowPos(hwnd, NULL,
+                0, 0, 
+                bounds.width, bounds.height,
+                SWP_NOZORDER |  SWP_NOMOVE))
+            throw win32_error("SetWindowPos failed");
+}
+
+void CWindow::SetBounds(int left, int top, int width, int height)
+{
+    bounds = CBoundary(left, top, width, height);
+    if (hwnd)
+        if (!SetWindowPos(hwnd, NULL, 
+                bounds.left, bounds.top, 
+                bounds.width, bounds.height, 
+                SWP_NOZORDER))
+            throw win32_error("SetWindowPos failed");
+}
+
+void CWindow::SetBounds(const RECT &rect)
+{
+    bounds = rect;
+    if (hwnd)
+        if (!SetWindowPos(hwnd, NULL, 
+                bounds.left, bounds.top, 
+                bounds.width, bounds.height, 
+                SWP_NOZORDER))
+            throw win32_error("SetWindowPos failed");
+}
+
+HWND CWindow::GetHandle()
+{
+    if (hwnd == NULL)
+        Create();
+    return hwnd;
+}
+
+void CWindow::SetParent(CWindow *window)
+{
+    parent = window->GetHandle();
+    if (hwnd != NULL)
+        if (::SetParent(hwnd, parent) == NULL)
+            throw win32_error("SetParent failed");
+        
+}
+
+void CWindow::SetStyle(DWORD style)
+{
+    this->style = style;
+    SetLastError(0);
+    if (hwnd)
+        SetWindowLong(hwnd, GWL_STYLE, style);
+    int err = GetLastError();
+    if (err != 0)
+        throw win32_error("SetWindowLong failed", err);
+}
+
+void CWindow::SetExStyle(DWORD exstyle)
+{
+    this->exstyle = exstyle;
+    SetLastError(0);
+    if (hwnd)
+        SetWindowLong(hwnd, GWL_EXSTYLE, exstyle);
+    int err = GetLastError();
+    if (err != 0)
+        throw win32_error("SetWindowWLong failed", err);
+}
diff --git a/hw/xwin/xlaunch/window/window.h b/hw/xwin/xlaunch/window/window.h
new file mode 100755
index 0000000..baf4014
--- /dev/null
+++ b/hw/xwin/xlaunch/window/window.h
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+#ifndef __WINDOW_H__
+#define __WINDOW_H__
+
+#include <windows.h>
+#include <string>
+
+class CDialog;
+class CWindow
+{
+    friend class CDialog;
+    public:
+        struct CBoundary
+        {
+            int left;
+            int top;
+            int width;
+            int height;
+            CBoundary() : 
+                left(0), top(0), width(0), height(0) {};
+            CBoundary(int x, int y, int w, int h) : 
+                left(x), top(y), width(w), height(h) {};
+            CBoundary(const RECT &r) : 
+                left(r.left), top(r.top), width(r.right-r.left), height(r.bottom-r.top) {};
+        };
+        class CWindowClass
+        {
+            private:
+                WNDPROC wndproc;
+                ATOM atom;
+                std::string classname;
+            protected:
+                void Register();
+            public:
+                CWindowClass(const char *name, WNDPROC wndproc);
+                ~CWindowClass();
+                const char *GetClassName() { return classname.c_str(); };
+        };
+    private:
+        static CWindowClass windowClass;
+
+        std::string title;
+        DWORD exstyle;
+        DWORD style;
+        CBoundary bounds;
+        HWND hwnd; 
+        HWND parent;
+        WNDPROC owndproc;
+
+        BOOL showing;
+
+    protected:
+
+        virtual const char *GetClassName();
+	virtual HWND CreateWindowHandle();
+        static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+    public:
+        CWindow(const char *title);
+	virtual void Create();
+
+        virtual int ShowModal();
+
+        void Show();
+        void Hide();
+
+        void SetWidth(int width);
+        void SetHeight(int height);
+        void SetLeft(int left);
+        void SetTop(int top);
+        int GetWidth() { return bounds.width; };
+        int GetHeight() { return bounds.height; };
+        int GetLeft() { return bounds.left; };
+        int GetTop() { return bounds.top; };
+
+        void SetBounds(int left, int top, int width, int height);
+        void SetBounds(const RECT &rect);
+
+        void SetStyle(DWORD style);
+        DWORD GetStyle() { return style; };
+        
+        void SetExStyle(DWORD exstyle);
+        DWORD GetExStyle() { return exstyle; };
+
+        HWND GetHandle();
+        void SetParent(CWindow *window);
+
+        virtual LRESULT Dispatch(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+};
+
+#endif
diff --git a/hw/xwin/xlaunch/window/wizard.cc b/hw/xwin/xlaunch/window/wizard.cc
new file mode 100755
index 0000000..9d6c711
--- /dev/null
+++ b/hw/xwin/xlaunch/window/wizard.cc
@@ -0,0 +1,244 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+#include "wizard.h"
+#include "util.h"
+
+CWizard::CWizard() : pages() 
+{
+};
+
+void CWizard::AddPage(const PROPSHEETPAGE &page)
+{
+    pages.push_back(page);
+}
+
+void CWizard::AddPage(const char *page, HINSTANCE instance)
+{
+    PROPSHEETPAGE psp;
+    if (instance == NULL)
+        instance = GetModuleHandle(NULL);
+    
+    memset(&psp, 0, sizeof(psp));
+    psp.dwSize = sizeof(PROPSHEETPAGE);
+    psp.dwFlags = PSP_DEFAULT;
+    psp.hInstance = instance;
+    psp.pszTemplate = page;
+    psp.pfnDlgProc = WizardDialogProc;
+    psp.lParam = (LPARAM)this;
+
+    AddPage(psp);
+}
+
+void CWizard::AddPage(DWORD id, DWORD title, DWORD subtitle, HINSTANCE instance)
+{
+    PROPSHEETPAGE psp;
+    if (instance == NULL)
+        instance = GetModuleHandle(NULL);
+    
+    memset(&psp, 0, sizeof(psp));
+    psp.dwSize = sizeof(PROPSHEETPAGE);
+    psp.dwFlags = PSP_DEFAULT;
+#if _WIN32_IE >= 0x0500
+    if (title != 0)
+    {
+        psp.dwFlags |= PSP_USEHEADERTITLE;
+        psp.pszHeaderTitle = MAKEINTRESOURCE(title);
+    }
+    if (subtitle != 0)
+    {
+        psp.dwFlags |= PSP_USEHEADERSUBTITLE;
+        psp.pszHeaderSubTitle = MAKEINTRESOURCE(subtitle);
+    }
+#endif
+		
+    psp.hInstance = instance;
+    psp.pszTemplate = MAKEINTRESOURCE(id);
+    psp.pfnDlgProc = WizardDialogProc;
+    psp.lParam = (LPARAM)this;
+
+    AddPage(psp);
+}
+
+HWND CWizard::CreateWindowHandle()
+{
+    PROPSHEETHEADER psh;
+    HWND ret;
+    
+    PrepareSheetHeader(psh, FALSE);
+    ret = (HWND)PropertySheet(&psh);
+    free(psh.phpage);
+    if (ret == NULL)
+        throw win32_error("PropertySheet failed");
+    return ret;
+}
+
+int CWizard::ShowModal()
+{
+    PROPSHEETHEADER psh;
+    int ret;
+    
+    PrepareSheetHeader(psh, TRUE);
+    ret = PropertySheet(&psh);
+    free(psh.phpage);
+    return ret;
+}
+
+void CWizard::PrepareSheetHeader(PROPSHEETHEADER &psh, BOOL modal)
+{
+    HPROPSHEETPAGE *phpage = (HPROPSHEETPAGE*)malloc(pages.size() * sizeof(HPROPSHEETPAGE));
+    DWORD modeflag;
+
+    if (modal)
+        modeflag = 0;
+    else
+        modeflag = PSH_MODELESS;
+    
+    for (unsigned i = 0; i < pages.size(); i++)
+    {
+        phpage[i] = CreatePropertySheetPage(&pages[i]);
+        if (phpage[i] == NULL)
+        {
+            DWORD err = GetLastError();
+            free(phpage);
+            throw win32_error("CreatePropertySheetPage failed", err);
+        }
+    }
+
+    memset(&psh, 0, sizeof(psh));
+    psh.dwSize = sizeof(PROPSHEETHEADER);
+#if _WIN32_IE >= 0x0500
+    psh.dwFlags = PSH_WIZARD97 | modeflag;
+#else
+    psh.dwFlags = PSH_WIZARD | modeflag;
+#endif
+    psh.hwndParent = NULL;
+    psh.hInstance = GetModuleHandle(NULL);
+    psh.pszIcon = NULL;
+    psh.pszCaption = (LPSTR) "Cell Properties";
+    psh.nPages = pages.size(); 
+    psh.nStartPage = 0;
+    psh.phpage = phpage;
+    psh.pfnCallback = NULL;
+}
+
+DWORD CWizard::PageID(unsigned index)
+{
+    if (index < pages.size() && IS_INTRESOURCE(pages[index].pszTemplate))
+	return (DWORD)pages[index].pszTemplate;
+    return (DWORD)-1;
+}
+
+unsigned CWizard::PageIndex(PROPSHEETPAGE *psp)
+{
+    for (unsigned i = 0; i < pages.size(); i++)
+    {
+	if (IS_INTRESOURCE(psp->pszTemplate) || IS_INTRESOURCE(pages[i].pszTemplate ))
+	{
+	    if (psp->pszTemplate == pages[i].pszTemplate)
+		return i;
+	}	    
+	else if (psp->pszTemplate && pages[i].pszTemplate)
+	{
+	    if (strcmp(psp->pszTemplate, pages[i].pszTemplate) == 0)
+		return i;
+	}
+    }
+    return (unsigned)-1;
+}
+
+INT_PTR CWizard::DlgDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+    return CBaseDialog::DlgDispatch(hwndDlg, uMsg, wParam, lParam);
+}
+
+INT_PTR CWizard::PageDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam, PROPSHEETPAGE *psp)
+{
+    LPNMHDR pnmh = (LPNMHDR)lParam;
+    DWORD flags; 
+    unsigned pageindex;
+    switch (uMsg)
+    {
+	case WM_NOTIFY:
+	    switch (pnmh->code)
+	    {
+		case PSN_SETACTIVE:
+#ifdef _DEBUG
+                    printf("PSN_SETACTIVE %d\n", PageIndex(psp));
+#endif
+		    pageindex = PageIndex(psp);
+		    if (pageindex != (unsigned)-1)
+		    {
+			flags = 0;
+			if (pageindex > 0)
+			    flags |= PSWIZB_BACK;
+			if ((unsigned)pageindex + 1 == pages.size())
+			    flags |= PSWIZB_FINISH;
+			if ((unsigned)pageindex + 1 < pages.size())
+                            flags |= PSWIZB_NEXT;
+                        PropSheet_SetWizButtons(GetParent(hwndDlg), flags);
+		    }
+		    WizardActivate(hwndDlg, pageindex);
+		    break;
+		case PSN_WIZNEXT:
+                    if (WizardNext(hwndDlg, PageIndex(psp)))
+                        return TRUE;
+		    break;
+		case PSN_WIZBACK:
+                    if (WizardBack(hwndDlg, PageIndex(psp)))
+                        return TRUE;
+		    break;
+                case PSN_WIZFINISH:
+                    if (WizardFinish(hwndDlg, PageIndex(psp)))
+                        return TRUE;
+                    DestroyWindow(GetParent(hwndDlg));
+		case PSN_RESET:
+                    if (WizardReset(hwndDlg, PageIndex(psp)))
+                        return TRUE;
+                    DestroyWindow(GetParent(hwndDlg));
+		    break;
+	    }
+    }
+    return DlgDispatch(hwndDlg, uMsg, wParam, lParam);
+}
+
+
+INT_PTR CALLBACK CWizard::WizardDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+    MessageDebug::debug(hwndDlg, uMsg, wParam, lParam, __FUNCTION__);
+    PROPSHEETPAGE *psp = (PROPSHEETPAGE*)lParam;
+    switch (uMsg)
+    {
+	case WM_INITDIALOG:
+	    SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)psp);
+	    break;
+    }
+    psp = (PROPSHEETPAGE*)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+    CWizard* wizard = psp?(CWizard*)psp->lParam:NULL;
+    if (wizard != NULL)
+        return wizard->PageDispatch(hwndDlg, uMsg, wParam, lParam, psp);
+    return FALSE;
+}
+
diff --git a/hw/xwin/xlaunch/window/wizard.h b/hw/xwin/xlaunch/window/wizard.h
new file mode 100755
index 0000000..a2361c5
--- /dev/null
+++ b/hw/xwin/xlaunch/window/wizard.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2005 Alexander Gottwald
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+#ifndef __WIZARD_H__
+#define __WIZARD_H__
+
+#include "dialog.h"
+#include <vector>
+
+#define _WIN32_IE 0x0500
+#include <prsht.h>
+
+class CWizard : public CBaseDialog
+{
+    private:
+        std::vector<PROPSHEETPAGE> pages;
+        void PrepareSheetHeader(PROPSHEETHEADER &psh, BOOL modal);
+    protected:
+        virtual HWND CreateWindowHandle();
+        static INT_PTR CALLBACK WizardDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
+        virtual INT_PTR DlgDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
+        virtual INT_PTR PageDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam, PROPSHEETPAGE *psp);
+        virtual unsigned PageIndex(PROPSHEETPAGE *psp);
+	virtual DWORD PageID(unsigned index);
+        virtual BOOL WizardNext(HWND hwndDlg, unsigned index) { return FALSE; }
+        virtual BOOL WizardBack(HWND hwndDlg, unsigned index) { return FALSE; } 
+        virtual BOOL WizardFinish(HWND hwndDlg, unsigned index) { return FALSE; }
+        virtual BOOL WizardReset(HWND hwndDlg, unsigned index) { return FALSE; }
+        virtual BOOL WizardActivate(HWND hwndDlg, unsigned index) { return FALSE; }
+    public:
+        CWizard();
+        void AddPage(const PROPSHEETPAGE &page);
+        void AddPage(const char *page, HINSTANCE instance = NULL);
+        void AddPage(DWORD id, DWORD title, DWORD subtitle, HINSTANCE instance = NULL);
+        virtual int ShowModal();
+};
+#endif
diff --git a/include/xwin-config.h.in b/include/xwin-config.h.in
new file mode 100644
index 0000000..c8de110
--- /dev/null
+++ b/include/xwin-config.h.in
@@ -0,0 +1,24 @@
+/*
+ * xwin-config.h.in
+ *
+ * This file has all defines used in the xwin ddx
+ *
+ */
+#include <dix-config.h>
+
+/* Winsock networking */
+#undef HAS_WINSOCK
+
+/* Cygwin has /dev/windows for signaling new win32 messages */
+#undef HAS_DEVWINDOWS
+
+/* Switch on debug messages */ 
+#undef CYGDEBUG
+#undef CYGWINDOWING_DEBUG
+#undef CYGMULTIWINDOW_DEBUG
+
+/* Define to 1 if unsigned long is 64 bits. */
+#undef _XSERVER64
+
+/* Do we require our own snprintf? */
+#undef NEED_SNPRINTF
commit 14396fdebac1868df17559220ed7aaa34c34251e
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sat Apr 19 23:31:05 2008 -0700

    XQuartz: Cleanup turning off COMPOSITE
    (cherry picked from commit 8f920fca6f9149185649d52569d33bf81b6c6857)

diff --git a/configure.ac b/configure.ac
index 0b9b907..ca16c5a 100644
--- a/configure.ac
+++ b/configure.ac
@@ -782,7 +782,7 @@ dnl XQuartz DDX Detection... Yes, it's ugly to have it here... but we need to di
 if test "x$COMPOSITE" = xauto; then
 	case $host_os in
 		darwin*)
-			[ "x$XQUARTZ" = xyes -o "x$XQUARTZ" = xauto ] && COMPOSITE=no
+			test "x$XQUARTZ" = xyes -o "x$XQUARTZ" = xauto && COMPOSITE=no
 			;;
 		*)
 			COMPOSITE=yes
diff --git a/hw/xquartz/xpr/Makefile.am b/hw/xquartz/xpr/Makefile.am
index 3e2e605..6007423 100644
--- a/hw/xquartz/xpr/Makefile.am
+++ b/hw/xquartz/xpr/Makefile.am
@@ -31,7 +31,6 @@ Xquartz_LDADD = \
 	$(top_builddir)/damageext/libdamageext.la \
 	$(top_builddir)/miext/damage/libdamage.la \
 	$(top_builddir)/xfixes/libxfixes.la \
-	$(top_builddir)/miext/cw/libcw.la \
 	$(top_builddir)/Xext/libXext.la \
 	$(top_builddir)/xkb/libxkb.la \
 	$(top_builddir)/xkb/libxkbstubs.la \
commit d13828797fe22856b07e08a55d2b9375902194bf
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri Apr 18 20:38:31 2008 -0700

    XQuartz: Cleaned up some casting to get rid of compiler warnings
    (cherry picked from commit 6f1c85b96550adf0bc34efb6ca649b87bcc1b18c)

diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index 990b08e..aad55fc 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -335,37 +335,34 @@ static void DarwinChangePointerControl(
  * DarwinMouseProc
  *  Handle the initialization, etc. of a mouse
  */
-static int DarwinMouseProc(
-    DeviceIntPtr    pPointer,
-    int             what )
-{
-  CARD8 map[8] = {0, 1, 2, 3, 4, 5, 6, 7};
-
+static int DarwinMouseProc(DeviceIntPtr pPointer, int what) {
+    CARD8 map[8] = {0, 1, 2, 3, 4, 5, 6, 7};
+    
     switch (what) {
-
+            
         case DEVICE_INIT:
             pPointer->public.on = FALSE;
-
+            
             // Set button map.
-              InitPointerDeviceStruct( (DevicePtr)pPointer, map, 7,
-				     GetMotionHistory,
-				     (PtrCtrlProcPtr)NoopDDA,
-				     GetMotionHistorySize(), 7);
-	    InitProximityClassDeviceStruct( (DevicePtr)pPointer);
+            InitPointerDeviceStruct((DevicePtr)pPointer, map, 7,
+                                    GetMotionHistory,
+                                    (PtrCtrlProcPtr)NoopDDA,
+                                    GetMotionHistorySize(), 7);
+            InitProximityClassDeviceStruct(pPointer);
             break;
-
+            
         case DEVICE_ON:
             pPointer->public.on = TRUE;
             AddEnabledDevice( darwinEventReadFD );
             return Success;
-
+            
         case DEVICE_CLOSE:
         case DEVICE_OFF:
             pPointer->public.on = FALSE;
-            RemoveEnabledDevice( darwinEventReadFD );
+            RemoveEnabledDevice(darwinEventReadFD);
             return Success;
     }
-
+    
     return Success;
 }
 
commit 6550078b0925f754e3eec3bbce94dbfe5de8c419
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sat Apr 19 09:29:46 2008 -0700

    Removed XWin DDX

diff --git a/.gitignore b/.gitignore
index 548e784..afd5415 100644
--- a/.gitignore
+++ b/.gitignore
@@ -284,7 +284,6 @@ include/xgl-config.h
 include/xkb-config.h
 include/xorg-config.h
 include/xorg-server.h
-include/xwin-config.h
 mfb/mfbbltC.c
 mfb/mfbbltCI.c
 mfb/mfbbltG.c
diff --git a/configure.ac b/configure.ac
index fcecc7a..0b9b907 100644
--- a/configure.ac
+++ b/configure.ac
@@ -46,8 +46,6 @@ dnl xorg-config.h covers the Xorg DDX.
 AC_CONFIG_HEADERS(include/xorg-config.h)
 dnl xkb-config.h covers XKB for the Xorg and Xnest DDXs.
 AC_CONFIG_HEADERS(include/xkb-config.h)
-dnl xwin-config.h covers the XWin DDX.
-AC_CONFIG_HEADERS(include/xwin-config.h)
 dnl kdrive-config.h covers the kdrive DDX
 AC_CONFIG_HEADERS(include/kdrive-config.h)
 
@@ -566,7 +564,6 @@ AC_ARG_ENABLE(xquartz,        AS_HELP_STRING([--enable-xquartz], [Build Xquartz
 AC_ARG_ENABLE(x11app,         AS_HELP_STRING([--enable-x11app], [Build Apple's X11.app for Xquartz (default: auto)]), [X11APP=$enableval], [X11APP=auto])
 AC_ARG_WITH(x11app-archs,     AS_HELP_STRING([--with-x11app-archs=ARCHS], [Architectures to build X11.app for, space delimeted (default: "ppc i386")]), [X11APP_ARCHS=$enableval], [X11APP_ARCHS="ppc i386"])
 AC_SUBST([X11APP_ARCHS])
-AC_ARG_ENABLE(xwin,    	      AS_HELP_STRING([--enable-xwin], [Build XWin server (default: auto)]), [XWIN=$enableval], [XWIN=auto])
 AC_ARG_ENABLE(xprint,         AS_HELP_STRING([--enable-xprint], [Build Xprint extension and server (default: no)]), [XPRINT=$enableval], [XPRINT=no])
 AC_ARG_ENABLE(xgl,            AS_HELP_STRING([--enable-xgl], [Build Xgl server (default: no)]), [XGL=$enableval], [XGL=no])
 AC_ARG_ENABLE(xglx,           AS_HELP_STRING([--enable-xglx], [Build Xglx xgl module (default: no)]), [XGLX=$enableval], [XGLX=no])
@@ -1639,76 +1636,6 @@ if test "x$XPRINT" = xyes; then
 fi
 AM_CONDITIONAL(XP_USE_FREETYPE, [test "x$XPRINT" = xyes && test "x$XP_USE_FREETYPE" = xyes])
 
-
-dnl XWin DDX
-
-AC_MSG_CHECKING([whether to build XWin DDX])
-if test "x$XWIN" = xauto; then
-	case $host_os in
-		cygwin*) XWIN="yes" ;;
-		mingw*) XWIN="yes" ;;
-		*) XWIN="no" ;;
-	esac
-	XWIN_LIBS="$FB_LIB $XEXT_LIB $CONFIG_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $COMPOSITE_LIB $DAMAGE_LIB $LAYER_LIB $XPSTUBS_LIB $SHADOW_LIB"
-	AC_SUBST([XWIN_LIBS])
-fi
-AC_MSG_RESULT([$XWIN])
-
-if test "x$XWIN" = xyes; then
-	case $host_os in
-		cygwin*)
-			XWIN_SERVER_NAME=XWin
-			PKG_CHECK_MODULES([XWINMODULES],[x11 xdmcp xau xfont])
-			AC_DEFINE(HAS_DEVWINDOWS,1,[Cygwin has /dev/windows for signaling new win32 messages])
-			AC_DEFINE(ROOTLESS,1,[Build Rootless code])
-			CFLAGS="$CFLAGS -DFD_SETSIZE=256"
-			;;
-		mingw*)
-			XWIN_SERVER_NAME=Xming
-			PKG_CHECK_MODULES([XWINMODULES],[x11 xdmcp xau xfont])
-			AC_DEFINE(RELOCATE_PROJECTROOT,1,[Make PROJECT_ROOT relative to the xserver location])
-			AC_DEFINE(HAS_WINSOCK,1,[Use Windows sockets])
-			XWIN_SYS_LIBS=-lwinsock2
-			;;
-	esac
-	XWIN_SYS_LIBS="$XWIN_SYS_LIBS $(XWINMODULES_LIBS)"
-	AC_SUBST(XWIN_SERVER_NAME)
-	AC_SUBST(XWIN_SYS_LIBS)
-
-	if test "x$DEBUGGING" = xyes; then
-		AC_DEFINE(CYGDEBUG, 1, [Simple debug messages])
-		AC_DEFINE(CYGWINDOWING_DEBUG, 1, [Debug messages for window handling])
-		AC_DEFINE(CYGMULTIWINDOW_DEBUG, 1, [Debug window manager])
-	fi
-
-	AC_DEFINE(DDXOSINIT, 1, [Use OsVendorInit])
-	AC_DEFINE(DDXTIME, 1, [Use GetTimeInMillis])
-	AC_DEFINE(DDXOSFATALERROR, 1, [Use OsVendorFatalError])
-	AC_DEFINE(DDXOSVERRORF, 1, [Use OsVendorVErrorF])
-	AC_DEFINE(DDXBEFORERESET, 1, [Use ddxBeforeReset ])
-	if test "x$XF86VIDMODE" = xyes; then
-		AC_MSG_NOTICE([Disabling XF86VidMode extension])
-		XF86VIDMODE=no
-	fi
-	if test "x$XF86MISC" = xyes; then
-		AC_MSG_NOTICE([Disabling XF86Misc extension])
-		XF86MISC=no
-	fi
-	if test "x$COMPOSITE" = xyes; then
-		AC_MSG_NOTICE([Disabling Composite extension])
-		COMPOSITE=no
-	fi
-fi
-AM_CONDITIONAL(XWIN, [test "x$XWIN" = xyes])
-AM_CONDITIONAL(XWIN_MULTIWINDOW, [test "x$XWIN" = xyes])
-AM_CONDITIONAL(XWIN_MULTIWINDOWEXTWM, [test "x$XWIN" = xyes && false])
-AM_CONDITIONAL(XWIN_CLIPBOARD, [test "x$XWIN" = xyes])
-AM_CONDITIONAL(XWIN_GLX_WINDOWS, [test "x$XWIN" = xyes && false])
-AM_CONDITIONAL(XWIN_NATIVEGDI, [test "x$XWIN" = xyes && false])
-AM_CONDITIONAL(XWIN_PRIMARYFB, [test "x$XWIN" = xyes && false])
-AM_CONDITIONAL(XWIN_RANDR, [test "x$XWIN" = xyes])
-AM_CONDITIONAL(XWIN_XV, [test "x$XWIN" = xyes && test "x$XV" = xyes])
-
 dnl Darwin / OS X DDX
 if test "X$XQUARTZ" = Xauto; then
 	AC_CACHE_CHECK([whether to build Xquartz],xorg_cv_Carbon_framework,[
@@ -2206,7 +2133,6 @@ hw/xgl/glx/module/Makefile
 hw/xgl/glxext/Makefile
 hw/xgl/glxext/module/Makefile
 hw/xnest/Makefile
-hw/xwin/Makefile
 hw/xquartz/Makefile
 hw/xquartz/bundle/Makefile
 hw/xquartz/xpr/Makefile
diff --git a/hw/Makefile.am b/hw/Makefile.am
index c2b9571..011a280 100644
--- a/hw/Makefile.am
+++ b/hw/Makefile.am
@@ -14,10 +14,6 @@ if XNEST
 XNEST_SUBDIRS = xnest
 endif
 
-if XWIN
-XWIN_SUBDIRS = xwin
-endif
-
 if XGL
 XGL_SUBDIRS = xgl
 endif
@@ -37,7 +33,6 @@ endif
 SUBDIRS =			\
 	$(XORG_SUBDIRS)		\
 	$(XGL_SUBDIRS)		\
-	$(XWIN_SUBDIRS)		\
 	$(XVFB_SUBDIRS)		\
 	$(XNEST_SUBDIRS)	\
 	$(DMX_SUBDIRS)		\
@@ -45,7 +40,7 @@ SUBDIRS =			\
 	$(XQUARTZ_SUBDIRS)	\
 	$(XPRINT_SUBDIRS)
 
-DIST_SUBDIRS = dmx xfree86 vfb xnest xwin xquartz kdrive xgl xprint
+DIST_SUBDIRS = dmx xfree86 vfb xnest xquartz kdrive xgl xprint
 
 relink:
 	for i in $(SUBDIRS) ; do $(MAKE) -C $$i relink ; done
diff --git a/hw/xwin/ChangeLog b/hw/xwin/ChangeLog
deleted file mode 100644
index aca2ffc..0000000
--- a/hw/xwin/ChangeLog
+++ /dev/null
@@ -1,683 +0,0 @@
-2006-03-03  Alan Hourihane  <alanh at fairlite.demon.co.uk>
-
-	* winprefs.c: (HandleCustomWM_COMMAND):
-	https://bugs.freedesktop.org/show_bug.cgi?id=4341
-	Make Xming error messages more meaningful.
-
-2006-03-03  Alan Hourihane  <alanh at fairlite.demon.co.uk>
-
-	* winmultiwindowwndproc.c: (winTopLevelWindowProc):
-	* winwndproc.c: (winWindowProc):
-	https://bugs.freedesktop.org/show_bug.cgi?id=4538
-	Fix mouse button release on multiwindows scrolling.
-
-2006-03-03  Alan Hourihane  <alanh at fairlite.demon.co.uk>
-
-	* winmultiwindowicons.c: (winXIconToHICON), (winUpdateIcon):
-	* winwin32rootlesswindow.c: (winMWExtWMUpdateIcon):
-	https://bugs.freedesktop.org/show_bug.cgi?id=5138
-	Check for NULL pointer
-
-2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwm.c:
-	Fix crash on server shutdown
-	
-2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winkeybd.c:
-	* winkeybd.h:
-	* winwndproc.c:
-	Fix simultanious presses of Left and Right Control and Shift keys.
-	https://bugs.freedesktop.org/show_bug.cgi?id=3677
-
-2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwm.c:
-	Fix typo which broke window titles
-
-2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwndproc.c:
-	* winkeybd.c:
-	Fix problem with fake Control press on Alt-Gr
-	https://bugs.freedesktop.org/show_bug.cgi?id=3680
-	https://bugs.freedesktop.org/show_bug.cgi?id=3497
-
-	* InitOutput.c:
-	Fix static declaration of winGetBaseDir
-
-2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winwindow.h:
-	* winmultiwindowwm.c:
-	* winscrinit.c:
-	External windowmanagers could connect in multiwindow mode which lead
-	to strange results with the internal windowmanager.
-
-2005-07-05  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* *.c:
-	Include xwin-config.h if HAVE_XWIN_CONFIG is defined
-	Cleanup X11 includes handling
-	Warning fixes
-	
-2005-06-30  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwndproc.c:
-	Pass serverClient instead of NULL to ConfigureWindow.
-	This should fix a crash reported by Øyvind Harboe
-
-2005-06-08  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winlayouts.h:
-	Merge from CYGWIN
-	Added layout "French (Canada)" as ca_enhanced 
-	Added Czech (QWERTY) layout
-	* winshaddnl.c:
-	Merge from CYGWIN
-	Print error code if winStoreColorsShadowDDNL fails
-
-2005-06-08  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwindow.c:
-	Fix crash reported by Øyvind Harboe
-
-2005-06-03  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwndproc.c:
-	* winblock.c:
-	Backout last winRaiseWindow patch which caused stacking problems
-
-2005-05-25  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* win.h:
-	* winmultiwindowwm.c:
-	Workaround bug in pthread.h
-
-2005-05-08  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwndproc.c:
-	* winblock.c:
-	Only call ConfigureWindow from winRaiseWindow if the windows
-	message dispatch loop is running.
-
-2005-05-02  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winerror.c:
-	Print correct logfile in FatalError message
-
-2005-04-19  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwndproc.c:
-	Prevent recursive calls to winRaiseWindow. 
-
-2005-03-10  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwndproc.c:
-	Force rebuilding of window stack if a window changes it's state from 
-	minimized.
-
-2005-03-07  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwndproc.c:
-	* winmultiwindowwindow.c:
-	Prevent winRaiseWindow from calling ConfigureWindow if the message
-	was sent from within winDestroyWindowsWindow
-
-	DestroyWindow send a WM_WINDOWPOSCHANGED to another window causing
-	a restacking of all windows, even of the window which is just about
-	to destroyed and whose structures may not be intact anymore.
-
-2005-02-24  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwndproc.c:
-	on WM_WINDOWPOSCHANGED raise window directly and in sync without 
-	utilizing the async windowmanager thread. Fixes some restacking 
-	problems occuring which were timing dependent
-	Do not raise the window on WM_ACTIVATE
-	Removed unused code for WM_WINDOWPOSCHANGING
-	ESC is debug key. Print status but do not abort processing the message
-	
-2005-02-12  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwindow.c
-	* winmultiwindowwndproc.c
-	* winwin32rootlesswndproc.c:
-	Cleanup some message debugging
-	
-2005-02-12  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* win.h
-	* winfont.c
-	* winmultiwindowshape.c
-	* winmultiwindowwindow.c
-	* winpfbdd.c
-	* winshaddd.c
-	* winshadddnl.c
-	* winshadgdi.c
-	* winwindow.c:
-	Fix incorrect wrapping of functions. Ensure the pointers from pScreen 
-	point to the called function even if wrapped functions changed it
-	
-	* winmultiwindowwindow.c:
-	Set the window properties to NULL to avoid referencing freed memory 
-	because of timing problems after deleting a window
-
-	* winscrinit.c:
-	Do not wrap ChangeWindowAttributes. All functions are noops currently
-	
-2005-02-12  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmsg.h:
-	* winmsg.c:
-	print window handle in message output
-	
-2005-02-08  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winkeybd.c:
-	* winkeynames.h:
-	Updated fix for ABNT2 and HK_Toggle keys. 
-
-2005-02-08  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winkeybd.h:
-	* winkeynames.h:
-	Backout ABNT2 and HK_Toggle fix since it broke keys F1 and F4. 
-
-2005-02-07  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winlayouts.h:
-	* winconfig.c:
-	Moved keyboard layout table to external file.
-
-2005-02-02  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* wincreatewnd.c:
-	Force ShowWindow if XWin was started via run.exe. Fixes mainwindow
-	not showing bug
-
-2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwindow.c
-	* winmultiwindowwndproc.c:
-	Create windows with SWP_NOACTIVATE flag (updated) (Kensuke Matsuzaki)
-
-2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwndproc.c:
-	Fixes for window ordering problem (updated) (Kensuke Matsuzaki)
-
-2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winconfig.c:
-	Added hungarian keyboard layout.
-
-2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmessages.h
-	* winmsg.h
-	* winmsg.c
-	* winmultiwindowwndproc.c
-	* winwin32rootlesswndproc.c
-	* winwndproc.c:
-	Make logging of messages configurable with environment variables
-
-2005-01-31  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* InitOutput.c:
-	resolve SHGetFolderPath dynamicly since it is not available on all Windows 
-	systems.
-
-2005-01-12  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmsg.c
-	* winmsg.h:
-	Introduce function winTrace which prints log message with verbosity 10
-	* winmultiwindowwindow.c:
-	Use winTrace for 3 heavily called functions
-
-2005-01-11  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* XWin.man:
-	Document the -silent-dup-error switch
-
-2005-01-11  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winkeyhook.c:
-	Do not grab ALT-TAB when window is in multiwindow mode
-	
-2005-01-11  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winprefs.h:
-	Fix crash with not matching definitions of PATH_MAX
-	
-2005-01-10  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winkeybd.h
-	* winkeynames.h:
-	Adjust keysyms for  Hiragana_Katakana toggle and backslash/underscore
-	on Japanese and ABNT2 keyboards
-
-2005-01-10  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winkeybd.h
-	* winkeyhook.c
-	* winwndproc.c:
-	Make keyhook feature work in multiwindowmode too
-	Hook windows keys
-
-2005-01-08  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winblock.c:
-	Fix a possible null-pointer dereference	(Keishi Suenaga)
-
-2005-01-06  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* Imakefile 
-	* InitOutput.c 
-	* XWin.rc 
-	* winerror.c 
-	* wintrayicon.c 
-	* winvideo.c
-	* winshaddd.c       	
-	* winwindow.h:
-	Set PROJECT_NAME in Imakefile to create alternative window titles 
-	for Cygwin/X and Xming
-	
-2005-01-06  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowclass.c:
-	* winmultiwindowwm.c:
-	Fix crash with non-nullterminated strings (reported by Øyvind Harboe)
-
-2004-12-14  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* InitOutput.c:
-	* winprocarg.c:
-	EnumDisplayMonitors is not available on Window NT4 and 95. Resolve
-	the function dynamicly
-
-2004-12-08  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* InitOutput.c:
-	* winprocarg.c:
-	Added support for placing the main window with the @<monitor#>.
-	Patch by Mark Fisher, small changes by Alexander Gottwald
-	
-2004-12-06  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* XWin.rc:
-	include windows.h
-
-2004-12-05  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* ddraw.h:
-	redone ddraw.h to be able to mix it with w32api style COM header 
-	files. 
-	
-	* winmultiwindowwm.c:
-	* obj_base.h:
-	* ddraw.h:
-	obj_base.h is not needed anymore. Using <objbase.h> instead.
-
-	* winms.h:
-	Use Xwindows.h instead of windows.h
-
-	* winresource.h:
-	do not include win_ms.h
-	
-	* win.h:
-	remove extra definition of sleep()
-
-	* InitOutput.c:
-	Set HOME to Documents and Settings/username if not set
-	
-	* winprefs.c:
-	Use Xming basedir instead of ProjectRoot for system.XWinrc
-
-	* windialogs.c:
-	* winshadgdi.c:
-	* winprefs.c:
-	Fix callback functions to use wBOOL instead of BOOL
-
-	* winmultiwindowwindow.c:
-	* winwin32rootless.c:
-	* winwin32rootlesswindow.c:
-	* winerror.c:
-	Fix compiler warnings. Added debug output.
-
-	* winconfig.c:
-	Fix warning about undefined macro max
-	
-2004-12-04  Earle Philhower
-
-	* InitOutput.c:
-	* win.h:
-	* wincreatewnd.c:
-	* winprocarg.c:
-	Optional position -screen parameter (-screen n WxH+X+Y or 
-	-screen n W H X Y)
-
-2004-12-03  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* windialogs.c:
-	* win.h:
-	* Imakefile:
-	* winerror.c:
-	Removed scprintf, aprintf and snprintf stuff and use newXprintf
-
-2004-12-02  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winwin32rootless.c:
-	Adjust the width of the rootless backbuffer to match 32 bit alignment
-
-	* winprocarg.c:
-	Make multiplemonitors default for -internalwm
-
-2004-12-01  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* InitOutput.c:
-	Set XERRORDB environment variable to relocate the XErrorDB file
-
-2004-11-29  Kensuke Matsuzaki  <zakki at peppermint.jp>
-
-	* winmultiwindowwm.c:
-	Fixed windows.h include for cygwin.
-	
-	* winmultiwindowwindow.c:
-	Bugzilla #1945: Stop unnecessary reordering.
-
-2004-11-24  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwm.c:
-	Finally the multiwindow mode defines a default cursor
-
-2004-11-22  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmultiwindowwm.c: 
-	Fixes for building multiwindow and internalwm on mingw
-	* winwin32rootless.c:
-	Changed some debugging output
-
-2004-11-22  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* InitOutput.c, winglobals.c, winprocarg.c:
-	Xming: Place logfile in users tempdir
-	
-2004-11-15  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* Imakefile:
-	Remove override of HasSnprintf
-
-2004-11-15  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* Imakefile:
-	* InitInput.c: (InitInput):
-	* InitOutput.c: (winClipboardShutdown), (ddxGiveUp),
-	(winCheckMount), (winGetBaseDir), (winFixupPaths), (OsVendorInit),
-	(winCheckDisplayNumber):
-	* win.h:
-	* winblock.c: (winBlockHandler):
-	* winclipboard.h:
-	* winclipboardthread.c: (winClipboardProc):
-	* winclipboardwndproc.c: (winClipboardWindowProc):
-	* winconfig.c: (winConfigKeyboard), (winConfigFiles):
-	* wincreatewnd.c: (winCreateBoundingWindowWindowed):
-	* windialogs.c: (winDisplayExitDialog), (winExitDlgProc),
-	(winAboutDlgProc):
-	* winengine.c: (winSetEngine):
-	* winerror.c: (OsVendorVErrorF), (winMessageBoxF), (scprintf):
-	* winglobals.c: (winInitializeGlobals):
-	* winkeybd.c: (winKeybdReleaseKeys):
-	* winmultiwindowicons.c:
-	* winmultiwindowwindow.c: (winCreateWindowsWindow):
-	* winmultiwindowwm.c:
-	* winprefs.c: (ReloadPrefs), (HandleCustomWM_COMMAND):
-	* winprocarg.c: (ddxProcessArgument):
-	* winscrinit.c: (winFinishScreenInitFB):
-	* winshadddnl.c:
-	* wintrayicon.c: (winHandleIconMessage):
-	* winwakeup.c: (winWakeupHandler):
-	* winwin32rootless.c: (winMWExtWMCreateFrame):
-	* winwindow.c: (winReshapeRootless):
-	* winwindow.h:
-	* winwndproc.c: (winWindowProc):
-	Bufzilla #1802, http://freedesktop.org/bugzilla/show_bug.cgi?id=1802
-	Added mingw (Win32) port     
-
-2004-11-11  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winconfig.c:
-	added keyboard layout "French (Switzerland)"
-
-2004-11-06  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winwndproc.c, wintrayicon.c, winscrinit.c:
-	* winmultiwindowwindow.c:
-	Wrap all mwextwm and internalwm code with XWIN_MULTIWINDOWEXTWM
-
-2004-11-04  Kensuke Matsuzaki  <zakki at peppermint.jp>
-
-	* InitOutput.c: (winUseMsg):
-	* win.h:
-	* winmultiwindowwindow.c: (winMinimizeWindow):
-	* winmultiwindowwm.c: (PushMessage), (UpdateName),
-	(PreserveWin32Stack), (winMultiWindowWMProc),
-	(winMultiWindowXMsgProc), (winInitWM), (winInitMultiWindowWM),
-	(CheckAnotherWindowManager):
-	* winprocarg.c: (winInitializeDefaultScreens),
-	(ddxProcessArgument):
-	* winscrinit.c: (winFinishScreenInitFB):
-	* wintrayicon.c: (winHandleIconMessage):
-	* winwin32rootless.c: (InitWin32RootlessEngine),
-	(winMWExtWMResizeFrame), (winMWExtWMRestackFrame),
-	(winMWExtWMStartDrawing), (winMWExtWMRootlessSwitchWindow),
-	(winMWExtWMSetNativeProperty):
-	* winwin32rootlesswindow.c: (winMWExtWMReorderWindows),
-	(winMWExtWMDecorateWindow), (winMWExtWMUpdateWindowDecoration),
-	(winIsInternalWMRunning), (winMWExtWMRestackWindows):
-	* winwin32rootlesswndproc.c: (winMWExtWMWindowProc):
-	* winwindow.h:
-	* winwndproc.c: (winWindowProc):
-	Add internalwm mode.
-
-2004-10-28  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* win.h:
-	add fRetryCreateSurface
-	* winshaddnl.c (winBltExposedRegionsShadowDDNL):
-	try to recreate the primary surface if it was lost
-	* winshaddnl.c (winCreatePrimarySurfaceShadowDDNL):
-	mark screen to retry creating the primary surface if it failed
-
-2004-10-23  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winconfig (winConfigFiles):
-	Simplify /etc/X11/font-dirs parsing
-
-2004-10-20  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* XWin.rc, winresource.h, winwndproc.c:
-	Add ShowCursor entry to tray menu 
-
-2004-10-20  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* Imakefile:
-	Add ETCX11DIR to DEFINES
-	* InitOutput.c (InitOutput):
-	* winconfig.c (winConfigFiles) :
-	Add entries from /etc/X11/font-dirs to default fontpath
-
-2004-10-16  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winprocarg.c (winInitializeDefaultScreens, ddxProcessArgument):
-	* win.h:
-	Make multiple monitors default for -multiwindow and -mwextwm.
-	Added a flag to indicate if the user has overridden the multimonitor
-	settings. (Øyvind Harboe, Alexander Gottwald)
-
-2004-10-07  Torrey Lyons  <torrey at freedesktop dot org>
-
-	* winscrinit.c:
-	Add compatibility with the generic rootless layer's new
-	DoReorderWindow function.
-
-2004-10-05  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* XWin.rc:
-	Set the dialogstyle to DS_CENTERMOUSE. Dialogs will now popup on the
-	monitor where the mouse is and not on the center of the whole desktop.
-
-2004-10-02  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winmouse.c (winMouseProc):
-	Make sure buttons 1-3 are mouse buttons and wheel events are 4-5
-	Document code
-	Replace ErrorF with appropriate winMsg
-	use a symbolic name for the wheel event offset
-	
-2004-10-01  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* wincreatewnd.c (winCreateBoundingWindowWindowed):
-	Do not adjust workarea if native windowmanager is used
-
-2004-09-22  Kensuke Matsuzaki
-
-	* winclipboardthread.c (winClipboardErrorHandler):
-	* winclipboardwndproc.c (winClipboardWindowProc):
-	* winclipboardxevents.c (winClipboardFlushXEvents):
-	Fix clipboard bug with unicode applications.
-	
-2004-09-17  Torrey Lyons  <torrey at freedesktop dot org>
-
-	* winscrinit.c: (winFinishScreenInitFB):
-	Bugzilla #1032: Make rootless acceleration functions compatible with
-	Damage.
-
-2004-09-16  Alexander Gottwald <ago at freedesktop dot org>
-
-	* wincreatewnd.c (winCreateBoundingWindowWindowed):
-	Remove code which prevented the use from specifying the window
-	size in nodecoration mode. 	
-
-2004-08-26  Chris B  <news at sempermax dot com>
-
-	* win.h, winmessages.h:
-	Add defines for WM_XBUTTON
-	* winmouse.c (winMouseProc):
-	Query number of mouse buttons from windows. 
-	* winmultiwindowwndproc.c (winTopLevelWindowProc):
-	* winwin32rootlesswndproc.c (winMWExtWMWindowProc):
-	* winwndproc.c (winWindowProc):
-	Handle WM_XBUTTON messages.  
-
-2004-08-02  Kensuke Matsuzaki
-
-	* winclipboardthread.c winclipboardwndproc.c: 
-	* winclipboardxevents.c winwin32rootlesswndproc.c:
-	Fix the bug that we can't copy & paste multi-byte string to
-	Unicode-base Windows application.  Rename fUnicodeSupport to
-	fUseUnicode, because it don't mean wheather Windows support
-	Unicode or not.
-	
-2004-07-31  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* win.h:
-	adjust prototype for winInitCmapPrivates to match Egberts change.	
-
-2004-07-30  Egbert Eich  <eich at freedesktop dot org>
-
-	* winallpriv.c: (winInitCmapPrivates):
-	test if colormap with index really exists in the list of
-	installed maps before using it.
-
-2004-07-09  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winconfig.c: Add entry for irish layout (ie)
-	* InitOutput.c, winerror.c, winglobals.c: rename g_fUseMsg to 
-	g_fSilentFatalError
-	* InitOutput.c, winglobals.c, winprocarg.c: added commandline option 
-	-silent-dup-error to allow silent termination if another instance of
-	XWin was found running
-
-2004-06-27  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winconfig.c: Add entry for us layout. This changes not much but 
-	removes a strange error message about the unknown us layout. 
-
-2004-06-24  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* InitOutput.c: Check for textmode mounted /tmp and print a warning
-
-2004-06-15  Harold Hunt  <huntharo at msu dot edu>
-
-	* windialogs.c: Fix path to locally installed changelog for the About 
-	dialog box.
-
-2004-05-27  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* winpriv.c: Create win32 window if not already created
-	* winmultiwindowwindow.c: Export winCreateWindowWindow
-
-2004-05-27  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* win.h: Allow CYGDEBUG to defined in the Makefile
-	* winwindow.h: Allow CYGWINDOWING_DEBUG to defined in the Makefile
-
-2004-05-19  Alexander Gottwald  <ago at freedesktop dot org>
-	
-	* winmultiwindowicons.c (winInitGlobalIcons): Load the small default
-	icon too
-	* winprefs.h, winprefs.c (winOverrideDefaultIcon): Takes the iconsize
-	as parameter
-
-2004-05-19  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* win.h, winmultiwindowicons.c (winXIconToHICON): Takes iconsize
-	as parameter 
-	* winglobals.c, winmultiwindowicons.c: Rename g_hiconX to g_hIconX.
-	Added new variable g_hSmallIconX for 16x16 icon.
-	* winwindow.h, winmultiwindowicons.c (winInitGlobalIcons): Inits the 
-	global g_hIconX handles.
-	* winwindow.h, winmultiwindowicons.c (winDestroyIcon): Free the icon
-	without messing with the global icon handle. 
-	* winmultiwindowicons.c (winSelectIcons): Generate a custom icon from
-	window settigns or set them to globals.
-	* winmultiwindowshape.c, winmultiwindowwindow.c, winwin32rootless.c,
-	  winwin32rootlesswindow.c, winwin32rootlesswndproc.c: Remove 
-	declaration of g_hiconX;
-	* winmultiwindowwindow.c (winCreateWindowsWindow),
-	  winwin32rootless.c (winMWExtWMCreateFrame): Use winSelectIcons 
-	to get the window icons. Set the small icon too.
-	* winmultiwindowwindow.c (winDestroyWindowsWindow),
-	  winmultiwindowicons.c (winUpdateIcon), 
-	  winprefs.c (ReloadEnumWindowsProc),
-	  winwin32rootlesswindow.c (winMWExtWMUpdateIcon),
-	  winwin32rootless.c (winMWExtWMDestroyFrame): Use winDestroyIcon
-	to free the icon without destroying the global icon.  
-	  
-2004-05-17  Alexander Gottwald  <ago at freedesktop dot org>
-
-	* windialogs.c (winExitDlgProc, winAboutDlgProc),
-	  winmultiwindowwndproc.c (winTopLevelWindowProc),
-	  winwndproc.c (winWindowProc): Check if g_fSoftwareCursor is set 
-	before calling ShowCursor.  
-
-2004-05-09  Dan Wilks  <Dan_Wilks at intuit dot com>
-    
-	* winclipboard.h: Add extern prototypes for winDebug, winErrorFVerb
-	copied from winmsg.h.
-	* winclipboardinit.c (winFixClipboardChain): Post rather than send the
-	reinit message to the clipboard window.  Sending the message caused,
-	or possibly just exacerbated an existing, race condition that would
-	cause the X server to hang when coming back from a remote desktop
-	session.
-	* winclipboardwndproc.c (winProcessXEventsTimeout): switch to new
-	logging api's.
-	* winclipboardwindproc.c (winClipboardWindowProc): switch to new 
-	logging api's.  Add some additional debug logging.  Make best effort 
-	to prevent our window appearing twice in the clipboard chain.  Also 
-	detect loops when they occur and try to behave in a reasonable way.
-
-# vim:ts=8:noexpandtab:encoding=utf8        
diff --git a/hw/xwin/InitInput.c b/hw/xwin/InitInput.c
deleted file mode 100644
index 6a850cd..0000000
--- a/hw/xwin/InitInput.c
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
-
-  Copyright 1993, 1998  The Open Group
-
-  Permission to use, copy, modify, distribute, and sell this software and its
-  documentation for any purpose is hereby granted without fee, provided that
-  the above copyright notice appear in all copies and that both that
-  copyright notice and this permission notice appear in supporting
-  documentation.
-
-  The above copyright notice and this permission notice shall be included
-  in all copies or substantial portions of the Software.
-
-  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-  IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
-  OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-  ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-  OTHER DEALINGS IN THE SOFTWARE.
-
-  Except as contained in this notice, the name of The Open Group shall
-  not be used in advertising or otherwise to promote the sale, use or
-  other dealings in this Software without prior written authorization
-  from The Open Group.
-
-*/
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#ifdef XWIN_CLIPBOARD
-# include "../../Xext/xf86miscproc.h"
-#endif
-#include "dixstruct.h"
-
-
-/*
- * Local function prototypes
- */
-
-#ifdef XWIN_CLIPBOARD
-DISPATCH_PROC(winProcEstablishConnection);
-DISPATCH_PROC(winProcQueryTree);
-DISPATCH_PROC(winProcSetSelectionOwner);
-#endif
-
-
-/*
- * Local global declarations
- */
-
-CARD32				g_c32LastInputEventTime = 0;
-
-
-/*
- * References to external symbols
- */
-
-#ifdef HAS_DEVWINDOWS
-extern int			g_fdMessageQueue;
-#endif
-extern Bool			g_fXdmcpEnabled;
-#ifdef XWIN_CLIPBOARD
-extern winDispatchProcPtr	winProcEstablishConnectionOrig;
-extern winDispatchProcPtr	winProcQueryTreeOrig;
-#endif
-
-
-/* Called from dix/devices.c */
-/*
- * All of our keys generate up and down transition notifications,
- * so all of our keys can be used as modifiers.
- * 
- * An example of a modifier is mapping the A key to the Control key.
- * A has to be a legal modifier.  I think.
- */
-
-Bool
-LegalModifier (unsigned int uiKey, DeviceIntPtr pDevice)
-{
-  return TRUE;
-}
-
-
-/* Called from dix/dispatch.c */
-/*
- * Run through the Windows message queue(s) one more time.
- * Tell mi to dequeue the events that we have sent it.
- */
-void
-ProcessInputEvents (void)
-{
-#if 0
-  ErrorF ("ProcessInputEvents\n");
-#endif
-
-  mieqProcessInputEvents ();
-  miPointerUpdate ();
-
-#if 0
-  ErrorF ("ProcessInputEvents - returning\n");
-#endif
-}
-
-
-int
-TimeSinceLastInputEvent ()
-{
-  if (g_c32LastInputEventTime == 0)
-    g_c32LastInputEventTime = GetTickCount ();
-  return GetTickCount () - g_c32LastInputEventTime;
-}
-
-
-/* See Porting Layer Definition - p. 17 */
-void
-InitInput (int argc, char *argv[])
-{
-  DeviceIntPtr		pMouse, pKeyboard;
-
-#if CYGDEBUG
-  winDebug ("InitInput\n");
-#endif
-
-#ifdef XWIN_CLIPBOARD
-  /*
-   * Wrap some functions at every generation of the server.
-   */
-  if (InitialVector[2] != winProcEstablishConnection)
-    {
-      winProcEstablishConnectionOrig = InitialVector[2];
-      InitialVector[2] = winProcEstablishConnection;
-    }
-  if (g_fXdmcpEnabled
-      && ProcVector[X_QueryTree] != winProcQueryTree)
-    {
-      winProcQueryTreeOrig = ProcVector[X_QueryTree];
-      ProcVector[X_QueryTree] = winProcQueryTree;
-    }
-#endif
-
-  pMouse = AddInputDevice (winMouseProc, TRUE);
-  pKeyboard = AddInputDevice (winKeybdProc, TRUE);
-  
-  RegisterPointerDevice (pMouse);
-  RegisterKeyboardDevice (pKeyboard);
-
-  miRegisterPointerDevice (screenInfo.screens[0], pMouse);
-  mieqInit ((DevicePtr)pKeyboard, (DevicePtr)pMouse);
-
-  /* Initialize the mode key states */
-  winInitializeModeKeyStates ();
-
-#ifdef HAS_DEVWINDOWS
-  /* Only open the windows message queue device once */
-  if (g_fdMessageQueue == WIN_FD_INVALID)
-    {
-      /* Open a file descriptor for the Windows message queue */
-      g_fdMessageQueue = open (WIN_MSG_QUEUE_FNAME, O_RDONLY);
-      
-      if (g_fdMessageQueue == -1)
-	{
-	  FatalError ("InitInput - Failed opening %s\n",
-		      WIN_MSG_QUEUE_FNAME);
-	}
-
-      /* Add the message queue as a device to wait for in WaitForSomething */
-      AddEnabledDevice (g_fdMessageQueue);
-    }
-#endif
-
-#if CYGDEBUG
-  winDebug ("InitInput - returning\n");
-#endif
-}
diff --git a/hw/xwin/InitOutput.c b/hw/xwin/InitOutput.c
deleted file mode 100644
index d215981..0000000
--- a/hw/xwin/InitOutput.c
+++ /dev/null
@@ -1,1144 +0,0 @@
-/*
-
-Copyright 1993, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
-OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall
-not be used in advertising or otherwise to promote the sale, use or
-other dealings in this Software without prior written authorization
-from The Open Group.
-
-*/
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winmsg.h"
-#include "winconfig.h"
-#include "winprefs.h"
-#ifdef XWIN_CLIPBOARD
-#include "X11/Xlocale.h"
-#endif
-#ifdef DPMSExtension
-#include "dpmsproc.h"
-#endif
-#ifdef __CYGWIN__
-#include <mntent.h>
-#endif
-#if defined(XKB) && defined(WIN32)
-#include <xkbsrv.h>
-#endif
-#ifdef RELOCATE_PROJECTROOT
-#include <shlobj.h>
-typedef HRESULT (*SHGETFOLDERPATHPROC)(
-    HWND hwndOwner,
-    int nFolder,
-    HANDLE hToken,
-    DWORD dwFlags,
-    LPTSTR pszPath
-);
-#endif
-
-
-/*
- * References to external symbols
- */
-
-extern int			g_iNumScreens;
-extern winScreenInfo		g_ScreenInfo[];
-extern int			g_iLastScreen;
-extern char *			g_pszCommandLine;
-extern Bool			g_fSilentFatalError;
-
-extern char *			g_pszLogFile;
-extern Bool			g_fLogFileChanged;
-extern int			g_iLogVerbose;
-Bool				g_fLogInited;
-
-extern Bool			g_fXdmcpEnabled;
-#ifdef HAS_DEVWINDOWS
-extern int			g_fdMessageQueue;
-#endif
-extern const char *		g_pszQueryHost;
-extern HINSTANCE		g_hInstance;
-
-#ifdef XWIN_CLIPBOARD
-extern Bool			g_fUnicodeClipboard;
-extern Bool			g_fClipboardLaunched;
-extern Bool			g_fClipboardStarted;
-extern pthread_t		g_ptClipboardProc;
-extern HWND			g_hwndClipboard;
-extern Bool			g_fClipboard;
-#endif
-
-extern HMODULE			g_hmodDirectDraw;
-extern FARPROC			g_fpDirectDrawCreate;
-extern FARPROC			g_fpDirectDrawCreateClipper;
-  
-extern HMODULE			g_hmodCommonControls;
-extern FARPROC			g_fpTrackMouseEvent;
-extern Bool			g_fNoHelpMessageBox;                     
-extern Bool			g_fSilentDupError;                     
-  
-  
-/*
- * Function prototypes
- */
-
-#ifdef XWIN_CLIPBOARD
-static void
-winClipboardShutdown (void);
-#endif
-
-#if defined(DDXOSVERRORF)
-void
-OsVendorVErrorF (const char *pszFormat, va_list va_args);
-#endif
-
-void
-winInitializeDefaultScreens (void);
-
-static Bool
-winCheckDisplayNumber (void);
-
-void
-winLogCommandLine (int argc, char *argv[]);
-
-void
-winLogVersionInfo (void);
-
-Bool
-winValidateArgs (void);
-
-#ifdef RELOCATE_PROJECTROOT
-const char *
-winGetBaseDir(void);
-#endif
-
-/*
- * For the depth 24 pixmap we default to 32 bits per pixel, but
- * we change this pixmap format later if we detect that the display
- * is going to be running at 24 bits per pixel.
- *
- * FIXME: On second thought, don't DIBs only support 32 bits per pixel?
- * DIBs are the underlying bitmap used for DirectDraw surfaces, so it
- * seems that all pixmap formats with depth 24 would be 32 bits per pixel.
- * Confirm whether depth 24 DIBs can have 24 bits per pixel, then remove/keep
- * the bits per pixel adjustment and update this comment to reflect the
- * situation.  Harold Hunt - 2002/07/02
- */
-
-static PixmapFormatRec g_PixmapFormats[] = {
-  { 1,    1,      BITMAP_SCANLINE_PAD },
-  { 4,    8,      BITMAP_SCANLINE_PAD },
-  { 8,    8,      BITMAP_SCANLINE_PAD },
-  { 15,   16,     BITMAP_SCANLINE_PAD },
-  { 16,   16,     BITMAP_SCANLINE_PAD },
-  { 24,   32,     BITMAP_SCANLINE_PAD },
-#ifdef RENDER
-  { 32,   32,     BITMAP_SCANLINE_PAD }
-#endif
-};
-
-const int NUMFORMATS = sizeof (g_PixmapFormats) / sizeof (g_PixmapFormats[0]);
-
-#ifdef XWIN_CLIPBOARD
-static void
-winClipboardShutdown (void)
-{
-  /* Close down clipboard resources */
-  if (g_fClipboard && g_fClipboardLaunched && g_fClipboardStarted)
-    {
-      /* Synchronously destroy the clipboard window */
-      if (g_hwndClipboard != NULL)
-	{
-	  SendMessage (g_hwndClipboard, WM_DESTROY, 0, 0);
-	  /* NOTE: g_hwndClipboard is set to NULL in winclipboardthread.c */
-	}
-      else
-	return;
-      
-      /* Wait for the clipboard thread to exit */
-      pthread_join (g_ptClipboardProc, NULL);
-
-      g_fClipboardLaunched = FALSE;
-      g_fClipboardStarted = FALSE;
-
-      winDebug ("winClipboardShutdown - Clipboard thread has exited.\n");
-    }
-}
-#endif
-
-
-#if defined(DDXBEFORERESET)
-/*
- * Called right before KillAllClients when the server is going to reset,
- * allows us to shutdown our seperate threads cleanly.
- */
-
-void
-ddxBeforeReset (void)
-{
-  winDebug ("ddxBeforeReset - Hello\n");
-
-#ifdef XWIN_CLIPBOARD
-  winClipboardShutdown ();
-#endif
-}
-#endif
-
-
-/* See Porting Layer Definition - p. 57 */
-void
-ddxGiveUp (void)
-{
-  int		i;
-
-#if CYGDEBUG
-  winDebug ("ddxGiveUp\n");
-#endif
-
-  /* Perform per-screen deinitialization */
-  for (i = 0; i < g_iNumScreens; ++i)
-    {
-      /* Delete the tray icon */
-      if (!g_ScreenInfo[i].fNoTrayIcon && g_ScreenInfo[i].pScreen)
- 	winDeleteNotifyIcon (winGetScreenPriv (g_ScreenInfo[i].pScreen));
-    }
-
-#ifdef XWIN_MULTIWINDOW
-  /* Notify the worker threads we're exiting */
-  winDeinitMultiWindowWM ();
-#endif
-
-#ifdef HAS_DEVWINDOWS
-  /* Close our handle to our message queue */
-  if (g_fdMessageQueue != WIN_FD_INVALID)
-    {
-      /* Close /dev/windows */
-      close (g_fdMessageQueue);
-
-      /* Set the file handle to invalid */
-      g_fdMessageQueue = WIN_FD_INVALID;
-    }
-#endif
-
-  if (!g_fLogInited) {
-    LogInit (g_pszLogFile, NULL);
-    g_fLogInited = TRUE;
-  }  
-  LogClose ();
-
-  /*
-   * At this point we aren't creating any new screens, so
-   * we are guaranteed to not need the DirectDraw functions.
-   */
-  if (g_hmodDirectDraw != NULL)
-    {
-      FreeLibrary (g_hmodDirectDraw);
-      g_hmodDirectDraw = NULL;
-      g_fpDirectDrawCreate = NULL;
-      g_fpDirectDrawCreateClipper = NULL;
-    }
-
-  /* Unload our TrackMouseEvent funtion pointer */
-  if (g_hmodCommonControls != NULL)
-    {
-      FreeLibrary (g_hmodCommonControls);
-      g_hmodCommonControls = NULL;
-      g_fpTrackMouseEvent = (FARPROC) (void (*)(void))NoopDDA;
-    }
-  
-  /* Free concatenated command line */
-  if (g_pszCommandLine)
-    {
-      free (g_pszCommandLine);
-      g_pszCommandLine = NULL;
-    }
-
-  /* Remove our keyboard hook if it is installed */
-  winRemoveKeyboardHookLL ();
-
-  /* Tell Windows that we want to end the app */
-  PostQuitMessage (0);
-}
-
-
-/* See Porting Layer Definition - p. 57 */
-void
-AbortDDX (void)
-{
-#if CYGDEBUG
-  winDebug ("AbortDDX\n");
-#endif
-  ddxGiveUp ();
-}
-
-#ifdef __CYGWIN__
-/* hasmntopt is currently not implemented for cygwin */
-static const char *winCheckMntOpt(const struct mntent *mnt, const char *opt)
-{
-    const char *s;
-    size_t len;
-    if (mnt == NULL)
-        return NULL;
-    if (opt == NULL)
-        return NULL;
-    if (mnt->mnt_opts == NULL)
-        return NULL;
-
-    len = strlen(opt);
-    s = strstr(mnt->mnt_opts, opt);
-    if (s == NULL)
-        return NULL;
-    if ((s == mnt->mnt_opts || *(s-1) == ',') &&  (s[len] == 0 || s[len] == ','))
-        return (char *)opt;
-    return NULL;
-}
-
-static void
-winCheckMount(void)
-{
-  FILE *mnt;
-  struct mntent *ent;
-
-  enum { none = 0, sys_root, user_root, sys_tmp, user_tmp } 
-    level = none, curlevel;
-  BOOL binary = TRUE;
-
-  mnt = setmntent("/etc/mtab", "r");
-  if (mnt == NULL)
-  {
-    ErrorF("setmntent failed");
-    return;
-  }
-
-  while ((ent = getmntent(mnt)) != NULL)
-  {
-    BOOL system = (strcmp(ent->mnt_type, "system") == 0);
-    BOOL root = (strcmp(ent->mnt_dir, "/") == 0);
-    BOOL tmp = (strcmp(ent->mnt_dir, "/tmp") == 0);
-    
-    if (system)
-    {
-      if (root)
-        curlevel = sys_root;
-      else if (tmp)
-        curlevel = sys_tmp;
-      else
-        continue;
-    }
-    else
-    {
-      if (root)
-        curlevel = user_root;
-      else if (tmp) 
-        curlevel = user_tmp;
-      else
-        continue;
-    }
-
-    if (curlevel <= level)
-      continue;
-    level = curlevel;
-
-    if (winCheckMntOpt(ent, "binmode") == NULL)
-      binary = 0;
-    else
-      binary = 1;
-  }
-    
-  if (endmntent(mnt) != 1)
-  {
-    ErrorF("endmntent failed");
-    return;
-  }
-  
- if (!binary) 
-   winMsg(X_WARNING, "/tmp mounted int textmode\n"); 
-}
-#else
-static void
-winCheckMount(void) 
-{
-}
-#endif
-
-#ifdef RELOCATE_PROJECTROOT
-const char * 
-winGetBaseDir(void)
-{
-    static BOOL inited = FALSE;
-    static char buffer[MAX_PATH];
-    if (!inited)
-    {
-        char *fendptr;
-        HMODULE module = GetModuleHandle(NULL);
-        DWORD size = GetModuleFileName(module, buffer, sizeof(buffer));
-        if (sizeof(buffer) > 0)
-            buffer[sizeof(buffer)-1] = 0;
-    
-        fendptr = buffer + size;
-        while (fendptr > buffer)
-        {
-            if (*fendptr == '\\' || *fendptr == '/')
-            {
-                *fendptr = 0;
-                break;
-            }
-            fendptr--;
-        }
-        inited = TRUE;
-    }
-    return buffer;
-}
-#endif
-
-static void
-winFixupPaths (void)
-{
-    BOOL changed_fontpath = FALSE;
-    MessageType font_from = X_DEFAULT;
-#ifdef RELOCATE_PROJECTROOT
-    const char *basedir = winGetBaseDir();
-    size_t basedirlen = strlen(basedir);
-#endif
-
-#ifdef READ_FONTDIRS
-    {
-        /* Open fontpath configuration file */
-        FILE *fontdirs = fopen(ETCX11DIR "/font-dirs", "rt");
-        if (fontdirs != NULL)
-        {
-            char buffer[256];
-            int needs_sep = TRUE; 
-            int comment_block = FALSE;
-
-            /* get defautl fontpath */
-            char *fontpath = xstrdup(defaultFontPath);
-            size_t size = strlen(fontpath);
-
-            /* read all lines */
-            while (!feof(fontdirs))
-            {
-                size_t blen;
-                char *hashchar;
-                char *str;
-                int has_eol = FALSE;
-
-                /* read one line */
-                str = fgets(buffer, sizeof(buffer), fontdirs);
-                if (str == NULL) /* stop on error or eof */
-                    break;
-
-                if (strchr(str, '\n') != NULL)
-                    has_eol = TRUE;
-
-                /* check if block is continued comment */
-                if (comment_block)
-                {
-                    /* ignore all input */
-                    *str = 0; 
-                    blen = 0; 
-                    if (has_eol) /* check if line ended in this block */
-                        comment_block = FALSE;
-                }
-                else 
-                {
-                    /* find comment character. ignore all trailing input */
-                    hashchar = strchr(str, '#');
-                    if (hashchar != NULL)
-                    {
-                        *hashchar = 0;
-                        if (!has_eol) /* mark next block as continued comment */
-                            comment_block = TRUE;
-                    }
-                }
-
-                /* strip whitespaces from beginning */
-                while (*str == ' ' || *str == '\t')
-                    str++;
-
-                /* get size, strip whitespaces from end */ 
-                blen = strlen(str);
-                while (blen > 0 && (str[blen-1] == ' ' || 
-                            str[blen-1] == '\t' || str[blen-1] == '\n'))
-                {
-                    str[--blen] = 0;
-                }
-
-                /* still something left to add? */ 
-                if (blen > 0)
-                {
-                    size_t newsize = size + blen;
-                    /* reserve one character more for ',' */
-                    if (needs_sep)
-                        newsize++;
-
-                    /* allocate memory */
-                    if (fontpath == NULL)
-                        fontpath = malloc(newsize+1);
-                    else
-                        fontpath = realloc(fontpath, newsize+1);
-
-                    /* add separator */
-                    if (needs_sep)
-                    {
-                        fontpath[size] = ',';
-                        size++;
-                        needs_sep = FALSE;
-                    }
-
-                    /* mark next line as new entry */
-                    if (has_eol)
-                        needs_sep = TRUE;
-
-                    /* add block */
-                    strncpy(fontpath + size, str, blen);
-                    fontpath[newsize] = 0;
-                    size = newsize;
-                }
-            }
-
-            /* cleanup */
-            fclose(fontdirs);  
-            defaultFontPath = xstrdup(fontpath);
-            free(fontpath);
-            changed_fontpath = TRUE;
-            font_from = X_CONFIG;
-        }
-    }
-#endif /* READ_FONTDIRS */
-#ifdef RELOCATE_PROJECTROOT
-    {
-        const char *libx11dir = PROJECTROOT "/lib/X11";
-        size_t libx11dir_len = strlen(libx11dir);
-        char *newfp = NULL;
-        size_t newfp_len = 0;
-        const char *endptr, *ptr, *oldptr = defaultFontPath;
-
-        endptr = oldptr + strlen(oldptr);
-        ptr = strchr(oldptr, ',');
-        if (ptr == NULL)
-            ptr = endptr;
-        while (ptr != NULL)
-        {
-            size_t oldfp_len = (ptr - oldptr);
-            size_t newsize = oldfp_len;
-            char *newpath = malloc(newsize + 1);
-            strncpy(newpath, oldptr, newsize);
-            newpath[newsize] = 0;
-
-
-            if (strncmp(libx11dir, newpath, libx11dir_len) == 0)
-            {
-                char *compose;
-                newsize = newsize - libx11dir_len + basedirlen;
-                compose = malloc(newsize + 1);  
-                strcpy(compose, basedir);
-                strncat(compose, newpath + libx11dir_len, newsize - basedirlen);
-                compose[newsize] = 0;
-                free(newpath);
-                newpath = compose;
-            }
-
-            oldfp_len = newfp_len;
-            if (oldfp_len > 0)
-                newfp_len ++; /* space for separator */
-            newfp_len += newsize;
-
-            if (newfp == NULL)
-                newfp = malloc(newfp_len + 1);
-            else
-                newfp = realloc(newfp, newfp_len + 1);
-
-            if (oldfp_len > 0)
-            {
-                strcpy(newfp + oldfp_len, ",");
-                oldfp_len++;
-            }
-            strcpy(newfp + oldfp_len, newpath);
-
-            free(newpath);
-
-            if (*ptr == 0)
-            {
-                oldptr = ptr;
-                ptr = NULL;
-            } else
-            {
-                oldptr = ptr + 1;
-                ptr = strchr(oldptr, ',');
-                if (ptr == NULL)
-                    ptr = endptr;
-            }
-        } 
-
-        defaultFontPath = xstrdup(newfp);
-        free(newfp);
-        changed_fontpath = TRUE;
-    }
-#endif /* RELOCATE_PROJECTROOT */
-    if (changed_fontpath)
-        winMsg (font_from, "FontPath set to \"%s\"\n", defaultFontPath);
-
-#ifdef RELOCATE_PROJECTROOT
-    if (getenv("XKEYSYMDB") == NULL)
-    {
-        char buffer[MAX_PATH];
-        snprintf(buffer, sizeof(buffer), "XKEYSYMDB=%s\\XKeysymDB",
-                basedir);
-        buffer[sizeof(buffer)-1] = 0;
-        putenv(buffer);
-    }
-    if (getenv("XERRORDB") == NULL)
-    {
-        char buffer[MAX_PATH];
-        snprintf(buffer, sizeof(buffer), "XERRORDB=%s\\XErrorDB",
-                basedir);
-        buffer[sizeof(buffer)-1] = 0;
-        putenv(buffer);
-    }
-    if (getenv("XLOCALEDIR") == NULL)
-    {
-        char buffer[MAX_PATH];
-        snprintf(buffer, sizeof(buffer), "XLOCALEDIR=%s\\locale",
-                basedir);
-        buffer[sizeof(buffer)-1] = 0;
-        putenv(buffer);
-    }
-    if (getenv("HOME") == NULL)
-    {
-        HMODULE shfolder;
-        SHGETFOLDERPATHPROC shgetfolderpath = NULL;
-        char buffer[MAX_PATH + 5];
-        strncpy(buffer, "HOME=", 5);
-
-        /* Try to load SHGetFolderPath from shfolder.dll and shell32.dll */
-        
-        shfolder = LoadLibrary("shfolder.dll");
-        /* fallback to shell32.dll */
-        if (shfolder == NULL)
-            shfolder = LoadLibrary("shell32.dll");
-
-        /* resolve SHGetFolderPath */
-        if (shfolder != NULL)
-            shgetfolderpath = (SHGETFOLDERPATHPROC)GetProcAddress(shfolder, "SHGetFolderPathA");
-
-        /* query appdata directory */
-        if (shgetfolderpath &&
-                shgetfolderpath(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE, NULL, 0, 
-                    buffer + 5) == 0)
-        { 
-            putenv(buffer);
-        } else
-        {
-            winMsg (X_ERROR, "Can not determine HOME directory\n");
-        } 
-        if (shfolder != NULL)
-            FreeLibrary(shfolder);
-    }
-    if (!g_fLogFileChanged) {
-        static char buffer[MAX_PATH];
-        DWORD size = GetTempPath(sizeof(buffer), buffer);
-        if (size && size < sizeof(buffer))
-        {
-            snprintf(buffer + size, sizeof(buffer) - size, 
-                    "XWin.%s.log", display); 
-            buffer[sizeof(buffer)-1] = 0;
-            g_pszLogFile = buffer;
-            winMsg (X_DEFAULT, "Logfile set to \"%s\"\n", g_pszLogFile);
-        }
-    }
-#ifdef XKB
-    {
-        static char xkbbasedir[MAX_PATH];
-
-        snprintf(xkbbasedir, sizeof(xkbbasedir), "%s\\xkb", basedir);
-        if (sizeof(xkbbasedir) > 0)
-            xkbbasedir[sizeof(xkbbasedir)-1] = 0;
-        XkbBaseDirectory = xkbbasedir;
-	XkbBinDirectory = basedir;
-    }
-#endif /* XKB */
-#endif /* RELOCATE_PROJECTROOT */
-}
-
-void
-OsVendorInit (void)
-{
-  /* Re-initialize global variables on server reset */
-  winInitializeGlobals ();
-
-  LogInit (NULL, NULL);
-  LogSetParameter (XLOG_VERBOSITY, g_iLogVerbose);
-
-  winFixupPaths();
-
-#ifdef DDXOSVERRORF
-  if (!OsVendorVErrorFProc)
-    OsVendorVErrorFProc = OsVendorVErrorF;
-#endif
-
-  if (!g_fLogInited) {
-    /* keep this order. If LogInit fails it calls Abort which then calls
-     * ddxGiveUp where LogInit is called again and creates an infinite 
-     * recursion. If we set g_fLogInited to TRUE before the init we 
-     * avoid the second call 
-     */  
-    g_fLogInited = TRUE;
-    LogInit (g_pszLogFile, NULL);
-  } 
-  LogSetParameter (XLOG_FLUSH, 1);
-  LogSetParameter (XLOG_VERBOSITY, g_iLogVerbose);
-  LogSetParameter (XLOG_FILE_VERBOSITY, 1);
-
-  /* Log the version information */
-  if (serverGeneration == 1)
-    winLogVersionInfo ();
-
-  winCheckMount();  
-
-  /* Add a default screen if no screens were specified */
-  if (g_iNumScreens == 0)
-    {
-      winDebug ("OsVendorInit - Creating bogus screen 0\n");
-
-      /* 
-       * We need to initialize default screens if no arguments
-       * were processed.  Otherwise, the default screens would
-       * already have been initialized by ddxProcessArgument ().
-       */
-      winInitializeDefaultScreens ();
-
-      /*
-       * Add a screen 0 using the defaults set by 
-       * winInitializeDefaultScreens () and any additional parameters
-       * processed by ddxProcessArgument ().
-       */
-      g_iNumScreens = 1;
-      g_iLastScreen = 0;
-
-      /* We have to flag this as an explicit screen, even though it isn't */
-      g_ScreenInfo[0].fExplicitScreen = TRUE;
-    }
-}
-
-
-static void
-winUseMsg (void)
-{
-  ErrorF ("-depth bits_per_pixel\n"
-	  "\tSpecify an optional bitdepth to use in fullscreen mode\n"
-	  "\twith a DirectDraw engine.\n");
-
-  ErrorF ("-emulate3buttons [timeout]\n"
-	  "\tEmulate 3 button mouse with an optional timeout in\n"
-	  "\tmilliseconds.\n");
-
-  ErrorF ("-engine engine_type_id\n"
-	  "\tOverride the server's automatically selected engine type:\n"
-	  "\t\t1 - Shadow GDI\n"
-	  "\t\t2 - Shadow DirectDraw\n"
-	  "\t\t4 - Shadow DirectDraw4 Non-Locking\n"
-#ifdef XWIN_NATIVEGDI
-	  "\t\t16 - Native GDI - experimental\n"
-#endif
-	  );
-
-  ErrorF ("-fullscreen\n"
-	  "\tRun the server in fullscreen mode.\n");
-  
-  ErrorF ("-refresh rate_in_Hz\n"
-	  "\tSpecify an optional refresh rate to use in fullscreen mode\n"
-	  "\twith a DirectDraw engine.\n");
-
-  ErrorF ("-screen scr_num [width height [x y] | [[WxH[+X+Y]][@m]] ]\n"
-	  "\tEnable screen scr_num and optionally specify a width and\n"
-	  "\theight and initial position for that screen. Additionally\n"
-	  "\ta monitor number can be specified to start the server on,\n"
-	  "\tat which point, all coordinates become relative to that\n"
-      "\tmonitor (Not for Windows NT4 and 95). Examples:\n"
-      "\t -screen 0 800x600+100+100 at 2 ; 2nd monitor offset 100,100 size 800x600\n"
-      "\t -screen 0 1024x768 at 3        ; 3rd monitor size 1024x768\n"
-      "\t -screen 0 @1 ; on 1st monitor using its full resolution (the default)\n");
-
-  ErrorF ("-lesspointer\n"
-	  "\tHide the windows mouse pointer when it is over an inactive\n"
-          "\t" PROJECT_NAME " window.  This prevents ghost cursors appearing where\n"
-	  "\tthe Windows cursor is drawn overtop of the X cursor\n");
-
-  ErrorF ("-nodecoration\n"
-          "\tDo not draw a window border, title bar, etc.  Windowed\n"
-	  "\tmode only.\n");
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-  ErrorF ("-mwextwm\n"
-	  "\tRun the server in multi-window external window manager mode.\n");
-
-  ErrorF ("-internalwm\n"
-	  "\tRun the internal window manager.\n");
-#endif
-
-  ErrorF ("-rootless\n"
-	  "\tRun the server in rootless mode.\n");
-
-#ifdef XWIN_MULTIWINDOW
-  ErrorF ("-multiwindow\n"
-	  "\tRun the server in multi-window mode.\n");
-#endif
-
-  ErrorF ("-multiplemonitors\n"
-	  "\tEXPERIMENTAL: Use the entire virtual screen if multiple\n"
-	  "\tmonitors are present.\n");
-
-#ifdef XWIN_CLIPBOARD
-  ErrorF ("-clipboard\n"
-	  "\tRun the clipboard integration module.\n"
-	  "\tDo not use at the same time as 'xwinclip'.\n");
-
-  ErrorF ("-nounicodeclipboard\n"
-	  "\tDo not use Unicode clipboard even if NT-based platform.\n");
-#endif
-
-  ErrorF ("-scrollbars\n"
-	  "\tIn windowed mode, allow screens bigger than the Windows desktop.\n"
-	  "\tMoreover, if the window has decorations, one can now resize\n"
-	  "\tit.\n");
-
-  ErrorF ("-[no]trayicon\n"
-          "\tDo not create a tray icon.  Default is to create one\n"
-	  "\ticon per screen.  You can globally disable tray icons with\n"
-	  "\t-notrayicon, then enable it for specific screens with\n"
-	  "\t-trayicon for those screens.\n");
-
-  ErrorF ("-clipupdates num_boxes\n"
-	  "\tUse a clipping region to constrain shadow update blits to\n"
-	  "\tthe updated region when num_boxes, or more, are in the\n"
-	  "\tupdated region.  Currently supported only by `-engine 1'.\n");
-
-#ifdef XWIN_EMULATEPSEUDO
-  ErrorF ("-emulatepseudo\n"
-	  "\tCreate a depth 8 PseudoColor visual when running in\n"
-	  "\tdepths 15, 16, 24, or 32, collectively known as TrueColor\n"
-	  "\tdepths.  The PseudoColor visual does not have correct colors,\n"
-	  "\tand it may crash, but it at least allows you to run your\n"
-	  "\tapplication in TrueColor modes.\n");
-#endif
-
-  ErrorF ("-[no]unixkill\n"
-          "\tCtrl+Alt+Backspace exits the X Server.\n");
-
-  ErrorF ("-[no]winkill\n"
-          "\tAlt+F4 exits the X Server.\n");
-
-#ifdef XWIN_XF86CONFIG
-  ErrorF ("-config\n"
-          "\tSpecify a configuration file.\n");
-
-  ErrorF ("-keyboard\n"
-	  "\tSpecify a keyboard device from the configuration file.\n");
-#endif
-
-#ifdef XKB
-  ErrorF ("-xkbrules XKBRules\n"
-	  "\tEquivalent to XKBRules in XF86Config files.\n");
-
-  ErrorF ("-xkbmodel XKBModel\n"
-	  "\tEquivalent to XKBModel in XF86Config files.\n");
-
-  ErrorF ("-xkblayout XKBLayout\n"
-	  "\tEquivalent to XKBLayout in XF86Config files.\n"
-	  "\tFor example: -xkblayout de\n");
-
-  ErrorF ("-xkbvariant XKBVariant\n"
-	  "\tEquivalent to XKBVariant in XF86Config files.\n"
-	  "\tFor example: -xkbvariant nodeadkeys\n");
-
-  ErrorF ("-xkboptions XKBOptions\n"
-	  "\tEquivalent to XKBOptions in XF86Config files.\n");
-#endif
-
-  ErrorF ("-logfile filename\n"
-	  "\tWrite logmessages to <filename> instead of /tmp/Xwin.log.\n");
-
-  ErrorF ("-logverbose verbosity\n"
-	  "\tSet the verbosity of logmessages. [NOTE: Only a few messages\n"
-	  "\trespect the settings yet]\n"
-	  "\t\t0 - only print fatal error.\n"
-	  "\t\t1 - print additional configuration information.\n"
-	  "\t\t2 - print additional runtime information [default].\n"
-	  "\t\t3 - print debugging and tracing information.\n");
-
-  ErrorF ("-[no]keyhook\n"
-	  "\tGrab special windows key combinations like Alt-Tab or the Menu "
-          "key.\n These keys are discarded by default.\n");
-
-  ErrorF ("-swcursor\n"
-	  "\tDisable the usage of the windows cursor and use the X11 software "
-	  "cursor instead\n");
-}
-
-/* See Porting Layer Definition - p. 57 */
-void
-ddxUseMsg(void)
-{
-  /* Set a flag so that FatalError won't give duplicate warning message */
-  g_fSilentFatalError = TRUE;
-  
-  winUseMsg();  
-
-  /* Log file will not be opened for UseMsg unless we open it now */
-  if (!g_fLogInited) {
-    LogInit (g_pszLogFile, NULL);
-    g_fLogInited = TRUE;
-  }  
-  LogClose ();
-
-  /* Notify user where UseMsg text can be found.*/
-  if (!g_fNoHelpMessageBox)
-    winMessageBoxF ("The " PROJECT_NAME " help text has been printed to "
-		  "/tmp/XWin.log.\n"
-		  "Please open /tmp/XWin.log to read the help text.\n",
-		  MB_ICONINFORMATION);
-}
-
-/* ddxInitGlobals - called by |InitGlobals| from os/util.c */
-void ddxInitGlobals(void)
-{
-}
-
-/* See Porting Layer Definition - p. 20 */
-/*
- * Do any global initialization, then initialize each screen.
- * 
- * NOTE: We use ddxProcessArgument, so we don't need to touch argc and argv
- */
-
-void
-InitOutput (ScreenInfo *screenInfo, int argc, char *argv[])
-{
-  int		i;
-
-  /* Log the command line */
-  winLogCommandLine (argc, argv);
-
-#if CYGDEBUG
-  winDebug ("InitOutput\n");
-#endif
-
-  /* Validate command-line arguments */
-  if (serverGeneration == 1 && !winValidateArgs ())
-    {
-      FatalError ("InitOutput - Invalid command-line arguments found.  "
-		  "Exiting.\n");
-    }
-
-  /* Check for duplicate invocation on same display number.*/
-  if (serverGeneration == 1 && !winCheckDisplayNumber ())
-    {
-      if (g_fSilentDupError)
-        g_fSilentFatalError = TRUE;  
-      FatalError ("InitOutput - Duplicate invocation on display "
-		  "number: %s.  Exiting.\n", display);
-    }
-
-#ifdef XWIN_XF86CONFIG
-  /* Try to read the xorg.conf-style configuration file */
-  if (!winReadConfigfile ())
-    winErrorFVerb (1, "InitOutput - Error reading config file\n");
-#else
-  winMsg(X_INFO, "XF86Config is not supported\n");
-  winMsg(X_INFO, "See http://x.cygwin.com/docs/faq/cygwin-x-faq.html "
-         "for more information\n");
-  winConfigFiles ();
-#endif
-
-  /* Load preferences from XWinrc file */
-  LoadPreferences();
-
-  /* Setup global screen info parameters */
-  screenInfo->imageByteOrder = IMAGE_BYTE_ORDER;
-  screenInfo->bitmapScanlinePad = BITMAP_SCANLINE_PAD;
-  screenInfo->bitmapScanlineUnit = BITMAP_SCANLINE_UNIT;
-  screenInfo->bitmapBitOrder = BITMAP_BIT_ORDER;
-  screenInfo->numPixmapFormats = NUMFORMATS;
-  
-  /* Describe how we want common pixmap formats padded */
-  for (i = 0; i < NUMFORMATS; i++)
-    {
-      screenInfo->formats[i] = g_PixmapFormats[i];
-    }
-
-  /* Load pointers to DirectDraw functions */
-  winGetDDProcAddresses ();
-  
-  /* Detect supported engines */
-  winDetectSupportedEngines ();
-
-  /* Load common controls library */
-  g_hmodCommonControls = LoadLibraryEx ("comctl32.dll", NULL, 0);
-
-  /* Load TrackMouseEvent function pointer */  
-  g_fpTrackMouseEvent = GetProcAddress (g_hmodCommonControls,
-					 "_TrackMouseEvent");
-  if (g_fpTrackMouseEvent == NULL)
-    {
-      winErrorFVerb (1, "InitOutput - Could not get pointer to function\n"
-	      "\t_TrackMouseEvent in comctl32.dll.  Try installing\n"
-	      "\tInternet Explorer 3.0 or greater if you have not\n"
-	      "\talready.\n");
-
-      /* Free the library since we won't need it */
-      FreeLibrary (g_hmodCommonControls);
-      g_hmodCommonControls = NULL;
-
-      /* Set function pointer to point to no operation function */
-      g_fpTrackMouseEvent = (FARPROC) (void (*)(void))NoopDDA;
-    }
-
-  /* Store the instance handle */
-  g_hInstance = GetModuleHandle (NULL);
-
-  /* Initialize each screen */
-  for (i = 0; i < g_iNumScreens; ++i)
-    {
-      /* Initialize the screen */
-      if (-1 == AddScreen (winScreenInit, argc, argv))
-	{
-	  FatalError ("InitOutput - Couldn't add screen %d", i);
-	}
-    }
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-
-#if defined(XCSECURITY)
-  /* Generate a cookie used by internal clients for authorization */
-  if (g_fXdmcpEnabled)
-    winGenerateAuthorization ();
-#endif
-
-  /* Perform some one time initialization */
-  if (1 == serverGeneration)
-    {
-      /*
-       * setlocale applies to all threads in the current process.
-       * Apply locale specified in LANG environment variable.
-       */
-      setlocale (LC_ALL, "");
-    }
-#endif
-
-#if CYGDEBUG || YES
-  winDebug ("InitOutput - Returning.\n");
-#endif
-}
-
-
-/*
- * winCheckDisplayNumber - Check if another instance of Cygwin/X is
- * already running on the same display number.  If no one exists,
- * make a mutex to prevent new instances from running on the same display.
- *
- * return FALSE if the display number is already used.
- */
-
-static Bool
-winCheckDisplayNumber ()
-{
-  int			nDisp;
-  HANDLE		mutex;
-  char			name[MAX_PATH];
-  char *		pszPrefix = '\0';
-  OSVERSIONINFO		osvi = {0};
-
-  /* Check display range */
-  nDisp = atoi (display);
-  if (nDisp < 0 || nDisp > 65535)
-    {
-      ErrorF ("winCheckDisplayNumber - Bad display number: %d\n", nDisp);
-      return FALSE;
-    }
-
-  /* Set first character of mutex name to null */
-  name[0] = '\0';
-
-  /* Get operating system version information */
-  osvi.dwOSVersionInfoSize = sizeof (osvi);
-  GetVersionEx (&osvi);
-
-  /* Want a mutex shared among all terminals on NT > 4.0 */
-  if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT
-      && osvi.dwMajorVersion >= 5)
-    {
-      pszPrefix = "Global\\";
-    }
-
-  /* Setup Cygwin/X specific part of name */
-  snprintf (name, sizeof(name), "%sCYGWINX_DISPLAY:%d", pszPrefix, nDisp);
-
-  /* Windows automatically releases the mutex when this process exits */
-  mutex = CreateMutex (NULL, FALSE, name);
-  if (!mutex)
-    {
-      LPVOID lpMsgBuf;
-
-      /* Display a fancy error message */
-      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | 
-		     FORMAT_MESSAGE_FROM_SYSTEM | 
-		     FORMAT_MESSAGE_IGNORE_INSERTS,
-		     NULL,
-		     GetLastError (),
-		     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-		     (LPTSTR) &lpMsgBuf,
-		     0, NULL);
-      ErrorF ("winCheckDisplayNumber - CreateMutex failed: %s\n",
-	      (LPSTR)lpMsgBuf);
-      LocalFree (lpMsgBuf);
-
-      return FALSE;
-    }
-  if (GetLastError () == ERROR_ALREADY_EXISTS)
-    {
-      ErrorF ("winCheckDisplayNumber - "
-	      PROJECT_NAME " is already running on display %d\n",
-	      nDisp);
-      return FALSE;
-    }
-
-  return TRUE;
-}
-
-#ifdef DPMSExtension
-Bool DPMSSupported(void)
-{
-  return FALSE;
-}
-
-void DPMSSet(int level)
-{
-  return;
-}
-
-int DPMSGet(int *plevel)
-{
-  return 0;
-}
-#endif
diff --git a/hw/xwin/Makefile.am b/hw/xwin/Makefile.am
deleted file mode 100644
index 5ffba12..0000000
--- a/hw/xwin/Makefile.am
+++ /dev/null
@@ -1,197 +0,0 @@
-bin_PROGRAMS = XWin
-
-if XWIN_CLIPBOARD
-SRCS_CLIPBOARD = \
-	winclipboardinit.c \
-	winclipboardtextconv.c \
-	winclipboardthread.c \
-	winclipboardunicode.c \
-	winclipboardwndproc.c \
-	winclipboardwrappers.c \
-	winclipboardxevents.c
-DEFS_CLIPBOARD = -DXWIN_CLIPBOARD
-endif
-
-if XWIN_GLX_WINDOWS
-SRCS_GLX_WINDOWS = \
-	winpriv.c
-DEFS_GLX_WINDOWS = -DXWIN_GLX_WINDOWS
-endif
-
-if XWIN_MULTIWINDOW
-SRCS_MULTIWINDOW = \
-	winmultiwindowshape.c \
-	winmultiwindowwindow.c \
-	winmultiwindowwm.c \
-	winmultiwindowwndproc.c
-DEFS_MULTIWINDOW = -DXWIN_MULTIWINDOW
-endif
-
-if XWIN_MULTIWINDOWEXTWM
-SRCS_MULTIWINDOWEXTWM = \
-	winwin32rootless.c \
-	winwin32rootlesswindow.c \
-	winwin32rootlesswndproc.c \
-	winwindowswm.c
-DEFS_MULTIWINDOWEXTWM = -DXWIN_MULTIWINDOWEXTWM
-endif
-
-if XWIN_NATIVEGDI
-SRCS_NATIVEGDI = \
-	winclip.c \
-	winfillsp.c \
-	winfont.c \
-	wingc.c \
-	wingetsp.c \
-	winnativegdi.c \
-	winpixmap.c \
-	winpolyline.c \
-	winpushpxl.c \
-	winrop.c \
-	winsetsp.c
-DEFS_NATIVEGDI = -DXWIN_NATIVEGDI
-endif
-
-if XWIN_PRIMARYFB
-SRCS_PRIMARYFB = \
-	winpfbdd.c
-DEFS_PRIMARYFB = -DXWIN_PRIMARYFB
-endif
-
-if XWIN_RANDR
-SRCS_RANDR = \
-	winrandr.c
-DEFS_RANDR = -DXWIN_RANDR
-endif
-
-if XWIN_XV
-SRCS_XV = \
-	winvideo.c
-DEFS_XV = -DXWIN_XV
-endif
-
-SRCS =	InitInput.c \
-	InitOutput.c \
-	winallpriv.c \
-	winauth.c \
-	winblock.c \
-	wincmap.c \
-	winconfig.c \
-	wincreatewnd.c \
-	wincursor.c \
-	windialogs.c \
-	winengine.c \
-	winerror.c \
-	winglobals.c \
-	winkeybd.c \
-	winkeyhook.c \
-	winmisc.c \
-	winmouse.c \
-	winmsg.c \
-	winmultiwindowclass.c \
-	winmultiwindowicons.c \
-	winprefs.c \
-	winprefsyacc.y \
-	winprefslex.l \
-	winprocarg.c \
-	winregistry.c \
-	winscrinit.c \
-	winshaddd.c \
-	winshadddnl.c \
-	winshadgdi.c \
-	wintrayicon.c \
-	winvalargs.c \
-	winwakeup.c \
-	winwindow.c \
-	winwndproc.c \
-	ddraw.h \
-	winclipboard.h \
-	winconfig.h \
-	win.h \
-	winkeybd.h \
-	winkeymap.h \
-	winkeynames.h \
-	winlayouts.h \
-	winmessages.h \
-	winmsg.h \
-	winms.h \
-	winmultiwindowclass.h \
-	winprefs.h \
-	winpriv.h \
-	winresource.h \
-	winwindow.h \
-	$(top_srcdir)/mi/miinitext.c \
-	$(top_srcdir)/fb/fbcmap.c \
-	$(SRCS_CLIPBOARD) \
-	$(SRCS_GLX_WINDOWS) \
-	$(SRCS_MULTIWINDOW) \
-	$(SRCS_MULTIWINDOWEXTWM) \
-	$(SRCS_NATIVEGDI) \
-	$(SRCS_PRIMARYFB) \
-	$(SRCS_RANDR) \
-	$(SRCS_XV)
-
- DEFS = $(DEFS_CLIPBOARD) \
-	$(DEFS_GLX_WINDOWS) \
-	$(DEFS_MULTIWINDOW) \
-	$(DEFS_MULTIWINDOWEXTWM) \
-	$(DEFS_NATIVEGDI) \
-	$(DEFS_PRIMARYFB) \
-	$(DEFS_RANDR) \
-	$(DEFS_XV)
-
-XWin_SOURCES = $(SRCS)
-
-INCLUDES = -I$(top_srcdir)/miext/rootless \
-           -I$(top_srcdir)/miext/rootless/safeAlpha
-
-XWIN_LIBS = \
-	$(top_builddir)/fb/libfb.la \
-	$(XSERVER_LIBS)
-
-XWin_DEPENDENCIES = $(XWIN_LIBS)
-XWin_LDADD = $(XWIN_LIBS) $(XSERVER_SYS_LIBS) $(XWIN_SYS_LIBS)
-
-XWin_LDFLAGS = -mwindows -static
-
-winprefsyacc.h: winprefsyacc.c
-winprefslex.c: winprefslex.l winprefsyacc.c winprefsyacc.h
-
-BUILT_SOURCES = winprefsyacc.h winprefsyacc.c winprefslex.c
-CLEANFILES = $(BUILT_SOURCES)
-
-AM_YFLAGS = -d
-AM_LFLAGS = -i
-AM_CFLAGS = -DHAVE_XWIN_CONFIG_H $(DIX_CFLAGS) \
-            $(XWINMODULES_CFLAGS)
-
-dist_man1_MANS = XWin.man XWinrc.man
-
-EXTRA_DIST = \
-	_usr_X11R6_lib_X11_system.XWinrc \
-	X-boxed.ico \
-	X.ico \
-	XWin.rc \
-	xlaunch/config.cc \
-	xlaunch/COPYING \
-	xlaunch/main.cc \
-	xlaunch/resources/dialog.rc \
-	xlaunch/resources/fullscreen.bmp \
-	xlaunch/resources/images.rc \
-	xlaunch/resources/multiwindow.bmp \
-	xlaunch/resources/nodecoration.bmp \
-	xlaunch/resources/resources.h \
-	xlaunch/resources/resources.rc \
-	xlaunch/resources/strings.rc \
-	xlaunch/resources/windowed.bmp \
-	xlaunch/window/dialog.cc \
-	xlaunch/window/dialog.h \
-	xlaunch/window/util.cc \
-	xlaunch/window/util.h \
-	xlaunch/window/window.cc \
-	xlaunch/window/window.h \
-	xlaunch/window/wizard.cc \
-	xlaunch/window/wizard.h
-
-relink:
-	rm -f XWin && $(MAKE) XWin
diff --git a/hw/xwin/README b/hw/xwin/README
deleted file mode 100644
index 219fd13..0000000
--- a/hw/xwin/README
+++ /dev/null
@@ -1,141 +0,0 @@
-Cygwin/X Release Notes
-======================
-
-Release X11R6.7
-===============
-
-Cygwin/X has continued its rapid pace of development that it has sustained
-since Spring 2001 and this release shows it, we now have: a stable and fast
-multi-window mode, seamless clipboard integration, a configurable tray menu
-icon, popups on error messages pointing users to the log file and our mailing
-list, the beginnings of indirect 3D acceleration for OpenGL applications,
-improved non-US keyboard and clipboard support, and only a handful of bugs
-that continue to be reported.
-
-Between the XFree86 4.3.0 release and the X.Org X11R6.7 release the Cyg-
-win/XFree86 project broke away from The XFree86 Project, Inc. due to a lack
-of support from the XFree86 project.  As such, the Cygwin/XFree86 project was
-renamed to the Cygwin/X project and the upstream source code tree that Cyg-
-win/X pulls from and pushes to is now the tree managed by the X.Org Founda-
-tion.  The Cygwin/X project has seen a rush of development and interest in
-the project since the split; one metric showing this is that the number of
-CVS committers we have has gone from zero to six.
-
-The most outstanding features of this release are
-
-   o Major multi-window mode improvements. (Takuma Murakami, Earle F. 
-     Philhower III)
-
-   o Initial work of accelerated OpenGL using the windows OpenGL drivers. 
-     (Alexander Gottwald)
-
-   o Massive rework of clipboard integration with windows. (Harold L Hunt II,
-     Kensuke Matsuzaki)
-
-   o Improved Japanese clipboard and keyboard support. (Kensuke Matsuzaki,
-     Takuma Murakami, Alexander Gottwald)
-
-   o Customizable tray menu icon allowing shortcuts to start programs,
-     etc.(Earle F. Philhower III)
-
-   o New icons. (Jehan Bing, Michael Bax, Benjamin Rienfenstahl)
-
-   o Fix some multi-monitor problems.(Takuma Murakami)
-
-   o Fix repeated key strokes. (Ivan Pascal)
-
-   o Automatic keyboard layouts for the most frequently used keyboard lay-
-     outs. (Alexander Gottwald)
-
-   o Built in SHM support with detection of the SHM engine (cygserver).
-     (Ralf Habacker, Harold L Hunt II)
-
-   o Merged in work on the NativeGDI engine. (Alan Hourihane)
-
-OpenGL with Cygwin/X
-====================
-
-Cygwin/X has supported GLX only with software rendering provided by the Mesa
-library. Starting with X11R6.7 we add support for hardware accelerated OpenGL.
-
-This support is still under development and still has some bigger problems. 
-To provide both versions (the stable software rendering and the new hardware
-accelerated) we ship to binaries. XWin.exe contains the software rendering 
-and XWin_GL.exe uses the hardware acceleration provided by the windows drivers.
-
-The known problems with hardware accelerated OpenGL are:
-
-   o Only multiwindow mode is useful. In the other modes the OpenGL output 
-     does not align with the X11 windows.
-
-   o Using two programs which require different visuals will fail. For example
-     glxgears and glxinfo will not work without restarting XWin_GL.exe.
-
-   o OpenGL extensions and functions from OpenGL 1.2 and later should work 
-     but are not completely tested.
-
-   o The standard Windows OpenGL driver will produce no output. Use the one 
-     from your video adapter vendor.  
-
-If you notice problems with some programs please send a message with the 
-logfile /tmp/XWin.log and a short error description to <cygwin-xfree at cygwin.com>
-
-The hardware accelerated OpenGL was tested using: 
-
-   o glxgears
-   o glxinfo
-   o blender
-   o tuxkart
-   o GLUT demos (some did fail)
-   o tuxracer (currently not working)
-
-    
-Release X11R6.8
-===============
-
-Having reached a quite mature state in release X11R6.7 the development 
-has slowed down a little bit. Some of the former active developers have
-retired or cut their work for the Cygwin/X project due to conflicts with 
-job, study and family. 
-
-The X11R6.8 release now includes major improvements from the xserver project.
-This includes the XFixes, Damage, Composite and XEVIE extension which is a 
-major step towards allowing Cygwin/X to have real transparency. 
-
-But at the current state Composite is not working with Cygwin/X. Not all code
-in the Cygwin/X Server has been updated to support the Composite feature and
-using it will even crash the xserver. But as a second problem nearly all
-functions required for compositing are lacking acceleration in Cygwin/X so
-the feature would not be very useful if it would work. So it is disabled by
-default. 
-
-OpenGL with Cygwin/X
-====================
-
-The OpenGL support has lost some of it's limitations from the last release 
-and should be much more stable. But due to missing wide spread testing in 
-the community it is still available in a separate program. XWin still uses 
-the old software OpenGL which is known to be stable.
-
-The known problems with hardware accelerated OpenGL are:
-
-   o Only multiwindow mode is useful. In the other modes the OpenGL output 
-     does not align with the X11 windows.
-
-   o OpenGL extensions and functions from OpenGL 1.2 and later should work 
-     but are not completely tested.
-
-   o The standard Windows OpenGL driver will produce no output. Use the one 
-     from your video adapter vendor.  
-
-If you notice problems with some programs please send a message with the 
-logfile /tmp/XWin.log and a short error description to <cygwin-xfree at cygwin.com>
-
-The hardware accelerated OpenGL was tested using: 
-
-   o glxgears
-   o glxinfo
-   o blender
-   o tuxkart
-   o GLUT demos (some did fail)
-
diff --git a/hw/xwin/X-boxed.ico b/hw/xwin/X-boxed.ico
deleted file mode 100755
index 0727042..0000000
Binary files a/hw/xwin/X-boxed.ico and /dev/null differ
diff --git a/hw/xwin/X.ico b/hw/xwin/X.ico
deleted file mode 100644
index d47168f..0000000
Binary files a/hw/xwin/X.ico and /dev/null differ
diff --git a/hw/xwin/XWin.man b/hw/xwin/XWin.man
deleted file mode 100644
index 4e70c19..0000000
--- a/hw/xwin/XWin.man
+++ /dev/null
@@ -1,287 +0,0 @@
-.TH XWIN 1 __vendorversion__
-.SH NAME
-XWin \- X Server for the Cygwin environment on Microsoft Windows
-
-
-.SH SYNOPSIS
-.B XWin
-[ options ] ...
-
-
-.SH DESCRIPTION
-.I XWin is an X Server for the X Window System on the Cygwin environment
-running on Microsoft Windows.
-
-
-.SH MODES
-\fIXWin\fP can operate in five different and incompatible modes:
-.br
-* \fISingle Window\fP: This is the default option.  The X server
-appears as a single Windows window and all X windows are contained
-within this window.  This mode requires an external window manager.
-.br
-* \fINo Decoration\fP: This mode is like single window mode except
-that the X server window does not have a title bar or border, thus
-maximizing the amount of space available for X windows within the X
-server window.  This mode requires an external window manager.
-.br
-* \fIFull Screen\fP: This mode is like single window mode except that
-the X server window takes the full screen, covering completely the
-Windows desktop.  This mode requires an external window manager.
-.br
-* \fIRootless\fP: The X server works on a window covering the whole
-screen but the root window (traditionally covered with an X hatch
-pattern) is hidden from view.  This mode requires an external window
-manager.
-.br
-* \fIMulti-Window\fP: In this mode \fIXWin\fP uses its own integrated
-window manager in order to handle the top-level X windows, in such a
-way that they appear as normal Windows windows.
-.PP
-NOTE: \fIMulti-Window\fP mode will crash if an external window manager
-such as \fItwm\fP or \fIfvwm\fP is launched since \fIMulti-Window\fP
-uses its own internal window manager; all other modes require an
-external window manager in order to move, resize, and perform other
-operations on the individual X windows.
-
-
-.SH LOG
-As it runs \fIXWin\fP writes messages indicating the most relevant events
-to  the console
-from which it was called and to a log file that by default is located at
-\fI/tmp/XWin.log\fP.  This file is mainly for debugging purposes.
-
-
-.SH PREFERENCES FILE
-On startup \fIXWin\fP looks for the file \fI$HOME/.XWinrc\fP or, if
-the previous file does not exist,
-\fI/usr/X11R6/lib/X11/system.XWinrc\fP.  \fI.XWinrc\fP allows setting
-preferences for the following:
-.br
-1- To include items into the menu associated with the \fIXWin\fP icon
-which is in the \fIWindows\fP system tray.  This functions in all
-modes that have a tray icon.
-.br
-2- To include items in the menu which is associated with the Windows
-window that \fIXWin -multiwindow\fP produces for each top-level X
-window.  That can be done both for the generic case and for particular
-programs.
-.br
-3- To change the icon that is associated to the Windows window that
-\fIXWin -multiwindow\fP produces for each top-level X-window.  Again,
-that can be done both for the generic case and for particular
-programs.
-.PP
-The format of the \fI.XWinrc\fP file is given in the man page XWinrc(5).
-
-
-.SH OPTIONS
-In addition to the normal server options described in the \fIXserver(1)\fP
-manual page, \fIXWin\fP accepts the following command line switches,
-\fIall\fP of which are optional:
-.TP 8
-.B \-clipboard
-Enables the integration
-between the Cygwin/X clipboard and Windows clipboard.  Do not use in
-conjunction with the \fIxwinclip\fP program.
-.TP 8
-.B "\-clipupdates \fInum_boxes\fP"
-Specify an optional threshold, above which the boxes in a shadow
-update operation will be collected into a GDI clipping region.  The
-clipping region is then used to do a single bit block transfer that is
-constrained to the updated area by the clipping region.  There is some
-overhead involved in creating, installing, destroying, and removing
-the clipping region, thus there may not be much benefit for a small
-number of boxes (less than 10).  It is even possible that this
-functionality does not provide a benefit at any number of boxes; we
-can only determine the usefulness of this feature through testing.
-This parameter works in conjunction with engines 1, 2, and 4 (Shadow
-GDI, Shadow DirectDraw, and Shadow DirectDraw Non-Locking,
-respectively).
-.TP 8
-.B "\-emulate3buttons \fItimeout\fP"
-Emulate a three button mouse; pressing both buttons within
-.I timeout
-milliseconds causes an emulated middle button press.  The default 
-.I timeout
-is 50 milliseconds.  Note that most mice with scroll wheel have middle
-button functionality, usually you will need this option only if you have
-a two button mouse without scroll wheel.
-.TP 8
-.B \-emulatepseudo
-Create a depth 8 PseudoColor visual when running in depths 15, 16, 24,
-or 32, collectively known as TrueColor depths.
- At this date (April 2004) this option is not still operative.
-.TP 8
-.B "\-engine \fIengine_type_id\fP"
-This option, which is intended for Cygwin/X developers,
-overrides the server's automatically supported engine type.  This
-parameter will be ignored if the specified engine type is not
-supported on the current system.  The supported engine type ids are 1
-- Shadow GDI, 2 - Shadow DirectDraw, and 4 - Shadow DirectDraw4.
-Additionally, there is a barely functional experimental engine type id
-16 - Native GDI.
-.TP 8
-.B "\-fullscreen [-depth \fIdepth\fP] [-refresh \fIrate_in_Hz\fP]"
-Run the server in fullscreen mode, as opposed to the default windowed
-mode.
-.TP 8
-.B "\-depth \fIdepth\fP"
-Specify the color depth, in bits per pixel, to use when running in
-fullscreen with a DirectDraw engine.  This parameter is ignored if
-\fB\-fullscreen\fP is not specified.
-.TP 8
-.B "\-refresh \fIrate_in_Hz\fP"
-Specify an optional refresh rate to use when running in
-fullscreen with a DirectDraw engine.  This parameter is ignored if
-\fB\-fullscreen\fP is not specified.
-.TP 8
-.B \-help
-Write a help text to the console and to the log file.
-.TP 8
-.B \-ignoreinput
-Ignore keyboard and mouse input.  This is usually only used for testing
-and debugging purposes.
-.TP 8
-.B \-[no]keyhook
-Enable [disable] a low-level keyboard hook for catching
-special key combinations like Alt+Tab and passing them to the X
-Server instead of letting \fIWindows\fP handle them.
-.TP 8
-.B \-lesspointer
-Hide the Windows mouse cursor when the mouse is over any Cygwin/X
-window (regardless of whether that window is active or inactive).  This
-prevents the Windows mouse cursor from being placed overtop of the X
-cursor.
-.TP 8
-.B "\-logfile \fIFile_Name\fP"
-Change the log file from the default located at \fI/tmp/XWin.log\fP to
-the one indicated by \fIFile_Name\fP.
-.TP 8
-.B "\-logverbose \fIlevel\fP"
-Control the degree of verbosity of the log messages with the integer
-parameter \fIlevel\fP.  For \fIlevel\fP=0 only fatal errors are
-reported, for \fIlevel\fP=1 (default) simple information about
-configuration is also given, for \fIlevel\fP=2 a detailed log
-information (including trace and debug output) is produced.  Bigger
-values will yield a still more detailed debug output.  At this date
-(April 2004) the option is still not fully operative; the default
-value is 2 and the output is insensitive to the level value.
-.TP 8
-.B \-multimonitors
-Create a root window that covers all monitors on a system with
-multiple monitors.
-.TP 8
-.B \-multiwindow
-Start the integrated \fIWindowsi\fP-based window manager, which launches each
-top-level X window in its own \fIWindows\fP window.  Not to be used together
-with \fB\-rootless\fP nor \fB\-fullscreen\fP.
-.TP 8
-.B \-nodecoration
-Do not give the Cygwin/X window a Windows window border, title bar,
-etc.  This parameter only applies to windowed mode screens, i.e., this
-parameter is ignored when the \fB\-fullscreen\fP parameter is specified.
-.TP 8
-.B \-nounicodeclipboard
-Do not use Unicode clipboard even if NT-based platform.
-.TP 8
-.B \-rootless
-Run the server in rootless mode.  Not to be used with \fB\-multiwindow\fP
-nor with \fB\-fullscreen\fP.
-.TP 8
-.B "\-screen \fIscreen_number\fP \fIwidth\fP \fIheight\fP"
-This parameter may be used to specify the
-.I screen_number,
-.I height,
-and
-.I width
-of one or several Cygwin/X screens; each Cygwin/X screen will be
-opened in its own window.  When using multiple screens, be sure not to
-duplicate any screen numbers.
-.I XWin
-default behavior is to create a single screen that is roughly
-the size of the current Windows display area.
-Screen specific parameters, such as \fB\-fullscreen\fP, can be applied as a
-default to all screens by placing those screen specific parameters
-before any \fB\-screen\fP parameter.  Screen specific parameters placed after
-the first \fB\-screen\fP parameter will apply only to the immediately
-preceeding \fB\-screen\fP parameter.
-.TP 8
-.B \-scrollbars
-In windowed mode, allow screens bigger than the Windows desktop.
-Moreover, if the window has decorations, one can now resize it.
-.TP 8
-.B \-[no]trayicon
-Do not create a tray icon.  Default is to create one
-icon per screen.  You can globally disable tray icons with
-\fB\-notrayicon\fP, then enable it for specific screens with
-\fB\-trayicon\fP for those screens.
-.TP 8
-.B \-[no]unixkill
-Enable or disable the \fICtrl-Alt-Backspace\fP key combination as a
-signal to exit the X Server.  The \fICtrl-Alt-Backspace\fP key combination
-is disabled by default.
-.TP 8
-.B \-[no]winkill
-Enable or disable the \fIAlt-F4\fP key combination as a signal to exit the
-X Server.
-The \fIAlt-F4\fP key combination is enabled by default.
-.TP 8
-.B \-swcursor
-Disable the usage of the windows cursor and use the X11 software cursor instead.
-.B \-silent-dup-error
-If another instance of XWin is found running, exit silently and don't display 
-the error messge.
-.TP 8
-.B "\-xkblayout \fIlayout\fP"
-.TP 8
-.B "\-xkbmodel \fImodel\fP"
-.TP 8
-.B "\-xkboptions \fIoption\fP"
-.TP 8
-.B "\-xkbrules \fIrule\fP"
-.TP 8
-.B "\-xkbvariant \fIvariant\fp"
-These options implement the xkeyboard extension for loading
-a particular keyboard map as the X server starts.  The behavior is similar
-to the \fIsetxkbmap\fP program.  The layout data is located at
-\fI/usr/X11R6/lib/X11/xkb/\fP.  Additional information is found in the
-README files therein and in the man page of \fIsetxkbmap\fP.  For example
-in order to load a German layout for a pc105 keyboard one uses
-the options:
-.br
-.I " \-xkblayout de \-xkbmodel pc105"
-.PP
-Alternatively one may use the \fIsetxkbmap\fP program after XWin is
-running or even the \fIxmodmap\fP program for loading the old-style
-keyboard maps.
-
-
-.SH "SEE ALSO"
-X(__miscmansuffix__), Xserver(1), xdm(1), xinit(1), XWinrc(1), setxkbmap(1)
-
-
-.SH BUGS
-.I XWin
-and this man page still have many limitations.  Some of the more obvious
-ones are:
-.br
-- The display mode can not be changed once the X server has started.
-.br
-- The XWin software is developing rapidly; it is therefore likely that
-this man page is not up to date.  It is always prudent to 
-look also at the output of \fIXWin -help\fP and to the Cygwin/X User Guide
-at /usr/share/doc/cygwin-x-doc-x.x.x/ug/cygwin-x-ug.xxx in order to
-check the options that are operative.
-
-
-.SH AUTHORS
-This list is by no means complete, but direct contributors to the
-Cygwin/X project include (in alphabetical order by last name): Stuart
-Adamson, Michael Bax, Jehan Bing, Lev Bishop, Dr. Peter Busch, Biju G
-C, Robert Collins, Nick Crabtree, Early Ehlinger, Christopher Faylor,
-John Fortin, Brian Genisio, Fabrizio Gennari, Alexander Gottwald, Ralf
-Habacker, Colin Harrison, Matthieu Herrb, Alan Hourihane, Pierre A
-Humblet, Harold L Hunt II, Dakshinamurthy Karra, Kensuke Matsuzaki,
-Takuma Murakami, Earle F. Philhower III, Benjamin Riefenstahl, Suhaib
-Siddiqi, Jack Tanner, and Nicholas Wourms.
diff --git a/hw/xwin/XWin.rc b/hw/xwin/XWin.rc
deleted file mode 100644
index 749c0f5..0000000
--- a/hw/xwin/XWin.rc
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- *Copyright (C) 2002-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#include "windows.h"
-#include "winresource.h"
-
-/*
- * Dialogs
- */
-
-/* About */
-ABOUT_BOX DIALOG DISCARDABLE  32, 32, 240, 105
-STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_TABSTOP  | DS_CENTERMOUSE
-CAPTION "About " PROJECT_NAME
-FONT 8, "MS Sans Serif"
-BEGIN
-  CONTROL               PROJECT_NAME " Website", ID_ABOUT_WEBSITE, "Button",
-                        BS_OWNERDRAW | WS_TABSTOP, 30, 45, 75, 15
-  CONTROL               "Change Log", ID_ABOUT_CHANGELOG, "Button",
-                        BS_OWNERDRAW | WS_TABSTOP, 135, 45, 75, 15
-  CONTROL               "User's Guide", ID_ABOUT_UG, "Button",
-                        BS_OWNERDRAW | WS_TABSTOP, 30, 65, 75, 15
-  CONTROL               "FAQ", ID_ABOUT_FAQ, "Button",
-                        BS_OWNERDRAW | WS_TABSTOP, 135, 65, 75, 15
-
-  DEFPUSHBUTTON		"Dismiss", IDOK, 95, 85, 50, 15
-
-  CTEXT			"Welcome to the preliminary About box for the " PROJECT_NAME " X Server.  This dialog was created on 2004/03/25 and will eventually be filled with more useful information.  For now, use the links below to learn more about the " PROJECT_NAME " project.", IDC_STATIC, 5, 5, 230, 35
-END
-
-
-/* Depth change */
-
-DEPTH_CHANGE_BOX DIALOG DISCARDABLE	32, 32, 180, 100
-STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | DS_CENTERMOUSE
-FONT 8, "MS Sans Serif"
-CAPTION PROJECT_NAME
-BEGIN
-  DEFPUSHBUTTON		"Dismiss", IDOK, 66, 80, 50, 14
-  CTEXT			PROJECT_NAME, IDC_STATIC, 40, 12, 100, 8
-  CTEXT			"Disruptive screen configuration change.", IDC_STATIC, 7, 40, 166, 8
-  CTEXT			"Restore previous resolution to use " PROJECT_NAME ".", IDC_STATIC, 7, 52, 166, 8
-END
-
-
-/* Exit */
-
-EXIT_DIALOG DIALOG DISCARDABLE	32, 32, 180, 78
-STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_TABSTOP | DS_CENTERMOUSE
-FONT 8, "MS Sans Serif"
-CAPTION PROJECT_NAME " - Exit?"
-BEGIN
-  PUSHBUTTON "E&xit", IDOK, 55, 56, 30, 14
-  DEFPUSHBUTTON "&Cancel", IDCANCEL, 95, 56, 30, 14
-  CTEXT "Exiting will close all screens running on this display.", IDC_STATIC, 7, 12, 166, 8
-  CTEXT "No information about connected clients available.", IDC_CLIENTS_CONNECTED, 7, 24, 166, 8
-  CTEXT "Proceed with shutdown of this display/server?", IDC_STATIC, 7, 36, 166, 8
-END
-
-
-/*
- * Menus
- */
-
-IDM_TRAYICON_MENU MENU DISCARDABLE
-BEGIN
-	POPUP "TRAYICON_MENU"
-	BEGIN
-		MENUITEM "&Hide Root Window", ID_APP_HIDE_ROOT
-		MENUITEM "&About...", ID_APP_ABOUT
-		MENUITEM SEPARATOR
-		MENUITEM "E&xit", ID_APP_EXIT
-	END
-END
-
-
-/*
- * Icons
- */
-
-IDI_XWIN		ICON	DISCARDABLE	"X.ico"
-IDI_XWIN_BOXED		ICON	DISCARDABLE	"X-boxed.ico"
diff --git a/hw/xwin/XWinrc.man b/hw/xwin/XWinrc.man
deleted file mode 100755
index eba3fb6..0000000
--- a/hw/xwin/XWinrc.man
+++ /dev/null
@@ -1,180 +0,0 @@
-.TH XWIN 5 __vendorversion__
-
-
-.SH NAME
-XWinrc\- XWin Server Resource Configuration File.
-
-
-.SH DESCRIPTION
-The X Server for the X Window System on the Cygwin/X environment
-running on Microsoft Windows, \fIXWin\fP can be optionally configured
-with the \fIXWinrc\fP file.  A system-wide configuration file should
-be placed in \fI/usr/X11R6/lib/X11/system.XWinrc\fP, a per-user file
-should be put at \fI$HOME/.XWinrc\fP.  The \fIsystem.XWinrc\fP file is
-read only if no \fI$HOME/.XWinrc\fP exist.
-.PP
-With the \fI.XWinrc\fP configuration file it is possible to do the
-following:
-.PP
-1- To include items into the menu associated with the \fIXWin\fP icon
-which is in the \fIWindows\fP system tray.  This feature functions in
-all XWin modes that have such tray icon.
-.PP
-2- To include items into the menu which is associated with the
-\fIWindows\fP window that \fIXWin -multiwindow\fP produces for each
-top-level X-window.  That can be done both for the generic case and
-for particular programs.
-.PP
-3- To change the icon that is associated to the \fIWindows\fP window
-that \fIXWin -multiwindow\fP produces for each top-level X-window.
-Again, that can be done both for the generic case and for particular
-programs.  The new icons associated should be \fIWindows\fP format
-icons \fI.ico\fP.
-
-
-.SH FILE FORMAT
-.B Keywords
-are case insensitive, but in this document they will be written
-completely capitalized.
-.PP
-.B Comments
-are legal pretty much anywhere you can have an end-of-line; they
-begin with "#" or "//" and go to the end-of-line.
-.PP
-Quote marks in strings are optional unless the string has included spaces.
-.PP
-There are three kinds of instructions: miscellaneous, menu, and icon.
-
-
-.SH Miscellaneous instruction
-.TP 8
-.B DEBUG \fIString\fP
-The \fIString\fP is printed to the XWin.log file.
-
-.TP 8
-.B TRAYICON \fIicon-specifier\fB
-The \fBTRAYICON\fP keyword changes the icon \fIXWin\fP displays in the
-system tray area.
-
-.TP 8
-.B SILENTEXIT
-The \fBSILENTEXIT\fP keyword, which takes no parameters, disables the
-exit confirmation dialog.
-
-
-.SH Menu instructions
-.TP 8
-.B MENU \fIMenu_Name\fP {
-.br
-.B       \fIMenu_Item_Line\fP
-.br
-.B       \fIMenu_Item_Line\fP
-.br
-.B        \fI...\fP
-.br
-.B }
-.br
-This instruction defines a menu and asigns a \fIMenu_Name\fP to it.
-\fIMenu_Item_Line\fP are lines  of any of the following types:
-.TP 8
-.B \t SEPARATOR
-.TP 8
-.B  \t \fIItem_Label\fP  EXEC \fICommand\fP
-.TP 8
-.B \t \fIItem_Label\fP  MENU \fIpreviously-defined-menu-name\fP
-.TP 8
-.B \t \fIItem_Label\fP  ALWAYSONTOP
-.TP 8
-.B \t \fIItem_Label\fP  RELOAD
-.br
-The \fIItem_Label\fP is the string that is written in the menu item.
-.br
-\fICommand\fP is a string with the command that will be executed by /bin/sh.
-Here paths should be \fICYGWIN\fP style (e.g. /usr/local/bin/myprogram).
-A string "%display%" appearing in the \fICommand\fP will be replaced
-with the proper display variable (i.e. 127.0.0.1:<display>.0).
-.br
-\fBALWAYSONTOP\fP sets the window to which the menu is associated to
-display above all others.
-.br
-\fBRELOAD\fP causes the XWinrc file to be reloaded and icons and menus
-regenerated.
-.TP 8
-.B ROOTMENU \fIpreviously-defined-menu-name\fP
-Includes the items in the indicated menu into the menu associated with
-\fIXWin\fP that appears in the system tray.
-.TP 8
-.B DEFAULTSYSMENU \fIpreviously-defined-menu-name\fP ATSTART|ATEND
-Includes the items in the indicated menu into the menu associated with
-generic top-level X-Windows in the \fIXWin\fP \fImultiwindow\fP mode.  The
-keywords \fBATSTART\fP and \fBATEND\fP indicate if such items should be
-included at the start or at the end of the menu.
-.TP 8
-.B SYSMENU {
-  \fIclass-or-name-of-window\fP \fIdefined-menu-name\fP \fBATSTART|ATEND\fP
-.br
-  \fI...\fP
-.br
-  \fB}\fP
-.br
-Associates a specific menu to a specific WM_CLASS or WM_NAME.
-
-
-.SH Icon Instructions
-When specifying an \fIicon-file\fP in the following commands several different formats are allowed:
-.br
-\fB"NAME.ICO"\fP\fI of an .ico format file\fP
-.br
-\t \t ("cygwin.ico", "apple.ico")
-.br
-\fB"NAME.DLL,nn"\fP\fI of a .DLL and icon index\fP
-.br
-\t \t ("c:\\windows\\system32\\shell32.dll,4" is the default folder icon)
-.br
-\fB",nn"\fP\fI index into XWin.EXE internal ICON resources\fP
-.br
-\t \t (",101" is the 1st icon inside \fIXWin.EXE\fP)
-.TP 8
-.B ICONDIRECTORY \fIWindows-path-to-icon-directory\fP
-Defines the default directory to search for \ficon-file\fP files.
-It should be a \fIWindows\fP style path (e.g. C:\\cygwin\\usr\\local\\icons).
-.TP 8
-.B DEFAULTICON \fIicon-file\fP
-Defines a replacement for the standard X icon for applications without
-specified icons.
-.TP 8
-.B ICONS {
-.br
- \fIclass-or-name-of-window\fP \fIicon-file\fP
-.br
-  \fI...\fP
-.br
-  \fB}\fP
-.br
-Defines icon replacements windows matching the specified window class or names.
-If multiple name or class matches occur for a window, only the first one
-will be used.
-
-
-.SH EXAMPLE
-.TP 8
-This example adds an Xterm menu item to the system tray icon
-\fBMENU systray {
-.br
-\t xterm  EXEC "xterm -display %display% -sb -sl 999"
-.br
-\t SEPARATOR
-.br
-}
-.br
-ROOTMENU systray
-\fP
-
-
-.SH "SEE ALSO"
- XWin(1)
-
-
-.SH AUTHOR
-The XWinrc feature of XWin was written primarily by Earle F. Philhower
-III.
diff --git a/hw/xwin/_usr_X11R6_lib_X11_system.XWinrc b/hw/xwin/_usr_X11R6_lib_X11_system.XWinrc
deleted file mode 100644
index d9c2d42..0000000
--- a/hw/xwin/_usr_X11R6_lib_X11_system.XWinrc
+++ /dev/null
@@ -1,125 +0,0 @@
-# XWin Server Resource File - EXAMPLE
-# Earle F. Philhower, III
-
-# Place in ~/.XWinrc or in /usr/X11R6/lib/X11/system.XWinrc
-
-# Keywords are case insensitive, comments legal pretty much anywhere
-# you can have an end-of-line
-
-# Comments begin with "#" or "//" and go to the end-of-line
-
-# Paths to commands are **cygwin** based (i.e. /usr/local/bin/xcalc)
-
-# Paths to icons are **WINDOWS** based (i.e. c:\windows\icons)
-
-# Menus are defined as...
-# MENU <name> {
-#	<Menu Text>	EXEC	<command>
-#                               ^^ This command will have any "%display%"
-#                                  string replaced with the proper display
-#                                  variable (i.e. 127.0.0.1:<display>.0)
-#  or	<Menu Text>	MENU	<name-of-some-prior-defined-menu>
-#  or	<Menu Text>	ALWAYSONTOP
-#                         ^^ Sets the window to display above all others
-#  or   <Menu Text>	RELOAD
-#                         ^^ Causes ~/.XWinrc or the system.XWinrc file
-#                            to be reloaded and icons and menus regenerated
-#  or	SEPARATOR
-#       ...
-# }
-
-# Set the taskmar menu with
-# ROOTMENU <name-of-some-prior-defined-menu>
-
-# If you want a menu to be applied to all popup window's system menu
-# DEFAULTSYSMENU <name-of-some-prior-defined-menu> <atstart|atend>
-
-# To choose a specific menu for a specific WM_CLASS or WM_NAME use ...
-# SYSMENU {
-#	<class-or-name-of-window> <name-of-prior-defined-menu> <atstart|atend>
-#	...
-# }
-
-# When specifying an ICONFILE in the following commands several different
-# formats are allowed:
-# 1. Name of a regular Windows .ico format file
-#    (ex:  "cygwin.ico", "apple.ico")
-# 2. Name and index into a Windows .DLL
-#    (ex: "c:\windows\system32\shell32.dll,4" gives the default folder icon
-#         "c:\windows\system32\shell32.dll,5" gives the floppy drive icon)
-# 3. Index into XWin.EXE internal ICON resource
-#    (ex: ",101" is the 1st icon inside XWin.exe)
-
-# To define where ICO files live (** Windows path**)
-# ICONDIRECTORY	<windows-path i.e. c:\cygwin\usr\icons>
-# NOTE: If you specify a fully qualified path to an ICON below
-#             (i.e. "c:\xxx" or "d:\xxxx")
-#       this ICONDIRECTORY will not be prepended
-
-# To change the taskbar icon use...
-# TRAYICON       <name-of-windows-ico-file-in-icondirectory>
-
-# To define a replacement for the standard X icon for apps w/o specified icons
-# DEFAULTICON	<name-of-windows-ico-file-in-icondirectory>
-
-# To define substitute icons on a per-window basis use...
-# ICONS {
-#	<class-or-name-of-window> <icon-file-name.ico>
-#	...
-# }
-# In the case where multiple matches occur, the first listed in the ICONS
-# section will be chosen.
-
-# To disable exit confirmation dialog add the line containing SilentExit
-
-# DEBUG <string> prints out the string to the XWin.log file
-
-// Below are just some silly menus to demonstrate writing your
-// own configuration file.
-
-// Make some menus...
-menu apps {
-	xterm	exec	"xterm"
-	"Emacs"		exec	"emacs"
-	notepad	exec	notepad
-	xload	exec	"xload -display %display%"  # Comment
-}
-
-menu root {
-// Comments fit here, too...
-	"Reload .XWinrc"	RELOAD
-	"Applications"	menu	apps
-	SEParATOR
-}
-
-menu aot {
-	Separator
-	"Always on Top"	alwaysontop
-}
-
-menu xtermspecial {
-	"Emacs"		exec	"emacs"
-	"Always on Top"	alwaysontop
-	SepArAtor
-}
-
-RootMenu root
-
-DefaultSysMenu aot atend
-
-SysMenu {
-	"xterm"	xtermspecial atstart
-}
-
-# IconDirectory	"c:\winnt\"
-
-# DefaultIcon	"reinstall.ico"
-
-# Icons {
-# 	"xterm"	"uninstall.ico"
-# }
-
-# SilentExit
-
-DEBUG "Done parsing the configuration file..."
-
diff --git a/hw/xwin/ddraw.h b/hw/xwin/ddraw.h
deleted file mode 100644
index 2eb7c26..0000000
--- a/hw/xwin/ddraw.h
+++ /dev/null
@@ -1,2106 +0,0 @@
-#ifndef __XWIN_DDRAW_H
-#define __XWIN_DDRAW_H
-
-#include <winnt.h>
-#include <wingdi.h>
-#include <objbase.h>
-
-#if defined(NONAMELESSUNION) && !defined(DUMMYUNIONNAME1)
-#define DUMMYUNIONNAME1 u1
-#endif
-
-#define ICOM_CALL_( xfn, p, args) (p)->lpVtbl->xfn args
-
-# ifdef UNICODE
-#  define WINELIB_NAME_AW(func) func##W
-# else
-#  define WINELIB_NAME_AW(func) func##A
-# endif  /* UNICODE */
-#define DECL_WINELIB_TYPE_AW(type)  typedef WINELIB_NAME_AW(type) type;
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* defined(__cplusplus) */
-
-#ifndef	DIRECTDRAW_VERSION
-#define	DIRECTDRAW_VERSION	0x0700
-#endif /* DIRECTDRAW_VERSION */
-
-/*****************************************************************************
- * Predeclare the interfaces
- */
-DEFINE_GUID( CLSID_DirectDraw,		0xD7B70EE0,0x4340,0x11CF,0xB0,0x63,0x00,0x20,0xAF,0xC2,0xCD,0x35 );
-DEFINE_GUID( CLSID_DirectDraw7,         0x3C305196,0x50DB,0x11D3,0x9C,0xFE,0x00,0xC0,0x4F,0xD9,0x30,0xC5 );
-DEFINE_GUID( CLSID_DirectDrawClipper,	0x593817A0,0x7DB3,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xb9,0x33,0x56 );
-DEFINE_GUID( IID_IDirectDraw,		0x6C14DB80,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 );
-DEFINE_GUID( IID_IDirectDraw2,		0xB3A6F3E0,0x2B43,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xB9,0x33,0x56 );
-DEFINE_GUID( IID_IDirectDraw4,          0x9c59509a,0x39bd,0x11d1,0x8c,0x4a,0x00,0xc0,0x4f,0xd9,0x30,0xc5 );
-DEFINE_GUID( IID_IDirectDraw7,          0x15e65ec0,0x3b9c,0x11d2,0xb9,0x2f,0x00,0x60,0x97,0x97,0xea,0x5b );
-DEFINE_GUID( IID_IDirectDrawSurface,	0x6C14DB81,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 );
-DEFINE_GUID( IID_IDirectDrawSurface2,	0x57805885,0x6eec,0x11cf,0x94,0x41,0xa8,0x23,0x03,0xc1,0x0e,0x27 );
-DEFINE_GUID( IID_IDirectDrawSurface3,	0xDA044E00,0x69B2,0x11D0,0xA1,0xD5,0x00,0xAA,0x00,0xB8,0xDF,0xBB );
-DEFINE_GUID( IID_IDirectDrawSurface4,   0x0B2B8630,0xAD35,0x11D0,0x8E,0xA6,0x00,0x60,0x97,0x97,0xEA,0x5B );
-DEFINE_GUID( IID_IDirectDrawSurface7,   0x06675a80,0x3b9b,0x11d2,0xb9,0x2f,0x00,0x60,0x97,0x97,0xea,0x5b );
-DEFINE_GUID( IID_IDirectDrawPalette,	0x6C14DB84,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 );
-DEFINE_GUID( IID_IDirectDrawClipper,	0x6C14DB85,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 );
-DEFINE_GUID( IID_IDirectDrawColorControl,0x4B9F0EE0,0x0D7E,0x11D0,0x9B,0x06,0x00,0xA0,0xC9,0x03,0xA3,0xB8 );
-DEFINE_GUID( IID_IDirectDrawGammaControl,0x69C11C3E,0xB46B,0x11D1,0xAD,0x7A,0x00,0xC0,0x4F,0xC2,0x9B,0x4E );
-
-typedef struct IDirectDraw *LPDIRECTDRAW;
-typedef struct IDirectDraw2 *LPDIRECTDRAW2;
-typedef struct IDirectDraw4 *LPDIRECTDRAW4;
-typedef struct IDirectDraw7 *LPDIRECTDRAW7;
-typedef struct IDirectDrawClipper *LPDIRECTDRAWCLIPPER;
-typedef struct IDirectDrawPalette *LPDIRECTDRAWPALETTE;
-typedef struct IDirectDrawSurface *LPDIRECTDRAWSURFACE;
-typedef struct IDirectDrawSurface2 *LPDIRECTDRAWSURFACE2;
-typedef struct IDirectDrawSurface3 *LPDIRECTDRAWSURFACE3;
-typedef struct IDirectDrawSurface4 *LPDIRECTDRAWSURFACE4;
-typedef struct IDirectDrawSurface7 *LPDIRECTDRAWSURFACE7;
-typedef struct IDirectDrawColorControl *LPDIRECTDRAWCOLORCONTROL;
-typedef struct IDirectDrawGammaControl *LPDIRECTDRAWGAMMACONTROL;
-
-
-#define DDENUMRET_CANCEL	0
-#define DDENUMRET_OK		1
-
-#define DD_OK			0
-
-
-#define _FACDD		0x876
-#define MAKE_DDHRESULT( code )  MAKE_HRESULT( 1, _FACDD, code )
-
-#define DDERR_ALREADYINITIALIZED		MAKE_DDHRESULT( 5 )
-#define DDERR_CANNOTATTACHSURFACE		MAKE_DDHRESULT( 10 )
-#define DDERR_CANNOTDETACHSURFACE		MAKE_DDHRESULT( 20 )
-#define DDERR_CURRENTLYNOTAVAIL			MAKE_DDHRESULT( 40 )
-#define DDERR_EXCEPTION				MAKE_DDHRESULT( 55 )
-#define DDERR_GENERIC				E_FAIL
-#define DDERR_HEIGHTALIGN			MAKE_DDHRESULT( 90 )
-#define DDERR_INCOMPATIBLEPRIMARY		MAKE_DDHRESULT( 95 )
-#define DDERR_INVALIDCAPS			MAKE_DDHRESULT( 100 )
-#define DDERR_INVALIDCLIPLIST			MAKE_DDHRESULT( 110 )
-#define DDERR_INVALIDMODE			MAKE_DDHRESULT( 120 )
-#define DDERR_INVALIDOBJECT			MAKE_DDHRESULT( 130 )
-#define DDERR_INVALIDPARAMS			E_INVALIDARG
-#define DDERR_INVALIDPIXELFORMAT		MAKE_DDHRESULT( 145 )
-#define DDERR_INVALIDRECT			MAKE_DDHRESULT( 150 )
-#define DDERR_LOCKEDSURFACES			MAKE_DDHRESULT( 160 )
-#define DDERR_NO3D				MAKE_DDHRESULT( 170 )
-#define DDERR_NOALPHAHW				MAKE_DDHRESULT( 180 )
-#define DDERR_NOSTEREOHARDWARE          	MAKE_DDHRESULT( 181 )
-#define DDERR_NOSURFACELEFT                     MAKE_DDHRESULT( 182 )
-#define DDERR_NOCLIPLIST			MAKE_DDHRESULT( 205 )
-#define DDERR_NOCOLORCONVHW			MAKE_DDHRESULT( 210 )
-#define DDERR_NOCOOPERATIVELEVELSET		MAKE_DDHRESULT( 212 )
-#define DDERR_NOCOLORKEY			MAKE_DDHRESULT( 215 )
-#define DDERR_NOCOLORKEYHW			MAKE_DDHRESULT( 220 )
-#define DDERR_NODIRECTDRAWSUPPORT		MAKE_DDHRESULT( 222 )
-#define DDERR_NOEXCLUSIVEMODE			MAKE_DDHRESULT( 225 )
-#define DDERR_NOFLIPHW				MAKE_DDHRESULT( 230 )
-#define DDERR_NOGDI				MAKE_DDHRESULT( 240 )
-#define DDERR_NOMIRRORHW			MAKE_DDHRESULT( 250 )
-#define DDERR_NOTFOUND				MAKE_DDHRESULT( 255 )
-#define DDERR_NOOVERLAYHW			MAKE_DDHRESULT( 260 )
-#define DDERR_OVERLAPPINGRECTS                  MAKE_DDHRESULT( 270 )
-#define DDERR_NORASTEROPHW			MAKE_DDHRESULT( 280 )
-#define DDERR_NOROTATIONHW			MAKE_DDHRESULT( 290 )
-#define DDERR_NOSTRETCHHW			MAKE_DDHRESULT( 310 )
-#define DDERR_NOT4BITCOLOR			MAKE_DDHRESULT( 316 )
-#define DDERR_NOT4BITCOLORINDEX			MAKE_DDHRESULT( 317 )
-#define DDERR_NOT8BITCOLOR			MAKE_DDHRESULT( 320 )
-#define DDERR_NOTEXTUREHW			MAKE_DDHRESULT( 330 )
-#define DDERR_NOVSYNCHW				MAKE_DDHRESULT( 335 )
-#define DDERR_NOZBUFFERHW			MAKE_DDHRESULT( 340 )
-#define DDERR_NOZOVERLAYHW			MAKE_DDHRESULT( 350 )
-#define DDERR_OUTOFCAPS				MAKE_DDHRESULT( 360 )
-#define DDERR_OUTOFMEMORY			E_OUTOFMEMORY
-#define DDERR_OUTOFVIDEOMEMORY			MAKE_DDHRESULT( 380 )
-#define DDERR_OVERLAYCANTCLIP			MAKE_DDHRESULT( 382 )
-#define DDERR_OVERLAYCOLORKEYONLYONEACTIVE	MAKE_DDHRESULT( 384 )
-#define DDERR_PALETTEBUSY			MAKE_DDHRESULT( 387 )
-#define DDERR_COLORKEYNOTSET			MAKE_DDHRESULT( 400 )
-#define DDERR_SURFACEALREADYATTACHED		MAKE_DDHRESULT( 410 )
-#define DDERR_SURFACEALREADYDEPENDENT		MAKE_DDHRESULT( 420 )
-#define DDERR_SURFACEBUSY			MAKE_DDHRESULT( 430 )
-#define DDERR_CANTLOCKSURFACE			MAKE_DDHRESULT( 435 )
-#define DDERR_SURFACEISOBSCURED			MAKE_DDHRESULT( 440 )
-#define DDERR_SURFACELOST			MAKE_DDHRESULT( 450 )
-#define DDERR_SURFACENOTATTACHED		MAKE_DDHRESULT( 460 )
-#define DDERR_TOOBIGHEIGHT			MAKE_DDHRESULT( 470 )
-#define DDERR_TOOBIGSIZE			MAKE_DDHRESULT( 480 )
-#define DDERR_TOOBIGWIDTH			MAKE_DDHRESULT( 490 )
-#define DDERR_UNSUPPORTED			E_NOTIMPL
-#define DDERR_UNSUPPORTEDFORMAT			MAKE_DDHRESULT( 510 )
-#define DDERR_UNSUPPORTEDMASK			MAKE_DDHRESULT( 520 )
-#define DDERR_INVALIDSTREAM                     MAKE_DDHRESULT( 521 )
-#define DDERR_VERTICALBLANKINPROGRESS		MAKE_DDHRESULT( 537 )
-#define DDERR_WASSTILLDRAWING			MAKE_DDHRESULT( 540 )
-#define DDERR_DDSCAPSCOMPLEXREQUIRED            MAKE_DDHRESULT( 542 )
-#define DDERR_XALIGN				MAKE_DDHRESULT( 560 )
-#define DDERR_INVALIDDIRECTDRAWGUID		MAKE_DDHRESULT( 561 )
-#define DDERR_DIRECTDRAWALREADYCREATED		MAKE_DDHRESULT( 562 )
-#define DDERR_NODIRECTDRAWHW			MAKE_DDHRESULT( 563 )
-#define DDERR_PRIMARYSURFACEALREADYEXISTS	MAKE_DDHRESULT( 564 )
-#define DDERR_NOEMULATION			MAKE_DDHRESULT( 565 )
-#define DDERR_REGIONTOOSMALL			MAKE_DDHRESULT( 566 )
-#define DDERR_CLIPPERISUSINGHWND		MAKE_DDHRESULT( 567 )
-#define DDERR_NOCLIPPERATTACHED			MAKE_DDHRESULT( 568 )
-#define DDERR_NOHWND				MAKE_DDHRESULT( 569 )
-#define DDERR_HWNDSUBCLASSED			MAKE_DDHRESULT( 570 )
-#define DDERR_HWNDALREADYSET			MAKE_DDHRESULT( 571 )
-#define DDERR_NOPALETTEATTACHED			MAKE_DDHRESULT( 572 )
-#define DDERR_NOPALETTEHW			MAKE_DDHRESULT( 573 )
-#define DDERR_BLTFASTCANTCLIP			MAKE_DDHRESULT( 574 )
-#define DDERR_NOBLTHW				MAKE_DDHRESULT( 575 )
-#define DDERR_NODDROPSHW			MAKE_DDHRESULT( 576 )
-#define DDERR_OVERLAYNOTVISIBLE			MAKE_DDHRESULT( 577 )
-#define DDERR_NOOVERLAYDEST			MAKE_DDHRESULT( 578 )
-#define DDERR_INVALIDPOSITION			MAKE_DDHRESULT( 579 )
-#define DDERR_NOTAOVERLAYSURFACE		MAKE_DDHRESULT( 580 )
-#define DDERR_EXCLUSIVEMODEALREADYSET		MAKE_DDHRESULT( 581 )
-#define DDERR_NOTFLIPPABLE			MAKE_DDHRESULT( 582 )
-#define DDERR_CANTDUPLICATE			MAKE_DDHRESULT( 583 )
-#define DDERR_NOTLOCKED				MAKE_DDHRESULT( 584 )
-#define DDERR_CANTCREATEDC			MAKE_DDHRESULT( 585 )
-#define DDERR_NODC				MAKE_DDHRESULT( 586 )
-#define DDERR_WRONGMODE				MAKE_DDHRESULT( 587 )
-#define DDERR_IMPLICITLYCREATED			MAKE_DDHRESULT( 588 )
-#define DDERR_NOTPALETTIZED			MAKE_DDHRESULT( 589 )
-#define DDERR_UNSUPPORTEDMODE			MAKE_DDHRESULT( 590 )
-#define DDERR_NOMIPMAPHW			MAKE_DDHRESULT( 591 )
-#define DDERR_INVALIDSURFACETYPE		MAKE_DDHRESULT( 592 )
-#define DDERR_NOOPTIMIZEHW			MAKE_DDHRESULT( 600 )
-#define DDERR_NOTLOADED				MAKE_DDHRESULT( 601 )
-#define DDERR_NOFOCUSWINDOW			MAKE_DDHRESULT( 602 )
-#define DDERR_NOTONMIPMAPSUBLEVEL               MAKE_DDHRESULT( 603 )
-#define DDERR_DCALREADYCREATED			MAKE_DDHRESULT( 620 )
-#define DDERR_NONONLOCALVIDMEM			MAKE_DDHRESULT( 630 )
-#define DDERR_CANTPAGELOCK			MAKE_DDHRESULT( 640 )
-#define DDERR_CANTPAGEUNLOCK			MAKE_DDHRESULT( 660 )
-#define DDERR_NOTPAGELOCKED			MAKE_DDHRESULT( 680 )
-#define DDERR_MOREDATA				MAKE_DDHRESULT( 690 )
-#define DDERR_EXPIRED                           MAKE_DDHRESULT( 691 )
-#define DDERR_TESTFINISHED                      MAKE_DDHRESULT( 692 )
-#define DDERR_NEWMODE                           MAKE_DDHRESULT( 693 )
-#define DDERR_D3DNOTINITIALIZED                 MAKE_DDHRESULT( 694 )
-#define DDERR_VIDEONOTACTIVE			MAKE_DDHRESULT( 695 )
-#define DDERR_NOMONITORINFORMATION              MAKE_DDHRESULT( 696 )
-#define DDERR_NODRIVERSUPPORT                   MAKE_DDHRESULT( 697 )
-#define DDERR_DEVICEDOESNTOWNSURFACE		MAKE_DDHRESULT( 699 )
-#define DDERR_NOTINITIALIZED			CO_E_NOTINITIALIZED
-
-/* dwFlags for Blt* */
-#define DDBLT_ALPHADEST				0x00000001
-#define DDBLT_ALPHADESTCONSTOVERRIDE		0x00000002
-#define DDBLT_ALPHADESTNEG			0x00000004
-#define DDBLT_ALPHADESTSURFACEOVERRIDE		0x00000008
-#define DDBLT_ALPHAEDGEBLEND			0x00000010
-#define DDBLT_ALPHASRC				0x00000020
-#define DDBLT_ALPHASRCCONSTOVERRIDE		0x00000040
-#define DDBLT_ALPHASRCNEG			0x00000080
-#define DDBLT_ALPHASRCSURFACEOVERRIDE		0x00000100
-#define DDBLT_ASYNC				0x00000200
-#define DDBLT_COLORFILL				0x00000400
-#define DDBLT_DDFX				0x00000800
-#define DDBLT_DDROPS				0x00001000
-#define DDBLT_KEYDEST				0x00002000
-#define DDBLT_KEYDESTOVERRIDE			0x00004000
-#define DDBLT_KEYSRC				0x00008000
-#define DDBLT_KEYSRCOVERRIDE			0x00010000
-#define DDBLT_ROP				0x00020000
-#define DDBLT_ROTATIONANGLE			0x00040000
-#define DDBLT_ZBUFFER				0x00080000
-#define DDBLT_ZBUFFERDESTCONSTOVERRIDE		0x00100000
-#define DDBLT_ZBUFFERDESTOVERRIDE		0x00200000
-#define DDBLT_ZBUFFERSRCCONSTOVERRIDE		0x00400000
-#define DDBLT_ZBUFFERSRCOVERRIDE		0x00800000
-#define DDBLT_WAIT				0x01000000
-#define DDBLT_DEPTHFILL				0x02000000
-#define DDBLT_DONOTWAIT                         0x08000000
-
-/* dwTrans for BltFast */
-#define DDBLTFAST_NOCOLORKEY			0x00000000
-#define DDBLTFAST_SRCCOLORKEY			0x00000001
-#define DDBLTFAST_DESTCOLORKEY			0x00000002
-#define DDBLTFAST_WAIT				0x00000010
-#define DDBLTFAST_DONOTWAIT                     0x00000020
-
-/* dwFlags for Flip */
-#define DDFLIP_WAIT		0x00000001
-#define DDFLIP_EVEN		0x00000002 /* only valid for overlay */
-#define DDFLIP_ODD		0x00000004 /* only valid for overlay */
-#define DDFLIP_NOVSYNC		0x00000008
-#define DDFLIP_STEREO		0x00000010
-#define DDFLIP_DONOTWAIT	0x00000020
-
-/* dwFlags for GetBltStatus */
-#define DDGBS_CANBLT				0x00000001
-#define DDGBS_ISBLTDONE				0x00000002
-
-/* dwFlags for IDirectDrawSurface7::GetFlipStatus */
-#define DDGFS_CANFLIP		1L
-#define DDGFS_ISFLIPDONE	2L
-
-/* dwFlags for IDirectDrawSurface7::SetPrivateData */
-#define DDSPD_IUNKNOWNPTR	1L
-#define DDSPD_VOLATILE		2L
-
-/* DDSCAPS.dwCaps */
-/* reserved1, was 3d capable */
-#define DDSCAPS_RESERVED1		0x00000001
-/* surface contains alpha information */
-#define DDSCAPS_ALPHA			0x00000002
-/* this surface is a backbuffer */
-#define DDSCAPS_BACKBUFFER		0x00000004
-/* complex surface structure */
-#define DDSCAPS_COMPLEX			0x00000008
-/* part of surface flipping structure */
-#define DDSCAPS_FLIP			0x00000010
-/* this surface is the frontbuffer surface */
-#define DDSCAPS_FRONTBUFFER		0x00000020
-/* this is a plain offscreen surface */
-#define DDSCAPS_OFFSCREENPLAIN		0x00000040
-/* overlay */
-#define DDSCAPS_OVERLAY			0x00000080
-/* palette objects can be created and attached to us */
-#define DDSCAPS_PALETTE			0x00000100
-/* primary surface (the one the user looks at currently)(right eye)*/
-#define DDSCAPS_PRIMARYSURFACE		0x00000200
-/* primary surface for left eye */
-#define DDSCAPS_PRIMARYSURFACELEFT	0x00000400
-/* surface exists in systemmemory */
-#define DDSCAPS_SYSTEMMEMORY		0x00000800
-/* surface can be used as a texture */
-#define DDSCAPS_TEXTURE		        0x00001000
-/* surface may be destination for 3d rendering */
-#define DDSCAPS_3DDEVICE		0x00002000
-/* surface exists in videomemory */
-#define DDSCAPS_VIDEOMEMORY		0x00004000
-/* surface changes immediately visible */
-#define DDSCAPS_VISIBLE			0x00008000
-/* write only surface */
-#define DDSCAPS_WRITEONLY		0x00010000
-/* zbuffer surface */
-#define DDSCAPS_ZBUFFER			0x00020000
-/* has its own DC */
-#define DDSCAPS_OWNDC			0x00040000
-/* surface should be able to receive live video */
-#define DDSCAPS_LIVEVIDEO		0x00080000
-/* should be able to have a hw codec decompress stuff into it */
-#define DDSCAPS_HWCODEC			0x00100000
-/* mode X (320x200 or 320x240) surface */
-#define DDSCAPS_MODEX			0x00200000
-/* one mipmap surface (1 level) */
-#define DDSCAPS_MIPMAP			0x00400000
-#define DDSCAPS_RESERVED2		0x00800000
-/* memory allocation delayed until Load() */
-#define DDSCAPS_ALLOCONLOAD		0x04000000
-/* Indicates that the surface will receive data from a video port */
-#define DDSCAPS_VIDEOPORT		0x08000000
-/* surface is in local videomemory */
-#define DDSCAPS_LOCALVIDMEM		0x10000000
-/* surface is in nonlocal videomemory */
-#define DDSCAPS_NONLOCALVIDMEM		0x20000000
-/* surface is a standard VGA mode surface (NOT ModeX) */
-#define DDSCAPS_STANDARDVGAMODE		0x40000000
-/* optimized? surface */
-#define DDSCAPS_OPTIMIZED		0x80000000
-
-typedef struct _DDSCAPS {
-	DWORD	dwCaps;	/* capabilities of surface wanted */
-} DDSCAPS,*LPDDSCAPS;
-
-/* DDSCAPS2.dwCaps2 */
-/* indicates the surface will receive data from a video port using
-   deinterlacing hardware. */
-#define DDSCAPS2_HARDWAREDEINTERLACE	0x00000002
-/* indicates the surface will be locked very frequently. */
-#define DDSCAPS2_HINTDYNAMIC		0x00000004
-/* indicates surface can be re-ordered or retiled on load() */
-#define DDSCAPS2_HINTSTATIC             0x00000008
-/* indicates surface to be managed by directdraw/direct3D */
-#define DDSCAPS2_TEXTUREMANAGE          0x00000010
-/* reserved bits */
-#define DDSCAPS2_RESERVED1              0x00000020
-#define DDSCAPS2_RESERVED2              0x00000040
-/* indicates surface will never be locked again */
-#define DDSCAPS2_OPAQUE                 0x00000080
-/* set at CreateSurface() time to indicate antialising will be used */
-#define DDSCAPS2_HINTANTIALIASING       0x00000100
-/* set at CreateSurface() time to indicate cubic environment map */
-#define DDSCAPS2_CUBEMAP                0x00000200
-/* face flags for cube maps */
-#define DDSCAPS2_CUBEMAP_POSITIVEX      0x00000400
-#define DDSCAPS2_CUBEMAP_NEGATIVEX      0x00000800
-#define DDSCAPS2_CUBEMAP_POSITIVEY      0x00001000
-#define DDSCAPS2_CUBEMAP_NEGATIVEY      0x00002000
-#define DDSCAPS2_CUBEMAP_POSITIVEZ      0x00004000
-#define DDSCAPS2_CUBEMAP_NEGATIVEZ      0x00008000
-/* specifies all faces of a cube for CreateSurface() */
-#define DDSCAPS2_CUBEMAP_ALLFACES ( DDSCAPS2_CUBEMAP_POSITIVEX |\
-                                    DDSCAPS2_CUBEMAP_NEGATIVEX |\
-                                    DDSCAPS2_CUBEMAP_POSITIVEY |\
-                                    DDSCAPS2_CUBEMAP_NEGATIVEY |\
-                                    DDSCAPS2_CUBEMAP_POSITIVEZ |\
-                                    DDSCAPS2_CUBEMAP_NEGATIVEZ )
-/* set for mipmap sublevels on DirectX7 and later.  ignored by CreateSurface() */
-#define DDSCAPS2_MIPMAPSUBLEVEL         0x00010000
-/* indicates texture surface to be managed by Direct3D *only* */
-#define DDSCAPS2_D3DTEXTUREMANAGE       0x00020000
-/* indicates managed surface that can safely be lost */
-#define DDSCAPS2_DONOTPERSIST           0x00040000
-/* indicates surface is part of a stereo flipping chain */
-#define DDSCAPS2_STEREOSURFACELEFT      0x00080000
-
-typedef struct _DDSCAPS2 {
-	DWORD	dwCaps;	/* capabilities of surface wanted */
-	DWORD   dwCaps2; /* additional capabilities */
-	DWORD   dwCaps3; /* reserved capabilities */
-	DWORD   dwCaps4; /* more reserved capabilities */
-} DDSCAPS2,*LPDDSCAPS2;
-
-#define	DD_ROP_SPACE	(256/32)	/* space required to store ROP array */
-
-typedef struct _DDCAPS_DX7		/* DirectX 7 version of caps struct */
-{
-    DWORD	dwSize;                 /* size of the DDDRIVERCAPS structure */
-    DWORD	dwCaps;                 /* driver specific capabilities */
-    DWORD	dwCaps2;                /* more driver specific capabilites */
-    DWORD	dwCKeyCaps;             /* color key capabilities of the surface */
-    DWORD	dwFXCaps;               /* driver specific stretching and effects capabilites */
-    DWORD	dwFXAlphaCaps;          /* alpha driver specific capabilities */
-    DWORD	dwPalCaps;              /* palette capabilities */
-    DWORD	dwSVCaps;               /* stereo vision capabilities */
-    DWORD	dwAlphaBltConstBitDepths;       /* DDBD_2,4,8 */
-    DWORD	dwAlphaBltPixelBitDepths;       /* DDBD_1,2,4,8 */
-    DWORD	dwAlphaBltSurfaceBitDepths;     /* DDBD_1,2,4,8 */
-    DWORD	dwAlphaOverlayConstBitDepths;   /* DDBD_2,4,8 */
-    DWORD	dwAlphaOverlayPixelBitDepths;   /* DDBD_1,2,4,8 */
-    DWORD	dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */
-    DWORD	dwZBufferBitDepths;             /* DDBD_8,16,24,32 */
-    DWORD	dwVidMemTotal;          /* total amount of video memory */
-    DWORD	dwVidMemFree;           /* amount of free video memory */
-    DWORD	dwMaxVisibleOverlays;   /* maximum number of visible overlays */
-    DWORD	dwCurrVisibleOverlays;  /* current number of visible overlays */
-    DWORD	dwNumFourCCCodes;       /* number of four cc codes */
-    DWORD	dwAlignBoundarySrc;     /* source rectangle alignment */
-    DWORD	dwAlignSizeSrc;         /* source rectangle byte size */
-    DWORD	dwAlignBoundaryDest;    /* dest rectangle alignment */
-    DWORD	dwAlignSizeDest;        /* dest rectangle byte size */
-    DWORD	dwAlignStrideAlign;     /* stride alignment */
-    DWORD	dwRops[DD_ROP_SPACE];   /* ROPS supported */
-    DDSCAPS	ddsOldCaps;             /* old DDSCAPS - superceded for DirectX6+ */
-    DWORD	dwMinOverlayStretch;    /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMaxOverlayStretch;    /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMinLiveVideoStretch;  /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMaxLiveVideoStretch;  /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMinHwCodecStretch;    /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMaxHwCodecStretch;    /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwReserved1;
-    DWORD	dwReserved2;
-    DWORD	dwReserved3;
-    DWORD	dwSVBCaps;              /* driver specific capabilities for System->Vmem blts */
-    DWORD	dwSVBCKeyCaps;          /* driver color key capabilities for System->Vmem blts */
-    DWORD	dwSVBFXCaps;            /* driver FX capabilities for System->Vmem blts */
-    DWORD	dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */
-    DWORD	dwVSBCaps;              /* driver specific capabilities for Vmem->System blts */
-    DWORD	dwVSBCKeyCaps;          /* driver color key capabilities for Vmem->System blts */
-    DWORD	dwVSBFXCaps;            /* driver FX capabilities for Vmem->System blts */
-    DWORD	dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */
-    DWORD	dwSSBCaps;              /* driver specific capabilities for System->System blts */
-    DWORD	dwSSBCKeyCaps;          /* driver color key capabilities for System->System blts */
-    DWORD	dwSSBFXCaps;            /* driver FX capabilities for System->System blts */
-    DWORD	dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */
-    DWORD       dwMaxVideoPorts;        /* maximum number of usable video ports */
-    DWORD   	dwCurrVideoPorts;       /* current number of video ports used */
-    DWORD   	dwSVBCaps2;             /* more driver specific capabilities for System->Vmem blts */
-    DWORD   	dwNLVBCaps;             /* driver specific capabilities for non-local->local vidmem blts */
-    DWORD   	dwNLVBCaps2;            /* more driver specific capabilities non-local->local vidmem blts */
-    DWORD   	dwNLVBCKeyCaps;         /* driver color key capabilities for non-local->local vidmem blts */
-    DWORD   	dwNLVBFXCaps;           /* driver FX capabilities for non-local->local blts */
-    DWORD   	dwNLVBRops[DD_ROP_SPACE]; /* ROPS supported for non-local->local blts */
-    DDSCAPS2    ddsCaps;		/* surface capabilities */
-} DDCAPS_DX7,*LPDDCAPS_DX7;
-
-typedef struct _DDCAPS_DX6		/* DirectX 6 version of caps struct */
-{
-    DWORD	dwSize;                 /* size of the DDDRIVERCAPS structure */
-    DWORD	dwCaps;                 /* driver specific capabilities */
-    DWORD	dwCaps2;                /* more driver specific capabilites */
-    DWORD	dwCKeyCaps;             /* color key capabilities of the surface */
-    DWORD	dwFXCaps;               /* driver specific stretching and effects capabilites */
-    DWORD	dwFXAlphaCaps;          /* alpha driver specific capabilities */
-    DWORD	dwPalCaps;              /* palette capabilities */
-    DWORD	dwSVCaps;               /* stereo vision capabilities */
-    DWORD	dwAlphaBltConstBitDepths;       /* DDBD_2,4,8 */
-    DWORD	dwAlphaBltPixelBitDepths;       /* DDBD_1,2,4,8 */
-    DWORD	dwAlphaBltSurfaceBitDepths;     /* DDBD_1,2,4,8 */
-    DWORD	dwAlphaOverlayConstBitDepths;   /* DDBD_2,4,8 */
-    DWORD	dwAlphaOverlayPixelBitDepths;   /* DDBD_1,2,4,8 */
-    DWORD	dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */
-    DWORD	dwZBufferBitDepths;             /* DDBD_8,16,24,32 */
-    DWORD	dwVidMemTotal;          /* total amount of video memory */
-    DWORD	dwVidMemFree;           /* amount of free video memory */
-    DWORD	dwMaxVisibleOverlays;   /* maximum number of visible overlays */
-    DWORD	dwCurrVisibleOverlays;  /* current number of visible overlays */
-    DWORD	dwNumFourCCCodes;       /* number of four cc codes */
-    DWORD	dwAlignBoundarySrc;     /* source rectangle alignment */
-    DWORD	dwAlignSizeSrc;         /* source rectangle byte size */
-    DWORD	dwAlignBoundaryDest;    /* dest rectangle alignment */
-    DWORD	dwAlignSizeDest;        /* dest rectangle byte size */
-    DWORD	dwAlignStrideAlign;     /* stride alignment */
-    DWORD	dwRops[DD_ROP_SPACE];   /* ROPS supported */
-    DDSCAPS	ddsOldCaps;             /* old DDSCAPS - superceded for DirectX6+ */
-    DWORD	dwMinOverlayStretch;    /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMaxOverlayStretch;    /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMinLiveVideoStretch;  /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMaxLiveVideoStretch;  /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMinHwCodecStretch;    /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMaxHwCodecStretch;    /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwReserved1;
-    DWORD	dwReserved2;
-    DWORD	dwReserved3;
-    DWORD	dwSVBCaps;              /* driver specific capabilities for System->Vmem blts */
-    DWORD	dwSVBCKeyCaps;          /* driver color key capabilities for System->Vmem blts */
-    DWORD	dwSVBFXCaps;            /* driver FX capabilities for System->Vmem blts */
-    DWORD	dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */
-    DWORD	dwVSBCaps;              /* driver specific capabilities for Vmem->System blts */
-    DWORD	dwVSBCKeyCaps;          /* driver color key capabilities for Vmem->System blts */
-    DWORD	dwVSBFXCaps;            /* driver FX capabilities for Vmem->System blts */
-    DWORD	dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */
-    DWORD	dwSSBCaps;              /* driver specific capabilities for System->System blts */
-    DWORD	dwSSBCKeyCaps;          /* driver color key capabilities for System->System blts */
-    DWORD	dwSSBFXCaps;            /* driver FX capabilities for System->System blts */
-    DWORD	dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */
-    DWORD       dwMaxVideoPorts;        /* maximum number of usable video ports */
-    DWORD   	dwCurrVideoPorts;       /* current number of video ports used */
-    DWORD   	dwSVBCaps2;             /* more driver specific capabilities for System->Vmem blts */
-    DWORD   	dwNLVBCaps;             /* driver specific capabilities for non-local->local vidmem blts */
-    DWORD   	dwNLVBCaps2;            /* more driver specific capabilities non-local->local vidmem blts */
-    DWORD   	dwNLVBCKeyCaps;         /* driver color key capabilities for non-local->local vidmem blts */
-    DWORD   	dwNLVBFXCaps;           /* driver FX capabilities for non-local->local blts */
-    DWORD   	dwNLVBRops[DD_ROP_SPACE]; /* ROPS supported for non-local->local blts */
-    /* and one new member for DirectX 6 */
-    DDSCAPS2    ddsCaps;		/* surface capabilities */
-} DDCAPS_DX6,*LPDDCAPS_DX6;
-
-typedef struct _DDCAPS_DX5		/* DirectX5 version of caps struct */
-{
-    DWORD	dwSize;                 /* size of the DDDRIVERCAPS structure */
-    DWORD	dwCaps;                 /* driver specific capabilities */
-    DWORD	dwCaps2;                /* more driver specific capabilites */
-    DWORD	dwCKeyCaps;             /* color key capabilities of the surface */
-    DWORD	dwFXCaps;               /* driver specific stretching and effects capabilites */
-    DWORD	dwFXAlphaCaps;          /* alpha driver specific capabilities */
-    DWORD	dwPalCaps;              /* palette capabilities */
-    DWORD	dwSVCaps;               /* stereo vision capabilities */
-    DWORD	dwAlphaBltConstBitDepths;       /* DDBD_2,4,8 */
-    DWORD	dwAlphaBltPixelBitDepths;       /* DDBD_1,2,4,8 */
-    DWORD	dwAlphaBltSurfaceBitDepths;     /* DDBD_1,2,4,8 */
-    DWORD	dwAlphaOverlayConstBitDepths;   /* DDBD_2,4,8 */
-    DWORD	dwAlphaOverlayPixelBitDepths;   /* DDBD_1,2,4,8 */
-    DWORD	dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */
-    DWORD	dwZBufferBitDepths;             /* DDBD_8,16,24,32 */
-    DWORD	dwVidMemTotal;          /* total amount of video memory */
-    DWORD	dwVidMemFree;           /* amount of free video memory */
-    DWORD	dwMaxVisibleOverlays;   /* maximum number of visible overlays */
-    DWORD	dwCurrVisibleOverlays;  /* current number of visible overlays */
-    DWORD	dwNumFourCCCodes;       /* number of four cc codes */
-    DWORD	dwAlignBoundarySrc;     /* source rectangle alignment */
-    DWORD	dwAlignSizeSrc;         /* source rectangle byte size */
-    DWORD	dwAlignBoundaryDest;    /* dest rectangle alignment */
-    DWORD	dwAlignSizeDest;        /* dest rectangle byte size */
-    DWORD	dwAlignStrideAlign;     /* stride alignment */
-    DWORD	dwRops[DD_ROP_SPACE];   /* ROPS supported */
-    DDSCAPS	ddsCaps;                /* DDSCAPS structure has all the general capabilities */
-    DWORD	dwMinOverlayStretch;    /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMaxOverlayStretch;    /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMinLiveVideoStretch;  /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMaxLiveVideoStretch;  /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMinHwCodecStretch;    /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMaxHwCodecStretch;    /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwReserved1;
-    DWORD	dwReserved2;
-    DWORD	dwReserved3;
-    DWORD	dwSVBCaps;              /* driver specific capabilities for System->Vmem blts */
-    DWORD	dwSVBCKeyCaps;          /* driver color key capabilities for System->Vmem blts */
-    DWORD	dwSVBFXCaps;            /* driver FX capabilities for System->Vmem blts */
-    DWORD	dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */
-    DWORD	dwVSBCaps;              /* driver specific capabilities for Vmem->System blts */
-    DWORD	dwVSBCKeyCaps;          /* driver color key capabilities for Vmem->System blts */
-    DWORD	dwVSBFXCaps;            /* driver FX capabilities for Vmem->System blts */
-    DWORD	dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */
-    DWORD	dwSSBCaps;              /* driver specific capabilities for System->System blts */
-    DWORD	dwSSBCKeyCaps;          /* driver color key capabilities for System->System blts */
-    DWORD	dwSSBFXCaps;            /* driver FX capabilities for System->System blts */
-    DWORD	dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */
-    /* the following are the new DirectX 5 members */
-    DWORD       dwMaxVideoPorts;        /* maximum number of usable video ports */
-    DWORD   	dwCurrVideoPorts;       /* current number of video ports used */
-    DWORD   	dwSVBCaps2;             /* more driver specific capabilities for System->Vmem blts */
-    DWORD   	dwNLVBCaps;             /* driver specific capabilities for non-local->local vidmem blts */
-    DWORD   	dwNLVBCaps2;            /* more driver specific capabilities non-local->local vidmem blts */
-    DWORD   	dwNLVBCKeyCaps;         /* driver color key capabilities for non-local->local vidmem blts */
-    DWORD   	dwNLVBFXCaps;           /* driver FX capabilities for non-local->local blts */
-    DWORD   	dwNLVBRops[DD_ROP_SPACE]; /* ROPS supported for non-local->local blts */
-} DDCAPS_DX5,*LPDDCAPS_DX5;
-
-typedef struct _DDCAPS_DX3		/* DirectX3 version of caps struct */
-{
-    DWORD	dwSize;                 /* size of the DDDRIVERCAPS structure */
-    DWORD	dwCaps;                 /* driver specific capabilities */
-    DWORD	dwCaps2;                /* more driver specific capabilites */
-    DWORD	dwCKeyCaps;             /* color key capabilities of the surface */
-    DWORD	dwFXCaps;               /* driver specific stretching and effects capabilites */
-    DWORD	dwFXAlphaCaps;          /* alpha driver specific capabilities */
-    DWORD	dwPalCaps;              /* palette capabilities */
-    DWORD	dwSVCaps;               /* stereo vision capabilities */
-    DWORD	dwAlphaBltConstBitDepths;       /* DDBD_2,4,8 */
-    DWORD	dwAlphaBltPixelBitDepths;       /* DDBD_1,2,4,8 */
-    DWORD	dwAlphaBltSurfaceBitDepths;     /* DDBD_1,2,4,8 */
-    DWORD	dwAlphaOverlayConstBitDepths;   /* DDBD_2,4,8 */
-    DWORD	dwAlphaOverlayPixelBitDepths;   /* DDBD_1,2,4,8 */
-    DWORD	dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */
-    DWORD	dwZBufferBitDepths;             /* DDBD_8,16,24,32 */
-    DWORD	dwVidMemTotal;          /* total amount of video memory */
-    DWORD	dwVidMemFree;           /* amount of free video memory */
-    DWORD	dwMaxVisibleOverlays;   /* maximum number of visible overlays */
-    DWORD	dwCurrVisibleOverlays;  /* current number of visible overlays */
-    DWORD	dwNumFourCCCodes;       /* number of four cc codes */
-    DWORD	dwAlignBoundarySrc;     /* source rectangle alignment */
-    DWORD	dwAlignSizeSrc;         /* source rectangle byte size */
-    DWORD	dwAlignBoundaryDest;    /* dest rectangle alignment */
-    DWORD	dwAlignSizeDest;        /* dest rectangle byte size */
-    DWORD	dwAlignStrideAlign;     /* stride alignment */
-    DWORD	dwRops[DD_ROP_SPACE];   /* ROPS supported */
-    DDSCAPS	ddsCaps;                /* DDSCAPS structure has all the general capabilities */
-    DWORD	dwMinOverlayStretch;    /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMaxOverlayStretch;    /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMinLiveVideoStretch;  /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMaxLiveVideoStretch;  /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMinHwCodecStretch;    /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwMaxHwCodecStretch;    /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */
-    DWORD	dwReserved1;
-    DWORD	dwReserved2;
-    DWORD	dwReserved3;
-    DWORD	dwSVBCaps;              /* driver specific capabilities for System->Vmem blts */
-    DWORD	dwSVBCKeyCaps;          /* driver color key capabilities for System->Vmem blts */
-    DWORD	dwSVBFXCaps;            /* driver FX capabilities for System->Vmem blts */
-    DWORD	dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */
-    DWORD	dwVSBCaps;              /* driver specific capabilities for Vmem->System blts */
-    DWORD	dwVSBCKeyCaps;          /* driver color key capabilities for Vmem->System blts */
-    DWORD	dwVSBFXCaps;            /* driver FX capabilities for Vmem->System blts */
-    DWORD	dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */
-    DWORD	dwSSBCaps;              /* driver specific capabilities for System->System blts */
-    DWORD	dwSSBCKeyCaps;          /* driver color key capabilities for System->System blts */
-    DWORD	dwSSBFXCaps;            /* driver FX capabilities for System->System blts */
-    DWORD	dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */
-    DWORD	dwReserved4;
-    DWORD	dwReserved5;
-    DWORD	dwReserved6;
-} DDCAPS_DX3,*LPDDCAPS_DX3;
-
-/* set caps struct according to DIRECTDRAW_VERSION */
-
-#if DIRECTDRAW_VERSION <= 0x300
-typedef DDCAPS_DX3 DDCAPS;
-#elif DIRECTDRAW_VERSION <= 0x500
-typedef DDCAPS_DX5 DDCAPS;
-#elif DIRECTDRAW_VERSION <= 0x600
-typedef DDCAPS_DX6 DDCAPS;
-#else
-typedef DDCAPS_DX7 DDCAPS;
-#endif
-
-typedef DDCAPS *LPDDCAPS;
-
-/* DDCAPS.dwCaps */
-#define DDCAPS_3D			0x00000001
-#define DDCAPS_ALIGNBOUNDARYDEST	0x00000002
-#define DDCAPS_ALIGNSIZEDEST		0x00000004
-#define DDCAPS_ALIGNBOUNDARYSRC		0x00000008
-#define DDCAPS_ALIGNSIZESRC		0x00000010
-#define DDCAPS_ALIGNSTRIDE		0x00000020
-#define DDCAPS_BLT			0x00000040
-#define DDCAPS_BLTQUEUE			0x00000080
-#define DDCAPS_BLTFOURCC		0x00000100
-#define DDCAPS_BLTSTRETCH		0x00000200
-#define DDCAPS_GDI			0x00000400
-#define DDCAPS_OVERLAY			0x00000800
-#define DDCAPS_OVERLAYCANTCLIP		0x00001000
-#define DDCAPS_OVERLAYFOURCC		0x00002000
-#define DDCAPS_OVERLAYSTRETCH		0x00004000
-#define DDCAPS_PALETTE			0x00008000
-#define DDCAPS_PALETTEVSYNC		0x00010000
-#define DDCAPS_READSCANLINE		0x00020000
-#define DDCAPS_STEREOVIEW		0x00040000
-#define DDCAPS_VBI			0x00080000
-#define DDCAPS_ZBLTS			0x00100000
-#define DDCAPS_ZOVERLAYS		0x00200000
-#define DDCAPS_COLORKEY			0x00400000
-#define DDCAPS_ALPHA			0x00800000
-#define DDCAPS_COLORKEYHWASSIST		0x01000000
-#define DDCAPS_NOHARDWARE		0x02000000
-#define DDCAPS_BLTCOLORFILL		0x04000000
-#define DDCAPS_BANKSWITCHED		0x08000000
-#define DDCAPS_BLTDEPTHFILL		0x10000000
-#define DDCAPS_CANCLIP			0x20000000
-#define DDCAPS_CANCLIPSTRETCHED		0x40000000
-#define DDCAPS_CANBLTSYSMEM		0x80000000
-
-/* DDCAPS.dwCaps2 */
-#define DDCAPS2_CERTIFIED		0x00000001
-#define DDCAPS2_NO2DDURING3DSCENE       0x00000002
-#define DDCAPS2_VIDEOPORT		0x00000004
-#define DDCAPS2_AUTOFLIPOVERLAY		0x00000008
-#define DDCAPS2_CANBOBINTERLEAVED	0x00000010
-#define DDCAPS2_CANBOBNONINTERLEAVED	0x00000020
-#define DDCAPS2_COLORCONTROLOVERLAY	0x00000040
-#define DDCAPS2_COLORCONTROLPRIMARY	0x00000080
-#define DDCAPS2_CANDROPZ16BIT		0x00000100
-#define DDCAPS2_NONLOCALVIDMEM		0x00000200
-#define DDCAPS2_NONLOCALVIDMEMCAPS	0x00000400
-#define DDCAPS2_NOPAGELOCKREQUIRED	0x00000800
-#define DDCAPS2_WIDESURFACES		0x00001000
-#define DDCAPS2_CANFLIPODDEVEN		0x00002000
-#define DDCAPS2_CANBOBHARDWARE		0x00004000
-#define DDCAPS2_COPYFOURCC              0x00008000
-#define DDCAPS2_PRIMARYGAMMA            0x00020000
-#define DDCAPS2_CANRENDERWINDOWED       0x00080000
-#define DDCAPS2_CANCALIBRATEGAMMA       0x00100000
-#define DDCAPS2_FLIPINTERVAL            0x00200000
-#define DDCAPS2_FLIPNOVSYNC             0x00400000
-#define DDCAPS2_CANMANAGETEXTURE        0x00800000
-#define DDCAPS2_TEXMANINNONLOCALVIDMEM  0x01000000
-#define DDCAPS2_STEREO                  0x02000000
-#define DDCAPS2_SYSTONONLOCAL_AS_SYSTOLOCAL   0x04000000
-
-
-/* Set/Get Colour Key Flags */
-#define DDCKEY_COLORSPACE  0x00000001  /* Struct is single colour space */
-#define DDCKEY_DESTBLT     0x00000002  /* To be used as dest for blt */
-#define DDCKEY_DESTOVERLAY 0x00000004  /* To be used as dest for CK overlays */
-#define DDCKEY_SRCBLT      0x00000008  /* To be used as src for blt */
-#define DDCKEY_SRCOVERLAY  0x00000010  /* To be used as src for CK overlays */
-
-typedef struct _DDCOLORKEY
-{
-	DWORD	dwColorSpaceLowValue;/* low boundary of color space that is to
-                                      * be treated as Color Key, inclusive
-				      */
-	DWORD	dwColorSpaceHighValue;/* high boundary of color space that is
-                                       * to be treated as Color Key, inclusive
-				       */
-} DDCOLORKEY,*LPDDCOLORKEY;
-
-/* ddCKEYCAPS bits */
-#define DDCKEYCAPS_DESTBLT			0x00000001
-#define DDCKEYCAPS_DESTBLTCLRSPACE		0x00000002
-#define DDCKEYCAPS_DESTBLTCLRSPACEYUV		0x00000004
-#define DDCKEYCAPS_DESTBLTYUV			0x00000008
-#define DDCKEYCAPS_DESTOVERLAY			0x00000010
-#define DDCKEYCAPS_DESTOVERLAYCLRSPACE		0x00000020
-#define DDCKEYCAPS_DESTOVERLAYCLRSPACEYUV	0x00000040
-#define DDCKEYCAPS_DESTOVERLAYONEACTIVE		0x00000080
-#define DDCKEYCAPS_DESTOVERLAYYUV		0x00000100
-#define DDCKEYCAPS_SRCBLT			0x00000200
-#define DDCKEYCAPS_SRCBLTCLRSPACE		0x00000400
-#define DDCKEYCAPS_SRCBLTCLRSPACEYUV		0x00000800
-#define DDCKEYCAPS_SRCBLTYUV			0x00001000
-#define DDCKEYCAPS_SRCOVERLAY			0x00002000
-#define DDCKEYCAPS_SRCOVERLAYCLRSPACE		0x00004000
-#define DDCKEYCAPS_SRCOVERLAYCLRSPACEYUV	0x00008000
-#define DDCKEYCAPS_SRCOVERLAYONEACTIVE		0x00010000
-#define DDCKEYCAPS_SRCOVERLAYYUV		0x00020000
-#define DDCKEYCAPS_NOCOSTOVERLAY		0x00040000
-
-typedef struct _DDPIXELFORMAT {
-    DWORD	dwSize;                 /* 0: size of structure */
-    DWORD	dwFlags;                /* 4: pixel format flags */
-    DWORD	dwFourCC;               /* 8: (FOURCC code) */
-    union {
-	DWORD	dwRGBBitCount;          /* C: how many bits per pixel */
-	DWORD	dwYUVBitCount;          /* C: how many bits per pixel */
-	DWORD	dwZBufferBitDepth;      /* C: how many bits for z buffers */
-	DWORD	dwAlphaBitDepth;        /* C: how many bits for alpha channels*/
-	DWORD	dwLuminanceBitCount;
-	DWORD	dwBumpBitCount;
-    } DUMMYUNIONNAME1;
-    union {
-	DWORD	dwRBitMask;             /* 10: mask for red bit*/
-	DWORD	dwYBitMask;             /* 10: mask for Y bits*/
-	DWORD	dwStencilBitDepth;
-	DWORD	dwLuminanceBitMask;
-	DWORD	dwBumpDuBitMask;
-    } DUMMYUNIONNAME2;
-    union {
-	DWORD	dwGBitMask;             /* 14: mask for green bits*/
-	DWORD	dwUBitMask;             /* 14: mask for U bits*/
-	DWORD	dwZBitMask;
-	DWORD	dwBumpDvBitMask;
-    } DUMMYUNIONNAME3;
-    union {
-	DWORD   dwBBitMask;             /* 18: mask for blue bits*/
-	DWORD   dwVBitMask;             /* 18: mask for V bits*/
-	DWORD	dwStencilBitMask;
-	DWORD	dwBumpLuminanceBitMask;
-    } DUMMYUNIONNAME4;
-    union {
-    	DWORD	dwRGBAlphaBitMask;	/* 1C: mask for alpha channel */
-    	DWORD	dwYUVAlphaBitMask;	/* 1C: mask for alpha channel */
-	DWORD	dwLuminanceAlphaBitMask;
-	DWORD	dwRGBZBitMask;		/* 1C: mask for Z channel */
-	DWORD	dwYUVZBitMask;		/* 1C: mask for Z channel */
-    } DUMMYUNIONNAME5;
-    					/* 20: next structure */
-} DDPIXELFORMAT,*LPDDPIXELFORMAT;
-
-/* DDCAPS.dwFXCaps */
-#define DDFXCAPS_BLTALPHA               0x00000001
-#define DDFXCAPS_OVERLAYALPHA           0x00000004
-#define DDFXCAPS_BLTARITHSTRETCHYN	0x00000010
-#define DDFXCAPS_BLTARITHSTRETCHY	0x00000020
-#define DDFXCAPS_BLTMIRRORLEFTRIGHT	0x00000040
-#define DDFXCAPS_BLTMIRRORUPDOWN	0x00000080
-#define DDFXCAPS_BLTROTATION		0x00000100
-#define DDFXCAPS_BLTROTATION90		0x00000200
-#define DDFXCAPS_BLTSHRINKX		0x00000400
-#define DDFXCAPS_BLTSHRINKXN		0x00000800
-#define DDFXCAPS_BLTSHRINKY		0x00001000
-#define DDFXCAPS_BLTSHRINKYN		0x00002000
-#define DDFXCAPS_BLTSTRETCHX		0x00004000
-#define DDFXCAPS_BLTSTRETCHXN		0x00008000
-#define DDFXCAPS_BLTSTRETCHY		0x00010000
-#define DDFXCAPS_BLTSTRETCHYN		0x00020000
-#define DDFXCAPS_OVERLAYARITHSTRETCHY	0x00040000
-#define DDFXCAPS_OVERLAYARITHSTRETCHYN	0x00000008
-#define DDFXCAPS_OVERLAYSHRINKX		0x00080000
-#define DDFXCAPS_OVERLAYSHRINKXN	0x00100000
-#define DDFXCAPS_OVERLAYSHRINKY		0x00200000
-#define DDFXCAPS_OVERLAYSHRINKYN	0x00400000
-#define DDFXCAPS_OVERLAYSTRETCHX	0x00800000
-#define DDFXCAPS_OVERLAYSTRETCHXN	0x01000000
-#define DDFXCAPS_OVERLAYSTRETCHY	0x02000000
-#define DDFXCAPS_OVERLAYSTRETCHYN	0x04000000
-#define DDFXCAPS_OVERLAYMIRRORLEFTRIGHT	0x08000000
-#define DDFXCAPS_OVERLAYMIRRORUPDOWN	0x10000000
-
-#define DDFXCAPS_OVERLAYFILTER          DDFXCAPS_OVERLAYARITHSTRETCHY
-
-/* DDCAPS.dwFXAlphaCaps */
-#define DDFXALPHACAPS_BLTALPHAEDGEBLEND		0x00000001
-#define DDFXALPHACAPS_BLTALPHAPIXELS		0x00000002
-#define DDFXALPHACAPS_BLTALPHAPIXELSNEG		0x00000004
-#define DDFXALPHACAPS_BLTALPHASURFACES		0x00000008
-#define DDFXALPHACAPS_BLTALPHASURFACESNEG	0x00000010
-#define DDFXALPHACAPS_OVERLAYALPHAEDGEBLEND	0x00000020
-#define DDFXALPHACAPS_OVERLAYALPHAPIXELS	0x00000040
-#define DDFXALPHACAPS_OVERLAYALPHAPIXELSNEG	0x00000080
-#define DDFXALPHACAPS_OVERLAYALPHASURFACES	0x00000100
-#define DDFXALPHACAPS_OVERLAYALPHASURFACESNEG	0x00000200
-
-/* DDCAPS.dwPalCaps */
-#define DDPCAPS_4BIT			0x00000001
-#define DDPCAPS_8BITENTRIES		0x00000002
-#define DDPCAPS_8BIT			0x00000004
-#define DDPCAPS_INITIALIZE		0x00000008
-#define DDPCAPS_PRIMARYSURFACE		0x00000010
-#define DDPCAPS_PRIMARYSURFACELEFT	0x00000020
-#define DDPCAPS_ALLOW256		0x00000040
-#define DDPCAPS_VSYNC			0x00000080
-#define DDPCAPS_1BIT			0x00000100
-#define DDPCAPS_2BIT			0x00000200
-#define DDPCAPS_ALPHA                   0x00000400
-
-/* DDCAPS.dwSVCaps */
-/* the first 4 of these are now obsolete */
-#if DIRECTDRAW_VERSION >= 0x700	/* FIXME: I'm not sure when this switch occured */
-#define DDSVCAPS_RESERVED1		0x00000001
-#define DDSVCAPS_RESERVED2		0x00000002
-#define DDSVCAPS_RESERVED3		0x00000004
-#define DDSVCAPS_RESERVED4		0x00000008
-#else
-#define DDSVCAPS_ENIGMA			0x00000001
-#define DDSVCAPS_FLICKER		0x00000002
-#define DDSVCAPS_REDBLUE		0x00000004
-#define DDSVCAPS_SPLIT			0x00000008
-#endif
-#define DDSVCAPS_STEREOSEQUENTIAL       0x00000010
-
-/* BitDepths */
-#define DDBD_1				0x00004000
-#define DDBD_2				0x00002000
-#define DDBD_4				0x00001000
-#define DDBD_8				0x00000800
-#define DDBD_16				0x00000400
-#define DDBD_24				0x00000200
-#define DDBD_32				0x00000100
-
-/* DDOVERLAYFX.dwDDFX */
-#define DDOVERFX_ARITHSTRETCHY		0x00000001
-#define DDOVERFX_MIRRORLEFTRIGHT	0x00000002
-#define DDOVERFX_MIRRORUPDOWN		0x00000004
-
-/* UpdateOverlay flags */
-#define DDOVER_ALPHADEST                        0x00000001
-#define DDOVER_ALPHADESTCONSTOVERRIDE           0x00000002
-#define DDOVER_ALPHADESTNEG                     0x00000004
-#define DDOVER_ALPHADESTSURFACEOVERRIDE         0x00000008
-#define DDOVER_ALPHAEDGEBLEND                   0x00000010
-#define DDOVER_ALPHASRC                         0x00000020
-#define DDOVER_ALPHASRCCONSTOVERRIDE            0x00000040
-#define DDOVER_ALPHASRCNEG                      0x00000080
-#define DDOVER_ALPHASRCSURFACEOVERRIDE          0x00000100
-#define DDOVER_HIDE                             0x00000200
-#define DDOVER_KEYDEST                          0x00000400
-#define DDOVER_KEYDESTOVERRIDE                  0x00000800
-#define DDOVER_KEYSRC                           0x00001000
-#define DDOVER_KEYSRCOVERRIDE                   0x00002000
-#define DDOVER_SHOW                             0x00004000
-#define DDOVER_ADDDIRTYRECT                     0x00008000
-#define DDOVER_REFRESHDIRTYRECTS                0x00010000
-#define DDOVER_REFRESHALL                       0x00020000
-#define DDOVER_DDFX                             0x00080000
-#define DDOVER_AUTOFLIP                         0x00100000
-#define DDOVER_BOB                              0x00200000
-#define DDOVER_OVERRIDEBOBWEAVE                 0x00400000
-#define DDOVER_INTERLEAVED                      0x00800000
-
-/* DDCOLORKEY.dwFlags */
-#define DDPF_ALPHAPIXELS		0x00000001
-#define DDPF_ALPHA			0x00000002
-#define DDPF_FOURCC			0x00000004
-#define DDPF_PALETTEINDEXED4		0x00000008
-#define DDPF_PALETTEINDEXEDTO8		0x00000010
-#define DDPF_PALETTEINDEXED8		0x00000020
-#define DDPF_RGB			0x00000040
-#define DDPF_COMPRESSED			0x00000080
-#define DDPF_RGBTOYUV			0x00000100
-#define DDPF_YUV			0x00000200
-#define DDPF_ZBUFFER			0x00000400
-#define DDPF_PALETTEINDEXED1		0x00000800
-#define DDPF_PALETTEINDEXED2		0x00001000
-#define DDPF_ZPIXELS			0x00002000
-#define DDPF_STENCILBUFFER              0x00004000
-#define DDPF_ALPHAPREMULT               0x00008000
-#define DDPF_LUMINANCE                  0x00020000
-#define DDPF_BUMPLUMINANCE              0x00040000
-#define DDPF_BUMPDUDV                   0x00080000
-
-/* SetCooperativeLevel dwFlags */
-#define DDSCL_FULLSCREEN		0x00000001
-#define DDSCL_ALLOWREBOOT		0x00000002
-#define DDSCL_NOWINDOWCHANGES		0x00000004
-#define DDSCL_NORMAL			0x00000008
-#define DDSCL_EXCLUSIVE			0x00000010
-#define DDSCL_ALLOWMODEX		0x00000040
-#define DDSCL_SETFOCUSWINDOW		0x00000080
-#define DDSCL_SETDEVICEWINDOW		0x00000100
-#define DDSCL_CREATEDEVICEWINDOW	0x00000200
-#define DDSCL_MULTITHREADED             0x00000400
-#define DDSCL_FPUSETUP                  0x00000800
-#define DDSCL_FPUPRESERVE               0x00001000
-
-
-/* DDSURFACEDESC.dwFlags */
-#define	DDSD_CAPS		0x00000001
-#define	DDSD_HEIGHT		0x00000002
-#define	DDSD_WIDTH		0x00000004
-#define	DDSD_PITCH		0x00000008
-#define	DDSD_BACKBUFFERCOUNT	0x00000020
-#define	DDSD_ZBUFFERBITDEPTH	0x00000040
-#define	DDSD_ALPHABITDEPTH	0x00000080
-#define	DDSD_LPSURFACE		0x00000800
-#define	DDSD_PIXELFORMAT	0x00001000
-#define	DDSD_CKDESTOVERLAY	0x00002000
-#define	DDSD_CKDESTBLT		0x00004000
-#define	DDSD_CKSRCOVERLAY	0x00008000
-#define	DDSD_CKSRCBLT		0x00010000
-#define	DDSD_MIPMAPCOUNT	0x00020000
-#define	DDSD_REFRESHRATE	0x00040000
-#define	DDSD_LINEARSIZE		0x00080000
-#define DDSD_TEXTURESTAGE       0x00100000
-#define DDSD_FVF                0x00200000
-#define DDSD_SRCVBHANDLE        0x00400000
-#define	DDSD_ALL		0x007ff9ee
-
-/* EnumSurfaces flags */
-#define DDENUMSURFACES_ALL          0x00000001
-#define DDENUMSURFACES_MATCH        0x00000002
-#define DDENUMSURFACES_NOMATCH      0x00000004
-#define DDENUMSURFACES_CANBECREATED 0x00000008
-#define DDENUMSURFACES_DOESEXIST    0x00000010
-
-/* SetDisplayMode flags */
-#define DDSDM_STANDARDVGAMODE	0x00000001
-
-/* EnumDisplayModes flags */
-#define DDEDM_REFRESHRATES	0x00000001
-#define DDEDM_STANDARDVGAMODES	0x00000002
-
-/* WaitForVerticalDisplay flags */
-
-#define DDWAITVB_BLOCKBEGIN		0x00000001
-#define DDWAITVB_BLOCKBEGINEVENT	0x00000002
-#define DDWAITVB_BLOCKEND		0x00000004
-
-typedef struct _DDSURFACEDESC
-{
-	DWORD	dwSize;		/* 0: size of the DDSURFACEDESC structure*/
-	DWORD	dwFlags;	/* 4: determines what fields are valid*/
-	DWORD	dwHeight;	/* 8: height of surface to be created*/
-	DWORD	dwWidth;	/* C: width of input surface*/
-	union {
-		LONG	lPitch;	/* 10: distance to start of next line (return value only)*/
-		DWORD	dwLinearSize;
-	} DUMMYUNIONNAME1;
-	DWORD	dwBackBufferCount;/* 14: number of back buffers requested*/
-	union {
-		DWORD	dwMipMapCount;/* 18:number of mip-map levels requested*/
-		DWORD	dwZBufferBitDepth;/*18: depth of Z buffer requested*/
-		DWORD	dwRefreshRate;/* 18:refresh rate (used when display mode is described)*/
-	} DUMMYUNIONNAME2;		
-	DWORD	dwAlphaBitDepth;/* 1C:depth of alpha buffer requested*/
-	DWORD	dwReserved;	/* 20:reserved*/
-	LPVOID	lpSurface;	/* 24:pointer to the associated surface memory*/
-	DDCOLORKEY	ddckCKDestOverlay;/* 28: CK for dest overlay use*/
-	DDCOLORKEY	ddckCKDestBlt;	/* 30: CK for destination blt use*/
-	DDCOLORKEY	ddckCKSrcOverlay;/* 38: CK for source overlay use*/
-	DDCOLORKEY	ddckCKSrcBlt;	/* 40: CK for source blt use*/
-	DDPIXELFORMAT	ddpfPixelFormat;/* 48: pixel format description of the surface*/
-	DDSCAPS		ddsCaps;	/* 68: direct draw surface caps */
-} DDSURFACEDESC,*LPDDSURFACEDESC;
-
-typedef struct _DDSURFACEDESC2
-{
-	DWORD	dwSize;		/* 0: size of the DDSURFACEDESC structure*/
-	DWORD	dwFlags;	/* 4: determines what fields are valid*/
-	DWORD	dwHeight;	/* 8: height of surface to be created*/
-	DWORD	dwWidth;	/* C: width of input surface*/
-	union {
-		LONG	lPitch;	      /*10: distance to start of next line (return value only)*/
-		DWORD   dwLinearSize; /*10: formless late-allocated optimized surface size */
-	} DUMMYUNIONNAME1;
-	DWORD	dwBackBufferCount;/* 14: number of back buffers requested*/
-	union {
-		DWORD	dwMipMapCount;/* 18:number of mip-map levels requested*/
-		DWORD	dwRefreshRate;/* 18:refresh rate (used when display mode is described)*/
-		DWORD   dwSrcVBHandle;/* 18:source used in VB::Optimize */
-	} DUMMYUNIONNAME2;
-	DWORD	dwAlphaBitDepth;/* 1C:depth of alpha buffer requested*/
-	DWORD	dwReserved;	/* 20:reserved*/
-	LPVOID	lpSurface;	/* 24:pointer to the associated surface memory*/
-	union {
-		DDCOLORKEY	ddckCKDestOverlay; /* 28: CK for dest overlay use*/
-		DWORD 		dwEmptyFaceColor;  /* 28: color for empty cubemap faces */
-	} DUMMYUNIONNAME3;
-	DDCOLORKEY	ddckCKDestBlt;	/* 30: CK for destination blt use*/
-	DDCOLORKEY	ddckCKSrcOverlay;/* 38: CK for source overlay use*/
-	DDCOLORKEY	ddckCKSrcBlt;	/* 40: CK for source blt use*/
-
-	union {
-		DDPIXELFORMAT	ddpfPixelFormat;/* 48: pixel format description of the surface*/
-		DWORD 		dwFVF;	/* 48: vertex format description of vertex buffers */	
-	} DUMMYUNIONNAME4;
-	DDSCAPS2	ddsCaps;  /* 68: DDraw surface caps */
-	DWORD		dwTextureStage; /* 78: stage in multitexture cascade */
-} DDSURFACEDESC2,*LPDDSURFACEDESC2;
-
-/* DDCOLORCONTROL.dwFlags */
-#define DDCOLOR_BRIGHTNESS	0x00000001
-#define DDCOLOR_CONTRAST	0x00000002
-#define DDCOLOR_HUE		0x00000004
-#define DDCOLOR_SATURATION	0x00000008
-#define DDCOLOR_SHARPNESS	0x00000010
-#define DDCOLOR_GAMMA		0x00000020
-#define DDCOLOR_COLORENABLE	0x00000040
-
-typedef struct {
-	DWORD	dwSize;
-	DWORD	dwFlags;
-	LONG	lBrightness;
-	LONG	lContrast;
-	LONG	lHue;
-	LONG	lSaturation;
-	LONG	lSharpness;
-	LONG	lGamma;
-	LONG	lColorEnable;
-	DWORD	dwReserved1;
-} DDCOLORCONTROL,*LPDDCOLORCONTROL;
-
-typedef struct {
-	WORD	red[256];
-	WORD	green[256];
-	WORD	blue[256];
-} DDGAMMARAMP,*LPDDGAMMARAMP;
-
-typedef BOOL CALLBACK (*LPDDENUMCALLBACKA)(GUID *, LPSTR, LPSTR, LPVOID);
-typedef BOOL CALLBACK (*LPDDENUMCALLBACKW)(GUID *, LPWSTR, LPWSTR, LPVOID);
-DECL_WINELIB_TYPE_AW(LPDDENUMCALLBACK)
-
-typedef HRESULT CALLBACK (*LPDDENUMMODESCALLBACK)(LPDDSURFACEDESC, LPVOID);
-typedef HRESULT CALLBACK (*LPDDENUMMODESCALLBACK2)(LPDDSURFACEDESC2, LPVOID);
-typedef HRESULT CALLBACK (*LPDDENUMSURFACESCALLBACK)(LPDIRECTDRAWSURFACE, LPDDSURFACEDESC, LPVOID);
-typedef HRESULT CALLBACK (*LPDDENUMSURFACESCALLBACK2)(LPDIRECTDRAWSURFACE4, LPDDSURFACEDESC2, LPVOID);
-typedef HRESULT CALLBACK (*LPDDENUMSURFACESCALLBACK7)(LPDIRECTDRAWSURFACE7, LPDDSURFACEDESC2, LPVOID);
-
-typedef BOOL CALLBACK (*LPDDENUMCALLBACKEXA)(GUID *, LPSTR, LPSTR, LPVOID, HMONITOR);
-typedef BOOL CALLBACK (*LPDDENUMCALLBACKEXW)(GUID *, LPWSTR, LPWSTR, LPVOID, HMONITOR);
-DECL_WINELIB_TYPE_AW(LPDDENUMCALLBACKEX)
-
-HRESULT WINAPI DirectDrawEnumerateExA( LPDDENUMCALLBACKEXA lpCallback, LPVOID lpContext, DWORD dwFlags);
-HRESULT WINAPI DirectDrawEnumerateExW( LPDDENUMCALLBACKEXW lpCallback, LPVOID lpContext, DWORD dwFlags);
-#define DirectDrawEnumerateEx WINELIB_NAME_AW(DirectDrawEnumerateEx)
-
-/* flags for DirectDrawEnumerateEx */
-#define DDENUM_ATTACHEDSECONDARYDEVICES	0x00000001
-#define DDENUM_DETACHEDSECONDARYDEVICES	0x00000002
-#define DDENUM_NONDISPLAYDEVICES	0x00000004
-
-/* flags for DirectDrawCreate or IDirectDraw::Initialize */
-#define DDCREATE_HARDWAREONLY	1L
-#define DDCREATE_EMULATIONONLY	2L
-
-typedef struct _DDBLTFX
-{
-    DWORD       dwSize;                         /* size of structure */
-    DWORD       dwDDFX;                         /* FX operations */
-    DWORD       dwROP;                          /* Win32 raster operations */
-    DWORD       dwDDROP;                        /* Raster operations new for DirectDraw */
-    DWORD       dwRotationAngle;                /* Rotation angle for blt */
-    DWORD       dwZBufferOpCode;                /* ZBuffer compares */
-    DWORD       dwZBufferLow;                   /* Low limit of Z buffer */
-    DWORD       dwZBufferHigh;                  /* High limit of Z buffer */
-    DWORD       dwZBufferBaseDest;              /* Destination base value */
-    DWORD       dwZDestConstBitDepth;           /* Bit depth used to specify Z constant for destination */
-    union
-    {
-        DWORD   dwZDestConst;                   /* Constant to use as Z buffer for dest */
-        LPDIRECTDRAWSURFACE lpDDSZBufferDest;   /* Surface to use as Z buffer for dest */
-    } DUMMYUNIONNAME1;
-    DWORD       dwZSrcConstBitDepth;            /* Bit depth used to specify Z constant for source */
-    union
-    {
-        DWORD   dwZSrcConst;                    /* Constant to use as Z buffer for src */
-        LPDIRECTDRAWSURFACE lpDDSZBufferSrc;    /* Surface to use as Z buffer for src */
-    } DUMMYUNIONNAME2;
-    DWORD       dwAlphaEdgeBlendBitDepth;       /* Bit depth used to specify constant for alpha edge blend */
-    DWORD       dwAlphaEdgeBlend;               /* Alpha for edge blending */
-    DWORD       dwReserved;
-    DWORD       dwAlphaDestConstBitDepth;       /* Bit depth used to specify alpha constant for destination */
-    union
-    {
-        DWORD   dwAlphaDestConst;               /* Constant to use as Alpha Channel */
-        LPDIRECTDRAWSURFACE lpDDSAlphaDest;     /* Surface to use as Alpha Channel */
-    } DUMMYUNIONNAME3;
-    DWORD       dwAlphaSrcConstBitDepth;        /* Bit depth used to specify alpha constant for source */
-    union
-    {
-        DWORD   dwAlphaSrcConst;                /* Constant to use as Alpha Channel */
-        LPDIRECTDRAWSURFACE lpDDSAlphaSrc;      /* Surface to use as Alpha Channel */
-    } DUMMYUNIONNAME4;
-    union
-    {
-        DWORD   dwFillColor;                    /* color in RGB or Palettized */
-        DWORD   dwFillDepth;                    /* depth value for z-buffer */
-	DWORD   dwFillPixel;			/* pixel val for RGBA or RGBZ */
-        LPDIRECTDRAWSURFACE lpDDSPattern;       /* Surface to use as pattern */
-    } DUMMYUNIONNAME5;
-    DDCOLORKEY  ddckDestColorkey;               /* DestColorkey override */
-    DDCOLORKEY  ddckSrcColorkey;                /* SrcColorkey override */
-} DDBLTFX,*LPDDBLTFX;
-
-/* dwDDFX */
-/* arithmetic stretching along y axis */
-#define DDBLTFX_ARITHSTRETCHY			0x00000001
-/* mirror on y axis */
-#define DDBLTFX_MIRRORLEFTRIGHT			0x00000002
-/* mirror on x axis */
-#define DDBLTFX_MIRRORUPDOWN			0x00000004
-/* do not tear */
-#define DDBLTFX_NOTEARING			0x00000008
-/* 180 degrees clockwise rotation */
-#define DDBLTFX_ROTATE180			0x00000010
-/* 270 degrees clockwise rotation */
-#define DDBLTFX_ROTATE270			0x00000020
-/* 90 degrees clockwise rotation */
-#define DDBLTFX_ROTATE90			0x00000040
-/* dwZBufferLow and dwZBufferHigh specify limits to the copied Z values */
-#define DDBLTFX_ZBUFFERRANGE			0x00000080
-/* add dwZBufferBaseDest to every source z value before compare */
-#define DDBLTFX_ZBUFFERBASEDEST			0x00000100
-
-typedef struct _DDOVERLAYFX
-{
-    DWORD       dwSize;                         /* size of structure */
-    DWORD       dwAlphaEdgeBlendBitDepth;       /* Bit depth used to specify constant for alpha edge blend */
-    DWORD       dwAlphaEdgeBlend;               /* Constant to use as alpha for edge blend */
-    DWORD       dwReserved;
-    DWORD       dwAlphaDestConstBitDepth;       /* Bit depth used to specify alpha constant for destination */
-    union
-    {
-        DWORD   dwAlphaDestConst;               /* Constant to use as alpha channel for dest */
-        LPDIRECTDRAWSURFACE lpDDSAlphaDest;     /* Surface to use as alpha channel for dest */
-    } DUMMYUNIONNAME1;
-    DWORD       dwAlphaSrcConstBitDepth;        /* Bit depth used to specify alpha constant for source */
-    union
-    {
-        DWORD   dwAlphaSrcConst;                /* Constant to use as alpha channel for src */
-        LPDIRECTDRAWSURFACE lpDDSAlphaSrc;      /* Surface to use as alpha channel for src */
-    } DUMMYUNIONNAME2;
-    DDCOLORKEY  dckDestColorkey;                /* DestColorkey override */
-    DDCOLORKEY  dckSrcColorkey;                 /* DestColorkey override */
-    DWORD       dwDDFX;                         /* Overlay FX */
-    DWORD       dwFlags;                        /* flags */
-} DDOVERLAYFX,*LPDDOVERLAYFX;
-
-typedef struct _DDBLTBATCH
-{
-    LPRECT		lprDest;
-    LPDIRECTDRAWSURFACE	lpDDSSrc;
-    LPRECT		lprSrc;
-    DWORD		dwFlags;
-    LPDDBLTFX		lpDDBltFx;
-} DDBLTBATCH,*LPDDBLTBATCH;
-
-#define MAX_DDDEVICEID_STRING          512
-
-typedef struct tagDDDEVICEIDENTIFIER {
-  char    szDriver[MAX_DDDEVICEID_STRING];
-  char    szDescription[MAX_DDDEVICEID_STRING];
-  LARGE_INTEGER  liDriverVersion;
-  DWORD   dwVendorId;
-  DWORD   dwDeviceId;
-  DWORD   dwSubSysId;
-  DWORD   dwRevision;
-  GUID    guidDeviceIdentifier;
-} DDDEVICEIDENTIFIER, * LPDDDEVICEIDENTIFIER;
-
-typedef struct tagDDDEVICEIDENTIFIER2 {
-  char    szDriver[MAX_DDDEVICEID_STRING];	/* user readable driver name */
-  char    szDescription[MAX_DDDEVICEID_STRING]; /* user readable description */
-  LARGE_INTEGER  liDriverVersion;		/* driver version */
-  DWORD   dwVendorId;				/* vendor ID, zero if unknown */
-  DWORD   dwDeviceId;				/* chipset ID, zero if unknown */
-  DWORD   dwSubSysId;				/* board ID, zero if unknown */
-  DWORD   dwRevision;				/* chipset version, zero if unknown */
-  GUID    guidDeviceIdentifier;			/* unique ID for this driver/chipset combination */
-  DWORD   dwWHQLLevel;				/* Windows Hardware Quality Lab certification level */
-} DDDEVICEIDENTIFIER2, * LPDDDEVICEIDENTIFIER2;
-
-/*****************************************************************************
- * IDirectDrawPalette interface
- */
-#undef INTERFACE
-#define INTERFACE IDirectDrawPalette
-DECLARE_INTERFACE_(IDirectDrawPalette,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE;
-    STDMETHOD(GetCaps)(THIS_ LPDWORD lpdwCaps) PURE;
-    STDMETHOD(GetEntries)(THIS_ DWORD dwFlags, DWORD dwBase, DWORD dwNumEntries, LPPALETTEENTRY lpEntries) PURE;
-    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, DWORD dwFlags, LPPALETTEENTRY lpDDColorTable) PURE;
-    STDMETHOD(SetEntries)(THIS_ DWORD dwFlags, DWORD dwStartingEntry, DWORD dwCount, LPPALETTEENTRY lpEntries) PURE;
-};
-
-    /*** IUnknown methods ***/
-#define IDirectDrawPalette_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDrawPalette_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDrawPalette_Release(p)            ICOM_CALL_(Release,p,(p))
-    /*** IDirectDrawPalette methods ***/
-#define IDirectDrawPalette_GetCaps(p,a)          ICOM_CALL_(GetCaps,p,(p,a))
-#define IDirectDrawPalette_GetEntries(p,a,b,c,d) ICOM_CALL_(GetEntries,p,(p,a,b,c,d))
-#define IDirectDrawPalette_Initialize(p,a,b,c)   ICOM_CALL_(Initialize,p,(p,a,b,c))
-#define IDirectDrawPalette_SetEntries(p,a,b,c,d) ICOM_CALL_(SetEntries,p,(p,a,b,c,d))
-
-
-/*****************************************************************************
- * IDirectDrawClipper interface
- */
-#undef INTERFACE
-#define INTERFACE IDirectDrawClipper
-DECLARE_INTERFACE_(IDirectDrawClipper,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE;
-    STDMETHOD(GetClipList)(THIS_ LPRECT lpRect, LPRGNDATA lpClipList, LPDWORD lpdwSize) PURE;
-    STDMETHOD(GetHWnd)(THIS_ HWND* lphWnd) PURE;
-    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, DWORD dwFlags) PURE;
-    STDMETHOD(IsClipListChanged)(THIS_ BOOL* lpbChanged) PURE;
-    STDMETHOD(SetClipList)(THIS_ LPRGNDATA lpClipList, DWORD dwFlags) PURE;
-    STDMETHOD(SetHWnd)(THIS_ DWORD dwFlags, HWND hWnd) PURE;
-};
-
-    /*** IUnknown methods ***/
-#define IDirectDrawClipper_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDrawClipper_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDrawClipper_Release(p)            ICOM_CALL_(Release,p,(p))
-    /*** IDirectDrawClipper methods ***/
-#define IDirectDrawClipper_GetClipList(p,a,b,c)   ICOM_CALL_(GetClipList,p,(p,a,b,c))
-#define IDirectDrawClipper_GetHWnd(p,a)           ICOM_CALL_(GetHWnd,p,(p,a))
-#define IDirectDrawClipper_Initialize(p,a,b)      ICOM_CALL_(Initialize,p,(p,a,b))
-#define IDirectDrawClipper_IsClipListChanged(p,a) ICOM_CALL_(IsClipListChanged,p,(p,a))
-#define IDirectDrawClipper_SetClipList(p,a,b)     ICOM_CALL_(SetClipList,p,(p,a,b))
-#define IDirectDrawClipper_SetHWnd(p,a,b)         ICOM_CALL_(SetHWnd,p,(p,a,b))
-
-
-/*****************************************************************************
- * IDirectDraw interface
- */
-#undef INTERFACE
-#define INTERFACE IDirectDraw
-DECLARE_INTERFACE_(IDirectDraw,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE;
-    STDMETHOD(Compact)(THIS) PURE;
-    STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE;
-    STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE;
-    STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc, LPDIRECTDRAWSURFACE* lplpDDSurface, IUnknown* pUnkOuter) PURE;
-    STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE lpDDSurface, LPDIRECTDRAWSURFACE* lplpDupDDSurface) PURE;
-    STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK lpEnumModesCallback) PURE;
-    STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE;
-    STDMETHOD(FlipToGDISurface)(THIS) PURE;
-    STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE;
-    STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE;
-    STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE;
-    STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE* lplpGDIDDSurface) PURE;
-    STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE;
-    STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE;
-    STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE;
-    STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE;
-    STDMETHOD(RestoreDisplayMode)(THIS) PURE;
-    STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE;
-    STDMETHOD(SetDisplayMode)(THIS_ DWORD, DWORD, DWORD) PURE;
-    STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE;
-};
-
-    /*** IUnknown methods ***/
-#define IDirectDraw_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDraw_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDraw_Release(p)            ICOM_CALL_(Release,p,(p))
-    /*** IDirectDraw methods ***/
-#define IDirectDraw_Compact(p)                  ICOM_CALL_(Compact,p,(p))
-#define IDirectDraw_CreateClipper(p,a,b,c)      ICOM_CALL_(CreateClipper,p,(p,a,b,c))
-#define IDirectDraw_CreatePalette(p,a,b,c,d)    ICOM_CALL_(CreatePalette,p,(p,a,b,c,d))
-#define IDirectDraw_CreateSurface(p,a,b,c)      ICOM_CALL_(CreateSurface,p,(p,a,b,c))
-#define IDirectDraw_DuplicateSurface(p,a,b)     ICOM_CALL_(DuplicateSurface,p,(p,a,b))
-#define IDirectDraw_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d))
-#define IDirectDraw_EnumSurfaces(p,a,b,c,d)     ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d))
-#define IDirectDraw_FlipToGDISurface(p)         ICOM_CALL_(FlipToGDISurface,p,(p))
-#define IDirectDraw_GetCaps(p,a,b)              ICOM_CALL_(GetCaps,p,(p,a,b))
-#define IDirectDraw_GetDisplayMode(p,a)         ICOM_CALL_(GetDisplayMode,p,(p,a))
-#define IDirectDraw_GetFourCCCodes(p,a,b)       ICOM_CALL_(GetFourCCCodes,p,(p,a,b))
-#define IDirectDraw_GetGDISurface(p,a)          ICOM_CALL_(GetGDISurface,p,(p,a))
-#define IDirectDraw_GetMonitorFrequency(p,a)    ICOM_CALL_(GetMonitorFrequency,p,(p,a))
-#define IDirectDraw_GetScanLine(p,a)            ICOM_CALL_(GetScanLine,p,(p,a))
-#define IDirectDraw_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a))
-#define IDirectDraw_Initialize(p,a)             ICOM_CALL_(Initialize,p,(p,a))
-#define IDirectDraw_RestoreDisplayMode(p)       ICOM_CALL_(RestoreDisplayMode,p,(p))
-#define IDirectDraw_SetCooperativeLevel(p,a,b)  ICOM_CALL_(SetCooperativeLevel,p,(p,a,b))
-#define IDirectDraw_SetDisplayMode(p,a,b,c)     ICOM_CALL_(SetDisplayMode,p,(p,a,b,c))
-#define IDirectDraw_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b))
-
-
-/* flags for Lock() */
-#define DDLOCK_SURFACEMEMORYPTR	0x00000000
-#define DDLOCK_WAIT		0x00000001
-#define DDLOCK_EVENT		0x00000002
-#define DDLOCK_READONLY		0x00000010
-#define DDLOCK_WRITEONLY	0x00000020
-#define DDLOCK_NOSYSLOCK	0x00000800
-
-
-/*****************************************************************************
- * IDirectDraw2 interface
- */
-/* Note: IDirectDraw2 cannot derive from IDirectDraw because the number of 
- * arguments of SetDisplayMode has changed !
- */
-#undef INTERFACE
-#define INTERFACE IDirectDraw2
-DECLARE_INTERFACE_(IDirectDraw2,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE;
-    STDMETHOD(Compact)(THIS) PURE; 
-    STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; 
-    STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; 
-    STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc, LPDIRECTDRAWSURFACE2* lplpDDSurface, IUnknown* pUnkOuter) PURE; 
-    STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE2 lpDDSurface, LPDIRECTDRAWSURFACE2* lplpDupDDSurface) PURE; 
-    STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK lpEnumModesCallback) PURE; 
-    STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
-    STDMETHOD(FlipToGDISurface)(THIS) PURE; 
-    STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; 
-    STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
-    STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; 
-    STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE2* lplpGDIDDSurface) PURE; 
-    STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; 
-    STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; 
-    STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; 
-    STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; 
-    STDMETHOD(RestoreDisplayMode)(THIS) PURE; 
-    STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; 
-    STDMETHOD(SetDisplayMode)(THIS_ DWORD dwWidth, DWORD dwHeight, DWORD dwBPP, DWORD dwRefreshRate, DWORD dwFlags) PURE; 
-    STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; 
-           
-    STDMETHOD(GetAvailableVidMem)(THIS_ LPDDSCAPS lpDDCaps, LPDWORD lpdwTotal, LPDWORD lpdwFree) PURE;
-};
-
-    /*** IUnknown methods ***/
-#define IDirectDraw2_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDraw2_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDraw2_Release(p)            ICOM_CALL_(Release,p,(p))
-    /*** IDirectDraw methods ***/
-#define IDirectDraw2_Compact(p)                  ICOM_CALL_(Compact,p,(p))
-#define IDirectDraw2_CreateClipper(p,a,b,c)      ICOM_CALL_(CreateClipper,p,(p,a,b,c))
-#define IDirectDraw2_CreatePalette(p,a,b,c,d)    ICOM_CALL_(CreatePalette,p,(p,a,b,c,d))
-#define IDirectDraw2_CreateSurface(p,a,b,c)      ICOM_CALL_(CreateSurface,p,(p,a,b,c))
-#define IDirectDraw2_DuplicateSurface(p,a,b)     ICOM_CALL_(DuplicateSurface,p,(p,a,b))
-#define IDirectDraw2_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d))
-#define IDirectDraw2_EnumSurfaces(p,a,b,c,d)     ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d))
-#define IDirectDraw2_FlipToGDISurface(p)         ICOM_CALL_(FlipToGDISurface,p,(p))
-#define IDirectDraw2_GetCaps(p,a,b)              ICOM_CALL_(GetCaps,p,(p,a,b))
-#define IDirectDraw2_GetDisplayMode(p,a)         ICOM_CALL_(GetDisplayMode,p,(p,a))
-#define IDirectDraw2_GetFourCCCodes(p,a,b)       ICOM_CALL_(GetFourCCCodes,p,(p,a,b))
-#define IDirectDraw2_GetGDISurface(p,a)          ICOM_CALL_(GetGDISurface,p,(p,a))
-#define IDirectDraw2_GetMonitorFrequency(p,a)    ICOM_CALL_(GetMonitorFrequency,p,(p,a))
-#define IDirectDraw2_GetScanLine(p,a)            ICOM_CALL_(GetScanLine,p,(p,a))
-#define IDirectDraw2_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a))
-#define IDirectDraw2_Initialize(p,a)             ICOM_CALL_(Initialize,p,(p,a))
-#define IDirectDraw2_RestoreDisplayMode(p)       ICOM_CALL_(RestoreDisplayMode,p,(p))
-#define IDirectDraw2_SetCooperativeLevel(p,a,b)  ICOM_CALL_(SetCooperativeLevel,p,(p,a,b))
-#define IDirectDraw2_SetDisplayMode(p,a,b,c,d,e) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c,d,e))
-#define IDirectDraw2_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b))
-/*** IDirectDraw2 methods ***/
-#define IDirectDraw2_GetAvailableVidMem(p,a,b,c) ICOM_CALL_(GetAvailableVidMem,p,(p,a,b,c))
-
-
-/*****************************************************************************
- * IDirectDraw4 interface
- */
-#undef INTERFACE
-#define INTERFACE IDirectDraw4
-DECLARE_INTERFACE_(IDirectDraw4,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE;
-    STDMETHOD(Compact)(THIS) PURE; 
-    STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; 
-    STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; 
-    STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc, LPDIRECTDRAWSURFACE4* lplpDDSurface, IUnknown* pUnkOuter) PURE; 
-    STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE4 lpDDSurface, LPDIRECTDRAWSURFACE4* lplpDupDDSurface) PURE; 
-    STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK2 lpEnumModesCallback) PURE; 
-    STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK2 lpEnumSurfacesCallback) PURE; 
-    STDMETHOD(FlipToGDISurface)(THIS) PURE; 
-    STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; 
-    STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; 
-    STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; 
-    STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE4* lplpGDIDDSurface) PURE; 
-    STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; 
-    STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; 
-    STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; 
-    STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; 
-    STDMETHOD(RestoreDisplayMode)(THIS) PURE; 
-    STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; 
-    STDMETHOD(SetDisplayMode)(THIS_ DWORD dwWidth, DWORD dwHeight, DWORD dwBPP, DWORD dwRefreshRate, DWORD dwFlags) PURE; 
-    STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; 
-           
-    STDMETHOD(GetAvailableVidMem)(THIS_ LPDDSCAPS2 lpDDCaps, LPDWORD lpdwTotal, LPDWORD lpdwFree) PURE; 
-     
-    STDMETHOD(GetSurfaceFromDC)(THIS_ HDC , LPDIRECTDRAWSURFACE4* ) PURE; 
-    STDMETHOD(RestoreAllSurfaces)(THIS) PURE; 
-    STDMETHOD(TestCooperativeLevel)(THIS) PURE; 
-    STDMETHOD(GetDeviceIdentifier)(THIS_ LPDDDEVICEIDENTIFIER , DWORD ) PURE;
-};
-
-    /*** IUnknown methods ***/
-#define IDirectDraw4_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDraw4_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDraw4_Release(p)            ICOM_CALL_(Release,p,(p))
-    /*** IDirectDraw methods ***/
-#define IDirectDraw4_Compact(p)                  ICOM_CALL_(Compact,p,(p))
-#define IDirectDraw4_CreateClipper(p,a,b,c)      ICOM_CALL_(CreateClipper,p,(p,a,b,c))
-#define IDirectDraw4_CreatePalette(p,a,b,c,d)    ICOM_CALL_(CreatePalette,p,(p,a,b,c,d))
-#define IDirectDraw4_CreateSurface(p,a,b,c)      ICOM_CALL_(CreateSurface,p,(p,a,b,c))
-#define IDirectDraw4_DuplicateSurface(p,a,b)     ICOM_CALL_(DuplicateSurface,p,(p,a,b))
-#define IDirectDraw4_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d))
-#define IDirectDraw4_EnumSurfaces(p,a,b,c,d)     ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d))
-#define IDirectDraw4_FlipToGDISurface(p)         ICOM_CALL_(FlipToGDISurface,p,(p))
-#define IDirectDraw4_GetCaps(p,a,b)              ICOM_CALL_(GetCaps,p,(p,a,b))
-#define IDirectDraw4_GetDisplayMode(p,a)         ICOM_CALL_(GetDisplayMode,p,(p,a))
-#define IDirectDraw4_GetFourCCCodes(p,a,b)       ICOM_CALL_(GetFourCCCodes,p,(p,a,b))
-#define IDirectDraw4_GetGDISurface(p,a)          ICOM_CALL_(GetGDISurface,p,(p,a))
-#define IDirectDraw4_GetMonitorFrequency(p,a)    ICOM_CALL_(GetMonitorFrequency,p,(p,a))
-#define IDirectDraw4_GetScanLine(p,a)            ICOM_CALL_(GetScanLine,p,(p,a))
-#define IDirectDraw4_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a))
-#define IDirectDraw4_Initialize(p,a)             ICOM_CALL_(Initialize,p,(p,a))
-#define IDirectDraw4_RestoreDisplayMode(p)       ICOM_CALL_(RestoreDisplayMode,p,(p))
-#define IDirectDraw4_SetCooperativeLevel(p,a,b)  ICOM_CALL_(SetCooperativeLevel,p,(p,a,b))
-#define IDirectDraw4_SetDisplayMode(p,a,b,c,d,e) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c,d,e))
-#define IDirectDraw4_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b))
-/*** IDirectDraw2 methods ***/
-#define IDirectDraw4_GetAvailableVidMem(p,a,b,c) ICOM_CALL_(GetAvailableVidMem,p,(p,a,b,c))
-/*** IDirectDraw4 methods ***/
-#define IDirectDraw4_GetSurfaceFromDC(p,a,b)    ICOM_CALL_(GetSurfaceFromDC,p,(p,a,b))
-#define IDirectDraw4_RestoreAllSurfaces(pc)     ICOM_CALL_(RestoreAllSurfaces,p,(p))
-#define IDirectDraw4_TestCooperativeLevel(p)    ICOM_CALL_(TestCooperativeLevel,p,(p))
-#define IDirectDraw4_GetDeviceIdentifier(p,a,b) ICOM_CALL_(GetDeviceIdentifier,p,(p,a,b))
-
-
-/*****************************************************************************
- * IDirectDraw7 interface
- */
-/* Note: IDirectDraw7 cannot derive from IDirectDraw4; it is even documented
- * as not interchangeable with earlier DirectDraw interfaces.
- */
-#undef INTERFACE
-#define INTERFACE IDirectDraw7
-DECLARE_INTERFACE_(IDirectDraw7,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE;
-    STDMETHOD(Compact)(THIS) PURE; 
-    STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; 
-    STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; 
-    STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc, LPDIRECTDRAWSURFACE7* lplpDDSurface, IUnknown* pUnkOuter) PURE; 
-    STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE7 lpDDSurface, LPDIRECTDRAWSURFACE7* lplpDupDDSurface) PURE; 
-    STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK2 lpEnumModesCallback) PURE; 
-    STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK7 lpEnumSurfacesCallback) PURE; 
-    STDMETHOD(FlipToGDISurface)(THIS) PURE; 
-    STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; 
-    STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; 
-    STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; 
-    STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE7* lplpGDIDDSurface) PURE; 
-    STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; 
-    STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; 
-    STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; 
-    STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; 
-    STDMETHOD(RestoreDisplayMode)(THIS) PURE; 
-    STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; 
-    STDMETHOD(SetDisplayMode)(THIS_ DWORD dwWidth, DWORD dwHeight, DWORD dwBPP, DWORD dwRefreshRate, DWORD dwFlags) PURE; 
-    STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; 
-           
-    STDMETHOD(GetAvailableVidMem)(THIS_ LPDDSCAPS2 lpDDCaps, LPDWORD lpdwTotal, LPDWORD lpdwFree) PURE; 
-           
-    STDMETHOD(GetSurfaceFromDC)(THIS_ HDC , LPDIRECTDRAWSURFACE7* ) PURE; 
-    STDMETHOD(RestoreAllSurfaces)(THIS) PURE; 
-    STDMETHOD(TestCooperativeLevel)(THIS) PURE; 
-    STDMETHOD(GetDeviceIdentifier)(THIS_ LPDDDEVICEIDENTIFIER2 , DWORD ) PURE; 
-           
-    STDMETHOD(StartModeTest)(THIS_ LPSIZE , DWORD , DWORD ) PURE; 
-    STDMETHOD(EvaluateMode)(THIS_ DWORD , DWORD * ) PURE;
-};
-
-    /*** IUnknown methods ***/
-#define IDirectDraw7_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDraw7_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDraw7_Release(p)            ICOM_CALL_(Release,p,(p))
-    /*** IDirectDraw methods ***/
-#define IDirectDraw7_Compact(p)                  ICOM_CALL_(Compact,p,(p))
-#define IDirectDraw7_CreateClipper(p,a,b,c)      ICOM_CALL_(CreateClipper,p,(p,a,b,c))
-#define IDirectDraw7_CreatePalette(p,a,b,c,d)    ICOM_CALL_(CreatePalette,p,(p,a,b,c,d))
-#define IDirectDraw7_CreateSurface(p,a,b,c)      ICOM_CALL_(CreateSurface,p,(p,a,b,c))
-#define IDirectDraw7_DuplicateSurface(p,a,b)     ICOM_CALL_(DuplicateSurface,p,(p,a,b))
-#define IDirectDraw7_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d))
-#define IDirectDraw7_EnumSurfaces(p,a,b,c,d)     ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d))
-#define IDirectDraw7_FlipToGDISurface(p)         ICOM_CALL_(FlipToGDISurface,p,(p))
-#define IDirectDraw7_GetCaps(p,a,b)              ICOM_CALL_(GetCaps,p,(p,a,b))
-#define IDirectDraw7_GetDisplayMode(p,a)         ICOM_CALL_(GetDisplayMode,p,(p,a))
-#define IDirectDraw7_GetFourCCCodes(p,a,b)       ICOM_CALL_(GetFourCCCodes,p,(p,a,b))
-#define IDirectDraw7_GetGDISurface(p,a)          ICOM_CALL_(GetGDISurface,p,(p,a))
-#define IDirectDraw7_GetMonitorFrequency(p,a)    ICOM_CALL_(GetMonitorFrequency,p,(p,a))
-#define IDirectDraw7_GetScanLine(p,a)            ICOM_CALL_(GetScanLine,p,(p,a))
-#define IDirectDraw7_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a))
-#define IDirectDraw7_Initialize(p,a)             ICOM_CALL_(Initialize,p,(p,a))
-#define IDirectDraw7_RestoreDisplayMode(p)       ICOM_CALL_(RestoreDisplayMode,p,(p))
-#define IDirectDraw7_SetCooperativeLevel(p,a,b)  ICOM_CALL_(SetCooperativeLevel,p,(p,a,b))
-#define IDirectDraw7_SetDisplayMode(p,a,b,c,d,e) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c,d,e))
-#define IDirectDraw7_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b))
-/*** added in IDirectDraw2 ***/
-#define IDirectDraw7_GetAvailableVidMem(p,a,b,c) ICOM_CALL_(GetAvailableVidMem,p,(p,a,b,c))
-/*** added in IDirectDraw4 ***/
-#define IDirectDraw7_GetSurfaceFromDC(p,a,b)    ICOM_CALL_(GetSurfaceFromDC,p,(p,a,b))
-#define IDirectDraw7_RestoreAllSurfaces(p)     ICOM_CALL_(RestoreAllSurfaces,p,(p))
-#define IDirectDraw7_TestCooperativeLevel(p)    ICOM_CALL_(TestCooperativeLevel,p,(p))
-#define IDirectDraw7_GetDeviceIdentifier(p,a,b) ICOM_CALL_(GetDeviceIdentifier,p,(p,a,b))
-/*** added in IDirectDraw 7 ***/
-#define IDirectDraw7_StartModeTest(p,a,b,c)     ICOM_CALL_(StartModeTest,p,(p,a,b,c))
-#define IDirectDraw7_EvaluateMode(p,a,b)        ICOM_CALL_(EvaluateMode,p,(p,a,b))
-
-
-/*****************************************************************************
- * IDirectDrawSurface interface
- */
-#undef INTERFACE
-#define INTERFACE IDirectDrawSurface
-DECLARE_INTERFACE_(IDirectDrawSurface,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE; 
-    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE lpDDSAttachedSurface) PURE; 
-    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
-    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
-    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
-    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
-    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE lpDDSAttachedSurface) PURE; 
-    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
-    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; 
-    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
-    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS lpDDSCaps, LPDIRECTDRAWSURFACE* lplpDDAttachedSurface) PURE; 
-    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS lpDDSCaps) PURE; 
-    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
-    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
-    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
-    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
-    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
-    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
-    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
-    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
-    STDMETHOD(IsLost)(THIS) PURE; 
-    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
-    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
-    STDMETHOD(Restore)(THIS) PURE; 
-    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
-    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
-    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
-    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
-    STDMETHOD(Unlock)(THIS_ LPVOID lpSurfaceData) PURE; 
-    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
-    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE lpDDSReference) PURE;
-};
-
-    /*** IUnknown methods ***/
-#define IDirectDrawSurface_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDrawSurface_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDrawSurface_Release(p)            ICOM_CALL_(Release,p,(p))
-    /*** IDirectDrawSurface methods ***/
-#define IDirectDrawSurface_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
-#define IDirectDrawSurface_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
-#define IDirectDrawSurface_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
-#define IDirectDrawSurface_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
-#define IDirectDrawSurface_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
-#define IDirectDrawSurface_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
-#define IDirectDrawSurface_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
-#define IDirectDrawSurface_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
-#define IDirectDrawSurface_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
-#define IDirectDrawSurface_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
-#define IDirectDrawSurface_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
-#define IDirectDrawSurface_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
-#define IDirectDrawSurface_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
-#define IDirectDrawSurface_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
-#define IDirectDrawSurface_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
-#define IDirectDrawSurface_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
-#define IDirectDrawSurface_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
-#define IDirectDrawSurface_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
-#define IDirectDrawSurface_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
-#define IDirectDrawSurface_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
-#define IDirectDrawSurface_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
-#define IDirectDrawSurface_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
-#define IDirectDrawSurface_Restore(p)                   ICOM_CALL_(Restore,p,(p))
-#define IDirectDrawSurface_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
-#define IDirectDrawSurface_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
-#define IDirectDrawSurface_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
-#define IDirectDrawSurface_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
-#define IDirectDrawSurface_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
-#define IDirectDrawSurface_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
-#define IDirectDrawSurface_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
-
-
-/*****************************************************************************
- * IDirectDrawSurface2 interface
- */
-/* Cannot inherit from IDirectDrawSurface because the LPDIRECTDRAWSURFACE parameters 
- * have been converted to LPDIRECTDRAWSURFACE2.
- */
-#undef INTERFACE
-#define INTERFACE IDirectDrawSurface2
-DECLARE_INTERFACE_(IDirectDrawSurface2,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE; 
-    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE2 lpDDSAttachedSurface) PURE; 
-    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
-    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE2 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
-    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
-    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE2 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
-    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE2 lpDDSAttachedSurface) PURE; 
-    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
-    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; 
-    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE2 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
-    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS lpDDSCaps, LPDIRECTDRAWSURFACE2* lplpDDAttachedSurface) PURE; 
-    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS lpDDSCaps) PURE; 
-    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
-    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
-    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
-    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
-    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
-    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
-    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
-    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
-    STDMETHOD(IsLost)(THIS) PURE; 
-    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
-    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
-    STDMETHOD(Restore)(THIS) PURE; 
-    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
-    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
-    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
-    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
-    STDMETHOD(Unlock)(THIS_ LPVOID lpSurfaceData) PURE; 
-    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE2 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
-    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE2 lpDDSReference) PURE; 
-    /* added in v2 */ 
-    STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; 
-    STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE;
-};
-
-    /*** IUnknown methods ***/
-#define IDirectDrawSurface2_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDrawSurface2_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDrawSurface2_Release(p)            ICOM_CALL_(Release,p,(p))
-/*** IDirectDrawSurface methods (almost) ***/
-#define IDirectDrawSurface2_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
-#define IDirectDrawSurface2_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
-#define IDirectDrawSurface2_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface2_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
-#define IDirectDrawSurface2_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface2_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
-#define IDirectDrawSurface2_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
-#define IDirectDrawSurface2_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
-#define IDirectDrawSurface2_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
-#define IDirectDrawSurface2_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
-#define IDirectDrawSurface2_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
-#define IDirectDrawSurface2_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
-#define IDirectDrawSurface2_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
-#define IDirectDrawSurface2_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
-#define IDirectDrawSurface2_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
-#define IDirectDrawSurface2_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
-#define IDirectDrawSurface2_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
-#define IDirectDrawSurface2_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
-#define IDirectDrawSurface2_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
-#define IDirectDrawSurface2_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
-#define IDirectDrawSurface2_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
-#define IDirectDrawSurface2_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
-#define IDirectDrawSurface2_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
-#define IDirectDrawSurface2_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
-#define IDirectDrawSurface2_Restore(p)                   ICOM_CALL_(Restore,p,(p))
-#define IDirectDrawSurface2_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
-#define IDirectDrawSurface2_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
-#define IDirectDrawSurface2_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
-#define IDirectDrawSurface2_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
-#define IDirectDrawSurface2_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
-#define IDirectDrawSurface2_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface2_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
-#define IDirectDrawSurface2_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
-/*** IDirectDrawSurface2 methods ***/
-#define IDirectDrawSurface2_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a))
-#define IDirectDrawSurface2_PageLock(p,a)       ICOM_CALL_(PageLock,p,(p,a))
-#define IDirectDrawSurface2_PageUnlock(p,a)     ICOM_CALL_(PageUnlock,p,(p,a))
-
-
-/*****************************************************************************
- * IDirectDrawSurface3 interface
- */
-/* Cannot inherit from IDirectDrawSurface2 because the LPDIRECTDRAWSURFACE2 parameters 
- * have been converted to LPDIRECTDRAWSURFACE3.
- */
-#undef INTERFACE
-#define INTERFACE IDirectDrawSurface3
-DECLARE_INTERFACE_(IDirectDrawSurface3,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE; 
-    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE3 lpDDSAttachedSurface) PURE; 
-    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
-    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE3 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
-    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
-    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE3 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
-    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE3 lpDDSAttachedSurface) PURE; 
-    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
-    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; 
-    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE3 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
-    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS lpDDSCaps, LPDIRECTDRAWSURFACE3* lplpDDAttachedSurface) PURE; 
-    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS lpDDSCaps) PURE; 
-    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
-    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
-    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
-    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
-    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
-    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
-    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
-    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
-    STDMETHOD(IsLost)(THIS) PURE; 
-    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
-    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
-    STDMETHOD(Restore)(THIS) PURE; 
-    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
-    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
-    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
-    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
-    STDMETHOD(Unlock)(THIS_ LPVOID lpSurfaceData) PURE; 
-    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE3 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
-    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE3 lpDDSReference) PURE; 
-    /* added in v2 */ 
-    STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; 
-    STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; 
-    /* added in v3 */ 
-    STDMETHOD(SetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSD, DWORD dwFlags) PURE;
-};
-
-    /*** IUnknown methods ***/
-#define IDirectDrawSurface3_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDrawSurface3_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDrawSurface3_Release(p)            ICOM_CALL_(Release,p,(p))
-/*** IDirectDrawSurface methods (almost) ***/
-#define IDirectDrawSurface3_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
-#define IDirectDrawSurface3_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
-#define IDirectDrawSurface3_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface3_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
-#define IDirectDrawSurface3_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface3_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
-#define IDirectDrawSurface3_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
-#define IDirectDrawSurface3_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
-#define IDirectDrawSurface3_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
-#define IDirectDrawSurface3_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
-#define IDirectDrawSurface3_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
-#define IDirectDrawSurface3_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
-#define IDirectDrawSurface3_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
-#define IDirectDrawSurface3_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
-#define IDirectDrawSurface3_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
-#define IDirectDrawSurface3_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
-#define IDirectDrawSurface3_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
-#define IDirectDrawSurface3_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
-#define IDirectDrawSurface3_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
-#define IDirectDrawSurface3_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
-#define IDirectDrawSurface3_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
-#define IDirectDrawSurface3_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
-#define IDirectDrawSurface3_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
-#define IDirectDrawSurface3_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
-#define IDirectDrawSurface3_Restore(p)                   ICOM_CALL_(Restore,p,(p))
-#define IDirectDrawSurface3_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
-#define IDirectDrawSurface3_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
-#define IDirectDrawSurface3_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
-#define IDirectDrawSurface3_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
-#define IDirectDrawSurface3_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
-#define IDirectDrawSurface3_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface3_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
-#define IDirectDrawSurface3_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
-/*** IDirectDrawSurface2 methods ***/
-#define IDirectDrawSurface3_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a))
-#define IDirectDrawSurface3_PageLock(p,a)       ICOM_CALL_(PageLock,p,(p,a))
-#define IDirectDrawSurface3_PageUnlock(p,a)     ICOM_CALL_(PageUnlock,p,(p,a))
-/*** IDirectDrawSurface3 methods ***/
-#define IDirectDrawSurface3_SetSurfaceDesc(p,a,b) ICOM_CALL_(SetSurfaceDesc,p,(p,a,b))
-
-
-/*****************************************************************************
- * IDirectDrawSurface4 interface
- */
-/* Cannot inherit from IDirectDrawSurface2 because DDSCAPS changed to DDSCAPS2.
- */
-#undef INTERFACE
-#define INTERFACE IDirectDrawSurface4
-DECLARE_INTERFACE_(IDirectDrawSurface4,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE; 
-    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE4 lpDDSAttachedSurface) PURE; 
-    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
-    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE4 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
-    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
-    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE4 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
-    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE4 lpDDSAttachedSurface) PURE; 
-    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; 
-    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; 
-    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE4 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
-    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS2 lpDDSCaps, LPDIRECTDRAWSURFACE4* lplpDDAttachedSurface) PURE; 
-    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS2 lpDDSCaps) PURE; 
-    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
-    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
-    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
-    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
-    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
-    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
-    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
-    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; 
-    STDMETHOD(IsLost)(THIS) PURE; 
-    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
-    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
-    STDMETHOD(Restore)(THIS) PURE; 
-    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
-    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
-    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
-    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
-    STDMETHOD(Unlock)(THIS_ LPRECT lpSurfaceData) PURE; 
-    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE4 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
-    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE4 lpDDSReference) PURE; 
-    /* added in v2 */ 
-    STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; 
-    STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; 
-    /* added in v3 */ 
-    STDMETHOD(SetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSD, DWORD dwFlags) PURE; 
-    /* added in v4 */ 
-    STDMETHOD(SetPrivateData)(THIS_ REFGUID , LPVOID , DWORD , DWORD ) PURE; 
-    STDMETHOD(GetPrivateData)(THIS_ REFGUID , LPVOID , LPDWORD ) PURE; 
-    STDMETHOD(FreePrivateData)(THIS_ REFGUID ) PURE; 
-    STDMETHOD(GetUniquenessValue)(THIS_ LPDWORD ) PURE; 
-    STDMETHOD(ChangeUniquenessValue)(THIS) PURE;
-};
-
-    /*** IUnknown methods ***/
-#define IDirectDrawSurface4_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDrawSurface4_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDrawSurface4_Release(p)            ICOM_CALL_(Release,p,(p))
-/*** IDirectDrawSurface (almost) methods ***/
-#define IDirectDrawSurface4_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
-#define IDirectDrawSurface4_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
-#define IDirectDrawSurface4_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface4_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
-#define IDirectDrawSurface4_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface4_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
-#define IDirectDrawSurface4_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
-#define IDirectDrawSurface4_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
-#define IDirectDrawSurface4_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
-#define IDirectDrawSurface4_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
-#define IDirectDrawSurface4_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
-#define IDirectDrawSurface4_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
-#define IDirectDrawSurface4_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
-#define IDirectDrawSurface4_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
-#define IDirectDrawSurface4_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
-#define IDirectDrawSurface4_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
-#define IDirectDrawSurface4_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
-#define IDirectDrawSurface4_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
-#define IDirectDrawSurface4_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
-#define IDirectDrawSurface4_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
-#define IDirectDrawSurface4_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
-#define IDirectDrawSurface4_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
-#define IDirectDrawSurface4_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
-#define IDirectDrawSurface4_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
-#define IDirectDrawSurface4_Restore(p)                   ICOM_CALL_(Restore,p,(p))
-#define IDirectDrawSurface4_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
-#define IDirectDrawSurface4_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
-#define IDirectDrawSurface4_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
-#define IDirectDrawSurface4_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
-#define IDirectDrawSurface4_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
-#define IDirectDrawSurface4_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface4_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
-#define IDirectDrawSurface4_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
-/*** IDirectDrawSurface2 methods ***/
-#define IDirectDrawSurface4_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a))
-#define IDirectDrawSurface4_PageLock(p,a)       ICOM_CALL_(PageLock,p,(p,a))
-#define IDirectDrawSurface4_PageUnlock(p,a)     ICOM_CALL_(PageUnlock,p,(p,a))
-/*** IDirectDrawSurface3 methods ***/
-#define IDirectDrawSurface4_SetSurfaceDesc(p,a,b) ICOM_CALL_(SetSurfaceDesc,p,(p,a,b))
-/*** IDirectDrawSurface4 methods ***/
-#define IDirectDrawSurface4_SetPrivateData(p,a,b,c,d) ICOM_CALL_(SetPrivateData,p,(p,a,b,c,d))
-#define IDirectDrawSurface4_GetPrivateData(p,a,b,c)   ICOM_CALL_(GetPrivateData,p,(p,a,b,c))
-#define IDirectDrawSurface4_FreePrivateData(p,a)      ICOM_CALL_(FreePrivateData,p,(p,a))
-#define IDirectDrawSurface4_GetUniquenessValue(p,a)   ICOM_CALL_(GetUniquenessValue,p,(p,a))
-#define IDirectDrawSurface4_ChangeUniquenessValue(p)  ICOM_CALL_(ChangeUniquenessValue,p,(p))
-
-
-/*****************************************************************************
- * IDirectDrawSurface7 interface
- */
-#undef INTERFACE
-#define INTERFACE IDirectDrawSurface7
-DECLARE_INTERFACE_(IDirectDrawSurface7,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE; 
-    STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE7 lpDDSAttachedSurface) PURE; 
-    STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; 
-    STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE7 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; 
-    STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; 
-    STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE7 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; 
-    STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE7 lpDDSAttachedSurface) PURE; 
-    STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK7 lpEnumSurfacesCallback) PURE; 
-    STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK7 lpfnCallback) PURE; 
-    STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE7 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; 
-    STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS2 lpDDSCaps, LPDIRECTDRAWSURFACE7* lplpDDAttachedSurface) PURE; 
-    STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(GetCaps)(THIS_ LPDDSCAPS2 lpDDSCaps) PURE; 
-    STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; 
-    STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
-    STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; 
-    STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; 
-    STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; 
-    STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; 
-    STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; 
-    STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; 
-    STDMETHOD(IsLost)(THIS) PURE; 
-    STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC2 lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; 
-    STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; 
-    STDMETHOD(Restore)(THIS) PURE; 
-    STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; 
-    STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; 
-    STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; 
-    STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; 
-    STDMETHOD(Unlock)(THIS_ LPRECT lpSurfaceData) PURE; 
-    STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE7 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; 
-    STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE7 lpDDSReference) PURE; 
-    /* added in v2 */ 
-    STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; 
-    STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; 
-    STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; 
-    /* added in v3 */ 
-    STDMETHOD(SetSurfaceDesc)(THIS_ LPDDSURFACEDESC2 lpDDSD, DWORD dwFlags) PURE; 
-    /* added in v4 */ 
-    STDMETHOD(SetPrivateData)(THIS_ REFGUID , LPVOID , DWORD , DWORD ) PURE; 
-    STDMETHOD(GetPrivateData)(THIS_ REFGUID , LPVOID , LPDWORD ) PURE; 
-    STDMETHOD(FreePrivateData)(THIS_ REFGUID ) PURE; 
-    STDMETHOD(GetUniquenessValue)(THIS_ LPDWORD ) PURE; 
-    STDMETHOD(ChangeUniquenessValue)(THIS) PURE; 
-    /* added in v7 */ 
-    STDMETHOD(SetPriority)(THIS_ DWORD prio) PURE; 
-    STDMETHOD(GetPriority)(THIS_ LPDWORD prio) PURE; 
-    STDMETHOD(SetLOD)(THIS_ DWORD lod) PURE; 
-    STDMETHOD(GetLOD)(THIS_ LPDWORD lod) PURE;
-};
-
-    /*** IUnknown methods ***/
-#define IDirectDrawSurface7_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDrawSurface7_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDrawSurface7_Release(p)            ICOM_CALL_(Release,p,(p))
-/*** IDirectDrawSurface (almost) methods ***/
-#define IDirectDrawSurface7_AddAttachedSurface(p,a)      ICOM_CALL_(AddAttachedSurface,p,(p,a))
-#define IDirectDrawSurface7_AddOverlayDirtyRect(p,a)     ICOM_CALL_(AddOverlayDirtyRect,p,(p,a))
-#define IDirectDrawSurface7_Blt(p,a,b,c,d,e)             ICOM_CALL_(Blt,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface7_BltBatch(p,a,b,c)            ICOM_CALL_(BltBatch,p,(p,a,b,c))
-#define IDirectDrawSurface7_BltFast(p,a,b,c,d,e)         ICOM_CALL_(BltFast,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface7_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b))
-#define IDirectDrawSurface7_EnumAttachedSurfaces(p,a,b)  ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b))
-#define IDirectDrawSurface7_EnumOverlayZOrders(p,a,b,c)  ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c))
-#define IDirectDrawSurface7_Flip(p,a,b)                  ICOM_CALL_(Flip,p,(p,a,b))
-#define IDirectDrawSurface7_GetAttachedSurface(p,a,b)    ICOM_CALL_(GetAttachedSurface,p,(p,a,b))
-#define IDirectDrawSurface7_GetBltStatus(p,a)            ICOM_CALL_(GetBltStatus,p,(p,a))
-#define IDirectDrawSurface7_GetCaps(p,a)                 ICOM_CALL_(GetCaps,p,(p,a))
-#define IDirectDrawSurface7_GetClipper(p,a)              ICOM_CALL_(GetClipper,p,(p,a))
-#define IDirectDrawSurface7_GetColorKey(p,a,b)           ICOM_CALL_(GetColorKey,p,(p,a,b))
-#define IDirectDrawSurface7_GetDC(p,a)                   ICOM_CALL_(GetDC,p,(p,a))
-#define IDirectDrawSurface7_GetFlipStatus(p,a)           ICOM_CALL_(GetFlipStatus,p,(p,a))
-#define IDirectDrawSurface7_GetOverlayPosition(p,a,b)    ICOM_CALL_(GetOverlayPosition,p,(p,a,b))
-#define IDirectDrawSurface7_GetPalette(p,a)              ICOM_CALL_(GetPalette,p,(p,a))
-#define IDirectDrawSurface7_GetPixelFormat(p,a)          ICOM_CALL_(GetPixelFormat,p,(p,a))
-#define IDirectDrawSurface7_GetSurfaceDesc(p,a)          ICOM_CALL_(GetSurfaceDesc,p,(p,a))
-#define IDirectDrawSurface7_Initialize(p,a,b)            ICOM_CALL_(Initialize,p,(p,a,b))
-#define IDirectDrawSurface7_IsLost(p)                    ICOM_CALL_(IsLost,p,(p))
-#define IDirectDrawSurface7_Lock(p,a,b,c,d)              ICOM_CALL_(Lock,p,(p,a,b,c,d))
-#define IDirectDrawSurface7_ReleaseDC(p,a)               ICOM_CALL_(ReleaseDC,p,(p,a))
-#define IDirectDrawSurface7_Restore(p)                   ICOM_CALL_(Restore,p,(p))
-#define IDirectDrawSurface7_SetClipper(p,a)              ICOM_CALL_(SetClipper,p,(p,a))
-#define IDirectDrawSurface7_SetColorKey(p,a,b)           ICOM_CALL_(SetColorKey,p,(p,a,b))
-#define IDirectDrawSurface7_SetOverlayPosition(p,a,b)    ICOM_CALL_(SetOverlayPosition,p,(p,a,b))
-#define IDirectDrawSurface7_SetPalette(p,a)              ICOM_CALL_(SetPalette,p,(p,a))
-#define IDirectDrawSurface7_Unlock(p,a)                  ICOM_CALL_(Unlock,p,(p,a))
-#define IDirectDrawSurface7_UpdateOverlay(p,a,b,c,d,e)   ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e))
-#define IDirectDrawSurface7_UpdateOverlayDisplay(p,a)    ICOM_CALL_(UpdateOverlayDisplay,p,(p,a))
-#define IDirectDrawSurface7_UpdateOverlayZOrder(p,a,b)   ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b))
-/*** IDirectDrawSurface2 methods ***/
-#define IDirectDrawSurface7_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a))
-#define IDirectDrawSurface7_PageLock(p,a)       ICOM_CALL_(PageLock,p,(p,a))
-#define IDirectDrawSurface7_PageUnlock(p,a)     ICOM_CALL_(PageUnlock,p,(p,a))
-/*** IDirectDrawSurface3 methods ***/
-#define IDirectDrawSurface7_SetSurfaceDesc(p,a,b) ICOM_CALL_(SetSurfaceDesc,p,(p,a,b))
-/*** IDirectDrawSurface4 methods ***/
-#define IDirectDrawSurface7_SetPrivateData(p,a,b,c,d) ICOM_CALL_(SetPrivateData,p,(p,a,b,c,d))
-#define IDirectDrawSurface7_GetPrivateData(p,a,b,c)   ICOM_CALL_(GetPrivateData,p,(p,a,b,c))
-#define IDirectDrawSurface7_FreePrivateData(p,a)      ICOM_CALL_(FreePrivateData,p,(p,a))
-#define IDirectDrawSurface7_GetUniquenessValue(p,a)   ICOM_CALL_(GetUniquenessValue,p,(p,a))
-#define IDirectDrawSurface7_ChangeUniquenessValue(p)  ICOM_CALL_(ChangeUniquenessValue,p,(p))
-/*** IDirectDrawSurface7 methods ***/
-#define IDirectDrawSurface7_SetPriority(p,a)          ICOM_CALL_(SetPriority,p,(p,a))
-#define IDirectDrawSurface7_GetPriority(p,a)          ICOM_CALL_(GetPriority,p,(p,a))
-#define IDirectDrawSurface7_SetLOD(p,a)               ICOM_CALL_(SetLOD,p,(p,a))
-#define IDirectDrawSurface7_GetLOD(p,a)               ICOM_CALL_(GetLOD,p,(p,a))
-
-/*****************************************************************************
- * IDirectDrawColorControl interface
- */
-#undef INTERFACE
-#define INTERFACE IDirectDrawColorControl
-DECLARE_INTERFACE_(IDirectDrawColorControl,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE; 
-    STDMETHOD(GetColorControls)(THIS_ LPDDCOLORCONTROL lpColorControl) PURE; 
-    STDMETHOD(SetColorControls)(THIS_ LPDDCOLORCONTROL lpColorControl) PURE;
-};
-
-	/*** IUnknown methods ***/
-#define IDirectDrawColorControl_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDrawColorControl_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDrawColorControl_Release(p)            ICOM_CALL_(Release,p,(p))
-	/*** IDirectDrawColorControl methods ***/
-#define IDirectDrawColorControl_GetColorControls(p,a) ICOM_CALL_(GetColorControls,p,(p,a))
-#define IDirectDrawColorControl_SetColorControls(p,a) ICOM_CALL_(SetColorControls,p,(p,a))
-
-/*****************************************************************************
- * IDirectDrawGammaControl interface
- */
-#undef INTERFACE
-#define INTERFACE IDirectDrawGammaControl
-DECLARE_INTERFACE_(IDirectDrawGammaControl,IUnknown)
-{
-    STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE;
-    STDMETHOD_(ULONG,AddRef)(THIS) PURE;
-    STDMETHOD_(ULONG,Release)(THIS) PURE; 
-    STDMETHOD(GetGammaRamp)(THIS_ DWORD dwFlags, LPDDGAMMARAMP lpGammaRamp) PURE; 
-    STDMETHOD(SetGammaRamp)(THIS_ DWORD dwFlags, LPDDGAMMARAMP lpGammaRamp) PURE;
-};
-
-	/*** IUnknown methods ***/
-#define IDirectDrawGammaControl_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b))
-#define IDirectDrawGammaControl_AddRef(p)             ICOM_CALL_(AddRef,p,(p))
-#define IDirectDrawGammaControl_Release(p)            ICOM_CALL_(Release,p,(p))
-	/*** IDirectDrawGammaControl methods ***/
-#define IDirectDrawGammaControl_GetGammaRamp(p,a,b)   ICOM_CALL_(GetGammaRamp,p,(p,a,b))
-#define IDirectDrawGammaControl_SetGammaRamp(p,a,b)   ICOM_CALL_(SetGammaRamp,p,(p,a,b))
-
-
-HRESULT WINAPI DirectDrawCreate(LPGUID,LPDIRECTDRAW*,LPUNKNOWN);
-HRESULT WINAPI DirectDrawCreateEx(LPGUID,LPVOID*,REFIID,LPUNKNOWN);
-HRESULT WINAPI DirectDrawEnumerateA(LPDDENUMCALLBACKA,LPVOID);
-HRESULT WINAPI DirectDrawEnumerateW(LPDDENUMCALLBACKW,LPVOID);
-#define DirectDrawEnumerate WINELIB_NAME_AW(DirectDrawEnumerate)
-HRESULT WINAPI DirectDrawCreateClipper(DWORD,LPDIRECTDRAWCLIPPER*,LPUNKNOWN);
-
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif /* defined(__cplusplus) */
-
-#endif /* __XWIN_DDRAW_H */
diff --git a/hw/xwin/win.h b/hw/xwin/win.h
deleted file mode 100644
index 3ab3249..0000000
--- a/hw/xwin/win.h
+++ /dev/null
@@ -1,1453 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- *		Kensuke Matsuzaki
- */
-
-#ifndef _WIN_H_
-#define _WIN_H_
-
-#ifndef NO
-#define NO					0
-#endif
-#ifndef YES
-#define YES					1
-#endif
-
-/* Turn debug messages on or off */
-#ifndef CYGDEBUG
-#define CYGDEBUG				NO
-#endif
-
-/* WM_XBUTTON Messages. They should go into w32api. */
-#ifndef WM_XBUTTONDOWN
-# define WM_XBUTTONDOWN 523
-#endif
-#ifndef WM_XBUTTONUP
-# define WM_XBUTTONUP 524
-#endif
-#ifndef WM_XBUTTONDBLCLK
-# define WM_XBUTTONDBLCLK 525
-#endif
-
-#define NEED_EVENTS
-
-#define WIN_DEFAULT_BPP				0
-#define WIN_DEFAULT_WHITEPIXEL			255
-#define WIN_DEFAULT_BLACKPIXEL			0
-#define WIN_DEFAULT_LINEBIAS			0
-#define WIN_DEFAULT_E3B_TIME			50 /* milliseconds */
-#define WIN_DEFAULT_DPI				75
-#define WIN_DEFAULT_REFRESH			0
-#define WIN_DEFAULT_WIN_KILL			TRUE
-#define WIN_DEFAULT_UNIX_KILL			FALSE
-#define WIN_DEFAULT_CLIP_UPDATES_NBOXES		0
-#ifdef XWIN_EMULATEPSEUDO
-#define WIN_DEFAULT_EMULATE_PSEUDO		FALSE
-#endif
-#define WIN_DEFAULT_USER_GAVE_HEIGHT_AND_WIDTH	FALSE
-
-#define WIN_DIB_MAXIMUM_SIZE	0x08000000 /* 16 MB on Windows 95, 98, Me */
-#define WIN_DIB_MAXIMUM_SIZE_MB (WIN_DIB_MAXIMUM_SIZE / 8 / 1024 / 1024)
-
-/*
- * Windows only supports 256 color palettes
- */
-#define WIN_NUM_PALETTE_ENTRIES			256
-
-/*
- * Number of times to call Restore in an attempt to restore the primary surface
- */
-#define WIN_REGAIN_SURFACE_RETRIES		1
-
-/*
- * Build a supported display depths mask by shifting one to the left
- * by the number of bits in the supported depth.
- */
-#define WIN_SUPPORTED_BPPS	( (1 << (32 - 1)) | (1 << (24 - 1)) \
-				| (1 << (16 - 1)) | (1 << (15 - 1)) \
-				| (1 << ( 8 - 1)))
-#define WIN_CHECK_DEPTH		YES
-
-/*
- * Timer IDs for WM_TIMER
- */
-#define WIN_E3B_TIMER_ID		1
-#define WIN_POLLING_MOUSE_TIMER_ID	2
-
-
-#define WIN_E3B_OFF		-1
-#define WIN_FD_INVALID		-1
-
-#define WIN_SERVER_NONE		0x0L	/* 0 */
-#define WIN_SERVER_SHADOW_GDI	0x1L	/* 1 */
-#define WIN_SERVER_SHADOW_DD	0x2L	/* 2 */
-#define WIN_SERVER_SHADOW_DDNL	0x4L	/* 4 */
-#ifdef XWIN_PRIMARYFB
-#define WIN_SERVER_PRIMARY_DD	0x8L	/* 8 */
-#endif
-#ifdef XWIN_NATIVEGDI
-# define WIN_SERVER_NATIVE_GDI	0x10L	/* 16 */
-#endif
-
-#define AltMapIndex		Mod1MapIndex
-#define NumLockMapIndex		Mod2MapIndex
-#define AltLangMapIndex		Mod3MapIndex
-#define KanaMapIndex		Mod4MapIndex
-#define ScrollLockMapIndex	Mod5MapIndex
-
-#define WIN_MOD_LALT		0x00000001
-#define WIN_MOD_RALT		0x00000002
-#define WIN_MOD_LCONTROL	0x00000004
-#define WIN_MOD_RCONTROL	0x00000008
-
-#define WIN_24BPP_MASK_RED	0x00FF0000
-#define WIN_24BPP_MASK_GREEN	0x0000FF00
-#define WIN_24BPP_MASK_BLUE	0x000000FF
-
-#define WIN_MAX_KEYS_PER_KEY	4
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <stdio.h>
-
-#include <errno.h>
-#if defined(XWIN_MULTIWINDOWEXTWM) || defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-#define HANDLE void *
-#include <pthread.h>
-#undef HANDLE
-#endif
-
-#ifdef HAS_MMAP
-#include <sys/mman.h>
-#ifndef MAP_FILE
-#define MAP_FILE 0
-#endif /* MAP_FILE */
-#endif /* HAS_MMAP */
-
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include <X11/Xos.h>
-#include <X11/Xprotostr.h>
-#include "scrnintstr.h"
-#include "pixmapstr.h"
-#include "pixmap.h"
-#include "region.h"
-#include "gcstruct.h"
-#include "colormap.h"
-#include "colormapst.h"
-#include "miscstruct.h"
-#include "servermd.h"
-#include "windowstr.h"
-#include "mi.h"
-#include "micmap.h"
-#include "mifillarc.h"
-#include "mifpoly.h"
-#include "mibstore.h"
-#include "input.h"
-#include "mipointer.h"
-#include "X11/keysym.h"
-#include "mibstore.h"
-#include "micoord.h"
-#include "dix.h"
-#include "miline.h"
-#include "shadow.h"
-#include "fb.h"
-#include "rootless.h"
-
-#ifdef RENDER
-#include "mipict.h"
-#include "picturestr.h"
-#endif
-
-#ifdef RANDR
-#include "randrstr.h"
-#endif
-
-/*
- * Windows headers
- */
-#include "winms.h"
-#include "./winresource.h"
-
-
-/*
- * Define Windows constants
- */
-
-#define WM_TRAYICON		(WM_USER + 1000)
-#define WM_INIT_SYS_MENU	(WM_USER + 1001)
-#define WM_GIVEUP		(WM_USER + 1002)
-
-
-/* Local includes */
-#include "winwindow.h"
-#include "winmsg.h"
-
-
-/*
- * Debugging macros
- */
-
-#if CYGDEBUG
-#define DEBUG_MSG(str,...) \
-if (fDebugProcMsg) \
-{ \
-  char *pszTemp; \
-  int iLength; \
-  pszTemp = Xprintf (str, ##__VA_ARGS__); \
-  MessageBox (NULL, pszTemp, szFunctionName, MB_OK); \
-  xfree (pszTemp); \
-}
-#else
-#define DEBUG_MSG(str,...)
-#endif
-
-#if CYGDEBUG
-#define DEBUG_FN_NAME(str) PTSTR szFunctionName = str
-#else
-#define DEBUG_FN_NAME(str)
-#endif
-
-#if CYGDEBUG || YES
-#define DEBUGVARS BOOL fDebugProcMsg = FALSE
-#else
-#define DEBUGVARS
-#endif
-
-#if CYGDEBUG || YES
-#define DEBUGPROC_MSG fDebugProcMsg = TRUE
-#else
-#define DEBUGPROC_MSG
-#endif
-
-#define PROFILEPOINT(point,thresh)\
-{\
-static unsigned int PROFPT##point = 0;\
-if (++PROFPT##point % thresh == 0)\
-ErrorF (#point ": PROFILEPOINT hit %u times\n", PROFPT##point);\
-}
-
-
-/* We use xor this macro for detecting toggle key state changes */
-#define WIN_XOR(a,b) ((!(a) && (b)) || ((a) && !(b)))
-
-#define DEFINE_ATOM_HELPER(func,atom_name)			\
-static Atom func (void) {					\
-    static int generation;					\
-    static Atom atom;						\
-    if (generation != serverGeneration) {			\
-	generation = serverGeneration;				\
-	atom = MakeAtom (atom_name, strlen (atom_name), TRUE);	\
-    }								\
-    return atom;						\
-}
-
-/*
- * Typedefs for engine dependent function pointers
- */
-
-typedef Bool (*winAllocateFBProcPtr)(ScreenPtr);
-
-typedef void (*winShadowUpdateProcPtr)(ScreenPtr, shadowBufPtr);
-
-typedef Bool (*winCloseScreenProcPtr)(int, ScreenPtr);
-
-typedef Bool (*winInitVisualsProcPtr)(ScreenPtr);
-
-typedef Bool (*winAdjustVideoModeProcPtr)(ScreenPtr);
-
-typedef Bool (*winCreateBoundingWindowProcPtr)(ScreenPtr);
-
-typedef Bool (*winFinishScreenInitProcPtr)(int, ScreenPtr, int, char **);
-
-typedef Bool (*winBltExposedRegionsProcPtr)(ScreenPtr);
-
-typedef Bool (*winActivateAppProcPtr)(ScreenPtr);
-
-typedef Bool (*winRedrawScreenProcPtr)(ScreenPtr pScreen);
-
-typedef Bool (*winRealizeInstalledPaletteProcPtr)(ScreenPtr pScreen);
-
-typedef Bool (*winInstallColormapProcPtr)(ColormapPtr pColormap);
-
-typedef Bool (*winStoreColorsProcPtr)(ColormapPtr pmap, 
-				      int ndef, xColorItem *pdefs);
-
-typedef Bool (*winCreateColormapProcPtr)(ColormapPtr pColormap);
-
-typedef Bool (*winDestroyColormapProcPtr)(ColormapPtr pColormap);
-
-typedef Bool (*winHotKeyAltTabProcPtr)(ScreenPtr);
-
-typedef Bool (*winCreatePrimarySurfaceProcPtr)(ScreenPtr);
-
-typedef Bool (*winReleasePrimarySurfaceProcPtr)(ScreenPtr);
-
-typedef Bool (*winFinishCreateWindowsWindowProcPtr)(WindowPtr pWin);
-
-
-/* Typedef for DIX wrapper functions */
-typedef int (*winDispatchProcPtr) (ClientPtr);
-
-
-/*
- * GC (graphics context) privates
- */
-
-typedef struct
-{
-  HDC			hdc;
-  HDC			hdcMem;
-} winPrivGCRec, *winPrivGCPtr;
-
-
-/*
- * Pixmap privates
- */
-
-typedef struct
-{
-  HDC			hdcSelected;
-  HBITMAP		hBitmap;
-  BYTE			*pbBits;
-  DWORD			dwScanlineBytes;
-  BITMAPINFOHEADER	*pbmih;
-} winPrivPixmapRec, *winPrivPixmapPtr;
-
-
-/*
- * Colormap privates
- */
-
-typedef struct
-{
-  HPALETTE		hPalette;
-  LPDIRECTDRAWPALETTE	lpDDPalette;
-  RGBQUAD		rgbColors[WIN_NUM_PALETTE_ENTRIES];
-  PALETTEENTRY		peColors[WIN_NUM_PALETTE_ENTRIES];
-} winPrivCmapRec, *winPrivCmapPtr;
-
-/*
- * Windows Cursor handling.
- */ 
-  
-typedef struct {
-  /* from GetSystemMetrics */
-  int sm_cx;
-  int sm_cy;
-
-  BOOL visible;
-  HCURSOR handle;
-  QueryBestSizeProcPtr QueryBestSize;
-  miPointerSpriteFuncPtr spriteFuncs;
-} winCursorRec;
-
-/*
- * Screen information structure that we need before privates are available
- * in the server startup sequence.
- */
-
-typedef struct
-{
-  ScreenPtr		pScreen;
-  
-  /* Did the user specify a height and width? */
-  Bool			fUserGaveHeightAndWidth;
-
-  DWORD			dwScreen;
-  DWORD			dwUserWidth;
-  DWORD			dwUserHeight;
-  DWORD			dwWidth;
-  DWORD			dwHeight;
-  DWORD			dwWidth_mm;
-  DWORD			dwHeight_mm;
-  DWORD			dwPaddedWidth;
-
-  /* Did the user specify a screen position? */
-  Bool			fUserGavePosition;
-  DWORD                 dwInitialX;
-  DWORD                 dwInitialY;
-
-  /*
-   * dwStride is the number of whole pixels that occupy a scanline,
-   * including those pixels that are not displayed.  This is basically
-   * a rounding up of the width.
-   */
-  DWORD			dwStride;
-
-  /* Offset of the screen in the window when using scrollbars */
-  DWORD			dwXOffset;
-  DWORD			dwYOffset;
-
-  DWORD			dwBPP;
-  DWORD			dwDepth;
-  DWORD			dwRefreshRate;
-  char			*pfb;
-  DWORD			dwEngine;
-  DWORD			dwEnginePreferred;
-  DWORD			dwClipUpdatesNBoxes;
-#ifdef XWIN_EMULATEPSEUDO
-  Bool			fEmulatePseudo;
-#endif
-  Bool			fFullScreen;
-  Bool			fDecoration;
-#ifdef XWIN_MULTIWINDOWEXTWM
-  Bool			fMWExtWM;
-  Bool			fInternalWM;
-  Bool			fAnotherWMRunning;
-#endif
-  Bool			fRootless;
-#ifdef XWIN_MULTIWINDOW
-  Bool			fMultiWindow;
-#endif
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-  Bool			fMultiMonitorOverride;
-#endif
-  Bool                  fMultipleMonitors;
-  Bool			fLessPointer;
-  Bool			fScrollbars;
-  Bool			fNoTrayIcon;
-  int			iE3BTimeout;
-  /* Windows (Alt+F4) and Unix (Ctrl+Alt+Backspace) Killkey */
-  Bool                  fUseWinKillKey;
-  Bool                  fUseUnixKillKey;
-  Bool			fIgnoreInput;
-
-  /* Did the user explicitly set this screen? */
-  Bool			fExplicitScreen;
-} winScreenInfo, *winScreenInfoPtr;
-
-
-/*
- * Screen privates
- */
-
-typedef struct _winPrivScreenRec
-{
-  winScreenInfoPtr	pScreenInfo;
-
-  Bool			fEnabled;
-  Bool			fClosed;
-  Bool			fActive;
-  Bool			fBadDepth;
-
-  int			iDeltaZ;
-
-  int			iConnectedClients;
-
-  CloseScreenProcPtr	CloseScreen;
-
-  DWORD			dwRedMask;
-  DWORD			dwGreenMask;
-  DWORD			dwBlueMask;
-  DWORD			dwBitsPerRGB;
-
-  DWORD			dwModeKeyStates;
-
-  /* Handle to icons that must be freed */
-  HICON			hiconNotifyIcon;
-
-  /* Last width, height, and depth of the Windows display */
-  DWORD			dwLastWindowsWidth;
-  DWORD			dwLastWindowsHeight;
-  DWORD			dwLastWindowsBitsPixel;
-
-  /* Palette management */
-  ColormapPtr		pcmapInstalled;
-
-  /* Pointer to the root visual so we only have to look it up once */
-  VisualPtr		pRootVisual;
-
-  /* 3 button emulation variables */
-  int			iE3BCachedPress;
-  Bool			fE3BFakeButton2Sent;
-
-  /* Privates used by shadow fb GDI server */
-  HBITMAP		hbmpShadow;
-  HDC			hdcScreen;
-  HDC			hdcShadow;
-  HWND			hwndScreen;
-  
-  /* Privates used by shadow fb and primary fb DirectDraw servers */
-  LPDIRECTDRAW		pdd;
-  LPDIRECTDRAWSURFACE2	pddsPrimary;
-  LPDIRECTDRAW2		pdd2;
-
-  /* Privates used by shadow fb DirectDraw server */
-  LPDIRECTDRAWSURFACE2	pddsShadow;
-  LPDDSURFACEDESC	pddsdShadow;
-
-  /* Privates used by primary fb DirectDraw server */
-  LPDIRECTDRAWSURFACE2	pddsOffscreen;
-  LPDDSURFACEDESC	pddsdOffscreen;
-  LPDDSURFACEDESC	pddsdPrimary;
-
-  /* Privates used by shadow fb DirectDraw Nonlocking server */
-  LPDIRECTDRAW4		pdd4;
-  LPDIRECTDRAWSURFACE4	pddsShadow4;
-  LPDIRECTDRAWSURFACE4	pddsPrimary4;
-  BOOL			fRetryCreateSurface;
-
-  /* Privates used by both shadow fb DirectDraw servers */
-  LPDIRECTDRAWCLIPPER	pddcPrimary;
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-  /* Privates used by multi-window external window manager */
-  RootlessFrameID	widTop;
-  Bool			fRestacking;
-#endif
-
-#ifdef XWIN_MULTIWINDOW
-  /* Privates used by multi-window */
-  pthread_t		ptWMProc;
-  pthread_t		ptXMsgProc;
-  void			*pWMInfo;
-#endif
-
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-  /* Privates used by both multi-window and rootless */
-  Bool			fRootWindowShown;
-#endif
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  /* Privates used for any module running in a seperate thread */
-  pthread_mutex_t	pmServerStarted;
-  Bool			fServerStarted;
-#endif
-  
-  /* Engine specific functions */
-  winAllocateFBProcPtr			pwinAllocateFB;
-  winShadowUpdateProcPtr		pwinShadowUpdate;
-  winCloseScreenProcPtr			pwinCloseScreen;
-  winInitVisualsProcPtr			pwinInitVisuals;
-  winAdjustVideoModeProcPtr		pwinAdjustVideoMode;
-  winCreateBoundingWindowProcPtr	pwinCreateBoundingWindow;
-  winFinishScreenInitProcPtr		pwinFinishScreenInit;
-  winBltExposedRegionsProcPtr		pwinBltExposedRegions;
-  winActivateAppProcPtr			pwinActivateApp;
-  winRedrawScreenProcPtr		pwinRedrawScreen;
-  winRealizeInstalledPaletteProcPtr	pwinRealizeInstalledPalette;
-  winInstallColormapProcPtr		pwinInstallColormap;
-  winStoreColorsProcPtr			pwinStoreColors;
-  winCreateColormapProcPtr		pwinCreateColormap;
-  winDestroyColormapProcPtr		pwinDestroyColormap;
-  winHotKeyAltTabProcPtr		pwinHotKeyAltTab;
-  winCreatePrimarySurfaceProcPtr	pwinCreatePrimarySurface;
-  winReleasePrimarySurfaceProcPtr	pwinReleasePrimarySurface;
-
-#ifdef XWIN_MULTIWINDOW
-  /* Window Procedures for MultiWindow mode */
-  winFinishCreateWindowsWindowProcPtr	pwinFinishCreateWindowsWindow;
-#endif
-
-  /* Window Procedures for Rootless mode */
-  CreateWindowProcPtr			CreateWindow;
-  DestroyWindowProcPtr			DestroyWindow;
-  PositionWindowProcPtr			PositionWindow;
-  ChangeWindowAttributesProcPtr		ChangeWindowAttributes;
-  RealizeWindowProcPtr			RealizeWindow;
-  UnrealizeWindowProcPtr		UnrealizeWindow;
-  ValidateTreeProcPtr			ValidateTree;
-  PostValidateTreeProcPtr		PostValidateTree;
-  WindowExposuresProcPtr		WindowExposures;
-  CopyWindowProcPtr			CopyWindow;
-  ClearToBackgroundProcPtr		ClearToBackground;
-  ClipNotifyProcPtr			ClipNotify;
-  RestackWindowProcPtr			RestackWindow;
-  ReparentWindowProcPtr			ReparentWindow;
-  ResizeWindowProcPtr			ResizeWindow;
-  MoveWindowProcPtr			MoveWindow;
-#ifdef SHAPE
-  SetShapeProcPtr			SetShape;
-#endif
-
-  winCursorRec                          cursor;
-} winPrivScreenRec;
-
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-typedef struct {
-  RootlessWindowPtr	pFrame;
-  HWND			hWnd;
-  int			dwWidthBytes;
-  BITMAPINFOHEADER	*pbmihShadow;
-  HBITMAP		hbmpShadow;
-  HDC			hdcShadow;
-  HDC			hdcScreen;
-  BOOL			fResized;
-  BOOL			fRestackingNow;
-  BOOL			fClose;
-  BOOL			fMovingOrSizing;
-  BOOL			fDestroyed;//for debug
-  char			*pfb;
-} win32RootlessWindowRec, *win32RootlessWindowPtr;
-#endif
-
-
-typedef struct {
-  pointer		value;
-  XID			id;
-} WindowIDPairRec, *WindowIDPairPtr;
-
-
-/*
- * Extern declares for general global variables
- */
-
-extern winScreenInfo		g_ScreenInfo[];
-extern miPointerScreenFuncRec	g_winPointerCursorFuncs;
-extern DWORD			g_dwEvents;
-#ifdef HAS_DEVWINDOWS
-extern int			g_fdMessageQueue;
-#endif
-extern DevPrivateKey		g_iScreenPrivateKey;
-extern DevPrivateKey		g_iCmapPrivateKey;
-extern DevPrivateKey		g_iGCPrivateKey;
-extern DevPrivateKey		g_iPixmapPrivateKey;
-extern DevPrivateKey		g_iWindowPrivateKey;
-extern unsigned long		g_ulServerGeneration;
-extern CARD32			g_c32LastInputEventTime;
-extern DWORD			g_dwEnginesSupported;
-extern HINSTANCE		g_hInstance;
-extern int                      g_copyROP[];
-extern int                      g_patternROP[];
-extern const char *		g_pszQueryHost;
-
-
-/*
- * Extern declares for dynamically loaded libraries and function pointers
- */
-
-extern HMODULE			g_hmodDirectDraw;
-extern FARPROC			g_fpDirectDrawCreate;
-extern FARPROC			g_fpDirectDrawCreateClipper;
-
-extern HMODULE			g_hmodCommonControls;
-extern FARPROC			g_fpTrackMouseEvent;
-
-
-/*
- * Screen privates macros
- */
-
-#define winGetScreenPriv(pScreen) ((winPrivScreenPtr) \
-    dixLookupPrivate(&(pScreen)->devPrivates, g_iScreenPrivateKey))
-
-#define winSetScreenPriv(pScreen,v) \
-    dixSetPrivate(&(pScreen)->devPrivates, g_iScreenPrivateKey, v)
-
-#define winScreenPriv(pScreen) \
-	winPrivScreenPtr pScreenPriv = winGetScreenPriv(pScreen)
-
-
-/*
- * Colormap privates macros
- */
-
-#define winGetCmapPriv(pCmap) ((winPrivCmapPtr) \
-    dixLookupPrivate(&(pCmap)->devPrivates, g_iCmapPrivateKey))
-
-#define winSetCmapPriv(pCmap,v) \
-    dixSetPrivate(&(pCmap)->devPrivates, g_iCmapPrivateKey, v)
-
-#define winCmapPriv(pCmap) \
-	winPrivCmapPtr pCmapPriv = winGetCmapPriv(pCmap)
-
-
-/*
- * GC privates macros
- */
-
-#define winGetGCPriv(pGC) ((winPrivGCPtr) \
-    dixLookupPrivate(&(pGC)->devPrivates, g_iGCPrivateKey))
-
-#define winSetGCPriv(pGC,v) \
-    dixSetPrivate(&(pGC)->devPrivates, g_iGCPrivateKey, v)
-
-#define winGCPriv(pGC) \
-	winPrivGCPtr pGCPriv = winGetGCPriv(pGC)
-
-
-/*
- * Pixmap privates macros
- */
-
-#define winGetPixmapPriv(pPixmap) ((winPrivPixmapPtr) \
-    dixLookupPrivate(&(pPixmap)->devPrivates, g_iPixmapPrivateKey))
-
-#define winSetPixmapPriv(pPixmap,v) \
-    dixLookupPrivate(&(pPixmap)->devPrivates, g_iPixmapPrivateKey, v)
-
-#define winPixmapPriv(pPixmap) \
-	winPrivPixmapPtr pPixmapPriv = winGetPixmapPriv(pPixmap)
-
-
-/*
- * Window privates macros
- */
-
-#define winGetWindowPriv(pWin) ((winPrivWinPtr) \
-    dixLookupPrivate(&(pWin)->devPrivates, g_iWindowPrivateKey))
-
-#define winSetWindowPriv(pWin,v) \
-    dixLookupPrivate(&(pWin)->devPrivates, g_iWindowPrivateKey, v)
-
-#define winWindowPriv(pWin) \
-	winPrivWinPtr pWinPriv = winGetWindowPriv(pWin)
-
-/*
- * wrapper macros 
- */
-#define _WIN_WRAP(priv, real, mem, func) {\
-    priv->mem = real->mem; \
-    real->mem = func; \
-}
-
-#define _WIN_UNWRAP(priv, real, mem) {\
-    real->mem = priv->mem; \
-}
-
-#define WIN_WRAP(mem, func) _WIN_WRAP(pScreenPriv, pScreen, mem, func) 
-
-#define WIN_UNWRAP(mem) _WIN_UNWRAP(pScreenPriv, pScreen, mem)
-
-/*
- * BEGIN DDX and DIX Function Prototypes
- */
-
-
-/*
- * winallpriv.c
- */
-
-Bool
-winAllocatePrivates (ScreenPtr pScreen);
-
-Bool
-winInitCmapPrivates (ColormapPtr pCmap, int index);
-
-Bool
-winAllocateCmapPrivates (ColormapPtr pCmap);
-
-
-/*
- * winauth.c
- */
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-# if defined(XCSECURITY)  
-Bool
-winGenerateAuthorization (void);
-# endif
-#endif
-
-
-/*
- * winblock.c
- */
-
-void
-winBlockHandler (int nScreen,
-		 pointer pBlockData,
-		 pointer pTimeout,
-		 pointer pReadMask);
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winclip.c
- */
-
-RegionPtr
-winPixmapToRegionNativeGDI (PixmapPtr pPix);
-#endif
-
-
-#ifdef XWIN_CLIPBOARD
-/*
- * winclipboardinit.c
- */
-
-Bool
-winInitClipboard (void);
-
-void
-winFixClipboardChain (void);
-#endif
-
-
-/*
- * wincmap.c
- */
-
-void
-winSetColormapFunctions (ScreenPtr pScreen);
-
-Bool
-winCreateDefColormap (ScreenPtr pScreen);
-
-
-/*
- * wincreatewnd.c
- */
-
-Bool
-winCreateBoundingWindowFullScreen (ScreenPtr pScreen);
-
-Bool
-winCreateBoundingWindowWindowed (ScreenPtr pScreen);
-
-
-/*
- * windialogs.c
- */
-
-void
-winDisplayExitDialog (winPrivScreenPtr pScreenPriv);
-
-void
-winDisplayDepthChangeDialog (winPrivScreenPtr pScreenPriv);
-
-void
-winDisplayAboutDialog (winPrivScreenPtr pScreenPriv);
-
-
-/*
- * winengine.c
- */
-
-void
-winDetectSupportedEngines (void);
-
-Bool
-winSetEngine (ScreenPtr pScreen);
-
-Bool
-winGetDDProcAddresses (void);
-
-
-/*
- * winerror.c
- */
-
-#ifdef DDXOSVERRORF
-void
-OSVenderVErrorF (const char *pszFormat, va_list va_args);
-#endif
-
-void
-winMessageBoxF (const char *pszError, UINT uType, ...);
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winfillsp.c
- */
-
-void
-winFillSpansNativeGDI (DrawablePtr	pDrawable,
-		       GCPtr		pGC,
-		       int		nSpans,
-		       DDXPointPtr	pPoints,
-		       int		*pWidths,
-		       int		fSorted);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winfont.c
- */
-
-Bool
-winRealizeFontNativeGDI (ScreenPtr pScreen, FontPtr pFont);
-
-Bool
-winUnrealizeFontNativeGDI (ScreenPtr pScreen, FontPtr pFont);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * wingc.c
- */
-
-Bool
-winCreateGCNativeGDI (GCPtr pGC);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * wingetsp.c
- */
-
-void
-winGetSpansNativeGDI (DrawablePtr	pDrawable, 
-		      int		wMax, 
-		      DDXPointPtr	pPoints, 
-		      int		*pWidths, 
-		      int		nSpans, 
-		      char		*pDst);
-#endif
-
-
-/*
- * winglobals.c
- */
-
-void
-winInitializeGlobals (void);
-
-
-/*
- * winkeybd.c
- */
-
-void
-winTranslateKey (WPARAM wParam, LPARAM lParam, int *piScanCode);
-
-int
-winKeybdProc (DeviceIntPtr pDeviceInt, int iState);
-
-void
-winInitializeModeKeyStates (void);
-
-void
-winRestoreModeKeyStates (void);
-
-Bool
-winIsFakeCtrl_L (UINT message, WPARAM wParam, LPARAM lParam);
-
-void
-winKeybdReleaseKeys (void);
-
-void
-winSendKeyEvent (DWORD dwKey, Bool fDown);
-
-
-/*
- * winkeyhook.c
- */
-
-Bool
-winInstallKeyboardHookLL (void);
-
-void
-winRemoveKeyboardHookLL (void);
-
-
-/*
- * winmisc.c
- */
-
-#ifdef XWIN_NATIVEGDI
-void
-winQueryBestSizeNativeGDI (int class, unsigned short *pWidth,
-			   unsigned short *pHeight, ScreenPtr pScreen);
-#endif
-
-CARD8
-winCountBits (DWORD dw);
-
-Bool
-winUpdateFBPointer (ScreenPtr pScreen, void *pbits);
-
-#ifdef XWIN_NATIVEGDI
-BOOL
-winPaintBackground (HWND hwnd, COLORREF colorref);
-#endif
-
-
-/*
- * winmouse.c
- */
-
-int
-winMouseProc (DeviceIntPtr pDeviceInt, int iState);
-
-int
-winMouseWheel (ScreenPtr pScreen, int iDeltaZ);
-
-void
-winMouseButtonsSendEvent (int iEventType, int iButton);
-
-int
-winMouseButtonsHandle (ScreenPtr pScreen,
-		       int iEventType, int iButton,
-		       WPARAM wParam);
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winnativegdi.c
- */
-
-HBITMAP
-winCreateDIBNativeGDI (int iWidth, int iHeight, int iDepth,
-		       BYTE **ppbBits, BITMAPINFO **ppbmi);
-
-Bool
-winSetEngineFunctionsNativeGDI (ScreenPtr pScreen);
-#endif
-
-
-#ifdef XWIN_PRIMARYFB
-/*
- * winpfbddd.c
- */
-
-Bool
-winSetEngineFunctionsPrimaryDD (ScreenPtr pScreen);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winpixmap.c
- */
-
-PixmapPtr
-winCreatePixmapNativeGDI (ScreenPtr pScreen, int width, int height, int depth,
-			  unsigned usage_hint);
-
-Bool
-winDestroyPixmapNativeGDI (PixmapPtr pPixmap);
-
-Bool
-winModifyPixmapHeaderNativeGDI (PixmapPtr pPixmap,
-				int iWidth, int iHeight,
-				int iDepth,
-				int iBitsPerPixel,
-				int devKind,
-				pointer pPixData);
-#endif
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winpolyline.c
- */
-
-void
-winPolyLineNativeGDI (DrawablePtr	pDrawable,
-		      GCPtr		pGC,
-		      int		mode,
-		      int		npt,
-		      DDXPointPtr	ppt);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winpushpxl.c
- */
-
-void
-winPushPixels (GCPtr pGC, PixmapPtr pBitMap, DrawablePtr pDrawable,
-	       int dx, int dy, int xOrg, int yOrg);
-#endif
-
-
-/*
- * winscrinit.c
- */
-
-Bool
-winScreenInit (int index,
-	       ScreenPtr pScreen,
-	       int argc, char **argv);
-
-Bool
-winFinishScreenInitFB (int index,
-		       ScreenPtr pScreen,
-		       int argc, char **argv);
-
-#if defined(XWIN_NATIVEGDI)
-Bool
-winFinishScreenInitNativeGDI (int index,
-			      ScreenPtr pScreen,
-			      int argc, char **argv);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * winsetsp.c
- */
-
-void
-winSetSpansNativeGDI (DrawablePtr	pDrawable,
-		      GCPtr		pGC,
-		      char		*pSrc,
-		      DDXPointPtr	pPoints,
-		      int		*pWidth,
-		      int		nSpans,
-		      int		fSorted);
-#endif
-
-
-/*
- * winshaddd.c
- */
-
-Bool
-winSetEngineFunctionsShadowDD (ScreenPtr pScreen);
-
-
-/*
- * winshadddnl.c
- */
-
-Bool
-winSetEngineFunctionsShadowDDNL (ScreenPtr pScreen);
-
-
-/*
- * winshadgdi.c
- */
-
-Bool
-winSetEngineFunctionsShadowGDI (ScreenPtr pScreen);
-
-
-/*
- * winwakeup.c
- */
-
-void
-winWakeupHandler (int nScreen,
-		  pointer pWakeupData,
-		  unsigned long ulResult,
-		  pointer pReadmask);
-
-
-/*
- * winwindow.c
- */
-
-#ifdef XWIN_NATIVEGDI
-Bool
-winCreateWindowNativeGDI (WindowPtr pWin);
-
-Bool
-winDestroyWindowNativeGDI (WindowPtr pWin);
-
-Bool
-winPositionWindowNativeGDI (WindowPtr pWin, int x, int y);
-
-void 
-winCopyWindowNativeGDI (WindowPtr pWin,
-			DDXPointRec ptOldOrg,
-			RegionPtr prgnSrc);
-
-Bool
-winChangeWindowAttributesNativeGDI (WindowPtr pWin, unsigned long mask);
-
-Bool
-winUnmapWindowNativeGDI (WindowPtr pWindow);
-
-Bool
-winMapWindowNativeGDI (WindowPtr pWindow);
-#endif
-
-Bool
-winCreateWindowRootless (WindowPtr pWindow);
-
-Bool
-winDestroyWindowRootless (WindowPtr pWindow);
-
-Bool
-winPositionWindowRootless (WindowPtr pWindow, int x, int y);
-
-Bool
-winChangeWindowAttributesRootless (WindowPtr pWindow, unsigned long mask);
-
-Bool
-winUnmapWindowRootless (WindowPtr pWindow);
-
-Bool
-winMapWindowRootless (WindowPtr pWindow);
-
-#ifdef SHAPE
-void
-winSetShapeRootless (WindowPtr pWindow);
-#endif
-
-
-/*
- * winmultiwindowicons.c - Used by both multi-window and Win32Rootless
- */
-
-HICON
-winXIconToHICON (WindowPtr pWin, int iconSize);
-
-
-#ifdef XWIN_MULTIWINDOW
-/*
- * winmultiwindowshape.c
- */
-
-# ifdef SHAPE
-void
-winReshapeMultiWindow (WindowPtr pWin);
-
-void
-winSetShapeMultiWindow (WindowPtr pWindow);
-
-void
-winUpdateRgnMultiWindow (WindowPtr pWindow);
-# endif
-#endif
-
-
-#ifdef XWIN_MULTIWINDOW
-/*
- * winmultiwindowwindow.c
- */
-
-Bool
-winCreateWindowMultiWindow (WindowPtr pWindow);
-
-Bool
-winDestroyWindowMultiWindow (WindowPtr pWindow);
-
-Bool
-winPositionWindowMultiWindow (WindowPtr pWindow, int x, int y);
-
-Bool
-winChangeWindowAttributesMultiWindow (WindowPtr pWindow, unsigned long mask);
-
-Bool
-winUnmapWindowMultiWindow (WindowPtr pWindow);
-
-Bool
-winMapWindowMultiWindow (WindowPtr pWindow);
-
-void
-winReparentWindowMultiWindow (WindowPtr pWin, WindowPtr pPriorParent);
-
-void
-winRestackWindowMultiWindow (WindowPtr pWin, WindowPtr pOldNextSib);
-
-void
-winReorderWindowsMultiWindow (void);
-
-void
-winResizeWindowMultiWindow (WindowPtr pWin, int x, int y, unsigned int w,
-			    unsigned int h, WindowPtr pSib);
-void
-winMoveWindowMultiWindow (WindowPtr pWin, int x, int y,
-			  WindowPtr pSib, VTKind kind);
-
-void
-winCopyWindowMultiWindow (WindowPtr pWin, DDXPointRec oldpt,
-			  RegionPtr oldRegion);
-
-XID
-winGetWindowID (WindowPtr pWin);
-
-int
-winAdjustXWindow (WindowPtr pWin, HWND hwnd);
-#endif
-
-
-#ifdef XWIN_MULTIWINDOW
-/*
- * winmultiwindowwndproc.c
- */
-
-LRESULT CALLBACK
-winTopLevelWindowProc (HWND hwnd, UINT message, 
-		       WPARAM wParam, LPARAM lParam);
-#endif
-
-
-/*
- * wintrayicon.c
- */
-
-void
-winInitNotifyIcon (winPrivScreenPtr pScreenPriv);
-
-void
-winDeleteNotifyIcon (winPrivScreenPtr pScreenPriv);
-
-LRESULT
-winHandleIconMessage (HWND hwnd, UINT message,
-		      WPARAM wParam, LPARAM lParam,
-		      winPrivScreenPtr pScreenPriv);
-
-
-/*
- * winwndproc.c
- */
-
-LRESULT CALLBACK
-winWindowProc (HWND hWnd, UINT message, 
-	       WPARAM wParam, LPARAM lParam);
-
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-/*
- * winwin32rootless.c
- */
-
-Bool
-winMWExtWMCreateFrame (RootlessWindowPtr pFrame, ScreenPtr pScreen,
-			     int newX, int newY, RegionPtr pShape);
-
-void
-winMWExtWMDestroyFrame (RootlessFrameID wid);
-
-void
-winMWExtWMMoveFrame (RootlessFrameID wid, ScreenPtr pScreen, int newX, int newY);
-
-void
-winMWExtWMResizeFrame (RootlessFrameID wid, ScreenPtr pScreen,
-			     int newX, int newY, unsigned int newW, unsigned int newH,
-			     unsigned int gravity);
-
-void
-winMWExtWMRestackFrame (RootlessFrameID wid, RootlessFrameID nextWid);
-
-void
-winMWExtWMReshapeFrame (RootlessFrameID wid, RegionPtr pShape);
-
-void
-winMWExtWMUnmapFrame (RootlessFrameID wid);
-
-void
-winMWExtWMStartDrawing (RootlessFrameID wid, char **pixelData, int *bytesPerRow);
-
-void
-winMWExtWMStopDrawing (RootlessFrameID wid, Bool flush);
-
-void
-winMWExtWMUpdateRegion (RootlessFrameID wid, RegionPtr pDamage);
-
-void
-winMWExtWMDamageRects (RootlessFrameID wid, int count, const BoxRec *rects,
-			     int shift_x, int shift_y);
-
-void
-winMWExtWMRootlessSwitchWindow (RootlessWindowPtr pFrame, WindowPtr oldWin);
-
-void
-winMWExtWMCopyBytes (unsigned int width, unsigned int height,
-			   const void *src, unsigned int srcRowBytes,
-			   void *dst, unsigned int dstRowBytes);
-
-void
-winMWExtWMFillBytes (unsigned int width, unsigned int height, unsigned int value,
-			   void *dst, unsigned int dstRowBytes);
-
-int
-winMWExtWMCompositePixels (unsigned int width, unsigned int height, unsigned int function,
-				 void *src[2], unsigned int srcRowBytes[2],
-				 void *mask, unsigned int maskRowBytes,
-				 void *dst[2], unsigned int dstRowBytes[2]);
-
-void
-winMWExtWMCopyWindow (RootlessFrameID wid, int dstNrects, const BoxRec *dstRects,
-			    int dx, int dy);
-#endif
-
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-/*
- * winwin32rootlesswindow.c
- */
-
-void
-winMWExtWMReorderWindows (ScreenPtr pScreen);
-
-void
-winMWExtWMMoveXWindow (WindowPtr pWin, int x, int y);
-
-void
-winMWExtWMResizeXWindow (WindowPtr pWin, int w, int h);
-
-void
-winMWExtWMMoveResizeXWindow (WindowPtr pWin, int x, int y, int w, int h);
-
-void
-winMWExtWMUpdateIcon (Window id);
-
-void
-winMWExtWMUpdateWindowDecoration (win32RootlessWindowPtr pRLWinPriv,
-				  winScreenInfoPtr pScreenInfo);
-
-wBOOL CALLBACK
-winMWExtWMDecorateWindow (HWND hwnd, LPARAM lParam);
-
-Bool
-winIsInternalWMRunning (winScreenInfoPtr pScreenInfo);
-
-void
-winMWExtWMRestackWindows (ScreenPtr pScreen);
-#endif
-
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-/*
- * winwin32rootlesswndproc.c
- */
-
-LRESULT CALLBACK
-winMWExtWMWindowProc (HWND hwnd, UINT message, 
-			    WPARAM wParam, LPARAM lParam);
-#endif
-
-
-/*
- * winwindowswm.c
- */
-
-void
-winWindowsWMSendEvent (int type, unsigned int mask, int which, int arg,
-		       Window window, int x, int y, int w, int h);
-
-void
-winWindowsWMExtensionInit (void);
-
-/*
- * wincursor.c
- */
-
-Bool
-winInitCursor (ScreenPtr pScreen);
-
-/*
- * END DDX and DIX Function Prototypes
- */
-
-#endif /* _WIN_H_ */
-
diff --git a/hw/xwin/winallpriv.c b/hw/xwin/winallpriv.c
deleted file mode 100644
index 21ccd9b..0000000
--- a/hw/xwin/winallpriv.c
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Keith Packard, MIT X Consortium
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/* See Porting Layer Definition - p. 58 */
-/*
- * Allocate indexes for the privates that we use.
- * Allocate memory directly for the screen privates.
- * Reserve space in GCs and Pixmaps for our privates.
- * Colormap privates are handled in winAllocateCmapPrivates ()
- */
-
-Bool
-winAllocatePrivates (ScreenPtr pScreen)
-{
-  winPrivScreenPtr	pScreenPriv;
-
-#if CYGDEBUG
-  winDebug ("winAllocateScreenPrivates - g_ulServerGeneration: %d "
-	  "serverGeneration: %d\n",
-	  g_ulServerGeneration, serverGeneration);
-#endif
-
-  /* We need a new slot for our privates if the screen gen has changed */
-  if (g_ulServerGeneration != serverGeneration)
-    {
-      g_ulServerGeneration = serverGeneration;
-    }
-
-  /* Allocate memory for the screen private structure */
-  pScreenPriv = (winPrivScreenPtr) malloc (sizeof (winPrivScreenRec));
-  if (!pScreenPriv)
-    {
-      ErrorF ("winAllocateScreenPrivates - malloc () failed\n");
-      return FALSE;
-    }
-
-  /* Initialize the memory of the private structure */
-  ZeroMemory (pScreenPriv, sizeof (winPrivScreenRec));
-
-  /* Intialize private structure members */
-  pScreenPriv->fActive = TRUE;
-
-  /* Save the screen private pointer */
-  winSetScreenPriv (pScreen, pScreenPriv);
-
-  /* Reserve GC memory for our privates */
-  if (!dixRequestPrivate(g_iGCPrivateKey, sizeof (winPrivGCRec)))
-    {
-      ErrorF ("winAllocatePrivates - AllocateGCPrivate () failed\n");
-      return FALSE;
-    }
-
-  /* Reserve Pixmap memory for our privates */
-  if (!dixRequestPrivate(g_iPixmapPrivateKey, sizeof (winPrivPixmapRec)))
-    {
-      ErrorF ("winAllocatePrivates - AllocatePixmapPrivates () failed\n");
-      return FALSE;
-    }
-
-  /* Reserve Window memory for our privates */
-  if (!dixRequestPrivate(g_iWindowPrivateKey, sizeof (winPrivWinRec)))
-    {
-      ErrorF ("winAllocatePrivates () - AllocateWindowPrivates () failed\n");
-       return FALSE;
-     }
-
-  return TRUE;
-}
-
-
-/*
- * Colormap privates may be allocated after the default colormap has
- * already been created for some screens.  This initialization procedure
- * is called for each default colormap that is found.
- */
-
-Bool
-winInitCmapPrivates (ColormapPtr pcmap, int index)
-{
-#if CYGDEBUG
-  winDebug ("winInitCmapPrivates\n");
-#endif
-  
-  /*
-   * I see no way that this function can do anything useful
-   * with only a ColormapPtr.  We don't have the index for
-   * our dev privates yet, so we can't really initialize
-   * anything.  Perhaps I am misunderstanding the purpose
-   * of this function.
-   */
-  /*  That's definitely true.
-   *  I therefore changed the API and added the index as argument.
-   */
-  return TRUE;
-}
-
-
-/*
- * Allocate memory for our colormap privates
- */
-
-Bool
-winAllocateCmapPrivates (ColormapPtr pCmap)
-{
-  winPrivCmapPtr		pCmapPriv;
-  static unsigned long		s_ulPrivateGeneration = 0;
-
-#if CYGDEBUG
-  winDebug ("winAllocateCmapPrivates\n");
-#endif
-
-  /* Get a new privates index when the server generation changes */
-  if (s_ulPrivateGeneration != serverGeneration)
-    {
-      /* Save the new server generation */
-      s_ulPrivateGeneration = serverGeneration;
-    }
-
-  /* Allocate memory for our private structure */
-  pCmapPriv = (winPrivCmapPtr) malloc (sizeof (winPrivCmapRec));
-  if (!pCmapPriv)
-    {
-      ErrorF ("winAllocateCmapPrivates - malloc () failed\n");
-      return FALSE;
-    }
-
-  /* Initialize the memory of the private structure */
-  ZeroMemory (pCmapPriv, sizeof (winPrivCmapRec));
-
-  /* Save the cmap private pointer */
-  winSetCmapPriv (pCmap, pCmapPriv);
-
-#if CYGDEBUG
-  winDebug ("winAllocateCmapPrivates - Returning\n");
-#endif
-
-  return TRUE;
-}
diff --git a/hw/xwin/winauth.c b/hw/xwin/winauth.c
deleted file mode 100644
index b57a35a..0000000
--- a/hw/xwin/winauth.c
+++ /dev/null
@@ -1,131 +0,0 @@
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#if defined(XCSECURITY)
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#include "win.h"
-
-/* Includes for authorization */
-#include <X11/Xauth.h>
-#include "securitysrv.h"
-#include <X11/extensions/securstr.h>
-
-
-/*
- * Constants
- */
-
-#define AUTH_NAME	"MIT-MAGIC-COOKIE-1"
-
-
-/*
- * Globals
- */
-
-XID		g_authId = 0;
-unsigned int	g_uiAuthDataLen = 0;
-char		*g_pAuthData = NULL;
-
-
-/*
- * Generate authorization cookie for internal server clients
- */
-
-Bool
-winGenerateAuthorization ()
-{
-  Bool				fFreeAuth = FALSE;
-  SecurityAuthorizationPtr	pAuth = NULL;
-
-  /* Call OS layer to generate authorization key */
-  g_authId = GenerateAuthorization (strlen (AUTH_NAME),
-				    AUTH_NAME,
-				    0,
-				    NULL,
-				    &g_uiAuthDataLen,
-				    &g_pAuthData);
-  if ((XID) ~0L == g_authId)
-    {
-      ErrorF ("winGenerateAuthorization - GenerateAuthorization failed\n");
-      goto auth_bailout;
-    }
-#if 0
-  else
-    {
-      ErrorF ("winGenerateAuthorization - GenerateAuthorization success!\n"
-	      "AuthDataLen: %d AuthData: %s\n",
-	      g_uiAuthDataLen, g_pAuthData);
-    }
-#endif
-  
-  /* Allocate structure for additional auth information */
-  pAuth = (SecurityAuthorizationPtr) 
-    xalloc (sizeof (SecurityAuthorizationRec));
-  if (!(pAuth))
-    {
-      ErrorF ("winGenerateAuthorization - Failed allocating "
-	      "SecurityAuthorizationPtr.\n");
-      goto auth_bailout;
-    }
-  
-  /* Fill in the auth fields */
-  pAuth->id = g_authId;
-  pAuth->timeout = 0; /* live for x seconds after refcnt == 0 */
-  pAuth->group = None;
-  pAuth->trustLevel = XSecurityClientTrusted;
-  pAuth->refcnt = 1; /* this auth must stick around */
-  pAuth->secondsRemaining = 0;
-  pAuth->timer = NULL;
-  pAuth->eventClients = NULL;
-  
-  /* Add the authorization to the server's auth list */
-  if (!AddResource (g_authId,
-		    SecurityAuthorizationResType,
-		    pAuth))
-    {
-      ErrorF ("winGenerateAuthorization - AddResource failed for auth.\n");
-      fFreeAuth = TRUE;
-      goto auth_bailout;
-    }
-  
-  /* Don't free the auth data, since it is still used internally */
-  pAuth = NULL;
-  
-  return TRUE;
-
- auth_bailout:
-  if (fFreeAuth)
-    xfree (pAuth);
-  
-  return FALSE;
-}
-#endif
diff --git a/hw/xwin/winblock.c b/hw/xwin/winblock.c
deleted file mode 100644
index abea60e..0000000
--- a/hw/xwin/winblock.c
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winmsg.h"
-
-
-/*
- * References to external symbols
- */
-
-extern HWND			g_hDlgDepthChange;
-extern HWND			g_hDlgExit;
-extern HWND			g_hDlgAbout;
-
-
-/* See Porting Layer Definition - p. 6 */
-void
-winBlockHandler (int nScreen,
-		 pointer pBlockData,
-		 pointer pTimeout,
-		 pointer pReadMask)
-{
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  winScreenPriv((ScreenPtr)pBlockData);
-#endif
-  MSG			msg;
-#ifndef HAS_DEVWINDOWS
-  struct timeval **tvp = pTimeout;
-  if (*tvp != NULL) 
-  {
-    (*tvp)->tv_sec = 0;
-    (*tvp)->tv_usec = 100;
-  }
-#endif
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  /* Signal threaded modules to begin */
-  if (pScreenPriv != NULL && !pScreenPriv->fServerStarted)
-    {
-      int		iReturn;
-      
-      winDebug ("winBlockHandler - Releasing pmServerStarted\n");
-
-      /* Flag that modules are to be started */
-      pScreenPriv->fServerStarted = TRUE;
-
-      /* Unlock the mutex for threaded modules */
-      iReturn = pthread_mutex_unlock (&pScreenPriv->pmServerStarted);
-      if (iReturn != 0)
-	{
-	  ErrorF ("winBlockHandler - pthread_mutex_unlock () failed: %d\n",
-		  iReturn);
-	  goto winBlockHandler_ProcessMessages; 
-	}
-
-      winDebug ("winBlockHandler - pthread_mutex_unlock () returned\n");
-    }
-
-winBlockHandler_ProcessMessages:
-#endif
-
-  /* Process all messages on our queue */
-  while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
-    {
-      if ((g_hDlgDepthChange == 0
-	   || !IsDialogMessage (g_hDlgDepthChange, &msg))
-	  && (g_hDlgExit == 0
-	      || !IsDialogMessage (g_hDlgExit, &msg))
-	  && (g_hDlgAbout == 0
-	      || !IsDialogMessage (g_hDlgAbout, &msg)))
-	{
-	  DispatchMessage (&msg);
-	}
-    }
-}
diff --git a/hw/xwin/winclip.c b/hw/xwin/winclip.c
deleted file mode 100644
index aab7d63..0000000
--- a/hw/xwin/winclip.c
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-/* Look at mfb/mfbclip.c for sample implementation */
-RegionPtr
-winPixmapToRegionNativeGDI (PixmapPtr pPix)
-{
-  ErrorF ("winPixmapToRegion()\n");
-  return NULL;
-}
diff --git a/hw/xwin/winclipboard.h b/hw/xwin/winclipboard.h
deleted file mode 100644
index 445c01b..0000000
--- a/hw/xwin/winclipboard.h
+++ /dev/null
@@ -1,164 +0,0 @@
-#ifndef _WINCLIPBOARD_H_
-#define _WINCLIPBOARD_H_
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-/* Standard library headers */
-#include <assert.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#ifdef __CYGWIN__
-#include <sys/select.h>
-#else
-#include "Xwinsock.h"
-#define HAS_WINSOCK
-#endif
-#include <fcntl.h>
-#include <setjmp.h>
-#include <pthread.h>
-
-/* X headers */
-#include <X11/X.h>
-#include <X11/Xatom.h>
-/* NOTE: For some unknown reason, including Xproto.h solves
- * tons of problems with including windows.h.  Unknowns reasons
- * are usually bad, so someone should investigate this.
- */
-#include <X11/Xproto.h>
-#include "X11/Xutil.h"
-#include "X11/Xlocale.h"
-
-/* Fixups to prevent collisions between Windows and X headers */
-#define ATOM			DWORD
-
-#ifndef __CYGWIN__
-#define sleep(x) Sleep (1000 * (x))
-#endif
-
-/* Windows headers */
-#ifndef XFree86Server
-#define XFree86Server
-#endif
-#include <windows.h>
-#undef XFree86Server
-
-
-/* Clipboard module constants */
-#define WIN_CLIPBOARD_WINDOW_CLASS		"xwinclip"
-#define WIN_CLIPBOARD_WINDOW_TITLE		"xwinclip"
-#ifdef HAS_DEVWINDOWS
-# define WIN_MSG_QUEUE_FNAME			"/dev/windows"
-#endif
-#define WIN_CONNECT_RETRIES			40
-#define WIN_CONNECT_DELAY			4
-#define WIN_JMP_OKAY				0
-#define WIN_JMP_ERROR_IO			2
-#define WIN_LOCAL_PROPERTY			"CYGX_CUT_BUFFER"
-#define WIN_XEVENTS_SUCCESS			0
-#define WIN_XEVENTS_SHUTDOWN			1
-#define WIN_XEVENTS_CONVERT			2
-#define WIN_XEVENTS_NOTIFY			3
-
-#define WM_WM_REINIT                           (WM_USER + 1)
-
-/*
- * References to external symbols
- */
-
-extern char *display;
-extern void ErrorF (const char* /*f*/, ...);
-extern void winDebug (const char *format, ...);
-extern void winErrorFVerb (int verb, const char *format, ...);
-
-
-/*
- * winclipboardinit.c
- */
-
-Bool
-winInitClipboard (void);
-
-HWND
-winClipboardCreateMessagingWindow (void);
-
-
-/*
- * winclipboardtextconv.c
- */
-
-void
-winClipboardDOStoUNIX (char *pszData, int iLength);
-
-void
-winClipboardUNIXtoDOS (unsigned char **ppszData, int iLength);
-
-
-/*
- * winclipboardthread.c
- */
-
-void *
-winClipboardProc (void *);
-
-void
-winDeinitClipboard (void);
-
-
-/*
- * winclipboardunicode.c
- */
-
-Bool
-winClipboardDetectUnicodeSupport (void);
-
-
-/*
- * winclipboardwndproc.c
- */
-
-BOOL
-winClipboardFlushWindowsMessageQueue (HWND hwnd);
-
-LRESULT CALLBACK
-winClipboardWindowProc (HWND hwnd, UINT message, 
-			WPARAM wParam, LPARAM lParam);
-
-
-/*
- * winclipboardxevents.c
- */
-
-int
-winClipboardFlushXEvents (HWND hwnd,
-			  int iWindow,
-			  Display *pDisplay,
-			  Bool fUnicodeSupport);
-#endif
diff --git a/hw/xwin/winclipboardinit.c b/hw/xwin/winclipboardinit.c
deleted file mode 100644
index 6a0cbaf..0000000
--- a/hw/xwin/winclipboardinit.c
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "dixstruct.h"
-#include "winclipboard.h"
-
-
-/*
- * Local typedefs
- */
-
-typedef int (*winDispatchProcPtr) (ClientPtr);
-
-DISPATCH_PROC(winProcSetSelectionOwner);
-
-
-/*
- * References to external symbols
- */
-
-extern pthread_t		g_ptClipboardProc;
-extern winDispatchProcPtr	winProcSetSelectionOwnerOrig;
-extern Bool			g_fClipboard;
-extern HWND			g_hwndClipboard;
-
-
-/*
- * Intialize the Clipboard module
- */
-
-Bool
-winInitClipboard ()
-{
-  ErrorF ("winInitClipboard ()\n");
-
-  /* Wrap some internal server functions */
-  if (ProcVector[X_SetSelectionOwner] != winProcSetSelectionOwner)
-    {
-      winProcSetSelectionOwnerOrig = ProcVector[X_SetSelectionOwner];
-      ProcVector[X_SetSelectionOwner] = winProcSetSelectionOwner;
-    }
-  
-  /* Spawn a thread for the Clipboard module */
-  if (pthread_create (&g_ptClipboardProc,
-		      NULL,
-		      winClipboardProc,
-		      NULL))
-    {
-      /* Bail if thread creation failed */
-      ErrorF ("winInitClipboard - pthread_create failed.\n");
-      return FALSE;
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Create the Windows window that we use to recieve Windows messages
- */
-
-HWND
-winClipboardCreateMessagingWindow ()
-{
-  WNDCLASS			wc;
-  HWND				hwnd;
-
-  /* Setup our window class */
-  wc.style = CS_HREDRAW | CS_VREDRAW;
-  wc.lpfnWndProc = winClipboardWindowProc;
-  wc.cbClsExtra = 0;
-  wc.cbWndExtra = 0;
-  wc.hInstance = GetModuleHandle (NULL);
-  wc.hIcon = 0;
-  wc.hCursor = 0;
-  wc.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
-  wc.lpszMenuName = NULL;
-  wc.lpszClassName = WIN_CLIPBOARD_WINDOW_CLASS;
-  RegisterClass (&wc);
-
-  /* Create the window */
-  hwnd = CreateWindowExA (0,			/* Extended styles */
-			  WIN_CLIPBOARD_WINDOW_CLASS,/* Class name */
-			  WIN_CLIPBOARD_WINDOW_TITLE,/* Window name */
-			  WS_OVERLAPPED,	/* Not visible anyway */
-			  CW_USEDEFAULT,	/* Horizontal position */
-			  CW_USEDEFAULT,	/* Vertical position */
-			  CW_USEDEFAULT,	/* Right edge */
-			  CW_USEDEFAULT,	/* Bottom edge */
-			  (HWND) NULL,		/* No parent or owner window */
-			  (HMENU) NULL,		/* No menu */
-			  GetModuleHandle (NULL),/* Instance handle */
-			  NULL);		/* Creation data */
-  assert (hwnd != NULL);
-
-  /* I'm not sure, but we may need to call this to start message processing */
-  ShowWindow (hwnd, SW_HIDE);
-
-  /* Similarly, we may need a call to this even though we don't paint */
-  UpdateWindow (hwnd);
-
-  return hwnd;
-}
-
-void
-winFixClipboardChain (void)
-{
-   if (g_fClipboard
-       && g_hwndClipboard)
-     {
-       PostMessage (g_hwndClipboard, WM_WM_REINIT, 0, 0);
-     }
-}
diff --git a/hw/xwin/winclipboardtextconv.c b/hw/xwin/winclipboardtextconv.c
deleted file mode 100644
index fd2e696..0000000
--- a/hw/xwin/winclipboardtextconv.c
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include <stdio.h>
-#include <stdlib.h>
-
-void
-winClipboardDOStoUNIX (char *pszSrc, int iLength);
-void
-winClipboardUNIXtoDOS (unsigned char **ppszData, int iLength);
-
-/*
- * Convert \r\n to \n
- *
- * NOTE: This was heavily inspired by, Cygwin's
- * winsup/cygwin/fhandler.cc/fhandler_base::read ()
- */
-
-void
-winClipboardDOStoUNIX (char *pszSrc, int iLength)
-{
-  char			*pszDest = pszSrc;
-  char			*pszEnd = pszSrc + iLength;
-
-  /* Loop until the last character */
-  while (pszSrc < pszEnd)
-    {
-      /* Copy the current source character to current destination character */
-      *pszDest = *pszSrc;
-
-      /* Advance to the next source character */
-      pszSrc++;
-
-      /* Don't advance the destination character if we need to drop an \r */
-      if (*pszDest != '\r' || *pszSrc != '\n')
-	pszDest++;
-    }
-
-  /* Move the terminating null */
-  *pszDest = '\0';
-}
-
-
-/*
- * Convert \n to \r\n
- */
-
-void
-winClipboardUNIXtoDOS (unsigned char **ppszData, int iLength)
-{
-  int			iNewlineCount = 0;
-  unsigned char		*pszSrc = *ppszData;
-  unsigned char		*pszEnd = pszSrc + iLength;
-  unsigned char		*pszDest = NULL, *pszDestBegin = NULL;
-
-#if 0
-  ErrorF ("UNIXtoDOS () - Original data:\n%s\n", *ppszData);
-#endif
-
-  /* Count \n characters without leading \r */
-  while (pszSrc < pszEnd)
-    {
-      /* Skip ahead two character if found set of \r\n */
-      if (*pszSrc == '\r' && pszSrc + 1 < pszEnd && *(pszSrc + 1) == '\n')
-	{
-	  pszSrc += 2;
-	  continue;
-	} 
-
-      /* Increment the count if found naked \n */
-      if (*pszSrc == '\n')
-	{
-	  iNewlineCount++;
-	}
-
-      pszSrc++;
-    }
-  
-  /* Return if no naked \n's */
-  if (iNewlineCount == 0)
-    return;
-
-  /* Allocate a new string */
-  pszDestBegin = pszDest = malloc (iLength + iNewlineCount + 1);
-
-  /* Set source pointer to beginning of data string */
-  pszSrc = *ppszData;
-
-  /* Loop through all characters in source string */
-  while (pszSrc < pszEnd)
-    {
-      /* Copy line endings that are already valid */
-      if (*pszSrc == '\r' && pszSrc + 1 < pszEnd && *(pszSrc + 1) == '\n')
-	{
-	  *pszDest = *pszSrc;
-	  *(pszDest + 1) = *(pszSrc + 1);
-	  pszDest += 2;
-	  pszSrc += 2;
-	  continue;
-	}
-
-      /* Add \r to naked \n's */
-      if (*pszSrc == '\n')
-	{
-	  *pszDest = '\r';
-	  *(pszDest + 1) = *pszSrc;
-	  pszDest += 2;
-	  pszSrc += 1;
-	  continue;
-	}
-
-      /* Copy normal characters */
-      *pszDest = *pszSrc;
-      pszSrc++;
-      pszDest++;
-    }
-
-  /* Put terminating null at end of new string */
-  *pszDest = '\0';
-
-  /* Swap string pointers */
-  free (*ppszData);
-  *ppszData = pszDestBegin;
-
-#if 0
-  ErrorF ("UNIXtoDOS () - Final string:\n%s\n", pszDestBegin);
-#endif
-}
diff --git a/hw/xwin/winclipboardthread.c b/hw/xwin/winclipboardthread.c
deleted file mode 100644
index 081abd5..0000000
--- a/hw/xwin/winclipboardthread.c
+++ /dev/null
@@ -1,477 +0,0 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include <sys/types.h>
-#include "winclipboard.h"
-#ifdef __CYGWIN__
-#include <errno.h>
-#endif
-#include "X11/Xauth.h"
-
-
-/*
- * Constants
- */
-
-#define AUTH_NAME	"MIT-MAGIC-COOKIE-1"
-
-
-/*
- * References to external symbols
- */
-
-extern Bool		g_fUnicodeClipboard;
-extern unsigned long	serverGeneration;
-#if defined(XCSECURITY)
-extern unsigned int	g_uiAuthDataLen;
-extern char		*g_pAuthData;
-#endif
-extern Bool		g_fClipboardStarted;
-extern HWND		g_hwndClipboard;
-extern void		*g_pClipboardDisplay;
-extern Window		g_iClipboardWindow;
-
-
-/*
- * Global variables
- */
-
-static jmp_buf			g_jmpEntry;
-Bool				g_fUnicodeSupport = FALSE;
-Bool				g_fUseUnicode = FALSE;
-
-
-/*
- * Local function prototypes
- */
-
-static int
-winClipboardErrorHandler (Display *pDisplay, XErrorEvent *pErr);
-
-static int
-winClipboardIOErrorHandler (Display *pDisplay);
-
-
-/*
- * Main thread function
- */
-
-void *
-winClipboardProc (void *pvNotUsed)
-{
-  Atom			atomClipboard, atomClipboardManager;
-  int			iReturn;
-  HWND			hwnd = NULL;
-  int			iConnectionNumber = 0;
-#ifdef HAS_DEVWINDOWS
-  int			fdMessageQueue = 0;
-#else
-  struct timeval        tvTimeout;
-#endif
-  fd_set		fdsRead;
-  int			iMaxDescriptor;
-  Display		*pDisplay = NULL;
-  Window		iWindow = None;
-  int			iRetries;
-  Bool			fUseUnicode;
-  char			szDisplay[512];
-  int			iSelectError;
-
-  ErrorF ("winClipboardProc - Hello\n");
-
-  /* Do we have Unicode support? */
-  g_fUnicodeSupport = winClipboardDetectUnicodeSupport ();
-
-  /* Do we use Unicode clipboard? */
-  fUseUnicode = g_fUnicodeClipboard && g_fUnicodeSupport;
-
-  /* Save the Unicode support flag in a global */
-  g_fUseUnicode = fUseUnicode;
-
-  /* Allow multiple threads to access Xlib */
-  if (XInitThreads () == 0)
-    {
-      ErrorF ("winClipboardProc - XInitThreads failed.\n");
-      pthread_exit (NULL);
-    }
-
-  /* See if X supports the current locale */
-  if (XSupportsLocale () == False)
-    {
-      ErrorF ("winClipboardProc - Locale not supported by X.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  /* Set jump point for Error exits */
-  iReturn = setjmp (g_jmpEntry);
-  
-  /* Check if we should continue operations */
-  if (iReturn != WIN_JMP_ERROR_IO
-      && iReturn != WIN_JMP_OKAY)
-    {
-      /* setjmp returned an unknown value, exit */
-      ErrorF ("winClipboardProc - setjmp returned: %d exiting\n",
-	      iReturn);
-      pthread_exit (NULL);
-    }
-  else if (iReturn == WIN_JMP_ERROR_IO)
-    {
-      /* TODO: Cleanup the Win32 window and free any allocated memory */
-      ErrorF ("winClipboardProc - setjmp returned for IO Error Handler.\n");
-      pthread_exit (NULL);
-    }
-
-#if defined(XCSECURITY)
-  /* Use our generated cookie for authentication */
-  XSetAuthorization (AUTH_NAME,
-		     strlen (AUTH_NAME),
-		     g_pAuthData,
-		     g_uiAuthDataLen);
-#endif
-
-  /* Set error handler */
-  XSetErrorHandler (winClipboardErrorHandler);
-  XSetIOErrorHandler (winClipboardIOErrorHandler);
-
-  /* Initialize retry count */
-  iRetries = 0;
-
-  /* Setup the display connection string x */
-  /*
-   * NOTE: Always connect to screen 0 since we require that screen
-   * numbers start at 0 and increase without gaps.  We only need
-   * to connect to one screen on the display to get events
-   * for all screens on the display.  That is why there is only
-   * one clipboard client thread.
-   */
-  snprintf (szDisplay,
-	    512,
-	    "127.0.0.1:%s.0",
-	    display);
-
-  /* Print the display connection string */
-  ErrorF ("winClipboardProc - DISPLAY=%s\n", szDisplay);
-
-  /* Open the X display */
-  do
-    {
-      pDisplay = XOpenDisplay (szDisplay);
-      if (pDisplay == NULL)
-	{
-	  ErrorF ("winClipboardProc - Could not open display, "
-		  "try: %d, sleeping: %d\n",
-		  iRetries + 1, WIN_CONNECT_DELAY);
-	  ++iRetries;
-	  sleep (WIN_CONNECT_DELAY);
-	  continue;
-	}
-      else
-	break;
-    }
-  while (pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
-
-  /* Make sure that the display opened */
-  if (pDisplay == NULL)
-    {
-      ErrorF ("winClipboardProc - Failed opening the display, giving up\n");
-      pthread_exit (NULL);
-    }
-
-  /* Save the display in the screen privates */
-  g_pClipboardDisplay = pDisplay;
-
-  ErrorF ("winClipboardProc - XOpenDisplay () returned and "
-	  "successfully opened the display.\n");
-
-  /* Get our connection number */
-  iConnectionNumber = ConnectionNumber (pDisplay);
-
-#ifdef HAS_DEVWINDOWS
-  /* Open a file descriptor for the windows message queue */
-  fdMessageQueue = open (WIN_MSG_QUEUE_FNAME, O_RDONLY);
-  if (fdMessageQueue == -1)
-    {
-      ErrorF ("winClipboardProc - Failed opening %s\n", WIN_MSG_QUEUE_FNAME);
-      pthread_exit (NULL);
-    }
-
-  /* Find max of our file descriptors */
-  iMaxDescriptor = max (fdMessageQueue, iConnectionNumber) + 1;
-#else
-  iMaxDescriptor = iConnectionNumber + 1;
-#endif
-
-  /* Select event types to watch */
-  if (XSelectInput (pDisplay,
-		    DefaultRootWindow (pDisplay),
-		    SubstructureNotifyMask |
-		    StructureNotifyMask |
-		    PropertyChangeMask) == BadWindow)
-    ErrorF ("winClipboardProc - XSelectInput generated BadWindow "
-	    "on RootWindow\n\n");
-
-  /* Create atoms */
-  atomClipboard = XInternAtom (pDisplay, "CLIPBOARD", False);
-  atomClipboardManager = XInternAtom (pDisplay, "CLIPBOARD_MANAGER", False);
-
-  /* Create a messaging window */
-  iWindow = XCreateSimpleWindow (pDisplay,
-				 DefaultRootWindow (pDisplay),
-				 1, 1,
-				 500, 500,
-				 0,
-				 BlackPixel (pDisplay, 0),
-				 BlackPixel (pDisplay, 0));
-  if (iWindow == 0)
-    {
-      ErrorF ("winClipboardProc - Could not create an X window.\n");
-      pthread_exit (NULL);
-    }
-
-  /* Save the window in the screen privates */
-  g_iClipboardWindow = iWindow;
-
-  /* Create Windows messaging window */
-  hwnd = winClipboardCreateMessagingWindow ();
-  
-  /* Save copy of HWND in screen privates */
-  g_hwndClipboard = hwnd;
-
-  /* Assert ownership of selections if Win32 clipboard is owned */
-  if (NULL != GetClipboardOwner ())
-    {
-      /* PRIMARY */
-      iReturn = XSetSelectionOwner (pDisplay, XA_PRIMARY,
-				    iWindow, CurrentTime);
-      if (iReturn == BadAtom || iReturn == BadWindow)
-	{
-	  ErrorF ("winClipboardProc - Could not set PRIMARY owner\n");
-	  pthread_exit (NULL);
-	}
-
-      /* CLIPBOARD */
-      iReturn = XSetSelectionOwner (pDisplay, atomClipboard,
-				    iWindow, CurrentTime);
-      if (iReturn == BadAtom || iReturn == BadWindow)
-	{
-	  ErrorF ("winClipboardProc - Could not set CLIPBOARD owner\n");
-	  pthread_exit (NULL);
-	}
-    }
-
-  /* Pre-flush X events */
-  /* 
-   * NOTE: Apparently you'll freeze if you don't do this,
-   *	   because there may be events in local data structures
-   *	   already.
-   */
-  winClipboardFlushXEvents (hwnd,
-			    iWindow,
-			    pDisplay,
-			    fUseUnicode);
-
-  /* Pre-flush Windows messages */
-  if (!winClipboardFlushWindowsMessageQueue (hwnd))
-    return 0;
-
-  /* Signal that the clipboard client has started */
-  g_fClipboardStarted = TRUE;
-
-  /* Loop for X events */
-  while (1)
-    {
-      /* Setup the file descriptor set */
-      /*
-       * NOTE: You have to do this before every call to select
-       *       because select modifies the mask to indicate
-       *       which descriptors are ready.
-       */
-      FD_ZERO (&fdsRead);
-      FD_SET (iConnectionNumber, &fdsRead);
-#ifdef HAS_DEVWINDOWS
-      FD_SET (fdMessageQueue, &fdsRead);
-#else
-      tvTimeout.tv_sec = 0;
-      tvTimeout.tv_usec = 100;
-#endif
-
-      /* Wait for a Windows event or an X event */
-      iReturn = select (iMaxDescriptor,	/* Highest fds number */
-			&fdsRead,	/* Read mask */
-			NULL,		/* No write mask */
-			NULL,		/* No exception mask */
-#ifdef HAS_DEVWINDOWS
-			NULL		/* No timeout */
-#else
-			&tvTimeout      /* Set timeout */
-#endif
-          );
-
-#ifndef HAS_WINSOCK
-      iSelectError = errno;
-#else
-      iSelectError = WSAGetLastError();
-#endif
-
-      if (iReturn < 0)
-	{
-#ifndef HAS_WINSOCK
-          if (iSelectError == EINTR)
-#else
-          if (iSelectError == WSAEINTR)
-#endif
-            continue;
-          
-	  ErrorF ("winClipboardProc - Call to select () failed: %d.  "
-		  "Bailing.\n", iReturn);
-	  break;
-	}
-
-      /* Branch on which descriptor became active */
-      if (FD_ISSET (iConnectionNumber, &fdsRead))
-	{
-	  /* Process X events */
-	  /* Exit when we see that server is shutting down */
-	  iReturn = winClipboardFlushXEvents (hwnd,
-					      iWindow,
-					      pDisplay,
-					      fUseUnicode);
-	  if (WIN_XEVENTS_SHUTDOWN == iReturn)
-	    {
-	      ErrorF ("winClipboardProc - winClipboardFlushXEvents "
-		      "trapped shutdown event, exiting main loop.\n");
-	      break;
-	    }
-	}
-
-#ifdef HAS_DEVWINDOWS
-      /* Check for Windows event ready */
-      if (FD_ISSET (fdMessageQueue, &fdsRead))
-#else
-      if (1)
-#endif
-	{
-	  /* Process Windows messages */
-	  if (!winClipboardFlushWindowsMessageQueue (hwnd))
-	    {
-	      ErrorF ("winClipboardProc - "
-		      "winClipboardFlushWindowsMessageQueue trapped "
-		      "WM_QUIT message, exiting main loop.\n");
-	      break;
-	    }
-	}
-    }
-
-  /* Close our X window */
-  if (pDisplay && iWindow)
-    {
-      iReturn = XDestroyWindow (pDisplay, iWindow);
-      if (iReturn == BadWindow)
-	ErrorF ("winClipboardProc - XDestroyWindow returned BadWindow.\n");
-      else
-	ErrorF ("winClipboardProc - XDestroyWindow succeeded.\n");
-    }
-
-
-#ifdef HAS_DEVWINDOWS
-  /* Close our Win32 message handle */
-  if (fdMessageQueue)
-    close (fdMessageQueue);
-#endif
-
-#if 0
-  /*
-   * FIXME: XCloseDisplay hangs if we call it, as of 2004/03/26.  The
-   * XSync and XSelectInput calls did not help.
-   */
-
-  /* Discard any remaining events */
-  XSync (pDisplay, TRUE);
-
-  /* Select event types to watch */
-  XSelectInput (pDisplay,
-		DefaultRootWindow (pDisplay),
-		None);
-
-  /* Close our X display */
-  if (pDisplay)
-    {
-      XCloseDisplay (pDisplay);
-    }
-#endif
-
-  g_iClipboardWindow = None;
-  g_pClipboardDisplay = NULL;
-  g_hwndClipboard = NULL;
-
-  return NULL;
-}
-
-
-/*
- * winClipboardErrorHandler - Our application specific error handler
- */
-
-static int
-winClipboardErrorHandler (Display *pDisplay, XErrorEvent *pErr)
-{
-  char pszErrorMsg[100];
-  
-  XGetErrorText (pDisplay,
-		 pErr->error_code,
-		 pszErrorMsg,
-		 sizeof (pszErrorMsg));
-  ErrorF ("winClipboardErrorHandler - ERROR: \n\t%s\n"
-	  "\tSerial: %d, Request Code: %d, Minor Code: %d\n",
-	  pszErrorMsg,
-	  pErr->serial,
-	  pErr->request_code,
-	  pErr->minor_code);
-  return 0;
-}
-
-
-/*
- * winClipboardIOErrorHandler - Our application specific IO error handler
- */
-
-static int
-winClipboardIOErrorHandler (Display *pDisplay)
-{
-  ErrorF ("\nwinClipboardIOErrorHandler!\n\n");
-
-  /* Restart at the main entry point */
-  longjmp (g_jmpEntry, WIN_JMP_ERROR_IO);
-  
-  return 0;
-}
diff --git a/hw/xwin/winclipboardunicode.c b/hw/xwin/winclipboardunicode.c
deleted file mode 100644
index ba86915..0000000
--- a/hw/xwin/winclipboardunicode.c
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "winclipboard.h"
-
-
-/*
- * Determine whether we suport Unicode or not.
- * NOTE: Currently, just check if we are on an NT-based platform or not.
- */
-
-Bool
-winClipboardDetectUnicodeSupport (void)
-{
-  Bool			fReturn = FALSE;
-  OSVERSIONINFO		osvi = {0};
-  
-  /* Get operating system version information */
-  osvi.dwOSVersionInfoSize = sizeof (osvi);
-  GetVersionEx (&osvi);
-
-  /* Branch on platform ID */
-  switch (osvi.dwPlatformId)
-    {
-    case VER_PLATFORM_WIN32_NT:
-      /* Unicode supported on NT only */
-      ErrorF ("DetectUnicodeSupport - Windows NT/2000/XP\n");
-      fReturn = TRUE;
-      break;
-
-    case VER_PLATFORM_WIN32_WINDOWS:
-      /* Unicode is not supported on non-NT */
-      ErrorF ("DetectUnicodeSupport - Windows 95/98/Me\n");
-      fReturn = FALSE;
-      break;
-    }
-
-  return fReturn;
-}
diff --git a/hw/xwin/winclipboardwndproc.c b/hw/xwin/winclipboardwndproc.c
deleted file mode 100644
index 802a740..0000000
--- a/hw/xwin/winclipboardwndproc.c
+++ /dev/null
@@ -1,622 +0,0 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include <sys/types.h>
-#include <sys/time.h>
-#include "winclipboard.h"
-
-extern void		winFixClipboardChain();
-
-
-/*
- * Constants
- */
-
-#define WIN_CLIPBOARD_PROP	"cyg_clipboard_prop"
-#define WIN_POLL_TIMEOUT	1
-
-
-/*
- * References to external symbols
- */
-
-extern Bool		g_fUseUnicode;
-extern Bool		g_fUnicodeSupport;
-extern void		*g_pClipboardDisplay;
-extern Window		g_iClipboardWindow;
-extern Atom		g_atomLastOwnedSelection;
-
-/* BPS - g_hwndClipboard needed for X app->Windows paste fix */
-extern HWND		g_hwndClipboard;
-
-/* 
- * Local function prototypes
- */
-
-static Bool
-winProcessXEventsTimeout (HWND hwnd, int iWindow, Display *pDisplay,
-			  Bool fUseUnicode, int iTimeoutSec);
-
-
-/*
- * Process X events up to specified timeout
- */
-
-static int
-winProcessXEventsTimeout (HWND hwnd, int iWindow, Display *pDisplay,
-			  Bool fUseUnicode, int iTimeoutSec)
-{
-  int			iConnNumber;
-  struct timeval	tv;
-  int			iReturn;
-  DWORD			dwStopTime = (GetTickCount () / 1000) + iTimeoutSec;
-
-  /* We need to ensure that all pending events are processed */
-  XSync (pDisplay, FALSE);
-
-  /* Get our connection number */
-  iConnNumber = ConnectionNumber (pDisplay);
-
-  /* Loop for X events */
-  while (1)
-    {
-      fd_set		fdsRead;
-
-      /* Setup the file descriptor set */
-      FD_ZERO (&fdsRead);
-      FD_SET (iConnNumber, &fdsRead);
-
-      /* Adjust timeout */
-      tv.tv_sec = dwStopTime - (GetTickCount () / 1000);
-      tv.tv_usec = 0;
-
-      /* Break out if no time left */
-      if (tv.tv_sec < 0)
-	return WIN_XEVENTS_SUCCESS;
-
-      /* Wait for a Windows event or an X event */
-      iReturn = select (iConnNumber + 1,/* Highest fds number */
-			&fdsRead,	/* Read mask */
-			NULL,		/* No write mask */
-			NULL,		/* No exception mask */
-			&tv);		/* No timeout */
-      if (iReturn <= 0)
-	{
-	  ErrorF ("winProcessXEventsTimeout - Call to select () failed: %d.  "
-		  "Bailing.\n", iReturn);
-	  break;
-	}
-
-      /* Branch on which descriptor became active */
-      if (FD_ISSET (iConnNumber, &fdsRead))
-	{
-	  /* Process X events */
-	  /* Exit when we see that server is shutting down */
-	  iReturn = winClipboardFlushXEvents (hwnd,
-					      iWindow,
-					      pDisplay,
-					      fUseUnicode);
-	  if (WIN_XEVENTS_NOTIFY == iReturn
-	      || WIN_XEVENTS_CONVERT == iReturn)
-	    {
-	      /* Bail out if convert or notify processed */
-	      return iReturn;
-	    }
-	}
-    }
-
-  return WIN_XEVENTS_SUCCESS;
-}
-
-
-/*
- * Process a given Windows message
- */
-
-/* BPS - Define our own message, which we'll post to ourselves to facilitate
- * resetting the delayed rendering mechanism after each paste from X app to
- * Windows app. TODO - Perhaps move to win.h with the other WM_USER messages.
- */
-#define WM_USER_PASTE_COMPLETE		(WM_USER + 1003)
-
-LRESULT CALLBACK
-winClipboardWindowProc (HWND hwnd, UINT message, 
-			WPARAM wParam, LPARAM lParam)
-{
-  static HWND		s_hwndNextViewer;
-  static Bool		s_fCBCInitialized;
-
-  /* Branch on message type */
-  switch (message)
-    {
-    case WM_DESTROY:
-      {
-	winDebug ("winClipboardWindowProc - WM_DESTROY\n");
-
-	/* Remove ourselves from the clipboard chain */
-	ChangeClipboardChain (hwnd, s_hwndNextViewer);
-	
-	s_hwndNextViewer = NULL;
-
-	PostQuitMessage (0);
-      }
-      return 0;
-
-
-    case WM_CREATE:
-      {
-	HWND first, next;
-	DWORD error_code = 0;
-	winDebug ("winClipboardWindowProc - WM_CREATE\n");
-	
-	first = GetClipboardViewer();			/* Get handle to first viewer in chain. */
-	if (first == hwnd) return 0;			/* Make sure it's not us! */
-	/* Add ourselves to the clipboard viewer chain */
-	next = SetClipboardViewer (hwnd);
-	error_code = GetLastError();
-	if (SUCCEEDED(error_code) && (next == first))	/* SetClipboardViewer must have succeeded, and the handle */
-		s_hwndNextViewer = next;		/* it returned must have been the first window in the chain */
-	else
-		s_fCBCInitialized = FALSE;
-      }
-      return 0;
-
-
-    case WM_CHANGECBCHAIN:
-      {
-	winDebug ("winClipboardWindowProc - WM_CHANGECBCHAIN: wParam(%x) "
-		  "lParam(%x) s_hwndNextViewer(%x)\n", 
-		  wParam, lParam, s_hwndNextViewer);
-
-	if ((HWND) wParam == s_hwndNextViewer)
-	  {
-	    s_hwndNextViewer = (HWND) lParam;
-	    if (s_hwndNextViewer == hwnd)
-	      {
-		s_hwndNextViewer = NULL;
-		winErrorFVerb (1, "winClipboardWindowProc - WM_CHANGECBCHAIN: "
-			       "attempted to set next window to ourselves.");
-	      }
-	  }
-	else if (s_hwndNextViewer)
-	  SendMessage (s_hwndNextViewer, message,
-		       wParam, lParam);
-
-      }
-      winDebug ("winClipboardWindowProc - WM_CHANGECBCHAIN: Exit\n");
-      return 0;
-
-    case WM_WM_REINIT:
-      {
-        /* Ensure that we're in the clipboard chain.  Some apps,
-         * WinXP's remote desktop for one, don't play nice with the
-         * chain.  This message is called whenever we receive a
-         * WM_ACTIVATEAPP message to ensure that we continue to
-         * receive clipboard messages.
-	 *
-	 * It might be possible to detect if we're still in the chain
-	 * by calling SendMessage (GetClipboardViewer(),
-	 * WM_DRAWCLIPBOARD, 0, 0); and then seeing if we get the
-	 * WM_DRAWCLIPBOARD message.  That, however, might be more
-	 * expensive than just putting ourselves back into the chain.
-	 */
-
-	HWND first, next;
-	DWORD error_code = 0;
-	winDebug ("winClipboardWindowProc - WM_WM_REINIT: Enter\n");
-
-	first = GetClipboardViewer();			/* Get handle to first viewer in chain. */
-	if (first == hwnd) return 0;			/* Make sure it's not us! */
-	winDebug ("  WM_WM_REINIT: Replacing us(%x) with %x at head "
-		  "of chain\n", hwnd, s_hwndNextViewer);
-	s_fCBCInitialized = FALSE;
-	ChangeClipboardChain (hwnd, s_hwndNextViewer);
-	s_hwndNextViewer = NULL;
-	s_fCBCInitialized = FALSE;
-	winDebug ("  WM_WM_REINIT: Putting us back at head of chain.\n");
-	first = GetClipboardViewer();			/* Get handle to first viewer in chain. */
-	if (first == hwnd) return 0;			/* Make sure it's not us! */
-	next = SetClipboardViewer (hwnd);
-	error_code = GetLastError();
-	if (SUCCEEDED(error_code) && (next == first))	/* SetClipboardViewer must have succeeded, and the handle */
-		s_hwndNextViewer = next;		/* it returned must have been the first window in the chain */
-	else
-		s_fCBCInitialized = FALSE;
-      }
-      winDebug ("winClipboardWindowProc - WM_WM_REINIT: Exit\n");
-      return 0;
-
-
-    case WM_DRAWCLIPBOARD:
-      {
-	static Bool s_fProcessingDrawClipboard = FALSE;
-	Display	*pDisplay = g_pClipboardDisplay;
-	Window	iWindow = g_iClipboardWindow;
-	int	iReturn;
-
-	winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Enter\n");
-
-	/*
-	 * We've occasionally seen a loop in the clipboard chain.
-	 * Try and fix it on the first hint of recursion.
-	 */
-	if (! s_fProcessingDrawClipboard) 
-	  {
-	    s_fProcessingDrawClipboard = TRUE;
-	  }
-	else
-	  {
-	    /* Attempt to break the nesting by getting out of the chain, twice?, and then fix and bail */
-	    s_fCBCInitialized = FALSE;
-	    ChangeClipboardChain (hwnd, s_hwndNextViewer);
-	    winFixClipboardChain();
-	    winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
-			   "Nested calls detected.  Re-initing.\n");
-	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
-	    s_fProcessingDrawClipboard = FALSE;
-	    return 0;
-	  }
-
-	/* Bail on first message */
-	if (!s_fCBCInitialized)
-	  {
-	    s_fCBCInitialized = TRUE;
-	    s_fProcessingDrawClipboard = FALSE;
-	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
-	    return 0;
-	  }
-
-	/*
-	 * NOTE: We cannot bail out when NULL == GetClipboardOwner ()
-	 * because some applications deal with the clipboard in a manner
-	 * that causes the clipboard owner to be NULL when they are in
-	 * fact taking ownership.  One example of this is the Win32
-	 * native compile of emacs.
-	 */
-	
-	/* Bail when we still own the clipboard */
-	if (hwnd == GetClipboardOwner ())
-	  {
-
-	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
-		    "We own the clipboard, returning.\n");
-	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
-	    s_fProcessingDrawClipboard = FALSE;
-	    if (s_hwndNextViewer)
-		SendMessage (s_hwndNextViewer, message, wParam, lParam);
-	    return 0;
-	  }
-
-	/*
-	 * Do not take ownership of the X11 selections when something
-	 * other than CF_TEXT or CF_UNICODETEXT has been copied
-	 * into the Win32 clipboard.
-	 */
-	if (!IsClipboardFormatAvailable (CF_TEXT)
-	    && !IsClipboardFormatAvailable (CF_UNICODETEXT))
-	  {
-
-	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
-		    "Clipboard does not contain CF_TEXT nor "
-		    "CF_UNICODETEXT.\n");
-
-	    /*
-	     * We need to make sure that the X Server has processed
-	     * previous XSetSelectionOwner messages.
-	     */
-	    XSync (pDisplay, FALSE);
-	    
-	    /* Release PRIMARY selection if owned */
-	    iReturn = XGetSelectionOwner (pDisplay, XA_PRIMARY);
-	    if (iReturn == g_iClipboardWindow)
-	      {
-		winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
-			"PRIMARY selection is owned by us.\n");
-		XSetSelectionOwner (pDisplay,
-				    XA_PRIMARY,
-				    None,
-				    CurrentTime);
-	      }
-	    else if (BadWindow == iReturn || BadAtom == iReturn)
-	      winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
-		      "XGetSelection failed for PRIMARY: %d\n", iReturn);
-
-	    /* Release CLIPBOARD selection if owned */
-	    iReturn = XGetSelectionOwner (pDisplay,
-					  XInternAtom (pDisplay,
-						       "CLIPBOARD",
-						       False));
-	    if (iReturn == g_iClipboardWindow)
-	      {
-		winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
-			"CLIPBOARD selection is owned by us.\n");
-		XSetSelectionOwner (pDisplay,
-				    XInternAtom (pDisplay,
-						 "CLIPBOARD",
-						 False),
-				    None,
-				    CurrentTime);
-	      }
-	    else if (BadWindow == iReturn || BadAtom == iReturn)
-	      winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
-		      "XGetSelection failed for CLIPBOARD: %d\n", iReturn);
-
-	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
-	    s_fProcessingDrawClipboard = FALSE;
-	    if (s_hwndNextViewer)
-		SendMessage (s_hwndNextViewer, message, wParam, lParam);
-	    return 0;
-	  }
-
-	/* Reassert ownership of PRIMARY */	  
-	iReturn = XSetSelectionOwner (pDisplay,
-				      XA_PRIMARY,
-				      iWindow,
-				      CurrentTime);
-	if (iReturn == BadAtom || iReturn == BadWindow)
-	  {
-	    winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
-		    "Could not reassert ownership of PRIMARY\n");
-	  }
-	else
-	  {
-	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
-		    "Reasserted ownership of PRIMARY\n");
-	  }
-	
-	/* Reassert ownership of the CLIPBOARD */	  
-	iReturn = XSetSelectionOwner (pDisplay,
-				      XInternAtom (pDisplay,
-						   "CLIPBOARD",
-						   False),
-				      iWindow,
-				      CurrentTime);
-	if (iReturn == BadAtom || iReturn == BadWindow)
-	  {
-	    winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
-		    "Could not reassert ownership of CLIPBOARD\n");
-	  }
-	else
-	  {
-	    winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
-		    "Reasserted ownership of CLIPBOARD\n");
-	  }
-	
-	/* Flush the pending SetSelectionOwner event now */
-	XFlush (pDisplay);
-
-	s_fProcessingDrawClipboard = FALSE;
-      }
-      winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
-      /* Pass the message on the next window in the clipboard viewer chain */
-      if (s_hwndNextViewer)
-	SendMessage (s_hwndNextViewer, message, wParam, lParam);
-      return 0;
-
-
-    case WM_DESTROYCLIPBOARD:
-      /*
-       * NOTE: Intentionally do nothing.
-       * Changes in the Win32 clipboard are handled by WM_DRAWCLIPBOARD
-       * above.  We only process this message to conform to the specs
-       * for delayed clipboard rendering in Win32.  You might think
-       * that we need to release ownership of the X11 selections, but
-       * we do not, because a WM_DRAWCLIPBOARD message will closely
-       * follow this message and reassert ownership of the X11
-       * selections, handling the issue for us.
-       */
-      return 0;
-
-
-    case WM_RENDERFORMAT:
-    case WM_RENDERALLFORMATS:
-      {
-	int	iReturn;
-	Display *pDisplay = g_pClipboardDisplay;
-	Window	iWindow = g_iClipboardWindow;
-	Bool	fConvertToUnicode;
-
-	winDebug ("winClipboardWindowProc - WM_RENDER*FORMAT - Hello.\n");
-
-	/* Flag whether to convert to Unicode or not */
-	if (message == WM_RENDERALLFORMATS)
-	  fConvertToUnicode = FALSE;
-	else
-	  fConvertToUnicode = g_fUnicodeSupport && (CF_UNICODETEXT == wParam);
-
-	/* Request the selection contents */
-	iReturn = XConvertSelection (pDisplay,
-				     g_atomLastOwnedSelection,
-				     XInternAtom (pDisplay,
-						  "COMPOUND_TEXT", False),
-				     XInternAtom (pDisplay,
-						  "CYGX_CUT_BUFFER", False),
-				     iWindow,
-				     CurrentTime);
-	if (iReturn == BadAtom || iReturn == BadWindow)
-	  {
-	    winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMAT - "
-		    "XConvertSelection () failed\n");
-	    break;
-	  }
-
-	/* Special handling for WM_RENDERALLFORMATS */
-	if (message == WM_RENDERALLFORMATS)
-	  {
-	    /* We must open and empty the clipboard */
-
-	    /* Close clipboard if we have it open already */
-	    if (GetOpenClipboardWindow () == hwnd)
-	      {
-		CloseClipboard ();
-	      }	    
-
-	    if (!OpenClipboard (hwnd))
-	      {
-		winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMATS - "
-			"OpenClipboard () failed: %08x\n",
-			GetLastError ());
-		break;
-	      }
-	    
-	    if (!EmptyClipboard ())
-	      {
-		winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMATS - "
-			"EmptyClipboard () failed: %08x\n",
-		      GetLastError ());
-		break;
-	      }
-	  }
-
-	/* Process the SelectionNotify event */
-	iReturn = winProcessXEventsTimeout (hwnd,
-					    iWindow,
-					    pDisplay,
-					    fConvertToUnicode,
-					    WIN_POLL_TIMEOUT);
-	if (WIN_XEVENTS_CONVERT == iReturn)
-	  {
-	    /*
-	     * The selection was offered for conversion first, so we have
-	     * to process a second SelectionNotify event to get the actual
-	     * data in the selection.
-	     */
-	    iReturn = winProcessXEventsTimeout (hwnd,
-						iWindow,
-						pDisplay,
-						fConvertToUnicode,
-						WIN_POLL_TIMEOUT);
-	  }
-	
-	/*
-	 * The last of the up-to two calls to winProcessXEventsTimeout
-	 * from above had better have seen a notify event, or else we
-	 * are dealing with a buggy or old X11 app.  In these cases we
-	 * have to paste some fake data to the Win32 clipboard to
-	 * satisfy the requirement that we write something to it.
-	 */
-	if (WIN_XEVENTS_NOTIFY != iReturn)
-	  {
-	    /* Paste no data, to satisfy required call to SetClipboardData */
-	    if (g_fUnicodeSupport)
-	      SetClipboardData (CF_UNICODETEXT, NULL);
-	    SetClipboardData (CF_TEXT, NULL);
-	  }
-
-	/* BPS - Post ourselves a user message whose handler will reset the
-	 * delayed rendering mechanism after the paste is complete. This is
-	 * necessary because calling SetClipboardData() with a NULL argument
-	 * here will cause the data we just put on the clipboard to be lost!
-	 */
-	PostMessage(g_hwndClipboard, WM_USER_PASTE_COMPLETE, 0, 0);
-
-	/* Special handling for WM_RENDERALLFORMATS */
-	if (message == WM_RENDERALLFORMATS)
-	  {
-	    /* We must close the clipboard */
-	    
-	    if (!CloseClipboard ())
-	      {
-	      winErrorFVerb (1, "winClipboardWindowProc - WM_RENDERALLFORMATS - "
-		      "CloseClipboard () failed: %08x\n",
-		      GetLastError ());
-	      break;
-	      }
-	  }
-
-	winDebug ("winClipboardWindowProc - WM_RENDER*FORMAT - Returning.\n");
-	return 0;
-      }
-    /* BPS - This WM_USER message is posted by us. It gives us the opportunity
-     * to reset the delayed rendering mechanism after each and every paste
-     * from an X app to a Windows app. Without such a mechanism, subsequent
-     * changes of selection in the X app owning the selection are not
-     * reflected in pastes into Windows apps, since Windows won't send us the
-     * WM_RENDERFORMAT message unless someone has set changed data (or NULL)
-     * on the clipboard. */
-    case WM_USER_PASTE_COMPLETE:
-      {
-	if (hwnd != GetClipboardOwner ())
-	  /* In case we've lost the selection since posting the message */
-	  return 0;
-	winDebug ("winClipboardWindowProc - WM_USER_PASTE_COMPLETE\n");
-
-	/* Set up for another delayed rendering callback */
-	OpenClipboard (g_hwndClipboard);
-
-	/* Take ownership of the Windows clipboard */
-	EmptyClipboard ();
-
-	/* Advertise Unicode if we support it */
-	if (g_fUnicodeSupport)
-	  SetClipboardData (CF_UNICODETEXT, NULL);
-
-	/* Always advertise regular text */
-	SetClipboardData (CF_TEXT, NULL);
-
-	/* Release the clipboard */
-	CloseClipboard ();
-      }
-      return 0;
-    }
-
-  /* Let Windows perform default processing for unhandled messages */
-  return DefWindowProc (hwnd, message, wParam, lParam);
-}
-
-
-/*
- * Process any pending Windows messages
- */
-
-BOOL
-winClipboardFlushWindowsMessageQueue (HWND hwnd)
-{
-  MSG			msg;
-
-  /* Flush the messaging window queue */
-  /* NOTE: Do not pass the hwnd of our messaging window to PeekMessage,
-   * as this will filter out many non-window-specific messages that
-   * are sent to our thread, such as WM_QUIT.
-   */
-  while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
-    {
-      /* Dispatch the message if not WM_QUIT */
-      if (msg.message == WM_QUIT)
-	return FALSE;
-      else
-	DispatchMessage (&msg);
-    }
-  
-  return TRUE;
-}
diff --git a/hw/xwin/winclipboardwrappers.c b/hw/xwin/winclipboardwrappers.c
deleted file mode 100755
index 2cfe0ff..0000000
--- a/hw/xwin/winclipboardwrappers.c
+++ /dev/null
@@ -1,541 +0,0 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "dixstruct.h"
-#include <X11/Xatom.h>
-
-
-/*
- * Constants
- */
-
-#define CLIP_NUM_SELECTIONS		2
-#define CLIP_OWN_PRIMARY		0
-#define CLIP_OWN_CLIPBOARD		1
-
-
-/*
- * Local function prototypes
- */
-
-DISPATCH_PROC(winProcEstablishConnection);
-DISPATCH_PROC(winProcQueryTree);
-DISPATCH_PROC(winProcSetSelectionOwner);
-
-
-/*
- * References to external symbols
- */
-
-extern Bool		g_fUnicodeSupport;
-extern int		g_iNumScreens;
-extern unsigned int	g_uiAuthDataLen;
-extern char		*g_pAuthData;
-extern Bool		g_fXdmcpEnabled;
-extern Bool		g_fClipboardLaunched;
-extern Bool		g_fClipboardStarted;
-extern Bool		g_fClipboard;
-extern Window		g_iClipboardWindow;
-extern Atom		g_atomLastOwnedSelection;
-extern HWND		g_hwndClipboard;
-
-extern winDispatchProcPtr	winProcEstablishConnectionOrig;
-extern winDispatchProcPtr	winProcQueryTreeOrig;
-extern winDispatchProcPtr	winProcSetSelectionOwnerOrig;
-
-
-/*
- * Wrapper for internal QueryTree function.
- * Hides the clipboard client when it is the only client remaining.
- */
-
-int
-winProcQueryTree (ClientPtr client)
-{
-  int			iReturn;
-
-  /*
-   * This procedure is only used for initialization.
-   * We can unwrap the original procedure at this point
-   * so that this function is no longer called until the
-   * server resets and the function is wrapped again.
-   */
-  ProcVector[X_QueryTree] = winProcQueryTreeOrig;
-
-  /*
-   * Call original function and bail if it fails.
-   * NOTE: We must do this first, since we need XdmcpOpenDisplay
-   * to be called before we initialize our clipboard client.
-   */
-  iReturn = (*winProcQueryTreeOrig) (client);
-  if (iReturn != 0)
-    {
-      ErrorF ("winProcQueryTree - ProcQueryTree failed, bailing.\n");
-      return iReturn;
-    }
-
-  /* Make errors more obvious */
-  winProcQueryTreeOrig = NULL;
-
-  /* Do nothing if clipboard is not enabled */
-  if (!g_fClipboard)
-    {
-      ErrorF ("winProcQueryTree - Clipboard is not enabled, "
-	      "returning.\n");
-      return iReturn;
-    }
-
-  /* If the clipboard client has already been started, abort */
-  if (g_fClipboardLaunched)
-    {
-      ErrorF ("winProcQueryTree - Clipboard client already "
-	      "launched, returning.\n");
-      return iReturn;
-    }
-
-  /* Startup the clipboard client if clipboard mode is being used */
-  if (g_fXdmcpEnabled && g_fClipboard)
-    {
-      /*
-       * NOTE: The clipboard client is started here for a reason:
-       * 1) Assume you are using XDMCP (e.g. XWin -query %hostname%)
-       * 2) If the clipboard client attaches during X Server startup,
-       *    then it becomes the "magic client" that causes the X Server
-       *    to reset if it exits.
-       * 3) XDMCP calls KillAllClients when it starts up.
-       * 4) The clipboard client is a client, so it is killed.
-       * 5) The clipboard client is the "magic client", so the X Server
-       *    resets itself.
-       * 6) This repeats ad infinitum.
-       * 7) We avoid this by waiting until at least one client (could
-       *    be XDM, could be another client) connects, which makes it
-       *    almost certain that the clipboard client will not connect
-       *    until after XDM when using XDMCP.
-       * 8) Unfortunately, there is another problem.
-       * 9) XDM walks the list of windows with XQueryTree,
-       *    killing any client it finds with a window.
-       * 10)Thus, when using XDMCP we wait until the first call
-       *    to ProcQueryTree before we startup the clipboard client.
-       *    This should prevent XDM from finding the clipboard client,
-       *    since it has not yet created a window.
-       * 11)Startup when not using XDMCP is handled in
-       *    winProcEstablishConnection.
-       */
-      
-      /* Create the clipboard client thread */
-      if (!winInitClipboard ())
-	{
-	  ErrorF ("winProcQueryTree - winClipboardInit "
-		  "failed.\n");
-	  return iReturn;
-	}
-      
-      ErrorF ("winProcQueryTree - winInitClipboard returned.\n");
-    }
-  
-  /* Flag that clipboard client has been launched */
-  g_fClipboardLaunched = TRUE;
-
-  return iReturn;
-}
-
-
-/*
- * Wrapper for internal EstablishConnection function.
- * Initializes internal clients that must not be started until
- * an external client has connected.
- */
-
-int
-winProcEstablishConnection (ClientPtr client)
-{
-  int			iReturn;
-  static int		s_iCallCount = 0;
-  static unsigned long	s_ulServerGeneration = 0;
-
-  ErrorF ("winProcEstablishConnection - Hello\n");
-
-  /* Do nothing if clipboard is not enabled */
-  if (!g_fClipboard)
-    {
-      ErrorF ("winProcEstablishConnection - Clipboard is not enabled, "
-	      "returning.\n");
-      
-      /* Unwrap the original function, call it, and return */
-      InitialVector[2] = winProcEstablishConnectionOrig;
-      iReturn = (*winProcEstablishConnectionOrig) (client);
-      winProcEstablishConnectionOrig = NULL;
-      return iReturn;
-    }
-
-  /* Watch for server reset */
-  if (s_ulServerGeneration != serverGeneration)
-    {
-      /* Save new generation number */
-      s_ulServerGeneration = serverGeneration;
-
-      /* Reset call count */
-      s_iCallCount = 0;
-    }
-
-  /* Increment call count */
-  ++s_iCallCount;
-
-  /* Wait for second call when Xdmcp is enabled */
-  if (g_fXdmcpEnabled
-      && !g_fClipboardLaunched
-      && s_iCallCount < 4)
-    {
-      ErrorF ("winProcEstablishConnection - Xdmcp enabled, waiting to "
-	      "start clipboard client until fourth call.\n");
-      return (*winProcEstablishConnectionOrig) (client);
-    }
-
-  /*
-   * This procedure is only used for initialization.
-   * We can unwrap the original procedure at this point
-   * so that this function is no longer called until the
-   * server resets and the function is wrapped again.
-   */
-  InitialVector[2] = winProcEstablishConnectionOrig;
-
-  /*
-   * Call original function and bail if it fails.
-   * NOTE: We must do this first, since we need XdmcpOpenDisplay
-   * to be called before we initialize our clipboard client.
-   */
-  iReturn = (*winProcEstablishConnectionOrig) (client);
-  if (iReturn != 0)
-    {
-      ErrorF ("winProcEstablishConnection - ProcEstablishConnection "
-	      "failed, bailing.\n");
-      return iReturn;
-    }
-
-  /* Clear original function pointer */
-  winProcEstablishConnectionOrig = NULL;
-
-  /* If the clipboard client has already been started, abort */
-  if (g_fClipboardLaunched)
-    {
-      ErrorF ("winProcEstablishConnection - Clipboard client already "
-	      "launched, returning.\n");
-      return iReturn;
-    }
-
-  /* Startup the clipboard client if clipboard mode is being used */
-  if (g_fClipboard)
-    {
-      /*
-       * NOTE: The clipboard client is started here for a reason:
-       * 1) Assume you are using XDMCP (e.g. XWin -query %hostname%)
-       * 2) If the clipboard client attaches during X Server startup,
-       *    then it becomes the "magic client" that causes the X Server
-       *    to reset if it exits.
-       * 3) XDMCP calls KillAllClients when it starts up.
-       * 4) The clipboard client is a client, so it is killed.
-       * 5) The clipboard client is the "magic client", so the X Server
-       *    resets itself.
-       * 6) This repeats ad infinitum.
-       * 7) We avoid this by waiting until at least one client (could
-       *    be XDM, could be another client) connects, which makes it
-       *    almost certain that the clipboard client will not connect
-       *    until after XDM when using XDMCP.
-       * 8) Unfortunately, there is another problem.
-       * 9) XDM walks the list of windows with XQueryTree,
-       *    killing any client it finds with a window.
-       * 10)Thus, when using XDMCP we wait until the second call
-       *    to ProcEstablishCeonnection before we startup the clipboard
-       *    client.  This should prevent XDM from finding the clipboard
-       *    client, since it has not yet created a window.
-       */
-      
-      /* Create the clipboard client thread */
-      if (!winInitClipboard ())
-	{
-	  ErrorF ("winProcEstablishConnection - winClipboardInit "
-		  "failed.\n");
-	  return iReturn;
-	}
-      
-      ErrorF ("winProcEstablishConnection - winInitClipboard returned.\n");
-    }
-  
-  /* Flag that clipboard client has been launched */
-  g_fClipboardLaunched = TRUE;
-
-  return iReturn;
-}
-
-
-/*
- * Wrapper for internal SetSelectionOwner function.
- * Grabs ownership of Windows clipboard when X11 clipboard owner changes.
- */
-
-int
-winProcSetSelectionOwner (ClientPtr client)
-{
-  int			i;
-  DrawablePtr		pDrawable;
-  WindowPtr		pWindow = None;
-  Bool			fOwnedToNotOwned = FALSE;
-  static Window		s_iOwners[CLIP_NUM_SELECTIONS] = {None};
-  static unsigned long	s_ulServerGeneration = 0;
-  REQUEST(xSetSelectionOwnerReq);
-  
-  REQUEST_SIZE_MATCH(xSetSelectionOwnerReq);
-
-#if 0
-  ErrorF ("winProcSetSelectionOwner - Hello.\n");
-#endif
-
-  /* Watch for server reset */
-  if (s_ulServerGeneration != serverGeneration)
-    {
-      /* Save new generation number */
-      s_ulServerGeneration = serverGeneration;
-
-      /* Initialize static variables */
-      for (i = 0; i < CLIP_NUM_SELECTIONS; ++i)
-	s_iOwners[i] = None;
-    }
-
-  /* Abort if clipboard not completely initialized yet */
-  if (!g_fClipboardStarted)
-    {
-      ErrorF ("winProcSetSelectionOwner - Clipboard not yet started, "
-	      "aborting.\n");
-      goto winProcSetSelectionOwner_Done;
-    }
-  
-  /* Grab window if we have one */
-  if (None != stuff->window)
-    {
-      /* Grab the Window from the request */
-      int rc = dixLookupWindow(&pWindow, stuff->window, client, DixReadAccess);
-      if (rc != Success) {
-	  ErrorF ("winProcSetSelectionOwner - Found BadWindow, aborting.\n");
-	  goto winProcSetSelectionOwner_Done;
-      }
-    }
-
-  /* Now we either have a valid window or None */
-
-  /* Save selection owners for monitored selections, ignore other selections */
-  if (XA_PRIMARY == stuff->selection)
-    {
-      /* Look for owned -> not owned transition */
-      if (None == stuff->window
-	  && None != s_iOwners[CLIP_OWN_PRIMARY])
-	{
-	  fOwnedToNotOwned = TRUE;
-
-#if 0
-	  ErrorF ("winProcSetSelectionOwner - PRIMARY - Going from "
-		  "owned to not owned.\n");
-#endif
-
-	  /* Adjust last owned selection */
-	  if (None != s_iOwners[CLIP_OWN_CLIPBOARD])
-	    g_atomLastOwnedSelection = MakeAtom ("CLIPBOARD", 9, TRUE);
-	  else
-	    g_atomLastOwnedSelection = None;
-	}
-      
-      /* Save new selection owner or None */
-      s_iOwners[CLIP_OWN_PRIMARY] = stuff->window;
-
-#if 0
-      ErrorF ("winProcSetSelectionOwner - PRIMARY - Now owned by: %d\n",
-	      stuff->window);
-#endif
-    }
-  else if (MakeAtom ("CLIPBOARD", 9, TRUE) == stuff->selection)
-    {
-      /* Look for owned -> not owned transition */
-      if (None == stuff->window
-	  && None != s_iOwners[CLIP_OWN_CLIPBOARD])
-	{
-	  fOwnedToNotOwned = TRUE;
-	  
-#if 0
-	  ErrorF ("winProcSetSelectionOwner - CLIPBOARD - Going from "
-		  "owned to not owned.\n");
-#endif
-
-	  /* Adjust last owned selection */
-	  if (None != s_iOwners[CLIP_OWN_PRIMARY])
-	    g_atomLastOwnedSelection = XA_PRIMARY;
-	  else
-	    g_atomLastOwnedSelection = None;
-	}
-      
-      /* Save new selection owner or None */
-      s_iOwners[CLIP_OWN_CLIPBOARD] = stuff->window;
-
-#if 0
-      ErrorF ("winProcSetSelectionOwner - CLIPBOARD - Now owned by: %d\n",
-	      stuff->window);
-#endif
-    }
-  else
-    goto winProcSetSelectionOwner_Done;
-
-  /*
-   * At this point, if one of the selections is still owned by the 
-   * clipboard manager then it should be marked as unowned since
-   * we will be taking ownership of the Win32 clipboard.
-   */
-  if (g_iClipboardWindow == s_iOwners[CLIP_OWN_PRIMARY])
-    s_iOwners[CLIP_OWN_PRIMARY] = None;
-  if (g_iClipboardWindow == s_iOwners[CLIP_OWN_CLIPBOARD])
-    s_iOwners[CLIP_OWN_CLIPBOARD] = None;
-
-  /*
-   * Handle case when selection is being disowned,
-   * WM_DRAWCLIPBOARD did not do the disowning,
-   * both monitored selections are no longer owned,
-   * an owned to not owned transition was detected,
-   * and we currently own the Win32 clipboard.
-   */
-  if (None == stuff->window
-      && (None == s_iOwners[CLIP_OWN_PRIMARY]
-	  || g_iClipboardWindow == s_iOwners[CLIP_OWN_PRIMARY])
-      && (None == s_iOwners[CLIP_OWN_CLIPBOARD]
-	  || g_iClipboardWindow == s_iOwners[CLIP_OWN_CLIPBOARD])
-      && fOwnedToNotOwned
-      && g_hwndClipboard != NULL
-      && g_hwndClipboard == GetClipboardOwner ())
-    {
-#if 0
-      ErrorF ("winProcSetSelectionOwner - We currently own the "
-	      "clipboard and neither the PRIMARY nor the CLIPBOARD "
-	      "selections are owned, releasing ownership of Win32 "
-	      "clipboard.\n");
-#endif
-      
-      /* Release ownership of the Windows clipboard */
-      OpenClipboard (NULL);
-      EmptyClipboard ();
-      CloseClipboard ();
-
-      /* Clear X selection ownership (might still be marked as us owning) */
-      s_iOwners[CLIP_OWN_PRIMARY] = None;
-      s_iOwners[CLIP_OWN_CLIPBOARD] = None;
-      
-      goto winProcSetSelectionOwner_Done;
-    }
-
-  /* Abort if no window at this point */
-  if (None == stuff->window)
-    {
-#if 0
-      ErrorF ("winProcSetSelectionOwner - No window, returning.\n");
-#endif
-      goto winProcSetSelectionOwner_Done;
-    }
-
-  /* Abort if invalid selection */
-  if (!ValidAtom (stuff->selection))
-    {
-      ErrorF ("winProcSetSelectionOwner - Found BadAtom, aborting.\n");
-      goto winProcSetSelectionOwner_Done;
-    }
-
-  /* Cast Window to Drawable */
-  pDrawable = (DrawablePtr) pWindow;
-  
-  /* Abort if clipboard manager is owning the selection */
-  if (pDrawable->id == g_iClipboardWindow)
-    {
-#if 0
-      ErrorF ("winProcSetSelectionOwner - We changed ownership, "
-	      "aborting.\n");
-#endif
-      goto winProcSetSelectionOwner_Done;
-    }
-
-  /* Abort if root window is taking ownership */
-  if (pDrawable->id == 0)
-    {
-      ErrorF ("winProcSetSelectionOwner - Root window taking ownership, "
-	      "aborting\n");
-      goto winProcSetSelectionOwner_Done;
-    }
-
-  /* Close clipboard if we have it open already */
-  if (GetOpenClipboardWindow () == g_hwndClipboard)
-    {
-      CloseClipboard ();
-    }
-
-  /* Access the Windows clipboard */
-  if (!OpenClipboard (g_hwndClipboard))
-    {
-      ErrorF ("winProcSetSelectionOwner - OpenClipboard () failed: %08x\n",
-	      (int) GetLastError ());
-      goto winProcSetSelectionOwner_Done;
-    }
-
-  /* Take ownership of the Windows clipboard */
-  if (!EmptyClipboard ())
-    {
-      ErrorF ("winProcSetSelectionOwner - EmptyClipboard () failed: %08x\n",
-	      (int) GetLastError ());
-      goto winProcSetSelectionOwner_Done;
-    }
-
-  /* Advertise Unicode if we support it */
-  if (g_fUnicodeSupport)
-    SetClipboardData (CF_UNICODETEXT, NULL);
-
-  /* Always advertise regular text */
-  SetClipboardData (CF_TEXT, NULL);
-
-  /* Save handle to last owned selection */
-  g_atomLastOwnedSelection = stuff->selection;
-
-  /* Release the clipboard */
-  if (!CloseClipboard ())
-    {
-      ErrorF ("winProcSetSelectionOwner - CloseClipboard () failed: "
-	      "%08x\n",
-	      (int) GetLastError ());
-      goto winProcSetSelectionOwner_Done;
-    }
-
- winProcSetSelectionOwner_Done:
-  return (*winProcSetSelectionOwnerOrig) (client);
-}
diff --git a/hw/xwin/winclipboardxevents.c b/hw/xwin/winclipboardxevents.c
deleted file mode 100644
index d4c617b..0000000
--- a/hw/xwin/winclipboardxevents.c
+++ /dev/null
@@ -1,796 +0,0 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "winclipboard.h"
-
-
-/*
- * References to external symbols
- */
-
-extern Bool		g_fUnicodeSupport;
-
-
-/*
- * Process any pending X events
- */
-
-int
-winClipboardFlushXEvents (HWND hwnd,
-			  int iWindow,
-			  Display *pDisplay,
-			  Bool fUseUnicode)
-{
-  Atom			atomLocalProperty = XInternAtom (pDisplay,
-							 WIN_LOCAL_PROPERTY,
-							 False);
-  Atom			atomUTF8String = XInternAtom (pDisplay,
-						      "UTF8_STRING",
-						      False);
-  Atom			atomCompoundText = XInternAtom (pDisplay,
-							"COMPOUND_TEXT",
-							False);
-  Atom			atomTargets = XInternAtom (pDisplay,
-						   "TARGETS",
-						   False);
-
-  /* Process all pending events */
-  while (XPending (pDisplay))
-    {
-      XTextProperty		xtpText = {0};
-      XEvent			event;
-      XSelectionEvent		eventSelection;
-      unsigned long		ulReturnBytesLeft;
-      unsigned char		*pszReturnData = NULL;
-      char			*pszGlobalData = NULL;
-      int			iReturn;
-      HGLOBAL			hGlobal = NULL;
-      XICCEncodingStyle		xiccesStyle;
-      int			iConvertDataLen = 0;
-      char			*pszConvertData = NULL;
-      char			*pszTextList[2] = {NULL};
-      int			iCount;
-      char			**ppszTextList = NULL;
-      wchar_t			*pwszUnicodeStr = NULL;
-      int			iUnicodeLen = 0;
-      int			iReturnDataLen = 0;
-      int			i;
-      Bool			fAbort = FALSE;
-      Bool			fCloseClipboard = FALSE;
-      Bool			fSetClipboardData = TRUE;
-
-      /* Get the next event - will not block because one is ready */
-      XNextEvent (pDisplay, &event);
-
-      /* Branch on the event type */
-      switch (event.type)
-	{
-	  /*
-	   * SelectionRequest
-	   */
-
-	case SelectionRequest:
-#if 0
-	  {
-	    char			*pszAtomName = NULL;
-	    
-	    ErrorF ("SelectionRequest - target %d\n",
-		    event.xselectionrequest.target);
-	    
-	    pszAtomName = XGetAtomName (pDisplay,
-					event.xselectionrequest.target);
-	    ErrorF ("SelectionRequest - Target atom name %s\n", pszAtomName);
-	    XFree (pszAtomName);
-	    pszAtomName = NULL;
-	  }
-#endif
-
-	  /* Abort if invalid target type */
-	  if (event.xselectionrequest.target != XA_STRING
-	      && event.xselectionrequest.target != atomUTF8String
-	      && event.xselectionrequest.target != atomCompoundText
-	      && event.xselectionrequest.target != atomTargets)
-	    {
-	      /* Abort */
-	      fAbort = TRUE;
-	      goto winClipboardFlushXEvents_SelectionRequest_Done;
-	    }
-
-	  /* Handle targets type of request */
-	  if (event.xselectionrequest.target == atomTargets)
-	    {
-	      Atom atomTargetArr[] = {atomTargets,
-				      atomCompoundText,
-				      atomUTF8String,
-				      XA_STRING};
-
-	      /* Try to change the property */
-	      iReturn = XChangeProperty (pDisplay,
-					 event.xselectionrequest.requestor,
-					 event.xselectionrequest.property,
-					 XA_ATOM,
-					 32,
-					 PropModeReplace,
-					 (unsigned char *) atomTargetArr,
-					 (sizeof (atomTargetArr)
-					  / sizeof (atomTargetArr[0])));
-	      if (iReturn == BadAlloc
-		  || iReturn == BadAtom
-		  || iReturn == BadMatch
-		  || iReturn == BadValue
-		  || iReturn == BadWindow)
-		{
-		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
-			  "XChangeProperty failed: %d\n",
-			  iReturn);
-		}
-
-	      /* Setup selection notify xevent */
-	      eventSelection.type	= SelectionNotify;
-	      eventSelection.send_event	= True;
-	      eventSelection.display	= pDisplay;
-	      eventSelection.requestor	= event.xselectionrequest.requestor;
-	      eventSelection.selection	= event.xselectionrequest.selection;
-	      eventSelection.target	= event.xselectionrequest.target;
-	      eventSelection.property	= event.xselectionrequest.property;
-	      eventSelection.time	= event.xselectionrequest.time;
-
-	      /*
-	       * Notify the requesting window that
-	       * the operation has completed
-	       */
-	      iReturn = XSendEvent (pDisplay,
-				    eventSelection.requestor,
-				    False,
-				    0L,
-				    (XEvent *) &eventSelection);
-	      if (iReturn == BadValue || iReturn == BadWindow)
-		{
-		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
-			  "XSendEvent () failed\n");
-		}
-	      break;
-	    }
-
-	  /* Check that clipboard format is available */
-	  if (fUseUnicode
-	      && !IsClipboardFormatAvailable (CF_UNICODETEXT))
-	    {
-	      ErrorF ("winClipboardFlushXEvents - CF_UNICODETEXT is not "
-		      "available from Win32 clipboard.  Aborting.\n");
-
-	      /* Abort */
-	      fAbort = TRUE;
-	      goto winClipboardFlushXEvents_SelectionRequest_Done;
-	    }
-	  else if (!fUseUnicode
-		   && !IsClipboardFormatAvailable (CF_TEXT))
-	    {
-	      ErrorF ("winClipboardFlushXEvents - CF_TEXT is not "
-		      "available from Win32 clipboard.  Aborting.\n");
-
-	      /* Abort */
-	      fAbort = TRUE;
-	      goto winClipboardFlushXEvents_SelectionRequest_Done;
-	    }
-
-	  /* Close clipboard if we have it open already */
-	  if (GetOpenClipboardWindow () == hwnd)
-	    {
-	      CloseClipboard ();
-	    }
-
-	  /* Access the clipboard */
-	  if (!OpenClipboard (hwnd))
-	    {
-	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
-		      "OpenClipboard () failed: %08x\n",
-		      GetLastError ());
-
-	      /* Abort */
-	      fAbort = TRUE;
-	      goto winClipboardFlushXEvents_SelectionRequest_Done;
-	    }
-	  
-	  /* Indicate that clipboard was opened */
-	  fCloseClipboard = TRUE;
-
-	  /* Setup the string style */
-	  if (event.xselectionrequest.target == XA_STRING)
-	    xiccesStyle = XStringStyle;
-#ifdef X_HAVE_UTF8_STRING
-	  else if (event.xselectionrequest.target == atomUTF8String)
-	    xiccesStyle = XUTF8StringStyle;
-#endif
-	  else if (event.xselectionrequest.target == atomCompoundText)
-	    xiccesStyle = XCompoundTextStyle;
-	  else
-	    xiccesStyle = XStringStyle;
-
-	  /*
-	   * FIXME: Can't pass CF_UNICODETEXT on Windows 95/98/Me
-	   */
-	  
-	  /* Get a pointer to the clipboard text, in desired format */
-	  if (fUseUnicode)
-	    {
-	      /* Retrieve clipboard data */
-	      hGlobal = GetClipboardData (CF_UNICODETEXT);
-	    }
-	  else
-	    {
-	      /* Retrieve clipboard data */
-	      hGlobal = GetClipboardData (CF_TEXT);
-	    }
-	  if (!hGlobal)
-	    {
-	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
-		      "GetClipboardData () failed: %08x\n",
-		      GetLastError ());
-
-	      /* Abort */
-	      fAbort = TRUE;
-	      goto winClipboardFlushXEvents_SelectionRequest_Done;
-	    }
-	  pszGlobalData = (char *) GlobalLock (hGlobal);
-
-	  /* Convert the Unicode string to UTF8 (MBCS) */
-	  if (fUseUnicode)
-	    {
-	      iConvertDataLen = WideCharToMultiByte (CP_UTF8,
-						     0,
-						     (LPCWSTR)pszGlobalData,
-						     -1,
-						     NULL,
-						     0,
-						     NULL,
-						     NULL);
-	      /* NOTE: iConvertDataLen includes space for null terminator */
-	      pszConvertData = (char *) malloc (iConvertDataLen);
-	      WideCharToMultiByte (CP_UTF8,
-				   0,
-				   (LPCWSTR)pszGlobalData,
-				   -1,
-				   pszConvertData,
-				   iConvertDataLen,
-				   NULL,
-				   NULL);
-	    }
-	  else
-	    {
-	      pszConvertData = strdup (pszGlobalData);
-	      iConvertDataLen = strlen (pszConvertData) + 1;
-	    }
-
-	  /* Convert DOS string to UNIX string */
-	  winClipboardDOStoUNIX (pszConvertData, strlen (pszConvertData));
-
-	  /* Setup our text list */
-	  pszTextList[0] = pszConvertData;
-	  pszTextList[1] = NULL;
-
-	  /* Initialize the text property */
-	  xtpText.value = NULL;
-
-	  /* Create the text property from the text list */
-	  if (fUseUnicode)
-	    {
-#ifdef X_HAVE_UTF8_STRING
-	      iReturn = Xutf8TextListToTextProperty (pDisplay,
-						     pszTextList,
-						     1,
-						     xiccesStyle,
-						     &xtpText);
-#endif
-	    }
-	  else
-	    {
-	      iReturn = XmbTextListToTextProperty (pDisplay,
-						   pszTextList,
-						   1,
-						   xiccesStyle,
-						   &xtpText);
-	    }
-	  if (iReturn == XNoMemory || iReturn == XLocaleNotSupported)
-	    {
-	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
-		      "X*TextListToTextProperty failed: %d\n",
-		      iReturn);
-
-	      /* Abort */
-	      fAbort = TRUE;
-	      goto winClipboardFlushXEvents_SelectionRequest_Done;
-	    }
-	  
-	  /* Free the converted string */
-	  free (pszConvertData);
-	  pszConvertData = NULL;
-
-	  /* Copy the clipboard text to the requesting window */
-	  iReturn = XChangeProperty (pDisplay,
-				     event.xselectionrequest.requestor,
-				     event.xselectionrequest.property,
-				     event.xselectionrequest.target,
-				     8,
-				     PropModeReplace,
-				     xtpText.value,
-				     xtpText.nitems);
-	  if (iReturn == BadAlloc || iReturn == BadAtom
-	      || iReturn == BadMatch || iReturn == BadValue
-	      || iReturn == BadWindow)
-	    {
-	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
-		      "XChangeProperty failed: %d\n",
-		      iReturn);
-
-	      /* Abort */
-	      fAbort = TRUE;
-	      goto winClipboardFlushXEvents_SelectionRequest_Done;
-	    }
-
-	  /* Release the clipboard data */
-	  GlobalUnlock (hGlobal);
-	  pszGlobalData = NULL;
-
-	  /* Clean up */
-	  XFree (xtpText.value);
-	  xtpText.value = NULL;
-
-	  /* Setup selection notify event */
-	  eventSelection.type = SelectionNotify;
-	  eventSelection.send_event = True;
-	  eventSelection.display = pDisplay;
-	  eventSelection.requestor = event.xselectionrequest.requestor;
-	  eventSelection.selection = event.xselectionrequest.selection;
-	  eventSelection.target = event.xselectionrequest.target;
-	  eventSelection.property = event.xselectionrequest.property;
-	  eventSelection.time = event.xselectionrequest.time;
-
-	  /* Notify the requesting window that the operation has completed */
-	  iReturn = XSendEvent (pDisplay,
-				eventSelection.requestor,
-				False,
-				0L,
-				(XEvent *) &eventSelection);
-	  if (iReturn == BadValue || iReturn == BadWindow)
-	    {
-	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
-		      "XSendEvent () failed\n");
-
-	      /* Abort */
-	      fAbort = TRUE;
-	      goto winClipboardFlushXEvents_SelectionRequest_Done;
-	    }
-
-	winClipboardFlushXEvents_SelectionRequest_Done:
-	  /* Free allocated resources */
-	  if (xtpText.value)
-	    XFree (xtpText.value);
-	  if (pszConvertData)
-	    free (pszConvertData);
-	  if (hGlobal && pszGlobalData)
-	    GlobalUnlock (hGlobal);
-	  
-	  /*
-	   * Send a SelectionNotify event to the requesting
-	   * client when we abort.
-	   */
-	  if (fAbort)
-	    {
-	      /* Setup selection notify event */
-	      eventSelection.type = SelectionNotify;
-	      eventSelection.send_event = True;
-	      eventSelection.display = pDisplay;
-	      eventSelection.requestor = event.xselectionrequest.requestor;
-	      eventSelection.selection = event.xselectionrequest.selection;
-	      eventSelection.target = event.xselectionrequest.target;
-	      eventSelection.property = None;
-	      eventSelection.time = event.xselectionrequest.time;
-
-	      /* Notify the requesting window that the operation is complete */
-	      iReturn = XSendEvent (pDisplay,
-				    eventSelection.requestor,
-				    False,
-				    0L,
-				    (XEvent *) &eventSelection);
-	      if (iReturn == BadValue || iReturn == BadWindow)
-		{
-		  /*
-		   * Should not be a problem if XSendEvent fails because
-		   * the client may simply have exited.
-		   */
-		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
-			  "XSendEvent () failed for abort event.\n");
-		}
-	    }
-
-	  /* Close clipboard if it was opened */
-	  if (fCloseClipboard)
-	    CloseClipboard ();
-	  break;
-
-
-	  /*
-	   * SelectionNotify
-	   */ 
-
-	case SelectionNotify:
-#if 0
-	  ErrorF ("winClipboardFlushXEvents - SelectionNotify\n");
-	  {
-	    char		*pszAtomName;
-	    
-	    pszAtomName = XGetAtomName (pDisplay,
-					event.xselection.selection);
-
-	    ErrorF ("winClipboardFlushXEvents - SelectionNotify - ATOM: %s\n",
-		    pszAtomName);
-	    
-	    XFree (pszAtomName);
-	  }
-#endif
-
-
-	  /*
-	   * Request conversion of UTF8 and CompoundText targets.
-	   */
-	  if (event.xselection.property == None)
-	    {
-	      if (event.xselection.target == XA_STRING)
-		{
-#if 0
-		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
-			  "XA_STRING\n");
-#endif
-		  return WIN_XEVENTS_CONVERT;
-		}
-	      else if (event.xselection.target == atomUTF8String)
-		{
-#if 0
-		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
-			  "Requesting conversion of UTF8 target.\n");
-#endif
-		  iReturn = XConvertSelection (pDisplay,
-					       event.xselection.selection,
-					       XA_STRING,
-					       atomLocalProperty,
-					       iWindow,
-					       CurrentTime);
-		  if (iReturn != Success)
-		    {
-		      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
-			      "XConvertSelection () failed for UTF8String, "
-			      "aborting: %d\n",
-			      iReturn);
-		      break;
-		    }
-
-		  /* Process the ConvertSelection event */
-		  XFlush (pDisplay);
-		  return WIN_XEVENTS_CONVERT;
-		}
-#ifdef X_HAVE_UTF8_STRING
-	      else if (event.xselection.target == atomCompoundText)
-		{
-#if 0
-		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
-			  "Requesting conversion of CompoundText target.\n");
-#endif
-		  iReturn = XConvertSelection (pDisplay,
-					       event.xselection.selection,
-					       atomUTF8String,
-					       atomLocalProperty,
-					       iWindow,
-					       CurrentTime);
-		  if (iReturn != Success)
-		    {
-		      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
-			      "XConvertSelection () failed for CompoundText, "
-			      "aborting: %d\n",
-			      iReturn);
-		      break;
-		    }
-
-		  /* Process the ConvertSelection event */
-		  XFlush (pDisplay);
-		  return WIN_XEVENTS_CONVERT;
-		}
-#endif
-	      else
-		{
-		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
-			  "Unknown format.  Cannot request conversion, "
-			  "aborting.\n");
-		  break;
-		}
-	    }
-
-	  /* Retrieve the size of the stored data */
-	  iReturn = XGetWindowProperty (pDisplay,
-					iWindow,
-					atomLocalProperty,
-					0,
-					0, /* Don't get data, just size */
-					False,
-					AnyPropertyType,
-					&xtpText.encoding,
-					&xtpText.format,
-					&xtpText.nitems,
-					&ulReturnBytesLeft,
-					&xtpText.value);
-	  if (iReturn != Success)
-	    {
-	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
-		      "XGetWindowProperty () failed, aborting: %d\n",
-		      iReturn);
-	      break;
-	    }
-
-#if 0
-	  ErrorF ("SelectionNotify - returned data %d left %d\n",
-		  xtpText.nitems, ulReturnBytesLeft);
-#endif
-
-	  /* Request the selection data */
-	  iReturn = XGetWindowProperty (pDisplay,
-					iWindow,
-					atomLocalProperty,
-					0,
-					ulReturnBytesLeft,
-					False,
-					AnyPropertyType,
-					&xtpText.encoding,
-					&xtpText.format,
-					&xtpText.nitems,
-					&ulReturnBytesLeft,
-					&xtpText.value);
-	  if (iReturn != Success)
-	    {
-	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
-		      "XGetWindowProperty () failed, aborting: %d\n",
-		      iReturn);
-	      break;
-	    }
-
-#if 0
-	    {
-	      char		*pszAtomName = NULL;
-
-	      ErrorF ("SelectionNotify - returned data %d left %d\n",
-		      xtpText.nitems, ulReturnBytesLeft);
-	      
-	      pszAtomName = XGetAtomName(pDisplay, xtpText.encoding);
-	      ErrorF ("Notify atom name %s\n", pszAtomName);
-	      XFree (pszAtomName);
-	      pszAtomName = NULL;
-	    }
-#endif
-
-	  if (fUseUnicode)
-	    {
-#ifdef X_HAVE_UTF8_STRING
-	      /* Convert the text property to a text list */
-	      iReturn = Xutf8TextPropertyToTextList (pDisplay,
-						     &xtpText,
-						     &ppszTextList,
-						     &iCount);
-#endif
-	    }
-	  else
-	    {
-	      iReturn = XmbTextPropertyToTextList (pDisplay,
-						   &xtpText,
-						   &ppszTextList,
-						   &iCount);
-	    }
-	  if (iReturn == Success || iReturn > 0)
-	    {
-	      /* Conversion succeeded or some unconvertible characters */
-	      if (ppszTextList != NULL)
-		{
-		  for (i = 0; i < iCount; i++)
-		    {
-		      iReturnDataLen += strlen(ppszTextList[i]);
-		    }
-		  pszReturnData = malloc (iReturnDataLen + 1);
-		  pszReturnData[0] = '\0';
-		  for (i = 0; i < iCount; i++)
-		    {
-		      strcat (pszReturnData, ppszTextList[i]);
-		    }
-		}
-	      else
-		{
-		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
-			  "X*TextPropertyToTextList list_return is NULL.\n");
-		  pszReturnData = malloc (1);
-		  pszReturnData[0] = '\0';
-		}
-	    }
-	  else
-	    {
-	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
-		      "X*TextPropertyToTextList returned: ");
-	      switch (iReturn)
-		{
-		case XNoMemory:
-		  ErrorF ("XNoMemory\n");
-		  break;
-		case XConverterNotFound:
-		  ErrorF ("XConverterNotFound\n");
-		  break;
-		default:
-		  ErrorF ("%d", iReturn);
-		  break;
-		}
-	      pszReturnData = malloc (1);
-	      pszReturnData[0] = '\0';
-	    }
-
-	  /* Free the data returned from XGetWindowProperty */
-	  if (ppszTextList)
-	    XFreeStringList (ppszTextList);
-	  ppszTextList = NULL;
-	  XFree (xtpText.value);
-	  xtpText.value = NULL;
-
-	  /* Convert the X clipboard string to DOS format */
-	  winClipboardUNIXtoDOS (&pszReturnData, strlen (pszReturnData));
-
-	  if (fUseUnicode)
-	    {
-	      /* Find out how much space needed to convert MBCS to Unicode */
-	      iUnicodeLen = MultiByteToWideChar (CP_UTF8,
-						 0,
-						 pszReturnData,
-						 -1,
-						 NULL,
-						 0);
-
-	      /* Allocate memory for the Unicode string */
-	      pwszUnicodeStr
-		= (wchar_t*) malloc (sizeof (wchar_t) * (iUnicodeLen + 1));
-	      if (!pwszUnicodeStr)
-		{
-		  ErrorF ("winClipboardFlushXEvents - SelectionNotify "
-			  "malloc failed for pwszUnicodeStr, aborting.\n");
-
-		  /* Abort */
-		  fAbort = TRUE;
-		  goto winClipboardFlushXEvents_SelectionNotify_Done;
-		}
-
-	      /* Do the actual conversion */
-	      MultiByteToWideChar (CP_UTF8,
-				   0,
-				   pszReturnData,
-				   -1,
-				   pwszUnicodeStr,
-				   iUnicodeLen);
-	      
-	      /* Allocate global memory for the X clipboard data */
-	      hGlobal = GlobalAlloc (GMEM_MOVEABLE,
-				     sizeof (wchar_t) * (iUnicodeLen + 1));
-	    }
-	  else
-	    {
-	      pszConvertData = strdup (pszReturnData);
-	      iConvertDataLen = strlen (pszConvertData) + 1;
-
-	      /* Allocate global memory for the X clipboard data */
-	      hGlobal = GlobalAlloc (GMEM_MOVEABLE, iConvertDataLen);
-	    }
-
-	  /* Check that global memory was allocated */
-	  if (!hGlobal)
-	    {
-	      ErrorF ("winClipboardFlushXEvents - SelectionNotify "
-		      "GlobalAlloc failed, aborting: %ld\n",
-		      GetLastError ());
-
-	      /* Abort */
-	      fAbort = TRUE;
-	      goto winClipboardFlushXEvents_SelectionNotify_Done;
-	    }
-
-	  /* Obtain a pointer to the global memory */
-	  pszGlobalData = GlobalLock (hGlobal);
-	  if (pszGlobalData == NULL)
-	    {
-	      ErrorF ("winClipboardFlushXEvents - Could not lock global "
-		      "memory for clipboard transfer\n");
-
-	      /* Abort */
-	      fAbort = TRUE;
-	      goto winClipboardFlushXEvents_SelectionNotify_Done;
-	    }
-
-	  /* Copy the returned string into the global memory */
-	  if (fUseUnicode)
-	    {
-	      memcpy (pszGlobalData,
-		      pwszUnicodeStr,
-		      sizeof (wchar_t) * (iUnicodeLen + 1));
-	      free (pwszUnicodeStr);
-	      pwszUnicodeStr = NULL;
-	    }
-	  else
-	    {
-	      strcpy (pszGlobalData, pszConvertData);
-	      free (pszConvertData);
-	      pszConvertData = NULL;
-	    }
-
-	  /* Release the pointer to the global memory */
-	  GlobalUnlock (hGlobal);
-	  pszGlobalData = NULL;
-
-	  /* Push the selection data to the Windows clipboard */
-	  if (fUseUnicode)
-	    SetClipboardData (CF_UNICODETEXT, hGlobal);
-	  else
-	    SetClipboardData (CF_TEXT, hGlobal);
-
-	  /* Flag that SetClipboardData has been called */
-	  fSetClipboardData = FALSE;
-
-	  /*
-	   * NOTE: Do not try to free pszGlobalData, it is owned by
-	   * Windows after the call to SetClipboardData ().
-	   */
-
-	winClipboardFlushXEvents_SelectionNotify_Done:
-	  /* Free allocated resources */
-	  if (ppszTextList)
-	    XFreeStringList (ppszTextList);
-	  if (xtpText.value)
-	    XFree (xtpText.value);
-	  if (pszConvertData)
-	    free (pszConvertData);
-	  if (pwszUnicodeStr)
-	    free (pwszUnicodeStr);
-	  if (hGlobal && pszGlobalData)
-	    GlobalUnlock (hGlobal);
-	  if (fSetClipboardData && g_fUnicodeSupport)
-	    SetClipboardData (CF_UNICODETEXT, NULL);
-	  if (fSetClipboardData)
-	    SetClipboardData (CF_TEXT, NULL);
-	  return WIN_XEVENTS_NOTIFY;
-
-	default:
-	  break;
-	}
-    }
-
-  return WIN_XEVENTS_SUCCESS;
-}
diff --git a/hw/xwin/wincmap.c b/hw/xwin/wincmap.c
deleted file mode 100644
index 7ebe002..0000000
--- a/hw/xwin/wincmap.c
+++ /dev/null
@@ -1,674 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * Local prototypes
- */
-
-static int
-winListInstalledColormaps (ScreenPtr pScreen, Colormap *pmaps);
-
-static void
-winStoreColors (ColormapPtr pmap, int ndef, xColorItem *pdefs);
-
-static void
-winInstallColormap (ColormapPtr pmap);
-
-static void
-winUninstallColormap (ColormapPtr pmap);
-
-static void
-winResolveColor (unsigned short *pred,
-		 unsigned short *pgreen,
-		 unsigned short *pblue,
-		 VisualPtr	pVisual);
-
-static Bool
-winCreateColormap (ColormapPtr pmap);
-
-static void
-winDestroyColormap (ColormapPtr pmap);
-
-static Bool
-winGetPaletteDIB (ScreenPtr pScreen, ColormapPtr pcmap);
-
-static Bool
-winGetPaletteDD (ScreenPtr pScreen, ColormapPtr pcmap);
-
-
-/*
- * Set screen functions for colormaps
- */
-
-void
-winSetColormapFunctions (ScreenPtr pScreen)
-{
-  pScreen->CreateColormap = winCreateColormap;
-  pScreen->DestroyColormap = winDestroyColormap;
-  pScreen->InstallColormap = winInstallColormap;
-  pScreen->UninstallColormap = winUninstallColormap;
-  pScreen->ListInstalledColormaps = winListInstalledColormaps;
-  pScreen->StoreColors = winStoreColors;
-  pScreen->ResolveColor = winResolveColor;
-}
-
-
-/* See Porting Layer Definition - p. 30 */
-/*
- * Walk the list of installed colormaps, filling the pmaps list
- * with the resource ids of the installed maps, and return
- * a count of the total number of installed maps.
- */
-static int
-winListInstalledColormaps (ScreenPtr pScreen, Colormap *pmaps)
-{
-  winScreenPriv(pScreen);
-
-  /*
-   * There will only be one installed colormap, so we only need
-   * to return one id, and the count of installed maps will always
-   * be one.
-   */
-  *pmaps = pScreenPriv->pcmapInstalled->mid;
-  return 1;
-}
-
-
-/* See Porting Layer Definition - p. 30 */
-/* See Programming Windows - p. 663 */
-static void
-winInstallColormap (ColormapPtr pColormap)
-{
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  ColormapPtr		oldpmap = pScreenPriv->pcmapInstalled;
-
-#if CYGDEBUG
-  winDebug ("winInstallColormap\n");
-#endif
- 
-  /* Did the colormap actually change? */
-  if (pColormap != oldpmap)
-    {
-#if CYGDEBUG
-      winDebug ("winInstallColormap - Colormap has changed, attempt "
-	      "to install.\n");
-#endif
-      
-      /* Was there a previous colormap? */
-      if (oldpmap != (ColormapPtr) None)
-	{
-	  /* There was a previous colormap; tell clients it is gone */
-	  WalkTree (pColormap->pScreen, TellLostMap, (char *)&oldpmap->mid);
-	}
-      
-      /* Install new colormap */
-      pScreenPriv->pcmapInstalled = pColormap;
-      WalkTree (pColormap->pScreen, TellGainedMap, (char *)&pColormap->mid);
-      
-      /* Call the engine specific colormap install procedure */
-      if (!((*pScreenPriv->pwinInstallColormap) (pColormap)))
-	{
-	  winErrorFVerb (2, "winInstallColormap - Screen specific colormap install "
-		  "procedure failed.  Continuing, but colors may be "
-		  "messed up from now on.\n");
-	}
-    }
-
-  /* Save a pointer to the newly installed colormap */
-  pScreenPriv->pcmapInstalled = pColormap;
-}
-
-
-/* See Porting Layer Definition - p. 30 */
-static void
-winUninstallColormap (ColormapPtr pmap)
-{
-  winScreenPriv(pmap->pScreen);
-  ColormapPtr curpmap = pScreenPriv->pcmapInstalled;
-
-#if CYGDEBUG
-  winDebug ("winUninstallColormap\n");
-#endif
-
-  /* Is the colormap currently installed? */
-  if (pmap != curpmap)
-    {
-      /* Colormap not installed, nothing to do */
-      return;
-    }
-  
-  /* Clear the installed colormap flag */
-  pScreenPriv->pcmapInstalled = NULL;
-  
-  /*
-   * NOTE: The default colormap does not get "uninstalled" before
-   * it is destroyed.
-   */
-
-  /* Install the default cmap in place of the cmap to be uninstalled */
-  if (pmap->mid != pmap->pScreen->defColormap)
-    {
-      curpmap = (ColormapPtr) LookupIDByType(pmap->pScreen->defColormap,
-					     RT_COLORMAP);
-      (*pmap->pScreen->InstallColormap) (curpmap);
-    }
-}
-
-
-/* See Porting Layer Definition - p. 30 */
-static void
-winStoreColors (ColormapPtr pmap,
-		int ndef,
-		xColorItem *pdefs)
-{
-  ScreenPtr		pScreen = pmap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pmap);
-  int			i;
-  unsigned short	nRed, nGreen, nBlue;
-
-#if CYGDEBUG
-  if (ndef != 1)
-    winDebug ("winStoreColors - ndef: %d\n",
-	    ndef);
-#endif
-
-  /* Save the new colors in the colormap privates */
-  for (i = 0; i < ndef; ++i)
-    {
-      /* Adjust the colors from the X color spec to the Windows color spec */
-      nRed = pdefs[i].red >> 8;
-      nGreen = pdefs[i].green >> 8;
-      nBlue = pdefs[i].blue >> 8;
-
-      /* Copy the colors to a palette entry table */
-      pCmapPriv->peColors[pdefs[0].pixel + i].peRed = nRed;
-      pCmapPriv->peColors[pdefs[0].pixel + i].peGreen = nGreen;
-      pCmapPriv->peColors[pdefs[0].pixel + i].peBlue = nBlue;
-      
-      /* Copy the colors to a RGBQUAD table */
-      pCmapPriv->rgbColors[pdefs[0].pixel + i].rgbRed = nRed;
-      pCmapPriv->rgbColors[pdefs[0].pixel + i].rgbGreen = nGreen;
-      pCmapPriv->rgbColors[pdefs[0].pixel + i].rgbBlue = nBlue;
-
-#if CYGDEBUG
-      winDebug ("winStoreColors - nRed %d nGreen %d nBlue %d\n",
-	      nRed, nGreen, nBlue);
-#endif
-    }
-
-  /* Call the engine specific store colors procedure */
-  if (!((pScreenPriv->pwinStoreColors) (pmap, ndef, pdefs)))
-    {
-      winErrorFVerb (2, "winStoreColors - Engine cpecific color storage procedure "
-	      "failed.  Continuing, but colors may be messed up from now "
-	      "on.\n");
-    }
-}
-
-
-/* See Porting Layer Definition - p. 30 */
-static void
-winResolveColor (unsigned short *pred,
-		 unsigned short *pgreen,
-		 unsigned short *pblue,
-		 VisualPtr	pVisual)
-{
-#if CYGDEBUG
-  winDebug ("winResolveColor ()\n");
-#endif
-
-  miResolveColor (pred, pgreen, pblue, pVisual);
-}
-
-
-/* See Porting Layer Definition - p. 29 */
-static Bool
-winCreateColormap (ColormapPtr pmap)
-{
-  winPrivCmapPtr	pCmapPriv = NULL;
-  ScreenPtr		pScreen = pmap->pScreen;
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winDebug ("winCreateColormap\n");
-#endif
-
-  /* Allocate colormap privates */
-  if (!winAllocateCmapPrivates (pmap))
-    {
-      ErrorF ("winCreateColorma - Couldn't allocate cmap privates\n");
-      return FALSE;
-    }
-
-  /* Get a pointer to the newly allocated privates */
-  pCmapPriv = winGetCmapPriv (pmap);
-
-  /*
-   * FIXME: This is some evil hackery to help in handling some X clients
-   * that expect the top pixel to be white.  This "help" only lasts until
-   * some client overwrites the top colormap entry.
-   * 
-   * We don't want to actually allocate the top entry, as that causes
-   * problems with X clients that need 7 planes (128 colors) in the default
-   * colormap, such as Magic 7.1.
-   */
-  pCmapPriv->rgbColors[WIN_NUM_PALETTE_ENTRIES - 1].rgbRed = 255;
-  pCmapPriv->rgbColors[WIN_NUM_PALETTE_ENTRIES - 1].rgbGreen = 255;
-  pCmapPriv->rgbColors[WIN_NUM_PALETTE_ENTRIES - 1].rgbBlue = 255;
-  pCmapPriv->peColors[WIN_NUM_PALETTE_ENTRIES - 1].peRed = 255;
-  pCmapPriv->peColors[WIN_NUM_PALETTE_ENTRIES - 1].peGreen = 255;
-  pCmapPriv->peColors[WIN_NUM_PALETTE_ENTRIES - 1].peBlue = 255;
-
-  /* Call the engine specific colormap initialization procedure */
-  if (!((*pScreenPriv->pwinCreateColormap) (pmap)))
-    {
-      ErrorF ("winCreateColormap - Engine specific colormap creation "
-	      "procedure failed.  Aborting.\n");
-      return FALSE;
-    }
-
-  return TRUE;
-}
-
-
-/* See Porting Layer Definition - p. 29, 30 */
-static void
-winDestroyColormap (ColormapPtr pColormap)
-{
-  winScreenPriv(pColormap->pScreen);
-  winCmapPriv(pColormap);
-
-  /* Call the engine specific colormap destruction procedure */
-  if (!((*pScreenPriv->pwinDestroyColormap) (pColormap)))
-    {
-      winErrorFVerb (2, "winDestroyColormap - Engine specific colormap destruction "
-	      "procedure failed.  Continuing, but it is possible that memory "
-	      "was leaked, or that colors will be messed up from now on.\n");
-    }
-
-  /* Free the colormap privates */
-  free (pCmapPriv);
-  winSetCmapPriv (pColormap, NULL);
-
-#if CYGDEBUG
-  winDebug ("winDestroyColormap - Returning\n");
-#endif
-}
-
-
-/*
- * Internal function to load the palette used by the Shadow DIB
- */
-
-static Bool
-winGetPaletteDIB (ScreenPtr pScreen, ColormapPtr pcmap)
-{
-  winScreenPriv(pScreen);
-  int			i;
-  Pixel			pixel; /* Pixel == CARD32 */
-  CARD16		nRed, nGreen, nBlue; /* CARD16 == unsigned short */
-  UINT			uiColorsRetrieved = 0;
-  RGBQUAD		rgbColors[WIN_NUM_PALETTE_ENTRIES];
-      
-  /* Get the color table for the screen */
-  uiColorsRetrieved = GetDIBColorTable (pScreenPriv->hdcScreen,
-					0,
-					WIN_NUM_PALETTE_ENTRIES,
-					rgbColors);
-  if (uiColorsRetrieved == 0)
-    {
-      ErrorF ("winGetPaletteDIB - Could not retrieve screen color table\n");
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winGetPaletteDIB - Retrieved %d colors from DIB\n",
-	  uiColorsRetrieved);
-#endif
-
-  /* Set the DIB color table to the default screen palette */
-  if (SetDIBColorTable (pScreenPriv->hdcShadow,
-			0,
-			uiColorsRetrieved,
-			rgbColors) == 0)
-    {
-      ErrorF ("winGetPaletteDIB - SetDIBColorTable () failed\n");
-      return FALSE;
-    }
-
-  /* Alloc each color in the DIB color table */
-  for (i = 0; i < uiColorsRetrieved; ++i)
-    {
-      pixel = i;
-
-      /* Extract the color values for current palette entry */
-      nRed = rgbColors[i].rgbRed << 8;
-      nGreen = rgbColors[i].rgbGreen << 8;
-      nBlue = rgbColors[i].rgbBlue << 8;
-
-#if CYGDEBUG
-      winDebug ("winGetPaletteDIB - Allocating a color: %d; "
-	      "%d %d %d\n",
-	      pixel, nRed, nGreen, nBlue);
-#endif
-
-      /* Allocate a entry in the X colormap */
-      if (AllocColor (pcmap,
-		      &nRed,
-		      &nGreen,
-		      &nBlue,
-		      &pixel,
-		      0) != Success)
-	{
-	  ErrorF ("winGetPaletteDIB - AllocColor () failed, pixel %d\n",
-		  i);
-	  return FALSE;
-	}
-
-      if (i != pixel
-	  || nRed != rgbColors[i].rgbRed 
-	  || nGreen != rgbColors[i].rgbGreen
-	  || nBlue != rgbColors[i].rgbBlue)
-	{
-	  winDebug ("winGetPaletteDIB - Got: %d; "
-		  "%d %d %d\n",
-		  (int) pixel, nRed, nGreen, nBlue);
-	}
-	  
-      /* FIXME: Not sure that this bit is needed at all */
-      pcmap->red[i].co.local.red = nRed;
-      pcmap->red[i].co.local.green = nGreen;
-      pcmap->red[i].co.local.blue = nBlue;
-    }
-
-  /* System is using a colormap */
-  /* Set the black and white pixel indices */
-  pScreen->whitePixel = uiColorsRetrieved - 1;
-  pScreen->blackPixel = 0;
-
-  return TRUE;
-}
-
-
-/*
- * Internal function to load the standard system palette being used by DD
- */
-
-static Bool
-winGetPaletteDD (ScreenPtr pScreen, ColormapPtr pcmap)
-{
-  int			i;
-  Pixel			pixel; /* Pixel == CARD32 */
-  CARD16		nRed, nGreen, nBlue; /* CARD16 == unsigned short */
-  UINT			uiSystemPaletteEntries;
-  LPPALETTEENTRY	ppeColors = NULL;
-  HDC			hdc = NULL;
-
-  /* Get a DC to obtain the default palette */
-  hdc = GetDC (NULL);
-  if (hdc == NULL)
-    {
-      ErrorF ("winGetPaletteDD - Couldn't get a DC\n");
-      return FALSE;
-    }
-
-  /* Get the number of entries in the system palette */
-  uiSystemPaletteEntries = GetSystemPaletteEntries (hdc,
-						    0, 0, NULL);
-  if (uiSystemPaletteEntries == 0)
-    {
-      ErrorF ("winGetPaletteDD - Unable to determine number of "
-	      "system palette entries\n");
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winGetPaletteDD - uiSystemPaletteEntries %d\n",
-	  uiSystemPaletteEntries);
-#endif
-  
-  /* Allocate palette entries structure */
-  ppeColors = malloc (uiSystemPaletteEntries * sizeof (PALETTEENTRY));
-  if (ppeColors == NULL)
-    {
-      ErrorF ("winGetPaletteDD - malloc () for colormap failed\n");
-      return FALSE;
-    }
-
-  /* Get system palette entries */
-  GetSystemPaletteEntries (hdc,
-			   0, uiSystemPaletteEntries, ppeColors);
-
-  /* Allocate an X colormap entry for every system palette entry */
-  for (i = 0; i < uiSystemPaletteEntries; ++i)
-    {
-      pixel = i;
-
-      /* Extract the color values for current palette entry */
-      nRed = ppeColors[i].peRed << 8;
-      nGreen = ppeColors[i].peGreen << 8;
-      nBlue = ppeColors[i].peBlue << 8;
-#if CYGDEBUG
-      winDebug ("winGetPaletteDD - Allocating a color: %d; "
-	      "%d %d %d\n",
-	      pixel, nRed, nGreen, nBlue);
-#endif
-      if (AllocColor (pcmap,
-		      &nRed,
-		      &nGreen,
-		      &nBlue,
-		      &pixel,
-		      0) != Success)
-	{
-	  ErrorF ("winGetPaletteDD - AllocColor () failed, pixel %d\n",
-		  i);
-	  free (ppeColors);
-	  ppeColors = NULL;
-	  return FALSE;
-	}
-
-      pcmap->red[i].co.local.red = nRed;
-      pcmap->red[i].co.local.green = nGreen;
-      pcmap->red[i].co.local.blue = nBlue;
-    }
-
-  /* System is using a colormap */
-  /* Set the black and white pixel indices */
-  pScreen->whitePixel = uiSystemPaletteEntries - 1;
-  pScreen->blackPixel = 0;
-
-  /* Free colormap */
-  if (ppeColors != NULL)
-    {
-      free (ppeColors);
-      ppeColors = NULL;
-    }
-
-  /* Free the DC */
-  if (hdc != NULL)
-    {
-      ReleaseDC (NULL, hdc);
-      hdc = NULL;
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Install the standard fb colormap, or the GDI colormap,
- * depending on the current screen depth.
- */
-
-Bool
-winCreateDefColormap (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  unsigned short	zero = 0, ones = 0xFFFF;
-  VisualPtr		pVisual = pScreenPriv->pRootVisual;
-  ColormapPtr		pcmap = NULL;
-  Pixel			wp, bp;
-
-#if CYGDEBUG
-  winDebug ("winCreateDefColormap\n");
-#endif
-
-  /* Use standard fb colormaps for non palettized color modes */
-  if (pScreenInfo->dwBPP > 8)
-    {
-      winDebug ("winCreateDefColormap - Deferring to " \
-	      "fbCreateDefColormap ()\n");
-      return fbCreateDefColormap (pScreen);
-    }
-
-  /*
-   *  AllocAll for non-Dynamic visual classes,
-   *  AllocNone for Dynamic visual classes.
-   */
-
-  /*
-   * Dynamic visual classes allow the colors of the color map
-   * to be changed by clients.
-   */
-
-#if CYGDEBUG
-  winDebug ("winCreateDefColormap - defColormap: %d\n",
-	  pScreen->defColormap);
-#endif
-
-  /* Allocate an X colormap, owned by client 0 */
-  if (CreateColormap (pScreen->defColormap, 
-		      pScreen,
-		      pVisual,
-		      &pcmap,
-		      (pVisual->class & DynamicClass) ? AllocNone : AllocAll,
-		      0) != Success)
-    {
-      ErrorF ("winCreateDefColormap - CreateColormap failed\n");
-      return FALSE;
-    }
-  if (pcmap == NULL)
-    {
-      ErrorF ("winCreateDefColormap - Colormap could not be created\n");
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winCreateDefColormap - Created a colormap\n");
-#endif
-
-  /* Branch on the visual class */
-  if (!(pVisual->class & DynamicClass))
-    {
-      /* Branch on engine type */
-      if (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_GDI)
-	{
-	  /* Load the colors being used by the Shadow DIB */
-	  if (!winGetPaletteDIB (pScreen, pcmap))
-	    {
-	      ErrorF ("winCreateDefColormap - Couldn't get DIB colors\n");
-	      return FALSE;
-	    }
-	}
-      else
-	{
-	  /* Load the colors from the default system palette */
-	  if (!winGetPaletteDD (pScreen, pcmap))
-	    {
-	      ErrorF ("winCreateDefColormap - Couldn't get colors "
-		      "for DD\n");
-	      return FALSE;
-	    }
-	}
-    }
-  else
-    {
-      wp = pScreen->whitePixel;
-      bp = pScreen->blackPixel;
-      
-      /* Allocate a black and white pixel */
-      if ((AllocColor (pcmap, &ones, &ones, &ones, &wp, 0) !=
-	   Success)
-	  ||
-	  (AllocColor (pcmap, &zero, &zero, &zero, &bp, 0) !=
-	   Success))
-	{
-	  ErrorF ("winCreateDefColormap - Couldn't allocate bp or wp\n");
-	  return FALSE;
-	}
-      
-      pScreen->whitePixel = wp;
-      pScreen->blackPixel = bp;
-
-#if 0
-      /* Have to reserve first 10 and last ten pixels in DirectDraw windowed */
-      if (pScreenInfo->dwEngine != WIN_SERVER_SHADOW_GDI)
-	{
-	  int		k;
-	  Pixel		p;
-
-	  for (k = 1; k < 10; ++k)
-	    {
-	      p = k;
-	      if (AllocColor (pcmap, &ones, &ones, &ones, &p, 0) != Success)
-		FatalError ("Foo!\n");
-	    }
-	  
-	  for (k = 245; k < 255; ++k)
-	    {
-	      p = k;
-	      if (AllocColor (pcmap, &zero, &zero, &zero, &p, 0) != Success)
-		FatalError ("Baz!\n");
-	    }
-	}
-#endif
-    }
-
-  /* Install the created colormap */
-  (*pScreen->InstallColormap)(pcmap);
-
-#if CYGDEBUG
-  winDebug ("winCreateDefColormap - Returning\n");
-#endif
-
-  return TRUE;
-}
diff --git a/hw/xwin/winconfig.c b/hw/xwin/winconfig.c
deleted file mode 100644
index 38966bf..0000000
--- a/hw/xwin/winconfig.c
+++ /dev/null
@@ -1,1150 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors: Alexander Gottwald	
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winconfig.h"
-#include "winmsg.h"
-#include "globals.h"
-
-#ifdef XKB
-#ifndef XKB_IN_SERVER
-#define XKB_IN_SERVER
-#endif
-#include <xkbsrv.h>
-#endif
-
-#ifdef XWIN_XF86CONFIG
-#ifndef CONFIGPATH
-#define CONFIGPATH  "%A," "%R," \
-                    "/etc/X11/%R," "%P/etc/X11/%R," \
-                    "%E," "%F," \
-                    "/etc/X11/%F," "%P/etc/X11/%F," \
-                    "/etc/X11/%X-%M," "/etc/X11/%X," "/etc/%X," \
-                    "%P/etc/X11/%X.%H," "%P/etc/X11/%X-%M," \
-                    "%P/etc/X11/%X," \
-                    "%P/lib/X11/%X.%H," "%P/lib/X11/%X-%M," \
-                    "%P/lib/X11/%X"
-#endif
-
-XF86ConfigPtr g_xf86configptr = NULL;
-#endif
-
-WinCmdlineRec g_cmdline = {
-#ifdef XWIN_XF86CONFIG
-  NULL,				/* configFile */
-#endif
-  NULL,				/* fontPath */
-#ifdef XWIN_XF86CONFIG
-  NULL,				/* keyboard */
-#endif
-#ifdef XKB
-  FALSE,			/* noXkbExtension */
-  NULL,				/* xkbMap */
-  NULL,             /* xkbRules */
-  NULL,             /* xkbModel */
-  NULL,             /* xkbLayout */
-  NULL,             /* xkbVariant */
-  NULL,             /* xkbOptions */
-#endif
-  NULL,				/* screenname */
-  NULL,				/* mousename */
-  FALSE,			/* emulate3Buttons */
-  0				/* emulate3Timeout */
-};
-
-winInfoRec g_winInfo = {
-  {				/* keyboard */
-   0,				/* leds */
-   500,				/* delay */
-   30				/* rate */
-#ifdef XKB
-   }
-  ,
-  {				/* xkb */
-   FALSE,			/* disable */
-   NULL,			/* rules */
-   NULL,			/* model */
-   NULL,			/* layout */
-   NULL,			/* variant */
-   NULL,			/* options */
-   NULL,			/* initialMap */
-   NULL,			/* keymap */
-   NULL,			/* types */
-   NULL,			/* compat */
-   NULL,			/* keycodes */
-   NULL,			/* symbols */
-   NULL				/* geometry */
-#endif
-   }
-  ,
-  {
-   FALSE,
-   50}
-};
-
-#define NULL_IF_EMPTY(x) (winNameCompare(x,"")?x:NULL)
-
-#ifdef XWIN_XF86CONFIG
-serverLayoutRec g_winConfigLayout;
-
-static Bool ParseOptionValue (int scrnIndex, pointer options,
-			      OptionInfoPtr p);
-static Bool configLayout (serverLayoutPtr, XF86ConfLayoutPtr, char *);
-static Bool configImpliedLayout (serverLayoutPtr, XF86ConfScreenPtr);
-static Bool GetBoolValue (OptionInfoPtr p, const char *s);
-
-
-Bool
-winReadConfigfile ()
-{
-  Bool		retval = TRUE;
-  const char	*filename;
-  MessageType	from = X_DEFAULT;
-  char		*xf86ConfigFile = NULL;
-
-  if (g_cmdline.configFile)
-    {
-      from = X_CMDLINE;
-      xf86ConfigFile = g_cmdline.configFile;
-    }
-
-  /* Parse config file into data structure */
-
-  filename = xf86openConfigFile (CONFIGPATH, xf86ConfigFile, PROJECTROOT);
-    
-  /* Hack for backward compatibility */
-  if (!filename && from == X_DEFAULT)
-    filename = xf86openConfigFile (CONFIGPATH, "XF86Config", PROJECTROOT);
-
-  if (filename)
-    {
-      winMsg (from, "Using config file: \"%s\"\n", filename);
-    }
-  else
-    {
-      winMsg (X_ERROR, "Unable to locate/open config file");
-      if (xf86ConfigFile)
-	ErrorF (": \"%s\"", xf86ConfigFile);
-      ErrorF ("\n");
-      return FALSE;
-    }
-  if ((g_xf86configptr = xf86readConfigFile ()) == NULL)
-    {
-      winMsg (X_ERROR, "Problem parsing the config file\n");
-      return FALSE;
-    }
-  xf86closeConfigFile ();
-
-  LogPrintMarkers();
-
-  /* set options from data structure */
-
-  if (g_xf86configptr->conf_layout_lst == NULL || g_cmdline.screenname != NULL)
-    {
-      if (g_cmdline.screenname == NULL)
-	{
-	  winMsg (X_WARNING,
-		  "No Layout section. Using the first Screen section.\n");
-	}
-      if (!configImpliedLayout (&g_winConfigLayout,
-				g_xf86configptr->conf_screen_lst))
-	{
-	  winMsg (X_ERROR, "Unable to determine the screen layout\n");
-	  return FALSE;
-	}
-    }
-  else
-    {
-      /* Check if layout is given in the config file */
-      if (g_xf86configptr->conf_flags != NULL)
-	{
-	  char *dfltlayout = NULL;
-	  pointer optlist = g_xf86configptr->conf_flags->flg_option_lst;
-
-	  if (optlist && winFindOption (optlist, "defaultserverlayout"))
-	    dfltlayout =
-	      winSetStrOption (optlist, "defaultserverlayout", NULL);
-
-	  if (!configLayout (&g_winConfigLayout,
-			     g_xf86configptr->conf_layout_lst,
-			     dfltlayout))
-	    {
-	      winMsg (X_ERROR, "Unable to determine the screen layout\n");
-	      return FALSE;
-	    }
-	}
-      else
-	{
-	  if (!configLayout (&g_winConfigLayout,
-			     g_xf86configptr->conf_layout_lst,
-			     NULL))
-	    {
-	      winMsg (X_ERROR, "Unable to determine the screen layout\n");
-	      return FALSE;
-	    }
-	}
-    }
-
-  /* setup special config files */
-  winConfigFiles ();
-  return retval;
-}
-#endif
-
-/* load layout definitions */
-#include "winlayouts.h"
-
-/* Set the keyboard configuration */
-Bool
-winConfigKeyboard (DeviceIntPtr pDevice)
-{
-#ifdef XKB
-  char                          layoutName[KL_NAMELENGTH];
-  static unsigned int           layoutNum = 0;
-  int                           keyboardType;
-#endif
-#ifdef XWIN_XF86CONFIG
-  XF86ConfInputPtr		kbd = NULL;
-  XF86ConfInputPtr		input_list = NULL;
-  MessageType			kbdfrom = X_CONFIG;
-#endif
-  MessageType			from = X_DEFAULT;
-  char				*s = NULL;
-
-  /* Setup defaults */
-#ifdef XKB
-  g_winInfo.xkb.disable = FALSE;
-# ifdef PC98 /* japanese */	/* not implemented */
-  g_winInfo.xkb.rules = "xfree98";
-  g_winInfo.xkb.model = "pc98";
-  g_winInfo.xkb.layout = "nex/jp";
-  g_winInfo.xkb.variant = NULL;
-  g_winInfo.xkb.options = NULL;
-# else
-  g_winInfo.xkb.rules = "xorg";
-  g_winInfo.xkb.model = "pc101";
-  g_winInfo.xkb.layout = "us";
-  g_winInfo.xkb.variant = NULL;
-  g_winInfo.xkb.options = NULL;
-# endif	/* PC98 */
-
-  /*
-   * Query the windows autorepeat settings and change the xserver defaults.   
-   * If XKB is disabled then windows handles the autorepeat and the special 
-   * treatment is not needed
-   */
-  {
-    int kbd_delay;
-    DWORD kbd_speed;
-    if (SystemParametersInfo(SPI_GETKEYBOARDDELAY, 0, &kbd_delay, 0) &&
-        SystemParametersInfo(SPI_GETKEYBOARDSPEED, 0, &kbd_speed, 0))
-      {
-        switch (kbd_delay) 
-          {
-            case 0:  g_winInfo.keyboard.delay = 250; break;
-            case 1:  g_winInfo.keyboard.delay = 500; break;
-            case 2:  g_winInfo.keyboard.delay = 750; break;
-            default:
-            case 3:  g_winInfo.keyboard.delay = 1000; break;
-          }
-        g_winInfo.keyboard.rate = (kbd_speed>0)?kbd_speed:1;
-        winMsgVerb(X_PROBED, 1, "Setting autorepeat to delay=%d, rate=%d\n",
-                g_winInfo.keyboard.delay, g_winInfo.keyboard.rate);
-      }
-  }
-  
-
-  keyboardType = GetKeyboardType (0);
-  if (keyboardType > 0 && GetKeyboardLayoutName (layoutName)) 
-  {
-    WinKBLayoutPtr	pLayout;
-    Bool                bfound = FALSE;
-
-    if (! layoutNum)
-      layoutNum = strtoul (layoutName, (char **)NULL, 16);
-    if ((layoutNum & 0xffff) == 0x411) {
-        /* The japanese layouts know a lot of different IMEs which all have
-	   different layout numbers set. Map them to a single entry. 
-	   Same might apply for chinese, korean and other symbol languages
-	   too */
-        layoutNum = (layoutNum & 0xffff);
-	if (keyboardType == 7)
-	  {
-	    /* Japanese layouts have problems with key event messages
-	       such as the lack of WM_KEYUP for Caps Lock key.
-	       Loading US layout fixes this problem. */
-	    if (LoadKeyboardLayout("00000409", KLF_ACTIVATE) != NULL)
-	      winMsg (X_INFO, "Loading US keyboard layout.\n");
-	    else
-	      winMsg (X_ERROR, "LoadKeyboardLaout failed.\n");
-	  }
-    }
-    winMsg (X_PROBED, "winConfigKeyboard - Layout: \"%s\" (%08x) \n", 
-            layoutName, layoutNum);
-
-    for (pLayout = winKBLayouts; pLayout->winlayout != -1; pLayout++)
-      {
-	if (pLayout->winlayout != layoutNum)
-	  continue;
-	if (pLayout->winkbtype > 0 && pLayout->winkbtype != keyboardType)
-	  continue;
-	
-        bfound = TRUE;
-	winMsg (X_PROBED,
-		"Using preset keyboard for \"%s\" (%x), type \"%d\"\n",
-		pLayout->layoutname, pLayout->winlayout, keyboardType);
-	
-	g_winInfo.xkb.model = pLayout->xkbmodel;
-	g_winInfo.xkb.layout = pLayout->xkblayout;
-	g_winInfo.xkb.variant = pLayout->xkbvariant;
-	g_winInfo.xkb.options = pLayout->xkboptions; 
-	break;
-      }
-    
-    if (!bfound)
-      {
-        HKEY                regkey = NULL;
-        const char          regtempl[] = 
-          "SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts\\";
-        char                *regpath;
-        char                lname[256];
-        DWORD               namesize = sizeof(lname);
-
-        regpath = malloc(sizeof(regtempl) + KL_NAMELENGTH + 1);
-        strcpy(regpath, regtempl);
-        strcat(regpath, layoutName);
-
-        if (!RegOpenKey(HKEY_LOCAL_MACHINE, regpath, &regkey) &&
-          !RegQueryValueEx(regkey, "Layout Text", 0, NULL, lname, &namesize))
-          {
-	    winMsg (X_ERROR,
-		"Keyboardlayout \"%s\" (%s) is unknown\n", lname, layoutName);
-          }
-
-	/* Close registry key */
-	if (regkey)
-	  RegCloseKey (regkey);
-        free(regpath);
-      }
-  }  
-  
-  g_winInfo.xkb.initialMap = NULL;
-  g_winInfo.xkb.keymap = NULL;
-  g_winInfo.xkb.types = NULL;
-  g_winInfo.xkb.compat = NULL;
-  g_winInfo.xkb.keycodes = NULL;
-  g_winInfo.xkb.symbols = NULL;
-  g_winInfo.xkb.geometry = NULL;
-#endif /* XKB */
-
-  /* parse the configuration */
-#ifdef XWIN_XF86CONFIG
-  if (g_cmdline.keyboard)
-    kbdfrom = X_CMDLINE;
-
-  /*
-   * Until the layout code is finished, I search for the keyboard 
-   * device and configure the server with it.
-   */
-
-  if (g_xf86configptr != NULL)
-    input_list = g_xf86configptr->conf_input_lst;
-
-  while (input_list != NULL)
-    {
-      if (winNameCompare (input_list->inp_driver, "keyboard") == 0)
-	{
-	  /* Check if device name matches requested name */
-	  if (g_cmdline.keyboard && winNameCompare (input_list->inp_identifier,
-						    g_cmdline.keyboard))
-	    continue;
-	  kbd = input_list;
-	}
-      input_list = input_list->list.next;
-    }
-
-  if (kbd != NULL)
-    {
-
-      if (kbd->inp_identifier)
-	winMsg (kbdfrom, "Using keyboard \"%s\" as primary keyboard\n",
-		kbd->inp_identifier);
-
-      if ((s = winSetStrOption(kbd->inp_option_lst, "AutoRepeat", NULL)))
-        {
-          if ((sscanf(s, "%ld %ld", &g_winInfo.keyboard.delay, 
-                      &g_winInfo.keyboard.rate) != 2) ||
-                  (g_winInfo.keyboard.delay < 1) || 
-                  (g_winInfo.keyboard.rate == 0) || 
-                  (1000 / g_winInfo.keyboard.rate) < 1) 
-            {
-              winErrorFVerb (2, "\"%s\" is not a valid AutoRepeat value", s);
-              xfree(s);
-              return FALSE;
-            }
-          xfree(s);
-          winMsg (X_CONFIG, "AutoRepeat: %ld %ld\n", 
-                  g_winInfo.keyboard.delay, g_winInfo.keyboard.rate);
-        }
-#endif
-      
-#ifdef XKB
-      from = X_DEFAULT;
-      if (g_cmdline.noXkbExtension)
-	{
-	  from = X_CMDLINE;
-	  g_winInfo.xkb.disable = TRUE;
-	}
-#ifdef XWIN_XF86CONFIG
-      else if (kbd->inp_option_lst)
-	{
-	  int b = winSetBoolOption (kbd->inp_option_lst, "XkbDisable", FALSE);
-	  if (b)
-	    {
-	      from = X_CONFIG;
-	      g_winInfo.xkb.disable = TRUE;
-	    }
-	}
-#endif
-      if (g_winInfo.xkb.disable)
-	{
-	  winMsg (from, "XkbExtension disabled\n");
-	}
-      else
-	{
-          s = NULL;  
-          if (g_cmdline.xkbRules)
-            {
-              s = g_cmdline.xkbRules;
-              from = X_CMDLINE;  
-            }
-#ifdef XWIN_XF86CONFIG
-          else 
-            {
-              s = winSetStrOption (kbd->inp_option_lst, "XkbRules", NULL);
-              from = X_CONFIG;  
-            }
-#endif
-          if (s)
-	    {
-	      g_winInfo.xkb.rules = NULL_IF_EMPTY (s);
-	      winMsg (from, "XKB: rules: \"%s\"\n", s);
-	    }
-          
-          s = NULL;
-          if (g_cmdline.xkbModel)
-            {
-              s = g_cmdline.xkbModel;
-              from = X_CMDLINE;
-            }
-#ifdef XWIN_XF86CONFIG
-          else
-            {
-              s = winSetStrOption (kbd->inp_option_lst, "XkbModel", NULL);
-              from = X_CONFIG;
-            }  
-#endif
-	  if (s)
-	    {
-	      g_winInfo.xkb.model = NULL_IF_EMPTY (s);
-	      winMsg (from, "XKB: model: \"%s\"\n", s);
-	    }
-
-          s = NULL;
-          if (g_cmdline.xkbLayout)
-            {
-              s = g_cmdline.xkbLayout;
-              from = X_CMDLINE;
-            }
-#ifdef XWIN_XF86CONFIG
-          else
-            {
-              s = winSetStrOption (kbd->inp_option_lst, "XkbLayout", NULL);
-              from = X_CONFIG;
-            }
-#endif
-          if (s)  
-	    {
-	      g_winInfo.xkb.layout = NULL_IF_EMPTY (s);
-	      winMsg (from, "XKB: layout: \"%s\"\n", s);
-	    }
-
-          s = NULL;
-          if (g_cmdline.xkbVariant)
-            {
-              s = g_cmdline.xkbVariant;
-              from = X_CMDLINE;
-            }
-#ifdef XWIN_XF86CONFIG
-          else
-            { 
-              s = winSetStrOption (kbd->inp_option_lst, "XkbVariant", NULL);
-              from = X_CONFIG;
-            }
-#endif
-	  if (s)
-	    {
-	      g_winInfo.xkb.variant = NULL_IF_EMPTY (s);
-	      winMsg (from, "XKB: variant: \"%s\"\n", s);
-	    }
-
-          s = NULL;
-          if (g_cmdline.xkbOptions)
-            {
-              s = g_cmdline.xkbOptions;
-              from = X_CMDLINE;
-            }
-#ifdef XWIN_XF86CONFIG
-          else
-            { 
-              s = winSetStrOption (kbd->inp_option_lst, "XkbOptions", NULL);
-              from = X_CONFIG;
-            }
-#endif
-          if (s)
-	    {
-	      g_winInfo.xkb.options = NULL_IF_EMPTY (s);
-	      winMsg (from, "XKB: options: \"%s\"\n", s);
-	    }
-
-#ifdef XWIN_XF86CONFIG
-	  from = X_CMDLINE;
-
-	  if ((s = winSetStrOption (kbd->inp_option_lst, "XkbKeymap", NULL)))
-	    {
-	      g_winInfo.xkb.keymap = NULL_IF_EMPTY (s);
-	      winMsg (X_CONFIG, "XKB: keymap: \"%s\" "
-		      " (overrides other XKB settings)\n", s);
-	    }
-
-	  if ((s = winSetStrOption (kbd->inp_option_lst, "XkbCompat", NULL)))
-	    {
-	      g_winInfo.xkb.compat = NULL_IF_EMPTY (s);
-	      winMsg (X_CONFIG, "XKB: compat: \"%s\"\n", s);
-	    }
-
-	  if ((s = winSetStrOption (kbd->inp_option_lst, "XkbTypes", NULL)))
-	    {
-	      g_winInfo.xkb.types = NULL_IF_EMPTY (s);
-	      winMsg (X_CONFIG, "XKB: types: \"%s\"\n", s);
-	    }
-
-	  if ((s =
-	       winSetStrOption (kbd->inp_option_lst, "XkbKeycodes", NULL)))
-	    {
-	      g_winInfo.xkb.keycodes = NULL_IF_EMPTY (s);
-	      winMsg (X_CONFIG, "XKB: keycodes: \"%s\"\n", s);
-	    }
-
-	  if ((s =
-	       winSetStrOption (kbd->inp_option_lst, "XkbGeometry", NULL)))
-	    {
-	      g_winInfo.xkb.geometry = NULL_IF_EMPTY (s);
-	      winMsg (X_CONFIG, "XKB: geometry: \"%s\"\n", s);
-	    }
-
-	  if ((s = winSetStrOption (kbd->inp_option_lst, "XkbSymbols", NULL)))
-	    {
-	      g_winInfo.xkb.symbols = NULL_IF_EMPTY (s);
-	      winMsg (X_CONFIG, "XKB: symbols: \"%s\"\n", s);
-	    }
-#endif
-#endif
-	}
-#ifdef XWIN_XF86CONFIG
-    }
-#endif
-
-  return TRUE;
-}
-
-
-#ifdef XWIN_XF86CONFIG
-Bool
-winConfigMouse (DeviceIntPtr pDevice)
-{
-  MessageType			mousefrom = X_CONFIG;
-
-  XF86ConfInputPtr		mouse = NULL;
-  XF86ConfInputPtr		input_list = NULL;
-
-  if (g_cmdline.mouse)
-    mousefrom = X_CMDLINE;
-
-  if (g_xf86configptr != NULL)
-    input_list = g_xf86configptr->conf_input_lst;
-
-  while (input_list != NULL)
-    {
-      if (winNameCompare (input_list->inp_driver, "mouse") == 0)
-	{
-	  /* Check if device name matches requested name */
-	  if (g_cmdline.mouse && winNameCompare (input_list->inp_identifier,
-						 g_cmdline.mouse))
-	    continue;
-	  mouse = input_list;
-	}
-      input_list = input_list->list.next;
-    }
-
-  if (mouse != NULL)
-    {
-      if (mouse->inp_identifier)
-	winMsg (mousefrom, "Using pointer \"%s\" as primary pointer\n",
-		mouse->inp_identifier);
-
-      g_winInfo.pointer.emulate3Buttons =
-	winSetBoolOption (mouse->inp_option_lst, "Emulate3Buttons", FALSE);
-      if (g_cmdline.emulate3buttons)
-	g_winInfo.pointer.emulate3Buttons = g_cmdline.emulate3buttons;
-
-      g_winInfo.pointer.emulate3Timeout =
-	winSetIntOption (mouse->inp_option_lst, "Emulate3Timeout", 50);
-      if (g_cmdline.emulate3timeout)
-	g_winInfo.pointer.emulate3Timeout = g_cmdline.emulate3timeout;
-    }
-  else
-    {
-      winMsg (X_ERROR, "No primary pointer configured\n");
-      winMsg (X_DEFAULT, "Using compiletime defaults for pointer\n");
-    }
-
-  return TRUE;
-}
-
-
-Bool
-winConfigFiles ()
-{
-  MessageType from;
-  XF86ConfFilesPtr filesptr = NULL;
-
-  /* set some shortcuts */
-  if (g_xf86configptr != NULL)
-    {
-      filesptr = g_xf86configptr->conf_files;
-    }
-
-
-  /* Fontpath */
-  from = X_DEFAULT;
-
-  if (g_cmdline.fontPath)
-    {
-      from = X_CMDLINE;
-      defaultFontPath = g_cmdline.fontPath;
-    }
-  else if (filesptr != NULL && filesptr->file_fontpath)
-    {
-      from = X_CONFIG;
-      defaultFontPath = xstrdup (filesptr->file_fontpath);
-    }
-  winMsg (from, "FontPath set to \"%s\"\n", defaultFontPath);
-
-  return TRUE;
-}
-#else
-Bool
-winConfigFiles ()
-{
-  MessageType from;
-
-  /* Fontpath */
-  if (g_cmdline.fontPath)
-    {
-      defaultFontPath = g_cmdline.fontPath;
-      winMsg (X_CMDLINE, "FontPath set to \"%s\"\n", defaultFontPath);
-    }
-
-  return TRUE;
-}
-#endif
-
-
-Bool
-winConfigOptions ()
-{
-  return TRUE;
-}
-
-
-Bool
-winConfigScreens ()
-{
-  return TRUE;
-}
-
-
-#ifdef XWIN_XF86CONFIG
-char *
-winSetStrOption (pointer optlist, const char *name, char *deflt)
-{
-  OptionInfoRec o;
-
-  o.name = name;
-  o.type = OPTV_STRING;
-  if (ParseOptionValue (-1, optlist, &o))
-    deflt = o.value.str;
-  if (deflt)
-    return xstrdup (deflt);
-  else
-    return NULL;
-}
-
-
-int
-winSetBoolOption (pointer optlist, const char *name, int deflt)
-{
-  OptionInfoRec o;
-
-  o.name = name;
-  o.type = OPTV_BOOLEAN;
-  if (ParseOptionValue (-1, optlist, &o))
-    deflt = o.value.bool;
-  return deflt;
-}
-
-
-int
-winSetIntOption (pointer optlist, const char *name, int deflt)
-{
-  OptionInfoRec o;
-
-  o.name = name;
-  o.type = OPTV_INTEGER;
-  if (ParseOptionValue (-1, optlist, &o))
-    deflt = o.value.num;
-  return deflt;
-}
-
-
-double
-winSetRealOption (pointer optlist, const char *name, double deflt)
-{
-  OptionInfoRec o;
-
-  o.name = name;
-  o.type = OPTV_REAL;
-  if (ParseOptionValue (-1, optlist, &o))
-    deflt = o.value.realnum;
-  return deflt;
-}
-#endif
-
-
-/*
- * Compare two strings for equality. This is caseinsensitive  and
- * The characters '_', ' ' (space) and '\t' (tab) are treated as 
- * not existing.
- */
-
-int
-winNameCompare (const char *s1, const char *s2)
-{
-  char c1, c2;
-
-  if (!s1 || *s1 == 0)
-    {
-      if (!s2 || *s2 == 0)
-	return 0;
-      else
-	return 1;
-    }
-
-  while (*s1 == '_' || *s1 == ' ' || *s1 == '\t')
-    s1++;
-  while (*s2 == '_' || *s2 == ' ' || *s2 == '\t')
-    s2++;
-
-  c1 = (isupper (*s1) ? tolower (*s1) : *s1);
-  c2 = (isupper (*s2) ? tolower (*s2) : *s2);
-
-  while (c1 == c2)
-    {
-      if (c1 == 0)
-	return 0;
-      s1++;
-      s2++;
-
-      while (*s1 == '_' || *s1 == ' ' || *s1 == '\t')
-	s1++;
-      while (*s2 == '_' || *s2 == ' ' || *s2 == '\t')
-	s2++;
-
-      c1 = (isupper (*s1) ? tolower (*s1) : *s1);
-      c2 = (isupper (*s2) ? tolower (*s2) : *s2);
-    }
-  return (c1 - c2);
-}
-
-
-#ifdef XWIN_XF86CONFIG
-/*
- * Find the named option in the list. 
- * @return the pointer to the option record, or NULL if not found.
- */
-
-XF86OptionPtr
-winFindOption (XF86OptionPtr list, const char *name)
-{
-  while (list)
-    {
-      if (winNameCompare (list->opt_name, name) == 0)
-	return list;
-      list = list->list.next;
-    }
-  return NULL;
-}
-
-
-/*
- * Find the Value of an named option.
- * @return The option value or NULL if not found.
- */
-
-char *
-winFindOptionValue (XF86OptionPtr list, const char *name)
-{
-  list = winFindOption (list, name);
-  if (list)
-    {
-      if (list->opt_val)
-	return (list->opt_val);
-      else
-	return "";
-    }
-  return (NULL);
-}
-
-
-/*
- * Parse the option.
- */
-
-static Bool
-ParseOptionValue (int scrnIndex, pointer options, OptionInfoPtr p)
-{
-  char *s, *end;
-
-  if ((s = winFindOptionValue (options, p->name)) != NULL)
-    {
-      switch (p->type)
-	{
-	case OPTV_INTEGER:
-	  if (*s == '\0')
-	    {
-	      winDrvMsg (scrnIndex, X_WARNING,
-			 "Option \"%s\" requires an integer value\n",
-			 p->name);
-	      p->found = FALSE;
-	    }
-	  else
-	    {
-	      p->value.num = strtoul (s, &end, 0);
-	      if (*end == '\0')
-		{
-		  p->found = TRUE;
-		}
-	      else
-		{
-		  winDrvMsg (scrnIndex, X_WARNING,
-			     "Option \"%s\" requires an integer value\n",
-			     p->name);
-		  p->found = FALSE;
-		}
-	    }
-	  break;
-	case OPTV_STRING:
-	  if (*s == '\0')
-	    {
-	      winDrvMsg (scrnIndex, X_WARNING,
-			 "Option \"%s\" requires an string value\n", p->name);
-	      p->found = FALSE;
-	    }
-	  else
-	    {
-	      p->value.str = s;
-	      p->found = TRUE;
-	    }
-	  break;
-	case OPTV_ANYSTR:
-	  p->value.str = s;
-	  p->found = TRUE;
-	  break;
-	case OPTV_REAL:
-	  if (*s == '\0')
-	    {
-	      winDrvMsg (scrnIndex, X_WARNING,
-			 "Option \"%s\" requires a floating point value\n",
-			 p->name);
-	      p->found = FALSE;
-	    }
-	  else
-	    {
-	      p->value.realnum = strtod (s, &end);
-	      if (*end == '\0')
-		{
-		  p->found = TRUE;
-		}
-	      else
-		{
-		  winDrvMsg (scrnIndex, X_WARNING,
-			     "Option \"%s\" requires a floating point value\n",
-			     p->name);
-		  p->found = FALSE;
-		}
-	    }
-	  break;
-	case OPTV_BOOLEAN:
-	  if (GetBoolValue (p, s))
-	    {
-	      p->found = TRUE;
-	    }
-	  else
-	    {
-	      winDrvMsg (scrnIndex, X_WARNING,
-			 "Option \"%s\" requires a boolean value\n", p->name);
-	      p->found = FALSE;
-	    }
-	  break;
-	case OPTV_FREQ:
-	  if (*s == '\0')
-	    {
-	      winDrvMsg (scrnIndex, X_WARNING,
-			 "Option \"%s\" requires a frequency value\n",
-			 p->name);
-	      p->found = FALSE;
-	    }
-	  else
-	    {
-	      double freq = strtod (s, &end);
-	      int units = 0;
-
-	      if (end != s)
-		{
-		  p->found = TRUE;
-		  if (!winNameCompare (end, "Hz"))
-		    units = 1;
-		  else if (!winNameCompare (end, "kHz") ||
-			   !winNameCompare (end, "k"))
-		    units = 1000;
-		  else if (!winNameCompare (end, "MHz") ||
-			   !winNameCompare (end, "M"))
-		    units = 1000000;
-		  else
-		    {
-		      winDrvMsg (scrnIndex, X_WARNING,
-				 "Option \"%s\" requires a frequency value\n",
-				 p->name);
-		      p->found = FALSE;
-		    }
-		  if (p->found)
-		    freq *= (double) units;
-		}
-	      else
-		{
-		  winDrvMsg (scrnIndex, X_WARNING,
-			     "Option \"%s\" requires a frequency value\n",
-			     p->name);
-		  p->found = FALSE;
-		}
-	      if (p->found)
-		{
-		  p->value.freq.freq = freq;
-		  p->value.freq.units = units;
-		}
-	    }
-	  break;
-	case OPTV_NONE:
-	  /* Should never get here */
-	  p->found = FALSE;
-	  break;
-	}
-      if (p->found)
-	{
-	  winDrvMsgVerb (scrnIndex, X_CONFIG, 2, "Option \"%s\"", p->name);
-	  if (!(p->type == OPTV_BOOLEAN && *s == 0))
-	    {
-	      winErrorFVerb (2, " \"%s\"", s);
-	    }
-	  winErrorFVerb (2, "\n");
-	}
-    }
-  else if (p->type == OPTV_BOOLEAN)
-    {
-      /* Look for matches with options with or without a "No" prefix. */
-      char *n, *newn;
-      OptionInfoRec opt;
-
-      n = winNormalizeName (p->name);
-      if (!n)
-	{
-	  p->found = FALSE;
-	  return FALSE;
-	}
-      if (strncmp (n, "no", 2) == 0)
-	{
-	  newn = n + 2;
-	}
-      else
-	{
-	  free (n);
-	  n = malloc (strlen (p->name) + 2 + 1);
-	  if (!n)
-	    {
-	      p->found = FALSE;
-	      return FALSE;
-	    }
-	  strcpy (n, "No");
-	  strcat (n, p->name);
-	  newn = n;
-	}
-      if ((s = winFindOptionValue (options, newn)) != NULL)
-	{
-	  if (GetBoolValue (&opt, s))
-	    {
-	      p->value.bool = !opt.value.bool;
-	      p->found = TRUE;
-	    }
-	  else
-	    {
-	      winDrvMsg (scrnIndex, X_WARNING,
-			 "Option \"%s\" requires a boolean value\n", newn);
-	      p->found = FALSE;
-	    }
-	}
-      else
-	{
-	  p->found = FALSE;
-	}
-      if (p->found)
-	{
-	  winDrvMsgVerb (scrnIndex, X_CONFIG, 2, "Option \"%s\"", newn);
-	  if (*s != 0)
-	    {
-	      winErrorFVerb (2, " \"%s\"", s);
-	    }
-	  winErrorFVerb (2, "\n");
-	}
-      free (n);
-    }
-  else
-    {
-      p->found = FALSE;
-    }
-  return p->found;
-}
-
-
-static Bool
-configLayout (serverLayoutPtr servlayoutp, XF86ConfLayoutPtr conf_layout,
-	      char *default_layout)
-{
-#if 0
-#pragma warn UNIMPLEMENTED
-#endif
-  return TRUE;
-}
-
-
-static Bool
-configImpliedLayout (serverLayoutPtr servlayoutp,
-		     XF86ConfScreenPtr conf_screen)
-{
-#if 0
-#pragma warn UNIMPLEMENTED
-#endif
-  return TRUE;
-}
-
-
-static Bool
-GetBoolValue (OptionInfoPtr p, const char *s)
-{
-  if (*s == 0)
-    {
-      p->value.bool = TRUE;
-    }
-  else
-    {
-      if (winNameCompare (s, "1") == 0)
-	p->value.bool = TRUE;
-      else if (winNameCompare (s, "on") == 0)
-	p->value.bool = TRUE;
-      else if (winNameCompare (s, "true") == 0)
-	p->value.bool = TRUE;
-      else if (winNameCompare (s, "yes") == 0)
-	p->value.bool = TRUE;
-      else if (winNameCompare (s, "0") == 0)
-	p->value.bool = FALSE;
-      else if (winNameCompare (s, "off") == 0)
-	p->value.bool = FALSE;
-      else if (winNameCompare (s, "false") == 0)
-	p->value.bool = FALSE;
-      else if (winNameCompare (s, "no") == 0)
-	p->value.bool = FALSE;
-    }
-  return TRUE;
-}
-#endif
-
-
-char *
-winNormalizeName (const char *s)
-{
-  char *ret, *q;
-  const char *p;
-
-  if (s == NULL)
-    return NULL;
-
-  ret = malloc (strlen (s) + 1);
-  for (p = s, q = ret; *p != 0; p++)
-    {
-      switch (*p)
-	{
-	case '_':
-	case ' ':
-	case '\t':
-	  continue;
-	default:
-	  if (isupper (*p))
-	    *q++ = tolower (*p);
-	  else
-	    *q++ = *p;
-	}
-    }
-  *q = '\0';
-  return ret;
-}
-
diff --git a/hw/xwin/winconfig.h b/hw/xwin/winconfig.h
deleted file mode 100644
index 4b56d63..0000000
--- a/hw/xwin/winconfig.h
+++ /dev/null
@@ -1,343 +0,0 @@
-#ifndef __WIN_CONFIG_H__
-#define __WIN_CONFIG_H__
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors: Alexander Gottwald	
- */
-
-#include "win.h"
-#ifdef XWIN_XF86CONFIG
-#include "../xfree86/parser/xf86Parser.h"
-#endif
-
-
-/* These are taken from hw/xfree86/common/xf86str.h */
-
-typedef struct
-{
-  CARD32 red, green, blue;
-}
-rgb;
-
-
-typedef struct
-{
-  float red, green, blue;
-}
-Gamma;
-
-
-typedef struct
-{
-  char *identifier;
-  char *vendor;
-  char *board;
-  char *chipset;
-  char *ramdac;
-  char *driver;
-  struct _confscreenrec *myScreenSection;
-  Bool claimed;
-  Bool active;
-  Bool inUse;
-  int videoRam;
-  int textClockFreq;
-  pointer options;
-  int screen;			/* For multi-CRTC cards */
-}
-GDevRec, *GDevPtr;
-
-
-typedef struct
-{
-  char *identifier;
-  char *driver;
-  pointer commonOptions;
-  pointer extraOptions;
-}
-IDevRec, *IDevPtr;
-
-
-typedef struct
-{
-  int frameX0;
-  int frameY0;
-  int virtualX;
-  int virtualY;
-  int depth;
-  int fbbpp;
-  rgb weight;
-  rgb blackColour;
-  rgb whiteColour;
-  int defaultVisual;
-  char **modes;
-  pointer options;
-}
-DispRec, *DispPtr;
-
-
-typedef struct _confxvportrec
-{
-  char *identifier;
-  pointer options;
-}
-confXvPortRec, *confXvPortPtr;
-
-
-typedef struct _confxvadaptrec
-{
-  char *identifier;
-  int numports;
-  confXvPortPtr ports;
-  pointer options;
-}
-confXvAdaptorRec, *confXvAdaptorPtr;
-
-
-typedef struct _confscreenrec
-{
-  char *id;
-  int screennum;
-  int defaultdepth;
-  int defaultbpp;
-  int defaultfbbpp;
-  GDevPtr device;
-  int numdisplays;
-  DispPtr displays;
-  int numxvadaptors;
-  confXvAdaptorPtr xvadaptors;
-  pointer options;
-}
-confScreenRec, *confScreenPtr;
-
-
-typedef enum
-{
-  PosObsolete = -1,
-  PosAbsolute = 0,
-  PosRightOf,
-  PosLeftOf,
-  PosAbove,
-  PosBelow,
-  PosRelative
-}
-PositionType;
-
-
-typedef struct _screenlayoutrec
-{
-  confScreenPtr screen;
-  char *topname;
-  confScreenPtr top;
-  char *bottomname;
-  confScreenPtr bottom;
-  char *leftname;
-  confScreenPtr left;
-  char *rightname;
-  confScreenPtr right;
-  PositionType where;
-  int x;
-  int y;
-  char *refname;
-  confScreenPtr refscreen;
-}
-screenLayoutRec, *screenLayoutPtr;
-
-
-typedef struct _serverlayoutrec
-{
-  char *id;
-  screenLayoutPtr screens;
-  GDevPtr inactives;
-  IDevPtr inputs;
-  pointer options;
-}
-serverLayoutRec, *serverLayoutPtr;
-
-
-/*
- * winconfig.c
- */
-
-typedef struct
-{
-  /* Files */
-#ifdef XWIN_XF86CONFIG
-  char *configFile;
-#endif
-  char *fontPath;
-  /* input devices - keyboard */
-#ifdef XWIN_XF86CONFIG
-  char *keyboard;
-#endif
-#ifdef XKB
-  Bool noXkbExtension;
-  char *xkbMap;
-  char *xkbRules; 
-  char *xkbModel;
-  char *xkbLayout;
-  char *xkbVariant;
-  char *xkbOptions;
-#endif
-  /* layout */
-  char *screenname;
-  /* mouse settings */
-  char *mouse;
-  Bool emulate3buttons;
-  long emulate3timeout;
-}
-WinCmdlineRec, *WinCmdlinePtr;
-
-
-extern WinCmdlineRec g_cmdline;
-#ifdef XWIN_XF86CONFIG
-extern XF86ConfigPtr g_xf86configptr;
-#endif
-extern serverLayoutRec g_winConfigLayout;
-
-
-/*
- * Function prototypes
- */
-
-Bool winReadConfigfile (void);
-Bool winConfigFiles (void);
-Bool winConfigOptions (void);
-Bool winConfigScreens (void);
-Bool winConfigKeyboard (DeviceIntPtr pDevice);
-Bool winConfigMouse (DeviceIntPtr pDevice);
-
-
-typedef struct
-{
-  double freq;
-  int units;
-}
-OptFrequency;
-
-
-typedef union
-{
-  unsigned long num;
-  char *str;
-  double realnum;
-  Bool bool;
-  OptFrequency freq;
-}
-ValueUnion;
-
-
-typedef enum
-{
-  OPTV_NONE = 0,
-  OPTV_INTEGER,
-  OPTV_STRING,			/* a non-empty string */
-  OPTV_ANYSTR,			/* Any string, including an empty one */
-  OPTV_REAL,
-  OPTV_BOOLEAN,
-  OPTV_FREQ
-}
-OptionValueType;
-
-
-typedef enum
-{
-  OPTUNITS_HZ = 1,
-  OPTUNITS_KHZ,
-  OPTUNITS_MHZ
-}
-OptFreqUnits;
-
-
-typedef struct
-{
-  int token;
-  const char *name;
-  OptionValueType type;
-  ValueUnion value;
-  Bool found;
-}
-OptionInfoRec, *OptionInfoPtr;
-
-
-/*
- * Function prototypes
- */
-
-char *winSetStrOption (pointer optlist, const char *name, char *deflt);
-int winSetBoolOption (pointer optlist, const char *name, int deflt);
-int winSetIntOption (pointer optlist, const char *name, int deflt);
-double winSetRealOption (pointer optlist, const char *name, double deflt);
-#ifdef XWIN_XF86CONFIG
-XF86OptionPtr winFindOption (XF86OptionPtr list, const char *name);
-char *winFindOptionValue (XF86OptionPtr list, const char *name);
-#endif
-int winNameCompare (const char *s1, const char *s2);
-char *winNormalizeName (const char *s);
-
-
-typedef struct
-{
-  struct
-  {
-    long leds;
-    long delay;
-    long rate;
-  }
-  keyboard;
-#ifdef XKB
-  struct
-  {
-    Bool disable;
-    char *rules;
-    char *model;
-    char *layout;
-    char *variant;
-    char *options;
-    char *initialMap;
-    char *keymap;
-    char *types;
-    char *compat;
-    char *keycodes;
-    char *symbols;
-    char *geometry;
-  }
-  xkb;
-#endif
-  struct
-  {
-    Bool emulate3Buttons;
-    long emulate3Timeout;
-  }
-  pointer;
-}
-winInfoRec, *winInfoPtr;
-
-
-extern winInfoRec g_winInfo;
-
-#endif
diff --git a/hw/xwin/wincreatewnd.c b/hw/xwin/wincreatewnd.c
deleted file mode 100644
index 796a085..0000000
--- a/hw/xwin/wincreatewnd.c
+++ /dev/null
@@ -1,644 +0,0 @@
-/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "shellapi.h"
-
-#ifndef ABS_AUTOHIDE
-#define ABS_AUTOHIDE 1
-#endif
-
-/*
- * Local function prototypes
- */
-
-static Bool
-winGetWorkArea (RECT *prcWorkArea, winScreenInfo *pScreenInfo);
-
-static Bool
-winAdjustForAutoHide (RECT *prcWorkArea);
-
-
-/*
- * Create a full screen window
- */
-
-Bool
-winCreateBoundingWindowFullScreen (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  int			iX = pScreenInfo->dwInitialX;
-  int			iY = pScreenInfo->dwInitialY;
-  int			iWidth = pScreenInfo->dwWidth;
-  int			iHeight = pScreenInfo->dwHeight;
-  HWND			*phwnd = &pScreenPriv->hwndScreen;
-  WNDCLASS		wc;
-  char			szTitle[256];
-
-#if CYGDEBUG
-  winDebug ("winCreateBoundingWindowFullScreen\n");
-#endif
-
-  /* Setup our window class */
-  wc.style = CS_HREDRAW | CS_VREDRAW;
-  wc.lpfnWndProc = winWindowProc;
-  wc.cbClsExtra = 0;
-  wc.cbWndExtra = 0;
-  wc.hInstance = g_hInstance;
-  wc.hIcon = LoadIcon (g_hInstance, MAKEINTRESOURCE(IDI_XWIN));
-  wc.hCursor = 0;
-  wc.hbrBackground = 0;
-  wc.lpszMenuName = NULL;
-  wc.lpszClassName = WINDOW_CLASS;
-  RegisterClass (&wc);
-
-  /* Set display and screen-specific tooltip text */
-  if (g_pszQueryHost != NULL)
-    snprintf (szTitle,
-	    sizeof (szTitle),
-	    WINDOW_TITLE_XDMCP,
-	    g_pszQueryHost); 
-  else    
-    snprintf (szTitle,
-	    sizeof (szTitle),
-	    WINDOW_TITLE,
-	    display, 
-	    (int) pScreenInfo->dwScreen);
-
-  /* Create the window */
-  *phwnd = CreateWindowExA (0,			/* Extended styles */
-			    WINDOW_CLASS,	/* Class name */
-			    szTitle,		/* Window name */
-			    WS_POPUP,
-			    iX,			/* Horizontal position */
-			    iY,			/* Vertical position */
-			    iWidth,		/* Right edge */ 
-			    iHeight,		/* Bottom edge */
-			    (HWND) NULL,	/* No parent or owner window */
-			    (HMENU) NULL,	/* No menu */
-			    GetModuleHandle (NULL),/* Instance handle */
-			    pScreenPriv);	/* ScreenPrivates */
-
-  /* Branch on the server engine */
-  switch (pScreenInfo->dwEngine)
-    {
-#ifdef XWIN_NATIVEGDI
-    case WIN_SERVER_SHADOW_GDI:
-      /* Show the window */
-      ShowWindow (*phwnd, SW_SHOWMAXIMIZED);
-      break;
-#endif
-
-    default:
-      /* Hide the window */
-      ShowWindow (*phwnd, SW_SHOWNORMAL);
-      break;
-    }
-
-  /* Send first paint message */
-  UpdateWindow (*phwnd);
-
-  /* Attempt to bring our window to the top of the display */
-  BringWindowToTop (*phwnd);
-
-  return TRUE;
-}
-
-
-/*
- * Create our primary Windows display window
- */
-
-Bool
-winCreateBoundingWindowWindowed (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  int			iWidth = pScreenInfo->dwUserWidth;
-  int			iHeight = pScreenInfo->dwUserHeight;
-  int                   iPosX;
-  int                   iPosY;
-  HWND			*phwnd = &pScreenPriv->hwndScreen;
-  WNDCLASS		wc;
-  RECT			rcClient, rcWorkArea;
-  DWORD			dwWindowStyle;
-  BOOL			fForceShowWindow = FALSE;
-  char			szTitle[256];
-  
-  winDebug ("winCreateBoundingWindowWindowed - User w: %d h: %d\n",
-	  (int) pScreenInfo->dwUserWidth, (int) pScreenInfo->dwUserHeight);
-  winDebug ("winCreateBoundingWindowWindowed - Current w: %d h: %d\n",
-	  (int) pScreenInfo->dwWidth, (int) pScreenInfo->dwHeight);
-
-  /* Set the common window style flags */
-  dwWindowStyle = WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX;
-  
-  /* Decorated or undecorated window */
-  if (pScreenInfo->fDecoration
-#ifdef XWIN_MULTIWINDOWEXTWM
-      && !pScreenInfo->fMWExtWM
-#endif
-      && !pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOW
-      && !pScreenInfo->fMultiWindow
-#endif
-      )
-    {
-        /* Try to handle startup via run.exe. run.exe instructs Windows to 
-         * hide all created windows. Detect this case and make sure the 
-         * window is shown nevertheless */
-        STARTUPINFO   startupInfo;
-        GetStartupInfo(&startupInfo);
-        if (startupInfo.dwFlags & STARTF_USESHOWWINDOW && 
-                startupInfo.wShowWindow == SW_HIDE)
-        {
-          fForceShowWindow = TRUE;
-        } 
-        dwWindowStyle |= WS_CAPTION;
-        if (pScreenInfo->fScrollbars)
-            dwWindowStyle |= WS_THICKFRAME | WS_MAXIMIZEBOX;
-    }
-  else
-    dwWindowStyle |= WS_POPUP;
-
-  /* Setup our window class */
-  wc.style = CS_HREDRAW | CS_VREDRAW;
-  wc.lpfnWndProc = winWindowProc;
-  wc.cbClsExtra = 0;
-  wc.cbWndExtra = 0;
-  wc.hInstance = g_hInstance;
-  wc.hIcon = LoadIcon (g_hInstance, MAKEINTRESOURCE(IDI_XWIN));
-  wc.hCursor = 0;
-  wc.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
-  wc.lpszMenuName = NULL;
-  wc.lpszClassName = WINDOW_CLASS;
-  RegisterClass (&wc);
-
-  /* Get size of work area */
-  winGetWorkArea (&rcWorkArea, pScreenInfo);
-
-  /* Adjust for auto-hide taskbars */
-  winAdjustForAutoHide (&rcWorkArea);
-
-  /* Did the user specify a position? */
-  if (pScreenInfo->fUserGavePosition)
-    {
-      iPosX = pScreenInfo->dwInitialX;
-      iPosY = pScreenInfo->dwInitialY;
-    }
-  else
-    {
-      iPosX = rcWorkArea.left;
-      iPosY = rcWorkArea.top;
-    }
-
-  /* Did the user specify a height and width? */
-  if (pScreenInfo->fUserGaveHeightAndWidth)
-    {
-      /* User gave a desired height and width, try to accomodate */
-#if CYGDEBUG
-      winDebug ("winCreateBoundingWindowWindowed - User gave height "
-	      "and width\n");
-#endif
-      
-      /* Adjust the window width and height for borders and title bar */
-      if (pScreenInfo->fDecoration
-#ifdef XWIN_MULTIWINDOWEXTWM
-	  && !pScreenInfo->fMWExtWM
-#endif
-	  && !pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOW
-	  && !pScreenInfo->fMultiWindow
-#endif
-	  )
-	{
-#if CYGDEBUG
-	  winDebug ("winCreateBoundingWindowWindowed - Window has decoration\n");
-#endif
-	  /* Are we using scrollbars? */
-	  if (pScreenInfo->fScrollbars)
-	    {
-#if CYGDEBUG
-	      winDebug ("winCreateBoundingWindowWindowed - Window has "
-		      "scrollbars\n");
-#endif
-
-	      iWidth += 2 * GetSystemMetrics (SM_CXSIZEFRAME);
-	      iHeight += 2 * GetSystemMetrics (SM_CYSIZEFRAME) 
-		+ GetSystemMetrics (SM_CYCAPTION);
-	    }
-	  else
-	    {
-#if CYGDEBUG
-	      winDebug ("winCreateBoundingWindowWindowed - Window does not have "
-		      "scrollbars\n");
-#endif
-
-	      iWidth += 2 * GetSystemMetrics (SM_CXFIXEDFRAME);
-	      iHeight += 2 * GetSystemMetrics (SM_CYFIXEDFRAME) 
-		+ GetSystemMetrics (SM_CYCAPTION);
-	    }
-	}
-    }
-  else
-    {
-      /* By default, we are creating a window that is as large as possible */
-#if CYGDEBUG
-      winDebug ("winCreateBoundingWindowWindowed - User did not give "
-	      "height and width\n");
-#endif
-      /* Defaults are wrong if we have multiple monitors */
-      if (pScreenInfo->fMultipleMonitors)
-	{
-	  iWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
-	  iHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
-	}
-    }
-
-  /* Clean up the scrollbars flag, if necessary */
-  if ((!pScreenInfo->fDecoration
-#ifdef XWIN_MULTIWINDOWEXTWM
-       || pScreenInfo->fMWExtWM
-#endif
-       || pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOW
-       || pScreenInfo->fMultiWindow
-#endif
-       )
-      && pScreenInfo->fScrollbars)
-    {
-      /* We cannot have scrollbars if we do not have a window border */
-      pScreenInfo->fScrollbars = FALSE;
-    }
- 
-  if (TRUE 
-#ifdef XWIN_MULTIWINDOWEXTWM
-       && !pScreenInfo->fMWExtWM
-#endif
-#ifdef XWIN_MULTIWINDOW
-       && !pScreenInfo->fMultiWindow
-#endif
-     )
-    {
-      /* Trim window width to fit work area */
-      if (iWidth > (rcWorkArea.right - rcWorkArea.left))
-        iWidth = rcWorkArea.right - rcWorkArea.left;
-  
-      /* Trim window height to fit work area */
-      if (iHeight >= (rcWorkArea.bottom - rcWorkArea.top))
-        iHeight = rcWorkArea.bottom - rcWorkArea.top;
-  
-#if CYGDEBUG
-      winDebug ("winCreateBoundingWindowWindowed - Adjusted width: %d "\
-	      "height: %d\n",
-    	  iWidth, iHeight);
-#endif
-    }
-
-  /* Set display and screen-specific tooltip text */
-  if (g_pszQueryHost != NULL)
-    snprintf (szTitle,
-	    sizeof (szTitle),
-	    WINDOW_TITLE_XDMCP,
-	    g_pszQueryHost); 
-  else    
-    snprintf (szTitle,
-	    sizeof (szTitle),
-	    WINDOW_TITLE,
-	    display, 
-	    (int) pScreenInfo->dwScreen);
-
-  /* Create the window */
-  *phwnd = CreateWindowExA (0,			/* Extended styles */
-			    WINDOW_CLASS,	/* Class name */
-			    szTitle,		/* Window name */
-			    dwWindowStyle,
-			    iPosX,	        /* Horizontal position */
-			    iPosY,	        /* Vertical position */
-			    iWidth,		/* Right edge */
-			    iHeight,		/* Bottom edge */
-			    (HWND) NULL,	/* No parent or owner window */
-			    (HMENU) NULL,	/* No menu */
-			    GetModuleHandle (NULL),/* Instance handle */
-			    pScreenPriv);	/* ScreenPrivates */
-  if (*phwnd == NULL)
-    {
-      ErrorF ("winCreateBoundingWindowWindowed - CreateWindowEx () failed\n");
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winCreateBoundingWindowWindowed - CreateWindowEx () returned\n");
-#endif
-
-  if (fForceShowWindow)
-  {
-      ErrorF("winCreateBoundingWindowWindowed - Setting normal windowstyle\n");
-      ShowWindow(*phwnd, SW_SHOW);      
-  }
-
-  /* Get the client area coordinates */
-  if (!GetClientRect (*phwnd, &rcClient))
-    {
-      ErrorF ("winCreateBoundingWindowWindowed - GetClientRect () "
-	      "failed\n");
-      return FALSE;
-    }
-
-  winDebug ("winCreateBoundingWindowWindowed - WindowClient "
-	  "w %ld h %ld r %ld l %ld b %ld t %ld\n",
-	  rcClient.right - rcClient.left,
-	  rcClient.bottom - rcClient.top,
-	  rcClient.right, rcClient.left,
-	  rcClient.bottom, rcClient.top);
-  
-  /* We adjust the visual size if the user did not specify it */
-  if (!(pScreenInfo->fScrollbars && pScreenInfo->fUserGaveHeightAndWidth))
-    {
-      /*
-       * User did not give a height and width with scrollbars enabled,
-       * so we will resize the underlying visual to be as large as
-       * the initial view port (page size).  This way scrollbars will
-       * not appear until the user shrinks the window, if they ever do.
-       *
-       * NOTE: We have to store the viewport size here because
-       * the user may have an autohide taskbar, which would
-       * cause the viewport size to be one less in one dimension
-       * than the viewport size that we calculated by subtracting
-       * the size of the borders and caption.
-       */
-      pScreenInfo->dwWidth = rcClient.right - rcClient.left;
-      pScreenInfo->dwHeight = rcClient.bottom - rcClient.top;
-    }
-
-#if 0
-  /*
-   * NOTE: For the uninitiated, the page size is the number of pixels
-   * that we can display in the x or y direction at a time and the
-   * range is the total number of pixels in the x or y direction that we
-   * have available to display.  In other words, the page size is the
-   * size of the window area minus the space the caption, borders, and
-   * scrollbars (if any) occupy, and the range is the size of the
-   * underlying X visual.  Notice that, contrary to what some of the
-   * MSDN Library arcticles lead you to believe, the windows
-   * ``client area'' size does not include the scrollbars.  In other words,
-   * the whole client area size that is reported to you is drawable by
-   * you; you do not have to subtract the size of the scrollbars from
-   * the client area size, and if you did it would result in the size
-   * of the scrollbars being double counted.
-   */
-
-  /* Setup scrollbar page and range, if scrollbars are enabled */
-  if (pScreenInfo->fScrollbars)
-    {
-      SCROLLINFO		si;
-      
-      /* Initialize the scrollbar info structure */
-      si.cbSize = sizeof (si);
-      si.fMask = SIF_RANGE | SIF_PAGE;
-      si.nMin = 0;
-      
-      /* Setup the width range and page size */
-      si.nMax = pScreenInfo->dwWidth - 1;
-      si.nPage = rcClient.right - rcClient.left;
-      winDebug ("winCreateBoundingWindowWindowed - HORZ nMax: %d nPage :%d\n",
-	      si.nMax, si.nPage);
-      SetScrollInfo (*phwnd, SB_HORZ, &si, TRUE);
-      
-      /* Setup the height range and page size */
-      si.nMax = pScreenInfo->dwHeight - 1;
-      si.nPage = rcClient.bottom - rcClient.top;
-      winDebug ("winCreateBoundingWindowWindowed - VERT nMax: %d nPage :%d\n",
-	      si.nMax, si.nPage);
-      SetScrollInfo (*phwnd, SB_VERT, &si, TRUE);
-    }
-#endif
-
-  /* Show the window */
-  if (FALSE
-#ifdef XWIN_MULTIWINDOWEXTWM
-      || pScreenInfo->fMWExtWM
-#endif
-#ifdef XWIN_MULTIWINDOW
-      || pScreenInfo->fMultiWindow
-#endif
-      )
-    {
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-      pScreenPriv->fRootWindowShown = FALSE;
-#endif
-      ShowWindow (*phwnd, SW_HIDE);
-    }
-  else
-    ShowWindow (*phwnd, SW_SHOWNORMAL);
-  if (!UpdateWindow (*phwnd))
-    {
-      ErrorF ("winCreateBoundingWindowWindowed - UpdateWindow () failed\n");
-      return FALSE;
-    }
-  
-  /* Attempt to bring our window to the top of the display */
-  if (TRUE
-#ifdef XWIN_MULTIWINDOWEXTWM
-      && !pScreenInfo->fMWExtWM
-#endif
-      && !pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOW
-      && !pScreenInfo->fMultiWindow
-#endif
-      )
-    {
-      if (!BringWindowToTop (*phwnd))
-	{
-	  ErrorF ("winCreateBoundingWindowWindowed - BringWindowToTop () "
-		  "failed\n");
-	  return FALSE;
-	}
-    }
-
-#ifdef XWIN_NATIVEGDI
-  /* Paint window background blue */
-  if (pScreenInfo->dwEngine == WIN_SERVER_NATIVE_GDI)
-    winPaintBackground (*phwnd, RGB (0x00, 0x00, 0xFF));
-#endif
-
-  winDebug ("winCreateBoundingWindowWindowed -  Returning\n");
-
-  return TRUE;
-}
-
-
-/*
- * Find the work area of all attached monitors
- */
-
-static Bool
-winGetWorkArea (RECT *prcWorkArea, winScreenInfo *pScreenInfo)
-{
-  int			iPrimaryWidth, iPrimaryHeight;
-  int			iWidth, iHeight;
-  int			iLeft, iTop;
-  int			iPrimaryNonWorkAreaWidth, iPrimaryNonWorkAreaHeight;
-
-  /* SPI_GETWORKAREA only gets the work area of the primary screen. */
-  SystemParametersInfo (SPI_GETWORKAREA, 0, prcWorkArea, 0);
-
-  /* Bail out here if we aren't using multiple monitors */
-  if (!pScreenInfo->fMultipleMonitors)
-    return TRUE;
-  
-  winDebug ("winGetWorkArea - Original WorkArea: %d %d %d %d\n",
-	  (int) prcWorkArea->top, (int) prcWorkArea->left,
-	  (int) prcWorkArea->bottom, (int) prcWorkArea->right);
-
-  /* Get size of full virtual screen */
-  iWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
-  iHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
-
-  winDebug ("winGetWorkArea - Virtual screen is %d x %d\n", iWidth, iHeight);
-
-  /* Get origin of full virtual screen */
-  iLeft = GetSystemMetrics (SM_XVIRTUALSCREEN);
-  iTop = GetSystemMetrics (SM_YVIRTUALSCREEN);
-
-  winDebug ("winGetWorkArea - Virtual screen origin is %d, %d\n", iLeft, iTop);
-  
-  /* Get size of primary screen */
-  iPrimaryWidth = GetSystemMetrics (SM_CXSCREEN);
-  iPrimaryHeight = GetSystemMetrics (SM_CYSCREEN);
-
-  winDebug ("winGetWorkArea - Primary screen is %d x %d\n",
-	 iPrimaryWidth, iPrimaryHeight);
-  
-  /* Work out how much of the primary screen we aren't using */
-  iPrimaryNonWorkAreaWidth = iPrimaryWidth - (prcWorkArea->right -
-					      prcWorkArea->left);
-  iPrimaryNonWorkAreaHeight = iPrimaryHeight - (prcWorkArea->bottom
-						- prcWorkArea->top);
-  
-  /* Update the rectangle to include all monitors */
-  if (iLeft < 0) 
-    {
-      prcWorkArea->left = iLeft;
-    }
-  if (iTop < 0) 
-    {
-      prcWorkArea->top = iTop;
-    }
-  prcWorkArea->right = prcWorkArea->left + iWidth -
-    iPrimaryNonWorkAreaWidth;
-  prcWorkArea->bottom = prcWorkArea->top + iHeight -
-    iPrimaryNonWorkAreaHeight;
-  
-  winDebug ("winGetWorkArea - Adjusted WorkArea for multiple "
-	  "monitors: %d %d %d %d\n",
-	  (int) prcWorkArea->top, (int) prcWorkArea->left,
-	  (int) prcWorkArea->bottom, (int) prcWorkArea->right);
-  
-  return TRUE;
-}
-
-
-/*
- * Adjust the client area so that any auto-hide toolbars
- * will work correctly.
- */
-
-static Bool
-winAdjustForAutoHide (RECT *prcWorkArea)
-{
-  APPBARDATA		abd;
-  HWND			hwndAutoHide;
-
-  winDebug ("winAdjustForAutoHide - Original WorkArea: %d %d %d %d\n",
-	  (int) prcWorkArea->top, (int) prcWorkArea->left,
-	  (int) prcWorkArea->bottom, (int) prcWorkArea->right);
-
-  /* Find out if the Windows taskbar is set to auto-hide */
-  ZeroMemory (&abd, sizeof (abd));
-  abd.cbSize = sizeof (abd);
-  if (SHAppBarMessage (ABM_GETSTATE, &abd) & ABS_AUTOHIDE)
-    winDebug ("winAdjustForAutoHide - Taskbar is auto hide\n");
-
-  /* Look for a TOP auto-hide taskbar */
-  abd.uEdge = ABE_TOP;
-  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETAUTOHIDEBAR, &abd);
-  if (hwndAutoHide != NULL)
-    {
-      winDebug ("winAdjustForAutoHide - Found TOP auto-hide taskbar\n");
-      prcWorkArea->top += 1;
-    }
-
-  /* Look for a LEFT auto-hide taskbar */
-  abd.uEdge = ABE_LEFT;
-  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETAUTOHIDEBAR, &abd);
-  if (hwndAutoHide != NULL)
-    {
-      winDebug ("winAdjustForAutoHide - Found LEFT auto-hide taskbar\n");
-      prcWorkArea->left += 1;
-    }
-
-  /* Look for a BOTTOM auto-hide taskbar */
-  abd.uEdge = ABE_BOTTOM;
-  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETAUTOHIDEBAR, &abd);
-  if (hwndAutoHide != NULL)
-    {
-      winDebug ("winAdjustForAutoHide - Found BOTTOM auto-hide taskbar\n");
-      prcWorkArea->bottom -= 1;
-    }
-
-  /* Look for a RIGHT auto-hide taskbar */
-  abd.uEdge = ABE_RIGHT;
-  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETAUTOHIDEBAR, &abd);
-  if (hwndAutoHide != NULL)
-    {
-      winDebug ("winAdjustForAutoHide - Found RIGHT auto-hide taskbar\n");
-      prcWorkArea->right -= 1;
-    }
-
-  winDebug ("winAdjustForAutoHide - Adjusted WorkArea: %d %d %d %d\n",
-	  (int) prcWorkArea->top, (int) prcWorkArea->left,
-	  (int) prcWorkArea->bottom, (int) prcWorkArea->right);
-  
-#if 0
-  /* Obtain the task bar window dimensions */
-  abd.hWnd = hwndAutoHide;
-  hwndAutoHide = (HWND) SHAppBarMessage (ABM_GETTASKBARPOS, &abd);
-  winDebug ("hwndAutoHide %08x abd.hWnd %08x %d %d %d %d\n",
-	  hwndAutoHide, abd.hWnd,
-	  abd.rc.top, abd.rc.left, abd.rc.bottom, abd.rc.right);
-#endif
-
-  return TRUE;
-}
diff --git a/hw/xwin/wincursor.c b/hw/xwin/wincursor.c
deleted file mode 100644
index 021b8b8..0000000
--- a/hw/xwin/wincursor.c
+++ /dev/null
@@ -1,614 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winmsg.h"
-#include <cursorstr.h>
-#include <mipointrst.h>
-#include <servermd.h>
-
-extern Bool	g_fSoftwareCursor;
-
-
-#ifndef MIN
-#define MIN(x,y) ((x)<(y)?(x):(y))
-#endif
-
-#define BYTE_COUNT(x) (((x) + 7) / 8)
-
-#define BRIGHTNESS(x) (x##Red * 0.299 + x##Green * 0.587 + x##Blue * 0.114)
-
-#if 0
-# define WIN_DEBUG_MSG winDebug
-#else
-# define WIN_DEBUG_MSG(...)
-#endif
-
-/*
- * Local function prototypes
- */
-
-static void
-winPointerWarpCursor (ScreenPtr pScreen, int x, int y);
-
-static Bool
-winCursorOffScreen (ScreenPtr *ppScreen, int *x, int *y);
-
-static void
-winCrossScreen (ScreenPtr pScreen, Bool fEntering);
-
-miPointerScreenFuncRec g_winPointerCursorFuncs =
-{
-  winCursorOffScreen,
-  winCrossScreen,
-  winPointerWarpCursor
-};
-
-
-static void
-winPointerWarpCursor (ScreenPtr pScreen, int x, int y)
-{
-  winScreenPriv(pScreen);
-  RECT			rcClient;
-  static Bool		s_fInitialWarp = TRUE;
-
-  /* Discard first warp call */
-  if (s_fInitialWarp)
-    {
-      /* First warp moves mouse to center of window, just ignore it */
-
-      /* Don't ignore subsequent warps */
-      s_fInitialWarp = FALSE;
-
-      winErrorFVerb (2, "winPointerWarpCursor - Discarding first warp: %d %d\n",
-	      x, y);
-      
-      return;
-    }
-
-  /* Only update the Windows cursor position if we are active */
-  if (pScreenPriv->hwndScreen == GetForegroundWindow ())
-    {
-      /* Get the client area coordinates */
-      GetClientRect (pScreenPriv->hwndScreen, &rcClient);
-      
-      /* Translate the client area coords to screen coords */
-      MapWindowPoints (pScreenPriv->hwndScreen,
-		       HWND_DESKTOP,
-		       (LPPOINT)&rcClient,
-		       2);
-      
-      /* 
-       * Update the Windows cursor position so that we don't
-       * immediately warp back to the current position.
-       */
-      SetCursorPos (rcClient.left + x, rcClient.top + y);
-    }
-
-  /* Call the mi warp procedure to do the actual warping in X. */
-  miPointerWarpCursor (pScreen, x, y);
-}
-
-static Bool
-winCursorOffScreen (ScreenPtr *ppScreen, int *x, int *y)
-{
-  return FALSE;
-}
-
-static void
-winCrossScreen (ScreenPtr pScreen, Bool fEntering)
-{
-}
-
-static unsigned char
-reverse(unsigned char c)
-{
-  int i;
-  unsigned char ret = 0;
-  for (i = 0; i < 8; ++i)
-    {
-      ret |= ((c >> i)&1) << (7 - i);
-    }
-  return ret;
-}
-
-/*
- * Convert X cursor to Windows cursor
- * FIXME: Perhaps there are more smart code
- */
-static HCURSOR
-winLoadCursor (ScreenPtr pScreen, CursorPtr pCursor, int screen)
-{
-  winScreenPriv(pScreen);
-  HCURSOR hCursor = NULL;
-  unsigned char *pAnd;
-  unsigned char *pXor;
-  int nCX, nCY;
-  int nBytes;
-  double dForeY, dBackY;
-  BOOL fReverse;
-  HBITMAP hAnd, hXor;
-  ICONINFO ii;
-  unsigned char *pCur;
-  int x, y;
-  unsigned char bit;
-  HDC hDC;
-  BITMAPV4HEADER bi;
-  BITMAPINFO *pbmi;
-  unsigned long *lpBits;
-
-  WIN_DEBUG_MSG("winLoadCursor: Win32: %dx%d X11: %dx%d hotspot: %d,%d\n", 
-          pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy,
-          pCursor->bits->width, pCursor->bits->height,
-          pCursor->bits->xhot, pCursor->bits->yhot
-          );
-
-  /* We can use only White and Black, so calc brightness of color 
-   * Also check if the cursor is inverted */  
-  dForeY = BRIGHTNESS(pCursor->fore);
-  dBackY = BRIGHTNESS(pCursor->back);
-  fReverse = dForeY < dBackY;
- 
-  /* Check wether the X11 cursor is bigger than the win32 cursor */
-  if (pScreenPriv->cursor.sm_cx < pCursor->bits->width || 
-      pScreenPriv->cursor.sm_cy < pCursor->bits->height)
-    {
-      winErrorFVerb (2, "winLoadCursor - Windows requires %dx%d cursor\n"
-	      "\tbut X requires %dx%d\n",
-	      pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy,
-	      pCursor->bits->width, pCursor->bits->height);
-    }
-
-  /* Get the number of bytes required to store the whole cursor image 
-   * This is roughly (sm_cx * sm_cy) / 8 
-   * round up to 8 pixel boundary so we can convert whole bytes */
-  nBytes = BYTE_COUNT(pScreenPriv->cursor.sm_cx) * pScreenPriv->cursor.sm_cy;
-
-  /* Get the effective width and height */
-  nCX = MIN(pScreenPriv->cursor.sm_cx, pCursor->bits->width);
-  nCY = MIN(pScreenPriv->cursor.sm_cy, pCursor->bits->height);
-
-  /* Allocate memory for the bitmaps */
-  pAnd = malloc (nBytes);
-  memset (pAnd, 0xFF, nBytes);
-  pXor = malloc (nBytes);
-  memset (pXor, 0x00, nBytes);
-
-  /* Convert the X11 bitmap to a win32 bitmap 
-   * The first is for an empty mask */
-  if (pCursor->bits->emptyMask)
-    {
-      int x, y, xmax = BYTE_COUNT(nCX);
-      for (y = 0; y < nCY; ++y)
-	for (x = 0; x < xmax; ++x)
-	  {
-	    int nWinPix = BYTE_COUNT(pScreenPriv->cursor.sm_cx) * y + x;
-	    int nXPix = BitmapBytePad(pCursor->bits->width) * y + x;
-
-	    pAnd[nWinPix] = 0;
-	    if (fReverse)
-	      pXor[nWinPix] = reverse (~pCursor->bits->source[nXPix]);
-	    else
-	      pXor[nWinPix] = reverse (pCursor->bits->source[nXPix]);
-	  }
-    }
-  else
-    {
-      int x, y, xmax = BYTE_COUNT(nCX);
-      for (y = 0; y < nCY; ++y)
-	for (x = 0; x < xmax; ++x)
-	  {
-	    int nWinPix = BYTE_COUNT(pScreenPriv->cursor.sm_cx) * y + x;
-	    int nXPix = BitmapBytePad(pCursor->bits->width) * y + x;
-
-	    unsigned char mask = pCursor->bits->mask[nXPix];
-	    pAnd[nWinPix] = reverse (~mask);
-	    if (fReverse)
-	      pXor[nWinPix] = reverse (~pCursor->bits->source[nXPix] & mask);
-	    else
-	      pXor[nWinPix] = reverse (pCursor->bits->source[nXPix] & mask);
-	  }
-    }
-
-  /* prepare the pointers */ 
-  hCursor = NULL;
-  lpBits = NULL;
-
-  /* We have a truecolor alpha-blended cursor and can use it! */
-  if (pCursor->bits->argb) 
-    {
-      WIN_DEBUG_MSG("winLoadCursor: Trying truecolor alphablended cursor\n"); 
-      memset (&bi, 0, sizeof (BITMAPV4HEADER));
-      bi.bV4Size = sizeof(BITMAPV4HEADER);
-      bi.bV4Width = pScreenPriv->cursor.sm_cx;
-      bi.bV4Height = -(pScreenPriv->cursor.sm_cy); /* right-side up */
-      bi.bV4Planes = 1;
-      bi.bV4BitCount = 32;
-      bi.bV4V4Compression = BI_BITFIELDS;
-      bi.bV4RedMask = 0x00FF0000;
-      bi.bV4GreenMask = 0x0000FF00;
-      bi.bV4BlueMask = 0x000000FF;
-      bi.bV4AlphaMask = 0xFF000000; 
-      
-      lpBits = (unsigned long *) calloc (pScreenPriv->cursor.sm_cx*pScreenPriv->cursor.sm_cy,
-					 sizeof (unsigned long));
-      
-      if (lpBits)
-	{
-	  for (y=0; y<nCY; y++)
-	    {
-	      unsigned long *src, *dst;
-	      src = &(pCursor->bits->argb[y * pCursor->bits->width]);
-	      dst = &(lpBits[y * pScreenPriv->cursor.sm_cx]);
-	      memcpy (dst, src, 4*nCX);
-	    }
-	}
-    } /* End if-truecolor-icon */
-  
-  if (!lpBits)
-    {
-      /* Bicolor, use a palettized DIB */
-      WIN_DEBUG_MSG("winLoadCursor: Trying two color cursor\n"); 
-      pbmi = (BITMAPINFO*)&bi;
-      memset (pbmi, 0, sizeof (BITMAPINFOHEADER));
-      pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
-      pbmi->bmiHeader.biWidth = pScreenPriv->cursor.sm_cx;
-      pbmi->bmiHeader.biHeight = -abs(pScreenPriv->cursor.sm_cy); /* right-side up */
-      pbmi->bmiHeader.biPlanes = 1;
-      pbmi->bmiHeader.biBitCount = 8;
-      pbmi->bmiHeader.biCompression = BI_RGB;
-      pbmi->bmiHeader.biSizeImage = 0;
-      pbmi->bmiHeader.biClrUsed = 3;
-      pbmi->bmiHeader.biClrImportant = 3;
-      pbmi->bmiColors[0].rgbRed = 0; /* Empty */
-      pbmi->bmiColors[0].rgbGreen = 0;
-      pbmi->bmiColors[0].rgbBlue = 0;
-      pbmi->bmiColors[0].rgbReserved = 0;
-      pbmi->bmiColors[1].rgbRed = pCursor->backRed>>8; /* Background */
-      pbmi->bmiColors[1].rgbGreen = pCursor->backGreen>>8;
-      pbmi->bmiColors[1].rgbBlue = pCursor->backBlue>>8;
-      pbmi->bmiColors[1].rgbReserved = 0;
-      pbmi->bmiColors[2].rgbRed = pCursor->foreRed>>8; /* Foreground */
-      pbmi->bmiColors[2].rgbGreen = pCursor->foreGreen>>8;
-      pbmi->bmiColors[2].rgbBlue = pCursor->foreBlue>>8;
-      pbmi->bmiColors[2].rgbReserved = 0;
-      
-      lpBits = (unsigned long *) calloc (pScreenPriv->cursor.sm_cx*pScreenPriv->cursor.sm_cy,
-					 sizeof (char));
-      
-      pCur = (unsigned char *)lpBits;
-      if (lpBits)
-	{
-	  for (y=0; y<pScreenPriv->cursor.sm_cy; y++)
-	    {
-	      for (x=0; x<pScreenPriv->cursor.sm_cx; x++)
-		{
-		  if (x>=nCX || y>=nCY) /* Outside of X11 icon bounds */
-		    (*pCur++) = 0;
-		  else /* Within X11 icon bounds */
-		    {
-		      int nWinPix = BYTE_COUNT(pScreenPriv->cursor.sm_cx) * y + (x/8);
-
-		      bit = pAnd[nWinPix];
-		      bit = bit & (1<<(7-(x&7)));
-		      if (!bit) /* Within the cursor mask? */
-			{
-			  int nXPix = BitmapBytePad(pCursor->bits->width) * y + (x/8);
-			  bit = ~reverse(~pCursor->bits->source[nXPix] & pCursor->bits->mask[nXPix]);
-			  bit = bit & (1<<(7-(x&7)));
-			  if (bit) /* Draw foreground */
-			    (*pCur++) = 2;
-			  else /* Draw background */
-			    (*pCur++) = 1;
-			}
-		      else /* Outside the cursor mask */
-			(*pCur++) = 0;
-		    }
-		} /* end for (x) */
-	    } /* end for (y) */
-	} /* end if (lpbits) */
-    }
-
-  /* If one of the previous two methods gave us the bitmap we need, make a cursor */
-  if (lpBits)
-    {
-      WIN_DEBUG_MSG("winLoadCursor: Creating bitmap cursor: hotspot %d,%d\n",
-              pCursor->bits->xhot, pCursor->bits->yhot);
-
-      hAnd = NULL;
-      hXor = NULL;
-
-      hAnd = CreateBitmap (pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy, 1, 1, pAnd);
-
-      hDC = GetDC (NULL);
-      if (hDC)
-	{
-	  hXor = CreateCompatibleBitmap (hDC, pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy);
-	  SetDIBits (hDC, hXor, 0, pScreenPriv->cursor.sm_cy, lpBits, (BITMAPINFO*)&bi, DIB_RGB_COLORS);
-	  ReleaseDC (NULL, hDC);
-	}
-      free (lpBits);
-      
-      
-      if (hAnd && hXor)
-	{
-	  ii.fIcon = FALSE;
-	  ii.xHotspot = pCursor->bits->xhot;
-	  ii.yHotspot = pCursor->bits->yhot;
-	  ii.hbmMask = hAnd;
-	  ii.hbmColor = hXor;
-	  hCursor = (HCURSOR) CreateIconIndirect( &ii );
-
-	  if (hCursor == NULL)
-	    winW32Error(2, "winLoadCursor - CreateIconIndirect failed:");
-	  else 
-	    {
-	      if (GetIconInfo(hCursor, &ii))
-		{
-		  if (ii.fIcon)
-		    {
-		      WIN_DEBUG_MSG("winLoadCursor: CreateIconIndirect returned  no cursor. Trying again.\n");
-		      
-		      DestroyCursor(hCursor);
-		      
-		      ii.fIcon = FALSE;
-		      ii.xHotspot = pCursor->bits->xhot;
-		      ii.yHotspot = pCursor->bits->yhot;
-		      hCursor = (HCURSOR) CreateIconIndirect( &ii );
-		      
-		      if (hCursor == NULL)
-			winW32Error(2, "winLoadCursor - CreateIconIndirect failed:");
-		    }
-		  /* GetIconInfo creates new bitmaps. Destroy them again */
-		  if (ii.hbmMask)
-     	            DeleteObject(ii.hbmMask);
-		  if (ii.hbmColor)
-		    DeleteObject(ii.hbmColor);
-		}
-	    }
-	}
-
-      if (hAnd)
-	DeleteObject (hAnd);
-      if (hXor)
-	DeleteObject (hXor);
-    }
-
-  if (!hCursor)
-    {
-      /* We couldn't make a color cursor for this screen, use
-	 black and white instead */
-      hCursor = CreateCursor (g_hInstance,
-			      pCursor->bits->xhot, pCursor->bits->yhot,
-			      pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy,
-			      pAnd, pXor);
-      if (hCursor == NULL)
-	winW32Error(2, "winLoadCursor - CreateCursor failed:");
-    }
-  free (pAnd);
-  free (pXor);
-
-  return hCursor;
-}
-
-/*
-===========================================================================
-
- Pointer sprite functions
-
-===========================================================================
-*/
-
-/*
- * winRealizeCursor
- *  Convert the X cursor representation to native format if possible.
- */
-static Bool
-winRealizeCursor (ScreenPtr pScreen, CursorPtr pCursor)
-{
-  if(pCursor == NULL || pCursor->bits == NULL)
-    return FALSE;
-  
-  /* FIXME: cache ARGB8888 representation? */
-
-  return TRUE;
-}
-
-
-/*
- * winUnrealizeCursor
- *  Free the storage space associated with a realized cursor.
- */
-static Bool
-winUnrealizeCursor(ScreenPtr pScreen, CursorPtr pCursor)
-{
-  return TRUE;
-}
-
-
-/*
- * winSetCursor
- *  Set the cursor sprite and position.
- */
-static void
-winSetCursor (ScreenPtr pScreen, CursorPtr pCursor, int x, int y)
-{
-  POINT ptCurPos, ptTemp;
-  HWND  hwnd;
-  RECT  rcClient;
-  BOOL  bInhibit;
-  winScreenPriv(pScreen);
-  WIN_DEBUG_MSG("winSetCursor: cursor=%p\n", pCursor); 
-  
-  /* Inhibit changing the cursor if the mouse is not in a client area */
-  bInhibit = FALSE;
-  if (GetCursorPos (&ptCurPos))
-    {
-      hwnd = WindowFromPoint (ptCurPos);
-      if (hwnd)
-	{
-	  if (GetClientRect (hwnd, &rcClient))
-	    {
-	      ptTemp.x = rcClient.left;
-	      ptTemp.y = rcClient.top;
-	      if (ClientToScreen (hwnd, &ptTemp))
-		{
-		  rcClient.left = ptTemp.x;
-		  rcClient.top = ptTemp.y;
-		  ptTemp.x = rcClient.right;
-		  ptTemp.y = rcClient.bottom;
-		  if (ClientToScreen (hwnd, &ptTemp))
-		    {
-		      rcClient.right = ptTemp.x;
-		      rcClient.bottom = ptTemp.y;
-		      if (!PtInRect (&rcClient, ptCurPos))
-			bInhibit = TRUE;
-		    }
-		}
-	    }
-	}
-    }
-
-  if (pCursor == NULL)
-    {
-      if (pScreenPriv->cursor.visible)
-	{
-	  if (!bInhibit && g_fSoftwareCursor)
-	    ShowCursor (FALSE);
-	  pScreenPriv->cursor.visible = FALSE;
-	}
-    }
-  else
-    {
-      if (pScreenPriv->cursor.handle)
-	{
-	  if (!bInhibit)
-	    SetCursor (NULL);
-	  DestroyCursor (pScreenPriv->cursor.handle);
-	  pScreenPriv->cursor.handle = NULL;
-	}
-      pScreenPriv->cursor.handle =
-	winLoadCursor (pScreen, pCursor, pScreen->myNum);
-      WIN_DEBUG_MSG("winSetCursor: handle=%p\n", pScreenPriv->cursor.handle); 
-
-      if (!bInhibit)
-	SetCursor (pScreenPriv->cursor.handle);
-
-      if (!pScreenPriv->cursor.visible)
-	{
-	  if (!bInhibit && g_fSoftwareCursor)
-	    ShowCursor (TRUE);
-	  pScreenPriv->cursor.visible = TRUE;
-	}
-    }
-}
-
-
-/*
- * QuartzMoveCursor
- *  Move the cursor. This is a noop for us.
- */
-static void
-winMoveCursor (ScreenPtr pScreen, int x, int y)
-{
-}
-
-
-static miPointerSpriteFuncRec winSpriteFuncsRec = {
-  winRealizeCursor,
-  winUnrealizeCursor,
-  winSetCursor,
-  winMoveCursor
-};
-
-
-/*
-===========================================================================
-
- Other screen functions
-
-===========================================================================
-*/
-
-/*
- * winCursorQueryBestSize
- *  Handle queries for best cursor size
- */
-static void
-winCursorQueryBestSize (int class, unsigned short *width,
-				     unsigned short *height, ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  
-  if (class == CursorShape)
-    {
-      *width = pScreenPriv->cursor.sm_cx;
-      *height = pScreenPriv->cursor.sm_cy;
-    }
-  else
-    {
-      if (pScreenPriv->cursor.QueryBestSize)
-        (*pScreenPriv->cursor.QueryBestSize)(class, width, height, pScreen);
-    }
-}
-
-/*
- * winInitCursor
- *  Initialize cursor support
- */
-Bool
-winInitCursor (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  miPointerScreenPtr pPointPriv;
-  /* override some screen procedures */
-  pScreenPriv->cursor.QueryBestSize = pScreen->QueryBestSize;
-  pScreen->QueryBestSize = winCursorQueryBestSize;
-  
-  pPointPriv = (miPointerScreenPtr)
-      dixLookupPrivate(&pScreen->devPrivates, miPointerScreenKey);
-  
-  pScreenPriv->cursor.spriteFuncs = pPointPriv->spriteFuncs;
-  pPointPriv->spriteFuncs = &winSpriteFuncsRec;
-
-  pScreenPriv->cursor.handle = NULL;
-  pScreenPriv->cursor.visible = FALSE;
-  
-  pScreenPriv->cursor.sm_cx = GetSystemMetrics (SM_CXCURSOR);
-  pScreenPriv->cursor.sm_cy = GetSystemMetrics (SM_CYCURSOR);
-
-  return TRUE;
-}
diff --git a/hw/xwin/windialogs.c b/hw/xwin/windialogs.c
deleted file mode 100755
index ab06b0d..0000000
--- a/hw/xwin/windialogs.c
+++ /dev/null
@@ -1,788 +0,0 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- *              Earle F. Philhower III
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#ifdef __CYGWIN__
-#include <sys/cygwin.h>
-#endif
-#include <shellapi.h>
-#include "winprefs.h"
-
-
-/*
- * References to external globals
- */
-
-extern Bool			g_fCursor;
-extern HWND			g_hDlgDepthChange;
-extern HWND			g_hDlgExit;
-extern HWND			g_hDlgAbout;
-extern WINPREFS			pref;
-#ifdef XWIN_CLIPBOARD
-extern Bool			g_fClipboardStarted;
-#endif
-extern Bool			g_fSoftwareCursor;
-
-
-/*
- * Local function prototypes
- */
-
-static wBOOL CALLBACK
-winExitDlgProc (HWND hDialog, UINT message,
-		WPARAM wParam, LPARAM lParam);
-
-static wBOOL CALLBACK
-winChangeDepthDlgProc (HWND hDialog, UINT message,
-		       WPARAM wParam, LPARAM lParam);
-
-static wBOOL CALLBACK
-winAboutDlgProc (HWND hDialog, UINT message,
-		 WPARAM wParam, LPARAM lParam);
-
-
-static void
-winDrawURLWindow (LPARAM lParam);
-
-static LRESULT CALLBACK
-winURLWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
-
-static void
-winOverrideURLButton (HWND hdlg, int id);
-
-static void
-winUnoverrideURLButton (HWND hdlg, int id);
-
-
-/*
- * Owner-draw a button as a URL
- */
-
-static void
-winDrawURLWindow (LPARAM lParam)
-{
-  DRAWITEMSTRUCT *draw;
-  char str[256];
-  RECT rect;
-  HFONT font;
-  COLORREF crText;
-  
-  draw = (DRAWITEMSTRUCT *) lParam;
-  GetWindowText (draw->hwndItem, str, sizeof(str));
-  str[255] = 0;
-  GetClientRect (draw->hwndItem, &rect);
-  
-  /* Color the button depending upon its state */
-  if (draw->itemState & ODS_SELECTED)
-    crText = RGB(128+64,0,0);
-  else if (draw->itemState & ODS_FOCUS)
-    crText = RGB(0,128+64,0);
-  else
-    crText = RGB(0,0,128+64);
-  SetTextColor (draw->hDC, crText);
-  
-  /* Create underlined font 14 high, standard dialog font */
-  font = CreateFont (-14, 0, 0, 0, FW_NORMAL, FALSE, TRUE, FALSE,
-		     0, 0, 0, 0, 0, "MS Sans Serif");
-  if (!font)
-    {
-      ErrorF ("winDrawURLWindow: Unable to create URL font, bailing.\n");
-      return;
-    }
-  /* Draw it */
-  SetBkMode (draw->hDC, OPAQUE);
-  SelectObject (draw->hDC, font);
-  DrawText (draw->hDC, str, strlen (str),&rect,DT_CENTER | DT_VCENTER);
-  /* Delete the created font, replace it with stock font */
-  DeleteObject (SelectObject (draw->hDC, GetStockObject (ANSI_VAR_FONT)));
-}
-
-
-/*
- * WndProc for overridden buttons
- */
-
-static LRESULT CALLBACK
-winURLWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
-{
-  WNDPROC origCB = NULL;
-  HCURSOR cursor;
-  
-  /* If it's a SetCursor message, tell it to the hand */
-  if (msg==WM_SETCURSOR) {
-    cursor = LoadCursor (NULL, IDC_HAND);
-    if (cursor)
-      SetCursor (cursor);
-    return TRUE;
-  }
-  origCB = (WNDPROC)GetWindowLong (hwnd, GWL_USERDATA);
-  /* Otherwise fall through to original WndProc */
-  if (origCB)
-    return CallWindowProc (origCB, hwnd, msg, wParam, lParam);
-  else
-    return FALSE;
-}
-
-
-/*
- * Register and unregister the custom WndProc
- */
-
-static void
-winOverrideURLButton (HWND hwnd, int id)
-{
-  WNDPROC origCB;
-  origCB = (WNDPROC)SetWindowLong (GetDlgItem (hwnd, id),
-				   GWL_WNDPROC, (LONG)winURLWndProc);
-  SetWindowLong (GetDlgItem (hwnd, id), GWL_USERDATA, (LONG)origCB);
-}
-
-static void
-winUnoverrideURLButton (HWND hwnd, int id)
-{
-  WNDPROC origCB;
-  origCB = (WNDPROC)SetWindowLong (GetDlgItem (hwnd, id),
-				   GWL_USERDATA, 0);
-  if (origCB)
-    SetWindowLong (GetDlgItem (hwnd, id), GWL_WNDPROC, (LONG)origCB);
-}
-
-
-/*
- * Center a dialog window in the desktop window
- */
-
-static void
-winCenterDialog (HWND hwndDlg)
-{
-  HWND hwndDesk; 
-  RECT rc, rcDlg, rcDesk; 
- 
-  hwndDesk = GetParent (hwndDlg);
-  if (!hwndDesk || IsIconic (hwndDesk))
-    hwndDesk = GetDesktopWindow (); 
-  
-  GetWindowRect (hwndDesk, &rcDesk); 
-  GetWindowRect (hwndDlg, &rcDlg); 
-  CopyRect (&rc, &rcDesk); 
-  
-  OffsetRect (&rcDlg, -rcDlg.left, -rcDlg.top); 
-  OffsetRect (&rc, -rc.left, -rc.top); 
-  OffsetRect (&rc, -rcDlg.right, -rcDlg.bottom); 
-  
-  SetWindowPos (hwndDlg, 
-		HWND_TOP, 
-		rcDesk.left + (rc.right / 2), 
-		rcDesk.top + (rc.bottom / 2), 
-		0, 0,
-		SWP_NOSIZE | SWP_NOZORDER); 
-}
-
-
-/*
- * Display the Exit dialog box
- */
-
-void
-winDisplayExitDialog (winPrivScreenPtr pScreenPriv)
-{
-  int i;
-  int liveClients = 0;
-
-  /* Count up running clinets (clients[0] is serverClient) */
-  for (i = 1; i < currentMaxClients; i++)
-    if (clients[i] != NullClient)	
-      liveClients++;
-#if defined(XWIN_MULTIWINDOW)
-  /* Count down server internal clients */
-  if (pScreenPriv->pScreenInfo->fMultiWindow)
-    liveClients -= 2; /* multiwindow window manager & XMsgProc  */
-#endif
-#if defined(XWIN_CLIPBOARD)
-  if (g_fClipboardStarted)
-    liveClients--; /* clipboard manager */
-#endif
-
-  /* A user reported that this sometimes drops below zero. just eye-candy. */ 
-  if (liveClients < 0)
-    liveClients = 0;      
-
-  /* Don't show the exit confirmation dialog if SilentExit is enabled */
-  if (pref.fSilentExit && liveClients <= 0)
-    {
-      if (g_hDlgExit != NULL)
-	{
-	  DestroyWindow (g_hDlgExit);
-	  g_hDlgExit = NULL;
-	}
-      PostMessage (pScreenPriv->hwndScreen, WM_GIVEUP, 0, 0);
-      return;
-    }
-
-  pScreenPriv->iConnectedClients = liveClients;
-  
-  /* Check if dialog already exists */
-  if (g_hDlgExit != NULL)
-    {
-      /* Dialog box already exists, display it */
-      ShowWindow (g_hDlgExit, SW_SHOWDEFAULT);
-
-      /* User has lost the dialog.  Show them where it is. */
-      SetForegroundWindow (g_hDlgExit);
-
-      return;
-    }
-
-  /* Create dialog box */
-  g_hDlgExit = CreateDialogParam (g_hInstance,
-				  "EXIT_DIALOG",
-				  pScreenPriv->hwndScreen,
-				  winExitDlgProc,
-				  (int) pScreenPriv);
-
-  /* Drop minimize and maximize buttons */
-  SetWindowLong (g_hDlgExit, GWL_STYLE,
-		 GetWindowLong (g_hDlgExit, GWL_STYLE)
-		 & ~(WS_MAXIMIZEBOX | WS_MINIMIZEBOX));
-  SetWindowLong (g_hDlgExit, GWL_EXSTYLE,
-		 GetWindowLong (g_hDlgExit, GWL_EXSTYLE) & ~WS_EX_APPWINDOW );
-  SetWindowPos (g_hDlgExit, HWND_TOPMOST, 0, 0, 0, 0,
-		SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE); 
- 
-  /* Show the dialog box */
-  ShowWindow (g_hDlgExit, SW_SHOW);
-  
-  /* Needed to get keyboard controls (tab, arrows, enter, esc) to work */
-  SetForegroundWindow (g_hDlgExit);
-  
-  /* Set focus to the Cancel button */
-  PostMessage (g_hDlgExit, WM_NEXTDLGCTL,
-	       (int) GetDlgItem (g_hDlgExit, IDCANCEL), TRUE);
-}
-
-#define CONNECTED_CLIENTS_FORMAT	"There are currently %d clients connected."
-
-
-/*
- * Exit dialog window procedure
- */
-
-static wBOOL CALLBACK
-winExitDlgProc (HWND hDialog, UINT message,
-		WPARAM wParam, LPARAM lParam)
-{
-  static winPrivScreenPtr	s_pScreenPriv = NULL;
-
-  /* Branch on message type */
-  switch (message)
-    {
-    case WM_INITDIALOG:
-      {
-	char			*pszConnectedClients;
-
-	/* Store pointers to private structures for future use */
-	s_pScreenPriv = (winPrivScreenPtr) lParam;
-	
-	winCenterDialog (hDialog);
-	
-	/* Set icon to standard app icon */
-	PostMessage (hDialog,
-		     WM_SETICON,
-		     ICON_SMALL,
-		     (LPARAM) LoadIcon (g_hInstance,
-					MAKEINTRESOURCE(IDI_XWIN)));
-
-	/* Format the connected clients string */
-	pszConnectedClients = Xprintf (CONNECTED_CLIENTS_FORMAT,
-            s_pScreenPriv->iConnectedClients);
-	if (!pszConnectedClients)
-	    return TRUE;
-     
-        
-	
-	/* Set the number of connected clients */
-	SetWindowText (GetDlgItem (hDialog, IDC_CLIENTS_CONNECTED),
-		       pszConnectedClients);
-	xfree (pszConnectedClients);
-      }
-      return TRUE;
-
-    case WM_COMMAND:
-      switch (LOWORD (wParam))
-	{
-	case IDOK:
-	  /* Send message to call the GiveUp function */
-	  PostMessage (s_pScreenPriv->hwndScreen, WM_GIVEUP, 0, 0);
-	  DestroyWindow (g_hDlgExit);
-	  g_hDlgExit = NULL;
-
-	  /* Fix to make sure keyboard focus isn't trapped */
-	  PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
-	  return TRUE;
-
-	case IDCANCEL:
-	  DestroyWindow (g_hDlgExit);
-	  g_hDlgExit = NULL;
-
-	  /* Fix to make sure keyboard focus isn't trapped */
-	  PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
-	  return TRUE;
-	}
-      break;
-
-    case WM_MOUSEMOVE:
-    case WM_NCMOUSEMOVE:
-      /* Show the cursor if it is hidden */
-      if (g_fSoftwareCursor && !g_fCursor)
-	{
-	  g_fCursor = TRUE;
-	  ShowCursor (TRUE);
-	}
-      return TRUE;
-
-    case WM_CLOSE:
-      DestroyWindow (g_hDlgExit);
-      g_hDlgExit = NULL;
-
-      /* Fix to make sure keyboard focus isn't trapped */
-      PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
-      return TRUE;
-    }
-
-  return FALSE;
-}
-
-
-/*
- * Display the Depth Change dialog box
- */
-
-void
-winDisplayDepthChangeDialog (winPrivScreenPtr pScreenPriv)
-{
-  /* Check if dialog already exists */
-  if (g_hDlgDepthChange != NULL)
-    {
-      /* Dialog box already exists, display it */
-      ShowWindow (g_hDlgDepthChange, SW_SHOWDEFAULT);
-
-      /* User has lost the dialog.  Show them where it is. */
-      SetForegroundWindow (g_hDlgDepthChange);
-
-      return;
-    }
-
-  /*
-   * Display a notification to the user that the visual 
-   * will not be displayed until the Windows display depth 
-   * is restored to the original value.
-   */
-  g_hDlgDepthChange = CreateDialogParam (g_hInstance,
-					 "DEPTH_CHANGE_BOX",
-					 pScreenPriv->hwndScreen,
-					 winChangeDepthDlgProc,
-					 (int) pScreenPriv);
- 
-  /* Drop minimize and maximize buttons */
-  SetWindowLong (g_hDlgDepthChange, GWL_STYLE,
-		 GetWindowLong (g_hDlgDepthChange, GWL_STYLE)
-		 & ~(WS_MAXIMIZEBOX | WS_MINIMIZEBOX));
-  SetWindowLong (g_hDlgDepthChange, GWL_EXSTYLE,
-		 GetWindowLong (g_hDlgDepthChange, GWL_EXSTYLE)
-		 & ~WS_EX_APPWINDOW );
-  SetWindowPos (g_hDlgDepthChange, 0, 0, 0, 0, 0,
-		SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOZORDER | SWP_NOSIZE); 
-
-  /* Show the dialog box */
-  ShowWindow (g_hDlgDepthChange, SW_SHOW);
-  
-  ErrorF ("winDisplayDepthChangeDialog - DialogBox returned: %d\n",
-	  (int) g_hDlgDepthChange);
-  ErrorF ("winDisplayDepthChangeDialog - GetLastError: %d\n",
-	  (int) GetLastError ());
-	      
-  /* Minimize the display window */
-  ShowWindow (pScreenPriv->hwndScreen, SW_MINIMIZE);
-}
-
-
-/*
- * Process messages for the dialog that is displayed for
- * disruptive screen depth changes. 
- */
-
-static wBOOL CALLBACK
-winChangeDepthDlgProc (HWND hwndDialog, UINT message,
-		       WPARAM wParam, LPARAM lParam)
-{
-  static winPrivScreenPtr	s_pScreenPriv = NULL;
-  static winScreenInfo		*s_pScreenInfo = NULL;
-  static ScreenPtr		s_pScreen = NULL;
-
-#if CYGDEBUG
-  winDebug ("winChangeDepthDlgProc\n");
-#endif
-
-  /* Branch on message type */
-  switch (message)
-    {
-    case WM_INITDIALOG:
-#if CYGDEBUG
-      winDebug ("winChangeDepthDlgProc - WM_INITDIALOG\n");
-#endif
-
-      /* Store pointers to private structures for future use */
-      s_pScreenPriv = (winPrivScreenPtr) lParam;
-      s_pScreenInfo = s_pScreenPriv->pScreenInfo;
-      s_pScreen = s_pScreenInfo->pScreen;
-
-#if CYGDEBUG
-      winDebug ("winChangeDepthDlgProc - WM_INITDIALOG - s_pScreenPriv: %08x, "
-	      "s_pScreenInfo: %08x, s_pScreen: %08x\n",
-	      s_pScreenPriv, s_pScreenInfo, s_pScreen);
-#endif
-
-#if CYGDEBUG
-      winDebug ("winChangeDepthDlgProc - WM_INITDIALOG - orig bpp: %d, "
-	      "last bpp: %d\n",
-	      s_pScreenInfo->dwBPP,
-	      s_pScreenPriv->dwLastWindowsBitsPixel);
-#endif
-      
-      winCenterDialog( hwndDialog );
-
-      /* Set icon to standard app icon */
-      PostMessage (hwndDialog,
-		   WM_SETICON,
-		   ICON_SMALL,
-		   (LPARAM) LoadIcon (g_hInstance, MAKEINTRESOURCE(IDI_XWIN)));
-
-      return TRUE;
-
-    case WM_DISPLAYCHANGE:
-#if CYGDEBUG
-      winDebug ("winChangeDepthDlgProc - WM_DISPLAYCHANGE - orig bpp: %d, "
-	      "last bpp: %d, new bpp: %d\n",
-	      s_pScreenInfo->dwBPP,
-	      s_pScreenPriv->dwLastWindowsBitsPixel,
-	      wParam);
-#endif
-
-      /* Dismiss the dialog if the display returns to the original depth */
-      if (wParam == s_pScreenInfo->dwBPP)
-	{
-	  ErrorF ("winChangeDelthDlgProc - wParam == s_pScreenInfo->dwBPP\n");
-
-	  /* Depth has been restored, dismiss dialog */
-	  DestroyWindow (g_hDlgDepthChange);
-	  g_hDlgDepthChange = NULL;
-
-	  /* Flag that we have a valid screen depth */
-	  s_pScreenPriv->fBadDepth = FALSE;
-	}
-      return TRUE;
-
-    case WM_COMMAND:
-      switch (LOWORD (wParam))
-	{
-	case IDOK:
-	case IDCANCEL:
-	  ErrorF ("winChangeDepthDlgProc - WM_COMMAND - IDOK or IDCANCEL\n");
-
-	  /* 
-	   * User dismissed the dialog, hide it until the
-	   * display mode is restored.
-	   */
-	  ShowWindow (g_hDlgDepthChange, SW_HIDE);
-	  return TRUE;
-	}
-      break;
-
-    case WM_CLOSE:
-      ErrorF ("winChangeDepthDlgProc - WM_CLOSE\n");
-
-      DestroyWindow (g_hDlgAbout);
-      g_hDlgAbout = NULL;
-
-      /* Fix to make sure keyboard focus isn't trapped */
-      PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
-      return TRUE;
-    }
-
-  return FALSE;
-}
-
-
-/*
- * Display the About dialog box
- */
-
-void
-winDisplayAboutDialog (winPrivScreenPtr pScreenPriv)
-{
-  /* Check if dialog already exists */
-  if (g_hDlgAbout != NULL)
-    {
-      /* Dialog box already exists, display it */
-      ShowWindow (g_hDlgAbout, SW_SHOWDEFAULT);
-
-      /* User has lost the dialog.  Show them where it is. */
-      SetForegroundWindow (g_hDlgAbout);
-
-      return;
-    }
-
-  /*
-   * Display the about box
-   */
-  g_hDlgAbout = CreateDialogParam (g_hInstance,
-				   "ABOUT_BOX",
-				   pScreenPriv->hwndScreen,
-				   winAboutDlgProc,
-				   (int) pScreenPriv);
- 
-  /* Drop minimize and maximize buttons */
-  SetWindowLong (g_hDlgAbout, GWL_STYLE,
-		 GetWindowLong (g_hDlgAbout, GWL_STYLE)
-		 & ~(WS_MAXIMIZEBOX | WS_MINIMIZEBOX));
-  SetWindowLong (g_hDlgAbout, GWL_EXSTYLE,
-		 GetWindowLong (g_hDlgAbout, GWL_EXSTYLE) & ~WS_EX_APPWINDOW);
-  SetWindowPos (g_hDlgAbout, 0, 0, 0, 0, 0,
-		SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE); 
-
-  /* Show the dialog box */
-  ShowWindow (g_hDlgAbout, SW_SHOW);
-
-  /* Needed to get keyboard controls (tab, arrows, enter, esc) to work */
-  SetForegroundWindow (g_hDlgAbout);
-  
-  /* Set focus to the OK button */
-  PostMessage (g_hDlgAbout, WM_NEXTDLGCTL,
-	       (int) GetDlgItem (g_hDlgAbout, IDOK), TRUE);
-}
-
-
-/*
- * Process messages for the about dialog.
- */
-
-static wBOOL CALLBACK
-winAboutDlgProc (HWND hwndDialog, UINT message,
-		 WPARAM wParam, LPARAM lParam)
-{
-  static winPrivScreenPtr	s_pScreenPriv = NULL;
-  static winScreenInfo		*s_pScreenInfo = NULL;
-  static ScreenPtr		s_pScreen = NULL;
-
-#if CYGDEBUG
-  winDebug ("winAboutDlgProc\n");
-#endif
-
-  /* Branch on message type */
-  switch (message)
-    {
-    case WM_INITDIALOG:
-#if CYGDEBUG
-      winDebug ("winAboutDlgProc - WM_INITDIALOG\n");
-#endif
-
-      /* Store pointers to private structures for future use */
-      s_pScreenPriv = (winPrivScreenPtr) lParam;
-      s_pScreenInfo = s_pScreenPriv->pScreenInfo;
-      s_pScreen = s_pScreenInfo->pScreen;
-
-      winCenterDialog (hwndDialog);
-
-      /* Set icon to standard app icon */
-      PostMessage (hwndDialog,
-		   WM_SETICON,
-		   ICON_SMALL,
-		   (LPARAM) LoadIcon (g_hInstance, MAKEINTRESOURCE(IDI_XWIN)));
-
-      /* Override the URL buttons */
-      winOverrideURLButton (hwndDialog, ID_ABOUT_CHANGELOG);
-      winOverrideURLButton (hwndDialog, ID_ABOUT_WEBSITE);
-      winOverrideURLButton (hwndDialog, ID_ABOUT_UG);
-      winOverrideURLButton (hwndDialog, ID_ABOUT_FAQ);
-
-      return TRUE;
-
-    case WM_DRAWITEM:
-      /* Draw the URL buttons as needed */
-      winDrawURLWindow (lParam);
-      return TRUE;
-
-    case WM_MOUSEMOVE:
-    case WM_NCMOUSEMOVE:
-      /* Show the cursor if it is hidden */
-      if (g_fSoftwareCursor && !g_fCursor)
-	{
-	  g_fCursor = TRUE;
-	  ShowCursor (TRUE);
-	}
-      return TRUE;
-
-    case WM_COMMAND:
-      switch (LOWORD (wParam))
-	{
-	case IDOK:
-	case IDCANCEL:
-	  ErrorF ("winAboutDlgProc - WM_COMMAND - IDOK or IDCANCEL\n");
-
-	  DestroyWindow (g_hDlgAbout);
-	  g_hDlgAbout = NULL;
-
-	  /* Fix to make sure keyboard focus isn't trapped */
-	  PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
-
-	  /* Restore window procedures for URL buttons */
-	  winUnoverrideURLButton (hwndDialog, ID_ABOUT_CHANGELOG);
-	  winUnoverrideURLButton (hwndDialog, ID_ABOUT_WEBSITE);
-	  winUnoverrideURLButton (hwndDialog, ID_ABOUT_UG);
-	  winUnoverrideURLButton (hwndDialog, ID_ABOUT_FAQ);
-
-	  return TRUE;
-
-	case ID_ABOUT_CHANGELOG:
-	  {
-	    int			iReturn;
-#ifdef __CYGWIN__
-	    const char *	pszCygPath = "/usr/X11R6/share/doc/"
-	      "xorg-x11-xwin/changelog.html";
-	    char		pszWinPath[MAX_PATH + 1];
-
-	    /* Convert the POSIX path to a Win32 path */
-	    cygwin_conv_to_win32_path (pszCygPath, pszWinPath);
-#else
-	    const char *	pszWinPath = "http://x.cygwin.com/"
-		    "devel/server/changelog.html";
-#endif
-	    
-	    iReturn = (int) ShellExecute (NULL,
-					  "open",
-					  pszWinPath,
-					  NULL,
-					  NULL,
-					  SW_MAXIMIZE);
-	    if (iReturn < 32)
-	      {
-		ErrorF ("winAboutDlgProc - WM_COMMAND - ID_ABOUT_CHANGELOG - "
-			"ShellExecute failed: %d\n",
-			iReturn);
-	      }	    
-	  }
-	  return TRUE;
-
-	case ID_ABOUT_WEBSITE:
-	  {
-	    const char *	pszPath = "http://x.cygwin.com/";
-	    int			iReturn;
-	    
-	    iReturn = (int) ShellExecute (NULL,
-					  "open",
-					  pszPath,
-					  NULL,
-					  NULL,
-					  SW_MAXIMIZE);
-	    if (iReturn < 32)
-	      {
-		ErrorF ("winAboutDlgProc - WM_COMMAND - ID_ABOUT_WEBSITE - "
-			"ShellExecute failed: %d\n",
-			iReturn);
-	      }	    
-	  }
-	  return TRUE;
-
-	case ID_ABOUT_UG:
-	  {
-	    const char *	pszPath = "http://x.cygwin.com/docs/ug/";
-	    int			iReturn;
-	    
-	    iReturn = (int) ShellExecute (NULL,
-					  "open",
-					  pszPath,
-					  NULL,
-					  NULL,
-					  SW_MAXIMIZE);
-	    if (iReturn < 32)
-	      {
-		ErrorF ("winAboutDlgProc - WM_COMMAND - ID_ABOUT_UG - "
-			"ShellExecute failed: %d\n",
-			iReturn);
-	      }	    
-	  }
-	  return TRUE;
-
-	case ID_ABOUT_FAQ:
-	  {
-	    const char *	pszPath = "http://x.cygwin.com/docs/faq/";
-	    int			iReturn;
-	    
-	    iReturn = (int) ShellExecute (NULL,
-					  "open",
-					  pszPath,
-					  NULL,
-					  NULL,
-					  SW_MAXIMIZE);
-	    if (iReturn < 32)
-	      {
-		ErrorF ("winAboutDlgProc - WM_COMMAND - ID_ABOUT_FAQ - "
-			"ShellExecute failed: %d\n",
-			iReturn);
-	      }	    
-	  }
-	  return TRUE;
-	}
-      break;
-
-    case WM_CLOSE:
-      ErrorF ("winAboutDlgProc - WM_CLOSE\n");
-
-      DestroyWindow (g_hDlgAbout);
-      g_hDlgAbout = NULL;
-
-      /* Fix to make sure keyboard focus isn't trapped */
-      PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);
-
-      /* Restore window procedures for URL buttons */
-      winUnoverrideURLButton (hwndDialog, ID_ABOUT_CHANGELOG);
-      winUnoverrideURLButton (hwndDialog, ID_ABOUT_WEBSITE);
-      winUnoverrideURLButton (hwndDialog, ID_ABOUT_UG);
-      winUnoverrideURLButton (hwndDialog, ID_ABOUT_FAQ);
-
-      return TRUE;
-    }
-
-  return FALSE;
-}
diff --git a/hw/xwin/winengine.c b/hw/xwin/winengine.c
deleted file mode 100644
index f0bc671..0000000
--- a/hw/xwin/winengine.c
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winmsg.h"
-
-
-/*
- * External global variables
- */
-
-extern const GUID _IID_IDirectDraw4;
-
-
-/*
- * Detect engines supported by current Windows version
- * DirectDraw version and hardware
- */
-
-void
-winDetectSupportedEngines ()
-{
-  OSVERSIONINFO		osvi;
-
-  /* Initialize the engine support flags */
-  g_dwEnginesSupported = WIN_SERVER_SHADOW_GDI;
-
-#ifdef XWIN_NATIVEGDI
-  g_dwEnginesSupported |= WIN_SERVER_NATIVE_GDI;
-#endif
-
-  /* Get operating system version information */
-  ZeroMemory (&osvi, sizeof (osvi));
-  osvi.dwOSVersionInfoSize = sizeof (osvi);
-  GetVersionEx (&osvi);
-
-  /* Branch on platform ID */
-  switch (osvi.dwPlatformId)
-    {
-    case VER_PLATFORM_WIN32_NT:
-      /* Engine 4 is supported on NT only */
-      winErrorFVerb (2, "winDetectSupportedEngines - Windows NT/2000/XP\n");
-      break;
-
-    case VER_PLATFORM_WIN32_WINDOWS:
-      /* Engine 4 is supported on NT only */
-      winErrorFVerb (2, "winDetectSupportedEngines - Windows 95/98/Me\n");
-      break;
-    }
-
-  /* Do we have DirectDraw? */
-  if (g_hmodDirectDraw != NULL)
-    {
-      LPDIRECTDRAW	lpdd = NULL;
-      LPDIRECTDRAW4	lpdd4 = NULL;
-      HRESULT		ddrval;
-
-      /* Was the DirectDrawCreate function found? */
-      if (g_fpDirectDrawCreate == NULL)
-	{
-	  /* No DirectDraw support */
-	  return;
-	}
-
-      /* DirectDrawCreate exists, try to call it */
-      /* Create a DirectDraw object, store the address at lpdd */
-      ddrval = (*g_fpDirectDrawCreate) (NULL,
-					(void**) &lpdd,
-					NULL);
-      if (FAILED (ddrval))
-	{
-	  /* No DirectDraw support */
-	  winErrorFVerb (2, "winDetectSupportedEngines - DirectDraw not installed\n");
-	  return;
-	}
-      else
-	{
-	  /* We have DirectDraw */
-	  winErrorFVerb (2, "winDetectSupportedEngines - DirectDraw installed\n");
-	  g_dwEnginesSupported |= WIN_SERVER_SHADOW_DD;
-
-#ifdef XWIN_PRIMARYFB
-	  /* Allow PrimaryDD engine if NT */
-	  if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
-	    {
-	      g_dwEnginesSupported |= WIN_SERVER_PRIMARY_DD;
-	      winErrorFVerb (2, "winDetectSupportedEngines - Allowing PrimaryDD\n");
-	    }
-#endif
-	}
-      
-      /* Try to query for DirectDraw4 interface */
-      ddrval = IDirectDraw_QueryInterface (lpdd,
-					   &IID_IDirectDraw4,
-					   (LPVOID*) &lpdd4);
-      if (SUCCEEDED (ddrval))
-	{
-	  /* We have DirectDraw4 */
-	  winErrorFVerb (2, "winDetectSupportedEngines - DirectDraw4 installed\n");
-	  g_dwEnginesSupported |= WIN_SERVER_SHADOW_DDNL;
-	}
-
-      /* Cleanup DirectDraw interfaces */
-      if (lpdd4 != NULL)
-	IDirectDraw_Release (lpdd4);
-      if (lpdd != NULL)
-	IDirectDraw_Release (lpdd);
-    }
-
-  winErrorFVerb (2, "winDetectSupportedEngines - Returning, supported engines %08x\n",
-	  (unsigned int) g_dwEnginesSupported);
-}
-
-
-/*
- * Set the engine type, depending on the engines
- * supported for this screen, and whether the user
- * suggested an engine type
- */
-
-Bool
-winSetEngine (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  HDC			hdc;
-  DWORD			dwBPP;
-
-  /* Get a DC */
-  hdc = GetDC (NULL);
-  if (hdc == NULL)
-    {
-      ErrorF ("winSetEngine - Couldn't get an HDC\n");
-      return FALSE;
-    }
-
-  /*
-   * pScreenInfo->dwBPP may be 0 to indicate that the current screen
-   * depth is to be used.  Thus, we must query for the current display
-   * depth here.
-   */
-  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
-
-  /* Release the DC */
-  ReleaseDC (NULL, hdc);
-  hdc = NULL;
-
-  /* ShadowGDI is the only engine that supports windowed PseudoColor */
-  if (dwBPP == 8 && !pScreenInfo->fFullScreen)
-    {
-      winErrorFVerb (2, "winSetEngine - Windowed && PseudoColor => ShadowGDI\n");
-      pScreenInfo->dwEngine = WIN_SERVER_SHADOW_GDI;
-
-      /* Set engine function pointers */
-      winSetEngineFunctionsShadowGDI (pScreen);
-      return TRUE;
-    }
-
-  /* ShadowGDI is the only engine that supports Multi Window Mode */
-  if (
-#ifdef XWIN_MULTIWINDOWEXTWM
-      pScreenInfo->fMWExtWM
-#else
-      FALSE
-#endif
-#ifdef XWIN_MULTIWINDOW
-      || pScreenInfo->fMultiWindow
-#else
-      || FALSE
-#endif
-      )
-    {
-      winErrorFVerb (2, "winSetEngine - Multi Window or Rootless => ShadowGDI\n");
-      pScreenInfo->dwEngine = WIN_SERVER_SHADOW_GDI;
-
-      /* Set engine function pointers */
-      winSetEngineFunctionsShadowGDI (pScreen);
-      return TRUE;
-    }
-
-  /* If the user's choice is supported, we'll use that */
-  if (g_dwEnginesSupported & pScreenInfo->dwEnginePreferred)
-    {
-      winErrorFVerb (2, "winSetEngine - Using user's preference: %d\n",
-	      (int) pScreenInfo->dwEnginePreferred);
-      pScreenInfo->dwEngine = pScreenInfo->dwEnginePreferred;
-
-      /* Setup engine function pointers */
-      switch (pScreenInfo->dwEngine)
-	{
-	case WIN_SERVER_SHADOW_GDI:
-	  winSetEngineFunctionsShadowGDI (pScreen);
-	  break;
-	case WIN_SERVER_SHADOW_DD:
-	  winSetEngineFunctionsShadowDD (pScreen);
-	  break;
-	case WIN_SERVER_SHADOW_DDNL:
-	  winSetEngineFunctionsShadowDDNL (pScreen);
-	  break;
-#ifdef XWIN_PRIMARYFB
-	case WIN_SERVER_PRIMARY_DD:
-	  winSetEngineFunctionsPrimaryDD (pScreen);
-	  break;
-#endif
-#ifdef XWIN_NATIVEGDI
-	case WIN_SERVER_NATIVE_GDI:
-	  winSetEngineFunctionsNativeGDI (pScreen);
-	  break;
-#endif
-	default:
-	  FatalError ("winSetEngine - Invalid engine type\n");
-	}
-      return TRUE;
-    }
-
-  /* ShadowDDNL has good performance, so why not */
-  if (g_dwEnginesSupported & WIN_SERVER_SHADOW_DDNL)
-    {
-      winErrorFVerb (2, "winSetEngine - Using Shadow DirectDraw NonLocking\n");
-      pScreenInfo->dwEngine = WIN_SERVER_SHADOW_DDNL;
-
-      /* Set engine function pointers */
-      winSetEngineFunctionsShadowDDNL (pScreen);
-      return TRUE;
-    }
-
-  /* ShadowDD is next in line */
-  if (g_dwEnginesSupported & WIN_SERVER_SHADOW_DD)
-    {
-      winErrorFVerb (2, "winSetEngine - Using Shadow DirectDraw\n");
-      pScreenInfo->dwEngine = WIN_SERVER_SHADOW_DD;
-
-      /* Set engine function pointers */
-      winSetEngineFunctionsShadowDD (pScreen);
-      return TRUE;
-    }
-
-  /* ShadowGDI is next in line */
-  if (g_dwEnginesSupported & WIN_SERVER_SHADOW_GDI)
-    {
-      winErrorFVerb (2, "winSetEngine - Using Shadow GDI DIB\n");
-      pScreenInfo->dwEngine = WIN_SERVER_SHADOW_GDI;
-
-      /* Set engine function pointers */
-      winSetEngineFunctionsShadowGDI (pScreen);
-      return TRUE;
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Get procedure addresses for DirectDrawCreate and DirectDrawCreateClipper
- */
-
-Bool
-winGetDDProcAddresses ()
-{
-  Bool			fReturn = TRUE;
-  
-  /* Load the DirectDraw library */
-  g_hmodDirectDraw = LoadLibraryEx ("ddraw.dll", NULL, 0);
-  if (g_hmodDirectDraw == NULL)
-    {
-      ErrorF ("winGetDDProcAddresses - Could not load ddraw.dll\n");
-      fReturn = TRUE;
-      goto winGetDDProcAddresses_Exit;
-    }
-
-  /* Try to get the DirectDrawCreate address */
-  g_fpDirectDrawCreate = GetProcAddress (g_hmodDirectDraw,
-					 "DirectDrawCreate");
-  if (g_fpDirectDrawCreate == NULL)
-    {
-      ErrorF ("winGetDDProcAddresses - Could not get DirectDrawCreate "
-	      "address\n");
-      fReturn = TRUE;
-      goto winGetDDProcAddresses_Exit;
-    }
-
-  /* Try to get the DirectDrawCreateClipper address */
-  g_fpDirectDrawCreateClipper = GetProcAddress (g_hmodDirectDraw,
-						"DirectDrawCreateClipper");
-  if (g_fpDirectDrawCreateClipper == NULL)
-    {
-      ErrorF ("winGetDDProcAddresses - Could not get "
-	      "DirectDrawCreateClipper address\n");
-      fReturn = FALSE;
-      goto winGetDDProcAddresses_Exit;
-    }
-
-  /*
-   * Note: Do not unload ddraw.dll here.  Do it in GiveUp
-   */
-
- winGetDDProcAddresses_Exit:
-  /* Unload the DirectDraw library if we failed to initialize */
-  if (!fReturn && g_hmodDirectDraw != NULL)
-    {
-      FreeLibrary (g_hmodDirectDraw);
-      g_hmodDirectDraw = NULL;
-    }
-  
-  return fReturn;
-}
diff --git a/hw/xwin/winerror.c b/hw/xwin/winerror.c
deleted file mode 100644
index 7d29213..0000000
--- a/hw/xwin/winerror.c
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#ifdef XVENDORNAME
-#define VENDOR_STRING XVENDORNAME
-#define VERSION_STRING XORG_RELEASE
-#define VENDOR_CONTACT BUILDERADDR
-#endif
-
-#include "win.h"
-
-/* References to external symbols */
-extern char *		g_pszCommandLine;
-extern char *		g_pszLogFile;
-extern Bool		g_fSilentFatalError;
-
-
-#ifdef DDXOSVERRORF
-/* Prototype */
-void
-OsVendorVErrorF (const char *pszFormat, va_list va_args);
-
-void
-OsVendorVErrorF (const char *pszFormat, va_list va_args)
-{
-#if defined(XWIN_CLIPBOARD) || defined (XWIN_MULTIWINDOW)
-  /* make sure the clipboard and multiwindow threads do not interfere the
-   * main thread */
-  static pthread_mutex_t	s_pmPrinting = PTHREAD_MUTEX_INITIALIZER;
-
-  /* Lock the printing mutex */
-  pthread_mutex_lock (&s_pmPrinting);
-#endif
-
-  /* Print the error message to a log file, could be stderr */
-  LogVWrite (0, pszFormat, va_args);
-
-#if defined(XWIN_CLIPBOARD) || defined (XWIN_MULTIWINDOW)
-  /* Unlock the printing mutex */
-  pthread_mutex_unlock (&s_pmPrinting);
-#endif
-}
-#endif
-
-
-/*
- * os/util.c/FatalError () calls our vendor ErrorF, so the message
- * from a FatalError will be logged.  Thus, the message for the
- * fatal error is not passed to this function.
- *
- * Attempt to do last-ditch, safe, important cleanup here.
- */
-#ifdef DDXOSFATALERROR
-void
-OsVendorFatalError (void)
-{
-  /* Don't give duplicate warning if UseMsg was called */
-  if (g_fSilentFatalError)
-    return;
-
-  winMessageBoxF (
-          "A fatal error has occurred and " PROJECT_NAME " will now exit.\n" \
-		  "Please open %s for more information.\n",
-		  MB_ICONERROR, (g_pszLogFile?g_pszLogFile:"the logfile"));
-}
-#endif
-
-
-/*
- * winMessageBoxF - Print a formatted error message in a useful
- * message box.
- */
-
-void
-winMessageBoxF (const char *pszError, UINT uType, ...)
-{
-  char *	pszErrorF = NULL;
-  char *	pszMsgBox = NULL;
-  va_list	args;
-
-  va_start(args, uType);
-  pszErrorF = Xvprintf(pszError, args);
-  va_end(args);
-  if (!pszErrorF)
-    goto winMessageBoxF_Cleanup;
-
-#define MESSAGEBOXF \
-	"%s\n" \
-	"Vendor: %s\n" \
-	"Release: %s\n" \
-	"Contact: %s\n" \
-	"XWin was started with the following command-line:\n\n" \
-	"%s\n"
-
-  pszMsgBox = Xprintf (MESSAGEBOXF,
-	   pszErrorF, VENDOR_STRING, VERSION_STRING, VENDOR_CONTACT,
-	   g_pszCommandLine);
-  if (!pszMsgBox)
-    goto winMessageBoxF_Cleanup;
-
-  /* Display the message box string */
-  MessageBox (NULL,
-	      pszMsgBox,
-	      PROJECT_NAME,
-	      MB_OK | uType);
-
- winMessageBoxF_Cleanup:
-  if (pszErrorF)
-    xfree (pszErrorF);
-  if (pszMsgBox)
-    xfree (pszMsgBox);
-#undef MESSAGEBOXF
-}
diff --git a/hw/xwin/winfillsp.c b/hw/xwin/winfillsp.c
deleted file mode 100644
index 702f34f..0000000
--- a/hw/xwin/winfillsp.c
+++ /dev/null
@@ -1,866 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Harold L Hunt II
- * 		Alan Hourihane <alanh at fairlite.demon.co.uk>
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-extern void ROP16(HDC hdc, int rop);
-
-#define TRANSLATE_COLOR(color)						\
-{									\
-  if (pDrawable->depth == 15)						\
-    color = ((color & 0x1F) << 19) | ((color & 0x03E0) << 6) |		\
-      ((color & 0xF800) >> 8);						\
-  else if (pDrawable->depth == 16)					\
-    color = ((color & 0x1F) << 19) | ((color & 0x07E0) << 5) |		\
-      ((color & 0xF800) >> 8);						\
-  else if (pDrawable->depth == 24 || pDrawable->depth == 32)		\
-    color = ((color & 0xFF) << 16) | (color & 0xFF00) |			\
-      ((color & 0xFF0000) >> 16);					\
-}
-
-/* See Porting Layer Definition - p. 54 */
-void
-winFillSpansNativeGDI (DrawablePtr	pDrawable,
-		       GCPtr		pGC,
-		       int		iSpans,
-		       DDXPointPtr	pPoints,
-		       int		*piWidths,
-		       int		fSorted)
-{
-  winGCPriv(pGC);
-  HBITMAP		hbmpOrig = NULL, hbmpOrigStipple = NULL;
-  HBITMAP		hPenOrig = NULL;
-  HBITMAP		hBitmap = NULL;
-  PixmapPtr		pPixmap = NULL;
-  winPrivPixmapPtr	pPixmapPriv = NULL;
-  PixmapPtr		pStipple = NULL;
-  winPrivPixmapPtr	pStipplePriv = NULL;
-  PixmapPtr		pTile = NULL;
-  winPrivPixmapPtr	pTilePriv = NULL;
-  HDC			hdcStipple = NULL, hdcTile = NULL;
-  HPEN			hPen = NULL;
-  int			iX;
-  int			fg, bg;
-  RegionPtr	    	pClip = pGC->pCompositeClip;
-  BoxPtr	    	pextent, pbox;
-  int		    	nbox;
-  int		    	extentX1, extentX2, extentY1, extentY2;
-  int		    	fullX1, fullX2, fullY1;
-  HRGN			hrgn = NULL, combined = NULL;
-
-  nbox = REGION_NUM_RECTS (pClip);
-  pbox = REGION_RECTS (pClip);
-
-  if (!nbox) return;
-
-  combined = CreateRectRgn (pbox->x1, pbox->y1, pbox->x2, pbox->y2);
-  nbox--; pbox++;
-
-  while (nbox--)
-    {
-      hrgn = CreateRectRgn (pbox->x1, pbox->y1, pbox->x2, pbox->y2);
-      CombineRgn (combined, combined, hrgn, RGN_OR);
-      DeleteObject (hrgn);
-      hrgn = NULL;
-      pbox++;
-    }
-
-  pextent = REGION_EXTENTS (pGC->pScreen, pClip);
-  extentX1 = pextent->x1;
-  extentY1 = pextent->y1;
-  extentX2 = pextent->x2;
-  extentY2 = pextent->y2;
-
-  /* Branch on the type of drawable we have */
-  switch (pDrawable->type)
-    {
-    case DRAWABLE_PIXMAP:
-
-      SelectClipRgn (pGCPriv->hdcMem, combined);
-      DeleteObject (combined);
-      combined = NULL;
-
-      /* Get a pixmap pointer from the drawable pointer, and fetch privates  */
-      pPixmap = (PixmapPtr) pDrawable;
-      pPixmapPriv = winGetPixmapPriv (pPixmap);
-
-      /* Select the drawable pixmap into memory hdc */
-      hbmpOrig = SelectObject (pGCPriv->hdcMem, pPixmapPriv->hBitmap);
-      if (hbmpOrig == NULL)
-	FatalError ("winFillSpans - DRAWABLE_PIXMAP - "
-		    "SelectObject () failed on\n\tpPixmapPriv->hBitmap: "
-		    "%08x\n", (unsigned int) pPixmapPriv->hBitmap);
-      
-      /* Branch on the fill type */
-      switch (pGC->fillStyle)
-	{
-	case FillSolid:
-
-          ROP16 (pGCPriv->hdcMem, pGC->alu);
-
-	  if (pDrawable->depth == 1) 
-	    {
-	      if (pGC->fgPixel == 0)
-		hPenOrig = SelectObject (pGCPriv->hdcMem, 
-					 GetStockObject (BLACK_PEN));
-	      else
-		hPenOrig = SelectObject (pGCPriv->hdcMem,
-					 GetStockObject (WHITE_PEN));
-	    } 
-	  else 
-	    {
-	      fg = pGC->fgPixel;
-	      TRANSLATE_COLOR (fg);
-	      hPen = CreatePen (PS_SOLID, 0, fg);
-	      hPenOrig = SelectObject (pGCPriv->hdcMem, hPen);
-	    }
-    	
-	  while (iSpans--)
-	    {
-	      fullX1 = pPoints->x;
-	      fullY1 = pPoints->y;
-	      fullX2 = fullX1 + (int) *piWidths;
-	      pPoints++;
-	      piWidths++;
-	
-	      if (fullY1 < extentY1 || extentY2 <= fullY1)
-		continue;
-	
-	      if (fullX1 < extentX1)
-		fullX1 = extentX1;
-	      if (fullX2 > extentX2)
-		fullX2 = extentX2;
-	
-	      if (fullX1 >= fullX2)
-		continue;
-	
-	      MoveToEx (pGCPriv->hdcMem, fullX1, fullY1, NULL);
-	      LineTo (pGCPriv->hdcMem, fullX2, fullY1);
-	    }
-
-          SetROP2 (pGCPriv->hdcMem, R2_COPYPEN);
-
-	  /* Give back the Pen */
-	  SelectObject (pGCPriv->hdcMem, hPenOrig);
-
-	  if (pDrawable->depth != 1)
-	    DeleteObject (hPen);
-	  break;
-
-	case FillOpaqueStippled:
-
-	  pStipple = pGC->stipple;
-	  pStipplePriv = winGetPixmapPriv (pStipple);
-
-	  /* Create a device-dependent bitmap for the stipple */
-	  hBitmap = CreateDIBitmap (pGCPriv->hdcMem,
-				    (BITMAPINFOHEADER *)pStipplePriv->pbmih,
-				    CBM_INIT,
-				    pStipplePriv->pbBits,
-				    (BITMAPINFO *)pStipplePriv->pbmih,
-				    DIB_RGB_COLORS);
-
-	  /* Create a memory DC to hold the stipple */
-	  hdcStipple = CreateCompatibleDC (pGCPriv->hdcMem);
-
-	  /* Select the stipple bitmap into the stipple DC */
-	  hbmpOrigStipple = SelectObject (hdcStipple, hBitmap);
-	  if (hbmpOrigStipple == NULL)
-	    FatalError ("winFillSpans () - DRAWABLE_PIXMAP - FillStippled - "
-			"SelectObject () failed on hbmpOrigStipple\n");
-
-	  /* Make a temporary copy of the foreground and background colors */
-   	  bg = pGC->bgPixel;
-   	  fg = pGC->fgPixel;
-
-	  /* Translate the depth-dependent colors to Win32 COLORREFs */
-	  TRANSLATE_COLOR (fg);
-	  TRANSLATE_COLOR (bg);
-	  SetTextColor (pGCPriv->hdcMem, fg);
-	  SetBkColor (pGCPriv->hdcMem, bg);
-
-	  while (iSpans--)
-	    {
-	      int width = pStipple->drawable.width;
-	      fullX1 = pPoints->x;
-	      fullY1 = pPoints->y;
-	      fullX2 = fullX1 + (int) *piWidths;
-	      pPoints++;
-	      piWidths++;
-	
-	      if (fullY1 < extentY1 || extentY2 <= fullY1)
-		continue;
-	
-	      if (fullX1 < extentX1)
-		fullX1 = extentX1;
-	      if (fullX2 > extentX2)
-		fullX2 = extentX2;
-	
-	      if (fullX1 >= fullX2)
-		continue;
-	
-	      for (iX = fullX1; iX < fullX2; iX += width)
-		{
-		  int xoffset;
-
-		  if ((iX + pStipple->drawable.width) > fullX2)
-		    width = fullX2 - iX;
-		  else
-		    width = pStipple->drawable.width;
-
-		  if (iX == fullX1)
-		    xoffset = (fullX1 - (pDrawable->x + (pGC->patOrg.x % pStipple->drawable.width) - pStipple->drawable.width)) % pStipple->drawable.width;
-		  else
-		    xoffset = 0;
-
-		  if (xoffset + width > pStipple->drawable.width)
-		    width = pStipple->drawable.width - xoffset;
-
-		  BitBlt (pGCPriv->hdcMem,
-			  iX, fullY1,
-			  width, 1,
-			  hdcStipple,
-			  xoffset,
-			  (fullY1 - (pDrawable->y + (pGC->patOrg.y % pStipple->drawable.height) - pStipple->drawable.height)) % pStipple->drawable.height,
-			  g_copyROP[pGC->alu]);
-		}
-	    }
-
-	  /* Clear the stipple HDC */
-	  SelectObject (hdcStipple, hbmpOrigStipple);
-	  DeleteDC (hdcStipple);
-
-	  /* Delete the device dependent stipple bitmap */
-	  DeleteObject (hBitmap);
-
-	  break;
-	case FillStippled:
-
-	  pStipple = pGC->stipple;
-	  pStipplePriv = winGetPixmapPriv (pStipple);
-
-	  /* Create a device-dependent bitmap for the stipple */
-	  hBitmap = CreateDIBitmap (pGCPriv->hdcMem,
-				    (BITMAPINFOHEADER *)pStipplePriv->pbmih,
-				    CBM_INIT,
-				    pStipplePriv->pbBits,
-				    (BITMAPINFO *)pStipplePriv->pbmih,
-				    DIB_RGB_COLORS);
-
-	  /* Create a memory DC to hold the stipple */
-	  hdcStipple = CreateCompatibleDC (pGCPriv->hdcMem);
-
-	  /* Select the stipple bitmap into the stipple DC */
-	  hbmpOrigStipple = SelectObject (hdcStipple, hBitmap);
-	  if (hbmpOrigStipple == NULL)
-	    FatalError ("winFillSpans () - DRAWABLE_PIXMAP - FillStippled - "
-			"SelectObject () failed on hbmpOrigStipple\n");
-
-	  /* Make a temporary copy of the foreground and background colors */
-   	  bg = pGC->bgPixel;
-   	  fg = pGC->fgPixel;
-
-	  /* Translate the depth-dependent colors to Win32 COLORREFs */
-	  TRANSLATE_COLOR (fg);
-	  TRANSLATE_COLOR (bg);
-
-	  /* this is fudgy, we should only invert on the last one
-	   * We need to get the black/white pixels right in the
-	   * colormap. But yeah ! it's working.. 
-	   */
-	  if (pGC->bgPixel != -1 && pGC->fgPixel != -1) 
-	    {
-	      SetTextColor (pGCPriv->hdcMem, fg);
-	      SetBkColor (pGCPriv->hdcMem, bg);
-	      BitBlt (hdcStipple,
-		      0, 0,
-		      pStipple->drawable.width, pStipple->drawable.height,
-		      hdcStipple,
-		      0, 0,
-		      0x330008);
-	    } 
-	  else if (pGC->bgPixel == -1) 
-	    {
-	      SetTextColor (pGCPriv->hdcMem, fg);
-	      SetBkMode (pGCPriv->hdcMem, TRANSPARENT);
-	      BitBlt (hdcStipple,
-		      0, 0,
-		      pStipple->drawable.width, pStipple->drawable.height,
-		      hdcStipple,
-		      0, 0,
-		      0x330008);
-	    } 
-	  else if (pGC->fgPixel == -1) 
-	    {
-	      SetTextColor (pGCPriv->hdcMem, bg);
-	      SetBkMode (pGCPriv->hdcMem, TRANSPARENT);
-#if 0
-	      BitBlt (hdcStipple,
-		      0, 0,
-		      pStipple->drawable.width, pStipple->drawable.height,
-		      hdcStipple,
-		      0, 0,
-		      0x330008);
-#endif
-	    }
-
-	  while (iSpans--)
-	    {
-	      int width = pStipple->drawable.width;
-	      fullX1 = pPoints->x;
-	      fullY1 = pPoints->y;
-	      fullX2 = fullX1 + (int) *piWidths;
-	      pPoints++;
-	      piWidths++;
-	
-	      if (fullY1 < extentY1 || extentY2 <= fullY1)
-		continue;
-	
-	      if (fullX1 < extentX1)
-		fullX1 = extentX1;
-	      if (fullX2 > extentX2)
-		fullX2 = extentX2;
-	
-	      if (fullX1 >= fullX2)
-		continue;
-	
-	      for (iX = fullX1; iX < fullX2; iX += width)
-		{
-		  int xoffset;
-
-		  if ((iX + pStipple->drawable.width) > fullX2)
-		    width = fullX2 - iX;
-		  else
-		    width = pStipple->drawable.width;
-
-		  if (iX == fullX1)
-		    xoffset = (fullX1 - (pDrawable->x + (pGC->patOrg.x % pStipple->drawable.width) - pStipple->drawable.width)) % pStipple->drawable.width;
-		  else
-		    xoffset = 0;
-
-		  if (xoffset + width > pStipple->drawable.width)
-		    width = pStipple->drawable.width - xoffset;
-
-		  BitBlt (pGCPriv->hdcMem,
-		          iX, fullY1,
-		          width, 1,
-		          hdcStipple,
-			  xoffset,
-			  (fullY1 - (pDrawable->y + (pGC->patOrg.y % pStipple->drawable.height) - pStipple->drawable.height)) % pStipple->drawable.height,
-			  g_copyROP[pGC->alu]);
-		}
-	    }
-
-	  /* Clear the stipple HDC */
-	  SelectObject (hdcStipple, hbmpOrigStipple);
-	  DeleteDC (hdcStipple);
-
-	  /* Delete the device dependent stipple bitmap */
-	  DeleteObject (hBitmap);
-
-	  /* Restore the background mode */
-	  SetBkMode (pGCPriv->hdcMem, OPAQUE);
-	  break;
-
-	case FillTiled:
-
-	  /* Get a pixmap pointer from the tile pointer, and fetch privates  */
-	  pTile = (PixmapPtr) pGC->tile.pixmap;
-	  pTilePriv = winGetPixmapPriv (pTile);
-
-	  /* Create a memory DC to hold the tile */
-	  hdcTile = CreateCompatibleDC (pGCPriv->hdcMem);
-
-	  /* Select the tile into a DC */
-	  hbmpOrig = SelectObject (hdcTile, pTilePriv->hBitmap);
-	  if (hbmpOrig == NULL)
-	    FatalError ("winFillSpans - DRAWABLE_PIXMAP - FillTiled - "
-			"SelectObject () failed on pTilePriv->hBitmap\n");
-
-	  while (iSpans--)
-	    {
-	      int width = pTile->drawable.width;
-	      fullX1 = pPoints->x;
-	      fullY1 = pPoints->y;
-	      fullX2 = fullX1 + (int) *piWidths;
-	      pPoints++;
-	      piWidths++;
-	
-	      if (fullY1 < extentY1 || extentY2 <= fullY1)
-		continue;
-	
-	      if (fullX1 < extentX1)
-		fullX1 = extentX1;
-	      if (fullX2 > extentX2)
-		fullX2 = extentX2;
-	
-	      if (fullX1 >= fullX2)
-		continue;
-	
-	      for (iX = fullX1; iX < fullX2; iX += width)
-	      	{
-		  int xoffset;
-
-		  if ((iX + pTile->drawable.width) > fullX2)
-		    width = fullX2 - iX;
-		  else
-		    width = pTile->drawable.width;
-
-		  if (iX == fullX1)
-		    xoffset = (fullX1 - (pDrawable->x + (pGC->patOrg.x % pTile->drawable.width) - pTile->drawable.width)) % pTile->drawable.width;
-		  else
-		    xoffset = 0;
-
-		  if (xoffset + width > pTile->drawable.width)
-		    width = pTile->drawable.width - xoffset;
-
-		  BitBlt (pGCPriv->hdcMem,
-			  iX, fullY1,
-			  width, 1,
-			  hdcTile,
-			  xoffset,
-			  (fullY1 - (pDrawable->y + (pGC->patOrg.y % pTile->drawable.height) - pTile->drawable.height)) % pTile->drawable.height,
-			  g_copyROP[pGC->alu]);
-		}
-	    }
-
-	  /* Push the tile pixmap out of the memory HDC */
-	  SelectObject (hdcTile, hbmpOrig);
-
-	  /* Delete the tile */
-	  DeleteDC (hdcTile);
-	  break;
-
-	default:
-	  ErrorF ("winFillSpans - DRAWABLE_PIXMAP - Unknown fillStyle\n");
-	  break;
-	}
-
-      /* Reset clip region */
-      SelectClipRgn (pGCPriv->hdcMem, NULL);
-
-      /* Push the drawable pixmap out of the GC HDC */
-      SelectObject (pGCPriv->hdcMem, hbmpOrig);
-      break;
-      
-    case DRAWABLE_WINDOW:
-
-      SelectClipRgn (pGCPriv->hdc, combined);
-      DeleteObject (combined);
-      combined = NULL;
-
-      /* Branch on fill style */
-      switch (pGC->fillStyle)
-	{
-	case FillSolid:
-
-          ROP16 (pGCPriv->hdc, pGC->alu);
-
-	  if (pDrawable->depth == 1) 
-	    {
-	      if (pGC->fgPixel == 0)
-		hPenOrig = SelectObject (pGCPriv->hdc, 
-					 GetStockObject (BLACK_PEN));
-	      else
-		hPenOrig = SelectObject (pGCPriv->hdc,
-					 GetStockObject (WHITE_PEN));
-	    } 
-	  else 
-	    {
-	      fg = pGC->fgPixel;
-	      TRANSLATE_COLOR (fg);
-	      hPen = CreatePen (PS_SOLID, 0, fg);
-	      hPenOrig = SelectObject (pGCPriv->hdc, hPen);
-	    }
-
-	  while (iSpans--)
-	    {
-	      fullX1 = pPoints->x;
-	      fullY1 = pPoints->y;
-	      fullX2 = fullX1 + (int) *piWidths;
-	      pPoints++;
-	      piWidths++;
-	
-	      if (fullY1 < extentY1 || extentY2 <= fullY1)
-		continue;
-	
-	      if (fullX1 < extentX1)
-		fullX1 = extentX1;
-	      if (fullX2 > extentX2)
-		fullX2 = extentX2;
-	
-	      if (fullX1 >= fullX2)
-		continue;
-	
-	      MoveToEx (pGCPriv->hdc, fullX1, fullY1, NULL);
-	      LineTo (pGCPriv->hdc, fullX2, fullY1);
-	    }
-
-          SetROP2 (pGCPriv->hdc, R2_COPYPEN);
-
-	  /* Give back the Brush */
-	  SelectObject (pGCPriv->hdc, hPenOrig);
-
-	  if (pDrawable->depth != 1)
-	    DeleteObject (hPen);
-	  break;
-
-	case FillOpaqueStippled:
-
-	  pStipple = pGC->stipple;
-	  pStipplePriv = winGetPixmapPriv (pStipple);
-
-	  /* Create a device-dependent bitmap for the stipple */
-	  hBitmap = CreateDIBitmap (pGCPriv->hdc,
-				    (BITMAPINFOHEADER *)pStipplePriv->pbmih,
-				    CBM_INIT,
-				    pStipplePriv->pbBits,
-				    (BITMAPINFO *)pStipplePriv->pbmih,
-				    DIB_RGB_COLORS);
-
-	  /* Create a memory DC to hold the stipple */
-	  hdcStipple = CreateCompatibleDC (pGCPriv->hdc);
-
-	  /* Select the stipple bitmap into the stipple DC */
-	  hbmpOrigStipple = SelectObject (hdcStipple, hBitmap);
-	  if (hbmpOrigStipple == NULL)
-	    FatalError ("winFillSpans () - DRAWABLE_PIXMAP - FillStippled - "
-			"SelectObject () failed on hbmpOrigStipple\n");
-
-	  /* Make a temporary copy of the foreground and background colors */
-   	  bg = pGC->bgPixel;
-   	  fg = pGC->fgPixel;
-
-	  /* Translate the depth-dependent colors to Win32 COLORREFs */
-	  TRANSLATE_COLOR (fg);
-	  TRANSLATE_COLOR (bg);
-	  SetTextColor (pGCPriv->hdc, fg);
-	  SetBkColor (pGCPriv->hdc, bg);
-
-	  while (iSpans--)
-	    {
-	      int width = pStipple->drawable.width;
-	      fullX1 = pPoints->x;
-	      fullY1 = pPoints->y;
-	      fullX2 = fullX1 + (int) *piWidths;
-	      pPoints++;
-	      piWidths++;
-	
-	      if (fullY1 < extentY1 || extentY2 <= fullY1)
-		continue;
-	
-	      if (fullX1 < extentX1)
-		fullX1 = extentX1;
-	      if (fullX2 > extentX2)
-		fullX2 = extentX2;
-	
-	      if (fullX1 >= fullX2)
-		continue;
-	
-	      for (iX = fullX1; iX < fullX2; iX += width)
-		{
-		  int xoffset;
-
-		  if ((iX + pStipple->drawable.width) > fullX2)
-		    width = fullX2 - iX;
-		  else
-		    width = pStipple->drawable.width;
-
-		  if (iX == fullX1)
-		    xoffset = (fullX1 - (pDrawable->x + (pGC->patOrg.x % pStipple->drawable.width) - pStipple->drawable.width)) % pStipple->drawable.width;
-		  else
-		    xoffset = 0;
-
-		  if (xoffset + width > pStipple->drawable.width)
-		    width = pStipple->drawable.width - xoffset;
-
-		  BitBlt (pGCPriv->hdc,
-			  iX, fullY1,
-			  width, 1,
-			  hdcStipple,
-			  xoffset,
-			  (fullY1 - (pDrawable->y + (pGC->patOrg.y % pStipple->drawable.height) - pStipple->drawable.height)) % pStipple->drawable.height,
-			  g_copyROP[pGC->alu]);
-		}
-	    }
-
-	  /* Clear the stipple HDC */
-	  SelectObject (hdcStipple, hbmpOrigStipple);
-	  DeleteDC (hdcStipple);
-
-	  /* Delete the device dependent stipple bitmap */
-	  DeleteObject (hBitmap);
-
-	  break;
-
-	case FillStippled:
-	  pStipple = pGC->stipple;
-	  pStipplePriv = winGetPixmapPriv (pStipple);
-
-	  /* Create a device-dependent bitmap for the stipple */
-	  hBitmap = CreateDIBitmap (pGCPriv->hdcMem,
-				    (BITMAPINFOHEADER *)pStipplePriv->pbmih,
-				    CBM_INIT,
-				    pStipplePriv->pbBits,
-				    (BITMAPINFO *)pStipplePriv->pbmih,
-				    DIB_RGB_COLORS);
-
-	  /* Create a memory DC to hold the stipple */
-	  hdcStipple = CreateCompatibleDC (pGCPriv->hdc);
-
-	  /* Select the stipple bitmap into the stipple DC */
-	  hbmpOrigStipple = SelectObject (hdcStipple, hBitmap);
-	  if (hbmpOrigStipple == NULL)
-	    FatalError ("winFillSpans () - DRAWABLE_PIXMAP - FillStippled - "
-			"SelectObject () failed on hbmpOrigStipple\n");
-
-	  /* Make a temporary copy of the foreground and background colors */
-   	  bg = pGC->bgPixel;
-   	  fg = pGC->fgPixel;
-
-	  /* Translate the depth-dependent colors to Win32 COLORREFs */
-	  TRANSLATE_COLOR (fg);
-	  TRANSLATE_COLOR (bg);
-
-	  /* this is fudgy, we should only invert on the last one
-	   * We need to get the black/white pixels right in the
-	   * colormap. But yeah ! it's working.. 
-	   */
-	  if (pGC->bgPixel != -1 && pGC->fgPixel != -1) 
-	    {
-	      SetTextColor (pGCPriv->hdc, fg);
-	      SetBkColor (pGCPriv->hdc, bg);
-	      BitBlt (hdcStipple,
-		      0, 0,
-		      pStipple->drawable.width, pStipple->drawable.height,
-		      hdcStipple,
-		      0,0,
-		      0x330008);
-	    } 
-	  else if (pGC->bgPixel == -1) 
-	    {
-	      SetTextColor (pGCPriv->hdc, fg);
-	      SetBkMode (pGCPriv->hdc, TRANSPARENT);
-	      BitBlt (hdcStipple,
-		      0, 0,
-		      pStipple->drawable.width, pStipple->drawable.height,
-		      hdcStipple,
-		      0,0,
-		      0x330008);
-	    } 
-	  else if (pGC->fgPixel == -1) 
-	    {
-	      SetTextColor (pGCPriv->hdc, bg);
-	      SetBkMode (pGCPriv->hdc, TRANSPARENT);
-#if 0
-	      BitBlt (hdcStipple,
-		      0, 0,
-		      pStipple->drawable.width, pStipple->drawable.height,
-		      hdcStipple,
-		      0, 0,
-		      0x330008);
-#endif
-	    }
-
-	  while (iSpans--)
-	    {
- 	      int width = pStipple->drawable.width;
-	      fullX1 = pPoints->x;
-	      fullY1 = pPoints->y;
-	      fullX2 = fullX1 + (int) *piWidths;
-	      pPoints++;
-	      piWidths++;
-	
-	      if (fullY1 < extentY1 || extentY2 <= fullY1)
-		continue;
-	
-	      if (fullX1 < extentX1)
-		fullX1 = extentX1;
-	      if (fullX2 > extentX2)
-		fullX2 = extentX2;
-	
-	      if (fullX1 >= fullX2)
-		continue;
-	
-	      for (iX = fullX1; iX < fullX2; iX += width)
-		{
-		  int xoffset;
-
-		  if ((iX + pStipple->drawable.width) > fullX2)
-		    width = fullX2 - iX;
-		  else
-		    width = pStipple->drawable.width;
-
-		  if (iX == fullX1)
-		    xoffset = (fullX1 - (pDrawable->x + (pGC->patOrg.x % pStipple->drawable.width) - pStipple->drawable.width)) % pStipple->drawable.width;
-		  else
-		    xoffset = 0;
-
-		  if (xoffset + width > pStipple->drawable.width)
-		    width = pStipple->drawable.width - xoffset;
-
-		  BitBlt (pGCPriv->hdc,
-			  iX, fullY1,
-			  width, 1,
-			  hdcStipple,
-			  xoffset,
-			  (fullY1 - (pDrawable->y + (pGC->patOrg.y % pStipple->drawable.height) - pStipple->drawable.height)) % pStipple->drawable.height,
-			  g_copyROP[pGC->alu]);
-		}
-	    }
-
-	  /* Clear the stipple HDC */
-	  SelectObject (hdcStipple, hbmpOrigStipple);
-	  DeleteDC (hdcStipple);
-
-	  /* Delete the device dependent stipple bitmap */
-	  DeleteObject (hBitmap);
-
-	  /* Restore the background mode */
-	  SetBkMode (pGCPriv->hdc, OPAQUE);	  
-	  break;
-
-	case FillTiled:
-
-	  /* Get a pixmap pointer from the tile pointer, and fetch privates  */
-	  pTile = (PixmapPtr) pGC->tile.pixmap;
-	  pTilePriv = winGetPixmapPriv (pTile);
-
-	  /* Select the tile into a DC */
-	  hbmpOrig = SelectObject (pGCPriv->hdcMem, pTilePriv->hBitmap);
-	  if (hbmpOrig == NULL)
-	    FatalError ("winFillSpans - DRAWABLE_WINDOW - FillTiled - "
-			"SelectObject () failed on pTilePriv->hBitmap\n");
-
-	  while (iSpans--)
-	    {
-	      int width = pTile->drawable.width;
-	      fullX1 = pPoints->x;
-	      fullY1 = pPoints->y;
-	      fullX2 = fullX1 + (int) *piWidths;
-	      pPoints++;
-	      piWidths++;
-	
-	      if (fullY1 < extentY1 || extentY2 <= fullY1)
-		continue;
-	
-	      if (fullX1 < extentX1)
-		fullX1 = extentX1;
-	      if (fullX2 > extentX2)
-		fullX2 = extentX2;
-	
-	      if (fullX1 >= fullX2)
-		continue;
-	
-	      for (iX = fullX1; iX < fullX2; iX += width)
-	      	{
-		  int xoffset;
-
-		  if ((iX + pTile->drawable.width) > fullX2)
-		    width = fullX2 - iX;
-		  else
-		    width = pTile->drawable.width;
-
-		  if (iX == fullX1)
-		    xoffset = (fullX1 - (pDrawable->x + (pGC->patOrg.x % pTile->drawable.width) - pTile->drawable.width)) % pTile->drawable.width;
-		  else
-		    xoffset = 0;
-
-		  if (xoffset + width > pTile->drawable.width)
-		    width = pTile->drawable.width - xoffset;
-
-		  BitBlt (pGCPriv->hdc,
-			  iX, fullY1,
-			  width, 1,
-			  pGCPriv->hdcMem,
-			  xoffset,
-			  (fullY1 - (pDrawable->y + (pGC->patOrg.y % pTile->drawable.height) - pTile->drawable.height)) % pTile->drawable.height,
-			  g_copyROP[pGC->alu]);
-		}
-	    }
-
-	  /* Push the tile pixmap out of the memory HDC */
-	  SelectObject (pGCPriv->hdcMem, hbmpOrig);
-	  break;
-
-	default:
-	  ErrorF ("winFillSpans - DRAWABLE_WINDOW - Unknown fillStyle\n");
-	  break;
-	}
-
-      /* Reset clip region */
-      SelectClipRgn (pGCPriv->hdc, NULL);
-      break;
-
-    case UNDRAWABLE_WINDOW:
-      /* UNDRAWABLE_WINDOW doesn't appear to get called when running xterm */
-      switch (pGC->fillStyle)
-	{
-	case FillSolid:
-	  ErrorF ("winFillSpans - UNDRAWABLE_WINDOW - FillSolid - "
-		  "Unimplemented\n");
-	  break;
-
-	case FillStippled:
-	  ErrorF ("winFillSpans - UNDRAWABLE_WINDOW - FillStippled - "
-		  "Unimplemented\n");
-	  break;
-
-	case FillTiled:
-	  ErrorF ("winFillSpans - UNDRAWABLE_WINDOW - FillTiled - "
-		  "Unimplemented\n");
-	  break;
-
-	case FillOpaqueStippled:
-	  ErrorF ("winFillSpans - UNDRAWABLE_WINDOW - OpaqueStippled - "
-		  "Unimplemented\n");
-	  break;
-
-	default:
-	  ErrorF ("winFillSpans - UNDRAWABLE_WINDOW - Unknown fillStyle\n");
-	  break;
-	}
-      break;
-
-    case DRAWABLE_BUFFER:
-      /* DRAWABLE_BUFFER seems to be undocumented. */
-      ErrorF ("winFillSpans - DRAWABLE_BUFFER - Unimplemented\n");
-      break;
-
-    default:
-      ErrorF ("winFillSpans - Unknown drawable type\n");
-      break;
-    }
-}
diff --git a/hw/xwin/winfont.c b/hw/xwin/winfont.c
deleted file mode 100644
index af3e90d..0000000
--- a/hw/xwin/winfont.c
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-#ifdef XWIN_NATIVEGDI
-/* See Porting Layer Definition - p. 32 */
-/* See mfb/mfbfont.c - mfbRealizeFont() - which is empty :) */
-Bool
-winRealizeFontNativeGDI (ScreenPtr pScreen, FontPtr pFont)
-{
-  BOOL			fResult = TRUE;
-  winScreenPriv(pScreen);
-  
-#if CYGDEBUG
-  winTrace ("winRealizeFont (%p, %p)\n", pScreen, pFont);
-#endif
-
-  WIN_UNWRAP(RealizeFont);
-  if (pScreen->RealizeFont)
-    fResult = (*pScreen->RealizeFont) (pScreen, pFont);
-  WIN_WRAP(RealizeFont, winRealizeFontNativeGDI);
-  
-  return fResult;
-}
-
-/* See Porting Layer Definition - p. 32 */
-/* See mfb/mfbfont.c - mfbUnrealizeFont() - which is empty :) */
-Bool
-winUnrealizeFontNativeGDI (ScreenPtr pScreen, FontPtr pFont)
-{
-  BOOL			fResult = TRUE;
-  winScreenPriv(pScreen);
-  
-#if CYGDEBUG
-  winTrace ("winUnrealizeFont (%p, %p)\n", pScreen, pFont);
-#endif
-
-  WIN_UNWRAP(UnrealizeFont);
-  if (pScreen->UnrealizeFont)
-    fResult = (*pScreen->UnrealizeFont) (pScreen, pFont);
-  WIN_WRAP(UnrealizeFont, winUnrealizeFontNativeGDI);
-  
-  return fResult;
-#if CYGDEBUG
-  winDebug ("winUnrealizeFont()\n");
-#endif
-  return TRUE;
-}
-#endif
diff --git a/hw/xwin/wingc.c b/hw/xwin/wingc.c
deleted file mode 100644
index 107d87a..0000000
--- a/hw/xwin/wingc.c
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-void
-winPushPixels (GCPtr pGC, PixmapPtr pBitMap, DrawablePtr pDrawable, int dx, int dy, int xOrg, int yOrg);
-
-
-/*
- * Local prototypes
- */
-
-#if 0
-static void
-winChangeGCNativeGDI (GCPtr pGC, unsigned long ulChanges);
-#endif
-
-static void
-winValidateGCNativeGDI (GCPtr pGC,
-			unsigned long changes,
-			DrawablePtr pDrawable);
-
-#if 0
-static void
-winCopyGCNativeGDI (GCPtr pGCsrc, unsigned long ulMask, GCPtr pGCdst);
-#endif
-
-static void
-winDestroyGCNativeGDI (GCPtr pGC);
-
-#if 0
-static void
-winChangeClipNativeGDI (GCPtr pGC, int nType, pointer pValue, int nRects);
-
-static void
-winDestroyClipNativeGDI (GCPtr pGC);
-
-static void
-winCopyClipNativeGDI (GCPtr pGCdst, GCPtr pGCsrc);
-#endif
-
-#if 0
-/* GC Handling Routines */
-const GCFuncs winGCFuncs = {
-  winValidateGCNativeGDI,
-  winChangeGCNativeGDI,
-  winCopyGCNativeGDI,
-  winDestroyGCNativeGDI,
-  winChangeClipNativeGDI,
-  winDestroyClipNativeGDI,
-  winCopyClipNativeGDI,
-};
-#else
-const GCFuncs winGCFuncs = {
-  winValidateGCNativeGDI,
-  miChangeGC,
-  miCopyGC,
-  winDestroyGCNativeGDI,
-  miChangeClip,
-  miDestroyClip,
-  miCopyClip,
-};
-#endif
-
-/* Drawing Primitives */
-const GCOps winGCOps = {
-  winFillSpansNativeGDI,
-  winSetSpansNativeGDI,
-  miPutImage,
-  miCopyArea,
-  miCopyPlane,
-  miPolyPoint,
-  winPolyLineNativeGDI,
-  miPolySegment,
-  miPolyRectangle,
-  miPolyArc,
-  miFillPolygon,
-  miPolyFillRect,
-  miPolyFillArc,
-  miPolyText8,
-  miPolyText16,
-  miImageText8,
-  miImageText16,
-#if 0
-  winImageGlyphBltNativeGDI,
-  winPolyGlyphBltNativeGDI,
-#else
-  miImageGlyphBlt,
-  miPolyGlyphBlt,
-#endif
-  winPushPixels
-};
-
-
-/* See Porting Layer Definition - p. 45 */
-/* See mfb/mfbgc.c - mfbCreateGC() */
-/* See Strategies for Porting - pp. 15, 16 */
-Bool
-winCreateGCNativeGDI (GCPtr pGC)
-{
-  winPrivGCPtr		pGCPriv = NULL;
-  winPrivScreenPtr	pScreenPriv = NULL;
-
-#if 0
-  ErrorF ("winCreateGCNativeGDI - depth: %d\n",
-	  pGC->depth);
-#endif
-
-  pGC->clientClip = NULL;
-  pGC->clientClipType = CT_NONE;
-  pGC->freeCompClip = FALSE;
-  pGC->pCompositeClip = 0;
-
-  pGC->ops = (GCOps *) &winGCOps;
-  pGC->funcs = (GCFuncs *) &winGCFuncs;
-
-  /* We want all coordinates passed to spans functions to be screen relative */
-  pGC->miTranslate = TRUE;
-
-  /* Allocate privates for this GC */
-  pGCPriv = winGetGCPriv (pGC);
-  if (pGCPriv == NULL)
-    {
-      ErrorF ("winCreateGCNativeGDI () - Privates pointer was NULL\n");
-      return FALSE;
-    }
-
-  /* Create a new screen DC for the display window */
-  pScreenPriv = winGetScreenPriv (pGC->pScreen);
-  pGCPriv->hdc = GetDC (pScreenPriv->hwndScreen);
-
-  /* Allocate a memory DC for the GC */
-  pGCPriv->hdcMem = CreateCompatibleDC (pGCPriv->hdc);
-
-  return TRUE;
-}
-
-
-#if 0
-/* See Porting Layer Definition - p. 45 */
-static void
-winChangeGCNativeGDI (GCPtr pGC, unsigned long ulChanges)
-{
-#if 0
-  ErrorF ("winChangeGCNativeGDI () - Doing nothing\n");
-#endif
-}
-#endif
-
-
-static void
-winValidateGCNativeGDI (GCPtr pGC,
-			unsigned long ulChanges,
-			DrawablePtr pDrawable)
-{
-  if ((ulChanges & (GCClipXOrigin | GCClipYOrigin | GCClipMask | GCSubwindowMode)) 
-      || (pDrawable->serialNumber != (pGC->serialNumber & DRAWABLE_SERIAL_BITS)))
-  {
-    miComputeCompositeClip (pGC, pDrawable);
-  }
-}
-
-
-#if 0
-/* See Porting Layer Definition - p. 46 */
-static void
-winCopyGCNativeGDI (GCPtr pGCsrc, unsigned long ulMask, GCPtr pGCdst)
-{
-
-}
-#endif
-
-
-/* See Porting Layer Definition - p. 46 */
-static void
-winDestroyGCNativeGDI (GCPtr pGC)
-{
-  winGCPriv(pGC);
-  winScreenPriv(pGC->pScreen);
-
-  if (pGC->freeCompClip)
-	REGION_DESTROY (pGC->pScreen, pGC->pCompositeClip);
-
-  /* Free the memory DC */
-  if (pGCPriv->hdcMem != NULL)
-    {
-      DeleteDC (pGCPriv->hdcMem);
-      pGCPriv->hdcMem = NULL;
-    }
-
-  /* Release the screen DC for the display window */
-  if (pGCPriv->hdc != NULL)
-    {
-      ReleaseDC (pScreenPriv->hwndScreen, pGCPriv->hdc);
-      pGCPriv->hdc = NULL;
-    }
-
-  /* Invalidate the GC privates pointer */
-  winSetGCPriv (pGC, NULL);
-}
-
-#if 0
-/* See Porting Layer Definition - p. 46 */
-static void
-winChangeClipNativeGDI (GCPtr pGC, int nType, pointer pValue, int nRects)
-{
-
-}
-
-
-/* See Porting Layer Definition - p. 47 */
-static void
-winDestroyClipNativeGDI (GCPtr pGC)
-{
-
-}
-
-
-/* See Porting Layer Definition - p. 47 */
-static void
-winCopyClipNativeGDI (GCPtr pGCdst, GCPtr pGCsrc)
-{
-
-}
-#endif
diff --git a/hw/xwin/wingetsp.c b/hw/xwin/wingetsp.c
deleted file mode 100644
index 03f7f10..0000000
--- a/hw/xwin/wingetsp.c
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Harold L Hunt II
- * 		Alan Hourihane <alanh at fairlite.demon.co.uk>
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-/* See Porting Layer Definition - p. 55 */
-void
-winGetSpansNativeGDI (DrawablePtr	pDrawable, 
-		      int		nMax, 
-		      DDXPointPtr	pPoints, 
-		      int		*piWidths, 
-		      int		iSpans, 
-		      char		*pDsts)
-{
-  PixmapPtr		pPixmap = NULL;
-  winPrivPixmapPtr	pPixmapPriv = NULL;
-  int			iSpan;
-  DDXPointPtr		pPoint = NULL;
-  int			*piWidth = NULL;
-  char			*pDst = pDsts;
-  HBITMAP		hbmpWindow, hbmpOrig, hbmpOrig1;
-  BYTE			*pbWindow = NULL;
-  HDC			hdcMem, hdcMem1;
-  ScreenPtr		pScreen = pDrawable->pScreen;
-  winScreenPriv(pScreen);
-
-  /* Branch on the drawable type */
-  switch (pDrawable->type)
-    {
-    case DRAWABLE_PIXMAP:
-#if 0
-      ErrorF ("winGetSpans - DRAWABLE_PIXMAP %08x\n",
-	      pDrawable);
-#endif
-
-      pPixmap = (PixmapPtr) pDrawable;
-      pPixmapPriv = winGetPixmapPriv (pPixmap);
-
-      /* Open a memory HDC */
-      hdcMem1 = CreateCompatibleDC (NULL);
-      hdcMem = CreateCompatibleDC (NULL);
-
-      /* Select the drawable pixmap into a DC */
-      hbmpOrig1 = SelectObject (hdcMem1, pPixmapPriv->hBitmap);
-
-      if (hbmpOrig1 == NULL)
-	FatalError ("winGetSpans - DRAWABLE_PIXMAP - SelectObject () "
-		    "failed on pPixmapPriv->hBitmap\n");
-
-      /* Loop through spans */
-      for (iSpan = 0; iSpan < iSpans; ++iSpan)
-	{
-	  pPoint = pPoints + iSpan;
-	  piWidth = piWidths + iSpan;
-
-      	  hbmpWindow = winCreateDIBNativeGDI (*piWidth, 1,
-					      pDrawable->depth,
-					      &pbWindow,
-					      NULL);
-
-      	  hbmpOrig = SelectObject (hdcMem, hbmpWindow);
-			       
-          /* Transfer the window bits to the window bitmap */
-          BitBlt (hdcMem,
-		  0, 0,
-		  *piWidth, 1, 
-		  hdcMem1,
-		  pPoint->x, pPoint->y,
-		  SRCCOPY);
-
-	  memcpy (pDst,
-		  (char*) pbWindow,
-		  PixmapBytePad (*piWidth, pDrawable->depth));
-
-      	  /* Pop the window bitmap out of the HDC and delete the bitmap */
-      	  SelectObject (hdcMem, hbmpOrig);
-	  DeleteObject (hbmpWindow);
-
-#if 0
-	  ErrorF ("(%dx%dx%d) (%d,%d) w: %d\n",
-		  pDrawable->width, pDrawable->height, pDrawable->depth,
-		  pPoint->x, pPoint->y, *piWidth);
-#endif
-
-	  /* Calculate offset of next bit destination */
-	  pDst += PixmapBytePad (*piWidth, pDrawable->depth);
-	}
-      
-      /* Pop the pixmap's bitmap out of the HDC */
-      SelectObject (hdcMem1, hbmpOrig1);
-
-      /* Delete the HDCs */
-      DeleteDC (hdcMem1);
-      DeleteDC (hdcMem);
-      break;
-
-    case DRAWABLE_WINDOW:
-#if 0
-      ErrorF ("winGetSpans - DRAWABLE_WINDOW\n");
-#endif
-
-      /* Open a memory HDC */
-      hdcMem = CreateCompatibleDC (NULL);
-
-      /* Loop through spans */
-      for (iSpan = 0; iSpan < iSpans; ++iSpan)
-	{
-	  pPoint = pPoints + iSpan;
-	  piWidth = piWidths + iSpan;
-
-      	  hbmpWindow = winCreateDIBNativeGDI (*piWidth, 1,
-					      pDrawable->depth,
-					      &pbWindow,
-					      NULL);
-
-      	  hbmpOrig = SelectObject (hdcMem, hbmpWindow);
-
-          /* Transfer the window bits to the window bitmap */
-          BitBlt (hdcMem,
-		  0, 0,
-		  *piWidth, 1, 
-		  pScreenPriv->hdcScreen,
-		  pPoint->x, pPoint->y,
-		  SRCCOPY);
-
-	  memcpy (pDst,
-		  (char*) pbWindow,
-		  PixmapBytePad (*piWidth, pDrawable->depth));
-
-      	  /* Pop the window bitmap out of the HDC */
-      	  SelectObject (hdcMem, hbmpOrig);
-
-	  DeleteObject (hbmpWindow);
-
-#if 0
-	  ErrorF ("(%dx%dx%d) (%d,%d) w: %d\n",
-		  pDrawable->width, pDrawable->height, pDrawable->depth,
-		  pPoint->x, pPoint->y, *piWidth);
-#endif
-
-	  /* Calculate offset of next bit destination */
-	  pDst += PixmapBytePad (*piWidth, pDrawable->depth);
-	}
-
-      /* Delete the window bitmap */
-      DeleteDC (hdcMem);
-      break;
-
-    case UNDRAWABLE_WINDOW:
-      FatalError ("winGetSpans - UNDRAWABLE_WINDOW\n");
-      break;
-
-    case DRAWABLE_BUFFER:
-      FatalError ("winGetSpans - DRAWABLE_BUFFER\n");
-      break;
-      
-    default:
-      FatalError ("winGetSpans - Unknown drawable type\n");
-      break;
-    }
-}
diff --git a/hw/xwin/winglobals.c b/hw/xwin/winglobals.c
deleted file mode 100644
index fddada3..0000000
--- a/hw/xwin/winglobals.c
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * General global variables
- */
-
-int		g_iNumScreens = 0;
-winScreenInfo	g_ScreenInfo[MAXSCREENS];
-int		g_iLastScreen = -1;
-#ifdef HAS_DEVWINDOWS
-int		g_fdMessageQueue = WIN_FD_INVALID;
-#endif
-DevPrivateKey	g_iScreenPrivateKey = &g_iScreenPrivateKey;
-DevPrivateKey	g_iCmapPrivateKey = &g_iCmapPrivateKey;
-DevPrivateKey	g_iGCPrivateKey = &g_iGCPrivateKey;
-DevPrivateKey	g_iPixmapPrivateKey = &g_iPixmapPrivateKey;
-DevPrivateKey	g_iWindowPrivateKey = &g_iWindowPrivateKey;
-unsigned long	g_ulServerGeneration = 0;
-Bool		g_fInitializedDefaultScreens = FALSE;
-DWORD		g_dwEnginesSupported = 0;
-HINSTANCE	g_hInstance = 0;
-HWND		g_hDlgDepthChange = NULL;
-HWND		g_hDlgExit = NULL;
-HWND		g_hDlgAbout = NULL;
-const char *	g_pszQueryHost = NULL;
-Bool		g_fXdmcpEnabled = FALSE;
-HICON		g_hIconX = NULL;
-HICON		g_hSmallIconX = NULL;
-#ifndef RELOCATE_PROJECTROOT
-char *		g_pszLogFile = "/tmp/XWin.log";
-#else
-char *		g_pszLogFile = "XWin.log";
-Bool		g_fLogFileChanged = FALSE;
-#endif
-int		g_iLogVerbose = 2;
-Bool		g_fLogInited = FALSE;
-char *		g_pszCommandLine = NULL;
-Bool		g_fSilentFatalError = FALSE;
-DWORD		g_dwCurrentThreadID = 0;
-Bool		g_fKeyboardHookLL = FALSE;
-HHOOK		g_hhookKeyboardLL = NULL;
-HWND		g_hwndKeyboardFocus = NULL;
-Bool		g_fNoHelpMessageBox = FALSE;
-Bool		g_fSoftwareCursor = FALSE;
-Bool		g_fSilentDupError = FALSE;
-
-
-/*
- * Global variables for dynamically loaded libraries and
- * their function pointers
- */
-
-HMODULE		g_hmodDirectDraw = NULL;
-FARPROC		g_fpDirectDrawCreate = NULL;
-FARPROC		g_fpDirectDrawCreateClipper = NULL;
-
-HMODULE		g_hmodCommonControls = NULL;
-FARPROC		g_fpTrackMouseEvent = (FARPROC) (void (*)(void))NoopDDA;
-
-
-#ifdef XWIN_CLIPBOARD
-/*
- * Wrapped DIX functions
- */
-winDispatchProcPtr	winProcEstablishConnectionOrig = NULL;
-winDispatchProcPtr	winProcQueryTreeOrig = NULL;
-winDispatchProcPtr	winProcSetSelectionOwnerOrig = NULL;
-
-
-/*
- * Clipboard variables
- */
-
-Bool			g_fUnicodeClipboard = TRUE;
-Bool			g_fClipboard = FALSE;
-Bool			g_fClipboardLaunched = FALSE;
-Bool			g_fClipboardStarted = FALSE;
-pthread_t		g_ptClipboardProc;
-HWND			g_hwndClipboard = NULL;
-void			*g_pClipboardDisplay = NULL;
-Window			g_iClipboardWindow = None;
-Atom			g_atomLastOwnedSelection = None;
-#endif
-
-
-/*
- * Re-initialize global variables that are invalidated
- * by a server reset.
- */
-
-void
-winInitializeGlobals (void)
-{
-  g_dwCurrentThreadID = GetCurrentThreadId ();
-  g_hwndKeyboardFocus = NULL;
-#ifdef XWIN_CLIPBOARD
-  g_fClipboardLaunched = FALSE;
-  g_fClipboardStarted = FALSE;
-  g_iClipboardWindow = None;
-  g_pClipboardDisplay = NULL;
-  g_atomLastOwnedSelection = None;
-  g_hwndClipboard = NULL;
-#endif
-}
diff --git a/hw/xwin/winkeybd.c b/hw/xwin/winkeybd.c
deleted file mode 100644
index d574f20..0000000
--- a/hw/xwin/winkeybd.c
+++ /dev/null
@@ -1,637 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- */
-
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winkeybd.h"
-#include "winconfig.h"
-#include "winmsg.h"
-
-#ifdef XKB
-#ifndef XKB_IN_SERVER
-#define XKB_IN_SERVER
-#endif
-#include <xkbsrv.h>
-#endif
-
-static Bool g_winKeyState[NUM_KEYCODES];
-
-/* Stored to get internal mode key states.  Must be read-only.  */
-static unsigned short const *g_winInternalModeKeyStatesPtr = NULL;
-
-
-/*
- * Local prototypes
- */
-
-static void
-winGetKeyMappings (KeySymsPtr pKeySyms, CARD8 *pModMap);
-
-static void
-winKeybdBell (int iPercent, DeviceIntPtr pDeviceInt,
-	      pointer pCtrl, int iClass);
-
-static void
-winKeybdCtrl (DeviceIntPtr pDevice, KeybdCtrl *pCtrl);
-
-
-/* 
- * Translate a Windows WM_[SYS]KEY(UP/DOWN) message
- * into an ASCII scan code.
- *
- * We do this ourselves, rather than letting Windows handle it,
- * because Windows tends to munge the handling of special keys,
- * like AltGr on European keyboards.
- */
-
-void
-winTranslateKey (WPARAM wParam, LPARAM lParam, int *piScanCode)
-{
-  int		iKeyFixup = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 1];
-  int		iKeyFixupEx = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 2];
-  int		iParamScanCode = LOBYTE (HIWORD (lParam));
-
-  /* Branch on special extended, special non-extended, or normal key */
-  if ((HIWORD (lParam) & KF_EXTENDED) && iKeyFixupEx)
-    *piScanCode = iKeyFixupEx;
-  else if (iKeyFixup)
-    *piScanCode = iKeyFixup;
-  else if (wParam == 0 && iParamScanCode == 0x70)
-    *piScanCode = KEY_HKTG;
-  else
-    switch (iParamScanCode)
-    {
-      case 0x70:
-        *piScanCode = KEY_HKTG;
-        break;
-      case 0x73:
-        *piScanCode = KEY_BSlash2;
-        break;
-      default: 
-        *piScanCode = iParamScanCode;
-        break;
-    }
-}
-
-
-/*
- * We call this function from winKeybdProc when we are
- * initializing the keyboard.
- */
-
-static void
-winGetKeyMappings (KeySymsPtr pKeySyms, CARD8 *pModMap)
-{
-  int			i;
-  KeySym		*pMap = map;
-  KeySym		*pKeySym;
-
-  /*
-   * Initialize all key states to up... which may not be true
-   * but it is close enough.
-   */
-  ZeroMemory (g_winKeyState, sizeof (g_winKeyState[0]) * NUM_KEYCODES);
-
-  /* MAP_LENGTH is defined in Xserver/include/input.h to be 256 */
-  for (i = 0; i < MAP_LENGTH; i++)
-    pModMap[i] = NoSymbol;  /* make sure it is restored */
-
-  /* Loop through all valid entries in the key symbol table */
-  for (pKeySym = pMap, i = MIN_KEYCODE;
-       i < (MIN_KEYCODE + NUM_KEYCODES);
-       i++, pKeySym += GLYPHS_PER_KEY)
-    {
-      switch (*pKeySym)
-	{
-	case XK_Shift_L:
-	case XK_Shift_R:
-	  pModMap[i] = ShiftMask;
-	  break;
-
-	case XK_Control_L:
-	case XK_Control_R:
-	  pModMap[i] = ControlMask;
-	  break;
-
-	case XK_Caps_Lock:
-	  pModMap[i] = LockMask;
-	  break;
-
-	case XK_Alt_L:
-	case XK_Alt_R:
-	  pModMap[i] = AltMask;
-	  break;
-
-	case XK_Num_Lock:
-	  pModMap[i] = NumLockMask;
-	  break;
-
-	case XK_Scroll_Lock:
-	  pModMap[i] = ScrollLockMask;
-	  break;
-
-#if 0
-	case XK_Super_L:
-	case XK_Super_R:
-	  pModMap[i] = Mod4Mask;
-	  break;
-#else
-	/* Hirigana/Katakana toggle */
-	case XK_Kana_Lock:
-	case XK_Kana_Shift:
-	  pModMap[i] = KanaMask;
-	  break;
-#endif
-
-	/* alternate toggle for multinational support */
-	case XK_Mode_switch:
-	  pModMap[i] = AltLangMask;
-	  break;
-	}
-    }
-
-  pKeySyms->map        = (KeySym *) pMap;
-  pKeySyms->mapWidth   = GLYPHS_PER_KEY;
-  pKeySyms->minKeyCode = MIN_KEYCODE;
-  pKeySyms->maxKeyCode = MAX_KEYCODE;
-}
-
-
-/* Ring the keyboard bell (system speaker on PCs) */
-static void
-winKeybdBell (int iPercent, DeviceIntPtr pDeviceInt,
-	      pointer pCtrl, int iClass)
-{
-  /*
-   * We can't use Beep () here because it uses the PC speaker
-   * on NT/2000.  MessageBeep (MB_OK) will play the default system
-   * sound on systems with a sound card or it will beep the PC speaker
-   * on systems that do not have a sound card.
-   */
-  MessageBeep (MB_OK);
-}
-
-
-/* Change some keyboard configuration parameters */
-static void
-winKeybdCtrl (DeviceIntPtr pDevice, KeybdCtrl *pCtrl)
-{
-  g_winInternalModeKeyStatesPtr = &(pDevice->key->state);
-}
-
-
-/* 
- * See Porting Layer Definition - p. 18
- * winKeybdProc is known as a DeviceProc.
- */
-
-int
-winKeybdProc (DeviceIntPtr pDeviceInt, int iState)
-{
-  KeySymsRec		keySyms;
-  CARD8 		modMap[MAP_LENGTH];
-  DevicePtr		pDevice = (DevicePtr) pDeviceInt;
-#ifdef XKB
-  XkbComponentNamesRec names;
-  XkbSrvInfoPtr       xkbi;
-  XkbControlsPtr      ctrl;
-#endif
-
-  switch (iState)
-    {
-    case DEVICE_INIT:
-      winConfigKeyboard (pDeviceInt);
-
-      winGetKeyMappings (&keySyms, modMap);
-
-#ifdef XKB
-      /* FIXME: Maybe we should use winGetKbdLeds () here? */
-      defaultKeyboardControl.leds = g_winInfo.keyboard.leds;
-#else
-      defaultKeyboardControl.leds = g_winInfo.keyboard.leds;
-#endif
-
-#ifdef XKB
-      if (g_winInfo.xkb.disable) 
-	{
-#endif
-	  InitKeyboardDeviceStruct (pDevice,
-				    &keySyms,
-				    modMap,
-				    winKeybdBell,
-				    winKeybdCtrl);
-#ifdef XKB
-	} 
-      else 
-	{
-
-          names.keymap = g_winInfo.xkb.keymap;
-          names.keycodes = g_winInfo.xkb.keycodes;
-          names.types = g_winInfo.xkb.types;
-          names.compat = g_winInfo.xkb.compat;
-          names.symbols = g_winInfo.xkb.symbols;
-          names.geometry = g_winInfo.xkb.geometry;
-
-	  winErrorFVerb(2, "Rules = \"%s\" Model = \"%s\" Layout = \"%s\""
-		 " Variant = \"%s\" Options = \"%s\"\n",
-		 g_winInfo.xkb.rules, g_winInfo.xkb.model,
-		 g_winInfo.xkb.layout, g_winInfo.xkb.variant,
-		 g_winInfo.xkb.options);
-          
-	  XkbSetRulesDflts (g_winInfo.xkb.rules, g_winInfo.xkb.model, 
-			    g_winInfo.xkb.layout, g_winInfo.xkb.variant, 
-			    g_winInfo.xkb.options);
-	  XkbInitKeyboardDeviceStruct (pDeviceInt, &names, &keySyms,
-				       modMap, winKeybdBell, winKeybdCtrl);
-	}
-#endif
-
-#ifdef XKB
-      if (!g_winInfo.xkb.disable)
-        {  
-          xkbi = pDeviceInt->key->xkbInfo;
-          if (xkbi != NULL)
-            {  
-              ctrl = xkbi->desc->ctrls;
-              ctrl->repeat_delay = g_winInfo.keyboard.delay;
-              ctrl->repeat_interval = 1000/g_winInfo.keyboard.rate;
-            }
-          else
-            {  
-              winErrorFVerb (1, "winKeybdProc - Error initializing keyboard AutoRepeat (No XKB)\n");
-            }
-        }
-#endif
-
-      g_winInternalModeKeyStatesPtr = &(pDeviceInt->key->state);
-      break;
-      
-    case DEVICE_ON: 
-      pDevice->on = TRUE;
-      g_winInternalModeKeyStatesPtr = &(pDeviceInt->key->state);
-      break;
-
-    case DEVICE_CLOSE:
-    case DEVICE_OFF: 
-      pDevice->on = FALSE;
-      g_winInternalModeKeyStatesPtr = NULL;
-      break;
-    }
-
-  return Success;
-}
-
-
-/*
- * Detect current mode key states upon server startup.
- *
- * Simulate a press and release of any key that is currently
- * toggled.
- */
-
-void
-winInitializeModeKeyStates (void)
-{
-  /* Restore NumLock */
-  if (GetKeyState (VK_NUMLOCK) & 0x0001)
-    {
-      winSendKeyEvent (KEY_NumLock, TRUE);
-      winSendKeyEvent (KEY_NumLock, FALSE);
-    }
-
-  /* Restore CapsLock */
-  if (GetKeyState (VK_CAPITAL) & 0x0001)
-    {
-      winSendKeyEvent (KEY_CapsLock, TRUE);
-      winSendKeyEvent (KEY_CapsLock, FALSE);
-    }
-
-  /* Restore ScrollLock */
-  if (GetKeyState (VK_SCROLL) & 0x0001)
-    {
-      winSendKeyEvent (KEY_ScrollLock, TRUE);
-      winSendKeyEvent (KEY_ScrollLock, FALSE);
-    }
-
-  /* Restore KanaLock */
-  if (GetKeyState (VK_KANA) & 0x0001)
-    {
-      winSendKeyEvent (KEY_HKTG, TRUE);
-      winSendKeyEvent (KEY_HKTG, FALSE);
-    }
-}
-
-
-/*
- * Upon regaining the keyboard focus we must
- * resynchronize our internal mode key states
- * with the actual state of the keys.
- */
-
-void
-winRestoreModeKeyStates ()
-{
-  DWORD			dwKeyState;
-  BOOL			processEvents = TRUE;
-  unsigned short	internalKeyStates;
-
-  /* X server is being initialized */
-  if (!g_winInternalModeKeyStatesPtr)
-    return;
-
-  /* Only process events if the rootwindow is mapped. The keyboard events
-   * will cause segfaults otherwise */
-  if (WindowTable && WindowTable[0] && WindowTable[0]->mapped == FALSE)
-    processEvents = FALSE;    
-  
-  /* Force to process all pending events in the mi event queue */
-  if (processEvents)
-    mieqProcessInputEvents ();
-  
-  /* Read the mode key states of our X server */
-  internalKeyStates = *g_winInternalModeKeyStatesPtr;
-
-  /* 
-   * NOTE: The C XOR operator, ^, will not work here because it is
-   * a bitwise operator, not a logical operator.  C does not
-   * have a logical XOR operator, so we use a macro instead.
-   */
-
-  /* Has the key state changed? */
-  dwKeyState = GetKeyState (VK_NUMLOCK) & 0x0001;
-  if (WIN_XOR (internalKeyStates & NumLockMask, dwKeyState))
-    {
-      winSendKeyEvent (KEY_NumLock, TRUE);
-      winSendKeyEvent (KEY_NumLock, FALSE);
-    }
-
-  /* Has the key state changed? */
-  dwKeyState = GetKeyState (VK_CAPITAL) & 0x0001;
-  if (WIN_XOR (internalKeyStates & LockMask, dwKeyState))
-    {
-      winSendKeyEvent (KEY_CapsLock, TRUE);
-      winSendKeyEvent (KEY_CapsLock, FALSE);
-    }
-
-  /* Has the key state changed? */
-  dwKeyState = GetKeyState (VK_SCROLL) & 0x0001;
-  if (WIN_XOR (internalKeyStates & ScrollLockMask, dwKeyState))
-    {
-      winSendKeyEvent (KEY_ScrollLock, TRUE);
-      winSendKeyEvent (KEY_ScrollLock, FALSE);
-    }
-
-  /* Has the key state changed? */
-  dwKeyState = GetKeyState (VK_KANA) & 0x0001;
-  if (WIN_XOR (internalKeyStates & KanaMask, dwKeyState))
-    {
-      winSendKeyEvent (KEY_HKTG, TRUE);
-      winSendKeyEvent (KEY_HKTG, FALSE);
-    }
-}
-
-
-/*
- * Look for the lovely fake Control_L press/release generated by Windows
- * when AltGr is pressed/released on a non-U.S. keyboard.
- */
-
-Bool
-winIsFakeCtrl_L (UINT message, WPARAM wParam, LPARAM lParam)
-{
-  MSG		msgNext;
-  LONG		lTime;
-  Bool		fReturn;
-
-  /*
-   * Fake Ctrl_L presses will be followed by an Alt_R keypress
-   * with the same timestamp as the Ctrl_L press.
-   */
-  if ((message == WM_KEYDOWN || message == WM_SYSKEYDOWN)
-      && wParam == VK_CONTROL
-      && (HIWORD (lParam) & KF_EXTENDED) == 0)
-    {
-      /* Got a Ctrl_L press */
-
-      /* Get time of current message */
-      lTime = GetMessageTime ();
-
-      /* Look for fake Ctrl_L preceeding an Alt_R press. */
-      fReturn = PeekMessage (&msgNext, NULL,
-			     WM_KEYDOWN, WM_SYSKEYDOWN,
-			     PM_NOREMOVE);
-
-      /*
-       * Try again if the first call fails.
-       * NOTE: This usually happens when TweakUI is enabled.
-       */
-      if (!fReturn)
-	{
-	  /* Voodoo to make sure that the Alt_R message has posted */
-	  Sleep (0);
-
-	  /* Look for fake Ctrl_L preceeding an Alt_R press. */
-	  fReturn = PeekMessage (&msgNext, NULL,
-				 WM_KEYDOWN, WM_SYSKEYDOWN,
-				 PM_NOREMOVE);
-	}
-      if (msgNext.message != WM_KEYDOWN && msgNext.message != WM_SYSKEYDOWN)
-          fReturn = 0;
-
-      /* Is next press an Alt_R with the same timestamp? */
-      if (fReturn && msgNext.wParam == VK_MENU
-	  && msgNext.time == lTime
-	  && (HIWORD (msgNext.lParam) & KF_EXTENDED))
-	{
-	  /* 
-	   * Next key press is Alt_R with same timestamp as current
-	   * Ctrl_L message.  Therefore, this Ctrl_L press is a fake
-	   * event, so discard it.
-	   */
-	  return TRUE;
-	}
-    }
-
-  /* 
-   * Fake Ctrl_L releases will be followed by an Alt_R release
-   * with the same timestamp as the Ctrl_L release.
-   */
-  if ((message == WM_KEYUP || message == WM_SYSKEYUP)
-      && wParam == VK_CONTROL
-      && (HIWORD (lParam) & KF_EXTENDED) == 0)
-    {
-      /* Got a Ctrl_L release */
-
-      /* Get time of current message */
-      lTime = GetMessageTime ();
-
-      /* Look for fake Ctrl_L release preceeding an Alt_R release. */
-      fReturn = PeekMessage (&msgNext, NULL,
-			     WM_KEYUP, WM_SYSKEYUP, 
-			     PM_NOREMOVE);
-
-      /*
-       * Try again if the first call fails.
-       * NOTE: This usually happens when TweakUI is enabled.
-       */
-      if (!fReturn)
-	{
-	  /* Voodoo to make sure that the Alt_R message has posted */
-	  Sleep (0);
-
-	  /* Look for fake Ctrl_L release preceeding an Alt_R release. */
-	  fReturn = PeekMessage (&msgNext, NULL,
-				 WM_KEYUP, WM_SYSKEYUP, 
-				 PM_NOREMOVE);
-	}
-
-      if (msgNext.message != WM_KEYUP && msgNext.message != WM_SYSKEYUP)
-          fReturn = 0;
-      
-      /* Is next press an Alt_R with the same timestamp? */
-      if (fReturn
-	  && (msgNext.message == WM_KEYUP
-	      || msgNext.message == WM_SYSKEYUP)
-	  && msgNext.wParam == VK_MENU
-	  && msgNext.time == lTime
-	  && (HIWORD (msgNext.lParam) & KF_EXTENDED))
-	{
-	  /*
-	   * Next key release is Alt_R with same timestamp as current
-	   * Ctrl_L message. Therefore, this Ctrl_L release is a fake
-	   * event, so discard it.
-	   */
-	  return TRUE;
-	}
-    }
-  
-  /* Not a fake control left press/release */
-  return FALSE;
-}
-
-
-/*
- * Lift any modifier keys that are pressed
- */
-
-void
-winKeybdReleaseKeys ()
-{
-  int				i;
-
-#ifdef HAS_DEVWINDOWS
-  /* Verify that the mi input system has been initialized */
-  if (g_fdMessageQueue == WIN_FD_INVALID)
-    return;
-#endif
-
-  /* Loop through all keys */
-  for (i = 0; i < NUM_KEYCODES; ++i)
-    {
-      /* Pop key if pressed */
-      if (g_winKeyState[i])
-	winSendKeyEvent (i, FALSE);
-
-      /* Reset pressed flag for keys */
-      g_winKeyState[i] = FALSE;
-    }
-}
-
-
-/*
- * Take a raw X key code and send an up or down event for it.
- *
- * Thanks to VNC for inspiration, though it is a simple function.
- */
-
-void
-winSendKeyEvent (DWORD dwKey, Bool fDown)
-{
-  xEvent			xCurrentEvent;
-
-  /*
-   * When alt-tabing between screens we can get phantom key up messages
-   * Here we only pass them through it we think we should!
-   */
-  if (g_winKeyState[dwKey] == FALSE && fDown == FALSE) return;
-
-  /* Update the keyState map */
-  g_winKeyState[dwKey] = fDown;
-  
-  ZeroMemory (&xCurrentEvent, sizeof (xCurrentEvent));
-
-  xCurrentEvent.u.u.type = fDown ? KeyPress : KeyRelease;
-  xCurrentEvent.u.keyButtonPointer.time =
-    g_c32LastInputEventTime = GetTickCount ();
-  xCurrentEvent.u.u.detail = dwKey + MIN_KEYCODE;
-  mieqEnqueue (&xCurrentEvent);
-}
-
-BOOL winCheckKeyPressed(WPARAM wParam, LPARAM lParam)
-{
-  switch (wParam)
-  {
-    case VK_CONTROL:
-      if ((lParam & 0x1ff0000) == 0x11d0000 && g_winKeyState[KEY_RCtrl])
-        return TRUE;
-      if ((lParam & 0x1ff0000) == 0x01d0000 && g_winKeyState[KEY_LCtrl])
-        return TRUE;
-      break;
-    case VK_SHIFT:
-      if ((lParam & 0x1ff0000) == 0x0360000 && g_winKeyState[KEY_ShiftR])
-        return TRUE;
-      if ((lParam & 0x1ff0000) == 0x02a0000 && g_winKeyState[KEY_ShiftL])
-        return TRUE;
-      break;
-    default:
-      return TRUE;
-  }
-  return FALSE;
-}
-
-/* Only on shift release message is sent even if both are pressed.
- * Fix this here 
- */
-void winFixShiftKeys (int iScanCode)
-{
-  if (GetKeyState (VK_SHIFT) & 0x8000)
-    return;
-
-  if (iScanCode == KEY_ShiftL && g_winKeyState[KEY_ShiftR])
-    winSendKeyEvent (KEY_ShiftR, FALSE);
-  if (iScanCode == KEY_ShiftR && g_winKeyState[KEY_ShiftL])
-    winSendKeyEvent (KEY_ShiftL, FALSE);
-}
diff --git a/hw/xwin/winkeybd.h b/hw/xwin/winkeybd.h
deleted file mode 100644
index 09eed14..0000000
--- a/hw/xwin/winkeybd.h
+++ /dev/null
@@ -1,309 +0,0 @@
-#if !defined(WINKEYBD_H)
-#define WINKEYBD_H
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Harold L Hunt II
- */
-
-/*
- * We need symbols for the scan codes of keys.
- */
-#include "winkeynames.h"
-
-
-/*
- * Include the standard ASCII keymap.
- *
- * This header declares a static KeySym array called 'map'.
- */
-#include "winkeymap.h"
-
-#define		WIN_KEYMAP_COLS		3
-
-const int
-g_iKeyMap [] = {
-  /* count	Windows VK,	ASCII,		ASCII when extended VK */
-  /* 0 */	0,		0,		0,
-  /* 1 */	0,		0,		0,
-  /* 2 */	0,		0,		0,
-  /* 3 */	VK_CANCEL,	0,		KEY_Break,
-  /* 4 */	0,		0,		0,
-  /* 5 */	0,		0,		0,
-  /* 6 */	0,		0,		0,
-  /* 7 */	0,		0,		0,
-  /* 8 */	0,		0,		0,
-  /* 9 */	0,		0,		0,
-  /* 10 */	0,		0,		0,
-  /* 11 */	0,		0,		0,
-  /* 12 */	0,		0,		0,
-  /* 13 */	VK_RETURN,	0,		KEY_KP_Enter,
-  /* 14 */	0,		0,		0,
-  /* 15 */	0,		0,		0,
-  /* 16 */	VK_SHIFT,	0,		0,
-  /* 17 */	VK_CONTROL,	0,		KEY_RCtrl,
-  /* 18 */	VK_MENU,	0,		KEY_AltLang,
-  /* 19 */	VK_PAUSE,	KEY_Pause,	0,
-  /* 20 */	0,		0,		0,
-  /* 21 */	0,		0,		0,
-  /* 22 */	0,		0,		0,
-  /* 23 */	0,		0,		0,
-  /* 24 */	0,		0,		0,
-  /* 25 */	0,		0,		0,
-  /* 26 */	0,		0,		0,
-  /* 27 */	0,		0,		0,
-  /* 28 */	0,		0,		0,
-  /* 29 */	0,		0,		0,
-  /* 30 */	0,		0,		0,
-  /* 31 */	0,		0,		0,
-  /* 32 */	0,		0,		0,
-  /* 33 */	VK_PRIOR,	0,		KEY_PgUp,
-  /* 34 */	VK_NEXT,	0,		KEY_PgDown,
-  /* 35 */	VK_END,		0,		KEY_End,
-  /* 36 */	VK_HOME,	0,		KEY_Home,
-  /* 37 */	VK_LEFT,	0,		KEY_Left,
-  /* 38 */	VK_UP,		0,		KEY_Up,
-  /* 39 */	VK_RIGHT,	0,		KEY_Right,
-  /* 40 */	VK_DOWN,	0,		KEY_Down,
-  /* 41 */	0,		0,		0,
-  /* 42 */	0,		0,		0,
-  /* 43 */	0,		0,		0,
-  /* 44 */	VK_SNAPSHOT,	0,		KEY_Print,  
-  /* 45 */	VK_INSERT,	0,		KEY_Insert,
-  /* 46 */	VK_DELETE,	0,		KEY_Delete,
-  /* 47 */	0,		0,		0,
-  /* 48 */	0,		0,		0,
-  /* 49 */	0,		0,		0,
-  /* 50 */	0,		0,		0,
-  /* 51 */	0,		0,		0,
-  /* 52 */	0,		0,		0,
-  /* 53 */	0,		0,		0,
-  /* 54 */	0,		0,		0,
-  /* 55 */	0,		0,		0,
-  /* 56 */	0,		0,		0,
-  /* 57 */	0,		0,		0,
-  /* 58 */	0,		0,		0,
-  /* 59 */	0,		0,		0,
-  /* 60 */	0,		0,		0,
-  /* 61 */	0,		0,		0,
-  /* 62 */	0,		0,		0,
-  /* 63 */	0,		0,		0,
-  /* 64 */	0,		0,		0,
-  /* 65 */	0,		0,		0,
-  /* 66 */	0,		0,		0,
-  /* 67 */	0,		0,		0,
-  /* 68 */	0,		0,		0,
-  /* 69 */	0,		0,		0,
-  /* 70 */	0,		0,		0,
-  /* 71 */	0,		0,		0,
-  /* 72 */	0,		0,		0,
-  /* 73 */	0,		0,		0,
-  /* 74 */	0,		0,		0,
-  /* 75 */	0,		0,		0,
-  /* 76 */	0,		0,		0,
-  /* 77 */	0,		0,		0,
-  /* 78 */	0,		0,		0,
-  /* 79 */	0,		0,		0,
-  /* 80 */	0,		0,		0,
-  /* 81 */	0,		0,		0,
-  /* 82 */	0,		0,		0,
-  /* 83 */	0,		0,		0,
-  /* 84 */	0,		0,		0,
-  /* 85 */	0,		0,		0,
-  /* 86 */	0,		0,		0,
-  /* 87 */	0,		0,		0,
-  /* 88 */	0,		0,		0,
-  /* 89 */	0,		0,		0,
-  /* 90 */	0,		0,		0,
-  /* 91 */	VK_LWIN,	KEY_LMeta,	0,
-  /* 92 */	VK_RWIN,	KEY_RMeta,	0,
-  /* 93 */	VK_APPS,	KEY_Menu,	0,
-  /* 94 */	0,		0,		0,
-  /* 95 */	0,		0,		0,
-  /* 96 */	0,		0,		0,
-  /* 97 */	0,		0,		0,
-  /* 98 */	0,		0,		0,
-  /* 99 */	0,		0,		0,
-  /* 100 */	0,		0,		0,
-  /* 101 */	0,		0,		0,
-  /* 102 */	0,		0,		0,
-  /* 103 */	0,		0,		0,
-  /* 104 */	0,		0,		0,
-  /* 105 */	0,		0,		0,
-  /* 106 */	0,		0,		0,
-  /* 107 */	0,		0,		0,
-  /* 108 */	0,		0,		0,
-  /* 109 */	0,		0,		0,
-  /* 110 */	0,		0,		0,
-  /* 111 */	VK_DIVIDE,	0,		KEY_KP_Divide,
-  /* 112 */	0,		0,		0,
-  /* 113 */	0,		0,		0,
-  /* 114 */	0,		0,		0,
-  /* 115 */	0,		0,		0,
-  /* 116 */	0,		0,		0,
-  /* 117 */	0,		0,		0,
-  /* 118 */	0,		0,		0,
-  /* 119 */	0,		0,		0,
-  /* 120 */	0,		0,		0,
-  /* 121 */	0,		0,		0,
-  /* 122 */	0,		0,		0,
-  /* 123 */	0,		0,		0,
-  /* 124 */	0,		0,		0,
-  /* 125 */	0,		0,		0,
-  /* 126 */	0,		0,		0,
-  /* 127 */	0,		0,		0,
-  /* 128 */	0,		0,		0,
-  /* 129 */	0,		0,		0,
-  /* 130 */	0,		0,		0,
-  /* 131 */	0,		0,		0,
-  /* 132 */	0,		0,		0,
-  /* 133 */	0,		0,		0,
-  /* 134 */	0,		0,		0,
-  /* 135 */	0,		0,		0,
-  /* 136 */	0,		0,		0,
-  /* 137 */	0,		0,		0,
-  /* 138 */	0,		0,		0,
-  /* 139 */	0,		0,		0,
-  /* 140 */	0,		0,		0,
-  /* 141 */	0,		0,		0,
-  /* 142 */	0,		0,		0,
-  /* 143 */	0,		0,		0,
-  /* 144 */	0,		0,		0,
-  /* 145 */	0,		0,		0,
-  /* 146 */	0,		0,		0,
-  /* 147 */	0,		0,		0,
-  /* 148 */	0,		0,		0,
-  /* 149 */	0,		0,		0,
-  /* 150 */	0,		0,		0,
-  /* 151 */	0,		0,		0,
-  /* 152 */	0,		0,		0,
-  /* 153 */	0,		0,		0,
-  /* 154 */	0,		0,		0,
-  /* 155 */	0,		0,		0,
-  /* 156 */	0,		0,		0,
-  /* 157 */	0,		0,		0,
-  /* 158 */	0,		0,		0,
-  /* 159 */	0,		0,		0,
-  /* 160 */	0,		0,		0,
-  /* 161 */	0,		0,		0,
-  /* 162 */	0,		0,		0,
-  /* 163 */	0,		0,		0,
-  /* 164 */	0,		0,		0,
-  /* 165 */	0,		0,		0,
-  /* 166 */	0,		0,		0,
-  /* 167 */	0,		0,		0,
-  /* 168 */	0,		0,		0,
-  /* 169 */	0,		0,		0,
-  /* 170 */	0,		0,		0,
-  /* 171 */	0,		0,		0,
-  /* 172 */	0,		0,		0,
-  /* 173 */	0,		0,		0,
-  /* 174 */	0,		0,		0,
-  /* 175 */	0,		0,		0,
-  /* 176 */	0,		0,		0,
-  /* 177 */	0,		0,		0,
-  /* 178 */	0,		0,		0,
-  /* 179 */	0,		0,		0,
-  /* 180 */	0,		0,		0,
-  /* 181 */	0,		0,		0,
-  /* 182 */	0,		0,		0,
-  /* 183 */	0,		0,		0,
-  /* 184 */	0,		0,		0,
-  /* 185 */	0,		0,		0,
-  /* 186 */	0,		0,		0,
-  /* 187 */	0,		0,		0,
-  /* 188 */	0,		0,		0,
-  /* 189 */	0,		0,		0,
-  /* 190 */	0,		0,		0,
-  /* 191 */	0,		0,		0,
-  /* 192 */	0,		0,		0,
-  /* 193 */	0,		0,		0,
-  /* 194 */	0,		0,		0,
-  /* 195 */	0,		0,		0,
-  /* 196 */	0,		0,		0,
-  /* 197 */	0,		0,		0,
-  /* 198 */	0,		0,		0,
-  /* 199 */	0,		0,		0,
-  /* 200 */	0,		0,		0,
-  /* 201 */	0,		0,		0,
-  /* 202 */	0,		0,		0,
-  /* 203 */	0,		0,		0,
-  /* 204 */	0,		0,		0,
-  /* 205 */	0,		0,		0,
-  /* 206 */	0,		0,		0,
-  /* 207 */	0,		0,		0,
-  /* 208 */	0,		0,		0,
-  /* 209 */	0,		0,		0,
-  /* 210 */	0,		0,		0,
-  /* 211 */	0,		0,		0,
-  /* 212 */	0,		0,		0,
-  /* 213 */	0,		0,		0,
-  /* 214 */	0,		0,		0,
-  /* 215 */	0,		0,		0,
-  /* 216 */	0,		0,		0,
-  /* 217 */	0,		0,		0,
-  /* 218 */	0,		0,		0,
-  /* 219 */	0,		0,		0,
-  /* 220 */	0,		0,		0,
-  /* 221 */	0,		0,		0,
-  /* 222 */	0,		0,		0,
-  /* 223 */	0,		0,		0,
-  /* 224 */	0,		0,		0,
-  /* 225 */	0,		0,		0,
-  /* 226 */	0,		0,		0,
-  /* 227 */	0,		0,		0,
-  /* 228 */	0,		0,		0,
-  /* 229 */	0,		0,		0,
-  /* 230 */	0,		0,		0,
-  /* 231 */	0,		0,		0,
-  /* 232 */	0,		0,		0,
-  /* 233 */	0,		0,		0,
-  /* 234 */	0,		0,		0,
-  /* 235 */	0,		0,		0,
-  /* 236 */	0,		0,		0,
-  /* 237 */	0,		0,		0,
-  /* 238 */	0,		0,		0,
-  /* 239 */	0,		0,		0,
-  /* 240 */	0,		0,		0,
-  /* 241 */	0,		0,		0,
-  /* 242 */	0,		0,		0,
-  /* 243 */	0,		0,		0,
-  /* 244 */	0,		0,		0,
-  /* 245 */	0,		0,		0,
-  /* 246 */	0,		0,		0,
-  /* 247 */	0,		0,		0,
-  /* 248 */	0,		0,		0,
-  /* 249 */	0,		0,		0,
-  /* 250 */	0,		0,		0,
-  /* 251 */	0,		0,		0,
-  /* 252 */	0,		0,		0,
-  /* 253 */	0,		0,		0,
-  /* 254 */	0,		0,		0,
-  /* 255 */	0,		0,		0
-};
-
-#endif /* WINKEYBD_H */
diff --git a/hw/xwin/winkeyhook.c b/hw/xwin/winkeyhook.c
deleted file mode 100755
index 53d91e6..0000000
--- a/hw/xwin/winkeyhook.c
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- *Copyright (C) 2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * References to external symbols
- */
-
-extern HHOOK			g_hhookKeyboardLL;
-extern DWORD			g_dwCurrentThreadID;
-extern HWND			g_hwndKeyboardFocus;
-
-
-/*
- * Function prototypes
- */
-
-static LRESULT CALLBACK
-winKeyboardMessageHookLL (int iCode, WPARAM wParam, LPARAM lParam);
-
-
-#ifndef LLKHF_EXTENDED
-# define LLKHF_EXTENDED  0x00000001
-#endif
-#ifndef LLKHF_UP
-# define LLKHF_UP  0x00000080
-#endif
-
-
-/*
- * KeyboardMessageHook
- */
-
-static LRESULT CALLBACK
-winKeyboardMessageHookLL (int iCode, WPARAM wParam, LPARAM lParam)
-{
-  BOOL			fPassKeystroke = FALSE;
-  BOOL			fPassAltTab = TRUE;
-  PKBDLLHOOKSTRUCT	p = (PKBDLLHOOKSTRUCT) lParam;
-  HWND			hwnd = GetActiveWindow(); 
-#ifdef XWIN_MULTIWINDOW
-  WindowPtr		pWin = NULL;
-  winPrivWinPtr	        pWinPriv = NULL;
-  winPrivScreenPtr	pScreenPriv = NULL;
-  winScreenInfo		*pScreenInfo = NULL;
-
-  /* Check if the Windows window property for our X window pointer is valid */
-  if ((pWin = GetProp (hwnd, WIN_WINDOW_PROP)) != NULL)
-    {
-      /* Get a pointer to our window privates */
-      pWinPriv		= winGetWindowPriv(pWin);
-
-      /* Get pointers to our screen privates and screen info */
-      pScreenPriv	= pWinPriv->pScreenPriv;
-      pScreenInfo	= pScreenPriv->pScreenInfo;
-
-      if (pScreenInfo->fMultiWindow)
-          fPassAltTab = FALSE;
-    }
-#endif
-
-  /* Pass keystrokes on to our main message loop */
-  if (iCode == HC_ACTION)
-    {
-#if 0
-      ErrorF ("vkCode: %08x\tscanCode: %08x\n", p->vkCode, p->scanCode);
-#endif
-
-      switch (wParam)
-	{
-	case WM_KEYDOWN:  case WM_SYSKEYDOWN:
-	case WM_KEYUP:    case WM_SYSKEYUP: 
-	  fPassKeystroke = 
-	    (fPassAltTab && 
-                (p->vkCode == VK_TAB) && ((p->flags & LLKHF_ALTDOWN) != 0))
-	    || (p->vkCode == VK_LWIN) || (p->vkCode == VK_RWIN)
-	    ;
-	  break;
-	}
-    }
-
-  /*
-   * Pass message on to our main message loop.
-   * We process this immediately with SendMessage so that the keystroke
-   * appears in, hopefully, the correct order.
-   */
-  if (fPassKeystroke)
-    {
-      LPARAM		lParamKey = 0x0;
-
-      /* Construct the lParam from KBDLLHOOKSTRUCT */
-      lParamKey = lParamKey | (0x0000FFFF & 0x00000001); /* Repeat count */
-      lParamKey = lParamKey | (0x00FF0000 & (p->scanCode << 16));
-      lParamKey = lParamKey
-	| (0x01000000 & ((p->flags & LLKHF_EXTENDED) << 23));
-      lParamKey = lParamKey
-	| (0x20000000
-	   & ((p->flags & LLKHF_ALTDOWN) << 24));
-      lParamKey = lParamKey | (0x80000000 & ((p->flags & LLKHF_UP) << 24));
-
-      /* Send message to our main window that has the keyboard focus */
-      PostMessage (hwnd,
-		   (UINT) wParam,
-		   (WPARAM) p->vkCode,
-		   lParamKey);
-
-      return 1;
-    }
-
-  /* Call next hook */
-  return CallNextHookEx (NULL, iCode, wParam, lParam);
-}
-
-
-/*
- * Attempt to install the keyboard hook, return FALSE if it was not installed
- */
-
-Bool
-winInstallKeyboardHookLL ()
-{
-  OSVERSIONINFO		osvi = {0};
-  
-  /* Get operating system version information */
-  osvi.dwOSVersionInfoSize = sizeof (osvi);
-  GetVersionEx (&osvi);
-
-  /* Branch on platform ID */
-  switch (osvi.dwPlatformId)
-    {
-    case VER_PLATFORM_WIN32_NT:
-      /* Low-level is supported on NT 4.0 SP3+ only */
-      /* TODO: Return FALSE on NT 4.0 with no SP, SP1, or SP2 */
-      break;
-
-    case VER_PLATFORM_WIN32_WINDOWS:
-      /* Low-level hook is not supported on non-NT */
-      return FALSE;
-    }
-
-  /* Install the hook only once */
-  if (!g_hhookKeyboardLL)
-    g_hhookKeyboardLL = SetWindowsHookEx (WH_KEYBOARD_LL,
-					  winKeyboardMessageHookLL,
-					  g_hInstance,
-					  0);
-
-  return TRUE;
-}
-
-
-/*
- * Remove the keyboard hook if it is installed
- */
-
-void
-winRemoveKeyboardHookLL ()
-{
-  if (g_hhookKeyboardLL)
-    UnhookWindowsHookEx (g_hhookKeyboardLL);
-  g_hhookKeyboardLL = NULL;
-}
diff --git a/hw/xwin/winkeymap.h b/hw/xwin/winkeymap.h
deleted file mode 100644
index 3862f03..0000000
--- a/hw/xwin/winkeymap.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- *
- * For Scancodes see notes in winkeynames.h  !!!!
- *
- */
-
-static KeySym map[NUM_KEYCODES * GLYPHS_PER_KEY] = {
-    /* 0x00 */  NoSymbol,       NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x01 */  XK_Escape,      NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x02 */  XK_1,           XK_exclam,	NoSymbol,	NoSymbol,
-    /* 0x03 */  XK_2,           XK_at,		NoSymbol,	NoSymbol,
-    /* 0x04 */  XK_3,           XK_numbersign,	NoSymbol,	NoSymbol,
-    /* 0x05 */  XK_4,           XK_dollar,	NoSymbol,	NoSymbol,
-    /* 0x06 */  XK_5,           XK_percent,	NoSymbol,	NoSymbol,
-    /* 0x07 */  XK_6,           XK_asciicircum,	NoSymbol,	NoSymbol,
-    /* 0x08 */  XK_7,           XK_ampersand,	NoSymbol,	NoSymbol,
-    /* 0x09 */  XK_8,           XK_asterisk,	NoSymbol,	NoSymbol,
-    /* 0x0a */  XK_9,           XK_parenleft,	NoSymbol,	NoSymbol,
-    /* 0x0b */  XK_0,           XK_parenright,	NoSymbol,	NoSymbol,
-    /* 0x0c */  XK_minus,       XK_underscore,	NoSymbol,	NoSymbol,
-    /* 0x0d */  XK_equal,       XK_plus,	NoSymbol,	NoSymbol,
-    /* 0x0e */  XK_BackSpace,   NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x0f */  XK_Tab,         XK_ISO_Left_Tab,NoSymbol,	NoSymbol,
-    /* 0x10 */  XK_Q,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x11 */  XK_W,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x12 */  XK_E,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x13 */  XK_R,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x14 */  XK_T,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x15 */  XK_Y,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x16 */  XK_U,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x17 */  XK_I,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x18 */  XK_O,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x19 */  XK_P,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x1a */  XK_bracketleft, XK_braceleft,	NoSymbol,	NoSymbol,
-    /* 0x1b */  XK_bracketright,XK_braceright,	NoSymbol,	NoSymbol,
-    /* 0x1c */  XK_Return,      NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x1d */  XK_Control_L,   NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x1e */  XK_A,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x1f */  XK_S,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x20 */  XK_D,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x21 */  XK_F,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x22 */  XK_G,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x23 */  XK_H,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x24 */  XK_J,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x25 */  XK_K,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x26 */  XK_L,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x27 */  XK_semicolon,   XK_colon,	NoSymbol,	NoSymbol,
-    /* 0x28 */  XK_quoteright,  XK_quotedbl,	NoSymbol,	NoSymbol,
-    /* 0x29 */  XK_quoteleft,	XK_asciitilde,	NoSymbol,	NoSymbol,
-    /* 0x2a */  XK_Shift_L,     NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x2b */  XK_backslash,   XK_bar,		NoSymbol,	NoSymbol,
-    /* 0x2c */  XK_Z,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x2d */  XK_X,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x2e */  XK_C,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x2f */  XK_V,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x30 */  XK_B,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x31 */  XK_N,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x32 */  XK_M,           NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x33 */  XK_comma,       XK_less,	NoSymbol,	NoSymbol,
-    /* 0x34 */  XK_period,      XK_greater,	NoSymbol,	NoSymbol,
-    /* 0x35 */  XK_slash,       XK_question,	NoSymbol,	NoSymbol,
-    /* 0x36 */  XK_Shift_R,     NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x37 */  XK_KP_Multiply, NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x38 */  XK_Alt_L,	XK_Meta_L,	NoSymbol,	NoSymbol,
-    /* 0x39 */  XK_space,       NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x3a */  XK_Caps_Lock,   NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x3b */  XK_F1,          NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x3c */  XK_F2,          NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x3d */  XK_F3,          NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x3e */  XK_F4,          NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x3f */  XK_F5,          NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x40 */  XK_F6,          NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x41 */  XK_F7,          NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x42 */  XK_F8,          NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x43 */  XK_F9,          NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x44 */  XK_F10,         NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x45 */  XK_Num_Lock,    NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x46 */  XK_Scroll_Lock,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x47 */  XK_KP_Home,	XK_KP_7,	NoSymbol,	NoSymbol,
-    /* 0x48 */  XK_KP_Up,	XK_KP_8,	NoSymbol,	NoSymbol,
-    /* 0x49 */  XK_KP_Prior,	XK_KP_9,	NoSymbol,	NoSymbol,
-    /* 0x4a */  XK_KP_Subtract, NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x4b */  XK_KP_Left,	XK_KP_4,	NoSymbol,	NoSymbol,
-    /* 0x4c */  XK_KP_Begin,	XK_KP_5,	NoSymbol,	NoSymbol,
-    /* 0x4d */  XK_KP_Right,	XK_KP_6,	NoSymbol,	NoSymbol,
-    /* 0x4e */  XK_KP_Add,      NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x4f */  XK_KP_End,	XK_KP_1,	NoSymbol,	NoSymbol,
-    /* 0x50 */  XK_KP_Down,	XK_KP_2,	NoSymbol,	NoSymbol,
-    /* 0x51 */  XK_KP_Next,	XK_KP_3,	NoSymbol,	NoSymbol,
-    /* 0x52 */  XK_KP_Insert,	XK_KP_0,	NoSymbol,	NoSymbol,
-    /* 0x53 */  XK_KP_Delete,	XK_KP_Decimal,	NoSymbol,	NoSymbol,
-    /* 0x54 */  XK_Sys_Req,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x55 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x56 */  XK_less,	XK_greater,	NoSymbol,	NoSymbol,
-    /* 0x57 */  XK_F11,		NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x58 */  XK_F12,		NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x59 */  XK_Home,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x5a */  XK_Up,		NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x5b */  XK_Prior,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x5c */  XK_Left,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x5d */  XK_Begin,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x5e */  XK_Right,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x5f */  XK_End,		NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x60 */  XK_Down,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x61 */  XK_Next,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x62 */  XK_Insert,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x63 */  XK_Delete,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x64 */  XK_KP_Enter,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x65 */  XK_Control_R,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x66 */  XK_Pause,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x67 */  XK_Print,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x68 */  XK_KP_Divide,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x69 */  XK_Alt_R,	XK_Meta_R,	NoSymbol,	NoSymbol,
-    /* 0x6a */  XK_Break,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x6b */  XK_Meta_L,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x6c */  XK_Meta_R,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x6d */  XK_Menu,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x6e */  XK_F13,		NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x6f */  XK_F14,		NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x70 */  XK_F15,		NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x71 */  XK_F16,		NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x72 */  XK_F17,		NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x73 */  XK_backslash,	XK_underscore,	NoSymbol,	NoSymbol,
-    /* 0x74 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x75 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x76 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x77 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x78 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x79 */  XK_Henkan,	XK_Mode_switch,	NoSymbol,	NoSymbol,
-    /* 0x7a */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x7b */  XK_Muhenkan,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x7c */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x7d */  XK_backslash,	XK_bar,		NoSymbol,	NoSymbol,
-    /* 0x7e */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-    /* 0x7f */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-};
diff --git a/hw/xwin/winkeynames.h b/hw/xwin/winkeynames.h
deleted file mode 100644
index 7c16337..0000000
--- a/hw/xwin/winkeynames.h
+++ /dev/null
@@ -1,202 +0,0 @@
-#ifndef _WINKEYNAMES_H
-#define _WINKEYNAMES_H
-/*
- * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Thomas Roell not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Thomas Roell makes no representations
- * about the suitability of this software for any purpose.  It is provided
- * "as is" without express or implied warranty.
- *
- * THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL THOMAS ROELL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS SOFTWARE.
- *
- */
-
-#define XK_TECHNICAL
-#define	XK_KATAKANA
-#include <X11/keysym.h>
-
-#define GLYPHS_PER_KEY	4
-#define NUM_KEYCODES	248
-#define MIN_KEYCODE     8
-#define MAX_KEYCODE     (NUM_KEYCODES + MIN_KEYCODE - 1)
-
-#define AltMask		Mod1Mask
-#define NumLockMask	Mod2Mask
-#define AltLangMask	Mod3Mask
-#define KanaMask	Mod4Mask
-#define ScrollLockMask	Mod5Mask
-
-#define KeyPressed(k) (keyc->down[k >> 3] & (1 << (k & 7)))
-#define ModifierDown(k) ((keyc->state & (k)) == (k))
-
-/*
- * NOTE: The AT/MF keyboards can generate (via the 8042) two (MF: three)
- *       sets of scancodes. Set3 can only be generated by a MF keyboard.
- *       Set2 sends a makecode for keypress, and the same code prefixed by a
- *       F0 for keyrelease. This is a little bit ugly to handle. Thus we use
- *       here for X386 the PC/XT compatible Set1. This set uses 8bit scancodes.
- *       Bit 7 ist set if the key is released. The code E0 switches to a
- *       different meaning to add the new MF cursorkeys, while not breaking old
- *       applications. E1 is another special prefix. Since I assume that there
- *       will be further versions of PC/XT scancode compatible keyboards, we
- *       may be in trouble one day.
- *
- * IDEA: 1) Use Set2 on AT84 keyboards and translate it to MF Set3.
- *       2) Use the keyboards native set and translate it to common keysyms.
- */
-
-/*
- * definition of the AT84/MF101/MF102 Keyboard:
- * ============================================================
- *       Defined             Key Cap Glyphs       Pressed value
- *      Key Name            Main       Also       (hex)    (dec)
- *      ----------------   ---------- -------    ------    ------
- */
-
-#define KEY_Escape       /* Escape                0x01  */    1  
-#define KEY_1            /* 1           !         0x02  */    2 
-#define KEY_2            /* 2           @         0x03  */    3 
-#define KEY_3            /* 3           #         0x04  */    4 
-#define KEY_4            /* 4           $         0x05  */    5 
-#define KEY_5            /* 5           %         0x06  */    6 
-#define KEY_6            /* 6           ^         0x07  */    7 
-#define KEY_7            /* 7           &         0x08  */    8 
-#define KEY_8            /* 8           *         0x09  */    9 
-#define KEY_9            /* 9           (         0x0a  */   10 
-#define KEY_0            /* 0           )         0x0b  */   11 
-#define KEY_Minus        /* - (Minus)   _ (Under) 0x0c  */   12
-#define KEY_Equal        /* = (Equal)   +         0x0d  */   13 
-#define KEY_BackSpace    /* Back Space            0x0e  */   14 
-#define KEY_Tab          /* Tab                   0x0f  */   15
-#define KEY_Q            /* Q                     0x10  */   16
-#define KEY_W            /* W                     0x11  */   17
-#define KEY_E            /* E                     0x12  */   18
-#define KEY_R            /* R                     0x13  */   19
-#define KEY_T            /* T                     0x14  */   20
-#define KEY_Y            /* Y                     0x15  */   21
-#define KEY_U            /* U                     0x16  */   22
-#define KEY_I            /* I                     0x17  */   23
-#define KEY_O            /* O                     0x18  */   24
-#define KEY_P            /* P                     0x19  */   25
-#define KEY_LBrace       /* [           {         0x1a  */   26
-#define KEY_RBrace       /* ]           }         0x1b  */   27 
-#define KEY_Enter        /* Enter                 0x1c  */   28
-#define KEY_LCtrl        /* Ctrl(left)            0x1d  */   29
-#define KEY_A            /* A                     0x1e  */   30
-#define KEY_S            /* S                     0x1f  */   31
-#define KEY_D            /* D                     0x20  */   32 
-#define KEY_F            /* F                     0x21  */   33
-#define KEY_G            /* G                     0x22  */   34
-#define KEY_H            /* H                     0x23  */   35
-#define KEY_J            /* J                     0x24  */   36
-#define KEY_K            /* K                     0x25  */   37
-#define KEY_L            /* L                     0x26  */   38
-#define KEY_SemiColon    /* ;(SemiColon) :(Colon) 0x27  */   39
-#define KEY_Quote        /* ' (Apostr)  " (Quote) 0x28  */   40
-#define KEY_Tilde        /* ` (Accent)  ~ (Tilde) 0x29  */   41
-#define KEY_ShiftL       /* Shift(left)           0x2a  */   42
-#define KEY_BSlash       /* \(BckSlash) |(VertBar)0x2b  */   43
-#define KEY_Z            /* Z                     0x2c  */   44
-#define KEY_X            /* X                     0x2d  */   45
-#define KEY_C            /* C                     0x2e  */   46
-#define KEY_V            /* V                     0x2f  */   47
-#define KEY_B            /* B                     0x30  */   48
-#define KEY_N            /* N                     0x31  */   49
-#define KEY_M            /* M                     0x32  */   50
-#define KEY_Comma        /* , (Comma)   < (Less)  0x33  */   51
-#define KEY_Period       /* . (Period)  >(Greater)0x34  */   52
-#define KEY_Slash        /* / (Slash)   ?         0x35  */   53
-#define KEY_ShiftR       /* Shift(right)          0x36  */   54
-#define KEY_KP_Multiply  /* *                     0x37  */   55
-#define KEY_Alt          /* Alt(left)             0x38  */   56
-#define KEY_Space        /*   (SpaceBar)          0x39  */   57
-#define KEY_CapsLock     /* CapsLock              0x3a  */   58
-#define KEY_F1           /* F1                    0x3b  */   59
-#define KEY_F2           /* F2                    0x3c  */   60
-#define KEY_F3           /* F3                    0x3d  */   61
-#define KEY_F4           /* F4                    0x3e  */   62
-#define KEY_F5           /* F5                    0x3f  */   63
-#define KEY_F6           /* F6                    0x40  */   64
-#define KEY_F7           /* F7                    0x41  */   65
-#define KEY_F8           /* F8                    0x42  */   66
-#define KEY_F9           /* F9                    0x43  */   67
-#define KEY_F10          /* F10                   0x44  */   68
-#define KEY_NumLock      /* NumLock               0x45  */   69
-#define KEY_ScrollLock   /* ScrollLock            0x46  */   70
-#define KEY_KP_7         /* 7           Home      0x47  */   71 
-#define KEY_KP_8         /* 8           Up        0x48  */   72 
-#define KEY_KP_9         /* 9           PgUp      0x49  */   73 
-#define KEY_KP_Minus     /* - (Minus)             0x4a  */   74
-#define KEY_KP_4         /* 4           Left      0x4b  */   75
-#define KEY_KP_5         /* 5                     0x4c  */   76
-#define KEY_KP_6         /* 6           Right     0x4d  */   77
-#define KEY_KP_Plus      /* + (Plus)              0x4e  */   78
-#define KEY_KP_1         /* 1           End       0x4f  */   79
-#define KEY_KP_2         /* 2           Down      0x50  */   80
-#define KEY_KP_3         /* 3           PgDown    0x51  */   81
-#define KEY_KP_0         /* 0           Insert    0x52  */   82
-#define KEY_KP_Decimal   /* . (Decimal) Delete    0x53  */   83 
-#define KEY_SysReqest    /* SysReqest             0x54  */   84
-                         /* NOTUSED               0x55  */
-#define KEY_Less         /* < (Less)   >(Greater) 0x56  */   86
-#define KEY_F11          /* F11                   0x57  */   87
-#define KEY_F12          /* F12                   0x58  */   88
-
-#define KEY_Prefix0      /* special               0x60  */   96
-#define KEY_Prefix1      /* specail               0x61  */   97
-
-/*
- * The 'scancodes' below are generated by the server, because the MF101/102
- * keyboard sends them as sequence of other scancodes
- */
-#define KEY_Home         /* Home                  0x59  */   89
-#define KEY_Up           /* Up                    0x5a  */   90
-#define KEY_PgUp         /* PgUp                  0x5b  */   91
-#define KEY_Left         /* Left                  0x5c  */   92
-#define KEY_Begin        /* Begin                 0x5d  */   93
-#define KEY_Right        /* Right                 0x5e  */   94
-#define KEY_End          /* End                   0x5f  */   95
-#define KEY_Down         /* Down                  0x60  */   96
-#define KEY_PgDown       /* PgDown                0x61  */   97
-#define KEY_Insert       /* Insert                0x62  */   98
-#define KEY_Delete       /* Delete                0x63  */   99
-#define KEY_KP_Enter     /* Enter                 0x64  */  100
-#define KEY_RCtrl        /* Ctrl(right)           0x65  */  101
-#define KEY_Pause        /* Pause                 0x66  */  102
-#define KEY_Print        /* Print                 0x67  */  103
-#define KEY_KP_Divide    /* Divide                0x68  */  104
-#define KEY_AltLang      /* AtlLang(right)        0x69  */  105
-#define KEY_Break        /* Break                 0x6a  */  106
-#define KEY_LMeta        /* Left Meta             0x6b  */  107
-#define KEY_RMeta        /* Right Meta            0x6c  */  108
-#define KEY_Menu         /* Menu                  0x6d  */  109
-#define KEY_F13          /* F13                   0x6e  */  110
-#define KEY_F14          /* F14                   0x6f  */  111
-#define KEY_F15          /* F15                   0x70  */  112
-#define KEY_F16          /* F16                   0x71  */  113
-#define KEY_F17          /* F17                   0x72  */  114
-#define KEY_KP_DEC       /* KP_DEC                0x73  */  115
-#define KEY_KP_Equal	 /* Equal (Keypad)        0x76  */  118
-#define KEY_XFER         /* Kanji Transfer        0x79  */  121
-#define KEY_NFER         /* No Kanji Transfer     0x7b  */  123
-#define KEY_Yen          /* Yen                   0x7d  */  125
-#define KEY_HKTG         /* Hirugana/Katakana tog 0xc8  */  200
-#define KEY_BSlash2      /* \           _         0xcb  */  203
-
-/* These are for "notused" and "unknown" entries in translation maps. */
-#define KEY_NOTUSED	  0
-#define KEY_UNKNOWN	255
-
-#endif /* _WINKEYNAMES_H */
diff --git a/hw/xwin/winlayouts.h b/hw/xwin/winlayouts.h
deleted file mode 100644
index cc07524..0000000
--- a/hw/xwin/winlayouts.h
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-/* Definitions for various keyboard layouts from windows and their 
- * XKB settings.
- */
-
-typedef struct 
-{
-    unsigned int winlayout;
-    int winkbtype;
-    char *xkbmodel;
-    char *xkblayout;
-    char *xkbvariant;
-    char *xkboptions;
-    char *layoutname;
-} WinKBLayoutRec, *WinKBLayoutPtr;
-
-WinKBLayoutRec winKBLayouts[] = 
-{
-    {  0x405, -1, "pc105", "cz",      NULL, NULL, "Czech"},
-    {0x10405, -1, "pc105", "cz_qwerty", NULL, NULL, "Czech (QWERTY)"},
-    {  0x406, -1, "pc105", "dk",      NULL, NULL, "Danish"},
-    {  0x407, -1, "pc105", "de",      NULL, NULL, "German (Germany)"},
-    {0x10407, -1, "pc105", "de",      NULL, NULL, "German (Germany, IBM)"},
-    {  0x807, -1, "pc105", "de_CH",   NULL, NULL, "German (Switzerland)"},
-    {  0x409, -1, "pc105", "us",      NULL, NULL, "English (USA)"},
-    {0x10409, -1, "pc105", "dvorak",  NULL, NULL, "English (USA, Dvorak)"}, 
-    {0x20409, -1, "pc105", "us_intl", NULL, NULL, "English (USA, International)"}, 
-    {  0x809, -1, "pc105", "gb",      NULL, NULL, "English (United Kingdom)"},
-    { 0x1809, -1, "pc105", "ie",      NULL, NULL, "Irish"},
-    {  0x40a, -1, "pc105", "es",      NULL, NULL, "Spanish (Spain, Traditional Sort)"},
-    {  0x40b, -1, "pc105", "fi",      NULL, NULL, "Finnish"},
-    {  0x40c, -1, "pc105", "fr",      NULL, NULL, "French (Standard)"},
-    {  0x80c, -1, "pc105", "be",      NULL, NULL, "French (Belgian)"},
-    {  0xc0c, -1, "pc105", "ca_enhanced", NULL, NULL, "French (Canada)"},
-    { 0x100c, -1, "pc105", "fr_CH",   NULL, NULL, "French (Switzerland)"},
-    {  0x40e, -1, "pc105", "hu",      NULL, NULL, "Hungarian"},
-    {  0x410, -1, "pc105", "it",      NULL, NULL, "Italian"},
-    {  0x411,  7, "jp106", "jp",      NULL, NULL, "Japanese"},
-    {  0x813, -1, "pc105", "be",      NULL, NULL, "Dutch (Belgian)"},  
-    {  0x414, -1, "pc105", "no",      NULL, NULL, "Norwegian"},
-    {  0x416, -1, "pc105", "br",      NULL, NULL, "Portuguese (Brazil, ABNT)"},
-    {0x10416, -1, "abnt2", "br",      NULL, NULL, "Portuguese (Brazil, ABNT2)"},
-    {  0x816, -1, "pc105", "pt",      NULL, NULL, "Portuguese (Portugal)"},
-    {  0x41d, -1, "pc105", "se",      NULL, NULL, "Swedish (Sweden)"},
-    {     -1, -1, NULL,    NULL,      NULL, NULL, NULL}
-};
-
-/* Listing of language codes from MSDN */
-/*
-Support ID       XKB        Language
-====================================================================
-   ?    0x0000              Language Neutral
-   ?    0x0400              Process or User Default Language
-   ?    0x0800              System Default Language
-        0x0401              Arabic (Saudi Arabia)
-        0x0801              Arabic (Iraq)
-        0x0c01              Arabic (Egypt)
-        0x1001              Arabic (Libya)
-        0x1401              Arabic (Algeria)
-        0x1801              Arabic (Morocco)
-        0x1c01              Arabic (Tunisia)
-        0x2001              Arabic (Oman)
-        0x2401              Arabic (Yemen)
-        0x2801              Arabic (Syria)
-        0x2c01              Arabic (Jordan)
-        0x3001              Arabic (Lebanon)
-        0x3401              Arabic (Kuwait)
-        0x3801              Arabic (U.A.E.)
-        0x3c01              Arabic (Bahrain)
-        0x4001              Arabic (Qatar)
-                            Arabic (102) AZERTY        				
-        0x0402              Bulgarian
-        0x0403              Catalan
-        0x0404              Chinese (Taiwan)
-        0x0804              Chinese (PRC)
-        0x0c04              Chinese (Hong Kong SAR, PRC)
-        0x1004              Chinese (Singapore)
-        0x1404              Chinese (Macao SAR) (98/ME,2K/XP)
-   X    0x0405  cz          Czech
-   X            cz_qwerty   Czech (QWERTY)
-                            Czech (Programmers)
-   X    0x0406  dk          Danish
-   X    0x0407  de          German (Standard)
-   X    0x0807  de_CH       German (Switzerland)
-        0x0c07              German (Austria)
-        0x1007              German (Luxembourg)
-        0x1407              German (Liechtenstein)
-        0x0408              Greek
-   X    0x0409  us          English (United States)
-   X    0x0809  gb          English (United Kingdom)
-        0x0c09              English (Australian)
-        0x1009              English (Canadian)
-        0x1409              English (New Zealand)
-   X    0x1809  ie          English (Ireland)
-        0x1c09              English (South Africa)
-        0x2009              English (Jamaica)
-        0x2409              English (Caribbean)
-        0x2809              English (Belize)
-        0x2c09              English (Trinidad)
-        0x3009              English (Zimbabwe) (98/ME,2K/XP)
-        0x3409              English (Philippines) (98/ME,2K/XP)
-   X    0x040a  es          Spanish (Spain, Traditional Sort)
-        0x080a              Spanish (Mexican)
-        0x0c0a              Spanish (Spain, Modern Sort)
-        0x100a              Spanish (Guatemala)
-        0x140a              Spanish (Costa Rica)
-        0x180a              Spanish (Panama)
-        0x1c0a              Spanish (Dominican Republic)
-        0x200a              Spanish (Venezuela)
-        0x240a              Spanish (Colombia)
-        0x280a              Spanish (Peru)
-        0x2c0a              Spanish (Argentina)
-        0x300a              Spanish (Ecuador)
-        0x340a              Spanish (Chile)
-        0x380a              Spanish (Uruguay)
-        0x3c0a              Spanish (Paraguay)
-        0x400a              Spanish (Bolivia)
-        0x440a              Spanish (El Salvador)
-        0x480a              Spanish (Honduras)
-        0x4c0a              Spanish (Nicaragua)
-        0x500a              Spanish (Puerto Rico)
-   X    0x040b  fi          Finnish
-                            Finnish (with Sami)
-   X    0x040c  fr          French (Standard)
-   X    0x080c  be          French (Belgian)
-   .    0x0c0c              French (Canadian)
-                            French (Canadian, Legacy)
-                            Canadian (Multilingual)
-   X    0x100c  fr_CH       French (Switzerland)
-        0x140c              French (Luxembourg)
-        0x180c              French (Monaco) (98/ME,2K/XP)
-        0x040d              Hebrew
-   X    0x040e  hu          Hungarian
-   .    0x040f              Icelandic
-   X    0x0410  it          Italian (Standard)
-        0x0810              Italian (Switzerland)
-   X    0x0411  jp          Japanese
-        0x0412              Korean
-        0x0812              Korean (Johab) (95,NT)
-   .    0x0413              Dutch (Netherlands)
-   X    0x0813  be          Dutch (Belgium)
-   X    0x0414  no          Norwegian (Bokmal)
-        0x0814              Norwegian (Nynorsk)
-   .    0x0415              Polish
-   X    0x0416  br          Portuguese (Brazil)
-   X    0x0816  pt          Portuguese (Portugal)
-   .    0x0418              Romanian
-        0x0419              Russian
-   .    0x041a              Croatian
-   .    0x081a              Serbian (Latin)
-   .    0x0c1a              Serbian (Cyrillic)
-        0x101a              Croatian (Bosnia and Herzegovina)
-        0x141a              Bosnian (Bosnia and Herzegovina)
-        0x181a              Serbian (Latin, Bosnia, and Herzegovina)
-        0x1c1a              Serbian (Cyrillic, Bosnia, and Herzegovina)
-   .    0x041b              Slovak
-   .    0x041c              Albanian
-   X    0x041d  se          Swedish
-        0x081d              Swedish (Finland)
-        0x041e              Thai
-        0x041f              Turkish
-        0x0420              Urdu (Pakistan) (98/ME,2K/XP) 
-        0x0820              Urdu (India)
-        0x0421              Indonesian
-        0x0422              Ukrainian
-        0x0423              Belarusian
-   .    0x0424              Slovenian
-        0x0425              Estonian
-        0x0426              Latvian
-        0x0427              Lithuanian
-        0x0827              Lithuanian (Classic) (98)
-        0x0429              Farsi
-        0x042a              Vietnamese (98/ME,NT,2K/XP)
-        0x042b              Armenian. This is Unicode only. (2K/XP)
-                            Armenian Eastern
-                            Armenian Western
-        0x042c              Azeri (Latin)
-        0x082c              Azeri (Cyrillic)
-        0x042d              Basque
-        0x042f              Macedonian (FYROM)
-        0x0430              Sutu
-        0x0432              Setswana/Tswana (South Africa)
-        0x0434              isiXhosa/Xhosa (South Africa)
-        0x0435              isiZulu/Zulu (South Africa)
-        0x0436              Afrikaans
-        0x0437              Georgian. This is Unicode only. (2K/XP)
-   .    0x0438              Faeroese
-        0x0439              Hindi. This is Unicode only. (2K/XP)
-        0x043a              Maltese (Malta)
-        0x043b              Sami, Northern (Norway)
-        0x083b              Sami, Northern (Sweden)
-        0x0c3b              Sami, Northern (Finland)
-        0x103b              Sami, Lule (Norway)
-        0x143b              Sami, Lule (Sweden)
-        0x183b              Sami, Southern (Norway)
-        0x1c3b              Sami, Southern (Sweden)
-        0x203b              Sami, Skolt (Finland)
-        0x243b              Sami, Inari (Finland)
-        0x043e              Malay (Malaysian)
-        0x083e              Malay (Brunei Darussalam)
-        0x0440              Kyrgyz. (XP)
-        0x0441              Swahili (Kenya)
-        0x0443              Uzbek (Latin)
-        0x0843              Uzbek (Cyrillic)
-        0x0444              Tatar (Tatarstan)
-        0x0445              Bengali (India)
-                            Bengali (Inscript)
-        0x0446              Punjabi. This is Unicode only. (XP)
-        0x0447              Gujarati. This is Unicode only. (XP)
-        0x0449              Tamil. This is Unicode only. (2K/XP)
-        0x044a              Telugu. This is Unicode only. (XP)
-        0x044b              Kannada. This is Unicode only. (XP)
-        0x044c              Malayalam (India)
-        0x044e              Marathi. This is Unicode only. (2K/XP)
-        0x044f              Sanskrit. This is Unicode only. (2K/XP)
-        0x0450              Mongolian (XP)
-        0x0452              Welsh (United Kingdom)
-        0x0455              Burmese
-        0x0456              Galician (XP)
-        0x0457              Konkani. This is Unicode only. (2K/XP)
-        0x045a              Syriac. This is Unicode only. (XP)
-        0x0465              Divehi. This is Unicode only. (XP)
-                            Divehi (Phonetic)
-                            Divehi (Typewriter)
-        0x046b              Quechua (Bolivia)
-        0x086b              Quechua (Ecuador)
-        0x0c6b              Quechua (Peru)
-        0x046c              Sesotho sa Leboa/Northern Sotho (South Africa)
-        0x007f              LOCALE_INVARIANT. See MAKELCID.
-        0x0481              Maori (New Zealand)
-*/    
-
-
diff --git a/hw/xwin/winmessages.h b/hw/xwin/winmessages.h
deleted file mode 100755
index ae50dc4..0000000
--- a/hw/xwin/winmessages.h
+++ /dev/null
@@ -1,1030 +0,0 @@
-#ifndef __WINMESSAGES_H__
-#define __WINMESSAGES_H__
-static const unsigned MESSAGE_NAMES_LEN =1024;
-static const char *MESSAGE_NAMES[1024] = {
-	"WM_NULL",
-	"WM_CREATE",
-	"WM_DESTROY",
-	"WM_MOVE",
-	"4",
-	"WM_SIZE",
-	"WM_ACTIVATE",
-	"WM_SETFOCUS",
-	"WM_KILLFOCUS",
-	"9",
-	"WM_ENABLE",
-	"WM_SETREDRAW",
-	"WM_SETTEXT",
-	"WM_GETTEXT",
-	"WM_GETTEXTLENGTH",
-	"WM_PAINT",
-	"WM_CLOSE",
-	"WM_QUERYENDSESSION",
-	"WM_QUIT",
-	"WM_QUERYOPEN",
-	"WM_ERASEBKGND",
-	"WM_SYSCOLORCHANGE",
-	"WM_ENDSESSION",
-	"23",
-	"WM_SHOWWINDOW",
-	"25",
-	"WM_WININICHANGE",
-	"WM_DEVMODECHANGE",
-	"WM_ACTIVATEAPP",
-	"WM_FONTCHANGE",
-	"WM_TIMECHANGE",
-	"WM_CANCELMODE",
-	NULL /* WM_SETCURSOR */,
-	"WM_MOUSEACTIVATE",
-	"WM_CHILDACTIVATE",
-	"WM_QUEUESYNC",
-	"WM_GETMINMAXINFO",
-	"37",
-	"WM_PAINTICON",
-	"WM_ICONERASEBKGND",
-	"WM_NEXTDLGCTL",
-	"41",
-	"WM_SPOOLERSTATUS",
-	"WM_DRAWITEM",
-	"WM_MEASUREITEM",
-	"WM_DELETEITEM",
-	"WM_VKEYTOITEM",
-	"WM_CHARTOITEM",
-	"WM_SETFONT",
-	"WM_GETFONT",
-	"WM_SETHOTKEY",
-	"WM_GETHOTKEY",
-	"52",
-	"53",
-	"54",
-	"WM_QUERYDRAGICON",
-	"56",
-	"WM_COMPAREITEM",
-	"58",
-	"59",
-	"60",
-	"61",
-	"62",
-	"63",
-	"64",
-	"WM_COMPACTING",
-	"66",
-	"67",
-	"WM_COMMNOTIFY",
-	"69",
-	"WM_WINDOWPOSCHANGING",
-	"WM_WINDOWPOSCHANGED",
-	"WM_POWER",
-	"73",
-	"WM_COPYDATA",
-	"WM_CANCELJOURNAL",
-	"76",
-	"77",
-	"WM_NOTIFY",
-	"79",
-	"WM_INPUTLANGCHANGEREQUEST",
-	"WM_INPUTLANGCHANGE",
-	"WM_TCARD",
-	"WM_HELP",
-	"WM_USERCHANGED",
-	"WM_NOTIFYFORMAT",
-	"86",
-	"87",
-	"88",
-	"89",
-	"90",
-	"91",
-	"92",
-	"93",
-	"94",
-	"95",
-	"96",
-	"97",
-	"98",
-	"99",
-	"100",
-	"101",
-	"102",
-	"103",
-	"104",
-	"105",
-	"106",
-	"107",
-	"108",
-	"109",
-	"110",
-	"111",
-	"112",
-	"113",
-	"114",
-	"115",
-	"116",
-	"117",
-	"118",
-	"119",
-	"120",
-	"121",
-	"122",
-	"WM_CONTEXTMENU",
-	"WM_STYLECHANGING",
-	"WM_STYLECHANGED",
-	"WM_DISPLAYCHANGE",
-	"WM_GETICON",
-	"WM_SETICON",
-	"WM_NCCREATE",
-	"WM_NCDESTROY",
-	"WM_NCCALCSIZE",
-	NULL /* WM_NCHITTEST */,
-	"WM_NCPAINT",
-	"WM_NCACTIVATE",
-	"WM_GETDLGCODE",
-	"WM_SYNCPAINT",
-	"137",
-	"138",
-	"139",
-	"140",
-	"141",
-	"142",
-	"143",
-	"144",
-	"145",
-	"146",
-	"147",
-	"148",
-	"149",
-	"150",
-	"151",
-	"152",
-	"153",
-	"154",
-	"155",
-	"156",
-	"157",
-	"158",
-	"159",
-	NULL /* WM_NCMOUSEMOVE */,
-	"WM_NCLBUTTONDOWN",
-	"WM_NCLBUTTONUP",
-	"WM_NCLBUTTONDBLCLK",
-	"WM_NCRBUTTONDOWN",
-	"WM_NCRBUTTONUP",
-	"WM_NCRBUTTONDBLCLK",
-	"WM_NCMBUTTONDOWN",
-	"WM_NCMBUTTONUP",
-	"WM_NCMBUTTONDBLCLK",
-	"170",
-	"171",
-	"172",
-	"173",
-	"174",
-	"175",
-	"176",
-	"177",
-	"178",
-	"179",
-	"180",
-	"181",
-	"182",
-	"183",
-	"184",
-	"185",
-	"186",
-	"187",
-	"188",
-	"189",
-	"190",
-	"191",
-	"192",
-	"193",
-	"194",
-	"195",
-	"196",
-	"197",
-	"198",
-	"199",
-	"200",
-	"201",
-	"202",
-	"203",
-	"204",
-	"205",
-	"206",
-	"207",
-	"208",
-	"209",
-	"210",
-	"211",
-	"212",
-	"213",
-	"214",
-	"215",
-	"216",
-	"217",
-	"218",
-	"219",
-	"220",
-	"221",
-	"222",
-	"223",
-	"224",
-	"225",
-	"226",
-	"227",
-	"228",
-	"229",
-	"230",
-	"231",
-	"232",
-	"233",
-	"234",
-	"235",
-	"236",
-	"237",
-	"238",
-	"239",
-	"240",
-	"241",
-	"242",
-	"243",
-	"244",
-	"245",
-	"246",
-	"247",
-	"248",
-	"249",
-	"250",
-	"251",
-	"252",
-	"253",
-	"254",
-	"255",
-	"WM_KEYDOWN",
-	"WM_KEYUP",
-	"WM_CHAR",
-	"WM_DEADCHAR",
-	"WM_SYSKEYDOWN",
-	"WM_SYSKEYUP",
-	"WM_SYSCHAR",
-	"WM_SYSDEADCHAR",
-	"WM_CONVERTREQUESTEX",
-	"265",
-	"266",
-	"267",
-	"268",
-	"WM_IME_STARTCOMPOSITION",
-	"WM_IME_ENDCOMPOSITION",
-	"WM_IME_KEYLAST",
-	"WM_INITDIALOG",
-	"WM_COMMAND",
-	"WM_SYSCOMMAND",
-	NULL /* WM_TIMER */,
-	"WM_HSCROLL",
-	"WM_VSCROLL",
-	"WM_INITMENU",
-	"WM_INITMENUPOPUP",
-	"280",
-	"281",
-	"282",
-	"283",
-	"284",
-	"285",
-	"286",
-	"WM_MENUSELECT",
-	"WM_MENUCHAR",
-	"WM_ENTERIDLE",
-	"290",
-	"291",
-	"292",
-	"293",
-	"294",
-	"295",
-	"296",
-	"297",
-	"298",
-	"299",
-	"300",
-	"301",
-	"302",
-	"303",
-	"304",
-	"305",
-	"WM_CTLCOLORMSGBOX",
-	"WM_CTLCOLOREDIT",
-	"WM_CTLCOLORLISTBOX",
-	"WM_CTLCOLORBTN",
-	"WM_CTLCOLORDLG",
-	"WM_CTLCOLORSCROLLBAR",
-	"WM_CTLCOLORSTATIC",
-	"313",
-	"314",
-	"315",
-	"316",
-	"317",
-	"318",
-	"319",
-	"320",
-	"321",
-	"322",
-	"323",
-	"324",
-	"325",
-	"326",
-	"327",
-	"328",
-	"329",
-	"330",
-	"331",
-	"332",
-	"333",
-	"334",
-	"335",
-	"336",
-	"337",
-	"338",
-	"339",
-	"340",
-	"341",
-	"342",
-	"343",
-	"344",
-	"345",
-	"346",
-	"347",
-	"348",
-	"349",
-	"350",
-	"351",
-	"352",
-	"353",
-	"354",
-	"355",
-	"356",
-	"357",
-	"358",
-	"359",
-	"360",
-	"361",
-	"362",
-	"363",
-	"364",
-	"365",
-	"366",
-	"367",
-	"368",
-	"369",
-	"370",
-	"371",
-	"372",
-	"373",
-	"374",
-	"375",
-	"376",
-	"377",
-	"378",
-	"379",
-	"380",
-	"381",
-	"382",
-	"383",
-	"384",
-	"385",
-	"386",
-	"387",
-	"388",
-	"389",
-	"390",
-	"391",
-	"392",
-	"393",
-	"394",
-	"395",
-	"396",
-	"397",
-	"398",
-	"399",
-	"400",
-	"401",
-	"402",
-	"403",
-	"404",
-	"405",
-	"406",
-	"407",
-	"408",
-	"409",
-	"410",
-	"411",
-	"412",
-	"413",
-	"414",
-	"415",
-	"416",
-	"417",
-	"418",
-	"419",
-	"420",
-	"421",
-	"422",
-	"423",
-	"424",
-	"425",
-	"426",
-	"427",
-	"428",
-	"429",
-	"430",
-	"431",
-	"432",
-	"433",
-	"434",
-	"435",
-	"436",
-	"437",
-	"438",
-	"439",
-	"440",
-	"441",
-	"442",
-	"443",
-	"444",
-	"445",
-	"446",
-	"447",
-	"448",
-	"449",
-	"450",
-	"451",
-	"452",
-	"453",
-	"454",
-	"455",
-	"456",
-	"457",
-	"458",
-	"459",
-	"460",
-	"461",
-	"462",
-	"463",
-	"464",
-	"465",
-	"466",
-	"467",
-	"468",
-	"469",
-	"470",
-	"471",
-	"472",
-	"473",
-	"474",
-	"475",
-	"476",
-	"477",
-	"478",
-	"479",
-	"480",
-	"481",
-	"482",
-	"483",
-	"484",
-	"485",
-	"486",
-	"487",
-	"488",
-	"489",
-	"490",
-	"491",
-	"492",
-	"493",
-	"494",
-	"495",
-	"496",
-	"497",
-	"498",
-	"499",
-	"500",
-	"501",
-	"502",
-	"503",
-	"504",
-	"505",
-	"506",
-	"507",
-	"508",
-	"509",
-	"510",
-	"511",
-	NULL /* WM_MOUSEMOVE */,
-	"WM_LBUTTONDOWN",
-	"WM_LBUTTONUP",
-	"WM_LBUTTONDBLCLK",
-	"WM_RBUTTONDOWN",
-	"WM_RBUTTONUP",
-	"WM_RBUTTONDBLCLK",
-	"WM_MBUTTONDOWN",
-	"WM_MBUTTONUP",
-	"WM_MBUTTONDBLCLK",
-	"WM_MOUSEWHEEL",
-	"WM_XBUTTONDOWN",
-	"WM_XBUTTONUP",
-	"WM_XBUTTONDBLCLK",
-	"526",
-	"527",
-	"WM_PARENTNOTIFY",
-	"WM_ENTERMENULOOP",
-	"WM_EXITMENULOOP",
-	"WM_NEXTMENU",
-	"WM_SIZING",
-	"WM_CAPTURECHANGED",
-	"WM_MOVING",
-	"535",
-	"WM_POWERBROADCAST",
-	"WM_DEVICECHANGE",
-	"538",
-	"539",
-	"540",
-	"541",
-	"542",
-	"543",
-	"WM_MDICREATE",
-	"WM_MDIDESTROY",
-	"WM_MDIACTIVATE",
-	"WM_MDIRESTORE",
-	"WM_MDINEXT",
-	"WM_MDIMAXIMIZE",
-	"WM_MDITILE",
-	"WM_MDICASCADE",
-	"WM_MDIICONARRANGE",
-	"WM_MDIGETACTIVE",
-	"554",
-	"555",
-	"556",
-	"557",
-	"558",
-	"559",
-	"WM_MDISETMENU",
-	"WM_ENTERSIZEMOVE",
-	"WM_EXITSIZEMOVE",
-	"WM_DROPFILES",
-	"WM_MDIREFRESHMENU",
-	"565",
-	"566",
-	"567",
-	"568",
-	"569",
-	"570",
-	"571",
-	"572",
-	"573",
-	"574",
-	"575",
-	"576",
-	"577",
-	"578",
-	"579",
-	"580",
-	"581",
-	"582",
-	"583",
-	"584",
-	"585",
-	"586",
-	"587",
-	"588",
-	"589",
-	"590",
-	"591",
-	"592",
-	"593",
-	"594",
-	"595",
-	"596",
-	"597",
-	"598",
-	"599",
-	"600",
-	"601",
-	"602",
-	"603",
-	"604",
-	"605",
-	"606",
-	"607",
-	"608",
-	"609",
-	"610",
-	"611",
-	"612",
-	"613",
-	"614",
-	"615",
-	"616",
-	"617",
-	"618",
-	"619",
-	"620",
-	"621",
-	"622",
-	"623",
-	"624",
-	"625",
-	"626",
-	"627",
-	"628",
-	"629",
-	"630",
-	"631",
-	"632",
-	"633",
-	"634",
-	"635",
-	"636",
-	"637",
-	"638",
-	"639",
-	"640",
-	"WM_IME_SETCONTEXT",
-	"WM_IME_NOTIFY",
-	"WM_IME_CONTROL",
-	"WM_IME_COMPOSITIONFULL",
-	"WM_IME_SELECT",
-	"WM_IME_CHAR",
-	"647",
-	"648",
-	"649",
-	"650",
-	"651",
-	"652",
-	"653",
-	"654",
-	"655",
-	"WM_IME_KEYDOWN",
-	"WM_IME_KEYUP",
-	"658",
-	"659",
-	"660",
-	"661",
-	"662",
-	"663",
-	"664",
-	"665",
-	"666",
-	"667",
-	"668",
-	"669",
-	"670",
-	"671",
-	"672",
-	"WM_MOUSEHOVER",
-	"674",
-	"WM_MOUSELEAVE",
-	"676",
-	"677",
-	"678",
-	"679",
-	"680",
-	"681",
-	"682",
-	"683",
-	"684",
-	"685",
-	"686",
-	"687",
-	"688",
-	"689",
-	"690",
-	"691",
-	"692",
-	"693",
-	"694",
-	"695",
-	"696",
-	"697",
-	"698",
-	"699",
-	"700",
-	"701",
-	"702",
-	"703",
-	"704",
-	"705",
-	"706",
-	"707",
-	"708",
-	"709",
-	"710",
-	"711",
-	"712",
-	"713",
-	"714",
-	"715",
-	"716",
-	"717",
-	"718",
-	"719",
-	"720",
-	"721",
-	"722",
-	"723",
-	"724",
-	"725",
-	"726",
-	"727",
-	"728",
-	"729",
-	"730",
-	"731",
-	"732",
-	"733",
-	"734",
-	"735",
-	"736",
-	"737",
-	"738",
-	"739",
-	"740",
-	"741",
-	"742",
-	"743",
-	"744",
-	"745",
-	"746",
-	"747",
-	"748",
-	"749",
-	"750",
-	"751",
-	"752",
-	"753",
-	"754",
-	"755",
-	"756",
-	"757",
-	"758",
-	"759",
-	"760",
-	"761",
-	"762",
-	"763",
-	"764",
-	"765",
-	"766",
-	"767",
-	"WM_CUT",
-	"WM_COPY",
-	"WM_PASTE",
-	"WM_CLEAR",
-	"WM_UNDO",
-	"WM_RENDERFORMAT",
-	"WM_RENDERALLFORMATS",
-	"WM_DESTROYCLIPBOARD",
-	"WM_DRAWCLIPBOARD",
-	"WM_PAINTCLIPBOARD",
-	"WM_VSCROLLCLIPBOARD",
-	"WM_SIZECLIPBOARD",
-	"WM_ASKCBFORMATNAME",
-	"WM_CHANGECBCHAIN",
-	"WM_HSCROLLCLIPBOARD",
-	"WM_QUERYNEWPALETTE",
-	"WM_PALETTEISCHANGING",
-	"WM_PALETTECHANGED",
-	"WM_HOTKEY",
-	"787",
-	"788",
-	"789",
-	"790",
-	"WM_PRINT",
-	"WM_PRINTCLIENT",
-	"793",
-	"794",
-	"795",
-	"796",
-	"797",
-	"798",
-	"799",
-	"800",
-	"801",
-	"802",
-	"803",
-	"804",
-	"805",
-	"806",
-	"807",
-	"808",
-	"809",
-	"810",
-	"811",
-	"812",
-	"813",
-	"814",
-	"815",
-	"816",
-	"817",
-	"818",
-	"819",
-	"820",
-	"821",
-	"822",
-	"823",
-	"824",
-	"825",
-	"826",
-	"827",
-	"828",
-	"829",
-	"830",
-	"831",
-	"832",
-	"833",
-	"834",
-	"835",
-	"836",
-	"837",
-	"838",
-	"839",
-	"840",
-	"841",
-	"842",
-	"843",
-	"844",
-	"845",
-	"846",
-	"847",
-	"848",
-	"849",
-	"850",
-	"851",
-	"852",
-	"853",
-	"854",
-	"855",
-	"856",
-	"857",
-	"858",
-	"859",
-	"860",
-	"861",
-	"862",
-	"863",
-	"864",
-	"865",
-	"866",
-	"867",
-	"868",
-	"869",
-	"870",
-	"871",
-	"872",
-	"873",
-	"874",
-	"875",
-	"876",
-	"877",
-	"878",
-	"879",
-	"880",
-	"881",
-	"882",
-	"883",
-	"884",
-	"885",
-	"886",
-	"887",
-	"888",
-	"889",
-	"890",
-	"891",
-	"892",
-	"893",
-	"894",
-	"895",
-	"896",
-	"897",
-	"898",
-	"899",
-	"900",
-	"901",
-	"902",
-	"903",
-	"904",
-	"905",
-	"906",
-	"907",
-	"908",
-	"909",
-	"910",
-	"911",
-	"912",
-	"913",
-	"914",
-	"915",
-	"916",
-	"917",
-	"918",
-	"919",
-	"920",
-	"921",
-	"922",
-	"923",
-	"924",
-	"925",
-	"926",
-	"927",
-	"928",
-	"929",
-	"930",
-	"931",
-	"932",
-	"933",
-	"934",
-	"935",
-	"936",
-	"937",
-	"938",
-	"939",
-	"940",
-	"941",
-	"942",
-	"943",
-	"944",
-	"945",
-	"946",
-	"947",
-	"948",
-	"949",
-	"950",
-	"951",
-	"952",
-	"953",
-	"954",
-	"955",
-	"956",
-	"957",
-	"958",
-	"959",
-	"960",
-	"961",
-	"962",
-	"963",
-	"964",
-	"965",
-	"966",
-	"967",
-	"968",
-	"969",
-	"970",
-	"971",
-	"972",
-	"973",
-	"974",
-	"975",
-	"976",
-	"977",
-	"978",
-	"979",
-	"980",
-	"981",
-	"982",
-	"983",
-	"984",
-	"985",
-	"986",
-	"987",
-	"988",
-	"989",
-	"990",
-	"991",
-	"992",
-	"993",
-	"994",
-	"995",
-	"996",
-	"997",
-	"998",
-	"999",
-	"1000",
-	"1001",
-	"1002",
-	"1003",
-	"1004",
-	"1005",
-	"1006",
-	"1007",
-	"1008",
-	"1009",
-	"1010",
-	"1011",
-	"1012",
-	"1013",
-	"1014",
-	"1015",
-	"1016",
-	"1017",
-	"1018",
-	"1019",
-	"1020",
-	"1021",
-	"1022",
-	"1023"
-};
-#endif
diff --git a/hw/xwin/winmisc.c b/hw/xwin/winmisc.c
deleted file mode 100644
index 8e66981..0000000
--- a/hw/xwin/winmisc.c
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-#ifdef XWIN_NATIVEGDI
-/* See Porting Layer Definition - p. 33 */
-/*
- * Called by clients, returns the best size for a cursor, tile, or
- * stipple, specified by class (sometimes called kind)
- */
-
-void
-winQueryBestSizeNativeGDI (int class, unsigned short *pWidth,
-			   unsigned short *pHeight, ScreenPtr pScreen)
-{
-  ErrorF ("winQueryBestSizeNativeGDI\n");
-}
-#endif
-
-
-/*
- * Count the number of one bits in a color mask.
- */
-
-CARD8
-winCountBits (DWORD dw)
-{
-  DWORD		dwBits = 0;
-
-  while (dw)
-    {
-      dwBits += (dw & 1);
-      dw >>= 1;
-    }
-
-  return dwBits;
-}
-
-
-/*
- * Modify the screen pixmap to point to the new framebuffer address
- */
-
-Bool
-winUpdateFBPointer (ScreenPtr pScreen, void *pbits)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-
-  /* Location of shadow framebuffer has changed */
-  pScreenInfo->pfb = pbits;
-
-  /* Update the screen pixmap */
-  if (!(*pScreen->ModifyPixmapHeader) (pScreen->devPrivate,
-				       pScreen->width,
-				       pScreen->height,
-				       pScreen->rootDepth,
-				       BitsPerPixel (pScreen->rootDepth),
-				       PixmapBytePad (pScreenInfo->dwStride,
-						      pScreenInfo->dwBPP),
-				       pScreenInfo->pfb))
-    {
-      FatalError ("winUpdateFramebufferPointer - Failed modifying "\
-		  "screen pixmap\n");
-    }
-
-  return TRUE;
-}
-
-
-#ifdef XWIN_NATIVEGDI
-/*
- * Paint the window background with the specified color
- */
-
-BOOL
-winPaintBackground (HWND hwnd, COLORREF colorref)
-{
-  HDC			hdc;
-  HBRUSH		hbrush;
-  RECT			rect;
-
-  /* Create an hdc */
-  hdc = GetDC (hwnd);
-  if (hdc == NULL)
-    {
-      printf ("gdiWindowProc - GetDC failed\n");
-      exit (1);
-    }
-
-  /* Create and select blue brush */
-  hbrush = CreateSolidBrush (colorref);
-  if (hbrush == NULL)
-    {
-      printf ("gdiWindowProc - CreateSolidBrush failed\n");
-      exit (1);
-    }
-
-  /* Get window extents */
-  if (GetClientRect (hwnd, &rect) == FALSE)
-    {
-      printf ("gdiWindowProc - GetClientRect failed\n");
-      exit (1);
-    }
-
-  /* Fill window with blue brush */
-  if (FillRect (hdc, &rect, hbrush) == 0)
-    {
-      printf ("gdiWindowProc - FillRect failed\n");
-      exit (1);
-    }
-
-  /* Delete blue brush */
-  DeleteObject (hbrush);
-
-  /* Release the hdc */
-  ReleaseDC (hwnd, hdc);
-
-  return TRUE;
-}
-#endif
diff --git a/hw/xwin/winmouse.c b/hw/xwin/winmouse.c
deleted file mode 100644
index 1507dd3..0000000
--- a/hw/xwin/winmouse.c
+++ /dev/null
@@ -1,341 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-#if defined(XFree86Server) && defined(XINPUT)
-#include "inputstr.h"
-
-/* Peek the internal button mapping */
-static CARD8 const *g_winMouseButtonMap = NULL;
-#endif
-
-
-/*
- * Local prototypes
- */
-
-static void
-winMouseCtrl (DeviceIntPtr pDevice, PtrCtrl *pCtrl);
-
-
-static void
-winMouseCtrl (DeviceIntPtr pDevice, PtrCtrl *pCtrl)
-{
-}
-
-
-/*
- * See Porting Layer Definition - p. 18
- * This is known as a DeviceProc
- */
-
-int
-winMouseProc (DeviceIntPtr pDeviceInt, int iState)
-{
-  int 			lngMouseButtons, i;
-  int			lngWheelEvents = 2;
-  CARD8			*map;
-  DevicePtr		pDevice = (DevicePtr) pDeviceInt;
-
-  switch (iState)
-    {
-    case DEVICE_INIT:
-      /* Get number of mouse buttons */
-      lngMouseButtons = GetSystemMetrics(SM_CMOUSEBUTTONS);
-
-      /* Mapping of windows events to X events:
-       * LEFT:1 MIDDLE:2 RIGHT:3
-       * SCROLL_UP:4 SCROLL_DOWN:5
-       * XBUTTON 1:6 XBUTTON 2:7 ...
-       *
-       * To map scroll wheel correctly we need at least the 3 normal buttons
-       */
-      if (lngMouseButtons < 3)
-        lngMouseButtons = 3;
-      winMsg(X_PROBED, "%d mouse buttons found\n", lngMouseButtons);
-
-      /* allocate memory: 
-       * number of buttons + 2x mouse wheel event + 1 extra (offset for map) 
-       */
-      map = malloc(sizeof(CARD8) * (lngMouseButtons + lngWheelEvents + 1));
-    
-      /* initalize button map */ 
-      map[0] = 0;
-      for (i=1; i <= lngMouseButtons + lngWheelEvents; i++)
-      	map[i] = i;
-      InitPointerDeviceStruct (pDevice,
-			       map,
-			       lngMouseButtons + lngWheelEvents,
-			       GetMotionHistory,
-			       winMouseCtrl,
-			       GetMotionHistorySize(),
-			       2);
-      free(map);
-
-#if defined(XFree86Server) && defined(XINPUT)
-      g_winMouseButtonMap = pDeviceInt->button->map;
-#endif
-      break;
-
-    case DEVICE_ON:
-      pDevice->on = TRUE;
-      break;
-
-    case DEVICE_CLOSE:
-#if defined(XFree86Server) && defined(XINPUT)
-      g_winMouseButtonMap = NULL;
-#endif
-    case DEVICE_OFF:
-      pDevice->on = FALSE;
-      break;
-    }
-  return Success;
-}
-
-
-/* Handle the mouse wheel */
-int
-winMouseWheel (ScreenPtr pScreen, int iDeltaZ)
-{
-  winScreenPriv(pScreen);
-  int button; /* Button4 or Button5 */
-
-  /* Button4 = WheelUp */
-  /* Button5 = WheelDown */
-
-  /* Do we have any previous delta stored? */
-  if ((pScreenPriv->iDeltaZ > 0
-       && iDeltaZ > 0)
-      || (pScreenPriv->iDeltaZ < 0
-	  && iDeltaZ < 0))
-    {
-      /* Previous delta and of same sign as current delta */
-      iDeltaZ += pScreenPriv->iDeltaZ;
-      pScreenPriv->iDeltaZ = 0;
-    }
-  else
-    {
-      /*
-       * Previous delta of different sign, or zero.
-       * We will set it to zero for either case,
-       * as blindly setting takes just as much time
-       * as checking, then setting if necessary :)
-       */
-      pScreenPriv->iDeltaZ = 0;
-    }
-
-  /*
-   * Only process this message if the wheel has moved further than
-   * WHEEL_DELTA
-   */
-  if (iDeltaZ >= WHEEL_DELTA || (-1 * iDeltaZ) >= WHEEL_DELTA)
-    {
-      pScreenPriv->iDeltaZ = 0;
-	  
-      /* Figure out how many whole deltas of the wheel we have */
-      iDeltaZ /= WHEEL_DELTA;
-    }
-  else
-    {
-      /*
-       * Wheel has not moved past WHEEL_DELTA threshold;
-       * we will store the wheel delta until the threshold
-       * has been reached.
-       */
-      pScreenPriv->iDeltaZ = iDeltaZ;
-      return 0;
-    }
-
-  /* Set the button to indicate up or down wheel delta */
-  if (iDeltaZ > 0)
-    {
-      button = Button4;
-    }
-  else
-    {
-      button = Button5;
-    }
-
-  /*
-   * Flip iDeltaZ to positive, if negative,
-   * because always need to generate a *positive* number of
-   * button clicks for the Z axis.
-   */
-  if (iDeltaZ < 0)
-    {
-      iDeltaZ *= -1;
-    }
-
-  /* Generate X input messages for each wheel delta we have seen */
-  while (iDeltaZ--)
-    {
-      /* Push the wheel button */
-      winMouseButtonsSendEvent (ButtonPress, button);
-
-      /* Release the wheel button */
-      winMouseButtonsSendEvent (ButtonRelease, button);
-    }
-
-  return 0;
-}
-
-
-/*
- * Enqueue a mouse button event
- */
-
-void
-winMouseButtonsSendEvent (int iEventType, int iButton)
-{
-  xEvent		xCurrentEvent;
-
-  /* Load an xEvent and enqueue the event */
-  xCurrentEvent.u.u.type = iEventType;
-#if defined(XFree86Server) && defined(XINPUT)
-  if (g_winMouseButtonMap)
-    xCurrentEvent.u.u.detail = g_winMouseButtonMap[iButton];
-  else
-#endif
-  xCurrentEvent.u.u.detail = iButton;
-  xCurrentEvent.u.keyButtonPointer.time
-    = g_c32LastInputEventTime = GetTickCount ();
-  mieqEnqueue (&xCurrentEvent);
-}
-
-
-/*
- * Decide what to do with a Windows mouse message
- */
-
-int
-winMouseButtonsHandle (ScreenPtr pScreen,
-		       int iEventType, int iButton,
-		       WPARAM wParam)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-
-  /* Send button events right away if emulate 3 buttons is off */
-  if (pScreenInfo->iE3BTimeout == WIN_E3B_OFF)
-    {
-      /* Emulate 3 buttons is off, send the button event */
-      winMouseButtonsSendEvent (iEventType, iButton);
-      return 0;
-    }
-
-  /* Emulate 3 buttons is on, let the fun begin */
-  if (iEventType == ButtonPress
-      && pScreenPriv->iE3BCachedPress == 0
-      && !pScreenPriv->fE3BFakeButton2Sent)
-    {
-      /*
-       * Button was pressed, no press is cached,
-       * and there is no fake button 2 release pending.
-       */
-
-      /* Store button press type */
-      pScreenPriv->iE3BCachedPress = iButton;
-
-      /*
-       * Set a timer to send this button press if the other button
-       * is not pressed within the timeout time.
-       */
-      SetTimer (pScreenPriv->hwndScreen,
-		WIN_E3B_TIMER_ID,
-		pScreenInfo->iE3BTimeout,
-		NULL);
-    }
-  else if (iEventType == ButtonPress
-	   && pScreenPriv->iE3BCachedPress != 0
-	   && pScreenPriv->iE3BCachedPress != iButton
-	   && !pScreenPriv->fE3BFakeButton2Sent)
-    {
-      /*
-       * Button press is cached, other button was pressed,
-       * and there is no fake button 2 release pending.
-       */
-
-      /* Mouse button was cached and other button was pressed */
-      KillTimer (pScreenPriv->hwndScreen, WIN_E3B_TIMER_ID);
-      pScreenPriv->iE3BCachedPress = 0;
-
-      /* Send fake middle button */
-      winMouseButtonsSendEvent (ButtonPress, Button2);
-
-      /* Indicate that a fake middle button event was sent */
-      pScreenPriv->fE3BFakeButton2Sent = TRUE;
-    }
-  else if (iEventType == ButtonRelease
-	   && pScreenPriv->iE3BCachedPress == iButton)
-    {
-      /*
-       * Cached button was released before timer ran out,
-       * and before the other mouse button was pressed.
-       */
-      KillTimer (pScreenPriv->hwndScreen, WIN_E3B_TIMER_ID);
-      pScreenPriv->iE3BCachedPress = 0;
-
-      /* Send cached press, then send release */
-      winMouseButtonsSendEvent (ButtonPress, iButton);
-      winMouseButtonsSendEvent (ButtonRelease, iButton);
-    }
-  else if (iEventType == ButtonRelease
-	   && pScreenPriv->fE3BFakeButton2Sent
-	   && !(wParam & MK_LBUTTON)
-	   && !(wParam & MK_RBUTTON))
-    {
-      /*
-       * Fake button 2 was sent and both mouse buttons have now been released
-       */
-      pScreenPriv->fE3BFakeButton2Sent = FALSE;
-      
-      /* Send middle mouse button release */
-      winMouseButtonsSendEvent (ButtonRelease, Button2);
-    }
-  else if (iEventType == ButtonRelease
-	   && pScreenPriv->iE3BCachedPress == 0
-	   && !pScreenPriv->fE3BFakeButton2Sent)
-    {
-      /*
-       * Button was release, no button is cached,
-       * and there is no fake button 2 release is pending.
-       */
-      winMouseButtonsSendEvent (ButtonRelease, iButton);
-    }
-
-  return 0;
-}
diff --git a/hw/xwin/winms.h b/hw/xwin/winms.h
deleted file mode 100644
index 1ad30dc..0000000
--- a/hw/xwin/winms.h
+++ /dev/null
@@ -1,46 +0,0 @@
-#ifndef _WINMS_H_
-#define _WINMS_H_
-/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#define NONAMELESSUNION
-#define DIRECTDRAW_VERSION	0x0300
-#ifndef WIN32_LEAN_AND_MEAN
-#define WIN32_LEAN_AND_MEAN
-#endif
-
-#include <X11/Xwindows.h>
-#include <windowsx.h>
-
-#include "ddraw.h"
-
-#undef CreateWindow
-
-#endif /* _WINMS_H_ */
diff --git a/hw/xwin/winmsg.c b/hw/xwin/winmsg.c
deleted file mode 100644
index d0464f7..0000000
--- a/hw/xwin/winmsg.c
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors: Alexander Gottwald	
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winmsg.h"
-#if CYGDEBUG
-#include "winmessages.h"
-#endif
-#include <stdarg.h>
-
-void winVMsg (int, MessageType, int verb, const char *, va_list);
-
-void
-winVMsg (int scrnIndex, MessageType type, int verb, const char *format,
-	 va_list ap)
-{
-  LogVMessageVerb(type, verb, format, ap);
-}
-
-
-void
-winDrvMsg (int scrnIndex, MessageType type, const char *format, ...)
-{
-  va_list ap;
-  va_start (ap, format);
-  LogVMessageVerb(type, 0, format, ap);
-  va_end (ap);
-}
-
-
-void
-winMsg (MessageType type, const char *format, ...)
-{
-  va_list ap;
-  va_start (ap, format);
-  LogVMessageVerb(type, 1, format, ap);
-  va_end (ap);
-}
-
-
-void
-winDrvMsgVerb (int scrnIndex, MessageType type, int verb, const char *format,
-	       ...)
-{
-  va_list ap;
-  va_start (ap, format);
-  LogVMessageVerb(type, verb, format, ap);
-  va_end (ap);
-}
-
-
-void
-winMsgVerb (MessageType type, int verb, const char *format, ...)
-{
-  va_list ap;
-  va_start (ap, format);
-  LogVMessageVerb(type, verb, format, ap);
-  va_end (ap);
-}
-
-
-void
-winErrorFVerb (int verb, const char *format, ...)
-{
-  va_list ap;
-  va_start (ap, format);
-  LogVMessageVerb(X_NONE, verb, format, ap);
-  va_end (ap);
-}
-
-void
-winDebug (const char *format, ...)
-{
-  va_list ap;
-  va_start (ap, format);
-  LogVMessageVerb(X_NONE, 3, format, ap);
-  va_end (ap);
-}
-
-void
-winTrace (const char *format, ...)
-{
-  va_list ap;
-  va_start (ap, format);
-  LogVMessageVerb(X_NONE, 10, format, ap);
-  va_end (ap);
-}
-
-void
-winW32Error(int verb, const char *msg)
-{
-    winW32ErrorEx(verb, msg, GetLastError());
-}
-
-void
-winW32ErrorEx(int verb, const char *msg, DWORD errorcode)
-{
-    LPVOID buffer;
-    if (!FormatMessage( 
-                FORMAT_MESSAGE_ALLOCATE_BUFFER | 
-                FORMAT_MESSAGE_FROM_SYSTEM | 
-                FORMAT_MESSAGE_IGNORE_INSERTS,
-                NULL,
-                errorcode,
-                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-                (LPTSTR) &buffer,
-                0,
-                NULL ))
-    {
-        winErrorFVerb(verb, "Unknown error in FormatMessage!\n"); 
-    }
-    else
-    {
-        winErrorFVerb(verb, "%s %s", msg, (char *)buffer); 
-        LocalFree(buffer);
-    }
-}
-
-#if CYGDEBUG
-void winDebugWin32Message(const char* function, HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
-{
-  static int force = 0;
-
-  if (message >= WM_USER)
-    {
-      if (force || getenv("WIN_DEBUG_MESSAGES") || getenv("WIN_DEBUG_WM_USER"))
-      {
-        winDebug("%s - Message WM_USER + %d\n", function, message - WM_USER);
-        winDebug("\thwnd 0x%x wParam 0x%x lParam 0x%x\n", hwnd, wParam, lParam);
-      }
-    }
-  else if (message < MESSAGE_NAMES_LEN && MESSAGE_NAMES[message])
-    {
-      const char *msgname = MESSAGE_NAMES[message];
-      char buffer[64];
-      snprintf(buffer, sizeof(buffer), "WIN_DEBUG_%s", msgname);
-      buffer[63] = 0;
-      if (force || getenv("WIN_DEBUG_MESSAGES") || getenv(buffer))
-      {
-        winDebug("%s - Message %s\n", function, MESSAGE_NAMES[message]);
-        winDebug("\thwnd 0x%x wParam 0x%x lParam 0x%x\n", hwnd, wParam, lParam);
-      }
-    }
-}
-#else
-void winDebugWin32Message(const char* function, HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
-{
-}
-#endif
diff --git a/hw/xwin/winmsg.h b/hw/xwin/winmsg.h
deleted file mode 100644
index 611dd69..0000000
--- a/hw/xwin/winmsg.h
+++ /dev/null
@@ -1,50 +0,0 @@
-#ifndef __WIN_MSG_H__
-#define __WIN_MSG_H__
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors: Alexander Gottwald	
- */
-
-/*
- * Function prototypes
- */
-
-void winDrvMsgVerb (int scrnIndex,
-		    MessageType type, int verb, const char *format, ...);
-void winDrvMsg (int scrnIndex, MessageType type, const char *format, ...);
-void winMsgVerb (MessageType type, int verb, const char *format, ...);
-void winMsg (MessageType type, const char *format, ...);
-void winDebug (const char *format, ...);
-void winTrace (const char *format, ...);
-
-void winErrorFVerb (int verb, const char *format, ...);
-void winW32Error(int verb, const char *message);
-void winW32ErrorEx(int verb, const char *message, DWORD errorcode);
-void winDebugWin32Message(const char* function, HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
-
-#endif
diff --git a/hw/xwin/winmultiwindowclass.c b/hw/xwin/winmultiwindowclass.c
deleted file mode 100755
index 5b47c39..0000000
--- a/hw/xwin/winmultiwindowclass.c
+++ /dev/null
@@ -1,325 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:     Earle F. Philhower, III
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include <X11/Xatom.h>
-#include "propertyst.h"
-#include "windowstr.h"
-#include "winmultiwindowclass.h"
-#include "win.h"
-
-/*
- * Local function
- */
-
-DEFINE_ATOM_HELPER(AtmWmWindowRole, "WM_WINDOW_ROLE")
-
-
-int
-winMultiWindowGetClassHint (WindowPtr pWin, char **res_name, char **res_class)
-{
-  struct _Window	*pwin;
-  struct _Property	*prop;
-  int			len_name, len_class;
-
-  if (!pWin || !res_name || !res_class)
-    {
-      ErrorF ("winMultiWindowGetClassHint - pWin, res_name, or res_class was "
-	      "NULL\n");
-      return 0;  
-    }
-  
-  pwin = (struct _Window*) pWin;
-
-  if (pwin->optional)
-    prop = (struct _Property *) pwin->optional->userProps;
-  else
-    prop = NULL;
-  
-  *res_name = *res_class = NULL;
-
-  while (prop)
-    {
-      if (prop->propertyName == XA_WM_CLASS
-	  && prop->type == XA_STRING
-	  && prop->format == 8
-	  && prop->data)
-	{
-	  len_name = strlen ((char *) prop->data);
-
-	  (*res_name) = malloc (len_name + 1);
-	  
-	  if (!*res_name)
-	    {
-	      ErrorF ("winMultiWindowGetClassHint - *res_name was NULL\n");
-	      return 0;
-	    }
-
-	  /* Add one to len_name to allow copying of trailing 0 */
-	  strncpy ((*res_name), prop->data, len_name + 1);
-
-	  if (len_name == prop->size)
-	    len_name--;
-
-	  len_class = strlen (((char *)prop->data) + 1 + len_name);
-
-	  (*res_class) = malloc (len_class + 1);
-
-	  if (!*res_class)
-	    {
-	      ErrorF ("winMultiWindowGetClassHint - *res_class was NULL\n");
-	      
-	      /* Free the previously allocated res_name */
-	      free (*res_name);
-	      return 0;
-	    }
-
-	  strcpy ((*res_class), ((char *)prop->data) + 1 + len_name);
-
-	  return 1;
-	}
-      else
-	prop = prop->next;
-    }
-  
-  return 0;
-}
-
-
-int
-winMultiWindowGetWMHints (WindowPtr pWin, WinXWMHints *hints)
-{
-  struct _Window	*pwin;
-  struct _Property	*prop;
-
-  if (!pWin || !hints)
-    {
-      ErrorF ("winMultiWindowGetWMHints - pWin or hints was NULL\n");
-      return 0; 
-    }
-
-  pwin = (struct _Window*) pWin;
-
-  if (pwin->optional)
-    prop = (struct _Property *) pwin->optional->userProps;
-  else
-    prop = NULL;
-  
-  memset (hints, 0, sizeof (WinXWMHints));
-
-  while (prop)
-    {
-      if (prop->propertyName == XA_WM_HINTS
-	  && prop->data)
-	{
-	  memcpy (hints, prop->data, sizeof (WinXWMHints));
-	  return 1;
-	}
-      else
-	prop = prop->next;
-    }
-  
-  return 0;
-}
-
-
-int
-winMultiWindowGetWindowRole (WindowPtr pWin, char **res_role)
-{
-  struct _Window	*pwin;
-  struct _Property	*prop;
-  int			len_role;
-
-  if (!pWin || !res_role) 
-    return 0; 
-
-  pwin = (struct _Window*) pWin;
-  
-  if (pwin->optional)
-    prop = (struct _Property *) pwin->optional->userProps;
-  else
-    prop = NULL;
-  
-  *res_role = NULL;
-  while (prop)
-    {
-      if (prop->propertyName == AtmWmWindowRole ()
-	  && prop->type == XA_STRING
-	  && prop->format == 8
-	  && prop->data)
-	{
-	  len_role= prop->size;
-
-	  (*res_role) = malloc (len_role + 1);
-
-	  if (!*res_role)
-	    {
-	      ErrorF ("winMultiWindowGetWindowRole - *res_role was NULL\n");
-	      return 0; 
-	    }
-
-	  strncpy ((*res_role), prop->data, len_role);
-	  (*res_role)[len_role] = 0;
-
-	  return 1;
-	}
-      else
-	prop = prop->next;
-    }
-  
-  return 0;
-}
-
-
-int
-winMultiWindowGetWMNormalHints (WindowPtr pWin, WinXSizeHints *hints)
-{
-  struct _Window	*pwin;
-  struct _Property	*prop;
-
-  if (!pWin || !hints)
-    {
-      ErrorF ("winMultiWindowGetWMNormalHints - pWin or hints was NULL\n");
-      return 0; 
-    }
-
-  pwin = (struct _Window*) pWin;
-
-  if (pwin->optional)
-    prop = (struct _Property *) pwin->optional->userProps;
-  else
-    prop = NULL;
-  
-  memset (hints, 0, sizeof (WinXSizeHints));
-
-  while (prop)
-    {
-      if (prop->propertyName == XA_WM_NORMAL_HINTS
-	  && prop->data)
-	{
-	  memcpy (hints, prop->data, sizeof (WinXSizeHints));
-	  return 1;
-	}
-      else
-	prop = prop->next;
-    }
-
-  return 0;
-}
-
-int
-winMultiWindowGetTransientFor (WindowPtr pWin, WindowPtr *ppDaddy)
-{
-  struct _Window        *pwin;
-  struct _Property      *prop;
-
-  if (!pWin)
-    {
-      ErrorF ("winMultiWindowGetTransientFor - pWin was NULL\n");
-      return 0;
-    }
-
-  pwin = (struct _Window*) pWin;
-
-  if (pwin->optional)
-    prop = (struct _Property *) pwin->optional->userProps;
-  else
-    prop = NULL;
-
-  if (ppDaddy)
-    *ppDaddy = NULL;
-
-  while (prop)
-    {
-      if (prop->propertyName == XA_WM_TRANSIENT_FOR)
-        {
-          if (ppDaddy)
-            memcpy (*ppDaddy, prop->data, sizeof (WindowPtr));
-          return 1;
-        }
-      else
-        prop = prop->next;
-    }
-
-  return 0;
-}
-
-int
-winMultiWindowGetWMName (WindowPtr pWin, char **wmName)
-{
-  struct _Window	*pwin;
-  struct _Property	*prop;
-  int			len_name;
-
-  if (!pWin || !wmName)
-    {
-      ErrorF ("winMultiWindowGetClassHint - pWin, res_name, or res_class was "
-	      "NULL\n");
-      return 0;  
-    }
-  
-  pwin = (struct _Window*) pWin;
-
-  if (pwin->optional)
-    prop = (struct _Property *) pwin->optional->userProps;
-  else
-    prop = NULL;
-  
-  *wmName = NULL;
-
-  while (prop)
-    {
-      if (prop->propertyName == XA_WM_NAME
-	  && prop->type == XA_STRING
-	  && prop->data)
-	{
-	  len_name = prop->size;
-
-	  (*wmName) = malloc (len_name + 1);
-	  
-	  if (!*wmName)
-	    {
-	      ErrorF ("winMultiWindowGetWMName - *wmName was NULL\n");
-	      return 0;
-	    }
-
-	  strncpy ((*wmName), prop->data, len_name);
-	  (*wmName)[len_name] = 0;
-
-	  return 1;
-	}
-      else
-	prop = prop->next;
-    }
-  
-  return 0;
-}
diff --git a/hw/xwin/winmultiwindowclass.h b/hw/xwin/winmultiwindowclass.h
deleted file mode 100755
index c635ab2..0000000
--- a/hw/xwin/winmultiwindowclass.h
+++ /dev/null
@@ -1,114 +0,0 @@
-#if !defined(WINMULTIWINDOWCLASS_H)
-#define WINMULTIWINDOWCLASS_H
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:     Earle F. Philhower, III
- */
-
-/*
- * Structures
- */
-
-typedef struct {
-  long		flags;	/* marks which fields in this structure are defined */
-  Bool		input;	/* does this application rely on the window manager to
-		   get keyboard input? */
-  int		initial_state;	/* see below */
-  Pixmap	icon_pixmap;	/* pixmap to be used as icon */
-  Window	icon_window; 	/* window to be used as icon */
-  int		icon_x, icon_y; 	/* initial position of icon */
-  Pixmap	icon_mask;	/* icon mask bitmap */
-  XID		window_group;	/* id of related window group */
-  /* this structure may be extended in the future */
-} WinXWMHints;
-
-
-/*
- * new version containing base_width, base_height, and win_gravity fields;
- * used with WM_NORMAL_HINTS.
- */
-typedef struct {
-  long flags;     /* marks which fields in this structure are defined */
-  int x, y;               /* obsolete for new window mgrs, but clients */
-  int width, height;      /* should set so old wm's don't mess up */
-  int min_width, min_height;
-  int max_width, max_height;
-  int width_inc, height_inc;
-  struct {
-    int x;  /* numerator */
-    int y;  /* denominator */
-  } min_aspect, max_aspect;
-  int base_width, base_height;            /* added by ICCCM version 1 */
-  int win_gravity;                        /* added by ICCCM version 1 */
-} WinXSizeHints;
-
-/*
- * The next block of definitions are for window manager properties that
- * clients and applications use for communication.
- */
-
-/* flags argument in size hints */
-#define USPosition      (1L << 0) /* user specified x, y */
-#define USSize          (1L << 1) /* user specified width, height */
-
-#define PPosition       (1L << 2) /* program specified position */
-#define PSize           (1L << 3) /* program specified size */
-#define PMinSize        (1L << 4) /* program specified minimum size */
-#define PMaxSize        (1L << 5) /* program specified maximum size */
-#define PResizeInc      (1L << 6) /* program specified resize increments */
-#define PAspect         (1L << 7) /* program specified min and max aspect ratios */
-#define PBaseSize       (1L << 8) /* program specified base for incrementing */
-#define PWinGravity     (1L << 9) /* program specified window gravity */
-
-/* obsolete */
-#define PAllHints (PPosition|PSize|PMinSize|PMaxSize|PResizeInc|PAspect)
-
-
-/*
- * Function prototypes
- */
-
-int
-winMultiWindowGetWMHints (WindowPtr pWin, WinXWMHints *hints);
-
-int
-winMultiWindowGetClassHint (WindowPtr pWin, char **res_name, char **res_class);
-
-int
-winMultiWindowGetWindowRole (WindowPtr pWin, char **res_role);
-
-int
-winMultiWindowGetWMNormalHints (WindowPtr pWin, WinXSizeHints *hints);
-
-int
-winMultiWindowGetWMName (WindowPtr pWin, char **wmName);
-
-int
-winMultiWindowGetTransientFor (WindowPtr pWin, WindowPtr *ppDaddy);
-
-#endif
diff --git a/hw/xwin/winmultiwindowicons.c b/hw/xwin/winmultiwindowicons.c
deleted file mode 100644
index 45ed093..0000000
--- a/hw/xwin/winmultiwindowicons.c
+++ /dev/null
@@ -1,478 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Earle F. Philhower, III
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "dixevents.h"
-#include "winmultiwindowclass.h"
-#include "winprefs.h"
-
-
-/*
- * External global variables
- */
-
-extern HICON		g_hIconX;
-extern HICON		g_hSmallIconX;
-
-
-/*
- * Prototypes for local functions
- */
-
-static void
-winScaleXBitmapToWindows (int iconSize, int effBPP,
-			  PixmapPtr pixmap, unsigned char *image);
-
-
-/*
- * Scale an X icon bitmap into a Windoze icon bitmap
- */
-
-static void
-winScaleXBitmapToWindows (int iconSize,
-			  int effBPP,
-			  PixmapPtr pixmap,
-			  unsigned char *image)
-{
-  int			row, column, effXBPP, effXDepth;
-  unsigned char		*outPtr;
-  unsigned char		*iconData = 0;
-  int			stride, xStride;
-  float			factX, factY;
-  int			posX, posY;
-  unsigned char		*ptr;
-  unsigned int		zero;
-  unsigned int		color;
-
-  effXBPP = BitsPerPixel(pixmap->drawable.depth);
-  effXDepth = pixmap->drawable.depth;
-
-  if (pixmap->drawable.bitsPerPixel == 15)
-    effXBPP = 16;
-  
-  if (pixmap->drawable.depth == 15)
-    effXDepth = 16;
-
-  /* Need 32-bit aligned rows */
-  stride = ((iconSize * effBPP + 31) & (~31)) / 8;
-  xStride = PixmapBytePad (pixmap->drawable.width, pixmap->drawable.depth);
-  if (stride == 0 || xStride == 0)
-    {
-      ErrorF ("winScaleXBitmapToWindows - stride or xStride is zero.  "
-	      "Bailing.\n");
-      return;
-    }
-
-  /* Allocate memory for icon data */
-  iconData = malloc (xStride * pixmap->drawable.height);
-  if (!iconData)
-    {
-      ErrorF ("winScaleXBitmapToWindows - malloc failed for iconData.  "
-	      "Bailing.\n");
-      return;
-    }
-
-  /* Get icon data */
-  miGetImage ((DrawablePtr) &(pixmap->drawable), 0, 0,
-	      pixmap->drawable.width, pixmap->drawable.height,
-	      ZPixmap, 0xffffffff, iconData);
-
-  /* Keep aspect ratio */
-  factX = ((float)pixmap->drawable.width) / ((float)iconSize);
-  factY = ((float)pixmap->drawable.height) / ((float)iconSize);
-  if (factX > factY)
-    factY = factX;
-  else
-    factX = factY;
-  
-  /* Out-of-bounds, fill icon with zero */
-  zero = 0;
- 
-  for (row = 0; row < iconSize; row++)
-    {
-      outPtr = image + stride * row;
-      for (column = 0; column < iconSize; column++)
-	{
-	  posX = factX * column;
-	  posY = factY * row;
-	  
-	  ptr = iconData + posY*xStride;
-	  if (effXBPP == 1)
-	    {
-	      ptr += posX / 8;
-	      
-	      /* Out of X icon bounds, leave space blank */
-	      if (posX >= pixmap->drawable.width
-		  || posY >= pixmap->drawable.height)
-		ptr = (unsigned char *) &zero;
-	      
-	      if ((*ptr) & (1 << (posX & 7)))
-		switch (effBPP)
-		  {
-		  case 32:
-		    *(outPtr++) = 0;
-		  case 24:
-		    *(outPtr++) = 0;
-		  case 16:
-		    *(outPtr++) = 0;
-		  case 8:
-		    *(outPtr++) = 0;
-		    break;
-		  case 1:
-		    outPtr[column / 8] &= ~(1 << (7 - (column & 7)));
-		    break;
-		  }
-	      else
-		switch (effBPP)
-		  {
-		  case 32:
-		    *(outPtr++) = 255;
-		    *(outPtr++) = 255;
-		    *(outPtr++) = 255;
-		    *(outPtr++) = 0;
-		    break;
-		  case 24:
-		    *(outPtr++) = 255;
-		  case 16:
-		    *(outPtr++) = 255;
-		  case 8: 
-		    *(outPtr++) = 255;
-		    break;
-		  case 1:
-		    outPtr[column / 8] |= (1 << (7 - (column & 7)));
-		    break;
-		  }
-	    }
-	  else if (effXDepth == 24 || effXDepth == 32)
-	    {
-	      ptr += posX * (effXBPP / 8);
-
-	      /* Out of X icon bounds, leave space blank */
-	      if (posX >= pixmap->drawable.width
-		  || posY >= pixmap->drawable.height)
-		ptr = (unsigned char *) &zero;
-	      color = (((*ptr) << 16)
-		       + ((*(ptr + 1)) << 8)
-		       + ((*(ptr + 2)) << 0));
-	      switch (effBPP)
-		{
-		case 32:
-		  *(outPtr++) = *(ptr++); // b
-		  *(outPtr++) = *(ptr++); // g
-		  *(outPtr++) = *(ptr++); // r
-		  *(outPtr++) = 0; // resvd
-		  break;
-		case 24:
-		  *(outPtr++) = *(ptr++);
-		  *(outPtr++) = *(ptr++);
-		  *(outPtr++) = *(ptr++);
-		  break;
-		case 16:
-		  color = ((((*ptr) >> 2) << 10)
-			   + (((*(ptr + 1)) >> 2) << 5)
-			   + (((*(ptr + 2)) >> 2)));
-		  *(outPtr++) = (color >> 8);
-		  *(outPtr++) = (color & 255);
-		  break;
-		case 8:
-		  color = (((*ptr))) + (((*(ptr + 1)))) + (((*(ptr + 2))));
-		  color /= 3;
-		  *(outPtr++) = color;
-		  break;
-		case 1:
-		  if (color)
-		    outPtr[column / 8] |= (1 << (7 - (column & 7)));
-		  else
-		    outPtr[column / 8] &= ~(1 << (7 - (column & 7)));
-		}
-	    }
-	  else if (effXDepth == 16)
-	    {
-	      ptr += posX * (effXBPP / 8);
-	
-	      /* Out of X icon bounds, leave space blank */
-	      if (posX >= pixmap->drawable.width
-		  || posY >= pixmap->drawable.height)
-		ptr = (unsigned char *) &zero;
-	      color = ((*ptr) << 8) + (*(ptr + 1));
-	      switch (effBPP)
-		{
-		case 32:
-		  *(outPtr++) = (color & 31) << 2;
-		  *(outPtr++) = ((color >> 5) & 31) << 2;
-		  *(outPtr++) = ((color >> 10) & 31) << 2;
-		  *(outPtr++) = 0; // resvd
-		  break;
-		case 24:
-		  *(outPtr++) = (color & 31) << 2;
-		  *(outPtr++) = ((color >> 5) & 31) << 2;
-		  *(outPtr++) = ((color >> 10) & 31) << 2;
-		  break;
-		case 16:
-		  *(outPtr++) = *(ptr++);
-		  *(outPtr++) = *(ptr++);
-		  break;
-		case 8:
-		  *(outPtr++) = (((color & 31)
-				  + ((color >> 5) & 31)
-				  + ((color >> 10) & 31)) / 3) << 2;
-		  break;
-		case 1:
-		  if (color)
-		    outPtr[column / 8] |= (1 << (7 - (column & 7)));
-		  else
-		    outPtr[column / 8] &= ~(1 << (7 - (column & 7)));
-		  break;
-		} /* end switch(effbpp) */
-	    } /* end if effxbpp==16) */
-	} /* end for column */
-    } /* end for row */
-  free (iconData);
-}
-
-
-/*
- * Attempt to create a custom icon from the WM_HINTS bitmaps
- */
-
-HICON
-winXIconToHICON (WindowPtr pWin, int iconSize)
-{
-  unsigned char		*mask, *image, *imageMask;
-  unsigned char		*dst, *src;
-  PixmapPtr		iconPtr;
-  PixmapPtr		maskPtr;
-  int			planes, bpp, effBPP, stride, maskStride, i;
-  HDC			hDC;
-  ICONINFO		ii;
-  WinXWMHints		hints;
-  HICON			hIcon;
-
-  winMultiWindowGetWMHints (pWin, &hints);
-  if (!hints.icon_pixmap) return NULL;
-
-  iconPtr = (PixmapPtr) LookupIDByType (hints.icon_pixmap, RT_PIXMAP);
-  
-  if (!iconPtr) return NULL;
-  
-  hDC = GetDC (GetDesktopWindow ());
-  planes = GetDeviceCaps (hDC, PLANES);
-  bpp = GetDeviceCaps (hDC, BITSPIXEL);
-  ReleaseDC (GetDesktopWindow (), hDC);
-  
-  /* 15 BPP is really 16BPP as far as we care */
-  if (bpp == 15)
-    effBPP = 16;
-  else
-    effBPP = bpp;
-  
-  /* Need 32-bit aligned rows */
-  stride = ((iconSize * effBPP + 31) & (~31)) / 8;
-
-  /* Mask is 1-bit deep */
-  maskStride = ((iconSize * 1 + 31) & (~31)) / 8; 
-
-  image = (unsigned char * ) malloc (stride * iconSize);
-  imageMask = (unsigned char *) malloc (stride * iconSize);
-  mask = (unsigned char *) malloc (maskStride * iconSize);
-  
-  /* Default to a completely black mask */
-  memset (mask, 0, maskStride * iconSize);
-  
-  winScaleXBitmapToWindows (iconSize, effBPP, iconPtr, image);
-  maskPtr = (PixmapPtr) LookupIDByType (hints.icon_mask, RT_PIXMAP);
-
-  if (maskPtr) 
-    {
-      winScaleXBitmapToWindows (iconSize, 1, maskPtr, mask);
-      
-      winScaleXBitmapToWindows (iconSize, effBPP, maskPtr, imageMask);
-      
-      /* Now we need to set all bits of the icon which are not masked */
-      /* on to 0 because Color is really an XOR, not an OR function */
-      dst = image;
-      src = imageMask;
-
-      for (i = 0; i < (stride * iconSize); i++)
-	if ((*(src++)))
-	  *(dst++) = 0;
-	else
-	  dst++;
-    }
-  
-  ii.fIcon = TRUE;
-  ii.xHotspot = 0; /* ignored */
-  ii.yHotspot = 0; /* ignored */
-  
-  /* Create Win32 mask from pixmap shape */
-  ii.hbmMask = CreateBitmap (iconSize, iconSize, planes, 1, mask);
-
-  /* Create Win32 bitmap from pixmap */
-  ii.hbmColor = CreateBitmap (iconSize, iconSize, planes, bpp, image);
-
-  /* Merge Win32 mask and bitmap into icon */
-  hIcon = CreateIconIndirect (&ii);
-
-  /* Release Win32 mask and bitmap */
-  DeleteObject (ii.hbmMask);
-  DeleteObject (ii.hbmColor);
-
-  /* Free X mask and bitmap */
-  free (mask);
-  free (image);
-  free (imageMask);
-
-  return hIcon;
-}
-
-
-
-/*
- * Change the Windows window icon 
- */
-
-#ifdef XWIN_MULTIWINDOW
-void
-winUpdateIcon (Window id)
-{
-  WindowPtr		pWin;
-  HICON			hIcon, hiconOld;
-
-  pWin = (WindowPtr) LookupIDByType (id, RT_WINDOW);
-  if (!pWin) return;
-  hIcon = (HICON)winOverrideIcon ((unsigned long)pWin);
-
-  if (!hIcon)
-    hIcon = winXIconToHICON (pWin, GetSystemMetrics(SM_CXICON));
-
-  if (hIcon)
-    {
-      winWindowPriv(pWin);
-
-      if (pWinPriv->hWnd)
-	{
-	  hiconOld = (HICON) SetClassLong (pWinPriv->hWnd,
-					   GCL_HICON,
-					   (int) hIcon);
-	  
-	  /* Delete the icon if its not the default */
-	  winDestroyIcon(hiconOld);
-	}
-    }
- 
-  hIcon = winXIconToHICON (pWin, GetSystemMetrics(SM_CXSMICON));
-  if (hIcon)
-    {
-      winWindowPriv(pWin);
-
-      if (pWinPriv->hWnd)
-	{
-	  hiconOld = (HICON) SetClassLong (pWinPriv->hWnd,
-					   GCL_HICONSM,
-					   (int) hIcon);
-	  winDestroyIcon (hiconOld);
-	}
-    }
-}
-
-void winInitGlobalIcons (void)
-{
-  int sm_cx = GetSystemMetrics(SM_CXICON);
-  int sm_cxsm = GetSystemMetrics(SM_CXSMICON);
-  /* Load default X icon in case it's not ready yet */
-  if (!g_hIconX) 
-    {  
-      g_hIconX = (HICON)winOverrideDefaultIcon(sm_cx);
-      g_hSmallIconX = (HICON)winOverrideDefaultIcon(sm_cxsm);
-    }
-  
-  if (!g_hIconX)
-    {   
-      g_hIconX = (HICON)LoadImage (g_hInstance,
-	      MAKEINTRESOURCE(IDI_XWIN),
-	      IMAGE_ICON,
-	      GetSystemMetrics(SM_CXICON),
-	      GetSystemMetrics(SM_CYICON),
-	      0);
-      g_hSmallIconX = (HICON)LoadImage (g_hInstance,
-	      MAKEINTRESOURCE(IDI_XWIN),
-	      IMAGE_ICON,
-	      GetSystemMetrics(SM_CXSMICON),
-	      GetSystemMetrics(SM_CYSMICON),
-	      LR_DEFAULTSIZE);
-    }
-}
-
-void winSelectIcons(WindowPtr pWin, HICON *pIcon, HICON *pSmallIcon)
-{
-  HICON hIcon, hSmallIcon;
-  
-  winInitGlobalIcons();  
-  
-  /* Try and get the icon from WM_HINTS */
-  hIcon = winXIconToHICON (pWin, GetSystemMetrics(SM_CXICON));
-  hSmallIcon = winXIconToHICON (pWin, GetSystemMetrics(SM_CXSMICON));
-
-  /* If we got the small, but not the large one swap them */
-  if (!hIcon && hSmallIcon) 
-  {
-      hIcon = hSmallIcon;
-      hSmallIcon = NULL;
-  }
-  
-  /* Use default X icon if no icon loaded from WM_HINTS */
-  if (!hIcon) {
-    hIcon = g_hIconX;
-    hSmallIcon = g_hSmallIconX;
-  }
-
-  if (pIcon)
-    *pIcon = hIcon;
-  else
-    winDestroyIcon(hIcon);
-  if (pSmallIcon)
-    *pSmallIcon = hSmallIcon;
-  else
-    winDestroyIcon(hSmallIcon);
-}
-
-void winDestroyIcon(HICON hIcon)
-{
-  /* Delete the icon if its not the default */
-  if (hIcon &&
-      hIcon != g_hIconX &&
-      hIcon != g_hSmallIconX &&
-      !winIconIsOverride((unsigned long)hIcon))
-    DestroyIcon (hIcon);
-}
-#endif
diff --git a/hw/xwin/winmultiwindowshape.c b/hw/xwin/winmultiwindowshape.c
deleted file mode 100644
index 33deae3..0000000
--- a/hw/xwin/winmultiwindowshape.c
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Kensuke Matsuzaki
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#ifdef SHAPE
-
-#include "win.h"
-
-
-/*
- * winSetShapeMultiWindow - See Porting Layer Definition - p. 42
- */
-
-void
-winSetShapeMultiWindow (WindowPtr pWin)
-{
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winSetShapeMultiWindow - pWin: %08x\n", pWin);
-#endif
-  
-  WIN_UNWRAP(SetShape); 
-  (*pScreen->SetShape)(pWin);
-  WIN_WRAP(SetShape, winSetShapeMultiWindow);
-  
-  /* Update the Windows window's shape */
-  winReshapeMultiWindow (pWin);
-  winUpdateRgnMultiWindow (pWin);
-
-  return;
-}
-
-
-/*
- * winUpdateRgnMultiWindow - Local function to update a Windows window region
- */
-
-void
-winUpdateRgnMultiWindow (WindowPtr pWin)
-{
-  SetWindowRgn (winGetWindowPriv(pWin)->hWnd,
-		winGetWindowPriv(pWin)->hRgn, TRUE);
-}
-
-
-/*
- * winReshapeMultiWindow - Computes the composite clipping region for a window
- */
-
-void
-winReshapeMultiWindow (WindowPtr pWin)
-{
-  int		nRects;
-  RegionRec	rrNewShape;
-  BoxPtr	pShape, pRects, pEnd;
-  HRGN		hRgn, hRgnRect;
-  winWindowPriv(pWin);
-
-#if CYGDEBUG
-  winDebug ("winReshape ()\n");
-#endif
-  
-  /* Bail if the window is the root window */
-  if (pWin->parent == NULL)
-    return;
-
-  /* Bail if the window is not top level */
-  if (pWin->parent->parent != NULL)
-    return;
-
-  /* Bail if Windows window handle is invalid */
-  if (pWinPriv->hWnd == NULL)
-    return;
-  
-  /* Free any existing window region stored in the window privates */
-  if (pWinPriv->hRgn != NULL)
-    {
-      DeleteObject (pWinPriv->hRgn);
-      pWinPriv->hRgn = NULL;
-    }
-  
-  /* Bail if the window has no bounding region defined */
-  if (!wBoundingShape (pWin))
-    return;
-
-  REGION_NULL(pWin->drawable.pScreen, &rrNewShape);
-  REGION_COPY(pWin->drawable.pScreen, &rrNewShape, wBoundingShape(pWin));
-  REGION_TRANSLATE(pWin->drawable.pScreen,
-		   &rrNewShape,
-		   pWin->borderWidth,
-                   pWin->borderWidth);
-  
-  nRects = REGION_NUM_RECTS(&rrNewShape);
-  pShape = REGION_RECTS(&rrNewShape);
-  
-  /* Don't do anything if there are no rectangles in the region */
-  if (nRects > 0)
-    {
-      RECT			rcClient;
-      RECT			rcWindow;
-      int			iOffsetX, iOffsetY;
-      
-      /* Get client rectangle */
-      if (!GetClientRect (pWinPriv->hWnd, &rcClient))
-	{
-	  ErrorF ("winReshape - GetClientRect failed, bailing: %d\n",
-		  (int) GetLastError ());
-	  return;
-	}
-
-      /* Translate client rectangle coords to screen coords */
-      /* NOTE: Only transforms top and left members */
-      ClientToScreen (pWinPriv->hWnd, (LPPOINT) &rcClient);
-
-      /* Get window rectangle */
-      if (!GetWindowRect (pWinPriv->hWnd, &rcWindow))
-	{
-	  ErrorF ("winReshape - GetWindowRect failed, bailing: %d\n",
-		  (int) GetLastError ());
-	  return;
-	}
-
-      /* Calculate offset from window upper-left to client upper-left */
-      iOffsetX = rcClient.left - rcWindow.left;
-      iOffsetY = rcClient.top - rcWindow.top;
-
-      /* Create initial Windows region for title bar */
-      /* FIXME: Mean, nasty, ugly hack!!! */
-      hRgn = CreateRectRgn (0, 0, rcWindow.right, iOffsetY);
-      if (hRgn == NULL)
-	{
-	  ErrorF ("winReshape - Initial CreateRectRgn (%d, %d, %d, %d) "
-		  "failed: %d\n",
-		  0, 0, (int) rcWindow.right, iOffsetY, (int) GetLastError ());
-	}
-
-      /* Loop through all rectangles in the X region */
-      for (pRects = pShape, pEnd = pShape + nRects; pRects < pEnd; pRects++)
-        {
-	  /* Create a Windows region for the X rectangle */
-	  hRgnRect = CreateRectRgn (pRects->x1 + iOffsetX,
-				    pRects->y1 + iOffsetY,
-				    pRects->x2 + iOffsetX,
-				    pRects->y2 + iOffsetY);
-	  if (hRgnRect == NULL)
-	    {
-	      ErrorF ("winReshape - Loop CreateRectRgn (%d, %d, %d, %d) "
-		      "failed: %d\n"
-		      "\tx1: %d x2: %d xOff: %d y1: %d y2: %d yOff: %d\n",
-		      pRects->x1 + iOffsetX,
-		      pRects->y1 + iOffsetY,
-		      pRects->x2 + iOffsetX,
-		      pRects->y2 + iOffsetY,
-		      (int) GetLastError (),
-		      pRects->x1, pRects->x2, iOffsetX,
-		      pRects->y1, pRects->y2, iOffsetY);
-	    }
-
-	  /* Merge the Windows region with the accumulated region */
-	  if (CombineRgn (hRgn, hRgn, hRgnRect, RGN_OR) == ERROR)
-	    {
-	      ErrorF ("winReshape - CombineRgn () failed: %d\n",
-		      (int) GetLastError ());
-	    }
-
-	  /* Delete the temporary Windows region */
-	  DeleteObject (hRgnRect);
-        }
-      
-      /* Save a handle to the composite region in the window privates */
-      pWinPriv->hRgn = hRgn;
-    }
-
-  REGION_UNINIT(pWin->drawable.pScreen, &rrNewShape);
-  
-  return;
-}
-#endif
diff --git a/hw/xwin/winmultiwindowwindow.c b/hw/xwin/winmultiwindowwindow.c
deleted file mode 100644
index 037c881..0000000
--- a/hw/xwin/winmultiwindowwindow.c
+++ /dev/null
@@ -1,1054 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Kensuke Matsuzaki
- *		Earle F. Philhower, III
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "dixevents.h"
-#include "winmultiwindowclass.h"
-#include "winprefs.h"
-
-/*
- * External global variables
- */
-
-extern HWND			g_hDlgDepthChange;
-
-extern void winSelectIcons(WindowPtr pWin, HICON *pIcon, HICON *pSmallIcon);
-
-/*
- * Prototypes for local functions
- */
-
-void
-winCreateWindowsWindow (WindowPtr pWin);
-
-static void
-winDestroyWindowsWindow (WindowPtr pWin);
-
-static void
-winUpdateWindowsWindow (WindowPtr pWin);
-
-static void
-winFindWindow (pointer value, XID id, pointer cdata);
-
-/*
- * Constant defines
- */
-
-#define MOUSE_POLLING_INTERVAL		500
-
-
-/*
- * Macros
- */
-
-#define SubSend(pWin) \
-    ((pWin->eventMask|wOtherEventMasks(pWin)) & SubstructureNotifyMask)
-
-#define StrSend(pWin) \
-    ((pWin->eventMask|wOtherEventMasks(pWin)) & StructureNotifyMask)
-
-#define SubStrSend(pWin,pParent) (StrSend(pWin) || SubSend(pParent))
-
-
-/*
- * CreateWindow - See Porting Layer Definition - p. 37
- */
-
-Bool
-winCreateWindowMultiWindow (WindowPtr pWin)
-{
-  Bool			fResult = TRUE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGMULTIWINDOW_DEBUG
-  winTrace ("winCreateWindowMultiWindow - pWin: %p\n", pWin);
-#endif
-  
-  WIN_UNWRAP(CreateWindow);
-  fResult = (*pScreen->CreateWindow) (pWin);
-  WIN_WRAP(CreateWindow, winCreateWindowMultiWindow);
-  
-  /* Initialize some privates values */
-  pWinPriv->hRgn = NULL;
-  pWinPriv->hWnd = NULL;
-  pWinPriv->pScreenPriv = winGetScreenPriv(pWin->drawable.pScreen);
-  pWinPriv->fXKilled = FALSE;
- 
-  return fResult;
-}
-
-
-/*
- * DestroyWindow - See Porting Layer Definition - p. 37
- */
-
-Bool
-winDestroyWindowMultiWindow (WindowPtr pWin)
-{
-  Bool			fResult = TRUE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winDestroyWindowMultiWindow - pWin: %p\n", pWin);
-#endif
-  
-  WIN_UNWRAP(DestroyWindow); 
-  fResult = (*pScreen->DestroyWindow)(pWin);
-  WIN_WRAP(DestroyWindow, winDestroyWindowMultiWindow);
-  
-  /* Flag that the window has been destroyed */
-  pWinPriv->fXKilled = TRUE;
-  
-  /* Kill the MS Windows window associated with this window */
-  winDestroyWindowsWindow (pWin); 
-
-  return fResult;
-}
-
-
-/*
- * PositionWindow - See Porting Layer Definition - p. 37
- *
- * This function adjusts the position and size of Windows window
- * with respect to the underlying X window.  This is the inverse
- * of winAdjustXWindow, which adjusts X window to Windows window.
- */
-
-Bool
-winPositionWindowMultiWindow (WindowPtr pWin, int x, int y)
-{
-  Bool			fResult = TRUE;
-  int		        iX, iY, iWidth, iHeight;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-  HWND hWnd = pWinPriv->hWnd;
-  RECT rcNew;
-  RECT rcOld;
-#if CYGMULTIWINDOW_DEBUG
-  RECT rcClient;
-  RECT *lpRc;
-#endif
-  DWORD dwExStyle;
-  DWORD dwStyle;
-
-#if CYGMULTIWINDOW_DEBUG
-  winTrace ("winPositionWindowMultiWindow - pWin: %p\n", pWin);
-#endif
-  
-  WIN_UNWRAP(PositionWindow);
-  fResult = (*pScreen->PositionWindow)(pWin, x, y);
-  WIN_WRAP(PositionWindow, winPositionWindowMultiWindow);
-  
-#if CYGWINDOWING_DEBUG
-  ErrorF ("winPositionWindowMultiWindow: (x, y) = (%d, %d)\n",
-	  x, y);
-#endif
-
-  /* Bail out if the Windows window handle is bad */
-  if (!hWnd)
-    {
-#if CYGWINDOWING_DEBUG
-      ErrorF ("\timmediately return since hWnd is NULL\n");
-#endif
-      return fResult;
-    }
-
-  /* Get the Windows window style and extended style */
-  dwExStyle = GetWindowLongPtr (hWnd, GWL_EXSTYLE);
-  dwStyle = GetWindowLongPtr (hWnd, GWL_STYLE);
-
-  /* Get the X and Y location of the X window */
-  iX = pWin->drawable.x + GetSystemMetrics (SM_XVIRTUALSCREEN);
-  iY = pWin->drawable.y + GetSystemMetrics (SM_YVIRTUALSCREEN);
-
-  /* Get the height and width of the X window */
-  iWidth = pWin->drawable.width;
-  iHeight = pWin->drawable.height;
-
-  /* Store the origin, height, and width in a rectangle structure */
-  SetRect (&rcNew, iX, iY, iX + iWidth, iY + iHeight);
-
-#if CYGMULTIWINDOW_DEBUG
-  lpRc = &rcNew;
-  ErrorF ("winPositionWindowMultiWindow - (%d ms)drawable (%d, %d)-(%d, %d)\n",
-	  GetTickCount (), lpRc->left, lpRc->top, lpRc->right, lpRc->bottom);
-#endif
-
-  /*
-   * Calculate the required size of the Windows window rectangle,
-   * given the size of the Windows window client area.
-   */
-  AdjustWindowRectEx (&rcNew, dwStyle, FALSE, dwExStyle);
-
-  /* Get a rectangle describing the old Windows window */
-  GetWindowRect (hWnd, &rcOld);
-
-#if CYGMULTIWINDOW_DEBUG
-  /* Get a rectangle describing the Windows window client area */
-  GetClientRect (hWnd, &rcClient);
-
-  lpRc = &rcNew;
-  ErrorF ("winPositionWindowMultiWindow - (%d ms)rcNew (%d, %d)-(%d, %d)\n",
-	  GetTickCount (), lpRc->left, lpRc->top, lpRc->right, lpRc->bottom);
-      
-  lpRc = &rcOld;
-  ErrorF ("winPositionWindowMultiWindow - (%d ms)rcOld (%d, %d)-(%d, %d)\n",
-	  GetTickCount (), lpRc->left, lpRc->top, lpRc->right, lpRc->bottom);
-      
-  lpRc = &rcClient;
-  ErrorF ("(%d ms)rcClient (%d, %d)-(%d, %d)\n",
-	  GetTickCount (), lpRc->left, lpRc->top, lpRc->right, lpRc->bottom);
-#endif
-
-  /* Check if the old rectangle and new rectangle are the same */
-  if (!EqualRect (&rcNew, &rcOld))
-    {
-#if CYGMULTIWINDOW_DEBUG
-      ErrorF ("winPositionWindowMultiWindow - Need to move\n");
-#endif
-
-#if CYGWINDOWING_DEBUG
-      ErrorF ("\tMoveWindow to (%ld, %ld) - %ldx%ld\n", rcNew.left, rcNew.top,
-	      rcNew.right - rcNew.left, rcNew.bottom - rcNew.top);
-#endif
-      /* Change the position and dimensions of the Windows window */
-      MoveWindow (hWnd,
-		  rcNew.left, rcNew.top,
-		  rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
-		  TRUE);
-    }
-  else
-    {
-#if CYGMULTIWINDOW_DEBUG
-      ErrorF ("winPositionWindowMultiWindow - Not need to move\n");
-#endif
-    }
-
-  return fResult;
-}
-
-
-/*
- * ChangeWindowAttributes - See Porting Layer Definition - p. 37
- */
-
-Bool
-winChangeWindowAttributesMultiWindow (WindowPtr pWin, unsigned long mask)
-{
-  Bool			fResult = TRUE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winChangeWindowAttributesMultiWindow - pWin: %08x\n", pWin);
-#endif
-  
-  WIN_UNWRAP(ChangeWindowAttributes); 
-  fResult = (*pScreen->ChangeWindowAttributes)(pWin, mask);
-  WIN_WRAP(ChangeWindowAttributes, winChangeWindowAttributesMultiWindow);
-  
-  /*
-   * NOTE: We do not currently need to do anything here.
-   */
-
-  return fResult;
-}
-
-
-/*
- * UnmapWindow - See Porting Layer Definition - p. 37
- * Also referred to as UnrealizeWindow
- */
-
-Bool
-winUnmapWindowMultiWindow (WindowPtr pWin)
-{
-  Bool			fResult = TRUE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winUnmapWindowMultiWindow - pWin: %08x\n", pWin);
-#endif
-  
-  WIN_UNWRAP(UnrealizeWindow); 
-  fResult = (*pScreen->UnrealizeWindow)(pWin);
-  WIN_WRAP(UnrealizeWindow, winUnmapWindowMultiWindow);
-  
-  /* Flag that the window has been killed */
-  pWinPriv->fXKilled = TRUE;
- 
-  /* Destroy the Windows window associated with this X window */
-  winDestroyWindowsWindow (pWin);
-
-  return fResult;
-}
-
-
-/*
- * MapWindow - See Porting Layer Definition - p. 37
- * Also referred to as RealizeWindow
- */
-
-Bool
-winMapWindowMultiWindow (WindowPtr pWin)
-{
-  Bool			fResult = TRUE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winMapWindowMultiWindow - pWin: %08x\n", pWin);
-#endif
-  
-  WIN_UNWRAP(RealizeWindow); 
-  fResult = (*pScreen->RealizeWindow)(pWin);
-  WIN_WRAP(RealizeWindow, winMapWindowMultiWindow);
-  
-  /* Flag that this window has not been destroyed */
-  pWinPriv->fXKilled = FALSE;
-
-  /* Refresh/redisplay the Windows window associated with this X window */
-  winUpdateWindowsWindow (pWin);
-
-#ifdef SHAPE
-  /* Update the Windows window's shape */
-  winReshapeMultiWindow (pWin);
-  winUpdateRgnMultiWindow (pWin);
-#endif
-
-  return fResult;
-}
-
-
-/*
- * ReparentWindow - See Porting Layer Definition - p. 42
- */
-
-void
-winReparentWindowMultiWindow (WindowPtr pWin, WindowPtr pPriorParent)
-{
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winReparentMultiWindow - pWin: %08x\n", pWin);
-#endif
-
-  WIN_UNWRAP(ReparentWindow);
-  if (pScreen->ReparentWindow) 
-    (*pScreen->ReparentWindow)(pWin, pPriorParent);
-  WIN_WRAP(ReparentWindow, winReparentWindowMultiWindow);
-  
-  /* Update the Windows window associated with this X window */
-  winUpdateWindowsWindow (pWin);
-}
-
-
-/*
- * RestackWindow - Shuffle the z-order of a window
- */
-
-void
-winRestackWindowMultiWindow (WindowPtr pWin, WindowPtr pOldNextSib)
-{
-  WindowPtr		pPrevWin;
-  UINT			uFlags;
-  HWND			hInsertAfter;
-  HWND                  hWnd = NULL;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGMULTIWINDOW_DEBUG || CYGWINDOWING_DEBUG
-  winTrace ("winRestackMultiWindow - %08x\n", pWin);
-#endif
-  
-   WIN_UNWRAP(RestackWindow);
-   if (pScreen->RestackWindow) 
-     (*pScreen->RestackWindow)(pWin, pOldNextSib);
-   WIN_WRAP(RestackWindow, winRestackWindowMultiWindow);
-  
-#if 1
-  /*
-   * Calling winReorderWindowsMultiWindow here means our window manager
-   * (i.e. Windows Explorer) has initiative to determine Z order.
-   */
-  if (pWin->nextSib != pOldNextSib)
-    winReorderWindowsMultiWindow ();
-#else
-  /* Bail out if no window privates or window handle is invalid */
-  if (!pWinPriv || !pWinPriv->hWnd)
-    return;
-
-  /* Get a pointer to our previous sibling window */
-  pPrevWin = pWin->prevSib;
-
-  /*
-   * Look for a sibling window with
-   * valid privates and window handle
-   */
-  while (pPrevWin
-	 && !winGetWindowPriv(pPrevWin)
-	 && !winGetWindowPriv(pPrevWin)->hWnd)
-    pPrevWin = pPrevWin->prevSib;
-      
-  /* Check if we found a valid sibling */
-  if (pPrevWin)
-    {
-      /* Valid sibling - get handle to insert window after */
-      hInsertAfter = winGetWindowPriv(pPrevWin)->hWnd;
-      uFlags = SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE;
-  
-      hWnd = GetNextWindow (pWinPriv->hWnd, GW_HWNDPREV);
-
-      do
-	{
-	  if (GetProp (hWnd, WIN_WINDOW_PROP))
-	    {
-	      if (hWnd == winGetWindowPriv(pPrevWin)->hWnd)
-		{
-		  uFlags |= SWP_NOZORDER;
-		}
-	      break;
-	    }
-	  hWnd = GetNextWindow (hWnd, GW_HWNDPREV);
-	}
-      while (hWnd);
-    }
-  else
-    {
-      /* No valid sibling - make this window the top window */
-      hInsertAfter = HWND_TOP;
-      uFlags = SWP_NOMOVE | SWP_NOSIZE;
-    }
-      
-  /* Perform the restacking operation in Windows */
-  SetWindowPos (pWinPriv->hWnd,
-		hInsertAfter,
-		0, 0,
-		0, 0,
-		uFlags);
-#endif
-}
-
-
-/*
- * winCreateWindowsWindow - Create a Windows window associated with an X window
- */
-
-void
-winCreateWindowsWindow (WindowPtr pWin)
-{
-  int                   iX, iY;
-  int			iWidth;
-  int			iHeight;
-  HWND			hWnd;
-  WNDCLASSEX		wc;
-  winWindowPriv(pWin);
-  HICON			hIcon;
-  HICON			hIconSmall;
-#define CLASS_NAME_LENGTH 512
-  char                  pszClass[CLASS_NAME_LENGTH], pszWindowID[12];
-  char                  *res_name, *res_class, *res_role;
-  static int		s_iWindowID = 0;
-  winPrivScreenPtr	pScreenPriv = pWinPriv->pScreenPriv;
-  WinXSizeHints         hints;
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winCreateWindowsWindow - pWin: %08x\n", pWin);
-#endif
-
-  iX = pWin->drawable.x + GetSystemMetrics (SM_XVIRTUALSCREEN);
-  iY = pWin->drawable.y + GetSystemMetrics (SM_YVIRTUALSCREEN);
-
-  /* Default positions if none specified */
-  if (!winMultiWindowGetWMNormalHints(pWin, &hints))
-    hints.flags = 0;
-  if ( !(hints.flags & (USPosition|PPosition)) &&
-       !winMultiWindowGetTransientFor (pWin, NULL) &&
-       !pWin->overrideRedirect )
-    {
-      iX = CW_USEDEFAULT;
-      iY = CW_USEDEFAULT;
-    }
-
-  iWidth = pWin->drawable.width;
-  iHeight = pWin->drawable.height;
-
-  winSelectIcons(pWin, &hIcon, &hIconSmall); 
-
-  /* Set standard class name prefix so we can identify window easily */
-  strncpy (pszClass, WINDOW_CLASS_X, sizeof(pszClass));
-
-  if (winMultiWindowGetClassHint (pWin, &res_name, &res_class))
-    {
-      strncat (pszClass, "-", 1);
-      strncat (pszClass, res_name, CLASS_NAME_LENGTH - strlen (pszClass));
-      strncat (pszClass, "-", 1);
-      strncat (pszClass, res_class, CLASS_NAME_LENGTH - strlen (pszClass));
-      
-      /* Check if a window class is provided by the WM_WINDOW_ROLE property,
-       * if not use the WM_CLASS information.
-       * For further information see:
-       * http://tronche.com/gui/x/icccm/sec-5.html
-       */ 
-      if (winMultiWindowGetWindowRole (pWin, &res_role) )
-	{
-	  strcat (pszClass, "-");
-	  strcat (pszClass, res_role);
-	  free (res_role);
-	}
-
-      free (res_name);
-      free (res_class);
-    }
-
-  /* Add incrementing window ID to make unique class name */
-  snprintf (pszWindowID, sizeof(pszWindowID), "-%x", s_iWindowID++);
-  pszWindowID[sizeof(pszWindowID)-1] = 0;
-  strcat (pszClass, pszWindowID);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winCreateWindowsWindow - Creating class: %s\n", pszClass);
-#endif
-
-  /* Setup our window class */
-  wc.cbSize = sizeof(wc);
-  wc.style = CS_HREDRAW | CS_VREDRAW;
-  wc.lpfnWndProc = winTopLevelWindowProc;
-  wc.cbClsExtra = 0;
-  wc.cbWndExtra = 0;
-  wc.hInstance = g_hInstance;
-  wc.hIcon = hIcon;
-  wc.hIconSm = hIconSmall;
-  wc.hCursor = 0;
-  wc.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
-  wc.lpszMenuName = NULL;
-  wc.lpszClassName = pszClass;
-  RegisterClassEx (&wc);
-
-  /* Create the window */
-  /* Make it OVERLAPPED in create call since WS_POPUP doesn't support */
-  /* CW_USEDEFAULT, change back to popup after creation */
-  hWnd = CreateWindowExA (WS_EX_TOOLWINDOW,	/* Extended styles */
-			  pszClass,		/* Class name */
-			  WINDOW_TITLE_X,	/* Window name */
-			  WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
-			  iX,			/* Horizontal position */
-			  iY,			/* Vertical position */
-			  iWidth,		/* Right edge */ 
-			  iHeight,		/* Bottom edge */
-			  (HWND) NULL,		/* No parent or owner window */
-			  (HMENU) NULL,		/* No menu */
-			  GetModuleHandle (NULL), /* Instance handle */
-			  pWin);		/* ScreenPrivates */
-  if (hWnd == NULL)
-    {
-      ErrorF ("winCreateWindowsWindow - CreateWindowExA () failed: %d\n",
-	      (int) GetLastError ());
-    }
- 
-  /* Change style back to popup, already placed... */
-  SetWindowLong (hWnd, GWL_STYLE, WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
-  SetWindowPos (hWnd, 0, 0, 0, 0, 0,
-		SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
-  /* Make sure it gets the proper system menu for a WS_POPUP, too */
-  GetSystemMenu (hWnd, TRUE);
-
-  pWinPriv->hWnd = hWnd;
-
-  /* Cause any .XWinrc menus to be added in main WNDPROC */
-  PostMessage (hWnd, WM_INIT_SYS_MENU, 0, 0);
-  
-  SetProp (pWinPriv->hWnd, WIN_WID_PROP, (HANDLE) winGetWindowID(pWin));
-
-  /* Flag that this Windows window handles its own activation */
-  SetProp (pWinPriv->hWnd, WIN_NEEDMANAGE_PROP, (HANDLE) 0);
-
-  /* Call engine-specific create window procedure */
-  (*pScreenPriv->pwinFinishCreateWindowsWindow) (pWin);
-}
-
-
-Bool winInDestroyWindowsWindow = FALSE;
-/*
- * winDestroyWindowsWindow - Destroy a Windows window associated
- * with an X window
- */
-static void
-winDestroyWindowsWindow (WindowPtr pWin)
-{
-  MSG			msg;
-  winWindowPriv(pWin);
-  HICON			hiconClass;
-  HICON			hiconSmClass;
-  HMODULE		hInstance;
-  int			iReturn;
-  char			pszClass[512];
-  BOOL			oldstate = winInDestroyWindowsWindow;
-  
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winDestroyWindowsWindow\n");
-#endif
-
-  /* Bail out if the Windows window handle is invalid */
-  if (pWinPriv->hWnd == NULL)
-    return;
-
-  winInDestroyWindowsWindow = TRUE;
-
-  /* Store the info we need to destroy after this window is gone */
-  hInstance = (HINSTANCE) GetClassLong (pWinPriv->hWnd, GCL_HMODULE);
-  hiconClass = (HICON) GetClassLong (pWinPriv->hWnd, GCL_HICON);
-  hiconSmClass = (HICON) GetClassLong (pWinPriv->hWnd, GCL_HICONSM);
-  iReturn = GetClassName (pWinPriv->hWnd, pszClass, 512);
-  
-  SetProp (pWinPriv->hWnd, WIN_WINDOW_PROP, NULL);
-  /* Destroy the Windows window */
-  DestroyWindow (pWinPriv->hWnd);
-
-  /* Null our handle to the Window so referencing it will cause an error */
-  pWinPriv->hWnd = NULL;
-
-  /* Process all messages on our queue */
-  while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
-    {
-      if (g_hDlgDepthChange == 0 || !IsDialogMessage (g_hDlgDepthChange, &msg))
-	{
-	  DispatchMessage (&msg);
-	}
-    }
-
-  /* Only if we were able to get the name */
-  if (iReturn)
-    { 
-#if CYGMULTIWINDOW_DEBUG
-      ErrorF ("winDestroyWindowsWindow - Unregistering %s: ", pszClass);
-#endif
-      iReturn = UnregisterClass (pszClass, hInstance);
-      
-#if CYGMULTIWINDOW_DEBUG
-      ErrorF ("winDestroyWindowsWindow - %d Deleting Icon: ", iReturn);
-#endif
-      
-      winDestroyIcon(hiconClass);
-      winDestroyIcon(hiconSmClass);
-    }
-
-  winInDestroyWindowsWindow = oldstate;
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("-winDestroyWindowsWindow\n");
-#endif
-}
-
-
-/*
- * winUpdateWindowsWindow - Redisplay/redraw a Windows window
- * associated with an X window
- */
-
-static void
-winUpdateWindowsWindow (WindowPtr pWin)
-{
-  winWindowPriv(pWin);
-  HWND			hWnd = pWinPriv->hWnd;
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winUpdateWindowsWindow\n");
-#endif
-
-  /* Check if the Windows window's parents have been destroyed */
-  if (pWin->parent != NULL
-      && pWin->parent->parent == NULL
-      && pWin->mapped)
-    {
-      /* Create the Windows window if it has been destroyed */
-      if (hWnd == NULL)
-	{
-	  winCreateWindowsWindow (pWin);
-	  assert (pWinPriv->hWnd != NULL);
-	}
-
-      /* Display the window without activating it */
-      ShowWindow (pWinPriv->hWnd, SW_SHOWNOACTIVATE);
-
-      /* Send first paint message */
-      UpdateWindow (pWinPriv->hWnd);
-    }
-  else if (hWnd != NULL)
-    {
-      /* Destroy the Windows window if its parents are destroyed */
-      winDestroyWindowsWindow (pWin);
-      assert (pWinPriv->hWnd == NULL);
-    }
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("-winUpdateWindowsWindow\n");
-#endif
-}
-
-
-/*
- * winGetWindowID - 
- */
-
-XID
-winGetWindowID (WindowPtr pWin)
-{
-  WindowIDPairRec	wi = {pWin, 0};
-  ClientPtr		c = wClient(pWin);
-  
-  /* */
-  FindClientResourcesByType (c, RT_WINDOW, winFindWindow, &wi);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winGetWindowID - Window ID: %d\n", wi.id);
-#endif
-
-  return wi.id;
-}
-
-
-/*
- * winFindWindow - 
- */
-
-static void
-winFindWindow (pointer value, XID id, pointer cdata)
-{
-  WindowIDPairPtr	wi = (WindowIDPairPtr)cdata;
-
-  if (value == wi->value)
-    {
-      wi->id = id;
-    }
-}
-
-
-/*
- * winReorderWindowsMultiWindow - 
- */
-
-void
-winReorderWindowsMultiWindow (void)
-{
-  HWND hwnd = NULL;
-  WindowPtr pWin = NULL;
-  WindowPtr pWinSib = NULL;
-  XID vlist[2];
-  static Bool fRestacking = FALSE; /* Avoid recusive calls to this function */
-  DWORD dwCurrentProcessID = GetCurrentProcessId ();
-  DWORD dwWindowProcessID = 0;
-
-#if CYGMULTIWINDOW_DEBUG || CYGWINDOWING_DEBUG
-  winTrace ("winReorderWindowsMultiWindow\n");
-#endif
-
-  if (fRestacking)
-    {
-      /* It is a recusive call so immediately exit */
-#if CYGWINDOWING_DEBUG
-      ErrorF ("winReorderWindowsMultiWindow - "
-	      "exit because fRestacking == TRUE\n");
-#endif
-      return;
-    }
-  fRestacking = TRUE;
-
-  /* Loop through top level Window windows, descending in Z order */
-  for ( hwnd = GetTopWindow (NULL);
-	hwnd;
-	hwnd = GetNextWindow (hwnd, GW_HWNDNEXT) )
-    {
-      /* Don't take care of other Cygwin/X process's windows */
-      GetWindowThreadProcessId (hwnd, &dwWindowProcessID);
-
-      if ( GetProp (hwnd, WIN_WINDOW_PROP)
-	   && (dwWindowProcessID == dwCurrentProcessID)
-	   && !IsIconic (hwnd) ) /* ignore minimized windows */
-	{
-	  pWinSib = pWin;
-	  pWin = GetProp (hwnd, WIN_WINDOW_PROP);
-	      
-	  if (!pWinSib)
-	    { /* 1st window - raise to the top */
-	      vlist[0] = Above;
-		  
-	      ConfigureWindow (pWin, CWStackMode, vlist, wClient(pWin));
-	    }
-	  else
-	    { /* 2nd or deeper windows - just below the previous one */
-	      vlist[0] = winGetWindowID (pWinSib);
-	      vlist[1] = Below;
-
-	      ConfigureWindow (pWin, CWSibling | CWStackMode,
-			       vlist, wClient(pWin));
-	    }
-	}
-    }
-
-  fRestacking = FALSE;
-}
-
-
-/*
- * winMinimizeWindow - Minimize in response to WM_CHANGE_STATE
- */
-
-void
-winMinimizeWindow (Window id)
-{
-  WindowPtr		pWin;
-  winPrivWinPtr	pWinPriv;
-#ifdef XWIN_MULTIWINDOWEXTWM
-  win32RootlessWindowPtr pRLWinPriv;
-#endif
-  HWND hWnd;
-  ScreenPtr pScreen = NULL;
-  winPrivScreenPtr pScreenPriv = NULL;
-  winScreenInfo *pScreenInfo = NULL;
-
-#if CYGWINDOWING_DEBUG
-  ErrorF ("winMinimizeWindow\n");
-#endif
-
-  pWin = LookupIDByType (id, RT_WINDOW);
-  if (!pWin) 
-  { 
-      ErrorF("%s: NULL pWin. Leaving\n", __FUNCTION__); 
-      return; 
-  }
-
-  pScreen = pWin->drawable.pScreen;
-  if (pScreen) pScreenPriv = winGetScreenPriv(pScreen);
-  if (pScreenPriv) pScreenInfo = pScreenPriv->pScreenInfo;
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-  if (pScreenPriv && pScreenInfo->fInternalWM)
-    {
-      pRLWinPriv  = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, FALSE);
-      hWnd = pRLWinPriv->hWnd;
-    }
-  else
-#else
-  if (pScreenPriv)
-#endif
-    {
-      pWinPriv = winGetWindowPriv (pWin);
-      hWnd = pWinPriv->hWnd;
-    }
-
-  ShowWindow (hWnd, SW_MINIMIZE);
-}
-
-
-/*
- * CopyWindow - See Porting Layer Definition - p. 39
- */
-void
-winCopyWindowMultiWindow (WindowPtr pWin, DDXPointRec oldpt,
-			  RegionPtr oldRegion)
-{
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGWINDOWING_DEBUG
-  ErrorF ("CopyWindowMultiWindow\n");
-#endif
-  WIN_UNWRAP(CopyWindow); 
-  (*pScreen->CopyWindow)(pWin, oldpt, oldRegion);
-  WIN_WRAP(CopyWindow, winCopyWindowMultiWindow);
-}
-
-
-/*
- * MoveWindow - See Porting Layer Definition - p. 42
- */
-void
-winMoveWindowMultiWindow (WindowPtr pWin, int x, int y,
-			  WindowPtr pSib, VTKind kind)
-{
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGWINDOWING_DEBUG
-  ErrorF ("MoveWindowMultiWindow to (%d, %d)\n", x, y);
-#endif
-
-  WIN_UNWRAP(MoveWindow); 
-  (*pScreen->MoveWindow)(pWin, x, y, pSib, kind);
-  WIN_WRAP(MoveWindow, winMoveWindowMultiWindow);
-}
-
-
-/*
- * ResizeWindow - See Porting Layer Definition - p. 42
- */
-void
-winResizeWindowMultiWindow (WindowPtr pWin, int x, int y, unsigned int w,
-			    unsigned int h, WindowPtr pSib)
-{
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGWINDOWING_DEBUG
-  ErrorF ("ResizeWindowMultiWindow to (%d, %d) - %dx%d\n", x, y, w, h);
-#endif
-  WIN_UNWRAP(ResizeWindow); 
-  (*pScreen->ResizeWindow)(pWin, x, y, w, h, pSib);
-  WIN_WRAP(ResizeWindow, winResizeWindowMultiWindow);
-}
-
-
-/*
- * winAdjustXWindow
- *
- * Move and resize X window with respect to corresponding Windows window.
- * This is called from WM_MOVE/WM_SIZE handlers when the user performs
- * any windowing operation (move, resize, minimize, maximize, restore).
- *
- * The functionality is the inverse of winPositionWindowMultiWindow, which
- * adjusts Windows window with respect to X window.
- */
-int
-winAdjustXWindow (WindowPtr pWin, HWND hwnd)
-{
-  RECT rcDraw; /* Rect made from pWin->drawable to be adjusted */
-  RECT rcWin;  /* The source: WindowRect from hwnd */
-  DrawablePtr pDraw;
-  XID vlist[4];
-  LONG dX, dY, dW, dH, x, y;
-  DWORD dwStyle, dwExStyle;
-
-#define WIDTH(rc) (rc.right - rc.left)
-#define HEIGHT(rc) (rc.bottom - rc.top)
-  
-#if CYGWINDOWING_DEBUG
-  ErrorF ("winAdjustXWindow\n");
-#endif
-
-  if (IsIconic (hwnd))
-    {
-#if CYGWINDOWING_DEBUG
-      ErrorF ("\timmediately return because the window is iconized\n");
-#endif
-      /*
-       * If the Windows window is minimized, its WindowRect has
-       * meaningless values so we don't adjust X window to it.
-       */
-      vlist[0] = 0;
-      vlist[1] = 0;
-      return ConfigureWindow (pWin, CWX | CWY, vlist, wClient(pWin));
-    }
-  
-  pDraw = &pWin->drawable;
-
-  /* Calculate the window rect from the drawable */
-  x = pDraw->x + GetSystemMetrics (SM_XVIRTUALSCREEN);
-  y = pDraw->y + GetSystemMetrics (SM_YVIRTUALSCREEN);
-  SetRect (&rcDraw, x, y, x + pDraw->width, y + pDraw->height);
-#ifdef CYGMULTIWINDOW_DEBUG
-          winDebug("\tDrawable extend {%d, %d, %d, %d}, {%d, %d}\n", 
-              rcDraw.left, rcDraw.top, rcDraw.right, rcDraw.bottom,
-              rcDraw.right - rcDraw.left, rcDraw.bottom - rcDraw.top);
-#endif
-  dwExStyle = GetWindowLongPtr (hwnd, GWL_EXSTYLE);
-  dwStyle = GetWindowLongPtr (hwnd, GWL_STYLE);
-#ifdef CYGMULTIWINDOW_DEBUG
-          winDebug("\tWindowStyle: %08x %08x\n", dwStyle, dwExStyle);
-#endif
-  AdjustWindowRectEx (&rcDraw, dwStyle, FALSE, dwExStyle);
-
-  /* The source of adjust */
-  GetWindowRect (hwnd, &rcWin);
-#ifdef CYGMULTIWINDOW_DEBUG
-          winDebug("\tWindow extend {%d, %d, %d, %d}, {%d, %d}\n", 
-              rcWin.left, rcWin.top, rcWin.right, rcWin.bottom,
-              rcWin.right - rcWin.left, rcWin.bottom - rcWin.top);
-          winDebug("\tDraw extend {%d, %d, %d, %d}, {%d, %d}\n", 
-              rcDraw.left, rcDraw.top, rcDraw.right, rcDraw.bottom,
-              rcDraw.right - rcDraw.left, rcDraw.bottom - rcDraw.top);
-#endif
-
-  if (EqualRect (&rcDraw, &rcWin)) {
-    /* Bail if no adjust is needed */
-#if CYGWINDOWING_DEBUG
-    ErrorF ("\treturn because already adjusted\n");
-#endif
-    return 0;
-  }
-  
-  /* Calculate delta values */
-  dX = rcWin.left - rcDraw.left;
-  dY = rcWin.top - rcDraw.top;
-  dW = WIDTH(rcWin) - WIDTH(rcDraw);
-  dH = HEIGHT(rcWin) - HEIGHT(rcDraw);
-
-  /*
-   * Adjust.
-   * We may only need to move (vlist[0] and [1]), or only resize
-   * ([2] and [3]) but currently we set all the parameters and leave
-   * the decision to ConfigureWindow.  The reason is code simplicity.
-  */
-  vlist[0] = pDraw->x + dX - wBorderWidth(pWin);
-  vlist[1] = pDraw->y + dY - wBorderWidth(pWin);
-  vlist[2] = pDraw->width + dW;
-  vlist[3] = pDraw->height + dH;
-#if CYGWINDOWING_DEBUG
-  ErrorF ("\tConfigureWindow to (%ld, %ld) - %ldx%ld\n", vlist[0], vlist[1],
-	  vlist[2], vlist[3]);
-#endif
-  return ConfigureWindow (pWin, CWX | CWY | CWWidth | CWHeight,
-			  vlist, wClient(pWin));
-  
-#undef WIDTH
-#undef HEIGHT
-}
-
diff --git a/hw/xwin/winmultiwindowwm.c b/hw/xwin/winmultiwindowwm.c
deleted file mode 100644
index 5401ecd..0000000
--- a/hw/xwin/winmultiwindowwm.c
+++ /dev/null
@@ -1,1440 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Kensuke Matsuzaki
- */
-
-/* X headers */
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#ifdef __CYGWIN__
-#include <sys/select.h>
-#endif
-#include <fcntl.h>
-#include <setjmp.h>
-#define HANDLE void *
-#include <pthread.h>
-#undef HANDLE
-#include <X11/X.h>
-#include <X11/Xatom.h>
-#include <X11/Xlib.h>
-#include <X11/Xlocale.h>
-#include <X11/Xproto.h>
-#include <X11/Xutil.h>
-#include <X11/cursorfont.h>
-
-/* Windows headers */
-#ifdef __CYGWIN__
-/* Fixups to prevent collisions between Windows and X headers */
-#define ATOM DWORD
-
-#include <windows.h>
-#else
-#include <Xwindows.h>
-#endif
-
-/* Local headers */
-#include "objbase.h"
-#include "ddraw.h"
-#include "winwindow.h"
-#ifdef XWIN_MULTIWINDOWEXTWM
-#include "windowswmstr.h"
-#endif
-
-extern void winDebug(const char *format, ...);
-
-#ifndef CYGDEBUG
-#define CYGDEBUG NO
-#endif
-
-/*
- * Constant defines
- */
-
-#define WIN_CONNECT_RETRIES	5
-#define WIN_CONNECT_DELAY	5
-#ifdef HAS_DEVWINDOWS
-# define WIN_MSG_QUEUE_FNAME	"/dev/windows"
-#endif
-#define WIN_JMP_OKAY		0
-#define WIN_JMP_ERROR_IO	2
-
-
-/*
- * Local structures
- */
-
-typedef struct _WMMsgNodeRec {
-  winWMMessageRec	msg;
-  struct _WMMsgNodeRec	*pNext;
-} WMMsgNodeRec, *WMMsgNodePtr;
-
-typedef struct _WMMsgQueueRec {
-  struct _WMMsgNodeRec	*pHead;
-  struct _WMMsgNodeRec	*pTail;
-  pthread_mutex_t	pmMutex;
-  pthread_cond_t	pcNotEmpty;
-  int			nQueueSize;
-} WMMsgQueueRec, *WMMsgQueuePtr;
-
-typedef struct _WMInfo {
-  Display		*pDisplay;
-  WMMsgQueueRec		wmMsgQueue;
-  Atom			atmWmProtos;
-  Atom			atmWmDelete;
-  Atom			atmPrivMap;
-  Bool			fAllowOtherWM;
-} WMInfoRec, *WMInfoPtr;
-
-typedef struct _WMProcArgRec {
-  DWORD			dwScreen;
-  WMInfoPtr		pWMInfo;
-  pthread_mutex_t	*ppmServerStarted;
-} WMProcArgRec, *WMProcArgPtr;
-
-typedef struct _XMsgProcArgRec {
-  Display		*pDisplay;
-  DWORD			dwScreen;
-  WMInfoPtr		pWMInfo;
-  pthread_mutex_t	*ppmServerStarted;
-  HWND			hwndScreen;
-} XMsgProcArgRec, *XMsgProcArgPtr;
-
-
-/*
- * References to external symbols
- */
-
-extern char *display;
-extern void ErrorF (const char* /*f*/, ...);
-
-
-/*
- * Prototypes for local functions
- */
-
-static void
-PushMessage (WMMsgQueuePtr pQueue, WMMsgNodePtr pNode);
-
-static WMMsgNodePtr
-PopMessage (WMMsgQueuePtr pQueue, WMInfoPtr pWMInfo);
-
-static Bool
-InitQueue (WMMsgQueuePtr pQueue);
-
-static void
-GetWindowName (Display * pDpy, Window iWin, char **ppName);
-
-static int
-SendXMessage (Display *pDisplay, Window iWin, Atom atmType, long nData);
-
-static void
-UpdateName (WMInfoPtr pWMInfo, Window iWindow);
-
-static void*
-winMultiWindowWMProc (void* pArg);
-
-static int
-winMultiWindowWMErrorHandler (Display *pDisplay, XErrorEvent *pErr);
-
-static int
-winMultiWindowWMIOErrorHandler (Display *pDisplay);
-
-static void *
-winMultiWindowXMsgProc (void *pArg);
-
-static int
-winMultiWindowXMsgProcErrorHandler (Display *pDisplay, XErrorEvent *pErr);
-
-static int
-winMultiWindowXMsgProcIOErrorHandler (Display *pDisplay);
-
-static int
-winRedirectErrorHandler (Display *pDisplay, XErrorEvent *pErr);
-
-static void
-winInitMultiWindowWM (WMInfoPtr pWMInfo, WMProcArgPtr pProcArg);
-
-#if 0
-static void
-PreserveWin32Stack(WMInfoPtr pWMInfo, Window iWindow, UINT direction);
-#endif
-
-static Bool
-CheckAnotherWindowManager (Display *pDisplay, DWORD dwScreen);
-
-
-/*
- * Local globals
- */
-
-static jmp_buf			g_jmpWMEntry;
-static jmp_buf			g_jmpXMsgProcEntry;
-static Bool			g_shutdown = FALSE;
-static Bool			redirectError = FALSE;
-static Bool			g_fAnotherWMRunnig = FALSE;
-
-/*
- * PushMessage - Push a message onto the queue
- */
-
-static void
-PushMessage (WMMsgQueuePtr pQueue, WMMsgNodePtr pNode)
-{
-
-  /* Lock the queue mutex */
-  pthread_mutex_lock (&pQueue->pmMutex);
-
-  pNode->pNext = NULL;
-  
-  if (pQueue->pTail != NULL)
-    {
-      pQueue->pTail->pNext = pNode;
-    }
-  pQueue->pTail = pNode;
-  
-  if (pQueue->pHead == NULL)
-    {
-      pQueue->pHead = pNode;
-    }
-
-
-#if 0
-  switch (pNode->msg.msg)
-    {
-    case WM_WM_MOVE:
-      ErrorF ("\tWM_WM_MOVE\n");
-      break;
-    case WM_WM_SIZE:
-      ErrorF ("\tWM_WM_SIZE\n");
-      break;
-    case WM_WM_RAISE:
-      ErrorF ("\tWM_WM_RAISE\n");
-      break;
-    case WM_WM_LOWER:
-      ErrorF ("\tWM_WM_LOWER\n");
-      break;
-    case WM_WM_MAP:
-      ErrorF ("\tWM_WM_MAP\n");
-      break;
-    case WM_WM_UNMAP:
-      ErrorF ("\tWM_WM_UNMAP\n");
-      break;
-    case WM_WM_KILL:
-      ErrorF ("\tWM_WM_KILL\n");
-      break;
-    case WM_WM_ACTIVATE:
-      ErrorF ("\tWM_WM_ACTIVATE\n");
-      break;
-    default:
-      ErrorF ("\tUnknown Message.\n");
-      break;
-    }
-#endif
-
-  /* Increase the count of elements in the queue by one */
-  ++(pQueue->nQueueSize);
-
-  /* Release the queue mutex */
-  pthread_mutex_unlock (&pQueue->pmMutex);
-
-  /* Signal that the queue is not empty */
-  pthread_cond_signal (&pQueue->pcNotEmpty);
-}
-
-
-#if CYGMULTIWINDOW_DEBUG
-/*
- * QueueSize - Return the size of the queue
- */
-
-static int
-QueueSize (WMMsgQueuePtr pQueue)
-{
-  WMMsgNodePtr		pNode;
-  int			nSize = 0;
-  
-  /* Loop through all elements in the queue */
-  for (pNode = pQueue->pHead; pNode != NULL; pNode = pNode->pNext)
-    ++nSize;
-
-  return nSize;
-}
-#endif
-
-
-/*
- * PopMessage - Pop a message from the queue
- */
-
-static WMMsgNodePtr
-PopMessage (WMMsgQueuePtr pQueue, WMInfoPtr pWMInfo)
-{
-  WMMsgNodePtr		pNode;
-
-  /* Lock the queue mutex */
-  pthread_mutex_lock (&pQueue->pmMutex);
-
-  /* Wait for --- */
-  while (pQueue->pHead == NULL)
-    {
-      pthread_cond_wait (&pQueue->pcNotEmpty, &pQueue->pmMutex);
-    }
-  
-  pNode = pQueue->pHead;
-  if (pQueue->pHead != NULL)
-    {
-      pQueue->pHead = pQueue->pHead->pNext;
-    }
-
-  if (pQueue->pTail == pNode)
-    {
-      pQueue->pTail = NULL;
-    }
-
-  /* Drop the number of elements in the queue by one */
-  --(pQueue->nQueueSize);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("Queue Size %d %d\n", pQueue->nQueueSize, QueueSize(pQueue));
-#endif
-  
-  /* Release the queue mutex */
-  pthread_mutex_unlock (&pQueue->pmMutex);
-
-  return pNode;
-}
-
-
-#if 0
-/*
- * HaveMessage - 
- */
-
-static Bool
-HaveMessage (WMMsgQueuePtr pQueue, UINT msg, Window iWindow)
-{
-  WMMsgNodePtr pNode;
-  
-  for (pNode = pQueue->pHead; pNode != NULL; pNode = pNode->pNext)
-    {
-      if (pNode->msg.msg==msg && pNode->msg.iWindow==iWindow)
-	return True;
-    }
-  
-  return False;
-}
-#endif
-
-
-/*
- * InitQueue - Initialize the Window Manager message queue
- */
-
-static
-Bool
-InitQueue (WMMsgQueuePtr pQueue)
-{
-  /* Check if the pQueue pointer is NULL */
-  if (pQueue == NULL)
-    {
-      ErrorF ("InitQueue - pQueue is NULL.  Exiting.\n");
-      return FALSE;
-    }
-
-  /* Set the head and tail to NULL */
-  pQueue->pHead = NULL;
-  pQueue->pTail = NULL;
-
-  /* There are no elements initially */
-  pQueue->nQueueSize = 0;
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("InitQueue - Queue Size %d %d\n", pQueue->nQueueSize,
-	  QueueSize(pQueue));
-#endif
-
-  ErrorF ("InitQueue - Calling pthread_mutex_init\n");
-
-  /* Create synchronization objects */
-  pthread_mutex_init (&pQueue->pmMutex, NULL);
-
-  ErrorF ("InitQueue - pthread_mutex_init returned\n");
-  ErrorF ("InitQueue - Calling pthread_cond_init\n");
-
-  pthread_cond_init (&pQueue->pcNotEmpty, NULL);
-
-  ErrorF ("InitQueue - pthread_cond_init returned\n");
-
-  return TRUE;
-}
-
-
-/*
- * GetWindowName - Retrieve the title of an X Window
- */
-
-static void
-GetWindowName (Display *pDisplay, Window iWin, char **ppName)
-{
-  int			nResult, nNum;
-  char			**ppList;
-  XTextProperty		xtpName;
-  
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("GetWindowName\n");
-#endif
-
-  /* Intialize ppName to NULL */
-  *ppName = NULL;
-
-  /* Try to get --- */
-  nResult = XGetWMName (pDisplay, iWin, &xtpName);
-  if (!nResult || !xtpName.value || !xtpName.nitems)
-    {
-#if CYGMULTIWINDOW_DEBUG
-      ErrorF ("GetWindowName - XGetWMName failed.  No name.\n");
-#endif
-      return;
-    }
-  
-  /* */
-  if (xtpName.encoding == XA_STRING)
-    {
-      /* */
-      if (xtpName.value)
-	{
-	  int size = xtpName.nitems * (xtpName.format >> 3);
-	  *ppName = malloc(size + 1);
-	  strncpy(*ppName, xtpName.value, size);
-	  (*ppName)[size] = 0;
-	  XFree (xtpName.value);
-	}
-
-#if CYGMULTIWINDOW_DEBUG
-      ErrorF ("GetWindowName - XA_STRING %s\n", *ppName);
-#endif
-    }
-  else
-    {
-      if (XmbTextPropertyToTextList (pDisplay, &xtpName, &ppList, &nNum) >= Success && nNum > 0 && *ppList)
-	{
-	  *ppName = strdup (*ppList);
-	  XFreeStringList (ppList);
-	}
-      XFree (xtpName.value);
-
-#if CYGMULTIWINDOW_DEBUG
-      ErrorF ("GetWindowName - %s %s\n",
-	      XGetAtomName (pDisplay, xtpName.encoding), *ppName);
-#endif
-    }
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("GetWindowName - Returning\n");
-#endif
-}
-
-
-/*
- * Send a message to the X server from the WM thread
- */
-
-static int
-SendXMessage (Display *pDisplay, Window iWin, Atom atmType, long nData)
-{
-  XEvent		e;
-
-  /* Prepare the X event structure */
-  e.type = ClientMessage;
-  e.xclient.window = iWin;
-  e.xclient.message_type = atmType;
-  e.xclient.format = 32;
-  e.xclient.data.l[0] = nData;
-  e.xclient.data.l[1] = CurrentTime;
-
-  /* Send the event to X */
-  return XSendEvent (pDisplay, iWin, False, NoEventMask, &e);
-}
-
-
-/*
- * Updates the name of a HWND according to its X WM_NAME property
- */
-
-static void
-UpdateName (WMInfoPtr pWMInfo, Window iWindow)
-{
-  char			*pszName;
-  Atom			atmType;
-  int			fmtRet;
-  unsigned long		items, remain;
-  HWND			*retHwnd, hWnd;
-  XWindowAttributes	attr;
-
-  hWnd = 0;
-
-  /* See if we can get the cached HWND for this window... */
-  if (XGetWindowProperty (pWMInfo->pDisplay,
-			  iWindow,
-			  pWMInfo->atmPrivMap,
-			  0,
-			  1,
-			  False,
-			  XA_INTEGER,//pWMInfo->atmPrivMap,
-			  &atmType,
-			  &fmtRet,
-			  &items,
-			  &remain,
-			  (unsigned char **) &retHwnd) == Success)
-    {
-      if (retHwnd)
-	{
-	  hWnd = *retHwnd;
-	  XFree (retHwnd);
-	}
-    }
-  
-  /* Some sanity checks */
-  if (!hWnd) return;
-  if (!IsWindow (hWnd)) return;
-
-  /* Set the Windows window name */
-  GetWindowName (pWMInfo->pDisplay, iWindow, &pszName);
-  if (pszName)
-    {
-      /* Get the window attributes */
-      XGetWindowAttributes (pWMInfo->pDisplay,
-			    iWindow,
-			    &attr);
-      if (!attr.override_redirect)
-	{
-	  SetWindowText (hWnd, pszName);
-	  winUpdateIcon (iWindow);
-	}
-
-      free (pszName);
-    }
-}
-
-
-#if 0
-/*
- * Fix up any differences between the X11 and Win32 window stacks
- * starting at the window passed in
- */
-static void
-PreserveWin32Stack(WMInfoPtr pWMInfo, Window iWindow, UINT direction)
-{
-  Atom                  atmType;
-  int                   fmtRet;
-  unsigned long         items, remain;
-  HWND                  hWnd, *retHwnd;
-  DWORD                 myWinProcID, winProcID;
-  Window                xWindow;
-  WINDOWPLACEMENT       wndPlace;
-  
-  hWnd = NULL;
-  /* See if we can get the cached HWND for this window... */
-  if (XGetWindowProperty (pWMInfo->pDisplay,
-			  iWindow,
-			  pWMInfo->atmPrivMap,
-			  0,
-			  1,
-			  False,
-			  XA_INTEGER,//pWMInfo->atmPrivMap,
-			  &atmType,
-			  &fmtRet,
-			  &items,
-			  &remain,
-			  (unsigned char **) &retHwnd) == Success)
-    {
-      if (retHwnd)
-	{
-	  hWnd = *retHwnd;
-	  XFree (retHwnd);
-	}
-    }
-  
-  if (!hWnd) return;
-  
-  GetWindowThreadProcessId (hWnd, &myWinProcID);
-  hWnd = GetNextWindow (hWnd, direction);
-  
-  while (hWnd) {
-    GetWindowThreadProcessId (hWnd, &winProcID);
-    if (winProcID == myWinProcID)
-      {
-	wndPlace.length = sizeof(WINDOWPLACEMENT);
-	GetWindowPlacement (hWnd, &wndPlace);
-	if ( !(wndPlace.showCmd==SW_HIDE ||
-	       wndPlace.showCmd==SW_MINIMIZE) )
-	  {
-	    xWindow = (Window)GetProp (hWnd, WIN_WID_PROP);
-	    if (xWindow)
-	      {
-		if (direction==GW_HWNDPREV)
-		  XRaiseWindow (pWMInfo->pDisplay, xWindow);
-		else
-		  XLowerWindow (pWMInfo->pDisplay, xWindow);
-	      }
-	  }
-      }
-    hWnd = GetNextWindow(hWnd, direction);
-  }
-}
-#endif /* PreserveWin32Stack */
-
-
-/*
- * winMultiWindowWMProc
- */
-
-static void *
-winMultiWindowWMProc (void *pArg)
-{
-  WMProcArgPtr		pProcArg = (WMProcArgPtr)pArg;
-  WMInfoPtr		pWMInfo = pProcArg->pWMInfo;
-  
-  /* Initialize the Window Manager */
-  winInitMultiWindowWM (pWMInfo, pProcArg);
-  
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winMultiWindowWMProc ()\n");
-#endif
-
-  /* Loop until we explicity break out */
-  for (;;)
-    {
-      WMMsgNodePtr	pNode;
-
-      if(g_fAnotherWMRunnig)/* Another Window manager exists. */
-	{
-	  Sleep (1000);
-	  continue;
-	}
-
-      /* Pop a message off of our queue */
-      pNode = PopMessage (&pWMInfo->wmMsgQueue, pWMInfo);
-      if (pNode == NULL)
-	{
-	  /* Bail if PopMessage returns without a message */
-	  /* NOTE: Remember that PopMessage is a blocking function. */
-	  ErrorF ("winMultiWindowWMProc - Queue is Empty?  Exiting.\n");
-	  pthread_exit (NULL);
-	}
-
-#if CYGMULTIWINDOW_DEBUG
-      ErrorF ("winMultiWindowWMProc - %d ms MSG: %d ID: %d\n",
-	      GetTickCount (), (int)pNode->msg.msg, (int)pNode->msg.dwID);
-#endif
-
-      /* Branch on the message type */
-      switch (pNode->msg.msg)
-	{
-#if 0
-	case WM_WM_MOVE:
-	  ErrorF ("\tWM_WM_MOVE\n");
-	  break;
-
-	case WM_WM_SIZE:
-	  ErrorF ("\tWM_WM_SIZE\n");
-	  break;
-#endif
-
-	case WM_WM_RAISE:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_RAISE\n");
-#endif
-	  /* Raise the window */
-	  XRaiseWindow (pWMInfo->pDisplay, pNode->msg.iWindow);
-#if 0
-	  PreserveWin32Stack (pWMInfo, pNode->msg.iWindow, GW_HWNDPREV);
-#endif
-	  break;
-
-	case WM_WM_LOWER:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_LOWER\n");
-#endif
-
-	  /* Lower the window */
-	  XLowerWindow (pWMInfo->pDisplay, pNode->msg.iWindow);
-	  break;
-
-	case WM_WM_MAP:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_MAP\n");
-#endif
-	  /* Put a note as to the HWND associated with this Window */
-	  XChangeProperty (pWMInfo->pDisplay,
-			   pNode->msg.iWindow,
-			   pWMInfo->atmPrivMap,
-			   XA_INTEGER,//pWMInfo->atmPrivMap,
-			   32,
-			   PropModeReplace,
-			   (unsigned char *) &(pNode->msg.hwndWindow),
-			   1);
-	  UpdateName (pWMInfo, pNode->msg.iWindow);
-	  winUpdateIcon (pNode->msg.iWindow);
-#if 0
-	  /* Handles the case where there are AOT windows above it in W32 */
-	  PreserveWin32Stack (pWMInfo, pNode->msg.iWindow, GW_HWNDPREV);
-#endif
-	  break;
-
-	case WM_WM_UNMAP:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_UNMAP\n");
-#endif
-	  
-	  /* Unmap the window */
-	  XUnmapWindow (pWMInfo->pDisplay, pNode->msg.iWindow);
-	  break;
-
-	case WM_WM_KILL:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_KILL\n");
-#endif
-	  {
-	    int				i, n, found = 0;
-	    Atom			*protocols;
-	    
-	    /* --- */
-	    if (XGetWMProtocols (pWMInfo->pDisplay,
-				 pNode->msg.iWindow,
-				 &protocols,
-				 &n))
-	      {
-		for (i = 0; i < n; ++i)
-		  if (protocols[i] == pWMInfo->atmWmDelete)
-		    ++found;
-		
-		XFree (protocols);
-	      }
-
-	    /* --- */
-	    if (found)
-	      SendXMessage (pWMInfo->pDisplay,
-			    pNode->msg.iWindow,
-			    pWMInfo->atmWmProtos,
-			    pWMInfo->atmWmDelete);
-	    else
-	      XKillClient (pWMInfo->pDisplay,
-			   pNode->msg.iWindow);
-	  }
-	  break;
-
-	case WM_WM_ACTIVATE:
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("\tWM_WM_ACTIVATE\n");
-#endif
-	  
-	  /* Set the input focus */
-	  XSetInputFocus (pWMInfo->pDisplay,
-			  pNode->msg.iWindow,
-			  RevertToPointerRoot,
-			  CurrentTime);
-	  break;
-
-	case WM_WM_NAME_EVENT:
-	  UpdateName (pWMInfo, pNode->msg.iWindow);
-	  break;
-
-	case WM_WM_HINTS_EVENT:
-	  winUpdateIcon (pNode->msg.iWindow);
-	  break;
-
-	case WM_WM_CHANGE_STATE:
-	  /* Minimize the window in Windows */
-	  winMinimizeWindow (pNode->msg.iWindow);
-	  break;
-
-	default:
-	  ErrorF ("winMultiWindowWMProc - Unknown Message.  Exiting.\n");
-	  pthread_exit (NULL);
-	  break;
-	}
-
-      /* Free the retrieved message */
-      free (pNode);
-
-      /* Flush any pending events on our display */
-      XFlush (pWMInfo->pDisplay);
-    }
-
-  /* Free the condition variable */
-  pthread_cond_destroy (&pWMInfo->wmMsgQueue.pcNotEmpty);
-  
-  /* Free the mutex variable */
-  pthread_mutex_destroy (&pWMInfo->wmMsgQueue.pmMutex);
-  
-  /* Free the passed-in argument */
-  free (pProcArg);
-  
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF("-winMultiWindowWMProc ()\n");
-#endif
-}
-
-
-/*
- * X message procedure
- */
-
-static void *
-winMultiWindowXMsgProc (void *pArg)
-{
-  winWMMessageRec       msg;
-  XMsgProcArgPtr	pProcArg = (XMsgProcArgPtr) pArg;
-  char			pszDisplay[512];
-  int                   iRetries;
-  XEvent		event;
-  Atom                  atmWmName;
-  Atom                  atmWmHints;
-  Atom			atmWmChange;
-  int			iReturn;
-  XIconSize		*xis;
-
-  ErrorF ("winMultiWindowXMsgProc - Hello\n");
-
-  /* Check that argument pointer is not invalid */
-  if (pProcArg == NULL)
-    {
-      ErrorF ("winMultiWindowXMsgProc - pProcArg is NULL.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  ErrorF ("winMultiWindowXMsgProc - Calling pthread_mutex_lock ()\n");
-
-  /* Grab the server started mutex - pause until we get it */
-  iReturn = pthread_mutex_lock (pProcArg->ppmServerStarted);
-  if (iReturn != 0)
-    {
-      ErrorF ("winMultiWindowXMsgProc - pthread_mutex_lock () failed: %d.  "
-	      "Exiting.\n",
-	      iReturn);
-      pthread_exit (NULL);
-    }
-
-  ErrorF ("winMultiWindowXMsgProc - pthread_mutex_lock () returned.\n");
-
-  /* Allow multiple threads to access Xlib */
-  if (XInitThreads () == 0)
-    {
-      ErrorF ("winMultiWindowXMsgProc - XInitThreads () failed.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  /* See if X supports the current locale */
-  if (XSupportsLocale () == False)
-    {
-      ErrorF ("winMultiWindowXMsgProc - Locale not supported by X.  "
-	      "Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  /* Release the server started mutex */
-  pthread_mutex_unlock (pProcArg->ppmServerStarted);
-
-  ErrorF ("winMultiWindowXMsgProc - pthread_mutex_unlock () returned.\n");
-
-  /* Set jump point for IO Error exits */
-  iReturn = setjmp (g_jmpXMsgProcEntry);
-  
-  /* Check if we should continue operations */
-  if (iReturn != WIN_JMP_ERROR_IO
-      && iReturn != WIN_JMP_OKAY)
-    {
-      /* setjmp returned an unknown value, exit */
-      ErrorF ("winInitMultiWindowXMsgProc - setjmp returned: %d.  Exiting.\n",
-	      iReturn);
-      pthread_exit (NULL);
-    }
-  else if (iReturn == WIN_JMP_ERROR_IO)
-    {
-      ErrorF ("winInitMultiWindowXMsgProc - Caught IO Error.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  /* Install our error handler */
-  XSetErrorHandler (winMultiWindowXMsgProcErrorHandler);
-  XSetIOErrorHandler (winMultiWindowXMsgProcIOErrorHandler);
-
-  /* Setup the display connection string x */
-  snprintf (pszDisplay,
-	    512, "127.0.0.1:%s.%d", display, (int)pProcArg->dwScreen);
-
-  /* Print the display connection string */
-  ErrorF ("winMultiWindowXMsgProc - DISPLAY=%s\n", pszDisplay);
-  
-  /* Initialize retry count */
-  iRetries = 0;
-
-  /* Open the X display */
-  do
-    {
-      /* Try to open the display */
-      pProcArg->pDisplay = XOpenDisplay (pszDisplay);
-      if (pProcArg->pDisplay == NULL)
-	{
-	  ErrorF ("winMultiWindowXMsgProc - Could not open display, try: %d, "
-		  "sleeping: %d\n\f",
-		  iRetries + 1, WIN_CONNECT_DELAY);
-	  ++iRetries;
-	  sleep (WIN_CONNECT_DELAY);
-	  continue;
-	}
-      else
-	break;
-    }
-  while (pProcArg->pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
-  
-  /* Make sure that the display opened */
-  if (pProcArg->pDisplay == NULL)
-    {
-      ErrorF ("winMultiWindowXMsgProc - Failed opening the display.  "
-	      "Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  ErrorF ("winMultiWindowXMsgProc - XOpenDisplay () returned and "
-	  "successfully opened the display.\n");
-
-  /* Check if another window manager is already running */
-  if (pProcArg->pWMInfo->fAllowOtherWM)
-  {
-    g_fAnotherWMRunnig = CheckAnotherWindowManager (pProcArg->pDisplay, pProcArg->dwScreen);
-  } else {
-    redirectError = FALSE;
-    XSetErrorHandler (winRedirectErrorHandler); 	 
-    XSelectInput(pProcArg->pDisplay, 	 
-        RootWindow (pProcArg->pDisplay, pProcArg->dwScreen), 	 
-        SubstructureNotifyMask | ButtonPressMask); 	 
-    XSync (pProcArg->pDisplay, 0); 	 
-    XSetErrorHandler (winMultiWindowXMsgProcErrorHandler); 	 
-    if (redirectError) 	 
-    { 	 
-      ErrorF ("winMultiWindowXMsgProc - " 	 
-          "another window manager is running.  Exiting.\n"); 	 
-      pthread_exit (NULL); 	 
-    }
-    g_fAnotherWMRunnig = FALSE;
-  }
-  
-  /* Set up the supported icon sizes */
-  xis = XAllocIconSize ();
-  if (xis)
-    {
-      xis->min_width = xis->min_height = 16;
-      xis->max_width = xis->max_height = 48;
-      xis->width_inc = xis->height_inc = 16;
-      XSetIconSizes (pProcArg->pDisplay,
-		     RootWindow (pProcArg->pDisplay, pProcArg->dwScreen),
-		     xis,
-		     1);
-      XFree (xis);
-    }
-
-  atmWmName   = XInternAtom (pProcArg->pDisplay,
-			     "WM_NAME",
-			     False);
-  atmWmHints   = XInternAtom (pProcArg->pDisplay,
-			      "WM_HINTS",
-			      False);
-  atmWmChange  = XInternAtom (pProcArg->pDisplay,
-			      "WM_CHANGE_STATE",
-			      False);
-
-  /* Loop until we explicitly break out */
-  while (1)
-    {
-      if (g_shutdown)
-        break;
-
-      if (pProcArg->pWMInfo->fAllowOtherWM && !XPending (pProcArg->pDisplay))
-	{
-	  if (CheckAnotherWindowManager (pProcArg->pDisplay, pProcArg->dwScreen))
-	    {
-	      if (!g_fAnotherWMRunnig)
-		{
-		  g_fAnotherWMRunnig = TRUE;
-		  SendMessage(*(HWND*)pProcArg->hwndScreen, WM_UNMANAGE, 0, 0);
-		}
-	    }
-	  else
-	    {
-	      if (g_fAnotherWMRunnig)
-		{
-		  g_fAnotherWMRunnig = FALSE;
-		  SendMessage(*(HWND*)pProcArg->hwndScreen, WM_MANAGE, 0, 0);
-		}
-	    }
-	  Sleep (500);
-	  continue;
-	}
-
-      /* Fetch next event */
-      XNextEvent (pProcArg->pDisplay, &event);
-
-      /* Branch on event type */
-      if (event.type == CreateNotify)
-	{
-	  XWindowAttributes	attr;
-
-	  XSelectInput (pProcArg->pDisplay,
-			event.xcreatewindow.window,
-			PropertyChangeMask);
-
-	  /* Get the window attributes */
-	  XGetWindowAttributes (pProcArg->pDisplay,
-				event.xcreatewindow.window,
-				&attr);
-
-	  if (!attr.override_redirect)
-	    XSetWindowBorderWidth(pProcArg->pDisplay,
-				  event.xcreatewindow.window,
-				  0);
-	}
-      else if (event.type == PropertyNotify
-	       && event.xproperty.atom == atmWmName)
-	{
-	  memset (&msg, 0, sizeof (msg));
-
-	  msg.msg = WM_WM_NAME_EVENT;
-	  msg.iWindow = event.xproperty.window;
-
-	  /* Other fields ignored */
-	  winSendMessageToWM (pProcArg->pWMInfo, &msg);
-	}
-      else if (event.type == PropertyNotify
-	       && event.xproperty.atom == atmWmHints)
-	{
-	  memset (&msg, 0, sizeof (msg));
-
-	  msg.msg = WM_WM_HINTS_EVENT;
-	  msg.iWindow = event.xproperty.window;
-
-	  /* Other fields ignored */
-	  winSendMessageToWM (pProcArg->pWMInfo, &msg);
-	}
-      else if (event.type == ClientMessage
-	       && event.xclient.message_type == atmWmChange
-	       && event.xclient.data.l[0] == IconicState)
-	{
-	  ErrorF ("winMultiWindowXMsgProc - WM_CHANGE_STATE - IconicState\n");
-
-	  memset (&msg, 0, sizeof (msg));
-
-	  msg.msg = WM_WM_CHANGE_STATE;
-	  msg.iWindow = event.xclient.window;
-
-	  winSendMessageToWM (pProcArg->pWMInfo, &msg);
-	}
-    }
-
-  XCloseDisplay (pProcArg->pDisplay);
-  pthread_exit (NULL);
- 
-}
-
-
-/*
- * winInitWM - Entry point for the X server to spawn
- * the Window Manager thread.  Called from
- * winscrinit.c/winFinishScreenInitFB ().
- */
-
-Bool
-winInitWM (void **ppWMInfo,
-	   pthread_t *ptWMProc,
-	   pthread_t *ptXMsgProc,
-	   pthread_mutex_t *ppmServerStarted,
-	   int dwScreen,
-	   HWND hwndScreen,
-	   BOOL allowOtherWM)
-{
-  WMProcArgPtr		pArg = (WMProcArgPtr) malloc (sizeof(WMProcArgRec));
-  WMInfoPtr		pWMInfo = (WMInfoPtr) malloc (sizeof(WMInfoRec));
-  XMsgProcArgPtr	pXMsgArg = (XMsgProcArgPtr) malloc (sizeof(XMsgProcArgRec));
-
-  /* Bail if the input parameters are bad */
-  if (pArg == NULL || pWMInfo == NULL)
-    {
-      ErrorF ("winInitWM - malloc failed.\n");
-      return FALSE;
-    }
-  
-  /* Zero the allocated memory */
-  ZeroMemory (pArg, sizeof (WMProcArgRec));
-  ZeroMemory (pWMInfo, sizeof (WMInfoRec));
-  ZeroMemory (pXMsgArg, sizeof (XMsgProcArgRec));
-
-  /* Set a return pointer to the Window Manager info structure */
-  *ppWMInfo = pWMInfo;
-  pWMInfo->fAllowOtherWM = allowOtherWM;
-
-  /* Setup the argument structure for the thread function */
-  pArg->dwScreen = dwScreen;
-  pArg->pWMInfo = pWMInfo;
-  pArg->ppmServerStarted = ppmServerStarted;
-  
-  /* Intialize the message queue */
-  if (!InitQueue (&pWMInfo->wmMsgQueue))
-    {
-      ErrorF ("winInitWM - InitQueue () failed.\n");
-      return FALSE;
-    }
-  
-  /* Spawn a thread for the Window Manager */
-  if (pthread_create (ptWMProc, NULL, winMultiWindowWMProc, pArg))
-    {
-      /* Bail if thread creation failed */
-      ErrorF ("winInitWM - pthread_create failed for Window Manager.\n");
-      return FALSE;
-    }
-
-  /* Spawn the XNextEvent thread, will send messages to WM */
-  pXMsgArg->dwScreen = dwScreen;
-  pXMsgArg->pWMInfo = pWMInfo;
-  pXMsgArg->ppmServerStarted = ppmServerStarted;
-  pXMsgArg->hwndScreen = hwndScreen;
-  if (pthread_create (ptXMsgProc, NULL, winMultiWindowXMsgProc, pXMsgArg))
-    {
-      /* Bail if thread creation failed */
-      ErrorF ("winInitWM - pthread_create failed on XMSG.\n");
-      return FALSE;
-    }
-
-#if CYGDEBUG || YES
-  winDebug ("winInitWM - Returning.\n");
-#endif
-
-  return TRUE;
-}
-
-
-/*
- * Window manager thread - setup
- */
-
-static void
-winInitMultiWindowWM (WMInfoPtr pWMInfo, WMProcArgPtr pProcArg)
-{
-  int                   iRetries = 0;
-  char			pszDisplay[512];
-  int			iReturn;
-
-  ErrorF ("winInitMultiWindowWM - Hello\n");
-
-  /* Check that argument pointer is not invalid */
-  if (pProcArg == NULL)
-    {
-      ErrorF ("winInitMultiWindowWM - pProcArg is NULL.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  ErrorF ("winInitMultiWindowWM - Calling pthread_mutex_lock ()\n");
-
-  /* Grab our garbage mutex to satisfy pthread_cond_wait */
-  iReturn = pthread_mutex_lock (pProcArg->ppmServerStarted);
-  if (iReturn != 0)
-    {
-      ErrorF ("winInitMultiWindowWM - pthread_mutex_lock () failed: %d.  "
-	      "Exiting.\n",
-	      iReturn);
-      pthread_exit (NULL);
-    }
-
-  ErrorF ("winInitMultiWindowWM - pthread_mutex_lock () returned.\n");
-
-  /* Allow multiple threads to access Xlib */
-  if (XInitThreads () == 0)
-    {
-      ErrorF ("winInitMultiWindowWM - XInitThreads () failed.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  /* See if X supports the current locale */
-  if (XSupportsLocale () == False)
-    {
-      ErrorF ("winInitMultiWindowWM - Locale not supported by X.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  /* Release the server started mutex */
-  pthread_mutex_unlock (pProcArg->ppmServerStarted);
-
-  ErrorF ("winInitMultiWindowWM - pthread_mutex_unlock () returned.\n");
-
-  /* Set jump point for IO Error exits */
-  iReturn = setjmp (g_jmpWMEntry);
-  
-  /* Check if we should continue operations */
-  if (iReturn != WIN_JMP_ERROR_IO
-      && iReturn != WIN_JMP_OKAY)
-    {
-      /* setjmp returned an unknown value, exit */
-      ErrorF ("winInitMultiWindowWM - setjmp returned: %d.  Exiting.\n",
-	      iReturn);
-      pthread_exit (NULL);
-    }
-  else if (iReturn == WIN_JMP_ERROR_IO)
-    {
-      ErrorF ("winInitMultiWindowWM - Caught IO Error.  Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  /* Install our error handler */
-  XSetErrorHandler (winMultiWindowWMErrorHandler);
-  XSetIOErrorHandler (winMultiWindowWMIOErrorHandler);
-
-  /* Setup the display connection string x */
-  snprintf (pszDisplay,
-	    512,
-	    "127.0.0.1:%s.%d",
-	    display,
-	    (int) pProcArg->dwScreen);
-
-  /* Print the display connection string */
-  ErrorF ("winInitMultiWindowWM - DISPLAY=%s\n", pszDisplay);
-  
-  /* Open the X display */
-  do
-    {
-      /* Try to open the display */
-      pWMInfo->pDisplay = XOpenDisplay (pszDisplay);
-      if (pWMInfo->pDisplay == NULL)
-	{
-	  ErrorF ("winInitMultiWindowWM - Could not open display, try: %d, "
-		  "sleeping: %d\n\f",
-		  iRetries + 1, WIN_CONNECT_DELAY);
-	  ++iRetries;
-	  sleep (WIN_CONNECT_DELAY);
-	  continue;
-	}
-      else
-	break;
-    }
-  while (pWMInfo->pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
-  
-  /* Make sure that the display opened */
-  if (pWMInfo->pDisplay == NULL)
-    {
-      ErrorF ("winInitMultiWindowWM - Failed opening the display.  "
-	      "Exiting.\n");
-      pthread_exit (NULL);
-    }
-
-  ErrorF ("winInitMultiWindowWM - XOpenDisplay () returned and "
-	  "successfully opened the display.\n");
-  
-
-  /* Create some atoms */
-  pWMInfo->atmWmProtos = XInternAtom (pWMInfo->pDisplay,
-				      "WM_PROTOCOLS",
-				      False);
-  pWMInfo->atmWmDelete = XInternAtom (pWMInfo->pDisplay,
-				      "WM_DELETE_WINDOW",
-				      False);
-#ifdef XWIN_MULTIWINDOWEXTWM
-  pWMInfo->atmPrivMap  = XInternAtom (pWMInfo->pDisplay,
-				      WINDOWSWM_NATIVE_HWND,
-				      False);
-#endif
-
-
-  if (1) {
-    Cursor cursor = XCreateFontCursor (pWMInfo->pDisplay, XC_left_ptr);
-    if (cursor)
-    {
-      XDefineCursor (pWMInfo->pDisplay, DefaultRootWindow(pWMInfo->pDisplay), cursor);
-      XFreeCursor (pWMInfo->pDisplay, cursor);
-    }
-  }
-}
-
-
-/*
- * winSendMessageToWM - Send a message from the X thread to the WM thread
- */
-
-void
-winSendMessageToWM (void *pWMInfo, winWMMessagePtr pMsg)
-{
-  WMMsgNodePtr pNode;
-  
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winSendMessageToWM ()\n");
-#endif
-  
-  pNode = (WMMsgNodePtr)malloc(sizeof(WMMsgNodeRec));
-  if (pNode != NULL)
-    {
-      memcpy (&pNode->msg, pMsg, sizeof(winWMMessageRec));
-      PushMessage (&((WMInfoPtr)pWMInfo)->wmMsgQueue, pNode);
-    }
-}
-
-
-/*
- * Window manager error handler
- */
-
-static int
-winMultiWindowWMErrorHandler (Display *pDisplay, XErrorEvent *pErr)
-{
-  char pszErrorMsg[100];
-
-  if (pErr->request_code == X_ChangeWindowAttributes
-      && pErr->error_code == BadAccess)
-    {
-      ErrorF ("winMultiWindowWMErrorHandler - ChangeWindowAttributes "
-	      "BadAccess.\n");
-      return 0;
-    }
-  
-  XGetErrorText (pDisplay,
-		 pErr->error_code,
-		 pszErrorMsg,
-		 sizeof (pszErrorMsg));
-  ErrorF ("winMultiWindowWMErrorHandler - ERROR: %s\n", pszErrorMsg);
-
-  return 0;
-}
-
-
-/*
- * Window manager IO error handler
- */
-
-static int
-winMultiWindowWMIOErrorHandler (Display *pDisplay)
-{
-  ErrorF ("\nwinMultiWindowWMIOErrorHandler!\n\n");
-
-  if (g_shutdown)
-    pthread_exit(NULL);
-
-  /* Restart at the main entry point */
-  longjmp (g_jmpWMEntry, WIN_JMP_ERROR_IO);
-  
-  return 0;
-}
-
-
-/*
- * X message procedure error handler
- */
-
-static int
-winMultiWindowXMsgProcErrorHandler (Display *pDisplay, XErrorEvent *pErr)
-{
-  char pszErrorMsg[100];
-  
-  XGetErrorText (pDisplay,
-		 pErr->error_code,
-		 pszErrorMsg,
-		 sizeof (pszErrorMsg));
-  ErrorF ("winMultiWindowXMsgProcErrorHandler - ERROR: %s\n", pszErrorMsg);
-  
-  return 0;
-}
-
-
-/*
- * X message procedure IO error handler
- */
-
-static int
-winMultiWindowXMsgProcIOErrorHandler (Display *pDisplay)
-{
-  ErrorF ("\nwinMultiWindowXMsgProcIOErrorHandler!\n\n");
-
-  /* Restart at the main entry point */
-  longjmp (g_jmpXMsgProcEntry, WIN_JMP_ERROR_IO);
-  
-  return 0;
-}
-
-
-/*
- * Catch RedirectError to detect other window manager running
- */
-
-static int
-winRedirectErrorHandler (Display *pDisplay, XErrorEvent *pErr)
-{
-  redirectError = TRUE;
-  return 0;
-}
-
-
-/*
- * Check if another window manager is running
- */
-
-static Bool
-CheckAnotherWindowManager (Display *pDisplay, DWORD dwScreen)
-{
-  redirectError = FALSE;
-  XSetErrorHandler (winRedirectErrorHandler);
-  XSelectInput(pDisplay, RootWindow (pDisplay, dwScreen),
-	       // SubstructureNotifyMask | ButtonPressMask
-	       ColormapChangeMask | EnterWindowMask | PropertyChangeMask |
-	       SubstructureRedirectMask | KeyPressMask |
-	       ButtonPressMask | ButtonReleaseMask);
-  XSync (pDisplay, 0);
-  XSetErrorHandler (winMultiWindowXMsgProcErrorHandler);
-  XSelectInput(pDisplay, RootWindow (pDisplay, dwScreen),
-	       SubstructureNotifyMask);
-  XSync (pDisplay, 0);
-  if (redirectError)
-    {
-      //ErrorF ("CheckAnotherWindowManager() - another window manager is running.  Exiting.\n");
-      return TRUE;
-    }
-  else
-    {
-      return FALSE;
-    }
-}
-
-/*
- * Notify the MWM thread we're exiting and not to reconnect
- */
-
-void
-winDeinitMultiWindowWM ()
-{
-  ErrorF ("winDeinitMultiWindowWM - Noting shutdown in progress\n");
-  g_shutdown = TRUE;
-}
diff --git a/hw/xwin/winmultiwindowwndproc.c b/hw/xwin/winmultiwindowwndproc.c
deleted file mode 100644
index 20ff9f7..0000000
--- a/hw/xwin/winmultiwindowwndproc.c
+++ /dev/null
@@ -1,1049 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Kensuke Matsuzaki
- *		Earle F. Philhower, III
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "dixevents.h"
-#include "winmultiwindowclass.h"
-#include "winprefs.h"
-#include "winmsg.h"
-#include "inputstr.h"
-
-/*
- * External global variables
- */
-
-extern Bool			g_fCursor;
-extern Bool			g_fKeyboardHookLL;
-extern Bool			g_fSoftwareCursor;
-extern Bool			g_fButton[3];
-
-
-/*
- * Local globals
- */
-
-static UINT_PTR		g_uipMousePollingTimerID = 0;
-
-
-/*
- * Constant defines
- */
-
-#define MOUSE_POLLING_INTERVAL		500
-#define WIN_MULTIWINDOW_SHAPE		YES
-
-
-/*
- * ConstrainSize - Taken from TWM sources - Respects hints for sizing
- */
-#define makemult(a,b) ((b==1) ? (a) : (((int)((a)/(b))) * (b)) )
-static void
-ConstrainSize (WinXSizeHints hints, int *widthp, int *heightp)
-{
-  int minWidth, minHeight, maxWidth, maxHeight, xinc, yinc, delta;
-  int baseWidth, baseHeight;
-  int dwidth = *widthp, dheight = *heightp;
-  
-  if (hints.flags & PMinSize)
-    {
-      minWidth = hints.min_width;
-      minHeight = hints.min_height;
-    }
-  else if (hints.flags & PBaseSize)
-    {
-      minWidth = hints.base_width;
-      minHeight = hints.base_height;
-    }
-  else
-    minWidth = minHeight = 1;
-  
-  if (hints.flags & PBaseSize)
-    {
-      baseWidth = hints.base_width;
-      baseHeight = hints.base_height;
-    } 
-  else if (hints.flags & PMinSize)
-    {
-      baseWidth = hints.min_width;
-      baseHeight = hints.min_height;
-    }
-  else
-    baseWidth = baseHeight = 0;
-
-  if (hints.flags & PMaxSize)
-    {
-      maxWidth = hints.max_width;
-      maxHeight = hints.max_height;
-    }
-  else
-    {
-      maxWidth = MAXINT;
-      maxHeight = MAXINT;
-    }
-
-  if (hints.flags & PResizeInc)
-    {
-      xinc = hints.width_inc;
-      yinc = hints.height_inc;
-    }
-  else
-    xinc = yinc = 1;
-
-  /*
-   * First, clamp to min and max values
-   */
-  if (dwidth < minWidth)
-    dwidth = minWidth;
-  if (dheight < minHeight)
-    dheight = minHeight;
-
-  if (dwidth > maxWidth)
-    dwidth = maxWidth;
-  if (dheight > maxHeight)
-    dheight = maxHeight;
-
-  /*
-   * Second, fit to base + N * inc
-   */
-  dwidth = ((dwidth - baseWidth) / xinc * xinc) + baseWidth;
-  dheight = ((dheight - baseHeight) / yinc * yinc) + baseHeight;
-  
-  /*
-   * Third, adjust for aspect ratio
-   */
-
-  /*
-   * The math looks like this:
-   *
-   * minAspectX    dwidth     maxAspectX
-   * ---------- <= ------- <= ----------
-   * minAspectY    dheight    maxAspectY
-   *
-   * If that is multiplied out, then the width and height are
-   * invalid in the following situations:
-   *
-   * minAspectX * dheight > minAspectY * dwidth
-   * maxAspectX * dheight < maxAspectY * dwidth
-   * 
-   */
-  
-  if (hints.flags & PAspect)
-    {
-      if (hints.min_aspect.x * dheight > hints.min_aspect.y * dwidth)
-        {
-	  delta = makemult(hints.min_aspect.x * dheight / hints.min_aspect.y - dwidth, xinc);
-	  if (dwidth + delta <= maxWidth)
-	    dwidth += delta;
-	  else
-            {
-	      delta = makemult(dheight - dwidth*hints.min_aspect.y/hints.min_aspect.x, yinc);
-	      if (dheight - delta >= minHeight)
-		dheight -= delta;
-            }
-        }
-      
-      if (hints.max_aspect.x * dheight < hints.max_aspect.y * dwidth)
-        {
-	  delta = makemult(dwidth * hints.max_aspect.y / hints.max_aspect.x - dheight, yinc);
-	  if (dheight + delta <= maxHeight)
-	    dheight += delta;
-	  else
-            {
-	      delta = makemult(dwidth - hints.max_aspect.x*dheight/hints.max_aspect.y, xinc);
-	      if (dwidth - delta >= minWidth)
-		dwidth -= delta;
-            }
-        }
-    }
-  
-  /* Return computed values */
-  *widthp = dwidth;
-  *heightp = dheight;
-}
-#undef makemult
-
-
-
-/*
- * ValidateSizing - Ensures size request respects hints
- */
-static int
-ValidateSizing (HWND hwnd, WindowPtr pWin,
-		WPARAM wParam, LPARAM lParam)
-{
-  WinXSizeHints sizeHints;
-  RECT *rect;
-  int iWidth, iHeight;
-
-  /* Invalid input checking */
-  if (pWin==NULL || lParam==0)
-    return FALSE;
-
-  /* No size hints, no checking */
-  if (!winMultiWindowGetWMNormalHints (pWin, &sizeHints))
-    return FALSE;
-  
-  /* Avoid divide-by-zero */
-  if (sizeHints.flags & PResizeInc)
-    {
-      if (sizeHints.width_inc == 0) sizeHints.width_inc = 1;
-      if (sizeHints.height_inc == 0) sizeHints.height_inc = 1;
-    }
-  
-  rect = (RECT*)lParam;
-  
-  iWidth = rect->right - rect->left;
-  iHeight = rect->bottom - rect->top;
-
-  /* Now remove size of any borders */
-  iWidth -= 2 * GetSystemMetrics(SM_CXSIZEFRAME);
-  iHeight -= (GetSystemMetrics(SM_CYCAPTION)
-	      + 2 * GetSystemMetrics(SM_CYSIZEFRAME));
-	      
-
-  /* Constrain the size to legal values */
-  ConstrainSize (sizeHints, &iWidth, &iHeight);
-
-  /* Add back the borders */
-  iWidth += 2 * GetSystemMetrics(SM_CXSIZEFRAME);
-  iHeight += (GetSystemMetrics(SM_CYCAPTION)
-	      + 2 * GetSystemMetrics(SM_CYSIZEFRAME));
-
-  /* Adjust size according to where we're dragging from */
-  switch(wParam) {
-  case WMSZ_TOP:
-  case WMSZ_TOPRIGHT:
-  case WMSZ_BOTTOM:
-  case WMSZ_BOTTOMRIGHT:
-  case WMSZ_RIGHT:
-    rect->right = rect->left + iWidth;
-    break;
-  default:
-    rect->left = rect->right - iWidth;
-    break;
-  }
-  switch(wParam) {
-  case WMSZ_BOTTOM:
-  case WMSZ_BOTTOMRIGHT:
-  case WMSZ_BOTTOMLEFT:
-  case WMSZ_RIGHT:
-  case WMSZ_LEFT:
-    rect->bottom = rect->top + iHeight;
-    break;
-  default:
-    rect->top = rect->bottom - iHeight;
-    break;
-  }
-  return TRUE;
-}
-
-extern Bool winInDestroyWindowsWindow;
-static Bool winInRaiseWindow = FALSE;
-static void winRaiseWindow(WindowPtr pWin)
-{
-  if (!winInDestroyWindowsWindow && !winInRaiseWindow)
-  {
-    BOOL oldstate = winInRaiseWindow;
-    winInRaiseWindow = TRUE;
-    /* Call configure window directly to make sure it gets processed 
-     * in time
-     */
-    XID vlist[1] = { 0 };
-    ConfigureWindow(pWin, CWStackMode, vlist, serverClient); 
-    winInRaiseWindow = oldstate;
-  }
-}
-
-
-/*
- * winTopLevelWindowProc - Window procedure for all top-level Windows windows.
- */
-
-LRESULT CALLBACK
-winTopLevelWindowProc (HWND hwnd, UINT message, 
-		       WPARAM wParam, LPARAM lParam)
-{
-  POINT			ptMouse;
-  HDC			hdcUpdate;
-  PAINTSTRUCT		ps;
-  WindowPtr		pWin = NULL;
-  winPrivWinPtr	        pWinPriv = NULL;
-  ScreenPtr		s_pScreen = NULL;
-  winPrivScreenPtr	s_pScreenPriv = NULL;
-  winScreenInfo		*s_pScreenInfo = NULL;
-  HWND			hwndScreen = NULL;
-  DrawablePtr		pDraw = NULL;
-  winWMMessageRec	wmMsg;
-  Bool                  fWMMsgInitialized = FALSE;
-  static Bool		s_fTracking = FALSE;
-  Bool			needRestack = FALSE;
-  LRESULT		ret;
-
-#if CYGDEBUG
-  winDebugWin32Message("winTopLevelWindowProc", hwnd, message, wParam, lParam);
-#endif
-  
-  /* Check if the Windows window property for our X window pointer is valid */
-  if ((pWin = GetProp (hwnd, WIN_WINDOW_PROP)) != NULL)
-    {
-      /* Our X window pointer is valid */
-
-      /* Get pointers to the drawable and the screen */
-      pDraw		= &pWin->drawable;
-      s_pScreen		= pWin->drawable.pScreen;
-
-      /* Get a pointer to our window privates */
-      pWinPriv		= winGetWindowPriv(pWin);
-
-      /* Get pointers to our screen privates and screen info */
-      s_pScreenPriv	= pWinPriv->pScreenPriv;
-      s_pScreenInfo	= s_pScreenPriv->pScreenInfo;
-
-      /* Get the handle for our screen-sized window */
-      hwndScreen	= s_pScreenPriv->hwndScreen;
-
-      /* */
-      wmMsg.msg		= 0;
-      wmMsg.hwndWindow	= hwnd;
-      wmMsg.iWindow	= (Window)GetProp (hwnd, WIN_WID_PROP);
-
-      wmMsg.iX		= pDraw->x;
-      wmMsg.iY		= pDraw->y;
-      wmMsg.iWidth	= pDraw->width;
-      wmMsg.iHeight	= pDraw->height;
-
-      fWMMsgInitialized = TRUE;
-
-#if 0
-      /*
-       * Print some debugging information
-       */
-
-      ErrorF ("hWnd %08X\n", hwnd);
-      ErrorF ("pWin %08X\n", pWin);
-      ErrorF ("pDraw %08X\n", pDraw);
-      ErrorF ("\ttype %08X\n", pWin->drawable.type);
-      ErrorF ("\tclass %08X\n", pWin->drawable.class);
-      ErrorF ("\tdepth %08X\n", pWin->drawable.depth);
-      ErrorF ("\tbitsPerPixel %08X\n", pWin->drawable.bitsPerPixel);
-      ErrorF ("\tid %08X\n", pWin->drawable.id);
-      ErrorF ("\tx %08X\n", pWin->drawable.x);
-      ErrorF ("\ty %08X\n", pWin->drawable.y);
-      ErrorF ("\twidth %08X\n", pWin->drawable.width);
-      ErrorF ("\thenght %08X\n", pWin->drawable.height);
-      ErrorF ("\tpScreen %08X\n", pWin->drawable.pScreen);
-      ErrorF ("\tserialNumber %08X\n", pWin->drawable.serialNumber);
-      ErrorF ("g_iWindowPrivateKey %p\n", g_iWindowPrivateKey);
-      ErrorF ("pWinPriv %08X\n", pWinPriv);
-      ErrorF ("s_pScreenPriv %08X\n", s_pScreenPriv);
-      ErrorF ("s_pScreenInfo %08X\n", s_pScreenInfo);
-      ErrorF ("hwndScreen %08X\n", hwndScreen);
-#endif
-    }
-
-  /* Branch on message type */
-  switch (message)
-    {
-    case WM_CREATE:
-
-      /* */
-      SetProp (hwnd,
-	       WIN_WINDOW_PROP,
-	       (HANDLE)((LPCREATESTRUCT) lParam)->lpCreateParams);
-      
-      /* */
-      SetProp (hwnd,
-	       WIN_WID_PROP,
-	       (HANDLE)winGetWindowID (((LPCREATESTRUCT) lParam)->lpCreateParams));
-
-      /*
-       * Make X windows' Z orders sync with Windows windows because
-       * there can be AlwaysOnTop windows overlapped on the window
-       * currently being created.
-       */
-      winReorderWindowsMultiWindow ();
-
-      /* Fix a 'round title bar corner background should be transparent not black' problem when first painted */
-      RECT rWindow;
-      HRGN hRgnWindow;
-      GetWindowRect(hwnd, &rWindow);
-      hRgnWindow = CreateRectRgnIndirect(&rWindow);
-      SetWindowRgn (hwnd, hRgnWindow, TRUE);
-      DeleteObject(hRgnWindow);
-
-      return 0;
-
-    case WM_INIT_SYS_MENU:
-      /*
-       * Add whatever the setup file wants to for this window
-       */
-      SetupSysMenu ((unsigned long)hwnd);
-      return 0;
-
-    case WM_SYSCOMMAND:
-      /*
-       * Any window menu items go through here
-       */
-      if (HandleCustomWM_COMMAND ((unsigned long)hwnd, LOWORD(wParam)))
-      {
-        /* Don't pass customized menus to DefWindowProc */
-        return 0;
-      }
-      if (wParam == SC_RESTORE || wParam == SC_MAXIMIZE)
-      {
-        WINDOWPLACEMENT wndpl;
-	wndpl.length = sizeof(wndpl);
-	if (GetWindowPlacement(hwnd, &wndpl) && wndpl.showCmd == SW_SHOWMINIMIZED)
-          needRestack = TRUE;
-      }
-      break;
-
-    case WM_INITMENU:
-      /* Checks/Unchecks any menu items before they are displayed */
-      HandleCustomWM_INITMENU ((unsigned long)hwnd, wParam);
-      break;
-
-    case WM_PAINT:
-      /* Only paint if our window handle is valid */
-      if (hwndScreen == NULL)
-	break;
-
-      /* BeginPaint gives us an hdc that clips to the invalidated region */
-      hdcUpdate = BeginPaint (hwnd, &ps);
-      /* Avoid the BitBlt's if the PAINTSTRUCT is bogus */
-      if (ps.rcPaint.right==0 && ps.rcPaint.bottom==0 && ps.rcPaint.left==0 && ps.rcPaint.top==0)
-      {
-	EndPaint (hwnd, &ps);
-	return 0;
-      }
-
-      /* Try to copy from the shadow buffer */
-      if (!BitBlt (hdcUpdate,
-		   ps.rcPaint.left, ps.rcPaint.top,
-		   ps.rcPaint.right - ps.rcPaint.left, ps.rcPaint.bottom - ps.rcPaint.top,
-		   s_pScreenPriv->hdcShadow,
-		   ps.rcPaint.left + pWin->drawable.x, ps.rcPaint.top + pWin->drawable.y,
-		   SRCCOPY))
-	{
-	  LPVOID lpMsgBuf;
-	  
-	  /* Display a fancy error message */
-	  FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | 
-			 FORMAT_MESSAGE_FROM_SYSTEM | 
-			 FORMAT_MESSAGE_IGNORE_INSERTS,
-			 NULL,
-			 GetLastError (),
-			 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-			 (LPTSTR) &lpMsgBuf,
-			 0, NULL);
-
-	  ErrorF ("winTopLevelWindowProc - BitBlt failed: %s\n",
-		  (LPSTR)lpMsgBuf);
-	  LocalFree (lpMsgBuf);
-	}
-
-      /* EndPaint frees the DC */
-      EndPaint (hwnd, &ps);
-      return 0;
-
-    case WM_MOUSEMOVE:
-      /* Unpack the client area mouse coordinates */
-      ptMouse.x = GET_X_LPARAM(lParam);
-      ptMouse.y = GET_Y_LPARAM(lParam);
-
-      /* Translate the client area mouse coordinates to screen coordinates */
-      ClientToScreen (hwnd, &ptMouse);
-
-      /* Screen Coords from (-X, -Y) -> Root Window (0, 0) */
-      ptMouse.x -= GetSystemMetrics (SM_XVIRTUALSCREEN);
-      ptMouse.y -= GetSystemMetrics (SM_YVIRTUALSCREEN);
-
-      /* We can't do anything without privates */
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-
-      /* Has the mouse pointer crossed screens? */
-      if (s_pScreen != miPointerGetScreen(inputInfo.pointer))
-	miPointerSetScreen (inputInfo.pointer, s_pScreenInfo->dwScreen,
-			       ptMouse.x - s_pScreenInfo->dwXOffset,
-			       ptMouse.y - s_pScreenInfo->dwYOffset);
-
-      /* Are we tracking yet? */
-      if (!s_fTracking)
-	{
-	  TRACKMOUSEEVENT		tme;
-	  
-	  /* Setup data structure */
-	  ZeroMemory (&tme, sizeof (tme));
-	  tme.cbSize = sizeof (tme);
-	  tme.dwFlags = TME_LEAVE;
-	  tme.hwndTrack = hwnd;
-
-	  /* Call the tracking function */
-	  if (!(*g_fpTrackMouseEvent) (&tme))
-	    ErrorF ("winTopLevelWindowProc - _TrackMouseEvent failed\n");
-
-	  /* Flag that we are tracking now */
-	  s_fTracking = TRUE;
-	}
-      
-      /* Hide or show the Windows mouse cursor */
-      if (g_fSoftwareCursor && g_fCursor)
-	{
-	  /* Hide Windows cursor */
-	  g_fCursor = FALSE;
-	  ShowCursor (FALSE);
-	}
-
-      /* Kill the timer used to poll mouse events */
-      if (g_uipMousePollingTimerID != 0)
-	{
-	  KillTimer (s_pScreenPriv->hwndScreen, WIN_POLLING_MOUSE_TIMER_ID);
-	  g_uipMousePollingTimerID = 0;
-	}
-
-      /* Deliver absolute cursor position to X Server */
-      miPointerAbsoluteCursor (ptMouse.x - s_pScreenInfo->dwXOffset,
-			       ptMouse.y - s_pScreenInfo->dwYOffset,
-			       g_c32LastInputEventTime = GetTickCount ());
-      return 0;
-      
-    case WM_NCMOUSEMOVE:
-      /*
-       * We break instead of returning 0 since we need to call
-       * DefWindowProc to get the mouse cursor changes
-       * and min/max/close button highlighting in Windows XP.
-       * The Platform SDK says that you should return 0 if you
-       * process this message, but it fails to mention that you
-       * will give up any default functionality if you do return 0.
-       */
-      
-      /* We can't do anything without privates */
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-
-      /* Non-client mouse movement, show Windows cursor */
-      if (g_fSoftwareCursor && !g_fCursor)
-	{
-	  g_fCursor = TRUE;
-	  ShowCursor (TRUE);
-	}
-
-      /*
-       * Timer to poll mouse events.  This is needed to make
-       * programs like xeyes follow the mouse properly.
-       */
-      if (g_uipMousePollingTimerID == 0)
-	g_uipMousePollingTimerID = SetTimer (s_pScreenPriv->hwndScreen,
-					     WIN_POLLING_MOUSE_TIMER_ID,
-					     MOUSE_POLLING_INTERVAL,
-					     NULL);
-      break;
-
-    case WM_MOUSELEAVE:
-      /* Mouse has left our client area */
-
-      /* Flag that we are no longer tracking */
-      s_fTracking = FALSE;
-
-      /* Show the mouse cursor, if necessary */
-      if (g_fSoftwareCursor && !g_fCursor)
-	{
-	  g_fCursor = TRUE;
-	  ShowCursor (TRUE);
-	}
-
-      /*
-       * Timer to poll mouse events.  This is needed to make
-       * programs like xeyes follow the mouse properly.
-       */
-      if (g_uipMousePollingTimerID == 0)
-	g_uipMousePollingTimerID = SetTimer (s_pScreenPriv->hwndScreen,
-					     WIN_POLLING_MOUSE_TIMER_ID,
-					     MOUSE_POLLING_INTERVAL,
-					     NULL);
-      return 0;
-
-    case WM_LBUTTONDBLCLK:
-    case WM_LBUTTONDOWN:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      g_fButton[0] = TRUE;
-      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button1, wParam);
-      
-    case WM_LBUTTONUP:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      g_fButton[0] = FALSE;
-      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button1, wParam);
-
-    case WM_MBUTTONDBLCLK:
-    case WM_MBUTTONDOWN:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      g_fButton[1] = TRUE;
-      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button2, wParam);
-      
-    case WM_MBUTTONUP:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      g_fButton[1] = FALSE;
-      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button2, wParam);
-      
-    case WM_RBUTTONDBLCLK:
-    case WM_RBUTTONDOWN:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      g_fButton[2] = TRUE;
-      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button3, wParam);
-      
-    case WM_RBUTTONUP:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      g_fButton[2] = FALSE;
-      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button3, wParam);
-
-    case WM_XBUTTONDBLCLK:
-    case WM_XBUTTONDOWN:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      return winMouseButtonsHandle (s_pScreen, ButtonPress, HIWORD(wParam) + 5, wParam);
-    case WM_XBUTTONUP:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      return winMouseButtonsHandle (s_pScreen, ButtonRelease, HIWORD(wParam) + 5, wParam);
-
-    case WM_MOUSEWHEEL:
-      
-      /* Pass the message to the root window */
-      SendMessage (hwndScreen, message, wParam, lParam);
-      return 0;
-
-    case WM_SETFOCUS:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-
-      winRestoreModeKeyStates ();
-
-      /* Add the keyboard hook if possible */
-      if (g_fKeyboardHookLL)
-	g_fKeyboardHookLL = winInstallKeyboardHookLL ();
-      return 0;
-      
-    case WM_KILLFOCUS:
-      /* Pop any pressed keys since we are losing keyboard focus */
-      winKeybdReleaseKeys ();
-
-      /* Remove our keyboard hook if it is installed */
-      winRemoveKeyboardHookLL ();
-      return 0;
-
-    case WM_SYSDEADCHAR:      
-    case WM_DEADCHAR:
-      /*
-       * NOTE: We do nothing with WM_*CHAR messages,
-       * nor does the root window, so we can just toss these messages.
-       */
-      return 0;
-
-    case WM_SYSKEYDOWN:
-    case WM_KEYDOWN:
-
-      /*
-       * Don't pass Alt-F4 key combo to root window,
-       * let Windows translate to WM_CLOSE and close this top-level window.
-       *
-       * NOTE: We purposely don't check the fUseWinKillKey setting because
-       * it should only apply to the key handling for the root window,
-       * not for top-level window-manager windows.
-       *
-       * ALSO NOTE: We do pass Ctrl-Alt-Backspace to the root window
-       * because that is a key combo that no X app should be expecting to
-       * receive, since it has historically been used to shutdown the X server.
-       * Passing Ctrl-Alt-Backspace to the root window preserves that
-       * behavior, assuming that -unixkill has been passed as a parameter.
-       */
-      if (wParam == VK_F4 && (GetKeyState (VK_MENU) & 0x8000))
-	  break;
-
-#if CYGWINDOWING_DEBUG
-      if (wParam == VK_ESCAPE)
-	{
-	  /* Place for debug: put any tests and dumps here */
-	  WINDOWPLACEMENT windPlace;
-	  RECT rc;
-	  LPRECT pRect;
-	  
-	  windPlace.length = sizeof (WINDOWPLACEMENT);
-	  GetWindowPlacement (hwnd, &windPlace);
-	  pRect = &windPlace.rcNormalPosition;
-	  ErrorF ("\nCYGWINDOWING Dump:\n"
-		  "\tdrawable: (%hd, %hd) - %hdx%hd\n", pDraw->x,
-		  pDraw->y, pDraw->width, pDraw->height);
-	  ErrorF ("\twindPlace: (%ld, %ld) - %ldx%ld\n", pRect->left,
-		  pRect->top, pRect->right - pRect->left,
-		  pRect->bottom - pRect->top);
-	  if (GetClientRect (hwnd, &rc))
-	    {
-	      pRect = &rc;
-	      ErrorF ("\tClientRect: (%ld, %ld) - %ldx%ld\n", pRect->left,
-		      pRect->top, pRect->right - pRect->left,
-		      pRect->bottom - pRect->top);
-	    }
-	  if (GetWindowRect (hwnd, &rc))
-	    {
-	      pRect = &rc;
-	      ErrorF ("\tWindowRect: (%ld, %ld) - %ldx%ld\n", pRect->left,
-		      pRect->top, pRect->right - pRect->left,
-		      pRect->bottom - pRect->top);
-	    }
-	  ErrorF ("\n");
-	}
-#endif
-      
-      /* Pass the message to the root window */
-      return winWindowProc(hwndScreen, message, wParam, lParam);
-
-    case WM_SYSKEYUP:
-    case WM_KEYUP:
-
-
-      /* Pass the message to the root window */
-      return winWindowProc(hwndScreen, message, wParam, lParam);
-
-    case WM_HOTKEY:
-
-      /* Pass the message to the root window */
-      SendMessage (hwndScreen, message, wParam, lParam);
-      return 0;
-
-    case WM_ACTIVATE:
-
-      /* Pass the message to the root window */
-      SendMessage (hwndScreen, message, wParam, lParam);
-
-      if (LOWORD(wParam) != WA_INACTIVE)
-	{
-	  /* Raise the window to the top in Z order */
-          /* ago: Activate does not mean putting it to front! */
-          /*
-	  wmMsg.msg = WM_WM_RAISE;
-	  if (fWMMsgInitialized)
-	    winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
-          */
-	  
-	  /* Tell our Window Manager thread to activate the window */
-	  wmMsg.msg = WM_WM_ACTIVATE;
-	  if (fWMMsgInitialized)
-	    if (!pWin || !pWin->overrideRedirect) /* for OOo menus */
-	      winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
-	}
-      return 0;
-
-    case WM_ACTIVATEAPP:
-      /*
-       * This message is also sent to the root window
-       * so we do nothing for individual multiwindow windows
-       */
-      break;
-
-    case WM_CLOSE:
-      /* Branch on if the window was killed in X already */
-      if (pWinPriv->fXKilled)
-        {
-	  /* Window was killed, go ahead and destroy the window */
-	  DestroyWindow (hwnd);
-	}
-      else
-	{
-	  /* Tell our Window Manager thread to kill the window */
-	  wmMsg.msg = WM_WM_KILL;
-	  if (fWMMsgInitialized)
-	    winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
-	}
-      return 0;
-
-    case WM_DESTROY:
-
-      /* Branch on if the window was killed in X already */
-      if (pWinPriv && !pWinPriv->fXKilled)
-	{
-	  ErrorF ("winTopLevelWindowProc - WM_DESTROY - WM_WM_KILL\n");
-	  
-	  /* Tell our Window Manager thread to kill the window */
-	  wmMsg.msg = WM_WM_KILL;
-	  if (fWMMsgInitialized)
-	    winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
-	}
-
-      RemoveProp (hwnd, WIN_WINDOW_PROP);
-      RemoveProp (hwnd, WIN_WID_PROP);
-      RemoveProp (hwnd, WIN_NEEDMANAGE_PROP);
-
-      break;
-
-    case WM_MOVE:
-      /* Adjust the X Window to the moved Windows window */
-      winAdjustXWindow (pWin, hwnd);
-      return 0;
-
-    case WM_SHOWWINDOW:
-      /* Bail out if the window is being hidden */
-      if (!wParam)
-	return 0;
-
-      /* Tell X to map the window */
-      MapWindow (pWin, wClient(pWin));
-
-      /* */
-      if (!pWin->overrideRedirect)
-	{
-	  DWORD		dwExStyle;
-	  DWORD		dwStyle;
-	  RECT		rcNew;
-	  int		iDx, iDy;
-	      
-	  /* Flag that this window needs to be made active when clicked */
-	  SetProp (hwnd, WIN_NEEDMANAGE_PROP, (HANDLE) 1);
-
-	  /* Get the standard and extended window style information */
-	  dwExStyle = GetWindowLongPtr (hwnd, GWL_EXSTYLE);
-	  dwStyle = GetWindowLongPtr (hwnd, GWL_STYLE);
-
-	  /* */
-	  if (dwExStyle != WS_EX_APPWINDOW)
-	    {
-	      /* Setup a rectangle with the X window position and size */
-	      SetRect (&rcNew,
-		       pDraw->x,
-		       pDraw->y,
-		       pDraw->x + pDraw->width,
-		       pDraw->y + pDraw->height);
-
-#if 0
-	      ErrorF ("winTopLevelWindowProc - (%d, %d)-(%d, %d)\n",
-		      rcNew.left, rcNew.top,
-		      rcNew.right, rcNew.bottom);
-#endif
-
-	      /* */
-	      AdjustWindowRectEx (&rcNew,
-				  WS_POPUP | WS_SIZEBOX | WS_OVERLAPPEDWINDOW,
-				  FALSE,
-				  WS_EX_APPWINDOW);
-
-	      /* Calculate position deltas */
-	      iDx = pDraw->x - rcNew.left;
-	      iDy = pDraw->y - rcNew.top;
-
-	      /* Calculate new rectangle */
-	      rcNew.left += iDx;
-	      rcNew.right += iDx;
-	      rcNew.top += iDy;
-	      rcNew.bottom += iDy;
-
-#if 0
-	      ErrorF ("winTopLevelWindowProc - (%d, %d)-(%d, %d)\n",
-		      rcNew.left, rcNew.top,
-		      rcNew.right, rcNew.bottom);
-#endif
-
-	      /* Set the window extended style flags */
-	      SetWindowLongPtr (hwnd, GWL_EXSTYLE, WS_EX_APPWINDOW);
-
-	      /* Set the window standard style flags */
-	      SetWindowLongPtr (hwnd, GWL_STYLE,
-				WS_POPUP | WS_SIZEBOX | WS_OVERLAPPEDWINDOW);
-
-	      /* Position the Windows window */
-	      SetWindowPos (hwnd, HWND_TOP,
-			    rcNew.left, rcNew.top,
-			    rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
-			    SWP_NOMOVE | SWP_FRAMECHANGED
-			    | SWP_SHOWWINDOW | SWP_NOACTIVATE);
-
-	      /* Bring the Windows window to the foreground */
-	      SetForegroundWindow (hwnd);
-	    }
-	}
-      else /* It is an overridden window so make it top of Z stack */
-	{
-#if CYGWINDOWING_DEBUG
-	  ErrorF ("overridden window is shown\n");
-#endif
-	  SetWindowPos (hwnd, HWND_TOPMOST, 0, 0, 0, 0,
-			SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
-	}
-	  
-      /* Setup the Window Manager message */
-      wmMsg.msg = WM_WM_MAP;
-      wmMsg.iWidth = pDraw->width;
-      wmMsg.iHeight = pDraw->height;
-
-      /* Tell our Window Manager thread to map the window */
-      if (fWMMsgInitialized)
-	winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
-
-      return 0;
-
-    case WM_SIZING:
-      /* Need to legalize the size according to WM_NORMAL_HINTS */
-      /* for applications like xterm */
-      return ValidateSizing (hwnd, pWin, wParam, lParam);
-
-    case WM_WINDOWPOSCHANGED:
-      {
-	LPWINDOWPOS pWinPos = (LPWINDOWPOS) lParam;
-
-	if (!(pWinPos->flags & SWP_NOZORDER))
-	  {
-#if CYGWINDOWING_DEBUG
-	    winDebug ("\twindow z order was changed\n");
-#endif
-	    if (pWinPos->hwndInsertAfter == HWND_TOP
-		||pWinPos->hwndInsertAfter == HWND_TOPMOST
-		||pWinPos->hwndInsertAfter == HWND_NOTOPMOST)
-	      {
-#if CYGWINDOWING_DEBUG
-		winDebug ("\traise to top\n");
-#endif
-		/* Raise the window to the top in Z order */
-		winRaiseWindow(pWin);
-	      }
-	    else if (pWinPos->hwndInsertAfter == HWND_BOTTOM)
-	      {
-	      }
-	    else
-	      {
-		/* Check if this window is top of X windows. */
-		HWND hWndAbove = NULL;
-		DWORD dwCurrentProcessID = GetCurrentProcessId ();
-		DWORD dwWindowProcessID = 0;
-
-		for (hWndAbove = pWinPos->hwndInsertAfter;
-		     hWndAbove != NULL;
-		     hWndAbove = GetNextWindow (hWndAbove, GW_HWNDPREV))
-		  {
-		    /* Ignore other XWin process's window */
-		    GetWindowThreadProcessId (hWndAbove, &dwWindowProcessID);
-
-		    if ((dwWindowProcessID == dwCurrentProcessID)
-			&& GetProp (hWndAbove, WIN_WINDOW_PROP)
-			&& !IsWindowVisible (hWndAbove)
-			&& !IsIconic (hWndAbove) ) /* ignore minimized windows */
-		      break;
-		  }
-		/* If this is top of X windows in Windows stack,
-		   raise it in X stack. */
-		if (hWndAbove == NULL)
-		  {
-#if CYGWINDOWING_DEBUG
-		    winDebug ("\traise to top\n");
-#endif
-		    winRaiseWindow(pWin);
-		  }
-	      }
-	  }
-      }
-      /*
-       * Pass the message to DefWindowProc to let the function
-       * break down WM_WINDOWPOSCHANGED to WM_MOVE and WM_SIZE.
-      */
-      break; 
-
-    case WM_SIZE:
-      /* see dix/window.c */
-#if CYGWINDOWING_DEBUG
-      {
-	char buf[64];
-	switch (wParam)
-	  {
-	  case SIZE_MINIMIZED:
-	    strcpy(buf, "SIZE_MINIMIZED");
-	    break;
-	  case SIZE_MAXIMIZED:
-	    strcpy(buf, "SIZE_MAXIMIZED");
-	    break;
-	  case SIZE_RESTORED:
-	    strcpy(buf, "SIZE_RESTORED");
-	    break;
-	  default:
-	    strcpy(buf, "UNKNOWN_FLAG");
-	  }
-	ErrorF ("winTopLevelWindowProc - WM_SIZE to %dx%d (%s) - %d ms\n",
-		(int)LOWORD(lParam), (int)HIWORD(lParam), buf,
-		(int)(GetTickCount ()));
-      }
-#endif
-      /* Adjust the X Window to the moved Windows window */
-      winAdjustXWindow (pWin, hwnd);
-      return 0; /* end of WM_SIZE handler */
-
-    case WM_MOUSEACTIVATE:
-
-      /* Check if this window needs to be made active when clicked */
-      if (!GetProp (pWinPriv->hWnd, WIN_NEEDMANAGE_PROP))
-	{
-#if CYGMULTIWINDOW_DEBUG
-	  ErrorF ("winTopLevelWindowProc - WM_MOUSEACTIVATE - "
-		  "MA_NOACTIVATE\n");
-#endif
-
-	  /* */
-	  return MA_NOACTIVATE;
-	}
-      break;
-
-    case WM_SETCURSOR:
-      if (LOWORD(lParam) == HTCLIENT)
-	{
-	  if (!g_fSoftwareCursor) SetCursor (s_pScreenPriv->cursor.handle);
-	  return TRUE;
-	}
-      break;
-
-    default:
-      break;
-    }
-
-  ret = DefWindowProc (hwnd, message, wParam, lParam);
-  /*
-   * If the window was minized we get the stack change before the window is restored
-   * and so it gets lost. Ensure there stacking order is correct.
-   */
-  if (needRestack)
-    winReorderWindowsMultiWindow();
-  return ret;
-}
diff --git a/hw/xwin/winnativegdi.c b/hw/xwin/winnativegdi.c
deleted file mode 100644
index 48a467a..0000000
--- a/hw/xwin/winnativegdi.c
+++ /dev/null
@@ -1,546 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * External symbols
- */
-
-extern HWND			g_hDlgExit;
-
-
-/*
- * Local function prototypes
- */
-
-static Bool
-winAllocateFBNativeGDI (ScreenPtr pScreen);
-
-static void
-winShadowUpdateNativeGDI (ScreenPtr pScreen, 
-			  shadowBufPtr pBuf);
-
-static Bool
-winCloseScreenNativeGDI (int nIndex, ScreenPtr pScreen);
-
-static Bool
-winInitVisualsNativeGDI (ScreenPtr pScreen);
-
-static Bool
-winAdjustVideoModeNativeGDI (ScreenPtr pScreen);
-
-#if 0
-static Bool
-winBltExposedRegionsNativeGDI (ScreenPtr pScreen);
-#endif
-
-static Bool
-winActivateAppNativeGDI (ScreenPtr pScreen);
-
-static Bool
-winRedrawScreenNativeGDI (ScreenPtr pScreen);
-
-static Bool
-winRealizeInstalledPaletteNativeGDI (ScreenPtr pScreen);
-
-static Bool
-winInstallColormapNativeGDI (ColormapPtr pColormap);
-
-static Bool
-winStoreColorsNativeGDI (ColormapPtr pmap, 
-			 int ndef,
-			 xColorItem *pdefs);
-
-static Bool
-winCreateColormapNativeGDI (ColormapPtr pColormap);
-
-static Bool
-winDestroyColormapNativeGDI (ColormapPtr pColormap);
-
-
-
-static Bool
-winAllocateFBNativeGDI (ScreenPtr pScreen)
-{
-  FatalError ("winAllocateFBNativeGDI\n");
-
-  return TRUE;
-}
-
-
-/*
- * We wrap whatever CloseScreen procedure was specified by fb;
- * a pointer to said procedure is stored in our privates.
- */
-
-static Bool
-winCloseScreenNativeGDI (int nIndex, ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-
-  ErrorF ("winCloseScreenNativeGDI - Freeing screen resources\n");
-
-  /* Flag that the screen is closed */
-  pScreenPriv->fClosed = TRUE;
-  pScreenPriv->fActive = FALSE;
-
-  /* 
-   * NOTE: mi doesn't use a CloseScreen procedure, so we do not
-   * need to call a wrapped procedure here.
-   */
-
-  /* Delete the window property */
-  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
-  
-  ErrorF ("winCloseScreenNativeGDI - Destroying window\n");
-  
-  /* Delete tray icon, if we have one */
-  if (!pScreenInfo->fNoTrayIcon)
-    winDeleteNotifyIcon (pScreenPriv);
-
-  /* Free the exit confirmation dialog box, if it exists */
-  if (g_hDlgExit != NULL)
-    {
-      DestroyWindow (g_hDlgExit);
-      g_hDlgExit = NULL;
-    }
-
-  /* Kill our window */
-  if (pScreenPriv->hwndScreen)
-    {
-      DestroyWindow (pScreenPriv->hwndScreen);
-      pScreenPriv->hwndScreen = NULL;
-    }
-
-  /* Invalidate our screeninfo's pointer to the screen */
-  pScreenInfo->pScreen = NULL;
-
-  /* Free the screen privates for this screen */
-  free (pScreenPriv);
-
-  ErrorF ("winCloseScreenNativeGDI - Returning\n");
-
-  return TRUE;
-}
-
-
-static void
-winShadowUpdateNativeGDI (ScreenPtr pScreen, 
-			  shadowBufPtr pBuf)
-{
-  FatalError ("winShadowUpdateNativeGDI\n");
-  return;
-}
-
-
-static Bool
-winInitVisualsNativeGDI (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-
-  /* Set the bitsPerRGB and bit masks */
-  switch (pScreenInfo->dwDepth)
-    {
-    case 24:
-      pScreenPriv->dwBitsPerRGB = 8;
-      pScreenPriv->dwRedMask = 0x00FF0000;
-      pScreenPriv->dwGreenMask = 0x0000FF00;
-      pScreenPriv->dwBlueMask = 0x000000FF;
-      break;
-      
-    case 16:
-      pScreenPriv->dwBitsPerRGB = 6;
-      pScreenPriv->dwRedMask = 0xF800;
-      pScreenPriv->dwGreenMask = 0x07E0;
-      pScreenPriv->dwBlueMask = 0x001F;
-      break;
-      
-    case 15:
-      pScreenPriv->dwBitsPerRGB = 5;
-      pScreenPriv->dwRedMask = 0x7C00;
-      pScreenPriv->dwGreenMask = 0x03E0;
-      pScreenPriv->dwBlueMask = 0x001F;
-      break;
-      
-    case 8:
-      pScreenPriv->dwBitsPerRGB = 8;
-      pScreenPriv->dwRedMask = 0;
-      pScreenPriv->dwGreenMask = 0;
-      pScreenPriv->dwBlueMask = 0;
-      break;
-
-    default:
-      ErrorF ("winInitVisualsNativeGDI - Unknown screen depth\n");
-      return FALSE;
-      break;
-    }
-
-  /* Tell the user how many bits per RGB we are using */
-  ErrorF ("winInitVisualsNativeGDI - Using dwBitsPerRGB: %d\n",
-	  (int) pScreenPriv->dwBitsPerRGB);
-
-  /* Create a single visual according to the Windows screen depth */
-  switch (pScreenInfo->dwDepth)
-    {
-    case 24:
-    case 16:
-    case 15:
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     TrueColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     TrueColor,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisuals - miSetVisualTypesAndMasks failed\n");
-	  return FALSE;
-	}
-      break;
-
-    case 8:
-      ErrorF ("winInitVisuals - Calling miSetVisualTypesAndMasks\n");
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     StaticColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     StaticColor,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisuals - miSetVisualTypesAndMasks failed\n");
-	  return FALSE;
-	}
-      break;
-
-    default:
-      ErrorF ("winInitVisualsNativeGDI - Unknown screen depth\n");
-      return FALSE;
-    }
-
-#if 1
-  ErrorF ("winInitVisualsNativeGDI - Returning\n");
-#endif
-
-  return TRUE;
-}
-
-
-/* Adjust the video mode */
-static Bool
-winAdjustVideoModeNativeGDI (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  HDC			hdc = NULL;
-  DWORD			dwBPP;
-  
-  hdc = GetDC (NULL);
-
-  /* We're in serious trouble if we can't get a DC */
-  if (hdc == NULL)
-    {
-      ErrorF ("winAdjustVideoModeNativeGDI - GetDC () failed\n");
-      return FALSE;
-    }
-
-  /* Query GDI for current display depth */
-  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
-  pScreenInfo->dwDepth = GetDeviceCaps (hdc, PLANES);
-
-  switch (pScreenInfo->dwDepth) {
-    case 24:
-    case 16:
-    case 15:
-    case 8:
-      break;
-    default:
-      if (dwBPP == 32)
-        pScreenInfo->dwDepth = 24;
-      else
-        pScreenInfo->dwDepth = dwBPP; 
-      break;
-  }
-
-  /* GDI cannot change the screen depth */
-  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
-    {
-      /* No -depth parameter passed, let the user know the depth being used */
-      ErrorF ("winAdjustVideoModeNativeGDI - Using Windows display "
-	      "depth of %d bits per pixel, %d depth\n",
-	      (int) dwBPP, (int) pScreenInfo->dwDepth);
-
-      /* Use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-  else if (dwBPP != pScreenInfo->dwBPP)
-    {
-      /* Warn user if GDI depth is different than -depth parameter */
-      ErrorF ("winAdjustVideoModeNativeGDI - Command line bpp: %d, "\
-	      "using bpp: %d\n",
-	      (int) pScreenInfo->dwBPP, (int) dwBPP);
-
-      /* We'll use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-  
-  /* Release our DC */
-  ReleaseDC (NULL, hdc);
-
-  return TRUE;
-}
-
-
-static Bool
-winActivateAppNativeGDI (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-
-  /*
-   * Are we active?
-   * Are we fullscreen?
-   */
-  if (pScreenPriv != NULL
-      && pScreenPriv->fActive
-      && pScreenInfo->fFullScreen)
-    {
-      /*
-       * Activating, attempt to bring our window 
-       * to the top of the display
-       */
-      ShowWindow (pScreenPriv->hwndScreen, SW_RESTORE);
-    }
-
-  /*
-   * Are we inactive?
-   * Are we fullscreen?
-   */
-  if (pScreenPriv != NULL
-      && !pScreenPriv->fActive
-      && pScreenInfo->fFullScreen)
-    {
-      /*
-       * Deactivating, stuff our window onto the
-       * task bar.
-       */
-      ShowWindow (pScreenPriv->hwndScreen, SW_MINIMIZE);
-    }
-
-  return TRUE;
-}
-
-
-HBITMAP
-winCreateDIBNativeGDI (int iWidth, int iHeight, int iDepth,
-		       BYTE **ppbBits, BITMAPINFO **ppbmi)
-{
-  BITMAPINFOHEADER	*pbmih = NULL;
-  HBITMAP		hBitmap = NULL;
-  BITMAPINFO		*pbmi = NULL;
-
-  /* Don't create an invalid bitmap */
-  if (iWidth == 0
-      || iHeight == 0
-      || iDepth == 0)
-    {
-      ErrorF ("\nwinCreateDIBNativeGDI - Invalid specs w %d h %d d %d\n\n",
-	      iWidth, iHeight, iDepth);
-      return NULL;
-    }
-
-  /* Allocate bitmap info header */
-  pbmih = (BITMAPINFOHEADER*) malloc (sizeof (BITMAPINFOHEADER)
-				      + 256 * sizeof (RGBQUAD));
-  if (pbmih == NULL)
-    {
-      ErrorF ("winCreateDIBNativeGDI - malloc () failed\n");
-      return FALSE;
-    }
-  ZeroMemory (pbmih, sizeof(BITMAPINFOHEADER) + 256 * sizeof (RGBQUAD));
-
-  /* Describe bitmap to be created */
-  pbmih->biSize = sizeof (BITMAPINFOHEADER);
-  pbmih->biWidth = iWidth;
-  pbmih->biHeight = -iHeight;
-  pbmih->biPlanes = 1;
-  pbmih->biBitCount = iDepth;
-  pbmih->biCompression = BI_RGB;
-  pbmih->biSizeImage = 0;
-  pbmih->biXPelsPerMeter = 0;
-  pbmih->biYPelsPerMeter = 0;
-  pbmih->biClrUsed = 0;
-  pbmih->biClrImportant = 0;
-
-  /* Setup color table for mono DIBs */
-  if (iDepth == 1)
-    {
-      pbmi = (BITMAPINFO*) pbmih;
-      pbmi->bmiColors[1].rgbBlue = 255;
-      pbmi->bmiColors[1].rgbGreen = 255;
-      pbmi->bmiColors[1].rgbRed = 255;
-    }
-
-  /* Create a DIB with a bit pointer */
-  hBitmap = CreateDIBSection (NULL,
-			      (BITMAPINFO *) pbmih,
-			      DIB_RGB_COLORS,
-			      (void **) ppbBits,
-			      NULL,
-			      0);
-  if (hBitmap == NULL)
-    {
-      ErrorF ("winCreateDIBNativeGDI - CreateDIBSection () failed\n");
-      return NULL;
-    }
-
-  /* Free the bitmap info header memory */
-  if (ppbmi != NULL)
-    {
-      /* Store the address of the BMIH in the ppbmih parameter */
-      *ppbmi = (BITMAPINFO *) pbmih;
-    }
-  else
-    {
-      free (pbmih);
-      pbmih = NULL;
-    }
-
-  return hBitmap;
-}
-
-
-#if 0
-static Bool
-winBltExposedRegionsNativeGDI (ScreenPtr pScreen)
-{
-  
-  return TRUE;
-}
-#endif
-
-
-static Bool
-winRedrawScreenNativeGDI (ScreenPtr pScreen)
-{
-  FatalError ("winRedrawScreenNativeGDI\n");
-  return TRUE;
-}
-
-
-static Bool
-winRealizeInstalledPaletteNativeGDI (ScreenPtr pScreen)
-{
-  FatalError ("winRealizeInstalledPaletteNativeGDI\n");
-  return TRUE;
-}
-
-
-static Bool
-winInstallColormapNativeGDI (ColormapPtr pColormap)
-{
-  FatalError ("winInstallColormapNativeGDI\n");
-  return TRUE;
-}
-
-
-static Bool
-winStoreColorsNativeGDI (ColormapPtr pmap, 
-			 int ndef,
-			 xColorItem *pdefs)
-{
-  FatalError ("winStoreColorsNativeGDI\n");
-  return TRUE;
-}
-
-
-static Bool
-winCreateColormapNativeGDI (ColormapPtr pColormap)
-{
-  FatalError ("winCreateColormapNativeGDI\n");
-  return TRUE;
-}
-
-
-static Bool
-winDestroyColormapNativeGDI (ColormapPtr pColormap)
-{
-  FatalError ("winDestroyColormapNativeGDI\n");
-  return TRUE;
-}
-
-
-/* Set engine specific funtions */
-Bool
-winSetEngineFunctionsNativeGDI (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  
-  /* Set our pointers */
-  pScreenPriv->pwinAllocateFB = winAllocateFBNativeGDI;
-  pScreenPriv->pwinShadowUpdate = winShadowUpdateNativeGDI;
-  pScreenPriv->pwinCloseScreen = winCloseScreenNativeGDI;
-  pScreenPriv->pwinInitVisuals = winInitVisualsNativeGDI;
-  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModeNativeGDI;
-  if (pScreenInfo->fFullScreen)
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
-  else
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
-  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitNativeGDI;
-  /*
-   * WARNING: Do not set the BltExposedRegions procedure pointer to anything
-   * other than NULL until a working painting procedure is in place.
-   * Else, winWindowProc will get stuck in an infinite loop because
-   * Windows expects the BeginPaint and EndPaint functions to be called
-   * before a WM_PAINT message can be removed from the queue.  We are
-   * using NULL here as a signal for winWindowProc that it should
-   * not signal that the WM_PAINT message has been processed.
-   */
-  pScreenPriv->pwinBltExposedRegions = NULL;
-  pScreenPriv->pwinActivateApp = winActivateAppNativeGDI;
-  pScreenPriv->pwinRedrawScreen = winRedrawScreenNativeGDI;
-  pScreenPriv->pwinRealizeInstalledPalette = 
-    winRealizeInstalledPaletteNativeGDI;
-  pScreenPriv->pwinInstallColormap = winInstallColormapNativeGDI;
-  pScreenPriv->pwinStoreColors = winStoreColorsNativeGDI;
-  pScreenPriv->pwinCreateColormap = winCreateColormapNativeGDI;
-  pScreenPriv->pwinDestroyColormap = winDestroyColormapNativeGDI;
-  pScreenPriv->pwinHotKeyAltTab = (winHotKeyAltTabProcPtr) (void (*)(void))NoopDDA;
-
-  return TRUE;
-}
diff --git a/hw/xwin/winpfbdd.c b/hw/xwin/winpfbdd.c
deleted file mode 100644
index 13fc105..0000000
--- a/hw/xwin/winpfbdd.c
+++ /dev/null
@@ -1,684 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * External symbols
- */
-
-extern const GUID		_IID_IDirectDraw2;
-extern HWND			g_hDlgExit;
-
-
-/*
- * Local function prototypes
- */
-
-static Bool
-winAllocateFBPrimaryDD (ScreenPtr pScreen);
-
-static Bool
-winCloseScreenPrimaryDD (int nIndex, ScreenPtr pScreen);
-
-static Bool
-winInitVisualsPrimaryDD (ScreenPtr pScreen);
-
-static Bool
-winAdjustVideoModePrimaryDD (ScreenPtr pScreen);
-
-static Bool
-winActivateAppPrimaryDD (ScreenPtr pScreen);
-
-static Bool
-winHotKeyAltTabPrimaryDD (ScreenPtr pScreen);
-
-
-/*
- * Create a DirectDraw primary surface 
- */
-
-static Bool
-winAllocateFBPrimaryDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;  
-  HRESULT		ddrval = DD_OK;
-  DDSURFACEDESC		ddsd;
-  DDSURFACEDESC		*pddsdPrimary = NULL;
-  DDSURFACEDESC		*pddsdOffscreen = NULL;
-  RECT			rcClient;
-
-  ErrorF ("winAllocateFBPrimaryDD\n");
-
-  /* Get client area location in screen coords */
-  GetClientRect (pScreenPriv->hwndScreen, &rcClient);
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&rcClient, 2);
-
-  /* Create a DirectDraw object, store the address at lpdd */
-  ddrval = (*g_fpDirectDrawCreate) (NULL, &pScreenPriv->pdd, NULL);
-  if (ddrval != DD_OK)
-    FatalError ("winAllocateFBPrimaryDD - Could not start DirectDraw\n");
-  
-  /* Get a DirectDraw2 interface pointer */
-  ddrval = IDirectDraw_QueryInterface (pScreenPriv->pdd,
-				       &IID_IDirectDraw2,
-				       (LPVOID*) &pScreenPriv->pdd2);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDD - Failed DD2 query: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-
-  ErrorF ("winAllocateFBPrimaryDD - Created and initialized DD\n");
-
-  /* Are we windowed or fullscreen? */
-  if (pScreenInfo->fFullScreen)
-    {
-      /* Full screen mode */
-      ddrval = IDirectDraw2_SetCooperativeLevel (pScreenPriv->pdd2,
-						 pScreenPriv->hwndScreen,
-						 DDSCL_FULLSCREEN
-						 | DDSCL_EXCLUSIVE);
-      if (FAILED (ddrval))
-	FatalError ("winAllocateFBPrimaryDD - Could not set "
-		    "cooperative level\n");
-
-      /* Change the video mode to the mode requested */
-      ddrval = IDirectDraw2_SetDisplayMode (pScreenPriv->pdd2,
-					    pScreenInfo->dwWidth,
-					    pScreenInfo->dwHeight,
-					    pScreenInfo->dwBPP,
-					    pScreenInfo->dwRefreshRate,
-					    0);
-       if (FAILED (ddrval))
-	FatalError ("winAllocateFBPrimaryDD - Could not set "
-		    "full screen display mode\n");
-    }
-  else
-    {
-      /* Windowed mode */
-      ddrval = IDirectDraw2_SetCooperativeLevel (pScreenPriv->pdd2,
-						 pScreenPriv->hwndScreen,
-						 DDSCL_NORMAL);
-      if (FAILED (ddrval))
-	FatalError ("winAllocateFBPrimaryDD - Could not set "
-		    "cooperative level\n");
-    }
-
-  /* Describe the primary surface */
-  ZeroMemory (&ddsd, sizeof (ddsd));
-  ddsd.dwSize = sizeof (ddsd);
-  ddsd.dwFlags = DDSD_CAPS;
-  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
-  
-  /* Create the primary surface */
-  ddrval = IDirectDraw2_CreateSurface (pScreenPriv->pdd2,
-				       &ddsd,
-				       &pScreenPriv->pddsPrimary,
-				       NULL);
-  if (FAILED (ddrval))
-       FatalError ("winAllocateFBPrimaryDD - Could not create primary "
-		  "surface %08x\n", (unsigned int) ddrval);
-
-  ErrorF ("winAllocateFBPrimaryDD - Created primary\n");
-
-  /* Allocate a DD surface description for our screen privates */
-  pddsdPrimary = pScreenPriv->pddsdPrimary
-    = malloc (sizeof (DDSURFACEDESC));
-  if (pddsdPrimary == NULL)
-    FatalError ("winAllocateFBPrimaryDD - Could not allocate surface "
-		"description memory\n");
-  ZeroMemory (pddsdPrimary, sizeof (*pddsdPrimary));
-  pddsdPrimary->dwSize = sizeof (*pddsdPrimary);
-
-  /* Describe the offscreen surface to be created */
-  /*
-   * NOTE: Do not use a DDSCAPS_VIDEOMEMORY surface,
-   * as drawing, locking, and unlocking take forever
-   * with video memory surfaces.  In addition,
-   * video memory is a somewhat scarce resource,
-   * so you shouldn't be allocating video memory when
-   * you have the option of using system memory instead.
-   */
-  ZeroMemory (&ddsd, sizeof (ddsd));
-  ddsd.dwSize = sizeof (ddsd);
-  ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
-  ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
-  ddsd.dwHeight = pScreenInfo->dwHeight;
-  ddsd.dwWidth = pScreenInfo->dwWidth;
-
-  /* Create the shadow surface */
-  ddrval = IDirectDraw2_CreateSurface (pScreenPriv->pdd2,
-				       &ddsd,
-				       &pScreenPriv->pddsOffscreen,
-				       NULL);
-  if (ddrval != DD_OK)
-    FatalError ("winAllocateFBPrimaryDD - Could not create shadow "
-		"surface\n");
-  
-  ErrorF ("winAllocateFBPrimaryDD - Created offscreen\n");
-
-  /* Allocate a DD surface description for our screen privates */
-  pddsdOffscreen = pScreenPriv->pddsdOffscreen
-    = malloc (sizeof (DDSURFACEDESC));
-  if (pddsdOffscreen == NULL)
-    FatalError ("winAllocateFBPrimaryDD - Could not allocate surface "
-		"description memory\n");
-  ZeroMemory (pddsdOffscreen, sizeof (*pddsdOffscreen));
-  pddsdOffscreen->dwSize = sizeof (*pddsdOffscreen);
-
-  ErrorF ("winAllocateFBPrimaryDD - Locking primary\n");
-
-  /* Lock the primary surface */
-  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsPrimary,
-				    pScreenInfo->fFullScreen ? NULL:&rcClient,
-				    pddsdPrimary,
-				    DDLOCK_WAIT,
-				    NULL);
-  if (ddrval != DD_OK || pddsdPrimary->lpSurface == NULL)
-    FatalError ("winAllocateFBPrimaryDD - Could not lock "
-		"primary surface\n");
-
-  ErrorF ("winAllocateFBPrimaryDD - Locked primary\n");
-
-  /* We don't know how to deal with anything other than RGB */
-  if (!(pddsdPrimary->ddpfPixelFormat.dwFlags & DDPF_RGB))
-    FatalError ("winAllocateFBPrimaryDD - Color format other than RGB\n");
-
-  /* Grab the pitch from the surface desc */
-  pScreenInfo->dwStride = (pddsdPrimary->u1.lPitch * 8)
-    / pScreenInfo->dwBPP;
-
-  /* Save the pointer to our surface memory */
-  pScreenInfo->pfb = pddsdPrimary->lpSurface;
-  
-  /* Grab the color depth and masks from the surface description */
-  pScreenPriv->dwRedMask = pddsdPrimary->ddpfPixelFormat.u2.dwRBitMask;
-  pScreenPriv->dwGreenMask = pddsdPrimary->ddpfPixelFormat.u3.dwGBitMask;
-  pScreenPriv->dwBlueMask = pddsdPrimary->ddpfPixelFormat.u4.dwBBitMask;
-
-  ErrorF ("winAllocateFBPrimaryDD - Returning\n");
-
-  return TRUE;
-}
-
-
-/*
- * Call the wrapped CloseScreen function.
- * 
- * Free our resources and private structures.
- */
-
-static Bool
-winCloseScreenPrimaryDD (int nIndex, ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  Bool			fReturn;
-  
-  ErrorF ("winCloseScreenPrimaryDD - Freeing screen resources\n");
-
-  /* Flag that the screen is closed */
-  pScreenPriv->fClosed = TRUE;
-  pScreenPriv->fActive = FALSE;
-
-  /* Call the wrapped CloseScreen procedure */
-  WIN_UNWRAP(CloseScreen);
-  fReturn = (*pScreen->CloseScreen) (nIndex, pScreen);
-
-  /* Delete the window property */
-  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
-
-  /* Free the offscreen surface, if there is one */
-  if (pScreenPriv->pddsOffscreen)
-    {
-      IDirectDrawSurface2_Unlock (pScreenPriv->pddsOffscreen, NULL);
-      IDirectDrawSurface2_Release (pScreenPriv->pddsOffscreen);
-      pScreenPriv->pddsOffscreen = NULL;
-    }
-
-  /* Release the primary surface, if there is one */
-  if (pScreenPriv->pddsPrimary)
-    {
-      IDirectDrawSurface2_Unlock (pScreenPriv->pddsPrimary, NULL);
-      IDirectDrawSurface2_Release (pScreenPriv->pddsPrimary);
-      pScreenPriv->pddsPrimary = NULL;
-    }
-
-  /* Free the DirectDraw object, if there is one */
-  if (pScreenPriv->pdd)
-    {
-      IDirectDraw2_RestoreDisplayMode (pScreenPriv->pdd);
-      IDirectDraw2_Release (pScreenPriv->pdd);
-      pScreenPriv->pdd = NULL;
-    }
-
-  /* Delete tray icon, if we have one */
-  if (!pScreenInfo->fNoTrayIcon)
-    winDeleteNotifyIcon (pScreenPriv);
-
-  /* Free the exit confirmation dialog box, if it exists */
-  if (g_hDlgExit != NULL)
-    {
-      DestroyWindow (g_hDlgExit);
-      g_hDlgExit = NULL;
-    }
-
-  /* Kill our window */
-  if (pScreenPriv->hwndScreen)
-    {
-      DestroyWindow (pScreenPriv->hwndScreen);
-      pScreenPriv->hwndScreen = NULL;
-    }
-
-  /* Kill our screeninfo's pointer to the screen */
-  pScreenInfo->pScreen = NULL;
-
-  /* Invalidate the ScreenInfo's fb pointer */
-  pScreenInfo->pfb = NULL;
-
-  /* Free the screen privates for this screen */
-  free ((pointer) pScreenPriv);
-
-  return fReturn;
-}
-
-
-/*
- * Tell mi what sort of visuals we need.
- * 
- * Generally we only need one visual, as our screen can only
- * handle one format at a time, I believe.  You may want
- * to verify that last sentence.
- */
-
-static Bool
-winInitVisualsPrimaryDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  DWORD			dwRedBits, dwGreenBits, dwBlueBits;
-
-  /* Count the number of ones in each color mask */
-  dwRedBits = winCountBits (pScreenPriv->dwRedMask);
-  dwGreenBits = winCountBits (pScreenPriv->dwGreenMask);
-  dwBlueBits = winCountBits (pScreenPriv->dwBlueMask);
-  
-  /* Store the maximum number of ones in a color mask as the bitsPerRGB */
-  if (dwRedBits > dwGreenBits && dwRedBits > dwBlueBits)
-    pScreenPriv->dwBitsPerRGB = dwRedBits;
-  else if (dwGreenBits > dwRedBits && dwGreenBits > dwBlueBits)
-    pScreenPriv->dwBitsPerRGB = dwGreenBits;
-  else
-    pScreenPriv->dwBitsPerRGB = dwBlueBits;
-  
-  ErrorF ("winInitVisualsPrimaryDD - Masks: %08x %08x %08x bpRGB: %d\n",
-	  (unsigned int) pScreenPriv->dwRedMask,
-	  (unsigned int) pScreenPriv->dwGreenMask,
-	  (unsigned int) pScreenPriv->dwBlueMask,
-	  (int) pScreenPriv->dwBitsPerRGB);
-
-  /* Create a single visual according to the Windows screen depth */
-  switch (pScreenInfo->dwDepth)
-    {
-    case 24:
-    case 16:
-    case 15:
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     TrueColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     TrueColor,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsPrimaryDD - " 
-		  "miSetVisualTypesAndMasks failed\n");
-	  return FALSE;
-	}
-      break;
-
-    case 8:
-#if CYGDEBUG
-      winDebug ("winInitVisuals - Calling miSetVisualTypesAndMasks\n");
-#endif /* CYGDEBUG */
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     PseudoColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     PseudoColor,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsPrimaryDD - "
-		  "miSetVisualTypesAndMasks failed\n");
-	  return FALSE;
-	}
-#if CYGDEBUG
-      winDebug ("winInitVisualsPrimaryDD - Returned from "
-	      "miSetVisualTypesAndMasks\n");
-#endif /* CYGDEBUG */
-      break;
-
-    default:
-      ErrorF ("winInitVisualsPrimaryDD - Unknown screen depth\n");
-      return FALSE;
-    }
-
-  ErrorF ("winInitVisualsPrimaryDD - Returning\n");
-
-  return TRUE;
-}
-
-
-static Bool
-winAdjustVideoModePrimaryDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  HDC			hdc = NULL;
-  DWORD			dwBPP;
-
-  /* We're in serious trouble if we can't get a DC */
-  hdc = GetDC (NULL);
-  if (hdc == NULL)
-    {
-      ErrorF ("winAdjustVideoModePrimaryDD - GetDC failed\n");
-      return FALSE;
-    }
-
-  /* Query GDI for current display depth */
-  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
-
-  /* DirectDraw can only change the depth in fullscreen mode */
-  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
-    {
-      /* No -depth parameter passed, let the user know the depth being used */
-      ErrorF ("winAdjustVideoModePrimaryDD - Using Windows display "
-	      "depth of %d bits per pixel\n", (int) dwBPP);
-
-      /* Use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-  else if (pScreenInfo->fFullScreen
-	   && pScreenInfo->dwBPP != dwBPP)
-    {
-      /* FullScreen, and GDI depth differs from -depth parameter */
-      ErrorF ("winAdjustVideoModePrimaryDD - FullScreen, using command "
-	      "line depth: %d\n", (int) pScreenInfo->dwBPP);
-    }
-  else if (dwBPP != pScreenInfo->dwBPP)
-    {
-      /* Windowed, and GDI depth differs from -depth parameter */
-      ErrorF ("winAdjustVideoModePrimaryDD - Windowed, command line "
-	      "depth: %d, using depth: %d\n",
-	      (int) pScreenInfo->dwBPP, (int) dwBPP);
-
-      /* We'll use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-  
-  /* Release our DC */
-  ReleaseDC (NULL, hdc);
-
-  return TRUE;
-}
-
-
-/*
- * We need to blit our offscreen fb to
- * the screen when we are activated, and we need to point
- * the fb code back to the primary surface memory.
- */
-
-static Bool
-winActivateAppPrimaryDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  RECT			rcSrc, rcClient;
-  HRESULT		ddrval = DD_OK;
-
-  /* Check for errors */
-  if (pScreenPriv == NULL
-      || pScreenPriv->pddsPrimary == NULL
-      || pScreenPriv->pddsOffscreen == NULL)
-    return FALSE;
-
-  /* Check for do-nothing */
-  if (!pScreenPriv->fActive)
-    return TRUE;
-  
-  /* We are activating */
-  ddrval = IDirectDrawSurface2_IsLost (pScreenPriv->pddsOffscreen);
-  if (ddrval == DD_OK)
-    {
-      IDirectDrawSurface2_Unlock (pScreenPriv->pddsOffscreen,
-				  NULL);
-      /*
-       * We don't check for an error from Unlock, because it
-       * doesn't matter if the Unlock failed.
-       */
-    }
-
-  /* Restore both surfaces, just cause I like it that way */
-  IDirectDrawSurface2_Restore (pScreenPriv->pddsOffscreen);
-  IDirectDrawSurface2_Restore (pScreenPriv->pddsPrimary);
-			      
-  /* Get client area in screen coords */
-  GetClientRect (pScreenPriv->hwndScreen, &rcClient);
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&rcClient, 2);
-
-  /* Setup a source rectangle */
-  rcSrc.left = 0;
-  rcSrc.top = 0;
-  rcSrc.right = pScreenInfo->dwWidth;
-  rcSrc.bottom = pScreenInfo->dwHeight;
-
-  ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
-				    &rcClient,
-				    pScreenPriv->pddsOffscreen,
-				    &rcSrc,
-				    DDBLT_WAIT,
-				    NULL);
-  if (ddrval != DD_OK)
-    FatalError ("winActivateAppPrimaryDD () - Failed blitting offscreen "
-		"surface to primary surface %08x\n", (unsigned int) ddrval);
-  
-  /* Lock the primary surface */
-  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsPrimary,
-				     &rcClient,
-				     pScreenPriv->pddsdPrimary,
-				     DDLOCK_WAIT,
-				     NULL);
-  if (ddrval != DD_OK
-      || pScreenPriv->pddsdPrimary->lpSurface == NULL)
-    FatalError ("winActivateAppPrimaryDD () - Could not lock "
-		"primary surface\n");
-
-  /* Notify FB of the new memory pointer */
-  winUpdateFBPointer (pScreen,
-		      pScreenPriv->pddsdPrimary->lpSurface);
-
-  /*
-   * Register the Alt-Tab combo as a hotkey so we can copy
-   * the primary framebuffer before the display mode changes
-   */
-  RegisterHotKey (pScreenPriv->hwndScreen, 1, MOD_ALT, 9);
-
-  return TRUE;
-}
-
-
-/*
- * Handle the Alt+Tab hotkey.
- *
- * We need to save the primary fb to an offscreen fb when
- * we get deactivated, and point the fb code at the offscreen
- * fb for the duration of the deactivation.
- */
-
-static Bool
-winHotKeyAltTabPrimaryDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  RECT			rcClient, rcSrc;
-  HRESULT		ddrval = DD_OK;
-
-  ErrorF ("\nwinHotKeyAltTabPrimaryDD\n\n");
-
-  /* Alt+Tab was pressed, we will lose focus very soon */
-  pScreenPriv->fActive = FALSE;
-  
-  /* Check for error conditions */
-  if (pScreenPriv->pddsPrimary == NULL
-      || pScreenPriv->pddsOffscreen == NULL)
-    return FALSE;
-
-  /* Get client area in screen coords */
-  GetClientRect (pScreenPriv->hwndScreen, &rcClient);
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&rcClient, 2);
-
-  /* Did we loose the primary surface? */
-  ddrval = IDirectDrawSurface2_IsLost (pScreenPriv->pddsPrimary);
-  if (ddrval == DD_OK)
-    {
-      ddrval = IDirectDrawSurface2_Unlock (pScreenPriv->pddsPrimary,
-					   NULL);
-      if (FAILED (ddrval))
-	FatalError ("winHotKeyAltTabPrimaryDD - Failed unlocking primary "
-		    "surface\n");
-    }
-
-  /* Setup a source rectangle */
-  rcSrc.left = 0;
-  rcSrc.top = 0;
-  rcSrc.right = pScreenInfo->dwWidth;
-  rcSrc.bottom = pScreenInfo->dwHeight;
-
-      /* Blit the primary surface to the offscreen surface */
-  ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsOffscreen,
-				    NULL, /* should be rcDest */
-				    pScreenPriv->pddsPrimary,
-				    NULL,
-				    DDBLT_WAIT,
-				    NULL);
-  if (ddrval == DDERR_SURFACELOST)
-    {
-      IDirectDrawSurface2_Restore (pScreenPriv->pddsOffscreen);  
-      IDirectDrawSurface2_Restore (pScreenPriv->pddsPrimary);
-		  		  
-      /* Blit the primary surface to the offscreen surface */
-      ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsOffscreen,
-					NULL,
-					pScreenPriv->pddsPrimary,
-					NULL,
-					DDBLT_WAIT,
-					NULL);
-      if (FAILED (ddrval))
-	FatalError ("winHotKeyAltTabPrimaryDD - Failed blitting primary "
-		    "surface to offscreen surface: %08x\n",
-		    (unsigned int) ddrval);
-    }
-  else
-    {
-      FatalError ("winHotKeyAltTabPrimaryDD - Unknown error from "
-		  "Blt: %08dx\n", (unsigned int) ddrval);
-    }
-
-  /* Lock the offscreen surface */
-  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsOffscreen,
-				     NULL,
-				     pScreenPriv->pddsdOffscreen,
-				     DDLOCK_WAIT,
-				     NULL);
-  if (ddrval != DD_OK
-      || pScreenPriv->pddsdPrimary->lpSurface == NULL)
-    FatalError ("winHotKeyAltTabPrimaryDD - Could not lock "
-		"offscreen surface\n");
-
-  /* Notify FB of the new memory pointer */
-  winUpdateFBPointer (pScreen,
-		      pScreenPriv->pddsdOffscreen->lpSurface);
-
-  /* Unregister our hotkey */
-  UnregisterHotKey (pScreenPriv->hwndScreen, 1);
-
-  return TRUE;
-}
-
-
-/* Set engine specific functions */
-Bool
-winSetEngineFunctionsPrimaryDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  
-  /* Set our pointers */
-  pScreenPriv->pwinAllocateFB = winAllocateFBPrimaryDD;
-  pScreenPriv->pwinShadowUpdate
-    = (winShadowUpdateProcPtr) (void (*)(void))NoopDDA;
-  pScreenPriv->pwinCloseScreen = winCloseScreenPrimaryDD;
-  pScreenPriv->pwinInitVisuals = winInitVisualsPrimaryDD;
-  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModePrimaryDD;
-  if (pScreenInfo->fFullScreen)
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
-  else
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
-  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitFB;
-  pScreenPriv->pwinBltExposedRegions
-    = (winBltExposedRegionsProcPtr) (void (*)(void))NoopDDA;
-  pScreenPriv->pwinActivateApp = winActivateAppPrimaryDD;
-  pScreenPriv->pwinHotKeyAltTab = winHotKeyAltTabPrimaryDD;
-#ifdef XWIN_MULTIWINDOW
-  pScreenPriv->pwinFinishCreateWindowsWindow =
-    (winFinishCreateWindowsWindowProcPtr) (void (*)(void))NoopDDA;
-#endif
-
-  return TRUE;
-}
diff --git a/hw/xwin/winpixmap.c b/hw/xwin/winpixmap.c
deleted file mode 100644
index 050c71a..0000000
--- a/hw/xwin/winpixmap.c
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	drewry, september 1986
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * Local prototypes
- */
-
-#if 0
-static void
-winXRotatePixmapNativeGDI (PixmapPtr pPix, int rw);
-
-static void
-winYRotatePixmapNativeGDI (PixmapPtr pPix, int rh);
-
-static void
-winCopyRotatePixmapNativeGDI (PixmapPtr psrcPix, PixmapPtr *ppdstPix,
-			      int xrot, int yrot);
-#endif
-
-
-/* See Porting Layer Definition - p. 34 */
-/* See mfb/mfbpixmap.c - mfbCreatePixmap() */
-PixmapPtr
-winCreatePixmapNativeGDI (ScreenPtr pScreen,
-			  int iWidth, int iHeight,
-			  int iDepth, unsigned usage_hint)
-{
-  winPrivPixmapPtr	pPixmapPriv = NULL;
-  PixmapPtr		pPixmap = NULL;
-
-  /* Allocate pixmap memory */
-  pPixmap = AllocatePixmap (pScreen, 0);
-  if (!pPixmap)
-    {
-      ErrorF ("winCreatePixmapNativeGDI () - Couldn't allocate a pixmap\n");
-      return NullPixmap;
-    }
-
-#if CYGDEBUG
-  winDebug ("winCreatePixmap () - w %d h %d d %d uh %d bw %d\n",
-	  iWidth, iHeight, iDepth, usage_hint,
-	  PixmapBytePad (iWidth, iDepth));
-#endif
-
-  /* Setup pixmap values */
-  pPixmap->drawable.type = DRAWABLE_PIXMAP;
-  pPixmap->drawable.class = 0;
-  pPixmap->drawable.pScreen = pScreen;
-  pPixmap->drawable.depth = iDepth;
-  pPixmap->drawable.bitsPerPixel = BitsPerPixel (iDepth);
-  pPixmap->drawable.id = 0;
-  pPixmap->drawable.serialNumber = NEXT_SERIAL_NUMBER;
-  pPixmap->drawable.x = 0;
-  pPixmap->drawable.y = 0;
-  pPixmap->drawable.width = iWidth;
-  pPixmap->drawable.height = iHeight;
-  pPixmap->devKind = 0;
-  pPixmap->refcnt = 1;
-  pPixmap->devPrivate.ptr = NULL;
-  pPixmap->usage_hint = usage_hint;
-
-  /* Pixmap privates are allocated by AllocatePixmap */
-  pPixmapPriv = winGetPixmapPriv (pPixmap);
-
-  /* Initialize pixmap privates */
-  pPixmapPriv->hBitmap = NULL;
-  pPixmapPriv->hdcSelected = NULL;
-  pPixmapPriv->pbBits = NULL;
-  pPixmapPriv->dwScanlineBytes = PixmapBytePad (iWidth, iDepth);
-
-  /* Check for zero width or height pixmaps */
-  if (iWidth == 0 || iHeight == 0)
-    {
-      /* Don't allocate a real pixmap, just set fields and return */
-      return pPixmap;
-    }
-
-  /* Create a DIB for the pixmap */
-  pPixmapPriv->hBitmap = winCreateDIBNativeGDI (iWidth, iHeight, iDepth,
-						&pPixmapPriv->pbBits,
-						(BITMAPINFO **) &pPixmapPriv->pbmih);
-
-#if CYGDEBUG
-  winDebug ("winCreatePixmap () - Created a pixmap %08x, %dx%dx%d, for " \
-	  "screen: %08x\n",
-	  pPixmapPriv->hBitmap, iWidth, iHeight, iDepth, pScreen);
-#endif
-
-  return pPixmap;
-}
-
-
-/* 
- * See Porting Layer Definition - p. 35
- *
- * See mfb/mfbpixmap.c - mfbDestroyPixmap()
- */
-
-Bool
-winDestroyPixmapNativeGDI (PixmapPtr pPixmap)
-{
-  winPrivPixmapPtr		pPixmapPriv = NULL;
-  
-#if CYGDEBUG
-  winDebug ("winDestroyPixmapNativeGDI ()\n");
-#endif
-
-  /* Bail early if there is not a pixmap to destroy */
-  if (pPixmap == NULL)
-    {
-      ErrorF ("winDestroyPixmapNativeGDI () - No pixmap to destroy\n");
-      return TRUE;
-    }
-
-  /* Get a handle to the pixmap privates */
-  pPixmapPriv = winGetPixmapPriv (pPixmap);
-
-#if CYGDEBUG
-  winDebug ("winDestroyPixmapNativeGDI - pPixmapPriv->hBitmap: %08x\n",
-	  pPixmapPriv->hBitmap);
-#endif
-
-  /* Decrement reference count, return if nonzero */
-  --pPixmap->refcnt;
-  if (pPixmap->refcnt != 0)
-    return TRUE;
-
-  /* Free GDI bitmap */
-  if (pPixmapPriv->hBitmap) DeleteObject (pPixmapPriv->hBitmap);
-  
-  /* Free the bitmap info header memory */
-  if (pPixmapPriv->pbmih != NULL)
-    {
-      free (pPixmapPriv->pbmih);
-      pPixmapPriv->pbmih = NULL;
-    }
-
-  /* Free the pixmap memory */
-  free (pPixmap);
-  pPixmap = NULL;
-
-  return TRUE;
-}
-
-
-/* 
- * Not used yet
- */
-
-Bool
-winModifyPixmapHeaderNativeGDI (PixmapPtr pPixmap,
-				int iWidth, int iHeight,
-				int iDepth,
-				int iBitsPerPixel,
-				int devKind,
-				pointer pPixData)
-{
-  FatalError ("winModifyPixmapHeaderNativeGDI ()\n");
-  return TRUE;
-}
-
-
-#if 0
-/* 
- * Not used yet.
- * See cfb/cfbpixmap.c
- */
-
-static void
-winXRotatePixmapNativeGDI (PixmapPtr pPix, int rw)
-{
-  ErrorF ("winXRotatePixmap()\n");
-  /* fill in this function, look at CFB */
-}
-
-
-/*
- * Not used yet.
- * See cfb/cfbpixmap.c
- */
-static void
-winYRotatePixmapNativeGDI (PixmapPtr pPix, int rh)
-{
-  ErrorF ("winYRotatePixmap()\n");
-  /* fill in this function, look at CFB */
-}
-
-
-/* 
- * Not used yet.
- * See cfb/cfbpixmap.c
- */
-
-static void
-winCopyRotatePixmapNativeGDI (PixmapPtr psrcPix, PixmapPtr *ppdstPix,
-			      int xrot, int yrot)
-{
-  ErrorF ("winCopyRotatePixmap()\n");
-  /* fill in this function, look at CFB */
-}
-#endif
diff --git a/hw/xwin/winpolyline.c b/hw/xwin/winpolyline.c
deleted file mode 100644
index db9dd34..0000000
--- a/hw/xwin/winpolyline.c
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-/* See Porting Layer Definition - p. 50 */
-void
-winPolyLineNativeGDI (DrawablePtr	pDrawable,
-		      GCPtr		pGC,
-		      int		mode,
-		      int		npt,
-		      DDXPointPtr	ppt)
-{
-  switch (pGC->lineStyle)
-    {
-    case LineSolid:
-      if (pGC->lineWidth == 0)
-	return miZeroLine (pDrawable, pGC, mode, npt, ppt);
-      else
-	miWideLine (pDrawable, pGC, mode, npt, ppt);
-      break;
-    case LineOnOffDash:
-    case LineDoubleDash:
-      miWideDash (pDrawable, pGC, mode, npt, ppt);
-      break;
-    }
-}
diff --git a/hw/xwin/winprefs.c b/hw/xwin/winprefs.c
deleted file mode 100644
index 30e587d..0000000
--- a/hw/xwin/winprefs.c
+++ /dev/null
@@ -1,822 +0,0 @@
-/*
- * Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name of the XFree86 Project
- * shall not be used in advertising or otherwise to promote the sale, use
- * or other dealings in this Software without prior written authorization
- * from the XFree86 Project.
- *
- * Authors:     Earle F. Philhower, III
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include <stdio.h>
-#include <stdlib.h>
-#ifdef __CYGWIN__
-#include <sys/resource.h>
-#endif
-#include "win.h"
-
-#include <X11/Xwindows.h>
-#include <shellapi.h>
-
-#include "winprefs.h"
-#include "winmultiwindowclass.h"
-
-/* Where will the custom menu commands start counting from? */
-#define STARTMENUID WM_USER
-
-/* External global variables */
-#ifdef XWIN_MULTIWINDOW
-extern DWORD g_dwCurrentThreadID;
-#endif
-
-extern const char *winGetBaseDir(void);
-
-/* From winmultiwindowflex.l, the real parser */
-extern void parse_file (FILE *fp);
-
-/* From winprefyacc.y, the pref structure loaded by the parser */
-extern WINPREFS pref;
-
-/* The global X default icon */
-extern HICON		g_hIconX;
-extern HICON		g_hSmallIconX;
-
-/* Currently in use command ID, incremented each new menu item created */
-static int g_cmdid = STARTMENUID;
-
-
-/* Defined in DIX */
-extern char *display;
-
-/* Local function to handle comma-ified icon names */
-static HICON
-LoadImageComma (char *fname, int sx, int sy, int flags);
-
-
-/*
- * Creates or appends a menu from a MENUPARSED structure
- */
-static HMENU
-MakeMenu (char *name,
-	  HMENU editMenu,
-	  int editItem)
-{
-  int i;
-  int item;
-  MENUPARSED *m;
-  HMENU hmenu, hsub;
-
-  for (i=0; i<pref.menuItems; i++)
-    {
-      if (!strcmp(name, pref.menu[i].menuName))
-	break;
-    }
-  
-  /* Didn't find a match, bummer */
-  if (i==pref.menuItems)
-    {
-      ErrorF("MakeMenu: Can't find menu %s\n", name);
-      return NULL;
-    }
-  
-  m = &(pref.menu[i]);
-
-  if (editMenu)
-    {
-      hmenu = editMenu;
-      item = editItem;
-    }
-  else
-    {
-      hmenu = CreatePopupMenu();
-      if (!hmenu)
-	{
-	  ErrorF("MakeMenu: Unable to CreatePopupMenu() %s\n", name);
-	  return NULL;
-	}
-      item = 0;
-    }
-
-  /* Add the menu items */
-  for (i=0; i<m->menuItems; i++)
-    {
-      /* Only assign IDs one time... */
-      if ( m->menuItem[i].commandID == 0 )
-	m->menuItem[i].commandID = g_cmdid++;
-
-      switch (m->menuItem[i].cmd)
-	{
-	case CMD_EXEC:
-	case CMD_ALWAYSONTOP:
-	case CMD_RELOAD:
-	  InsertMenu (hmenu,
-		      item,
-		      MF_BYPOSITION|MF_ENABLED|MF_STRING,
-		      m->menuItem[i].commandID,
-		      m->menuItem[i].text);
-	  break;
-	  
-	case CMD_SEPARATOR:
-	  InsertMenu (hmenu,
-		      item,
-		      MF_BYPOSITION|MF_SEPARATOR,
-		      0,
-		      NULL);
-	  break;
-	  
-	case CMD_MENU:
-	  /* Recursive! */
-	  hsub = MakeMenu (m->menuItem[i].param, 0, 0);
-	  if (hsub)
-	    InsertMenu (hmenu,
-			item,
-			MF_BYPOSITION|MF_POPUP|MF_ENABLED|MF_STRING,
-			(UINT_PTR)hsub,
-			m->menuItem[i].text);
-	  break;
-	}
-
-      /* If item==-1 (means to add at end of menu) don't increment) */
-      if (item>=0)
-	item++;
-    }
-
-  return hmenu;
-}
-
-
-#ifdef XWIN_MULTIWINDOW
-/*
- * Callback routine that is executed once per window class.
- * Removes or creates custom window settings depending on LPARAM
- */
-static wBOOL CALLBACK
-ReloadEnumWindowsProc (HWND hwnd, LPARAM lParam)
-{
-  HICON   hicon;
-  Window  wid;
-
-  if (!hwnd) {
-    ErrorF("ReloadEnumWindowsProc: hwnd==NULL!\n");
-    return FALSE;
-  }
-
-  /* It's our baby, either clean or dirty it */
-  if (lParam==FALSE) 
-    {
-      hicon = (HICON)GetClassLong(hwnd, GCL_HICON);
-
-      /* Unselect any icon in the class structure */
-      SetClassLong (hwnd, GCL_HICON, (LONG)LoadIcon (NULL, IDI_APPLICATION));
-
-      /* If it's generated on-the-fly, get rid of it, will regen */
-      winDestroyIcon (hicon);
-     
-      hicon = (HICON)GetClassLong(hwnd, GCL_HICONSM);
-
-      /* Unselect any icon in the class structure */
-      SetClassLong (hwnd, GCL_HICONSM, 0);
-
-      /* If it's generated on-the-fly, get rid of it, will regen */
-      winDestroyIcon (hicon);
-      
-      /* Remove any menu additions, use bRevert flag */
-      GetSystemMenu (hwnd, TRUE);
-      
-      /* This window is now clean of our taint */
-    }
-  else
-    {
-      /* Make the icon default, dynamic, or from xwinrc */
-      SetClassLong (hwnd, GCL_HICON, (LONG)g_hIconX);
-      SetClassLong (hwnd, GCL_HICONSM, (LONG)g_hSmallIconX);
-      wid = (Window)GetProp (hwnd, WIN_WID_PROP);
-      if (wid)
-	winUpdateIcon (wid);
-      /* Update the system menu for this window */
-      SetupSysMenu ((unsigned long)hwnd);
-
-      /* That was easy... */
-    }
-
-  return TRUE;
-}
-#endif
-
-
-/*
- * Removes any custom icons in classes, custom menus, etc.
- * Frees all members in pref structure.
- * Reloads the preferences file.
- * Set custom icons and menus again.
- */
-static void
-ReloadPrefs (void)
-{
-  int i;
-
-#ifdef XWIN_MULTIWINDOW
-  /* First, iterate over all windows replacing their icon with system */
-  /* default one and deleting any custom system menus                 */
-  EnumThreadWindows (g_dwCurrentThreadID, ReloadEnumWindowsProc, FALSE);
-#endif
-  
-  /* Now, free/clear all info from our prefs structure */
-  for (i=0; i<pref.menuItems; i++)
-    free (pref.menu[i].menuItem);
-  free (pref.menu);
-  pref.menu = NULL;
-  pref.menuItems = 0;
-
-  pref.rootMenuName[0] = 0;
-
-  free (pref.sysMenu);
-  pref.sysMenuItems = 0;
-
-  pref.defaultSysMenuName[0] = 0;
-  pref.defaultSysMenuPos = 0;
-
-  pref.iconDirectory[0] = 0;
-  pref.defaultIconName[0] = 0;
-  pref.trayIconName[0] = 0;
-
-  for (i=0; i<pref.iconItems; i++)
-    if (pref.icon[i].hicon)
-      DestroyIcon ((HICON)pref.icon[i].hicon);
-  free (pref.icon);
-  pref.icon = NULL;
-  pref.iconItems = 0;
-  
-  /* Free global default X icon */
-  if (g_hIconX) 
-    DestroyIcon (g_hIconX);
-  if (g_hSmallIconX)
-    DestroyIcon (g_hSmallIconX);  
-
-  /* Reset the custom command IDs */
-  g_cmdid = STARTMENUID;
-
-  /* Load the updated resource file */
-  LoadPreferences();
-
-  g_hIconX = NULL;
-  g_hSmallIconX = NULL;
-
-#ifdef XWIN_MULTIWINDOW
-  winInitGlobalIcons();
-#endif
-  
-#ifdef XWIN_MULTIWINDOW
-  /* Rebuild the icons and menus */
-  EnumThreadWindows (g_dwCurrentThreadID, ReloadEnumWindowsProc, TRUE);
-#endif
-
-  /* Whew, done */
-}
-
-/*
- * Check/uncheck the ALWAYSONTOP items in this menu
- */
-void
-HandleCustomWM_INITMENU(unsigned long hwndIn,
-			unsigned long hmenuIn)
-{
-  HWND    hwnd;
-  HMENU   hmenu;
-  DWORD   dwExStyle;
-  int     i, j;
-
-  hwnd = (HWND)hwndIn;
-  hmenu = (HMENU)hmenuIn;
-  if (!hwnd || !hmenu) 
-    return;
-  
-  if (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_TOPMOST)
-    dwExStyle = MF_BYCOMMAND | MF_CHECKED;
-  else
-    dwExStyle = MF_BYCOMMAND | MF_UNCHECKED;
-
-  for (i=0; i<pref.menuItems; i++)
-    for (j=0; j<pref.menu[i].menuItems; j++)
-      if (pref.menu[i].menuItem[j].cmd==CMD_ALWAYSONTOP)
-	CheckMenuItem (hmenu, pref.menu[i].menuItem[j].commandID, dwExStyle );
-  
-}
-    
-/*
- * Searches for the custom WM_COMMAND command ID and performs action.
- * Return TRUE if command is proccessed, FALSE otherwise.
- */
-Bool
-HandleCustomWM_COMMAND (unsigned long hwndIn,
-			int           command)
-{
-  HWND hwnd;
-  int i, j;
-  MENUPARSED *m;
-  DWORD			dwExStyle;
-
-  hwnd = (HWND)hwndIn;
-
-  if (!command)
-    return FALSE;
-
-  for (i=0; i<pref.menuItems; i++)
-    {
-      m = &(pref.menu[i]);
-      for (j=0; j<m->menuItems; j++)
-	{
-	  if (command==m->menuItem[j].commandID)
-	    {
-	      /* Match! */
-	      switch(m->menuItem[j].cmd)
-		{
-#ifdef __CYGWIN__
-		case CMD_EXEC:
-		  if (fork()==0)
-		    {
-		      struct rlimit rl;
-		      unsigned long i;
-
-		      /* Close any open descriptors except for STD* */
-		      getrlimit (RLIMIT_NOFILE, &rl);
-		      for (i = STDERR_FILENO+1; i < rl.rlim_cur; i++)
-			close(i);
-
-		      /* Disassociate any TTYs */
-		      setsid();
-
-		      execl ("/bin/sh",
-			     "/bin/sh",
-			     "-c",
-			     m->menuItem[j].param,
-			     NULL);
-		      exit (0);
-		    }
-		  else
-		    return TRUE;
-		  break;
-#else
-		case CMD_EXEC:
-                  {
-		    /* Start process without console window */
-		    STARTUPINFO start;
-		    PROCESS_INFORMATION child;
-
-		    memset (&start, 0, sizeof (start));
-		    start.cb = sizeof (start);
-		    start.dwFlags = STARTF_USESHOWWINDOW;
-		    start.wShowWindow = SW_HIDE;
-
-		    memset (&child, 0, sizeof (child));
-
-		    if (CreateProcess (NULL, m->menuItem[j].param, NULL, NULL, FALSE, 0,
-				       NULL, NULL, &start, &child))
-		    {
-			CloseHandle (child.hThread);
-			CloseHandle (child.hProcess);
-		    }
-		    else
-			MessageBox(NULL, m->menuItem[j].param, "Mingrc Exec Command Error!", MB_OK | MB_ICONEXCLAMATION);
-                  }
-		  return TRUE;
-#endif
-		case CMD_ALWAYSONTOP:
-		  if (!hwnd)
-		    return FALSE;
-
-		  /* Get extended window style */
-		  dwExStyle = GetWindowLong (hwnd, GWL_EXSTYLE);
-		  
-		  /* Handle topmost windows */
-		  if (dwExStyle & WS_EX_TOPMOST)
-		    SetWindowPos (hwnd,
-				  HWND_NOTOPMOST,
-				  0, 0,
-				  0, 0,
-				  SWP_NOSIZE | SWP_NOMOVE);
-		  else
-		    SetWindowPos (hwnd,
-				  HWND_TOPMOST,
-				  0, 0,
-				  0, 0,
-				  SWP_NOSIZE | SWP_NOMOVE);
-#if XWIN_MULTIWINDOW
-		  /* Reflect the changed Z order */
-		  winReorderWindowsMultiWindow ();
-#endif
-		  return TRUE;
-		  
-		case CMD_RELOAD:
-		  ReloadPrefs();
-		  return TRUE;
-
-		default:
-		  return FALSE;
-	      }
-	    } /* match */
-	} /* for j */
-    } /* for i */
-
-  return FALSE;
-}
-
-
-#ifdef XWIN_MULTIWINDOW
-/*
- * Add the default or a custom menu depending on the class match
- */
-void
-SetupSysMenu (unsigned long hwndIn)
-{
-  HWND    hwnd;
-  HMENU	  sys;
-  int     i;
-  WindowPtr pWin;
-  char *res_name, *res_class;
-
-  hwnd = (HWND)hwndIn;
-  if (!hwnd)
-    return;
-
-  pWin = GetProp (hwnd, WIN_WINDOW_PROP);
-  
-  sys = GetSystemMenu (hwnd, FALSE);
-  if (!sys)
-    return;
-
-  if (pWin)
-    {
-      /* First see if there's a class match... */
-      if (winMultiWindowGetClassHint (pWin, &res_name, &res_class))
-	{
-	  for (i=0; i<pref.sysMenuItems; i++)
-	    {
-	      if (!strcmp(pref.sysMenu[i].match, res_name) ||
-		  !strcmp(pref.sysMenu[i].match, res_class) ) 
-		{
-		  free(res_name);
-		  free(res_class);
-  
-		  MakeMenu (pref.sysMenu[i].menuName, sys,
-			    pref.sysMenu[i].menuPos==AT_START?0:-1);
-		  return;
-		}
-	    }
-	  
-	  /* No match, just free alloc'd strings */
-	  free(res_name);
-	  free(res_class);
-	} /* Found wm_class */
-    } /* if pwin */
-
-  /* Fallback to system default */
-  if (pref.defaultSysMenuName[0])
-    {
-      if (pref.defaultSysMenuPos==AT_START)
-	MakeMenu (pref.defaultSysMenuName, sys, 0);
-      else
-	MakeMenu (pref.defaultSysMenuName, sys, -1);
-    }
-}
-#endif
-
-
-/*
- * Possibly add a menu to the toolbar icon
- */
-void
-SetupRootMenu (unsigned long hmenuRoot)
-{
-  HMENU root;
-
-  root = (HMENU)hmenuRoot;
-  if (!root)
-    return;
-
-  if (pref.rootMenuName[0])
-    {
-      MakeMenu(pref.rootMenuName, root, 0);
-    }
-}
-
-
-/*
- * Check for and return an overridden default ICON specified in the prefs
- */
-unsigned long
-winOverrideDefaultIcon(int size)
-{
-  HICON hicon;
-  
-  if (pref.defaultIconName[0])
-    {
-      hicon = LoadImageComma (pref.defaultIconName, size, size, 0);
-      if (hicon==NULL)
-        ErrorF ("winOverrideDefaultIcon: LoadImageComma(%s) failed\n",
-		pref.defaultIconName);
-
-      return (unsigned long)hicon;
-    }
-
-  return 0;
-}
-
-
-/*
- * Return the HICON to use in the taskbar notification area
- */
-unsigned long
-winTaskbarIcon(void)
-{
-  HICON hicon;
-
-  hicon = 0;
-  /* First try and load an overridden, if success then return it */
-  if (pref.trayIconName[0])
-    {
-      hicon = LoadImageComma (pref.trayIconName,
-			      GetSystemMetrics (SM_CXSMICON),
-			      GetSystemMetrics (SM_CYSMICON),
-			      0 );
-    }
-
-  /* Otherwise return the default */
-  if (!hicon)
-    hicon =  (HICON) LoadImage (g_hInstance,
-				MAKEINTRESOURCE(IDI_XWIN),
-				IMAGE_ICON,
-				GetSystemMetrics (SM_CXSMICON),
-				GetSystemMetrics (SM_CYSMICON),
-				0);
-
-  return (unsigned long)hicon;
-}
-
-
-/*
- * Parse a filename to extract an icon:
- *  If fname is exactly ",nnn" then extract icon from our resource
- *  else if it is "file,nnn" then extract icon nnn from that file
- *  else try to load it as an .ico file and if that fails return NULL
- */
-static HICON
-LoadImageComma (char *fname, int sx, int sy, int flags)
-{
-  HICON  hicon;
-  int    index;
-  char   file[PATH_MAX+NAME_MAX+2];
-
-  /* Some input error checking */
-  if (!fname || !fname[0])
-    return NULL;
-
-  index = 0;
-  hicon = NULL;
-
-  if (fname[0]==',')
-    {
-      /* It's the XWIN.EXE resource they want */
-      index = atoi (fname+1);
-      hicon = LoadImage (g_hInstance,
-                        MAKEINTRESOURCE(index),
-                        IMAGE_ICON,
-                        sx,
-                        sy,
-                        flags);
-    }
-  else
-    {
-      file[0] = 0;
-      /* Prepend path if not given a "X:\" filename */
-      if ( !(fname[0] && fname[1]==':' && fname[2]=='\\') )
-        {
-         strcpy (file, pref.iconDirectory);
-         if (pref.iconDirectory[0])
-           if (fname[strlen(fname)-1]!='\\')
-             strcat (file, "\\");
-        }
-      strcat (file, fname);
-
-      if (strrchr (file, ','))
-       {
-         /* Specified as <fname>,<index> */
-
-         *(strrchr (file, ',')) = 0; /* End string at comma */
-         index = atoi (strrchr (fname, ',') + 1);
-         hicon = ExtractIcon (g_hInstance, file, index);
-       }
-      else
-       {
-         /* Just an .ico file... */
-
-         hicon = (HICON)LoadImage (NULL,
-                                   file,
-                                   IMAGE_ICON,
-                                   sx,
-                                   sy,
-                                   LR_LOADFROMFILE|flags);
-       }
-    }
-  return hicon;
-}
-
-/*
- * Check for a match of the window class to one specified in the
- * ICONS{} section in the prefs file, and load the icon from a file
- */
-unsigned long
-winOverrideIcon (unsigned long longWin)
-{
-  WindowPtr pWin = (WindowPtr) longWin;
-  char *res_name, *res_class;
-  int i;
-  HICON hicon;
-  char *wmName;
-
-  if (pWin==NULL)
-    return 0;
-
-  /* If we can't find the class, we can't override from default! */
-  if (!winMultiWindowGetClassHint (pWin, &res_name, &res_class))
-    return 0;
-
-  winMultiWindowGetWMName (pWin, &wmName);
-  
-  for (i=0; i<pref.iconItems; i++) {
-    if (!strcmp(pref.icon[i].match, res_name) ||
-	!strcmp(pref.icon[i].match, res_class) ||
-	(wmName && strstr(wmName, pref.icon[i].match))) 
-      {
-	free (res_name);
-	free (res_class);
-	if (wmName)
-	  free (wmName);
-
-	if (pref.icon[i].hicon)
-	  return pref.icon[i].hicon;
-
-       hicon = LoadImageComma (pref.icon[i].iconFile, 0, 0, LR_DEFAULTSIZE);
-       if (hicon==NULL)
-         ErrorF ("winOverrideIcon: LoadImageComma(%s) failed\n",
-                  pref.icon[i].iconFile);
-
-	pref.icon[i].hicon = (unsigned long)hicon;
-	return (unsigned long)hicon;
-      }
-  }
-  
-  /* Didn't find the icon, fail gracefully */
-  free (res_name);
-  free (res_class);
-  if (wmName)
-    free (wmName);
-
-  return 0;
-}
-
-
-/*
- * Should we free this icon or leave it in memory (is it part of our
- * ICONS{} overrides)?
- */
-int
-winIconIsOverride(unsigned hiconIn)
-{
-  HICON hicon;
-  int i;
-
-  hicon = (HICON)hiconIn;
-
-  if (!hicon)
-    return 0;
-  
-  for (i=0; i<pref.iconItems; i++)
-    if ((HICON)pref.icon[i].hicon == hicon)
-      return 1;
-  
-  return 0;
-}
-
-
-
-/*
- * Try and open ~/.XWinrc and /usr/X11R6/lib/X11/system.XWinrc
- * Load it into prefs structure for use by other functions
- */
-void
-LoadPreferences ()
-{
-  char *home;
-  char fname[PATH_MAX+NAME_MAX+2];
-  FILE *prefFile;
-  char szDisplay[512];
-  char *szEnvDisplay;
-  int i, j;
-  char param[PARAM_MAX+1];
-  char *srcParam, *dstParam;
-
-  /* First, clear all preference settings */
-  memset (&pref, 0, sizeof(pref));
-  prefFile = NULL;
-
-  /* Now try and find a ~/.xwinrc file */
-  home = getenv ("HOME");
-  if (home)
-    {
-      strcpy (fname, home);
-      if (fname[strlen(fname)-1]!='/')
-	strcat (fname, "/");
-      strcat (fname, ".XWinrc");
-      
-      prefFile = fopen (fname, "r");
-      if (prefFile)
-	ErrorF ("winPrefsLoadPreferences: %s\n", fname);
-    }
-
-  /* No home file found, check system default */
-  if (!prefFile)
-    {
-      char buffer[MAX_PATH];
-#ifdef RELOCATE_PROJECTROOT
-      snprintf(buffer, sizeof(buffer), "%s\\system.XWinrc", winGetBaseDir());
-#else
-      strncpy(buffer, PROJECTROOT"/lib/X11/system.XWinrc", sizeof(buffer));
-#endif
-      buffer[sizeof(buffer)-1] = 0;
-      prefFile = fopen (buffer, "r");
-      if (prefFile)
-	ErrorF ("winPrefsLoadPreferences: %s\n", buffer);
-    }
-
-  /* If we could open it, then read the settings and close it */
-  if (prefFile)
-    {
-      parse_file (prefFile);
-      fclose (prefFile);
-    }
-
-  /* Setup a DISPLAY environment variable, need to allocate on heap */
-  /* because putenv doesn't copy the argument... */
-  snprintf (szDisplay, 512, "DISPLAY=127.0.0.1:%s.0", display);
-  szEnvDisplay = (char *)(malloc (strlen(szDisplay)+1));
-  if (szEnvDisplay)
-    {
-      strcpy (szEnvDisplay, szDisplay);
-      putenv (szEnvDisplay);
-    }
-
-  /* Replace any "%display%" in menu commands with display string */
-  snprintf (szDisplay, 512, "127.0.0.1:%s.0", display);
-  for (i=0; i<pref.menuItems; i++)
-    {
-      for (j=0; j<pref.menu[i].menuItems; j++)
-	{
-	  if (pref.menu[i].menuItem[j].cmd==CMD_EXEC)
-	    {
-	      srcParam = pref.menu[i].menuItem[j].param;
-	      dstParam = param;
-	      while (*srcParam) {
-		if (!strncmp(srcParam, "%display%", 9))
-		  {
-		    memcpy (dstParam, szDisplay, strlen(szDisplay));
-		    dstParam += strlen(szDisplay);
-		    srcParam += 9;
-		  }
-		else
-		  {
-		    *dstParam = *srcParam;
-		    dstParam++;
-		    srcParam++;
-		  }
-	      }
-	      *dstParam = 0;
-	      strcpy (pref.menu[i].menuItem[j].param, param);
-	    } /* cmd==cmd_exec */
-	} /* for all menuitems */
-    } /* for all menus */
-
-}
diff --git a/hw/xwin/winprefs.h b/hw/xwin/winprefs.h
deleted file mode 100644
index d9e09de..0000000
--- a/hw/xwin/winprefs.h
+++ /dev/null
@@ -1,162 +0,0 @@
-#if !defined(WINPREFS_H)
-#define WINPREFS_H
-/*
- * Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name of the XFree86 Project
- * shall not be used in advertising or otherwise to promote the sale, use
- * or other dealings in this Software without prior written authorization
- * from the XFree86 Project.
- *
- * Authors:     Earle F. Philhower, III
- */
-
-/* Need Bool */
-#include <X11/Xdefs.h>
-/* Need TRUE */
-#include "misc.h"
-
-/* Need to know how long paths can be... */
-#include <limits.h>
-/* Xwindows redefines PATH_MAX to at least 1024 */
-#include <X11/Xwindows.h>
-
-#ifndef NAME_MAX
-#define NAME_MAX PATH_MAX
-#endif
-#define MENU_MAX 128   /* Maximum string length of a menu name or item */
-#define PARAM_MAX (4*PATH_MAX)  /* Maximum length of a parameter to a MENU */
-
-
-/* Supported commands in a MENU {} statement */
-typedef enum MENUCOMMANDTYPE
-{
-  CMD_EXEC,         /* /bin/sh -c the parameter            */
-  CMD_MENU,         /* Display a popup menu named param    */
-  CMD_SEPARATOR,    /* Menu separator                      */
-  CMD_ALWAYSONTOP,  /* Toggle always-on-top mode           */
-  CMD_RELOAD        /* Reparse the .XWINRC file            */
-} MENUCOMMANDTYPE;
-
-/* Where to place a system menu */
-typedef enum MENUPOSITION
-{
-  AT_START,   /* Place menu at the top of the system menu   */
-  AT_END      /* Put it at the bottom of the menu (default) */
-} MENUPOSITION;
-
-/* Menu item definitions */
-typedef struct MENUITEM
-{
-  char text[MENU_MAX+1];   /* To be displayed in menu */
-  MENUCOMMANDTYPE cmd;     /* What should it do? */
-  char param[PARAM_MAX+1]; /* Any parameters? */
-  unsigned long commandID; /* Windows WM_COMMAND ID assigned at runtime */
-} MENUITEM;
-
-/* A completely read in menu... */
-typedef struct MENUPARSED
-{
-  char menuName[MENU_MAX+1]; /* What's it called in the text? */
-  MENUITEM *menuItem;        /* Array of items */
-  int menuItems;             /* How big's the array? */
-} MENUPARSED;
-
-/* To map between a window and a system menu to add for it */
-typedef struct SYSMENUITEM
-{
-  char match[MENU_MAX+1];    /* String to look for to apply this sysmenu */
-  char menuName[MENU_MAX+1]; /* Which menu to show? Used to set *menu */
-  MENUPOSITION menuPos;      /* Where to place it (ignored in root) */
-} SYSMENUITEM;
-
-/* To redefine icons for certain window types */
-typedef struct ICONITEM
-{
-  char match[MENU_MAX+1];             /* What string to search for? */
-  char iconFile[PATH_MAX+NAME_MAX+2]; /* Icon location, WIN32 path */
-  unsigned long hicon;                /* LoadImage() result */
-} ICONITEM;
-
-typedef struct WINPREFS
-{
-  /* Menu information */
-  MENUPARSED *menu; /* Array of created menus */
-  int menuItems;      /* How big? */
-
-  /* Taskbar menu settings */
-  char rootMenuName[MENU_MAX+1];  /* Menu for taskbar icon */
-
-  /* System menu addition menus */
-  SYSMENUITEM *sysMenu;
-  int sysMenuItems;
-
-  /* Which menu to add to unmatched windows? */
-  char defaultSysMenuName[MENU_MAX+1];
-  MENUPOSITION defaultSysMenuPos;   /* Where to place it */
-
-  /* Icon information */
-  char iconDirectory[PATH_MAX+1]; /* Where do the .icos lie? (Win32 path) */
-  char defaultIconName[NAME_MAX+1];   /* Replacement for x.ico */
-  char trayIconName[NAME_MAX+1]; /* Replacement for tray icon */
-
-  ICONITEM *icon;
-  int iconItems;
-
-  /* Silent exit flag */
-  Bool fSilentExit;
-
-} WINPREFS;
-
-
-
-
-/* Functions */
-void
-LoadPreferences(void);
-
-void
-SetupRootMenu (unsigned long hmenuRoot);
-
-void
-SetupSysMenu (unsigned long hwndIn);
-
-void
-HandleCustomWM_INITMENU(unsigned long hwndIn,
-			unsigned long hmenuIn);
-
-Bool
-HandleCustomWM_COMMAND (unsigned long hwndIn,
-			int           command);
-
-int
-winIconIsOverride (unsigned hiconIn);
-
-unsigned long
-winOverrideIcon (unsigned long longpWin);
-
-unsigned long
-winTaskbarIcon(void);
-
-unsigned long
-winOverrideDefaultIcon(int size);
-#endif
diff --git a/hw/xwin/winprefslex.l b/hw/xwin/winprefslex.l
deleted file mode 100644
index a4c1abc..0000000
--- a/hw/xwin/winprefslex.l
+++ /dev/null
@@ -1,116 +0,0 @@
-%{ # -*- C -*-
-/*
- * Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name of the XFree86 Project
- * shall not be used in advertising or otherwise to promote the sale, use
- * or other dealings in this Software without prior written authorization
- * from the XFree86 Project.
- *
- * Authors:     Earle F. Philhower, III
- */
-/* $XFree86: $ */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include "winprefsyacc.h"
-
-extern YYSTYPE yylval;
-extern char *yytext;
-extern int yyparse(void);
-
-extern void ErrorF (const char* /*f*/, ...);
-
-int yylineno;
-
-/* Copy the parsed string, must be free()d in yacc parser */
-static char *makestr(char *str)
-{
-  char *ptr;
-  ptr = (char*)malloc (strlen(str)+1);
-  if (!ptr)
-    {
-      ErrorF ("winMultiWindowLex:makestr() out of memory\n");
-      exit (-1);
-    }
-  strcpy(ptr, str);
-  return ptr;
-}
-
-%}
-
-%option yylineno
-
-%%
-\#.*[\r\n]              { /* comment */ return NEWLINE; }
-\/\/.*[\r\n]            { /* comment */ return NEWLINE; }
-[\r\n]                  { return NEWLINE; }
-[ \t]+                  { /* ignore whitespace */ }
-MENU                    { return MENU; }
-ICONDIRECTORY           { return ICONDIRECTORY; }
-DEFAULTICON             { return DEFAULTICON; }
-ICONS                   { return ICONS; }
-ROOTMENU                { return ROOTMENU; }
-DEFAULTSYSMENU          { return DEFAULTSYSMENU; }
-SYSMENU                 { return SYSMENU; }
-SEPARATOR               { return SEPARATOR; }
-ATSTART                 { return ATSTART; }
-ATEND                   { return ATEND; }
-EXEC                    { return EXEC; }
-ALWAYSONTOP             { return ALWAYSONTOP; }
-DEBUG                   { return DEBUG; }
-RELOAD                  { return RELOAD; }
-TRAYICON                { return TRAYICON; }
-SILENTEXIT		{ return SILENTEXIT; }
-"{"                     { return LB; }
-"}"                     { return RB; }
-"\""[^\"\r\n]+"\""      { yylval.sVal = makestr(yytext+1); \
-                          yylval.sVal[strlen(yylval.sVal)-1] = 0; \
-                          return STRING; }
-[^ \t\r\n]+             { yylval.sVal = makestr(yytext); \
-                          return STRING; }
-%%
-
-/*
- * Run-of-the mill requirement for yacc
- */
-int
-yywrap ()
-{
-  return 1;
-}
-
-/*
- * Run a file through the yacc parser
- */
-void
-parse_file (FILE *file)
-{
-  if (!file)
-    return; 
-  
-  yylineno = 1;
-  yyin = file;
-  yyparse ();
-}
-
diff --git a/hw/xwin/winprefsyacc.y b/hw/xwin/winprefsyacc.y
deleted file mode 100644
index 2a54ff2..0000000
--- a/hw/xwin/winprefsyacc.y
+++ /dev/null
@@ -1,353 +0,0 @@
-%{
-/*
- * Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name of the XFree86 Project
- * shall not be used in advertising or otherwise to promote the sale, use
- * or other dealings in this Software without prior written authorization
- * from the XFree86 Project.
- *
- * Authors:     Earle F. Philhower, III
- */
-/* $XFree86: $ */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include "winprefs.h"
-
-/* The following give better error messages in bison at the cost of a few KB */
-#define YYERROR_VERBOSE 1
-
-/* The global pref settings */
-WINPREFS pref;
-
-/* The working menu */  
-static MENUPARSED menu;
-
-/* Functions for parsing the tokens into out structure */
-/* Defined at the end section of this file */
-
-static void SetIconDirectory (char *path);
-static void SetDefaultIcon (char *fname);
-static void SetRootMenu (char *menu);
-static void SetDefaultSysMenu (char *menu, int pos);
-static void SetTrayIcon (char *fname);
-
-static void OpenMenu(char *menuname);
-static void AddMenuLine(char *name, MENUCOMMANDTYPE cmd, char *param);
-static void CloseMenu(void);
-
-static void OpenIcons(void);
-static void AddIconLine(char *matchstr, char *iconfile);
-static void CloseIcons(void);
-
-static void OpenSysMenu(void);
-static void AddSysMenuLine(char *matchstr, char *menuname, int pos);
-static void CloseSysMenu(void);
-
-static int yyerror (char *s);
-
-extern void ErrorF (const char* /*f*/, ...);
-extern char *yytext;
-extern int yylex(void);
-
-%}
-
-%union {
-  char *sVal;
-  int iVal;
-}
-
-%token NEWLINE MENU LB RB ICONDIRECTORY DEFAULTICON ICONS DEFAULTSYSMENU
-%token SYSMENU ROOTMENU SEPARATOR ATSTART ATEND EXEC ALWAYSONTOP DEBUG
-%token RELOAD TRAYICON SILENTEXIT
-
-%token <sVal> STRING
-%type <iVal>  atspot
-
-%%
-
-input:	/* empty */
-	| input line
-	;
-
-line:	NEWLINE
-	| command
-	;
-
-
-newline_or_nada:	
-	| NEWLINE newline_or_nada
-	;
-
-command:	defaulticon
-	| icondirectory
-	| menu
-	| icons
-	| sysmenu
-	| rootmenu
-	| defaultsysmenu
-	| debug
-	| trayicon
-	| silentexit
-	;
-
-trayicon:	TRAYICON STRING NEWLINE { SetTrayIcon($2); free($2); }
-	;
-
-rootmenu:	ROOTMENU STRING NEWLINE { SetRootMenu($2); free($2); }
-	;
-
-defaultsysmenu:	DEFAULTSYSMENU STRING atspot NEWLINE { SetDefaultSysMenu($2, $3); free($2); }
-	;
-
-defaulticon:	DEFAULTICON STRING NEWLINE { SetDefaultIcon($2); free($2); }
-	;
-
-icondirectory:	ICONDIRECTORY STRING NEWLINE { SetIconDirectory($2); free($2); }
-	;
-
-menuline:	SEPARATOR NEWLINE newline_or_nada  { AddMenuLine("-", CMD_SEPARATOR, ""); }
-	| STRING ALWAYSONTOP NEWLINE newline_or_nada  { AddMenuLine($1, CMD_ALWAYSONTOP, ""); free($1); }
-	| STRING EXEC STRING NEWLINE newline_or_nada  { AddMenuLine($1, CMD_EXEC, $3); free($1); free($3); }
-	| STRING MENU STRING NEWLINE newline_or_nada  { AddMenuLine($1, CMD_MENU, $3); free($1); free($3); }
-	| STRING RELOAD NEWLINE newline_or_nada  { AddMenuLine($1, CMD_RELOAD, ""); free($1); }
-	;
-
-menulist:	menuline
-	| menuline menulist
-	;
-
-menu:	MENU STRING LB { OpenMenu($2); free($2); } newline_or_nada menulist RB {CloseMenu();}
-	;
-
-iconline:	STRING STRING NEWLINE newline_or_nada { AddIconLine($1, $2); free($1); free($2); }
-	;
-
-iconlist:	iconline
-	| iconline iconlist
-	;
-
-icons:	ICONS LB {OpenIcons();} newline_or_nada iconlist RB {CloseIcons();}
-	;
-
-atspot:	{ $$=AT_END; }
-	| ATSTART { $$=AT_START; }
-	| ATEND { $$=AT_END; }
-	;
-
-sysmenuline:	STRING STRING atspot NEWLINE newline_or_nada { AddSysMenuLine($1, $2, $3); free($1); free($2); }
-	;
-
-sysmenulist:	sysmenuline
-	| sysmenuline sysmenulist
-	;
-
-sysmenu:	SYSMENU LB NEWLINE {OpenSysMenu();} newline_or_nada sysmenulist RB {CloseSysMenu();}
-	;
-
-silentexit:	SILENTEXIT NEWLINE { pref.fSilentExit = TRUE; }
-	;
-
-debug: 	DEBUG STRING NEWLINE { ErrorF("LoadPreferences: %s\n", $2); free($2); }
-	;
-
-
-%%
-/*
- * Errors in parsing abort and print log messages
- */
-static int
-yyerror (char *s) 
-{
-  extern int yylineno; /* Handled by flex internally */
-
-  ErrorF("LoadPreferences: %s line %d\n", s, yylineno);
-  return 1;
-}
-
-/* Miscellaneous functions to store TOKENs into the structure */
-static void
-SetIconDirectory (char *path)
-{
-  strncpy (pref.iconDirectory, path, PATH_MAX);
-  pref.iconDirectory[PATH_MAX] = 0;
-}
-
-static void
-SetDefaultIcon (char *fname)
-{
-  strncpy (pref.defaultIconName, fname, NAME_MAX);
-  pref.defaultIconName[NAME_MAX] = 0;
-}
-
-static void
-SetTrayIcon (char *fname)
-{
-  strncpy (pref.trayIconName, fname, NAME_MAX);
-  pref.trayIconName[NAME_MAX] = 0;
-}
-
-static void
-SetRootMenu (char *menu)
-{
-  strncpy (pref.rootMenuName, menu, MENU_MAX);
-  pref.rootMenuName[MENU_MAX] = 0;
-}
-
-static void
-SetDefaultSysMenu (char *menu, int pos)
-{
-  strncpy (pref.defaultSysMenuName, menu, MENU_MAX);
-  pref.defaultSysMenuName[MENU_MAX] = 0;
-  pref.defaultSysMenuPos = pos;
-}
-
-static void
-OpenMenu (char *menuname)
-{
-  if (menu.menuItem) free(menu.menuItem);
-  menu.menuItem = NULL;
-  strncpy(menu.menuName, menuname, MENU_MAX);
-  menu.menuName[MENU_MAX] = 0;
-  menu.menuItems = 0;
-}
-
-static void
-AddMenuLine (char *text, MENUCOMMANDTYPE cmd, char *param)
-{
-  if (menu.menuItem==NULL)
-    menu.menuItem = (MENUITEM*)malloc(sizeof(MENUITEM));
-  else
-    menu.menuItem = (MENUITEM*)
-      realloc(menu.menuItem, sizeof(MENUITEM)*(menu.menuItems+1));
-
-  strncpy (menu.menuItem[menu.menuItems].text, text, MENU_MAX);
-  menu.menuItem[menu.menuItems].text[MENU_MAX] = 0;
-
-  menu.menuItem[menu.menuItems].cmd = cmd;
-
-  strncpy(menu.menuItem[menu.menuItems].param, param, PARAM_MAX);
-  menu.menuItem[menu.menuItems].param[PARAM_MAX] = 0;
-
-  menu.menuItem[menu.menuItems].commandID = 0;
-
-  menu.menuItems++;
-}
-
-static void
-CloseMenu (void)
-{
-  if (menu.menuItem==NULL || menu.menuItems==0)
-    {
-      ErrorF("LoadPreferences: Empty menu detected\n");
-      return;
-    }
-  
-  if (pref.menuItems)
-    pref.menu = (MENUPARSED*)
-      realloc (pref.menu, (pref.menuItems+1)*sizeof(MENUPARSED));
-  else
-    pref.menu = (MENUPARSED*)malloc (sizeof(MENUPARSED));
-  
-  memcpy (pref.menu+pref.menuItems, &menu, sizeof(MENUPARSED));
-  pref.menuItems++;
-
-  memset (&menu, 0, sizeof(MENUPARSED));
-}
-
-static void 
-OpenIcons (void)
-{
-  if (pref.icon != NULL) {
-    ErrorF("LoadPreferences: Redefining icon mappings\n");
-    free(pref.icon);
-    pref.icon = NULL;
-  }
-  pref.iconItems = 0;
-}
-
-static void
-AddIconLine (char *matchstr, char *iconfile)
-{
-  if (pref.icon==NULL)
-    pref.icon = (ICONITEM*)malloc(sizeof(ICONITEM));
-  else
-    pref.icon = (ICONITEM*)
-      realloc(pref.icon, sizeof(ICONITEM)*(pref.iconItems+1));
-
-  strncpy(pref.icon[pref.iconItems].match, matchstr, MENU_MAX);
-  pref.icon[pref.iconItems].match[MENU_MAX] = 0;
-
-  strncpy(pref.icon[pref.iconItems].iconFile, iconfile, PATH_MAX+NAME_MAX+1);
-  pref.icon[pref.iconItems].iconFile[PATH_MAX+NAME_MAX+1] = 0;
-
-  pref.icon[pref.iconItems].hicon = 0;
-
-  pref.iconItems++;
-}
-
-static void 
-CloseIcons (void)
-{
-}
-
-static void
-OpenSysMenu (void)
-{
-  if (pref.sysMenu != NULL) {
-    ErrorF("LoadPreferences: Redefining system menu\n");
-    free(pref.sysMenu);
-    pref.sysMenu = NULL;
-  }
-  pref.sysMenuItems = 0;
-}
-
-static void
-AddSysMenuLine (char *matchstr, char *menuname, int pos)
-{
-  if (pref.sysMenu==NULL)
-    pref.sysMenu = (SYSMENUITEM*)malloc(sizeof(SYSMENUITEM));
-  else
-    pref.sysMenu = (SYSMENUITEM*)
-      realloc(pref.sysMenu, sizeof(SYSMENUITEM)*(pref.sysMenuItems+1));
-
-  strncpy (pref.sysMenu[pref.sysMenuItems].match, matchstr, MENU_MAX);
-  pref.sysMenu[pref.sysMenuItems].match[MENU_MAX] = 0;
-
-  strncpy (pref.sysMenu[pref.sysMenuItems].menuName, menuname, MENU_MAX);
-  pref.sysMenu[pref.sysMenuItems].menuName[MENU_MAX] = 0;
-
-  pref.sysMenu[pref.sysMenuItems].menuPos = pos;
-
-  pref.sysMenuItems++;
-}
-
-static void
-CloseSysMenu (void)
-{
-}
-
diff --git a/hw/xwin/winpriv.c b/hw/xwin/winpriv.c
deleted file mode 100644
index 29221cf..0000000
--- a/hw/xwin/winpriv.c
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Export window information for the Windows-OpenGL GLX implementation.
- *
- * Authors: Alexander Gottwald
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winpriv.h"
-#include "winwindow.h"
-
-void
-winCreateWindowsWindow (WindowPtr pWin);
-/**
- * Return size and handles of a window.
- * If pWin is NULL, then the information for the root window is requested.
- */ 
-extern void winGetWindowInfo(WindowPtr pWin, winWindowInfoPtr pWinInfo)
-{
-    /* Sanity check */
-    if (pWinInfo == NULL)
-        return;
-
-    winDebug("%s:%d pWin=%p\n", __FUNCTION__, __LINE__, pWin);
-
-    /* a real window was requested */
-    if (pWin != NULL) 
-    {
-        /* Initialize the size information */
-        RECT rect = {
-            pWin->drawable.x,
-            pWin->drawable.y,
-            pWin->drawable.x + pWin->drawable.width,
-            pWin->drawable.y + pWin->drawable.height
-        }, rect_extends;
-        /* Get the window and screen privates */
-        ScreenPtr pScreen = pWin->drawable.pScreen;
-        winPrivScreenPtr pWinScreen = winGetScreenPriv(pScreen);
-        winScreenInfoPtr pScreenInfo = NULL;
-
-        rect_extends = rect;
-        OffsetRect(&rect_extends, -pWin->drawable.x, -pWin->drawable.y);
-
-        if (pWinScreen == NULL) 
-        {
-            ErrorF("winGetWindowInfo: screen has no privates\n");
-            return;
-        }
-        
-        pWinInfo->hwnd = pWinScreen->hwndScreen;
-        pWinInfo->hrgn = NULL;
-        pWinInfo->rect = rect;
-    
-
-        pScreenInfo = pWinScreen->pScreenInfo;
-#ifdef XWIN_MULTIWINDOW
-        /* check for multiwindow mode */
-        if (pScreenInfo->fMultiWindow)
-        {
-            winWindowPriv(pWin);
-
-            if (pWinPriv == NULL)
-            {
-                ErrorF("winGetWindowInfo: window has no privates\n");
-                return;
-            }
-
-            if (pWinPriv->hWnd == NULL)
-            {
-                winCreateWindowsWindow(pWin);
-            }
-            if (pWinPriv->hWnd != NULL) { 
-                
-                /* copy size and window handle */
-                pWinInfo->rect = rect_extends;
-                pWinInfo->hwnd = pWinPriv->hWnd;
-
-                /* Copy window region */
-                if (pWinInfo->hrgn)
-                    DeleteObject(pWinInfo->hrgn);
-                pWinInfo->hrgn = CreateRectRgn(0,0,0,0);
-                CombineRgn(pWinInfo->hrgn, pWinPriv->hRgn, pWinPriv->hRgn, 
-                        RGN_COPY);
-            }
-            
-            return;
-        }
-#endif
-#ifdef XWIN_MULTIWINDOWEXTWM
-        /* check for multiwindow external wm mode */
-        if (pScreenInfo->fMWExtWM)
-        {
-            win32RootlessWindowPtr pRLWinPriv
-                = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, FALSE);
-
-            if (pRLWinPriv == NULL) {
-                ErrorF("winGetWindowInfo: window has no privates\n");
-                return;
-            }
-            
-            if (pRLWinPriv->hWnd != NULL)
-            {
-                /* copy size and window handle */
-                pWinInfo->rect = rect_extends;
-                pWinInfo->hwnd = pRLWinPriv->hWnd;
-            }
-            return;
-        }
-#endif
-    } 
-    else 
-    {
-        RECT rect = {0, 0, 0, 0};
-        ScreenPtr pScreen = g_ScreenInfo[0].pScreen;
-        winPrivScreenPtr pWinScreen = winGetScreenPriv(pScreen);
-
-        pWinInfo->hwnd = NULL;
-        pWinInfo->hrgn = NULL;
-        pWinInfo->rect = rect;
-        
-        if (pWinScreen == NULL)
-        {
-            ErrorF("winGetWindowInfo: screen has no privates\n");
-            return;
-        }
-
-        ErrorF("winGetWindowInfo: returning root window\n");
-
-        pWinInfo->hwnd = pWinScreen->hwndScreen;
-    }
-    return;
-}
diff --git a/hw/xwin/winpriv.h b/hw/xwin/winpriv.h
deleted file mode 100644
index d4505c8..0000000
--- a/hw/xwin/winpriv.h
+++ /dev/null
@@ -1,15 +0,0 @@
-/*
- * Export window information for the Windows-OpenGL GLX implementation.
- *
- * Authors: Alexander Gottwald
- */
-#include <windows.h>
-
-typedef struct
-{
-    HWND    hwnd;
-    HRGN    hrgn;
-    RECT    rect;
-} winWindowInfoRec, *winWindowInfoPtr;
-
-extern void winGetWindowInfo(WindowPtr pWin, winWindowInfoPtr pWinInfo);
diff --git a/hw/xwin/winprocarg.c b/hw/xwin/winprocarg.c
deleted file mode 100755
index 7139cba..0000000
--- a/hw/xwin/winprocarg.c
+++ /dev/null
@@ -1,1551 +0,0 @@
-/*
-
-Copyright 1993, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
-OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall
-not be used in advertising or otherwise to promote the sale, use or
-other dealings in this Software without prior written authorization
-from The Open Group.
-
-*/
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#ifdef XVENDORNAME
-#define VENDOR_STRING XVENDORNAME
-#define VERSION_STRING XORG_RELEASE
-#define VENDOR_CONTACT BUILDERADDR
-#endif
-#include "win.h"
-#include "winconfig.h"
-#include "winprefs.h"
-#include "winmsg.h"
-
-/*
- * References to external symbols
- */
-
-extern int			g_iNumScreens;
-extern winScreenInfo		g_ScreenInfo[];
-extern int			g_iLastScreen;
-extern Bool			g_fInitializedDefaultScreens;
-#ifdef XWIN_CLIPBOARD
-extern Bool			g_fUnicodeClipboard;
-extern Bool			g_fClipboard;
-#endif
-extern int			g_iLogVerbose;
-extern char *			g_pszLogFile;
-#ifdef RELOCATE_PROJECTROOT
-extern Bool			g_fLogFileChanged;
-#endif
-extern Bool			g_fXdmcpEnabled;
-extern char *			g_pszCommandLine;
-extern Bool			g_fKeyboardHookLL;
-extern Bool			g_fNoHelpMessageBox;                     
-extern Bool			g_fSoftwareCursor;
-extern Bool			g_fSilentDupError;
-
-/* globals required by callback function for monitor information */
-struct GetMonitorInfoData {
-    int  requestedMonitor;
-    int  monitorNum;
-    Bool bUserSpecifiedMonitor;
-    Bool bMonitorSpecifiedExists;
-    int  monitorOffsetX;
-    int  monitorOffsetY;
-    int  monitorHeight;
-    int  monitorWidth;
-};
-
-typedef wBOOL (*ENUMDISPLAYMONITORSPROC)(HDC,LPCRECT,MONITORENUMPROC,LPARAM);
-ENUMDISPLAYMONITORSPROC _EnumDisplayMonitors;
-
-wBOOL CALLBACK getMonitorInfo(HMONITOR hMonitor, HDC hdc, LPRECT rect, LPARAM _data);
-
-static Bool QueryMonitor(int index, struct GetMonitorInfoData *data)
-{
-    /* Load EnumDisplayMonitors from DLL */
-    HMODULE user32;
-    FARPROC func;
-    user32 = LoadLibrary("user32.dll");
-    if (user32 == NULL)
-    {
-        winW32Error(2, "Could not open user32.dll");
-        return FALSE;
-    }
-    func = GetProcAddress(user32, "EnumDisplayMonitors");
-    if (func == NULL)
-    {
-        winW32Error(2, "Could not resolve EnumDisplayMonitors: ");
-        return FALSE;
-    }
-    _EnumDisplayMonitors = (ENUMDISPLAYMONITORSPROC)func;
-    
-    /* prepare data */
-    if (data == NULL)
-        return FALSE;
-    memset(data, 0, sizeof(*data));
-    data->requestedMonitor = index;
-
-    /* query information */
-    _EnumDisplayMonitors(NULL, NULL, getMonitorInfo, (LPARAM) data);
-
-    /* cleanup */
-    FreeLibrary(user32);
-    return TRUE;
-}
-
-/*
- * Function prototypes
- */
-
-void
-winLogCommandLine (int argc, char *argv[]);
-
-void
-winLogVersionInfo (void);
-
-#ifdef DDXOSVERRORF
-void OsVendorVErrorF (const char *pszFormat, va_list va_args);
-#endif
-
-void
-winInitializeDefaultScreens (void);
-
-/*
- * Process arguments on the command line
- */
-
-void
-winInitializeDefaultScreens (void)
-{
-  int                   i;
-  DWORD			dwWidth, dwHeight;
-
-  /* Bail out early if default screens have already been initialized */
-  if (g_fInitializedDefaultScreens)
-    return;
-
-  /* Zero the memory used for storing the screen info */
-  ZeroMemory (g_ScreenInfo, MAXSCREENS * sizeof (winScreenInfo));
-
-  /* Get default width and height */
-  /*
-   * NOTE: These defaults will cause the window to cover only
-   * the primary monitor in the case that we have multiple monitors.
-   */
-  dwWidth = GetSystemMetrics (SM_CXSCREEN);
-  dwHeight = GetSystemMetrics (SM_CYSCREEN);
-
-  winErrorFVerb (2, "winInitializeDefaultScreens - w %d h %d\n",
-	  (int) dwWidth, (int) dwHeight);
-
-  /* Set a default DPI, if no parameter was passed */
-  if (monitorResolution == 0)
-    monitorResolution = WIN_DEFAULT_DPI;
-
-  for (i = 0; i < MAXSCREENS; ++i)
-    {
-      g_ScreenInfo[i].dwScreen = i;
-      g_ScreenInfo[i].dwWidth  = dwWidth;
-      g_ScreenInfo[i].dwHeight = dwHeight;
-      g_ScreenInfo[i].dwUserWidth  = dwWidth;
-      g_ScreenInfo[i].dwUserHeight = dwHeight;
-      g_ScreenInfo[i].fUserGaveHeightAndWidth
-	=  WIN_DEFAULT_USER_GAVE_HEIGHT_AND_WIDTH;
-      g_ScreenInfo[i].fUserGavePosition = FALSE;
-      g_ScreenInfo[i].dwBPP = WIN_DEFAULT_BPP;
-      g_ScreenInfo[i].dwClipUpdatesNBoxes = WIN_DEFAULT_CLIP_UPDATES_NBOXES;
-#ifdef XWIN_EMULATEPSEUDO
-      g_ScreenInfo[i].fEmulatePseudo = WIN_DEFAULT_EMULATE_PSEUDO;
-#endif
-      g_ScreenInfo[i].dwRefreshRate = WIN_DEFAULT_REFRESH;
-      g_ScreenInfo[i].pfb = NULL;
-      g_ScreenInfo[i].fFullScreen = FALSE;
-      g_ScreenInfo[i].fDecoration = TRUE;
-#ifdef XWIN_MULTIWINDOWEXTWM
-      g_ScreenInfo[i].fMWExtWM = FALSE;
-      g_ScreenInfo[i].fInternalWM = FALSE;
-#endif
-      g_ScreenInfo[i].fRootless = FALSE;
-#ifdef XWIN_MULTIWINDOW
-      g_ScreenInfo[i].fMultiWindow = FALSE;
-#endif
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-      g_ScreenInfo[i].fMultiMonitorOverride = FALSE;
-#endif
-      g_ScreenInfo[i].fMultipleMonitors = FALSE;
-      g_ScreenInfo[i].fLessPointer = FALSE;
-      g_ScreenInfo[i].fScrollbars = FALSE;
-      g_ScreenInfo[i].fNoTrayIcon = FALSE;
-      g_ScreenInfo[i].iE3BTimeout = WIN_E3B_OFF;
-      g_ScreenInfo[i].dwWidth_mm = (dwWidth / WIN_DEFAULT_DPI)
-	* 25.4;
-      g_ScreenInfo[i].dwHeight_mm = (dwHeight / WIN_DEFAULT_DPI)
-	* 25.4;
-      g_ScreenInfo[i].fUseWinKillKey = WIN_DEFAULT_WIN_KILL;
-      g_ScreenInfo[i].fUseUnixKillKey = WIN_DEFAULT_UNIX_KILL;
-      g_ScreenInfo[i].fIgnoreInput = FALSE;
-      g_ScreenInfo[i].fExplicitScreen = FALSE;
-    }
-
-  /* Signal that the default screens have been initialized */
-  g_fInitializedDefaultScreens = TRUE;
-
-  winErrorFVerb (2, "winInitializeDefaultScreens - Returning\n");
-}
-
-/* See Porting Layer Definition - p. 57 */
-/*
- * INPUT
- * argv: pointer to an array of null-terminated strings, one for
- *   each token in the X Server command line; the first token
- *   is 'XWin.exe', or similar.
- * argc: a count of the number of tokens stored in argv.
- * i: a zero-based index into argv indicating the current token being
- *   processed.
- *
- * OUTPUT
- * return: return the number of tokens processed correctly.
- *
- * NOTE
- * When looking for n tokens, check that i + n is less than argc.  Or,
- *   you may check if i is greater than or equal to argc, in which case
- *   you should display the UseMsg () and return 0.
- */
-
-/* Check if enough arguments are given for the option */
-#define CHECK_ARGS(count) if (i + count >= argc) { UseMsg (); return 0; }
-
-/* Compare the current option with the string. */ 
-#define IS_OPTION(name) (strcmp (argv[i], name) == 0)
-
-int
-ddxProcessArgument (int argc, char *argv[], int i)
-{
-  static Bool		s_fBeenHere = FALSE;
-
-  /* Initialize once */
-  if (!s_fBeenHere)
-    {
-#ifdef DDXOSVERRORF
-      /*
-       * This initialises our hook into VErrorF () for catching log messages
-       * that are generated before OsInit () is called.
-       */
-      OsVendorVErrorFProc = OsVendorVErrorF;
-#endif
-
-      s_fBeenHere = TRUE;
-
-      /* Initialize only if option is not -help */
-      if (!IS_OPTION("-help") && !IS_OPTION("-h") && !IS_OPTION("--help") &&
-          !IS_OPTION("-version") && !IS_OPTION("--version"))
-	{
-
-          /* Log the version information */
-          winLogVersionInfo ();
-
-          /* Log the command line */
-          winLogCommandLine (argc, argv);
-
-	  /*
-	   * Initialize default screen settings.  We have to do this before
-	   * OsVendorInit () gets called, otherwise we will overwrite
-	   * settings changed by parameters such as -fullscreen, etc.
-	   */
-	  winErrorFVerb (2, "ddxProcessArgument - Initializing default "
-			 "screens\n");
-	  winInitializeDefaultScreens ();
-	}
-    }
-
-#if CYGDEBUG
-  winDebug ("ddxProcessArgument - arg: %s\n", argv[i]);
-#endif
-
-  /*
-   * Look for the '-help' and similar options
-   */ 
-  if (IS_OPTION ("-help") || IS_OPTION("-h") || IS_OPTION("--help"))
-    {
-      /* Reset logfile. We don't need that helpmessage in the logfile */  
-      g_pszLogFile = NULL;
-      g_fNoHelpMessageBox = TRUE;
-      UseMsg();
-      exit (0);
-      return 1;
-    }
-
-  if (IS_OPTION ("-version") || IS_OPTION("--version"))
-    {
-      /* Reset logfile. We don't need that versioninfo in the logfile */  
-      g_pszLogFile = NULL;
-      winLogVersionInfo ();
-      exit (0);
-      return 1;
-    }
-
-  /*
-   * Look for the '-screen scr_num [width height]' argument
-   */
-  if (IS_OPTION ("-screen"))
-    {
-      int		iArgsProcessed = 1;
-      int		nScreenNum;
-      int		iWidth, iHeight, iX, iY;
-      int		iMonitor;
-
-#if CYGDEBUG
-      winDebug ("ddxProcessArgument - screen - argc: %d i: %d\n",
-	      argc, i);
-#endif
-
-      /* Display the usage message if the argument is malformed */
-      if (i + 1 >= argc)
-	{
-	  return 0;
-	}
-      
-      /* Grab screen number */
-      nScreenNum = atoi (argv[i + 1]);
-
-      /* Validate the specified screen number */
-      if (nScreenNum < 0 || nScreenNum >= MAXSCREENS)
-        {
-          ErrorF ("ddxProcessArgument - screen - Invalid screen number %d\n",
-		  nScreenNum);
-          UseMsg ();
-	  return 0;
-        }
-
-	  /* look for @m where m is monitor number */
-	  if (i + 2 < argc
-		  && 1 == sscanf(argv[i + 2], "@%d", (int *) &iMonitor)) 
-      {
-        struct GetMonitorInfoData data;
-        if (!QueryMonitor(iMonitor, &data))
-        {
-            ErrorF ("ddxProcessArgument - screen - "
-                    "Querying monitors is not supported on NT4 and Win95\n");
-        } else if (data.bMonitorSpecifiedExists == TRUE) 
-        {
-		  winErrorFVerb(2, "ddxProcessArgument - screen - Found Valid ``@Monitor'' = %d arg\n", iMonitor);
-		  iArgsProcessed = 3;
-		  g_ScreenInfo[nScreenNum].fUserGaveHeightAndWidth = FALSE;
-		  g_ScreenInfo[nScreenNum].fUserGavePosition = TRUE;
-		  g_ScreenInfo[nScreenNum].dwWidth = data.monitorWidth;
-		  g_ScreenInfo[nScreenNum].dwHeight = data.monitorHeight;
-		  g_ScreenInfo[nScreenNum].dwUserWidth = data.monitorWidth;
-		  g_ScreenInfo[nScreenNum].dwUserHeight = data.monitorHeight;
-		  g_ScreenInfo[nScreenNum].dwInitialX = data.monitorOffsetX;
-		  g_ScreenInfo[nScreenNum].dwInitialY = data.monitorOffsetY;
-		}
-		else 
-        {
-		  /* monitor does not exist, error out */
-		  ErrorF ("ddxProcessArgument - screen - Invalid monitor number %d\n",
-				  iMonitor);
-		  UseMsg ();
-		  exit (0);
-		  return 0;
-		}
-	  }
-
-      /* Look for 'WxD' or 'W D' */
-      else if (i + 2 < argc
-	  && 2 == sscanf (argv[i + 2], "%dx%d",
-			  (int *) &iWidth,
-			  (int *) &iHeight))
-	{
-	  winErrorFVerb (2, "ddxProcessArgument - screen - Found ``WxD'' arg\n");
-	  iArgsProcessed = 3;
-	  g_ScreenInfo[nScreenNum].fUserGaveHeightAndWidth = TRUE;
-	  g_ScreenInfo[nScreenNum].dwWidth = iWidth;
-	  g_ScreenInfo[nScreenNum].dwHeight = iHeight;
-	  g_ScreenInfo[nScreenNum].dwUserWidth = iWidth;
-	  g_ScreenInfo[nScreenNum].dwUserHeight = iHeight;
-	  /* Look for WxD+X+Y */
-	  if (2 == sscanf (argv[i + 2], "%*dx%*d+%d+%d",
-			   (int *) &iX,
-			   (int *) &iY))
-	  {
-	    winErrorFVerb (2, "ddxProcessArgument - screen - Found ``X+Y'' arg\n");
-	    g_ScreenInfo[nScreenNum].fUserGavePosition = TRUE;
-	    g_ScreenInfo[nScreenNum].dwInitialX = iX;
-	    g_ScreenInfo[nScreenNum].dwInitialY = iY;
-
-		/* look for WxD+X+Y at m where m is monitor number. take X,Y to be offsets from monitor's root position */
-		if (1 == sscanf (argv[i + 2], "%*dx%*d+%*d+%*d@%d",
-						 (int *) &iMonitor)) 
-        {
-          struct GetMonitorInfoData data;
-          if (!QueryMonitor(iMonitor, &data))
-          {
-              ErrorF ("ddxProcessArgument - screen - "
-                      "Querying monitors is not supported on NT4 and Win95\n");
-          } else if (data.bMonitorSpecifiedExists == TRUE) 
-          {
-			g_ScreenInfo[nScreenNum].dwInitialX += data.monitorOffsetX;
-			g_ScreenInfo[nScreenNum].dwInitialY += data.monitorOffsetY;
-		  }
-		  else 
-          {
-			/* monitor does not exist, error out */
-			ErrorF ("ddxProcessArgument - screen - Invalid monitor number %d\n",
-					iMonitor);
-			UseMsg ();
-			exit (0);
-			return 0;
-		  }
-
-		}
-	  }
-
-	  /* look for WxD at m where m is monitor number */
-	  else if (1 == sscanf(argv[i + 2], "%*dx%*d@%d",
-						   (int *) &iMonitor)) 
-      {
-        struct GetMonitorInfoData data;
-        if (!QueryMonitor(iMonitor, &data))
-        {
-		  ErrorF ("ddxProcessArgument - screen - "
-                  "Querying monitors is not supported on NT4 and Win95\n");
-        } else if (data.bMonitorSpecifiedExists == TRUE) 
-        {
-		  winErrorFVerb (2, "ddxProcessArgument - screen - Found Valid ``@Monitor'' = %d arg\n", iMonitor);
-		  g_ScreenInfo[nScreenNum].fUserGavePosition = TRUE;
-		  g_ScreenInfo[nScreenNum].dwInitialX = data.monitorOffsetX;
-		  g_ScreenInfo[nScreenNum].dwInitialY = data.monitorOffsetY;
-		}
-		else 
-        {
-		  /* monitor does not exist, error out */
-		  ErrorF ("ddxProcessArgument - screen - Invalid monitor number %d\n",
-				  iMonitor);
-		  UseMsg ();
-		  exit (0);
-		  return 0;
-		}
-
-	  }
-	}
-      else if (i + 3 < argc
-	       && 1 == sscanf (argv[i + 2], "%d",
-			       (int *) &iWidth)
-	       && 1 == sscanf (argv[i + 3], "%d",
-			       (int *) &iHeight))
-	{
-	  winErrorFVerb (2, "ddxProcessArgument - screen - Found ``W D'' arg\n");
-	  iArgsProcessed = 4;
-	  g_ScreenInfo[nScreenNum].fUserGaveHeightAndWidth = TRUE;
-	  g_ScreenInfo[nScreenNum].dwWidth = iWidth;
-	  g_ScreenInfo[nScreenNum].dwHeight = iHeight;
-	  g_ScreenInfo[nScreenNum].dwUserWidth = iWidth;
-	  g_ScreenInfo[nScreenNum].dwUserHeight = iHeight;
-	  if (i + 5 < argc
-	      && 1 == sscanf (argv[i + 4], "%d",
-			      (int *) &iX)
-	      && 1 == sscanf (argv[i + 5], "%d",
-			      (int *) &iY))
-	  {
-	    winErrorFVerb (2, "ddxProcessArgument - screen - Found ``X Y'' arg\n");
-	    iArgsProcessed = 6;
-	    g_ScreenInfo[nScreenNum].fUserGavePosition = TRUE;
-	    g_ScreenInfo[nScreenNum].dwInitialX = iX;
-	    g_ScreenInfo[nScreenNum].dwInitialY = iY;
-	  }
-	}
-      else
-	{
-	  winErrorFVerb (2, "ddxProcessArgument - screen - Did not find size arg. "
-		  "dwWidth: %d dwHeight: %d\n",
-		  (int) g_ScreenInfo[nScreenNum].dwWidth,
-		  (int) g_ScreenInfo[nScreenNum].dwHeight);
-	  iArgsProcessed = 2;
-	  g_ScreenInfo[nScreenNum].fUserGaveHeightAndWidth = FALSE;
-	}
-
-      /* Calculate the screen width and height in millimeters */
-      if (g_ScreenInfo[nScreenNum].fUserGaveHeightAndWidth)
-	{
-	  g_ScreenInfo[nScreenNum].dwWidth_mm
-	    = (g_ScreenInfo[nScreenNum].dwWidth
-	       / monitorResolution) * 25.4;
-	  g_ScreenInfo[nScreenNum].dwHeight_mm
-	    = (g_ScreenInfo[nScreenNum].dwHeight
-	       / monitorResolution) * 25.4;
-	}
-
-      /* Flag that this screen was explicity specified by the user */
-      g_ScreenInfo[nScreenNum].fExplicitScreen = TRUE;
-
-      /*
-       * Keep track of the last screen number seen, as parameters seen
-       * before a screen number apply to all screens, whereas parameters
-       * seen after a screen number apply to that screen number only.
-       */
-      g_iLastScreen = nScreenNum;
-
-      /* Keep a count of the number of screens */
-      ++g_iNumScreens;
-
-      return iArgsProcessed;
-    }
-
-  /*
-   * Look for the '-engine n' argument
-   */
-  if (IS_OPTION ("-engine"))
-    {
-      DWORD		dwEngine = 0;
-      CARD8		c8OnBits = 0;
-      
-      /* Display the usage message if the argument is malformed */
-      if (++i >= argc)
-	{
-	  UseMsg ();
-	  return 0;
-	}
-
-      /* Grab the argument */
-      dwEngine = atoi (argv[i]);
-
-      /* Count the one bits in the engine argument */
-      c8OnBits = winCountBits (dwEngine);
-
-      /* Argument should only have a single bit on */
-      if (c8OnBits != 1)
-	{
-	  UseMsg ();
-	  return 0;
-	}
-
-      /* Is this parameter attached to a screen or global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int		j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].dwEnginePreferred = dwEngine;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].dwEnginePreferred = dwEngine;
-	}
-      
-      /* Indicate that we have processed the argument */
-      return 2;
-    }
-
-  /*
-   * Look for the '-fullscreen' argument
-   */
-  if (IS_OPTION ("-fullscreen"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-              if (!g_ScreenInfo[j].fMultiMonitorOverride)
-                g_ScreenInfo[j].fMultipleMonitors = FALSE;
-#endif
-	      g_ScreenInfo[j].fFullScreen = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-          if (!g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride)
-            g_ScreenInfo[g_iLastScreen].fMultipleMonitors = FALSE;
-#endif
-	  g_ScreenInfo[g_iLastScreen].fFullScreen = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-  /*
-   * Look for the '-lesspointer' argument
-   */
-  if (IS_OPTION ("-lesspointer"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].fLessPointer = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-          g_ScreenInfo[g_iLastScreen].fLessPointer = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-  /*
-   * Look for the '-nodecoration' argument
-   */
-  if (IS_OPTION ("-nodecoration"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-              if (!g_ScreenInfo[j].fMultiMonitorOverride)
-                g_ScreenInfo[j].fMultipleMonitors = FALSE;
-#endif
-	      g_ScreenInfo[j].fDecoration = FALSE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-          if (!g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride)
-            g_ScreenInfo[g_iLastScreen].fMultipleMonitors = FALSE;
-#endif
-	  g_ScreenInfo[g_iLastScreen].fDecoration = FALSE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-  /*
-   * Look for the '-mwextwm' argument
-   */
-  if (IS_OPTION ("-mwextwm"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-              if (!g_ScreenInfo[j].fMultiMonitorOverride)
-                g_ScreenInfo[j].fMultipleMonitors = TRUE;
-	      g_ScreenInfo[j].fMWExtWM = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-          if (!g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride)
-            g_ScreenInfo[g_iLastScreen].fMultipleMonitors = TRUE;
-	  g_ScreenInfo[g_iLastScreen].fMWExtWM = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-  /*
-   * Look for the '-internalwm' argument
-   */
-  if (IS_OPTION ("-internalwm"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      if (!g_ScreenInfo[j].fMultiMonitorOverride)
-	        g_ScreenInfo[j].fMultipleMonitors = TRUE;
-	      g_ScreenInfo[j].fMWExtWM = TRUE;
-	      g_ScreenInfo[j].fInternalWM = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  if (!g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride)
-	    g_ScreenInfo[g_iLastScreen].fMultipleMonitors = TRUE;
-	  g_ScreenInfo[g_iLastScreen].fMWExtWM = TRUE;
-	  g_ScreenInfo[g_iLastScreen].fInternalWM = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-#endif
-
-  /*
-   * Look for the '-rootless' argument
-   */
-  if (IS_OPTION ("-rootless"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-              if (!g_ScreenInfo[j].fMultiMonitorOverride)
-                g_ScreenInfo[j].fMultipleMonitors = FALSE;
-#endif
-	      g_ScreenInfo[j].fRootless = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-          if (!g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride)
-            g_ScreenInfo[g_iLastScreen].fMultipleMonitors = FALSE;
-#endif
-	  g_ScreenInfo[g_iLastScreen].fRootless = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-#ifdef XWIN_MULTIWINDOW
-  /*
-   * Look for the '-multiwindow' argument
-   */
-  if (IS_OPTION ("-multiwindow"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-              if (!g_ScreenInfo[j].fMultiMonitorOverride)
-                g_ScreenInfo[j].fMultipleMonitors = TRUE;
-#endif
-	      g_ScreenInfo[j].fMultiWindow = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-          if (!g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride)
-            g_ScreenInfo[g_iLastScreen].fMultipleMonitors = TRUE;
-#endif
-	  g_ScreenInfo[g_iLastScreen].fMultiWindow = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-#endif
-
-  /*
-   * Look for the '-multiplemonitors' argument
-   */
-  if (IS_OPTION ("-multiplemonitors")
-      || IS_OPTION ("-multimonitors"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-              g_ScreenInfo[j].fMultiMonitorOverride = TRUE;
-#endif
-	      g_ScreenInfo[j].fMultipleMonitors = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-          g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride = TRUE;
-#endif
-	  g_ScreenInfo[g_iLastScreen].fMultipleMonitors = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-  /*
-   * Look for the '-nomultiplemonitors' argument
-   */
-  if (IS_OPTION ("-nomultiplemonitors")
-      || IS_OPTION ("-nomultimonitors"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-              g_ScreenInfo[j].fMultiMonitorOverride = TRUE;
-#endif
-	      g_ScreenInfo[j].fMultipleMonitors = FALSE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-          g_ScreenInfo[g_iLastScreen].fMultiMonitorOverride = TRUE;
-#endif
-	  g_ScreenInfo[g_iLastScreen].fMultipleMonitors = FALSE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-
-  /*
-   * Look for the '-scrollbars' argument
-   */
-  if (IS_OPTION ("-scrollbars"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].fScrollbars = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].fScrollbars = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-
-#ifdef XWIN_CLIPBOARD
-  /*
-   * Look for the '-clipboard' argument
-   */
-  if (IS_OPTION ("-clipboard"))
-    {
-      g_fClipboard = TRUE;
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-#endif
-
-
-  /*
-   * Look for the '-ignoreinput' argument
-   */
-  if (IS_OPTION ("-ignoreinput"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].fIgnoreInput = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].fIgnoreInput = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-  /*
-   * Look for the '-emulate3buttons' argument
-   */
-  if (IS_OPTION ("-emulate3buttons"))
-    {
-      int	iArgsProcessed = 1;
-      int	iE3BTimeout = WIN_DEFAULT_E3B_TIME;
-
-      /* Grab the optional timeout value */
-      if (i + 1 < argc
-	  && 1 == sscanf (argv[i + 1], "%d",
-			  &iE3BTimeout))
-        {
-	  /* Indicate that we have processed the next argument */
-	  iArgsProcessed++;
-        }
-      else
-	{
-	  /*
-	   * sscanf () won't modify iE3BTimeout if it doesn't find
-	   * the specified format; however, I want to be explicit
-	   * about setting the default timeout in such cases to
-	   * prevent some programs (me) from getting confused.
-	   */
-	  iE3BTimeout = WIN_DEFAULT_E3B_TIME;
-	}
-
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].iE3BTimeout = iE3BTimeout;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].iE3BTimeout = iE3BTimeout;
-	}
-
-      /* Indicate that we have processed this argument */
-      return iArgsProcessed;
-    }
-
-  /*
-   * Look for the '-depth n' argument
-   */
-  if (IS_OPTION ("-depth"))
-    {
-      DWORD		dwBPP = 0;
-      
-      /* Display the usage message if the argument is malformed */
-      if (++i >= argc)
-	{
-	  UseMsg ();
-	  return 0;
-	}
-
-      /* Grab the argument */
-      dwBPP = atoi (argv[i]);
-
-      /* Is this parameter attached to a screen or global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int		j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].dwBPP = dwBPP;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].dwBPP = dwBPP;
-	}
-      
-      /* Indicate that we have processed the argument */
-      return 2;
-    }
-
-  /*
-   * Look for the '-refresh n' argument
-   */
-  if (IS_OPTION ("-refresh"))
-    {
-      DWORD		dwRefreshRate = 0;
-      
-      /* Display the usage message if the argument is malformed */
-      if (++i >= argc)
-	{
-	  UseMsg ();
-	  return 0;
-	}
-
-      /* Grab the argument */
-      dwRefreshRate = atoi (argv[i]);
-
-      /* Is this parameter attached to a screen or global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int		j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].dwRefreshRate = dwRefreshRate;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].dwRefreshRate = dwRefreshRate;
-	}
-      
-      /* Indicate that we have processed the argument */
-      return 2;
-    }
-
-  /*
-   * Look for the '-clipupdates num_boxes' argument
-   */
-  if (IS_OPTION ("-clipupdates"))
-    {
-      DWORD		dwNumBoxes = 0;
-      
-      /* Display the usage message if the argument is malformed */
-      if (++i >= argc)
-	{
-	  UseMsg ();
-	  return 0;
-	}
-
-      /* Grab the argument */
-      dwNumBoxes = atoi (argv[i]);
-
-      /* Is this parameter attached to a screen or global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int		j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].dwClipUpdatesNBoxes = dwNumBoxes;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].dwClipUpdatesNBoxes = dwNumBoxes;
-	}
-      
-      /* Indicate that we have processed the argument */
-      return 2;
-    }
-
-#ifdef XWIN_EMULATEPSEUDO
-  /*
-   * Look for the '-emulatepseudo' argument
-   */
-  if (IS_OPTION ("-emulatepseudo"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].fEmulatePseudo = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-          g_ScreenInfo[g_iLastScreen].fEmulatePseudo = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-#endif
-
-  /*
-   * Look for the '-nowinkill' argument
-   */
-  if (IS_OPTION ("-nowinkill"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].fUseWinKillKey = FALSE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].fUseWinKillKey = FALSE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-  /*
-   * Look for the '-winkill' argument
-   */
-  if (IS_OPTION ("-winkill"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].fUseWinKillKey = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].fUseWinKillKey = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-  /*
-   * Look for the '-nounixkill' argument
-   */
-  if (IS_OPTION ("-nounixkill"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].fUseUnixKillKey = FALSE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].fUseUnixKillKey = FALSE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-  /*
-   * Look for the '-unixkill' argument
-   */
-  if (IS_OPTION ("-unixkill"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].fUseUnixKillKey = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].fUseUnixKillKey = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-  /*
-   * Look for the '-notrayicon' argument
-   */
-  if (IS_OPTION ("-notrayicon"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].fNoTrayIcon = TRUE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].fNoTrayIcon = TRUE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-  /*
-   * Look for the '-trayicon' argument
-   */
-  if (IS_OPTION ("-trayicon"))
-    {
-      /* Is this parameter attached to a screen or is it global? */
-      if (-1 == g_iLastScreen)
-	{
-	  int			j;
-
-	  /* Parameter is for all screens */
-	  for (j = 0; j < MAXSCREENS; j++)
-	    {
-	      g_ScreenInfo[j].fNoTrayIcon = FALSE;
-	    }
-	}
-      else
-	{
-	  /* Parameter is for a single screen */
-	  g_ScreenInfo[g_iLastScreen].fNoTrayIcon = FALSE;
-	}
-
-      /* Indicate that we have processed this argument */
-      return 1;
-    }
-
-  /*
-   * Look for the '-fp' argument
-   */
-  if (IS_OPTION ("-fp"))
-    {
-      CHECK_ARGS (1);
-      g_cmdline.fontPath = argv[++i];
-      return 0; /* Let DIX parse this again */
-    }
-
-  /*
-   * Look for the '-query' argument
-   */
-  if (IS_OPTION ("-query"))
-    {
-      CHECK_ARGS (1);
-      g_fXdmcpEnabled = TRUE;
-      g_pszQueryHost = argv[++i];
-      return 0; /* Let DIX parse this again */
-    }
-
-  /*
-   * Look for the '-indirect' or '-broadcast' arguments
-   */
-  if (IS_OPTION ("-indirect")
-      || IS_OPTION ("-broadcast"))
-    {
-      g_fXdmcpEnabled = TRUE;
-      return 0; /* Let DIX parse this again */
-    }
-
-  /*
-   * Look for the '-config' argument
-   */
-  if (IS_OPTION ("-config")
-      || IS_OPTION ("-xf86config"))
-    {
-      CHECK_ARGS (1);
-#ifdef XWIN_XF86CONFIG
-      g_cmdline.configFile = argv[++i];
-#else
-      winMessageBoxF ("The %s option is not supported in this "
-		      "release.\n"
-		      "Ignoring this option and continuing.\n",
-		      MB_ICONINFORMATION,
-		      argv[i]);
-#endif
-      return 2;
-    }
-
-  /*
-   * Look for the '-keyboard' argument
-   */
-  if (IS_OPTION ("-keyboard"))
-    {
-#ifdef XWIN_XF86CONFIG
-      CHECK_ARGS (1);
-      g_cmdline.keyboard = argv[++i];
-#else
-      winMessageBoxF ("The -keyboard option is not supported in this "
-		      "release.\n"
-		      "Ignoring this option and continuing.\n",
-		      MB_ICONINFORMATION);
-#endif
-      return 2;
-    }
-
-  /*
-   * Look for the '-logfile' argument
-   */
-  if (IS_OPTION ("-logfile"))
-    {
-      CHECK_ARGS (1);
-      g_pszLogFile = argv[++i];
-#ifdef RELOCATE_PROJECTROOT
-      g_fLogFileChanged = TRUE;
-#endif
-      return 2;
-    }
-
-  /*
-   * Look for the '-logverbose' argument
-   */
-  if (IS_OPTION ("-logverbose"))
-    {
-      CHECK_ARGS (1);
-      g_iLogVerbose = atoi(argv[++i]);
-      return 2;
-    }
-
-#ifdef XWIN_CLIPBOARD
-  /*
-   * Look for the '-nounicodeclipboard' argument
-   */
-  if (IS_OPTION ("-nounicodeclipboard"))
-    {
-      g_fUnicodeClipboard = FALSE;
-      /* Indicate that we have processed the argument */
-      return 1;
-    }
-#endif
-
-#ifdef XKB
-  /*
-   * Look for the '-kb' argument
-   */
-  if (IS_OPTION ("-kb"))
-    {
-      g_cmdline.noXkbExtension = TRUE;  
-      return 0; /* Let DIX parse this again */
-    }
-
-  if (IS_OPTION ("-xkbrules"))
-    {
-      CHECK_ARGS (1);
-      g_cmdline.xkbRules = argv[++i];
-      return 2;
-    }
-  if (IS_OPTION ("-xkbmodel"))
-    {
-      CHECK_ARGS (1);
-      g_cmdline.xkbModel = argv[++i];
-      return 2;
-    }
-  if (IS_OPTION ("-xkblayout"))
-    {
-      CHECK_ARGS (1);
-      g_cmdline.xkbLayout = argv[++i];
-      return 2;
-    }
-  if (IS_OPTION ("-xkbvariant"))
-    {
-      CHECK_ARGS (1);
-      g_cmdline.xkbVariant = argv[++i];
-      return 2;
-    }
-  if (IS_OPTION ("-xkboptions"))
-    {
-      CHECK_ARGS (1);
-      g_cmdline.xkbOptions = argv[++i];
-      return 2;
-    }
-#endif
-
-  if (IS_OPTION ("-keyhook"))
-    {
-      g_fKeyboardHookLL = TRUE;
-      return 1;
-    }
-  
-  if (IS_OPTION ("-nokeyhook"))
-    {
-      g_fKeyboardHookLL = FALSE;
-      return 1;
-    }
-  
-  if (IS_OPTION ("-swcursor"))
-    {
-      g_fSoftwareCursor = TRUE;
-      return 1;
-    }
-  
-  if (IS_OPTION ("-silent-dup-error"))
-    {
-      g_fSilentDupError = TRUE;
-      return 1;
-    }
-  return 0;
-}
-
-
-/*
- * winLogCommandLine - Write entire command line to the log file
- */
-
-void
-winLogCommandLine (int argc, char *argv[])
-{
-  int		i;
-  int		iSize = 0;
-  int		iCurrLen = 0;
-
-#define CHARS_PER_LINE 60
-
-  /* Bail if command line has already been logged */
-  if (g_pszCommandLine)
-    return;
-
-  /* Count how much memory is needed for concatenated command line */
-  for (i = 0, iCurrLen = 0; i < argc; ++i)
-    if (argv[i])
-      {
-	/* Add a character for lines that overflow */
-	if ((strlen (argv[i]) < CHARS_PER_LINE
-	    && iCurrLen + strlen (argv[i]) > CHARS_PER_LINE)
-	    || strlen (argv[i]) > CHARS_PER_LINE)
-	  {
-	    iCurrLen = 0;
-	    ++iSize;
-	  }
-	
-	/* Add space for item and trailing space */
-	iSize += strlen (argv[i]) + 1;
-
-	/* Update current line length */
-	iCurrLen += strlen (argv[i]);
-      }
-
-  /* Allocate memory for concatenated command line */
-  g_pszCommandLine = malloc (iSize + 1);
-  if (!g_pszCommandLine)
-    FatalError ("winLogCommandLine - Could not allocate memory for "
-		"command line string.  Exiting.\n");
-  
-  /* Set first character to concatenated command line to null */
-  g_pszCommandLine[0] = '\0';
-
-  /* Loop through all args */
-  for (i = 0, iCurrLen = 0; i < argc; ++i)
-    {
-      /* Add a character for lines that overflow */
-      if ((strlen (argv[i]) < CHARS_PER_LINE
-	   && iCurrLen + strlen (argv[i]) > CHARS_PER_LINE)
-	  || strlen (argv[i]) > CHARS_PER_LINE)
-      {
-	iCurrLen = 0;
-	
-	/* Add line break if it fits */
-	strncat (g_pszCommandLine, "\n", iSize - strlen (g_pszCommandLine));
-      }
-      
-      strncat (g_pszCommandLine, argv[i], iSize - strlen (g_pszCommandLine));
-      strncat (g_pszCommandLine, " ", iSize - strlen (g_pszCommandLine));
-
-      /* Save new line length */
-      iCurrLen += strlen (argv[i]);
-    }
-
-  ErrorF ("XWin was started with the following command line:\n\n"
-	  "%s\n\n", g_pszCommandLine);
-}
-
-
-/*
- * winLogVersionInfo - Log Cygwin/X version information
- */
-
-void
-winLogVersionInfo (void)
-{
-  static Bool		s_fBeenHere = FALSE;
-
-  if (s_fBeenHere)
-    return;
-  s_fBeenHere = TRUE;
-
-  ErrorF ("Welcome to the XWin X Server\n");
-  ErrorF ("Vendor: %s\n", VENDOR_STRING);
-  ErrorF ("Release: %s\n\n", VERSION_STRING);
-  ErrorF ("Contact: %s\n\n", VENDOR_CONTACT);
-}
-
-/*
- * getMonitorInfo - callback function used to return information from the enumeration of monitors attached
- */
-
-wBOOL CALLBACK getMonitorInfo(HMONITOR hMonitor, HDC hdc, LPRECT rect, LPARAM _data) 
-{
-  struct GetMonitorInfoData* data = (struct GetMonitorInfoData*)_data;
-  // only get data for monitor number specified in <data>
-  data->monitorNum++;
-  if (data->monitorNum == data->requestedMonitor) 
-  {
-	data->bMonitorSpecifiedExists = TRUE;
-	data->monitorOffsetX = rect->left;
-	data->monitorOffsetY = rect->top;
-	data->monitorHeight  = rect->bottom - rect->top;
-	data->monitorWidth   = rect->right  - rect->left;
-    return FALSE;
-  }
-  return TRUE;
-}
diff --git a/hw/xwin/winpushpxl.c b/hw/xwin/winpushpxl.c
deleted file mode 100644
index 72ef2d5..0000000
--- a/hw/xwin/winpushpxl.c
+++ /dev/null
@@ -1,225 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include <X11/X.h>
-#include "gcstruct.h"
-#include "scrnintstr.h"
-#include "pixmapstr.h"
-#include "miscstruct.h"
-#include "../mfb/maskbits.h"
-#include "mi.h"
-
-#define NPT 128
-
-/* winPushPixels -- squeegees the fill style of pGC through pBitMap
- * into pDrawable.  pBitMap is a stencil (dx by dy of it is used, it may
- * be bigger) which is placed on the drawable at xOrg, yOrg.  Where a 1 bit
- * is set in the bitmap, the fill style is put onto the drawable using
- * the GC's logical function. The drawable is not changed where the bitmap
- * has a zero bit or outside the area covered by the stencil.
-
-WARNING:
-    this code works if the 1-bit deep pixmap format returned by GetSpans
-is the same as the format defined by the mfb code (i.e. 32-bit padding
-per scanline, scanline unit = 32 bits; later, this might mean
-bitsizeof(int) padding and sacnline unit == bitsizeof(int).)
-
- */
-
-/*
- * in order to have both (MSB_FIRST and LSB_FIRST) versions of this
- * in the server, we need to rename one of them
- */
-void
-winPushPixels (GCPtr pGC, PixmapPtr pBitMap, DrawablePtr pDrawable,
-	       int dx, int dy, int xOrg, int yOrg)
-{
-    int		h, dxDivPPW, ibEnd;
-    MiBits *pwLineStart;
-    register MiBits	*pw, *pwEnd;
-    register MiBits msk;
-    register int ib, w;
-    register int ipt;		/* index into above arrays */
-    Bool 	fInBox;
-    DDXPointRec	pt[NPT], ptThisLine;
-    int		width[NPT];
-    PixelType	startmask;
-
-
-    startmask = (MiBits)(-1) ^
-            LONG2CHARSDIFFORDER((MiBits)(-1) >> 1);
-
-    pwLineStart = (MiBits *)xalloc(BitmapBytePad(dx));
-    if (!pwLineStart)
-	return;
-    ipt = 0;
-    dxDivPPW = dx/PPW;
-
-    for(h = 0, ptThisLine.x = 0, ptThisLine.y = 0; 
-	h < dy; 
-	h++, ptThisLine.y++)
-    {
-
-	(*pBitMap->drawable.pScreen->GetSpans)((DrawablePtr)pBitMap, dx,
-			&ptThisLine, &dx, 1, (char *)pwLineStart);
-
-	pw = pwLineStart;
-	/* Process all words which are fully in the pixmap */
-	
-	fInBox = FALSE;
-	pwEnd = pwLineStart + dxDivPPW;
-	while(pw  < pwEnd)
-	{
-	    w = *pw;
-#ifdef XFree86Server
-	    msk = startmask;
-#else
-	    msk = (MiBits)(-1) ^ SCRRIGHT((MiBits)(-1), 1);
-#endif
-	    for(ib = 0; ib < PPW; ib++)
-	    {
-		if(w & msk)
-		{
-		    if(!fInBox)
-		    {
-			pt[ipt].x = ((pw - pwLineStart) << PWSH) + ib + xOrg;
-			pt[ipt].y = h + yOrg;
-			/* start new box */
-			fInBox = TRUE;
-		    }
-		}
-		else
-		{
-		    if(fInBox)
-		    {
-			width[ipt] = ((pw - pwLineStart) << PWSH) + 
-				     ib + xOrg - pt[ipt].x;
-			if (++ipt >= NPT)
-			{
-			    (*pGC->ops->FillSpans)(pDrawable, pGC, 
-					      NPT, pt, width, TRUE);
-			    ipt = 0;
-			}
-			/* end box */
-			fInBox = FALSE;
-		    }
-		}
-#ifdef XFree86Server
-    		/* This is not quite right, but it'll do for now */
-		msk = LONG2CHARSDIFFORDER(LONG2CHARSDIFFORDER(msk) >> 1);
-#else
-		msk = SCRRIGHT(msk, 1);
-#endif
-	    }
-	    pw++;
-	}
-	ibEnd = dx & PIM;
-	if(ibEnd)
-	{
-	    /* Process final partial word on line */
-	    w = *pw;
-#ifdef XFree86Server
-	    msk = startmask;
-#else
-	    msk = (MiBits)(-1) ^ SCRRIGHT((MiBits)(-1), 1);
-#endif
-	    for(ib = 0; ib < ibEnd; ib++)
-	    {
-		if(w & msk)
-		{
-		    if(!fInBox)
-		    {
-			/* start new box */
-			pt[ipt].x = ((pw - pwLineStart) << PWSH) + ib + xOrg;
-			pt[ipt].y = h + yOrg;
-			fInBox = TRUE;
-		    }
-		}
-		else
-		{
-		    if(fInBox)
-		    {
-			/* end box */
-			width[ipt] = ((pw - pwLineStart) << PWSH) + 
-				     ib + xOrg - pt[ipt].x;
-			if (++ipt >= NPT)
-			{
-			    (*pGC->ops->FillSpans)(pDrawable, 
-					      pGC, NPT, pt, width, TRUE);
-			    ipt = 0;
-			}
-			fInBox = FALSE;
-		    }
-		}
-#ifdef XFree86Server
-    		/* This is not quite right, but it'll do for now */
-		msk = LONG2CHARSDIFFORDER(LONG2CHARSDIFFORDER(msk) >> 1);
-#else
-		msk = SCRRIGHT(msk, 1);
-#endif
-	    }
-	}
-	/* If scanline ended with last bit set, end the box */
-	if(fInBox)
-	{
-	    width[ipt] = dx + xOrg - pt[ipt].x;
-	    if (++ipt >= NPT)
-	    {
-		(*pGC->ops->FillSpans)(pDrawable, pGC, NPT, pt, width, TRUE);
-		ipt = 0;
-	    }
-	}
-    }
-    xfree(pwLineStart);
-    /* Flush any remaining spans */
-    if (ipt)
-    {
-	(*pGC->ops->FillSpans)(pDrawable, pGC, ipt, pt, width, TRUE);
-    }
-}
diff --git a/hw/xwin/winrandr.c b/hw/xwin/winrandr.c
deleted file mode 100755
index 7b5b135..0000000
--- a/hw/xwin/winrandr.c
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * Local prototypes
- */
-
-static Bool
-winRandRGetInfo (ScreenPtr pScreen, Rotation *pRotations);
-
-static Bool
-winRandRSetConfig (ScreenPtr		pScreen,
-		   Rotation		rotateKind,
-		   int			rate,
-		   RRScreenSizePtr	pSize);
-
-Bool
-winRandRInit (ScreenPtr pScreen);
-
-
-/*
- * Answer queries about the RandR features supported.
- */
-
-static Bool
-winRandRGetInfo (ScreenPtr pScreen, Rotation *pRotations)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo			*pScreenInfo = pScreenPriv->pScreenInfo;
-  int				n;
-  Rotation			rotateKind;
-  RRScreenSizePtr		pSize;
-
-  winDebug ("winRandRGetInfo ()\n");
-
-  /* Don't support rotations, yet */
-  *pRotations = RR_Rotate_0;
-
-  /* Bail if no depth has a visual associated with it */
-  for (n = 0; n < pScreen->numDepths; n++)
-    if (pScreen->allowedDepths[n].numVids)
-      break;
-  if (n == pScreen->numDepths)
-    return FALSE;
-
-  /* Only one allowed rotation for now */
-  rotateKind = RR_Rotate_0;
-
-  /*
-   * Register supported sizes.  This can be called many times, but
-   * we only support one size for now.
-   */
-  pSize = RRRegisterSize (pScreen,
-			  pScreenInfo->dwWidth,
-			  pScreenInfo->dwHeight,
-			  pScreenInfo->dwWidth_mm,
-			  pScreenInfo->dwHeight_mm);
-
-  /* Tell RandR what the current config is */
-  RRSetCurrentConfig (pScreen,
-		      rotateKind,
-		      0, /* refresh rate, not needed */
-		      pSize);
-  
-  return TRUE;
-}
-
-
-/*
- * Respond to resize/rotate request from either X Server or X client app
- */
-
-static Bool
-winRandRSetConfig (ScreenPtr		pScreen,
-		   Rotation		rotateKind,
-		   int			rate,
-		   RRScreenSizePtr	pSize)
-{
-  winDebug ("winRandRSetConfig ()\n");
-
-  return TRUE;
-}
-
-
-/*
- * Initialize the RandR layer.
- */
-
-Bool
-winRandRInit (ScreenPtr pScreen)
-{
-  rrScrPrivPtr		pRRScrPriv;
-
-  winDebug ("winRandRInit ()\n");
-
-  if (!RRScreenInit (pScreen))
-    {
-      ErrorF ("winRandRInit () - RRScreenInit () failed\n");
-      return FALSE;
-    }
-
-  /* Set some RandR function pointers */
-  pRRScrPriv = rrGetScrPriv (pScreen);
-  pRRScrPriv->rrGetInfo = winRandRGetInfo;
-  pRRScrPriv->rrSetConfig = winRandRSetConfig;
-
-  return TRUE;
-}
diff --git a/hw/xwin/winregistry.c b/hw/xwin/winregistry.c
deleted file mode 100644
index 3571b14..0000000
--- a/hw/xwin/winregistry.c
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- *Copyright (C) 2002-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-/* Prototypes */
-DWORD
-winGetRegistryDWORD (HKEY hkey, char *pszRegistryKey);
-
-DWORD
-winGetRegistryDWORD (HKEY hkey, char *pszRegistryKey)
-{
-  HKEY		hkResult;
-  DWORD		dwDisposition;
-
-  RegCreateKeyEx (hkey,
-		  pszRegistryKey,
-		  0,
-		  '\0',
-		  REG_OPTION_NON_VOLATILE,
-		  KEY_READ,
-		  NULL,
-		  &hkResult,
-		  &dwDisposition);
-
-  if (dwDisposition == REG_CREATED_NEW_KEY)
-    {
-      ErrorF ("winGetRegistryDWORD - Created new key: %s\n", pszRegistryKey);
-    }
-  else if (dwDisposition == REG_OPENED_EXISTING_KEY)
-    {
-      ErrorF ("winGetRegistryDWORD - Opened existing key: %s\n",
-	      pszRegistryKey);
-    }
-
-  /* Free the registry key handle */
-  RegCloseKey (hkResult);
-  hkResult = NULL;
-
-  return 0;
-}
diff --git a/hw/xwin/winresource.h b/hw/xwin/winresource.h
deleted file mode 100644
index 5aa8840..0000000
--- a/hw/xwin/winresource.h
+++ /dev/null
@@ -1,55 +0,0 @@
-#if !defined(WINRESOURCE_H)
-#define WINRESOURCE_H
-/*
- *Copyright (C) 2002-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-
-/*
- * Local defines
- */
-
-#define IDC_STATIC		-1
-#define IDI_XWIN		101
-#define IDI_XWIN_BOXED		102
-#define IDM_TRAYICON_MENU	103
-#define IDC_CLIENTS_CONNECTED	104
-
-
-#define ID_APP_EXIT		200
-#define ID_APP_HIDE_ROOT	201
-#define ID_APP_ALWAYS_ON_TOP	202
-#define ID_APP_ABOUT		203
-
-#define ID_ABOUT_UG		300
-#define ID_ABOUT_FAQ		301
-#define ID_ABOUT_CHANGELOG	302
-#define ID_ABOUT_WEBSITE	303
-
-#endif
diff --git a/hw/xwin/winrop.c b/hw/xwin/winrop.c
deleted file mode 100644
index f481892..0000000
--- a/hw/xwin/winrop.c
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- *Copyright (C) 1994-2002 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * 	Authors:	Alan Hourihane <alanh at fairlite.demon.co.uk>
- */
-
-/*
- * Raster operations used by Windows translated to X's 16 rop codes...
- */
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-void
-ROP16 (HDC hdc, int rop);
-
-int g_copyROP[16] = { 	0xFF0062, /* GXclear 		- 0 */
-		 	0x8800C6, /* GXand 		- S & D */
-		 	0x440328, /* GXandReverse  	- S & !D */
-		 	0xCC0020, /* GXcopy 		- S */
-		 	0x220326, /* GXandInverted 	- !S & D */
-		 	0xAA0029, /* GXnoop		- D */
-		 	0x660046, /* GXxor 		- S ^ D */
-		 	0xEE0086, /* GXor		- S | D */
-		 	0x1100A6, /* GXnor 		- !S & !D */
-		 	0x990126, /* GXequiv		- !S ^ D */
-		 	0x550009, /* GXinvert		- !D */
-		 	0xDD0228, /* GXorReverse	- S | !D */
-		 	0x330008, /* GXcopyInverted	- !S */
-		 	0xBB0226, /* GXorInverted	- !S | D */
-		 	0x7700C6, /* GXnand		- !S | !D */
-		 	0x000042  /* GXset		- 1 */
-};
-
-int g_patternROP[16] = {0xFF0062, /* GXclear		- 0 */
-		 	0xA000C9, /* GXand 		- P & D */
-		 	0xF50225, /* GXandReverse	- P & !D */
-		 	0xF00021, /* GXcopy 		- P */
-		 	0x5F00E9, /* GXandInverted 	- !P & D */
-		 	0xAA0029, /* GXnoop		- D */
-		 	0xA50065, /* GXxor		- P ^ D */
-		 	0xA000C9, /* GXor		- P | D */
-		 	0x5F00E9, /* GXnor		- !P & !D */
-		 	0x5A0049, /* GXequiv		- !P ^ D */
-		 	0x550009, /* GXinvert		- !D */
-		 	0x500325, /* GXorReverse	- P | !D */
-		 	0x0F0001, /* GXcopyInverted	- !P */
-		 	0x0A0329, /* GXorInverted	- !P | D */
-		 	0x0500A9, /* GXnand		- !P | !D */
-		 	0x000042  /* GXset		- 1 */
-};
-
-
-void
-ROP16 (HDC hdc, int rop)
-{
-  switch (rop)
-    {
-    case GXclear:
-      SetROP2 (hdc, R2_BLACK);
-      break;
-
-    case GXand:
-      SetROP2 (hdc, R2_MASKPEN);
-      break;
-
-    case GXandReverse:
-      SetROP2 (hdc, R2_MASKPENNOT);
-      break;
-
-    case GXcopy:
-      SetROP2 (hdc, R2_COPYPEN);
-      break;
-
-    case GXnoop:
-      SetROP2 (hdc, R2_NOP);
-      break;
-
-    case GXxor:
-      SetROP2 (hdc, R2_XORPEN);
-      break;
-
-    case GXor:
-      SetROP2 (hdc, R2_MERGEPEN);
-      break;
-
-    case GXnor:
-      SetROP2 (hdc, R2_NOTMERGEPEN);
-      break;
-
-    case GXequiv:
-      SetROP2 (hdc, R2_NOTXORPEN);
-      break;
-
-    case GXinvert:
-      SetROP2 (hdc, R2_NOT);
-      break;
-
-    case GXorReverse:
-      SetROP2 (hdc, R2_MERGEPENNOT);
-      break;
-
-    case GXcopyInverted:
-      SetROP2 (hdc, R2_NOTCOPYPEN);
-      break;
-
-    case GXorInverted:
-      SetROP2 (hdc, R2_MERGENOTPEN);
-      break;
-
-    case GXnand:
-      SetROP2 (hdc, R2_NOTMASKPEN);
-      break;
-
-    case GXset:
-      SetROP2 (hdc, R2_WHITE);
-      break;
-    }
-}
diff --git a/hw/xwin/winscrinit.c b/hw/xwin/winscrinit.c
deleted file mode 100644
index 9dc4c3d..0000000
--- a/hw/xwin/winscrinit.c
+++ /dev/null
@@ -1,781 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- *		Kensuke Matsuzaki
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winmsg.h"
-#include "safeAlpha.h"	
-
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-static RootlessFrameProcsRec
-winMWExtWMProcs = {	
-  winMWExtWMCreateFrame,
-  winMWExtWMDestroyFrame,
-  
-  winMWExtWMMoveFrame,
-  winMWExtWMResizeFrame,
-  winMWExtWMRestackFrame,
-  winMWExtWMReshapeFrame,
-  winMWExtWMUnmapFrame,
-  
-  winMWExtWMStartDrawing,
-  winMWExtWMStopDrawing,
-  winMWExtWMUpdateRegion,
-#ifndef ROOTLESS_TRACK_DAMAGE
-  winMWExtWMDamageRects,
-#endif
-  winMWExtWMRootlessSwitchWindow,
-  NULL,//winWMExtWMDoReorderWindow,
-  
-  NULL,//winMWExtWMCopyBytes,
-  NULL,//winMWExtWMFillBytes,
-  NULL,//winMWExtWMCompositePixels,
-  winMWExtWMCopyWindow
-};
-#endif
-
-
-/*
- * References to external symbols
- */
-
-extern Bool                     g_fSoftwareCursor;
-
-
-/*
- * Prototypes
- */
-
-Bool
-winRandRInit (ScreenPtr pScreen);
-
-
-/*
- * Local functions
- */
-
-static Bool
-winSaveScreen (ScreenPtr pScreen, int on);
-
-
-/*
- * Determine what type of screen we are initializing
- * and call the appropriate procedure to intiailize
- * that type of screen.
- */
-
-Bool
-winScreenInit (int index,
-	       ScreenPtr pScreen,
-	       int argc, char **argv)
-{
-  winScreenInfoPtr      pScreenInfo = &g_ScreenInfo[index];
-  winPrivScreenPtr	pScreenPriv;
-  HDC			hdc;
-
-#if CYGDEBUG || YES
-  winDebug ("winScreenInit - dwWidth: %ld dwHeight: %ld\n",
-	  pScreenInfo->dwWidth, pScreenInfo->dwHeight);
-#endif
-
-  /* Allocate privates for this screen */
-  if (!winAllocatePrivates (pScreen))
-    {
-      ErrorF ("winScreenInit - Couldn't allocate screen privates\n");
-      return FALSE;
-    }
-
-  /* Get a pointer to the privates structure that was allocated */
-  pScreenPriv = winGetScreenPriv (pScreen);
-
-  /* Save a pointer to this screen in the screen info structure */
-  pScreenInfo->pScreen = pScreen;
-
-  /* Save a pointer to the screen info in the screen privates structure */
-  /* This allows us to get back to the screen info from a screen pointer */
-  pScreenPriv->pScreenInfo = pScreenInfo;
-
-  /*
-   * Determine which engine to use.
-   *
-   * NOTE: This is done once per screen because each screen possibly has
-   * a preferred engine specified on the command line.
-   */
-  if (!winSetEngine (pScreen))
-    {
-      ErrorF ("winScreenInit - winSetEngine () failed\n");
-      return FALSE;
-    }
-
-  /* Adjust the video mode for our engine type */
-  if (!(*pScreenPriv->pwinAdjustVideoMode) (pScreen))
-    {
-      ErrorF ("winScreenInit - winAdjustVideoMode () failed\n");
-      return FALSE;
-    }
-
-  /* Check for supported display depth */
-  if (!(WIN_SUPPORTED_BPPS & (1 << (pScreenInfo->dwBPP - 1))))
-    {
-      ErrorF ("winScreenInit - Unsupported display depth: %d\n" \
-	      "Change your Windows display depth to 15, 16, 24, or 32 bits "
-	      "per pixel.\n",
-	      (int) pScreenInfo->dwBPP);
-      ErrorF ("winScreenInit - Supported depths: %08x\n",
-	      WIN_SUPPORTED_BPPS);
-#if WIN_CHECK_DEPTH
-      return FALSE;
-#endif
-    }
-
-  /*
-   * Check that all monitors have the same display depth if we are using
-   * multiple monitors
-   */
-  if (pScreenInfo->fMultipleMonitors 
-      && !GetSystemMetrics (SM_SAMEDISPLAYFORMAT))
-    {
-      ErrorF ("winScreenInit - Monitors do not all have same pixel format / "
-	      "display depth.\n"
-	      "Using primary display only.\n");
-      pScreenInfo->fMultipleMonitors = FALSE;
-    }
-
-  /* Create display window */
-  if (!(*pScreenPriv->pwinCreateBoundingWindow) (pScreen))
-    {
-      ErrorF ("winScreenInit - pwinCreateBoundingWindow () "
-	      "failed\n");
-      return FALSE;
-    }
-
-  /* Get a device context */
-  hdc = GetDC (pScreenPriv->hwndScreen);
-
-  /* Store the initial height, width, and depth of the display */
-  /* Are we using multiple monitors? */
-  if (pScreenInfo->fMultipleMonitors)
-    {
-      pScreenPriv->dwLastWindowsWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
-      pScreenPriv->dwLastWindowsHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
-
-      /* 
-       * In this case, some of the defaults set in
-       * winInitializeDefaultScreens () are not correct ...
-       */
-      if (!pScreenInfo->fUserGaveHeightAndWidth)
-	{
-	  pScreenInfo->dwWidth = GetSystemMetrics (SM_CXVIRTUALSCREEN);
-	  pScreenInfo->dwHeight = GetSystemMetrics (SM_CYVIRTUALSCREEN);
-	  pScreenInfo->dwWidth_mm = (pScreenInfo->dwWidth /
-				     WIN_DEFAULT_DPI) * 25.4;
-	  pScreenInfo->dwHeight_mm = (pScreenInfo->dwHeight /
-				      WIN_DEFAULT_DPI) * 25.4;
-	}
-    }
-  else
-    {
-      pScreenPriv->dwLastWindowsWidth = GetSystemMetrics (SM_CXSCREEN);
-      pScreenPriv->dwLastWindowsHeight = GetSystemMetrics (SM_CYSCREEN);
-    }
-
-  /* Save the original bits per pixel */
-  pScreenPriv->dwLastWindowsBitsPixel = GetDeviceCaps (hdc, BITSPIXEL);
-
-  /* Release the device context */
-  ReleaseDC (pScreenPriv->hwndScreen, hdc);
-    
-  /* Clear the visuals list */
-  miClearVisualTypes ();
-  
-  /* Set the padded screen width */
-  pScreenInfo->dwPaddedWidth = PixmapBytePad (pScreenInfo->dwWidth,
-					      pScreenInfo->dwBPP);
-
-  /* Call the engine dependent screen initialization procedure */
-  if (!((*pScreenPriv->pwinFinishScreenInit) (index, pScreen, argc, argv)))
-    {
-      ErrorF ("winScreenInit - winFinishScreenInit () failed\n");
-      return FALSE;
-    }
-
-  if (!g_fSoftwareCursor)
-    winInitCursor(pScreen);
-  else
-    winErrorFVerb(2, "winScreenInit - Using software cursor\n");  
-
-#if CYGDEBUG || YES
-  winDebug ("winScreenInit - returning\n");
-#endif
-
-  return TRUE;
-}
-
-
-/* See Porting Layer Definition - p. 20 */
-Bool
-winFinishScreenInitFB (int index,
-		       ScreenPtr pScreen,
-		       int argc, char **argv)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  VisualPtr		pVisual = NULL;
-  char			*pbits = NULL;
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  int			iReturn;
-#endif
-
-  /* Create framebuffer */
-  if (!(*pScreenPriv->pwinAllocateFB) (pScreen))
-    {
-      ErrorF ("winFinishScreenInitFB - Could not allocate framebuffer\n");
-      return FALSE;
-    }
-
-  /*
-   * Grab the number of bits that are used to represent color in each pixel.
-   */
-  if (pScreenInfo->dwBPP == 8)
-    pScreenInfo->dwDepth = 8;
-  else
-    pScreenInfo->dwDepth = winCountBits (pScreenPriv->dwRedMask)
-      + winCountBits (pScreenPriv->dwGreenMask)
-      + winCountBits (pScreenPriv->dwBlueMask);
-  
-  winErrorFVerb (2, "winFinishScreenInitFB - Masks: %08x %08x %08x\n",
-	  (unsigned int) pScreenPriv->dwRedMask,
-	  (unsigned int) pScreenPriv->dwGreenMask,
-	  (unsigned int) pScreenPriv->dwBlueMask);
-
-  /* Init visuals */
-  if (!(*pScreenPriv->pwinInitVisuals) (pScreen))
-    {
-      ErrorF ("winFinishScreenInitFB - winInitVisuals failed\n");
-      return FALSE;
-    }
-
-  /* Setup a local variable to point to the framebuffer */
-  pbits = pScreenInfo->pfb;
-  
-  /* Apparently we need this for the render extension */
-  miSetPixmapDepths ();
-
-  /* Start fb initialization */
-  if (!fbSetupScreen (pScreen,
-		      pScreenInfo->pfb,
-		      pScreenInfo->dwWidth, pScreenInfo->dwHeight,
-		      monitorResolution, monitorResolution,
-		      pScreenInfo->dwStride,
-		      pScreenInfo->dwBPP))
-    {
-      ErrorF ("winFinishScreenInitFB - fbSetupScreen failed\n");
-      return FALSE;
-    }
-
-  /* Override default colormap routines if visual class is dynamic */
-  if (pScreenInfo->dwDepth == 8
-      && (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_GDI
-	  || (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL
-	      && pScreenInfo->fFullScreen)
-	  || (pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
-	      && pScreenInfo->fFullScreen)))
-    {
-      winSetColormapFunctions (pScreen);
-
-      /*
-       * NOTE: Setting whitePixel to 255 causes Magic 7.1 to allocate its
-       * own colormap, as it cannot allocate 7 planes in the default
-       * colormap.  Setting whitePixel to 1 allows Magic to get 7
-       * planes in the default colormap, so it doesn't create its
-       * own colormap.  This latter situation is highly desireable,
-       * as it keeps the Magic window viewable when switching to
-       * other X clients that use the default colormap.
-       */
-      pScreen->blackPixel = 0;
-      pScreen->whitePixel = 1;
-    }
-
-  /* Place our save screen function */
-  pScreen->SaveScreen = winSaveScreen;
-
-  /* Finish fb initialization */
-  if (!fbFinishScreenInit (pScreen,
-			   pScreenInfo->pfb,
-			   pScreenInfo->dwWidth, pScreenInfo->dwHeight,
-			   monitorResolution, monitorResolution,
-			   pScreenInfo->dwStride,
-			   pScreenInfo->dwBPP))
-    {
-      ErrorF ("winFinishScreenInitFB - fbFinishScreenInit failed\n");
-      return FALSE;
-    }
-
-  /* Save a pointer to the root visual */
-  for (pVisual = pScreen->visuals;
-       pVisual->vid != pScreen->rootVisual;
-       pVisual++);
-  pScreenPriv->pRootVisual = pVisual;
-
-  /* 
-   * Setup points to the block and wakeup handlers.  Pass a pointer
-   * to the current screen as pWakeupdata.
-   */
-  pScreen->BlockHandler = winBlockHandler;
-  pScreen->WakeupHandler = winWakeupHandler;
-  pScreen->blockData = pScreen;
-  pScreen->wakeupData = pScreen;
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-  /*
-   * Setup acceleration for multi-window external window manager mode.
-   * To be compatible with the Damage extension, this must be done
-   * before calling miDCInitialize, which calls DamageSetup.
-   */
-  if (pScreenInfo->fMWExtWM)
-    {
-      if (!RootlessAccelInit (pScreen))
-        {
-          ErrorF ("winFinishScreenInitFB - RootlessAccelInit () failed\n");
-          return FALSE;
-        }
-    }
-#endif
-
-#ifdef RENDER
-  /* Render extension initialization, calls miPictureInit */
-  if (!fbPictureInit (pScreen, NULL, 0))
-    {
-      ErrorF ("winFinishScreenInitFB - fbPictureInit () failed\n");
-      return FALSE;
-    }
-#endif
-
-#ifdef RANDR
-  /* Initialize resize and rotate support */
-  if (!winRandRInit (pScreen))
-    {
-      ErrorF ("winFinishScreenInitFB - winRandRInit () failed\n");
-      return FALSE;
-    }
-#endif
-
-  /*
-   * Backing store support should reduce network traffic and increase
-   * performance.
-   */
-  miInitializeBackingStore (pScreen);
-
-  /* KDrive does miDCInitialize right after miInitializeBackingStore */
-  /* Setup the cursor routines */
-#if CYGDEBUG
-  winDebug ("winFinishScreenInitFB - Calling miDCInitialize ()\n");
-#endif
-  miDCInitialize (pScreen, &g_winPointerCursorFuncs);
-
-  /* KDrive does winCreateDefColormap right after miDCInitialize */
-  /* Create a default colormap */
-#if CYGDEBUG
-  winDebug ("winFinishScreenInitFB - Calling winCreateDefColormap ()\n");
-#endif
-  if (!winCreateDefColormap (pScreen))
-    {
-      ErrorF ("winFinishScreenInitFB - Could not create colormap\n");
-      return FALSE;
-    }
-
-  /* Initialize the shadow framebuffer layer */
-  if ((pScreenInfo->dwEngine == WIN_SERVER_SHADOW_GDI
-       || pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
-       || pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL)
-#ifdef XWIN_MULTIWINDOWEXTWM
-      && !pScreenInfo->fMWExtWM
-#endif
-      )
-    {
-#if CYGDEBUG
-      winDebug ("winFinishScreenInitFB - Calling shadowInit ()\n");
-#endif
-      if (!shadowInit (pScreen,
-		       pScreenPriv->pwinShadowUpdate,
-		       NULL))
-	{
-	  ErrorF ("winFinishScreenInitFB - shadowInit () failed\n");
-	  return FALSE;
-	}
-    }
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-  /* Handle multi-window external window manager mode */
-  if (pScreenInfo->fMWExtWM)
-    {
-      winDebug ("winScreenInit - MultiWindowExtWM - Calling RootlessInit\n");
-      
-      RootlessInit(pScreen, &winMWExtWMProcs);
-      
-      winDebug ("winScreenInit - MultiWindowExtWM - RootlessInit returned\n");
-      
-      rootless_CopyBytes_threshold = 0;
-      rootless_FillBytes_threshold = 0;
-      rootless_CompositePixels_threshold = 0;
-      /* FIXME: How many? Profiling needed? */
-      rootless_CopyWindow_threshold = 1;
-
-      winWindowsWMExtensionInit ();
-    }
-#endif
-
-  /* Handle rootless mode */
-  if (pScreenInfo->fRootless)
-    {
-      /* Define the WRAP macro temporarily for local use */
-#define WRAP(a) \
-    if (pScreen->a) { \
-        pScreenPriv->a = pScreen->a; \
-    } else { \
-        ErrorF("null screen fn " #a "\n"); \
-        pScreenPriv->a = NULL; \
-    }
-
-      /* Save a pointer to each lower-level window procedure */
-      WRAP(CreateWindow);
-      WRAP(DestroyWindow);
-      WRAP(RealizeWindow);
-      WRAP(UnrealizeWindow);
-      WRAP(PositionWindow);
-      WRAP(ChangeWindowAttributes);
-#ifdef SHAPE
-      WRAP(SetShape);
-#endif
-
-      /* Assign rootless window procedures to be top level procedures */
-      pScreen->CreateWindow = winCreateWindowRootless;
-      pScreen->DestroyWindow = winDestroyWindowRootless;
-      pScreen->PositionWindow = winPositionWindowRootless;
-      /*pScreen->ChangeWindowAttributes = winChangeWindowAttributesRootless;*/
-      pScreen->RealizeWindow = winMapWindowRootless;
-      pScreen->UnrealizeWindow = winUnmapWindowRootless;
-#ifdef SHAPE
-      pScreen->SetShape = winSetShapeRootless;
-#endif
-
-      /* Undefine the WRAP macro, as it is not needed elsewhere */
-#undef WRAP
-    }
-
-
-#ifdef XWIN_MULTIWINDOW
-  /* Handle multi window mode */
-  else if (pScreenInfo->fMultiWindow)
-    {
-      /* Define the WRAP macro temporarily for local use */
-#define WRAP(a) \
-    if (pScreen->a) { \
-        pScreenPriv->a = pScreen->a; \
-    } else { \
-        ErrorF("null screen fn " #a "\n"); \
-        pScreenPriv->a = NULL; \
-    }
-
-      /* Save a pointer to each lower-level window procedure */
-      WRAP(CreateWindow);
-      WRAP(DestroyWindow);
-      WRAP(RealizeWindow);
-      WRAP(UnrealizeWindow);
-      WRAP(PositionWindow);
-      WRAP(ChangeWindowAttributes);
-      WRAP(ReparentWindow);
-      WRAP(RestackWindow);
-      WRAP(ResizeWindow);
-      WRAP(MoveWindow);
-      WRAP(CopyWindow);
-#ifdef SHAPE
-      WRAP(SetShape);
-#endif
-
-      /* Assign multi-window window procedures to be top level procedures */
-      pScreen->CreateWindow = winCreateWindowMultiWindow;
-      pScreen->DestroyWindow = winDestroyWindowMultiWindow;
-      pScreen->PositionWindow = winPositionWindowMultiWindow;
-      /*pScreen->ChangeWindowAttributes = winChangeWindowAttributesMultiWindow;*/
-      pScreen->RealizeWindow = winMapWindowMultiWindow;
-      pScreen->UnrealizeWindow = winUnmapWindowMultiWindow;
-      pScreen->ReparentWindow = winReparentWindowMultiWindow;
-      pScreen->RestackWindow = winRestackWindowMultiWindow;
-      pScreen->ResizeWindow = winResizeWindowMultiWindow;
-      pScreen->MoveWindow = winMoveWindowMultiWindow;
-      pScreen->CopyWindow = winCopyWindowMultiWindow;
-#ifdef SHAPE
-      pScreen->SetShape = winSetShapeMultiWindow;
-#endif
-
-      /* Undefine the WRAP macro, as it is not needed elsewhere */
-#undef WRAP
-    }
-#endif
-
-  /* Wrap either fb's or shadow's CloseScreen with our CloseScreen */
-  pScreenPriv->CloseScreen = pScreen->CloseScreen;
-  pScreen->CloseScreen = pScreenPriv->pwinCloseScreen;
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  /* Create a mutex for modules in separate threads to wait for */
-  iReturn = pthread_mutex_init (&pScreenPriv->pmServerStarted, NULL);
-  if (iReturn != 0)
-    {
-      ErrorF ("winFinishScreenInitFB - pthread_mutex_init () failed: %d\n",
-	      iReturn);
-      return FALSE;
-    }
-
-  /* Own the mutex for modules in separate threads */
-  iReturn = pthread_mutex_lock (&pScreenPriv->pmServerStarted);
-  if (iReturn != 0)
-    {
-      ErrorF ("winFinishScreenInitFB - pthread_mutex_lock () failed: %d\n",
-	      iReturn);
-      return FALSE;
-    }
-
-  /* Set the ServerStarted flag to false */
-  pScreenPriv->fServerStarted = FALSE;
-#endif
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-  pScreenPriv->fRestacking = FALSE;
-#endif
-
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-  if (FALSE
-#ifdef XWIN_MULTIWINDOW
-      || pScreenInfo->fMultiWindow
-#endif
-#ifdef XWIN_MULTIWINDOWEXTWM
-      || pScreenInfo->fInternalWM
-#endif
-      )
-    { 
-#if CYGDEBUG || YES
-      winDebug ("winFinishScreenInitFB - Calling winInitWM.\n");
-#endif
-
-      /* Initialize multi window mode */
-      if (!winInitWM (&pScreenPriv->pWMInfo,
-		      &pScreenPriv->ptWMProc,
-		      &pScreenPriv->ptXMsgProc,
-		      &pScreenPriv->pmServerStarted,
-		      pScreenInfo->dwScreen,
-		      (HWND)&pScreenPriv->hwndScreen,
-#ifdef XWIN_MULTIWINDOWEXTWM
-		      pScreenInfo->fInternalWM ||
-#endif
-		      FALSE))
-        {
-          ErrorF ("winFinishScreenInitFB - winInitWM () failed.\n");
-          return FALSE;
-        }
-    }      
-#endif
-
-  /* Tell the server that we are enabled */
-  pScreenPriv->fEnabled = TRUE;
-
-  /* Tell the server that we have a valid depth */
-  pScreenPriv->fBadDepth = FALSE;
-
-#if CYGDEBUG || YES
-  winDebug ("winFinishScreenInitFB - returning\n");
-#endif
-
-  return TRUE;
-}
-
-#ifdef XWIN_NATIVEGDI
-/* See Porting Layer Definition - p. 20 */
-
-Bool
-winFinishScreenInitNativeGDI (int index,
-			      ScreenPtr pScreen,
-			      int argc, char **argv)
-{
-  winScreenPriv(pScreen);
-  winScreenInfoPtr      pScreenInfo = &g_ScreenInfo[index];
-  VisualPtr		pVisuals = NULL;
-  DepthPtr		pDepths = NULL;
-  VisualID		rootVisual = 0;
-  int			nVisuals = 0, nDepths = 0, nRootDepth = 0;
-
-  /* Ignore user input (mouse, keyboard) */
-  pScreenInfo->fIgnoreInput = FALSE;
-
-  /* Get device contexts for the screen and shadow bitmap */
-  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
-  if (pScreenPriv->hdcScreen == NULL)
-    FatalError ("winFinishScreenInitNativeGDI - Couldn't get a DC\n");
-
-  /* Init visuals */
-  if (!(*pScreenPriv->pwinInitVisuals) (pScreen))
-    {
-      ErrorF ("winFinishScreenInitNativeGDI - pwinInitVisuals failed\n");
-      return FALSE;
-    }
-
-  /* Initialize the mi visuals */
-  if (!miInitVisuals (&pVisuals, &pDepths, &nVisuals, &nDepths, &nRootDepth,
-		      &rootVisual,
-		      ((unsigned long)1 << (pScreenInfo->dwDepth - 1)), 8,
-		      TrueColor))
-    {
-      ErrorF ("winFinishScreenInitNativeGDI - miInitVisuals () failed\n");
-      return FALSE;
-    }
-
-  /* Initialize the CloseScreen procedure pointer */
-  pScreen->CloseScreen = NULL;
-
-  /* Initialize the mi code */
-  if (!miScreenInit (pScreen,
-		     NULL, /* No framebuffer */
-		     pScreenInfo->dwWidth, pScreenInfo->dwHeight,
-		     monitorResolution, monitorResolution,
-		     pScreenInfo->dwStride,
-		     nRootDepth, nDepths, pDepths, rootVisual,
-		     nVisuals, pVisuals))
-    {
-      ErrorF ("winFinishScreenInitNativeGDI - miScreenInit failed\n");
-      return FALSE;
-    }
-
-  pScreen->defColormap = FakeClientID(0);
-
-  /*
-   * Register our block and wakeup handlers; these procedures
-   * process messages in our Windows message queue; specifically,
-   * they process mouse and keyboard input.
-   */
-  pScreen->BlockHandler = winBlockHandler;
-  pScreen->WakeupHandler = winWakeupHandler;
-  pScreen->blockData = pScreen;
-  pScreen->wakeupData = pScreen;
-
-  /* Place our save screen function */
-  pScreen->SaveScreen = winSaveScreen;
-
-  /* Pixmaps */
-  pScreen->CreatePixmap = winCreatePixmapNativeGDI;
-  pScreen->DestroyPixmap = winDestroyPixmapNativeGDI;
-
-  /* Other Screen Routines */
-  pScreen->QueryBestSize = winQueryBestSizeNativeGDI;
-  pScreen->SaveScreen = winSaveScreen;  
-  pScreen->GetImage = miGetImage;
-  pScreen->GetSpans = winGetSpansNativeGDI;
-
-  /* Window Procedures */
-  pScreen->CreateWindow = winCreateWindowNativeGDI;
-  pScreen->DestroyWindow = winDestroyWindowNativeGDI;
-  pScreen->PositionWindow = winPositionWindowNativeGDI;
-  /*pScreen->ChangeWindowAttributes = winChangeWindowAttributesNativeGDI;*/
-  pScreen->RealizeWindow = winMapWindowNativeGDI;
-  pScreen->UnrealizeWindow = winUnmapWindowNativeGDI;
-
-  /* Paint window */
-  pScreen->CopyWindow = winCopyWindowNativeGDI;
-
-  /* Fonts */
-  pScreen->RealizeFont = winRealizeFontNativeGDI;
-  pScreen->UnrealizeFont = winUnrealizeFontNativeGDI;
-
-  /* GC */
-  pScreen->CreateGC = winCreateGCNativeGDI;
-
-  /* Colormap Routines */
-  pScreen->CreateColormap = miInitializeColormap;
-  pScreen->DestroyColormap = (DestroyColormapProcPtr) (void (*)(void)) NoopDDA;
-  pScreen->InstallColormap = miInstallColormap;
-  pScreen->UninstallColormap = miUninstallColormap;
-  pScreen->ListInstalledColormaps = miListInstalledColormaps;
-  pScreen->StoreColors = (StoreColorsProcPtr) (void (*)(void)) NoopDDA;
-  pScreen->ResolveColor = miResolveColor;
-
-  /* Bitmap */
-  pScreen->BitmapToRegion = winPixmapToRegionNativeGDI;
-
-  ErrorF ("winFinishScreenInitNativeGDI - calling miDCInitialize\n");
-
-  /* Set the default white and black pixel positions */
-  pScreen->whitePixel = pScreen->blackPixel = (Pixel) 0;
-
-  /* Initialize the cursor */
-  if (!miDCInitialize (pScreen, &g_winPointerCursorFuncs))
-    {
-      ErrorF ("winFinishScreenInitNativeGDI - miDCInitialize failed\n");
-      return FALSE;
-    }
-  
-  /* Create a default colormap */
-  if (!miCreateDefColormap (pScreen))
-    {
-        ErrorF ("winFinishScreenInitNativeGDI - miCreateDefColormap () "
-		"failed\n");
-	return FALSE;
-    }
-
-  ErrorF ("winFinishScreenInitNativeGDI - miCreateDefColormap () "
-	  "returned\n");
-  
-  /* mi doesn't use a CloseScreen procedure, so no need to wrap */
-  pScreen->CloseScreen = pScreenPriv->pwinCloseScreen;
-
-  /* Tell the server that we are enabled */
-  pScreenPriv->fEnabled = TRUE;
-
-  ErrorF ("winFinishScreenInitNativeGDI - Successful addition of "
-	  "screen %08x\n",
-	  (unsigned int) pScreen);
-
-  return TRUE;
-}
-#endif
-
-
-/* See Porting Layer Definition - p. 33 */
-static Bool
-winSaveScreen (ScreenPtr pScreen, int on)
-{
-  return TRUE;
-}
diff --git a/hw/xwin/winsetsp.c b/hw/xwin/winsetsp.c
deleted file mode 100644
index f894d6c..0000000
--- a/hw/xwin/winsetsp.c
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Harold L Hunt II
- * 		Alan Hourihane <alanh at fairlite.demon.co.uk>
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/* See Porting Layer Definition - p. 55 */
-void
-winSetSpansNativeGDI (DrawablePtr	pDrawable,
-		      GCPtr		pGC,
-		      char		*pSrcs,
-		      DDXPointPtr	pPoints,
-		      int		*piWidths,
-		      int		iSpans,
-		      int		fSorted)
-{
-  winGCPriv(pGC);
-  PixmapPtr		pPixmap = NULL;
-  winPrivPixmapPtr	pPixmapPriv = NULL;
-  HBITMAP		hbmpOrig = NULL;
-  BITMAPINFO		bmi;
-  HRGN			hrgn = NULL, combined = NULL;
-  int			nbox;
-  BoxPtr	 	pbox;
-
-  nbox = REGION_NUM_RECTS (pGC->pCompositeClip);
-  pbox = REGION_RECTS (pGC->pCompositeClip);
-
-  if (!nbox) return;
-
-  combined = CreateRectRgn (pbox->x1, pbox->y1, pbox->x2, pbox->y2);
-  nbox--; pbox++;
-  while (nbox--)
-    {
-      hrgn = CreateRectRgn (pbox->x1, pbox->y1, pbox->x2, pbox->y2);
-      CombineRgn (combined, combined, hrgn, RGN_OR);
-      DeleteObject (hrgn);
-      hrgn = NULL;
-      pbox++;
-    }
-
-  /* Branch on the drawable type */
-  switch (pDrawable->type)
-    {
-    case DRAWABLE_PIXMAP:
-
-      SelectClipRgn (pGCPriv->hdcMem, combined);
-      DeleteObject (combined);
-      combined = NULL;
-
-      pPixmap = (PixmapPtr) pDrawable;
-      pPixmapPriv = winGetPixmapPriv (pPixmap);
-      
-      /* Select the drawable pixmap into a DC */
-      hbmpOrig = SelectObject (pGCPriv->hdcMem, pPixmapPriv->hBitmap);
-      if (hbmpOrig == NULL)
-	FatalError ("winSetSpans - DRAWABLE_PIXMAP - SelectObject () "
-		    "failed on pPixmapPriv->hBitmap\n");
-
-      while (iSpans--)
-        {
-	  ZeroMemory (&bmi, sizeof (BITMAPINFO));
-	  bmi.bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
-	  bmi.bmiHeader.biWidth = *piWidths;
-	  bmi.bmiHeader.biHeight = 1;
-	  bmi.bmiHeader.biPlanes = 1;
-	  bmi.bmiHeader.biBitCount = pDrawable->depth;
-	  bmi.bmiHeader.biCompression = BI_RGB;
-
-  	  /* Setup color table for mono DIBs */
-  	  if (pDrawable->depth == 1)
-    	    {
-      	      bmi.bmiColors[1].rgbBlue = 255;
-      	      bmi.bmiColors[1].rgbGreen = 255;
-      	      bmi.bmiColors[1].rgbRed = 255;
-    	    }
-
-	  StretchDIBits (pGCPriv->hdcMem, 
-			 pPoints->x, pPoints->y,
-			 *piWidths, 1,
-			 0, 0,
-			 *piWidths, 1,
-			 pSrcs,
-			 (BITMAPINFO *) &bmi,
-			 DIB_RGB_COLORS,
-			 g_copyROP[pGC->alu]);
-
-	  pSrcs += PixmapBytePad (*piWidths, pDrawable->depth);
-	  pPoints++;
-	  piWidths++;
-        }
-      
-      /* Reset the clip region */
-      SelectClipRgn (pGCPriv->hdcMem, NULL);
-
-      /* Push the drawable pixmap out of the GC HDC */
-      SelectObject (pGCPriv->hdcMem, hbmpOrig);
-      break;
-
-    case DRAWABLE_WINDOW:
-
-      SelectClipRgn (pGCPriv->hdc, combined);
-      DeleteObject (combined);
-      combined = NULL;
-
-      while (iSpans--)
-        {
-	  ZeroMemory (&bmi, sizeof (BITMAPINFO));
-	  bmi.bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
-	  bmi.bmiHeader.biWidth = *piWidths;
-	  bmi.bmiHeader.biHeight = 1;
-	  bmi.bmiHeader.biPlanes = 1;
-	  bmi.bmiHeader.biBitCount = pDrawable->depth;
-	  bmi.bmiHeader.biCompression = BI_RGB;
-
-  	  /* Setup color table for mono DIBs */
-  	  if (pDrawable->depth == 1)
-    	    {
-      	      bmi.bmiColors[1].rgbBlue = 255;
-      	      bmi.bmiColors[1].rgbGreen = 255;
-      	      bmi.bmiColors[1].rgbRed = 255;
-    	    }
-
-	  StretchDIBits (pGCPriv->hdc, 
-			 pPoints->x, pPoints->y,
-			 *piWidths, 1,
-			 0, 0,
-			 *piWidths, 1,
-			 pSrcs,
-			 (BITMAPINFO *) &bmi,
-			 DIB_RGB_COLORS,
-			 g_copyROP[pGC->alu]);
-
-	  pSrcs += PixmapBytePad (*piWidths, pDrawable->depth);
-	  pPoints++;
-	  piWidths++;
-        }
-
-      /* Reset the clip region */
-      SelectClipRgn (pGCPriv->hdc, NULL);
-      break;
-
-    case UNDRAWABLE_WINDOW:
-      FatalError ("\nwinSetSpansNativeGDI - UNDRAWABLE_WINDOW\n\n");
-      break;
-
-    case DRAWABLE_BUFFER:
-      FatalError ("\nwinSetSpansNativeGDI - DRAWABLE_BUFFER\n\n");
-      break;
-      
-    default:
-      FatalError ("\nwinSetSpansNativeGDI - Unknown drawable type\n\n");
-      break;
-    }
-}
diff --git a/hw/xwin/winshaddd.c b/hw/xwin/winshaddd.c
deleted file mode 100644
index a2c1dc9..0000000
--- a/hw/xwin/winshaddd.c
+++ /dev/null
@@ -1,1442 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * External symbols
- */
-
-extern HWND			g_hDlgExit;
-
-
-/*
- * FIXME: Headers are broken, DEFINE_GUID doesn't work correctly,
- * so we have to redefine it here.
- */
-#ifdef DEFINE_GUID
-#undef DEFINE_GUID
-#define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
-#endif /* DEFINE_GUID */
-
-
-/*
- * FIXME: Headers are broken, IID_IDirectDraw4 has to be defined
- * here manually.  Should be handled by ddraw.h
- */
-#ifndef IID_IDirectDraw2
-DEFINE_GUID( IID_IDirectDraw2,0xB3A6F3E0,0x2B43,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xB9,0x33,0x56 );
-#endif /* IID_IDirectDraw2 */
-
-
-/*
- * Local prototypes
- */
-
-static Bool
-winAllocateFBShadowDD (ScreenPtr pScreen);
-
-static void
-winShadowUpdateDD (ScreenPtr pScreen, 
-		   shadowBufPtr pBuf);
-
-static Bool
-winCloseScreenShadowDD (int nIndex, ScreenPtr pScreen);
-
-static Bool
-winInitVisualsShadowDD (ScreenPtr pScreen);
-
-static Bool
-winAdjustVideoModeShadowDD (ScreenPtr pScreen);
-
-static Bool
-winBltExposedRegionsShadowDD (ScreenPtr pScreen);
-
-static Bool
-winActivateAppShadowDD (ScreenPtr pScreen);
-
-static Bool
-winRedrawScreenShadowDD (ScreenPtr pScreen);
-
-static Bool
-winRealizeInstalledPaletteShadowDD (ScreenPtr pScreen);
-
-static Bool
-winInstallColormapShadowDD (ColormapPtr pColormap);
-
-static Bool
-winStoreColorsShadowDD (ColormapPtr pmap, 
-			int ndef,
-			xColorItem *pdefs);
-
-static Bool
-winCreateColormapShadowDD (ColormapPtr pColormap);
-
-static Bool
-winDestroyColormapShadowDD (ColormapPtr pColormap);
-
-static Bool
-winCreatePrimarySurfaceShadowDD (ScreenPtr pScreen);
-
-static Bool
-winReleasePrimarySurfaceShadowDD (ScreenPtr pScreen);
-
-
-/*
- * Create the primary surface and attach the clipper.
- * Used for both the initial surface creation and during
- * WM_DISPLAYCHANGE messages.
- */
-
-static Bool
-winCreatePrimarySurfaceShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  HRESULT		ddrval = DD_OK;
-  DDSURFACEDESC		ddsd;
-
-  /* Describe the primary surface */
-  ZeroMemory (&ddsd, sizeof (ddsd));
-  ddsd.dwSize = sizeof (ddsd);
-  ddsd.dwFlags = DDSD_CAPS;
-  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
-  
-  /* Create the primary surface */
-  ddrval = IDirectDraw2_CreateSurface (pScreenPriv->pdd2,
-				       &ddsd,
-				       &pScreenPriv->pddsPrimary,
-				       NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winCreatePrimarySurfaceShadowDD - Could not create primary "
-	      "surface: %08x\n", (unsigned int) ddrval);
-      return FALSE;
-    }
-  
-#if CYGDEBUG
-  winDebug ("winCreatePrimarySurfaceShadowDD - Created primary surface\n");
-#endif
-
-  /*
-   * Attach a clipper to the primary surface that will clip our blits to our
-   * display window.
-   */
-  ddrval = IDirectDrawSurface2_SetClipper (pScreenPriv->pddsPrimary,
-					   pScreenPriv->pddcPrimary);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winCreatePrimarySurfaceShadowDD - Primary attach clipper "
-	      "failed: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winCreatePrimarySurfaceShadowDD - Attached clipper to "
-	  "primary surface\n");
-#endif
-
-  /* Everything was correct */
-  return TRUE;
-}
-
-
-/*
- * Detach the clipper and release the primary surface.
- * Called from WM_DISPLAYCHANGE.
- */
-
-static Bool
-winReleasePrimarySurfaceShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-
-  ErrorF ("winReleasePrimarySurfaceShadowDD - Hello\n");
-
-  /* Release the primary surface and clipper, if they exist */
-  if (pScreenPriv->pddsPrimary)
-    {
-      /*
-       * Detach the clipper from the primary surface.
-       * NOTE: We do this explicity for clarity.  The Clipper is not released.
-       */
-      IDirectDrawSurface2_SetClipper (pScreenPriv->pddsPrimary,
-				      NULL);
-
-      ErrorF ("winReleasePrimarySurfaceShadowDD - Detached clipper\n");
-
-      /* Release the primary surface */
-      IDirectDrawSurface2_Release (pScreenPriv->pddsPrimary);
-      pScreenPriv->pddsPrimary = NULL;
-    }
-
-  ErrorF ("winReleasePrimarySurfaceShadowDD - Released primary surface\n");
-
-  return TRUE;
-}
-
-
-/*
- * Create a DirectDraw surface for the shadow framebuffer; also create
- * a primary surface object so we can blit to the display.
- * 
- * Install a DirectDraw clipper on our primary surface object
- * that clips our blits to the unobscured client area of our display window.
- */
-
-static Bool
-winAllocateFBShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;  
-  HRESULT		ddrval = DD_OK;
-  DDSURFACEDESC		ddsd;
-  DDSURFACEDESC		*pddsdShadow = NULL;
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD\n");
-#endif
-
-  /* Create a clipper */
-  ddrval = (*g_fpDirectDrawCreateClipper) (0,
-					   &pScreenPriv->pddcPrimary,
-					   NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDD - Could not create clipper: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD - Created a clipper\n");
-#endif
-
-  /* Get a device context for the screen  */
-  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
-
-  /* Attach the clipper to our display window */
-  ddrval = IDirectDrawClipper_SetHWnd (pScreenPriv->pddcPrimary,
-				       0,
-				       pScreenPriv->hwndScreen);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDD - Clipper not attached to "
-	      "window: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD - Attached clipper to window\n");
-#endif
-
-  /* Create a DirectDraw object, store the address at lpdd */
-  ddrval = (*g_fpDirectDrawCreate) (NULL, &pScreenPriv->pdd, NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDD - Could not start DirectDraw: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD () - Created and initialized DD\n");
-#endif
-
-  /* Get a DirectDraw2 interface pointer */
-  ddrval = IDirectDraw_QueryInterface (pScreenPriv->pdd,
-				       &IID_IDirectDraw2,
-				       (LPVOID*) &pScreenPriv->pdd2);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDD - Failed DD2 query: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-  /* Are we full screen? */
-  if (pScreenInfo->fFullScreen)
-    {
-      DDSURFACEDESC	ddsdCurrent;
-      DWORD		dwRefreshRateCurrent = 0;
-      HDC		hdc = NULL;
-
-      /* Set the cooperative level to full screen */
-      ddrval = IDirectDraw2_SetCooperativeLevel (pScreenPriv->pdd2,
-						 pScreenPriv->hwndScreen,
-						 DDSCL_EXCLUSIVE
-						 | DDSCL_FULLSCREEN);
-      if (FAILED (ddrval))
-	{
-	  ErrorF ("winAllocateFBShadowDD - Could not set "
-		  "cooperative level: %08x\n",
-		  (unsigned int) ddrval);
-	  return FALSE;
-	}
-
-      /*
-       * We only need to get the current refresh rate for comparison
-       * if a refresh rate has been passed on the command line.
-       */
-      if (pScreenInfo->dwRefreshRate != 0)
-	{
-	  ZeroMemory (&ddsdCurrent, sizeof (ddsdCurrent));
-	  ddsdCurrent.dwSize = sizeof (ddsdCurrent);
-	  
-	  /* Get information about current display settings */
-	  ddrval = IDirectDraw2_GetDisplayMode (pScreenPriv->pdd2,
-						&ddsdCurrent);
-	  if (FAILED (ddrval))
-	    {
-	      ErrorF ("winAllocateFBShadowDD - Could not get current "
-		      "refresh rate: %08x.  Continuing.\n",
-		      (unsigned int) ddrval);
-	      dwRefreshRateCurrent = 0;
-	    }
-	  else
-	    {
-	      /* Grab the current refresh rate */
-	      dwRefreshRateCurrent = ddsdCurrent.u2.dwRefreshRate;
-	    }
-	}
-
-      /* Clean up the refresh rate */
-      if (dwRefreshRateCurrent == pScreenInfo->dwRefreshRate)
-	{
-	  /*
-	   * Refresh rate is non-specified or equal to current.
-	   */
-	  pScreenInfo->dwRefreshRate = 0;
-	}
-
-      /* Grab a device context for the screen */
-      hdc = GetDC (NULL);
-      if (hdc == NULL)
-	{
-	  ErrorF ("winAllocateFBShadowDD - GetDC () failed\n");
-	  return FALSE;
-	}
-
-      /* Only change the video mode when different than current mode */
-      if (!pScreenInfo->fMultipleMonitors
-	  && (pScreenInfo->dwWidth != GetSystemMetrics (SM_CXSCREEN)
-	      || pScreenInfo->dwHeight != GetSystemMetrics (SM_CYSCREEN)
-	      || pScreenInfo->dwBPP != GetDeviceCaps (hdc, BITSPIXEL)
-	      || pScreenInfo->dwRefreshRate != 0))
-	{
-	  ErrorF ("winAllocateFBShadowDD - Changing video mode\n");
-
-	  /* Change the video mode to the mode requested */
-	  ddrval = IDirectDraw2_SetDisplayMode (pScreenPriv->pdd2,
-						pScreenInfo->dwWidth,
-						pScreenInfo->dwHeight,
-						pScreenInfo->dwBPP,
-						pScreenInfo->dwRefreshRate,
-						0);
-	  if (FAILED (ddrval))
-	    {
-	      ErrorF ("winAllocateFBShadowDD - Could not set "\
-		      "full screen display mode: %08x\n",
-		      (unsigned int) ddrval);
-	      return FALSE;
-	    }
-	}
-      else
-	{
-	  ErrorF ("winAllocateFBShadowDD - Not changing video mode\n");
-	}
-
-      /* Release our DC */
-      ReleaseDC (NULL, hdc);
-      hdc = NULL;
-    }
-  else
-    {
-      /* Set the cooperative level for windowed mode */
-      ddrval = IDirectDraw2_SetCooperativeLevel (pScreenPriv->pdd2,
-						 pScreenPriv->hwndScreen,
-						 DDSCL_NORMAL);
-      if (FAILED (ddrval))
-	{
-	  ErrorF ("winAllocateFBShadowDD - Could not set "\
-		  "cooperative level: %08x\n",
-		  (unsigned int) ddrval);
-	  return FALSE;
-	}
-    }
-
-  /* Create the primary surface */
-  if (!winCreatePrimarySurfaceShadowDD (pScreen))
-    {
-      ErrorF ("winAllocateFBShadowDD - winCreatePrimarySurfaceShadowDD "
-	      "failed\n");
-      return FALSE;
-    }
-
-  /* Describe the shadow surface to be created */
-  /* NOTE: Do not use a DDSCAPS_VIDEOMEMORY surface,
-   * as drawing, locking, and unlocking take forever
-   * with video memory surfaces.  In addition,
-   * video memory is a somewhat scarce resource,
-   * so you shouldn't be allocating video memory when
-   * you have the option of using system memory instead.
-   */
-  ZeroMemory (&ddsd, sizeof (ddsd));
-  ddsd.dwSize = sizeof (ddsd);
-  ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
-  ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
-  ddsd.dwHeight = pScreenInfo->dwHeight;
-  ddsd.dwWidth = pScreenInfo->dwWidth;
-
-  /* Create the shadow surface */
-  ddrval = IDirectDraw2_CreateSurface (pScreenPriv->pdd2,
-				       &ddsd,
-				       &pScreenPriv->pddsShadow,
-				       NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDD - Could not create shadow "\
-	      "surface: %08x\n", (unsigned int) ddrval);
-      return FALSE;
-    }
-  
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD - Created shadow\n");
-#endif
-
-  /* Allocate a DD surface description for our screen privates */
-  pddsdShadow = pScreenPriv->pddsdShadow = malloc (sizeof (DDSURFACEDESC));
-  if (pddsdShadow == NULL)
-    {
-      ErrorF ("winAllocateFBShadowDD - Could not allocate surface "\
-	      "description memory\n");
-      return FALSE;
-    }
-  ZeroMemory (pddsdShadow, sizeof (*pddsdShadow));
-  pddsdShadow->dwSize = sizeof (*pddsdShadow);
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD - Locking shadow\n");
-#endif
-
-  /* Lock the shadow surface */
-  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
-				     NULL,
-				     pddsdShadow,
-				     DDLOCK_WAIT,
-				     NULL);
-  if (FAILED (ddrval) || pddsdShadow->lpSurface == NULL)
-    {
-      ErrorF ("winAllocateFBShadowDD - Could not lock shadow "\
-	      "surface: %08x\n", (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD - Locked shadow\n");
-#endif
-
-  /* We don't know how to deal with anything other than RGB */
-  if (!(pddsdShadow->ddpfPixelFormat.dwFlags & DDPF_RGB))
-    {
-      ErrorF ("winAllocateFBShadowDD - Color format other than RGB\n");
-      return FALSE;
-    }
-
-  /* Grab the pitch from the surface desc */
-  pScreenInfo->dwStride = (pddsdShadow->u1.lPitch * 8)
-    / pScreenInfo->dwBPP;
-
-  /* Save the pointer to our surface memory */
-  pScreenInfo->pfb = pddsdShadow->lpSurface;
-  
-  /* Grab the color depth and masks from the surface description */
-  pScreenPriv->dwRedMask = pddsdShadow->ddpfPixelFormat.u2.dwRBitMask;
-  pScreenPriv->dwGreenMask = pddsdShadow->ddpfPixelFormat.u3.dwGBitMask;
-  pScreenPriv->dwBlueMask = pddsdShadow->ddpfPixelFormat.u4.dwBBitMask;
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDD - Returning\n");
-#endif
-
-  return TRUE;
-}
-
-
-/*
- * Transfer the damaged regions of the shadow framebuffer to the display.
- */
-
-static void
-winShadowUpdateDD (ScreenPtr pScreen, 
-		   shadowBufPtr pBuf)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  RegionPtr		damage = &pBuf->damage;
-  HRESULT		ddrval = DD_OK;
-  RECT			rcDest, rcSrc;
-  POINT			ptOrigin;
-  DWORD			dwBox = REGION_NUM_RECTS (damage);
-  BoxPtr		pBox = REGION_RECTS (damage);
-  HRGN			hrgnTemp = NULL, hrgnCombined = NULL;
-
-  /*
-   * Return immediately if the app is not active
-   * and we are fullscreen, or if we have a bad display depth
-   */
-  if ((!pScreenPriv->fActive && pScreenInfo->fFullScreen)
-      || pScreenPriv->fBadDepth) return;
-
-  /* Get the origin of the window in the screen coords */
-  ptOrigin.x = pScreenInfo->dwXOffset;
-  ptOrigin.y = pScreenInfo->dwYOffset;
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&ptOrigin, 1);
-
-  /* Unlock the shadow surface, so we can blit */
-  ddrval = IDirectDrawSurface2_Unlock (pScreenPriv->pddsShadow, NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winShadowUpdateProcDD - Unlock failed\n");
-      return;
-    }
-
-  /*
-   * Handle small regions with multiple blits,
-   * handle large regions by creating a clipping region and 
-   * doing a single blit constrained to that clipping region.
-   */
-  if (pScreenInfo->dwClipUpdatesNBoxes == 0
-      || dwBox < pScreenInfo->dwClipUpdatesNBoxes)
-    {
-      /* Loop through all boxes in the damaged region */
-      while (dwBox--)
-	{
-	  /* Assign damage box to source rectangle */
-	  rcSrc.left = pBox->x1;
-	  rcSrc.top = pBox->y1;
-	  rcSrc.right = pBox->x2;
-	  rcSrc.bottom = pBox->y2;
-	  
-	  /* Calculate destination rectange */
-	  rcDest.left = ptOrigin.x + rcSrc.left;
-	  rcDest.top = ptOrigin.y + rcSrc.top;
-	  rcDest.right = ptOrigin.x + rcSrc.right;
-	  rcDest.bottom = ptOrigin.y + rcSrc.bottom;
-	  
-	  /* Blit the damaged areas */
-	  ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
-					    &rcDest,
-					    pScreenPriv->pddsShadow,
-					    &rcSrc,
-					    DDBLT_WAIT,
-					    NULL);
-	  
-	  /* Get a pointer to the next box */
-	  ++pBox;
-	}
-    }
-  else
-    {
-      BoxPtr		pBoxExtents = REGION_EXTENTS (pScreen, damage);
-
-      /* Compute a GDI region from the damaged region */
-      hrgnCombined = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
-      dwBox--;
-      pBox++;
-      while (dwBox--)
-	{
-	  hrgnTemp = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
-	  CombineRgn (hrgnCombined, hrgnCombined, hrgnTemp, RGN_OR);
-	  DeleteObject (hrgnTemp);
-	  pBox++;
-	}  
-
-      /* Install the GDI region as a clipping region */
-      SelectClipRgn (pScreenPriv->hdcScreen, hrgnCombined);
-      DeleteObject (hrgnCombined);
-      hrgnCombined = NULL;
-
-      /* Calculating a bounding box for the source is easy */
-      rcSrc.left = pBoxExtents->x1;
-      rcSrc.top = pBoxExtents->y1;
-      rcSrc.right = pBoxExtents->x2;
-      rcSrc.bottom = pBoxExtents->y2;
-
-      /* Calculating a bounding box for the destination is trickier */
-      rcDest.left = ptOrigin.x + rcSrc.left;
-      rcDest.top = ptOrigin.y + rcSrc.top;
-      rcDest.right = ptOrigin.x + rcSrc.right;
-      rcDest.bottom = ptOrigin.y + rcSrc.bottom;
-      
-      /* Our Blt should be clipped to the invalidated region */
-      ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
-					&rcDest,
-					pScreenPriv->pddsShadow,
-					&rcSrc,
-					DDBLT_WAIT,
-					NULL);
-
-      /* Reset the clip region */
-      SelectClipRgn (pScreenPriv->hdcScreen, NULL);
-    }
-
-  /* Relock the shadow surface */
-  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
-				     NULL,
-				     pScreenPriv->pddsdShadow,
-				     DDLOCK_WAIT,
-				     NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winShadowUpdateProcDD - Lock failed\n");
-      return;
-    }
-
-  /* Has our memory pointer changed? */
-  if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface)
-    {
-      ErrorF ("winShadowUpdateProcDD - Memory location of the shadow "
-	      "surface has changed, trying to update the root window "
-	      "pixmap header to point to the new address.  If you get "
-	      "this message and "PROJECT_NAME" freezes or crashes "
-	      "after this message then send a problem report and your "
-	      "/tmp/XWin.log file to cygwin-xfree at cygwin.com\n");
-
-      /* Location of shadow framebuffer has changed */
-      pScreenInfo->pfb = pScreenPriv->pddsdShadow->lpSurface;
-      
-      /* Update the screen pixmap */
-      if (!(*pScreen->ModifyPixmapHeader)(pScreen->devPrivate,
-					  pScreen->width,
-					  pScreen->height,
-					  pScreen->rootDepth,
-					  BitsPerPixel (pScreen->rootDepth),
-					  PixmapBytePad (pScreenInfo->dwStride,
-							 pScreenInfo->dwBPP),
-					  pScreenInfo->pfb))
-	{
-	  ErrorF ("winShadowUpdateProcDD - Bits changed, could not "
-		  "notify fb.\n");
-	  return;
-	}
-    }
-}
-
-
-/*
- * Call the wrapped CloseScreen function.
- * 
- * Free our resources and private structures.
- */
-
-static Bool
-winCloseScreenShadowDD (int nIndex, ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  Bool			fReturn;
-  
-#if CYGDEBUG
-  winDebug ("winCloseScreenShadowDD - Freeing screen resources\n");
-#endif
-
-  /* Flag that the screen is closed */
-  pScreenPriv->fClosed = TRUE;
-  pScreenPriv->fActive = FALSE;
-
-  /* Call the wrapped CloseScreen procedure */
-  WIN_UNWRAP(CloseScreen);
-  fReturn = (*pScreen->CloseScreen) (nIndex, pScreen);
-
-  /* Free the screen DC */
-  ReleaseDC (pScreenPriv->hwndScreen, pScreenPriv->hdcScreen);
-
-  /* Delete the window property */
-  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
-
-  /* Free the shadow surface, if there is one */
-  if (pScreenPriv->pddsShadow)
-    {
-      IDirectDrawSurface2_Unlock (pScreenPriv->pddsShadow, NULL);
-      IDirectDrawSurface2_Release (pScreenPriv->pddsShadow);
-      pScreenPriv->pddsShadow = NULL;
-    }
-
-  /* Detach the clipper from the primary surface and release the clipper. */
-  if (pScreenPriv->pddcPrimary)
-    {
-      /* Detach the clipper */
-      IDirectDrawSurface2_SetClipper (pScreenPriv->pddsPrimary,
-				      NULL);
-
-      /* Release the clipper object */
-      IDirectDrawClipper_Release (pScreenPriv->pddcPrimary);
-      pScreenPriv->pddcPrimary = NULL;
-    }
-
-  /* Release the primary surface, if there is one */
-  if (pScreenPriv->pddsPrimary)
-    {
-      IDirectDrawSurface2_Release (pScreenPriv->pddsPrimary);
-      pScreenPriv->pddsPrimary = NULL;
-    }
-
-  /* Free the DirectDraw2 object, if there is one */
-  if (pScreenPriv->pdd2)
-    {
-      IDirectDraw2_RestoreDisplayMode (pScreenPriv->pdd2);
-      IDirectDraw2_Release (pScreenPriv->pdd2);
-      pScreenPriv->pdd2 = NULL;
-    }
-
-  /* Free the DirectDraw object, if there is one */
-  if (pScreenPriv->pdd)
-    {
-      IDirectDraw_Release (pScreenPriv->pdd);
-      pScreenPriv->pdd = NULL;
-    }
-
-  /* Delete tray icon, if we have one */
-  if (!pScreenInfo->fNoTrayIcon)
-    winDeleteNotifyIcon (pScreenPriv);
-  
-  /* Free the exit confirmation dialog box, if it exists */
-  if (g_hDlgExit != NULL)
-    {
-      DestroyWindow (g_hDlgExit);
-      g_hDlgExit = NULL;
-    }
-
-  /* Kill our window */
-  if (pScreenPriv->hwndScreen)
-    {
-      DestroyWindow (pScreenPriv->hwndScreen);
-      pScreenPriv->hwndScreen = NULL;
-    }
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  /* Destroy the thread startup mutex */
-  pthread_mutex_destroy (&pScreenPriv->pmServerStarted);
-#endif
-
-  /* Kill our screeninfo's pointer to the screen */
-  pScreenInfo->pScreen = NULL;
-
-  /* Invalidate the ScreenInfo's fb pointer */
-  pScreenInfo->pfb = NULL;
-
-  /* Free the screen privates for this screen */
-  free ((pointer) pScreenPriv);
-
-  return fReturn;
-}
-
-
-/*
- * Tell mi what sort of visuals we need.
- * 
- * Generally we only need one visual, as our screen can only
- * handle one format at a time, I believe.  You may want
- * to verify that last sentence.
- */
-
-static Bool
-winInitVisualsShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  DWORD			dwRedBits, dwGreenBits, dwBlueBits;
-
-  /* Count the number of ones in each color mask */
-  dwRedBits = winCountBits (pScreenPriv->dwRedMask);
-  dwGreenBits = winCountBits (pScreenPriv->dwGreenMask);
-  dwBlueBits = winCountBits (pScreenPriv->dwBlueMask);
-  
-  /* Store the maximum number of ones in a color mask as the bitsPerRGB */
-  if (dwRedBits == 0 || dwGreenBits == 0 || dwBlueBits == 0)
-    pScreenPriv->dwBitsPerRGB = 8;
-  else if (dwRedBits > dwGreenBits && dwRedBits > dwBlueBits)
-    pScreenPriv->dwBitsPerRGB = dwRedBits;
-  else if (dwGreenBits > dwRedBits && dwGreenBits > dwBlueBits)
-    pScreenPriv->dwBitsPerRGB = dwGreenBits;
-  else
-    pScreenPriv->dwBitsPerRGB = dwBlueBits;
-  
-  ErrorF ("winInitVisualsShadowDD - Masks %08x %08x %08x BPRGB %d d %d "
-	  "bpp %d\n",
-	  (unsigned int) pScreenPriv->dwRedMask,
-	  (unsigned int) pScreenPriv->dwGreenMask,
-	  (unsigned int) pScreenPriv->dwBlueMask,
-	  (int) pScreenPriv->dwBitsPerRGB,
-	  (int) pScreenInfo->dwDepth,
-	  (int) pScreenInfo->dwBPP);
-
-  /* Create a single visual according to the Windows screen depth */
-  switch (pScreenInfo->dwDepth)
-    {
-    case 24:
-    case 16:
-    case 15:
-#if defined(XFree86Server)
-      /* Create the real visual */
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     TrueColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     TrueColor,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDD - miSetVisualTypesAndMasks "
-		  "failed for TrueColor\n");
-	  return FALSE;
-	}
-
-#ifdef XWIN_EMULATEPSEUDO
-      if (!pScreenInfo->fEmulatePseudo)
-	break;
-
-      /* Setup a pseudocolor visual */
-      if (!miSetVisualTypesAndMasks (8,
-				     PseudoColorMask,
-				     8,
-				     -1,
-				     0,
-				     0,
-				     0))
-	{
-	  ErrorF ("winInitVisualsShadowDD - miSetVisualTypesAndMasks "
-		  "failed for PseudoColor\n");
-	  return FALSE;
-	}
-#endif
-#else /* XFree86Server */
-      /* Create the real visual */
-      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     TrueColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDD - fbSetVisualTypesAndMasks "
-		  "failed for TrueColor\n");
-	  return FALSE;
-	}
-
-#ifdef XWIN_EMULATEPSEUDO
-      if (!pScreenInfo->fEmulatePseudo)
-	break;
-
-      /* Setup a pseudocolor visual */
-      if (!fbSetVisualTypesAndMasks (8,
-				     PseudoColorMask,
-				     8,
-				     0,
-				     0,
-				     0))
-	{
-	  ErrorF ("winInitVisualsShadowDD - fbSetVisualTypesAndMasks "
-		  "failed for PseudoColor\n");
-	  return FALSE;
-	}
-#endif
-#endif /* XFree86Server */
-      break;
-
-    case 8:
-#if defined(XFree86Server)
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     pScreenInfo->fFullScreen 
-				     ? PseudoColorMask : StaticColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenInfo->fFullScreen 
-				     ? PseudoColor : StaticColor,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDD - miSetVisualTypesAndMasks "
-		  "failed\n");
-	  return FALSE;
-	}
-#else /* XFree86Server */
-      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     pScreenInfo->fFullScreen 
-				     ? PseudoColorMask : StaticColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDD - fbSetVisualTypesAndMasks "
-		  "failed\n");
-	  return FALSE;
-	}
-#endif /* XFree86Server */
-      break;
-
-    default:
-      ErrorF ("winInitVisualsShadowDD - Unknown screen depth\n");
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winInitVisualsShadowDD - Returning\n");
-#endif
-
-  return TRUE;
-}
-
-
-/*
- * Adjust the user proposed video mode
- */
-
-static Bool
-winAdjustVideoModeShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  HDC			hdc = NULL;
-  DWORD			dwBPP;
-
-  /* We're in serious trouble if we can't get a DC */
-  hdc = GetDC (NULL);
-  if (hdc == NULL)
-    {
-      ErrorF ("winAdjustVideoModeShadowDD - GetDC () failed\n");
-      return FALSE;
-    }
-
-  /* Query GDI for current display depth */
-  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
-
-  /* DirectDraw can only change the depth in fullscreen mode */
-  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
-    {
-      /* No -depth parameter passed, let the user know the depth being used */
-      ErrorF ("winAdjustVideoModeShadowDD - Using Windows display "
-	      "depth of %d bits per pixel\n", (int) dwBPP);
-
-      /* Use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-  else if (pScreenInfo->fFullScreen
-	   && pScreenInfo->dwBPP != dwBPP)
-    {
-      /* FullScreen, and GDI depth differs from -depth parameter */
-      ErrorF ("winAdjustVideoModeShadowDD - FullScreen, using command line "
-	      "bpp: %d\n", (int) pScreenInfo->dwBPP);
-    }
-  else if (dwBPP != pScreenInfo->dwBPP)
-    {
-      /* Windowed, and GDI depth differs from -depth parameter */
-      ErrorF ("winAdjustVideoModeShadowDD - Windowed, command line bpp: "
-	      "%d, using bpp: %d\n", (int) pScreenInfo->dwBPP, (int) dwBPP);
-
-      /* We'll use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-  
-  /* See if the shadow bitmap will be larger than the DIB size limit */
-  if (pScreenInfo->dwWidth * pScreenInfo->dwHeight * pScreenInfo->dwBPP
-      >= WIN_DIB_MAXIMUM_SIZE)
-    {
-      ErrorF ("winAdjustVideoModeShadowDD - Requested DirectDraw surface "
-	      "will be larger than %d MB.  The surface may fail to be "
-	      "allocated on Windows 95, 98, or Me, due to a %d MB limit in "
-	      "DIB size.  This limit does not apply to Windows NT/2000, and "
-	      "this message may be ignored on those platforms.\n",
-	      WIN_DIB_MAXIMUM_SIZE_MB, WIN_DIB_MAXIMUM_SIZE_MB);
-    }
-
-  /* Release our DC */
-  ReleaseDC (NULL, hdc);
-  return TRUE;
-}
-
-
-/*
- * Blt exposed regions to the screen
- */
-
-static Bool
-winBltExposedRegionsShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  RECT			rcSrc, rcDest;
-  POINT			ptOrigin;
-  HDC			hdcUpdate = NULL;
-  PAINTSTRUCT		ps;
-  HRESULT		ddrval = DD_OK;
-  Bool			fReturn = TRUE;
-  Bool			fLocked = TRUE;
-  int			i;
-
-  /* BeginPaint gives us an hdc that clips to the invalidated region */
-  hdcUpdate = BeginPaint (pScreenPriv->hwndScreen, &ps);
-  if (hdcUpdate == NULL)
-    {
-      ErrorF ("winBltExposedRegionsShadowDD - BeginPaint () returned "
-	      "a NULL device context handle.  Aborting blit attempt.\n");
-      return FALSE;
-    }
-  
-  /* Unlock the shadow surface, so we can blit */
-  ddrval = IDirectDrawSurface2_Unlock (pScreenPriv->pddsShadow, NULL);
-  if (FAILED (ddrval))
-    {
-      fReturn = FALSE;
-      goto winBltExposedRegionsShadowDD_Exit;
-    }
-  else
-    {
-      /* Flag that we have unlocked the shadow surface */
-      fLocked = FALSE;
-    }
-
-  /* Get the origin of the window in the screen coords */
-  ptOrigin.x = pScreenInfo->dwXOffset;
-  ptOrigin.y = pScreenInfo->dwYOffset;
-
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&ptOrigin, 1);
-  rcDest.left = ptOrigin.x;
-  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
-  rcDest.top = ptOrigin.y;
-  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
-
-  /* Source can be enter shadow surface, as Blt should clip */
-  rcSrc.left = 0;
-  rcSrc.top = 0;
-  rcSrc.right = pScreenInfo->dwWidth;
-  rcSrc.bottom = pScreenInfo->dwHeight;
-
-  /* Try to regain the primary surface and blit again if we've lost it */
-  for (i = 0; i <= WIN_REGAIN_SURFACE_RETRIES; ++i)
-    {
-      /* Our Blt should be clipped to the invalidated region */
-      ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
-					&rcDest,
-					pScreenPriv->pddsShadow,
-					&rcSrc,
-					DDBLT_WAIT,
-					NULL);
-      if (ddrval == DDERR_SURFACELOST)
-	{
-	  /* Surface was lost */
-	  ErrorF ("winBltExposedRegionsShadowDD - IDirectDrawSurface2_Blt "
-		  "reported that the primary surface was lost, "
-		  "trying to restore, retry: %d\n", i + 1);
-
-	  /* Try to restore the surface, once */
-	  ddrval = IDirectDrawSurface2_Restore (pScreenPriv->pddsPrimary);
-	  ErrorF ("winBltExposedRegionsShadowDD - "
-		  "IDirectDrawSurface2_Restore returned: ");
-	  if (ddrval == DD_OK)
-	    ErrorF ("DD_OK\n");
-	  else if (ddrval == DDERR_WRONGMODE)
-	    ErrorF ("DDERR_WRONGMODE\n");
-	  else if (ddrval == DDERR_INCOMPATIBLEPRIMARY)
-	    ErrorF ("DDERR_INCOMPATIBLEPRIMARY\n");
-	  else if (ddrval == DDERR_UNSUPPORTED)
-	    ErrorF ("DDERR_UNSUPPORTED\n");
-	  else if (ddrval == DDERR_INVALIDPARAMS)
-	    ErrorF ("DDERR_INVALIDPARAMS\n");
-	  else if (ddrval == DDERR_INVALIDOBJECT)
-	    ErrorF ("DDERR_INVALIDOBJECT\n");
-	  else
-	    ErrorF ("unknown error: %08x\n", (unsigned int) ddrval);
-
-	  /* Loop around to try the blit one more time */
-	  continue;
-	}
-      else if (FAILED (ddrval))
-	{
-	  fReturn = FALSE;
-	  ErrorF ("winBltExposedRegionsShadowDD - IDirectDrawSurface2_Blt "
-		  "failed, but surface not lost: %08x %d\n",
-		  (unsigned int) ddrval, (int) ddrval);
-	  goto winBltExposedRegionsShadowDD_Exit;
-	}
-      else
-	{
-	  /* Success, stop looping */
-	  break;
-	}
-    }
-
-  /* Relock the shadow surface */
-  ddrval = IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
-				     NULL,
-				     pScreenPriv->pddsdShadow,
-				     DDLOCK_WAIT,
-				     NULL);
-  if (FAILED (ddrval))
-    {
-      fReturn = FALSE;
-      ErrorF ("winBltExposedRegionsShadowDD - IDirectDrawSurface2_Lock "
-	      "failed\n");
-      goto winBltExposedRegionsShadowDD_Exit;
-    }
-  else
-    {
-      /* Indicate that we have relocked the shadow surface */
-      fLocked = TRUE;
-    }
-
-  /* Has our memory pointer changed? */
-  if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface)
-    winUpdateFBPointer (pScreen,
-			pScreenPriv->pddsdShadow->lpSurface);
-
- winBltExposedRegionsShadowDD_Exit:
-  /* EndPaint frees the DC */
-  if (hdcUpdate != NULL)
-    EndPaint (pScreenPriv->hwndScreen, &ps);
-
-  /*
-   * Relock the surface if it is not locked.  We don't care if locking fails,
-   * as it will cause the server to shutdown within a few more operations.
-   */
-  if (!fLocked)
-    {
-      IDirectDrawSurface2_Lock (pScreenPriv->pddsShadow,
-				NULL,
-				pScreenPriv->pddsdShadow,
-				DDLOCK_WAIT,
-				NULL);
-
-      /* Has our memory pointer changed? */
-      if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface)
-	winUpdateFBPointer (pScreen,
-			    pScreenPriv->pddsdShadow->lpSurface);
-      
-      fLocked = TRUE;
-    }
-  return fReturn;
-}
-
-
-/*
- * Do any engine-specific appliation-activation processing
- */
-
-static Bool
-winActivateAppShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-
-  /*
-   * Do we have a surface?
-   * Are we active?
-   * Are we fullscreen?
-   */
-  if (pScreenPriv != NULL
-      && pScreenPriv->pddsPrimary != NULL
-      && pScreenPriv->fActive)
-    {
-      /* Primary surface was lost, restore it */
-      IDirectDrawSurface2_Restore (pScreenPriv->pddsPrimary);
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Reblit the shadow framebuffer to the screen.
- */
-
-static Bool
-winRedrawScreenShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  HRESULT		ddrval = DD_OK;
-  RECT			rcSrc, rcDest;
-  POINT			ptOrigin;
-
-  /* Get the origin of the window in the screen coords */
-  ptOrigin.x = pScreenInfo->dwXOffset;
-  ptOrigin.y = pScreenInfo->dwYOffset;
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&ptOrigin, 1);
-  rcDest.left = ptOrigin.x;
-  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
-  rcDest.top = ptOrigin.y;
-  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
-
-  /* Source can be entire shadow surface, as Blt should clip for us */
-  rcSrc.left = 0;
-  rcSrc.top = 0;
-  rcSrc.right = pScreenInfo->dwWidth;
-  rcSrc.bottom = pScreenInfo->dwHeight;
-
-  /* Redraw the whole window, to take account for the new colors */
-  ddrval = IDirectDrawSurface2_Blt (pScreenPriv->pddsPrimary,
-				    &rcDest,
-				    pScreenPriv->pddsShadow,
-				    &rcSrc,
-				    DDBLT_WAIT,
-				    NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winRedrawScreenShadowDD - IDirectDrawSurface_Blt () "
-	      "failed: %08x\n",
-	      (unsigned int) ddrval);
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Realize the currently installed colormap
- */
-
-static Bool
-winRealizeInstalledPaletteShadowDD (ScreenPtr pScreen)
-{
-  return TRUE;
-}
-
-
-/*
- * Install the specified colormap
- */
-
-static Bool
-winInstallColormapShadowDD (ColormapPtr pColormap)
-{
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  HRESULT		ddrval = DD_OK;
-
-  /* Install the DirectDraw palette on the primary surface */
-  ddrval = IDirectDrawSurface2_SetPalette (pScreenPriv->pddsPrimary,
-					   pCmapPriv->lpDDPalette);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winInstallColormapShadowDD - Failed installing the "
-	      "DirectDraw palette.\n");
-      return FALSE;
-    }
-
-  /* Save a pointer to the newly installed colormap */
-  pScreenPriv->pcmapInstalled = pColormap;
-
-  return TRUE;
-}
-
-
-/*
- * Store the specified colors in the specified colormap
- */
-
-static Bool
-winStoreColorsShadowDD (ColormapPtr pColormap, 
-			int ndef,
-			xColorItem *pdefs)
-{
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  ColormapPtr		curpmap = pScreenPriv->pcmapInstalled;
-  HRESULT		ddrval = DD_OK;
-  
-  /* Put the X colormap entries into the Windows logical palette */
-  ddrval = IDirectDrawPalette_SetEntries (pCmapPriv->lpDDPalette,
-					  0,
-					  pdefs[0].pixel,
-					  ndef,
-					  pCmapPriv->peColors 
-					  + pdefs[0].pixel);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winStoreColorsShadowDD - SetEntries () failed\n");
-      return FALSE;
-    }
-
-  /* Don't install the DirectDraw palette if the colormap is not installed */
-  if (pColormap != curpmap)
-    {
-      return TRUE;
-    }
-
-  if (!winInstallColormapShadowDD (pColormap))
-    {
-      ErrorF ("winStoreColorsShadowDD - Failed installing colormap\n");
-      return FALSE;
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Colormap initialization procedure
- */
-
-static Bool
-winCreateColormapShadowDD (ColormapPtr pColormap)
-{
-  HRESULT		ddrval = DD_OK;
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  
-  /* Create a DirectDraw palette */
-  ddrval = IDirectDraw2_CreatePalette (pScreenPriv->pdd,
-				       DDPCAPS_8BIT | DDPCAPS_ALLOW256,
-				       pCmapPriv->peColors,
-				       &pCmapPriv->lpDDPalette,
-				       NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winCreateColormapShadowDD - CreatePalette failed\n");
-      return FALSE;
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Colormap destruction procedure
- */
-
-static Bool
-winDestroyColormapShadowDD (ColormapPtr pColormap)
-{
-  winScreenPriv(pColormap->pScreen);
-  winCmapPriv(pColormap);
-  HRESULT		ddrval = DD_OK;
-
-  /*
-   * Is colormap to be destroyed the default?
-   *
-   * Non-default colormaps should have had winUninstallColormap
-   * called on them before we get here.  The default colormap
-   * will not have had winUninstallColormap called on it.  Thus,
-   * we need to handle the default colormap in a special way.
-   */
-  if (pColormap->flags & IsDefault)
-    {
-#if CYGDEBUG
-      winDebug ("winDestroyColormapShadowDD - Destroying default "
-	      "colormap\n");
-#endif
-      
-      /*
-       * FIXME: Walk the list of all screens, popping the default
-       * palette out of each screen device context.
-       */
-      
-      /* Pop the palette out of the primary surface */
-      ddrval = IDirectDrawSurface2_SetPalette (pScreenPriv->pddsPrimary,
-					       NULL);
-      if (FAILED (ddrval))
-	{
-	  ErrorF ("winDestroyColormapShadowDD - Failed freeing the "
-		  "default colormap DirectDraw palette.\n");
-	  return FALSE;
-	}
-
-      /* Clear our private installed colormap pointer */
-      pScreenPriv->pcmapInstalled = NULL;
-    }
-  
-  /* Release the palette */
-  IDirectDrawPalette_Release (pCmapPriv->lpDDPalette);
- 
-  /* Invalidate the colormap privates */
-  pCmapPriv->lpDDPalette = NULL;
-
-  return TRUE;
-}
-
-
-/*
- * Set engine specific functions
- */
-
-Bool
-winSetEngineFunctionsShadowDD (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  
-  /* Set our pointers */
-  pScreenPriv->pwinAllocateFB = winAllocateFBShadowDD;
-  pScreenPriv->pwinShadowUpdate = winShadowUpdateDD;
-  pScreenPriv->pwinCloseScreen = winCloseScreenShadowDD;
-  pScreenPriv->pwinInitVisuals = winInitVisualsShadowDD;
-  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModeShadowDD;
-  if (pScreenInfo->fFullScreen)
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
-  else
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
-  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitFB;
-  pScreenPriv->pwinBltExposedRegions = winBltExposedRegionsShadowDD;
-  pScreenPriv->pwinActivateApp = winActivateAppShadowDD;
-  pScreenPriv->pwinRedrawScreen = winRedrawScreenShadowDD;
-  pScreenPriv->pwinRealizeInstalledPalette
-    = winRealizeInstalledPaletteShadowDD;
-  pScreenPriv->pwinInstallColormap = winInstallColormapShadowDD;
-  pScreenPriv->pwinStoreColors = winStoreColorsShadowDD;
-  pScreenPriv->pwinCreateColormap = winCreateColormapShadowDD;
-  pScreenPriv->pwinDestroyColormap = winDestroyColormapShadowDD;
-  pScreenPriv->pwinHotKeyAltTab = (winHotKeyAltTabProcPtr) (void (*)(void))NoopDDA;
-  pScreenPriv->pwinCreatePrimarySurface = winCreatePrimarySurfaceShadowDD;
-  pScreenPriv->pwinReleasePrimarySurface = winReleasePrimarySurfaceShadowDD;
-#ifdef XWIN_MULTIWINDOW
-  pScreenPriv->pwinFinishCreateWindowsWindow =
-    (winFinishCreateWindowsWindowProcPtr) (void (*)(void))NoopDDA;
-#endif
-
-  return TRUE;
-}
diff --git a/hw/xwin/winshadddnl.c b/hw/xwin/winshadddnl.c
deleted file mode 100644
index 47cc382..0000000
--- a/hw/xwin/winshadddnl.c
+++ /dev/null
@@ -1,1454 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * External symbols
- */
-
-extern HWND			g_hDlgExit;
-
-
-/*
- * FIXME: Headers are broken, DEFINE_GUID doesn't work correctly,
- * so we have to redefine it here.
- */
-#ifdef DEFINE_GUID
-#undef DEFINE_GUID
-#define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
-#endif /* DEFINE_GUID */
-
-/*
- * FIXME: Headers are broken, IID_IDirectDraw4 has to be defined
- * here manually.  Should be handled by ddraw.h
- */
-#ifndef IID_IDirectDraw4
-DEFINE_GUID( IID_IDirectDraw4, 0x9c59509a,0x39bd,0x11d1,0x8c,0x4a,0x00,0xc0,0x4f,0xd9,0x30,0xc5 );
-#endif /* IID_IDirectDraw4 */
-
-#define FAIL_MSG_MAX_BLT	10
-
-
-/*
- * Local prototypes
- */
-
-static Bool
-winAllocateFBShadowDDNL (ScreenPtr pScreen);
-
-static void
-winShadowUpdateDDNL (ScreenPtr pScreen, 
-		     shadowBufPtr pBuf);
-
-static Bool
-winCloseScreenShadowDDNL (int nIndex, ScreenPtr pScreen);
-
-static Bool
-winInitVisualsShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winAdjustVideoModeShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winBltExposedRegionsShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winActivateAppShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winRedrawScreenShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winRealizeInstalledPaletteShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winInstallColormapShadowDDNL (ColormapPtr pColormap);
-
-static Bool
-winStoreColorsShadowDDNL (ColormapPtr pmap, 
-			  int ndef,
-			  xColorItem *pdefs);
-
-static Bool
-winCreateColormapShadowDDNL (ColormapPtr pColormap);
-
-static Bool
-winDestroyColormapShadowDDNL (ColormapPtr pColormap);
-
-static Bool
-winCreatePrimarySurfaceShadowDDNL (ScreenPtr pScreen);
-
-static Bool
-winReleasePrimarySurfaceShadowDDNL (ScreenPtr pScreen);
-
-
-/*
- * Create the primary surface and attach the clipper.
- * Used for both the initial surface creation and during
- * WM_DISPLAYCHANGE messages.
- */
-
-static Bool
-winCreatePrimarySurfaceShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  HRESULT		ddrval = DD_OK;
-  DDSURFACEDESC2	ddsd;
-
-  winDebug ("winCreatePrimarySurfaceShadowDDNL - Creating primary surface\n");
-
-  /* Describe the primary surface */
-  ZeroMemory (&ddsd, sizeof (ddsd));
-  ddsd.dwSize = sizeof (ddsd);
-  ddsd.dwFlags = DDSD_CAPS;
-  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
-  
-  /* Create the primary surface */
-  ddrval = IDirectDraw4_CreateSurface (pScreenPriv->pdd4,
-				       &ddsd,
-				       &pScreenPriv->pddsPrimary4,
-				       NULL);
-  pScreenPriv->fRetryCreateSurface = FALSE;
-  if (FAILED (ddrval))
-    {
-      if (ddrval == DDERR_NOEXCLUSIVEMODE)
-        {
-          /* Recreating the surface failed. Mark screen to retry later */ 
-          pScreenPriv->fRetryCreateSurface = TRUE;
-          winDebug ("winCreatePrimarySurfaceShadowDDNL - Could not create "
-	          "primary surface: DDERR_NOEXCLUSIVEMODE\n");
-        }
-      else
-        {
-          ErrorF ("winCreatePrimarySurfaceShadowDDNL - Could not create "
-	          "primary surface: %08x\n", (unsigned int) ddrval);
-        }
-      return FALSE;
-    }
-  
-#if 1
-  winDebug ("winCreatePrimarySurfaceShadowDDNL - Created primary surface\n");
-#endif
-
-  /* Attach our clipper to our primary surface handle */
-  ddrval = IDirectDrawSurface4_SetClipper (pScreenPriv->pddsPrimary4,
-					   pScreenPriv->pddcPrimary);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winCreatePrimarySurfaceShadowDDNL - Primary attach clipper "
-	      "failed: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if 1
-  winDebug ("winCreatePrimarySurfaceShadowDDNL - Attached clipper to primary "
-	  "surface\n");
-#endif
-
-  /* Everything was correct */
-  return TRUE;
-}
-
-
-/*
- * Detach the clipper and release the primary surface.
- * Called from WM_DISPLAYCHANGE.
- */
-
-static Bool
-winReleasePrimarySurfaceShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-
-  winDebug ("winReleasePrimarySurfaceShadowDDNL - Hello\n");
-
-  /* Release the primary surface and clipper, if they exist */
-  if (pScreenPriv->pddsPrimary4)
-    {
-      /*
-       * Detach the clipper from the primary surface.
-       * NOTE: We do this explicity for clarity.  The Clipper is not released.
-       */
-      IDirectDrawSurface4_SetClipper (pScreenPriv->pddsPrimary4,
-				      NULL);
-  
-      winDebug ("winReleasePrimarySurfaceShadowDDNL - Detached clipper\n");
-
-      /* Release the primary surface */
-      IDirectDrawSurface4_Release (pScreenPriv->pddsPrimary4);
-      pScreenPriv->pddsPrimary4 = NULL;
-    }
-
-  winDebug ("winReleasePrimarySurfaceShadowDDNL - Released primary surface\n");
-  
-  return TRUE;
-}
-
-
-/*
- * Create a DirectDraw surface for the shadow framebuffer; also create
- * a primary surface object so we can blit to the display.
- * 
- * Install a DirectDraw clipper on our primary surface object
- * that clips our blits to the unobscured client area of our display window.
- */
-
-Bool
-winAllocateFBShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;  
-  HRESULT		ddrval = DD_OK;
-  DDSURFACEDESC2	ddsdShadow;
-  char			*lpSurface = NULL;
-  DDPIXELFORMAT		ddpfPrimary;
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDDNL - w %d h %d d %d\n",
-	  pScreenInfo->dwWidth, pScreenInfo->dwHeight, pScreenInfo->dwDepth);
-#endif
-
-  /* Allocate memory for our shadow surface */
-  lpSurface = malloc (pScreenInfo->dwPaddedWidth * pScreenInfo->dwHeight);
-  if (lpSurface == NULL)
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Could not allocate bits\n");
-      return FALSE;
-    }
-
-  /*
-   * Initialize the framebuffer memory so we don't get a 
-   * strange display at startup
-   */
-  ZeroMemory (lpSurface, pScreenInfo->dwPaddedWidth * pScreenInfo->dwHeight);
-  
-  /* Create a clipper */
-  ddrval = (*g_fpDirectDrawCreateClipper) (0,
-					   &pScreenPriv->pddcPrimary,
-					   NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Could not attach clipper: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDDNL - Created a clipper\n");
-#endif
-
-  /* Get a device context for the screen  */
-  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
-
-  /* Attach the clipper to our display window */
-  ddrval = IDirectDrawClipper_SetHWnd (pScreenPriv->pddcPrimary,
-				       0,
-				       pScreenPriv->hwndScreen);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Clipper not attached "
-	      "to window: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDDNL - Attached clipper to window\n");
-#endif
-
-  /* Create a DirectDraw object, store the address at lpdd */
-  ddrval = (*g_fpDirectDrawCreate) (NULL,
-				    (LPDIRECTDRAW*) &pScreenPriv->pdd,
-				    NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Could not start "
-	      "DirectDraw: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDDNL - Created and initialized DD\n");
-#endif
-
-  /* Get a DirectDraw4 interface pointer */
-  ddrval = IDirectDraw_QueryInterface (pScreenPriv->pdd,
-				       &IID_IDirectDraw4,
-				       (LPVOID*) &pScreenPriv->pdd4);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Failed DD4 query: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-  /* Are we full screen? */
-  if (pScreenInfo->fFullScreen)
-    {
-      DDSURFACEDESC2	ddsdCurrent;
-      DWORD		dwRefreshRateCurrent = 0;
-      HDC		hdc = NULL;
-
-      /* Set the cooperative level to full screen */
-      ddrval = IDirectDraw4_SetCooperativeLevel (pScreenPriv->pdd4,
-						 pScreenPriv->hwndScreen,
-						 DDSCL_EXCLUSIVE
-						 | DDSCL_FULLSCREEN);
-      if (FAILED (ddrval))
-	{
-	  ErrorF ("winAllocateFBShadowDDNL - Could not set "
-		  "cooperative level: %08x\n",
-		  (unsigned int) ddrval);
-	  return FALSE;
-	}
-
-      /*
-       * We only need to get the current refresh rate for comparison
-       * if a refresh rate has been passed on the command line.
-       */
-      if (pScreenInfo->dwRefreshRate != 0)
-	{
-	  ZeroMemory (&ddsdCurrent, sizeof (ddsdCurrent));
-	  ddsdCurrent.dwSize = sizeof (ddsdCurrent);
-
-	  /* Get information about current display settings */
-	  ddrval = IDirectDraw4_GetDisplayMode (pScreenPriv->pdd4,
-						&ddsdCurrent);
-	  if (FAILED (ddrval))
-	    {
-	      ErrorF ("winAllocateFBShadowDDNL - Could not get current "
-		      "refresh rate: %08x.  Continuing.\n",
-		      (unsigned int) ddrval);
-	      dwRefreshRateCurrent = 0;
-	    }
-	  else
-	    {
-	      /* Grab the current refresh rate */
-	      dwRefreshRateCurrent = ddsdCurrent.u2.dwRefreshRate;
-	    }
-	}
-
-      /* Clean up the refresh rate */
-      if (dwRefreshRateCurrent == pScreenInfo->dwRefreshRate)
-	{
-	  /*
-	   * Refresh rate is non-specified or equal to current.
-	   */
-	  pScreenInfo->dwRefreshRate = 0;
-	}
-
-      /* Grab a device context for the screen */
-      hdc = GetDC (NULL);
-      if (hdc == NULL)
-	{
-	  ErrorF ("winAllocateFBShadowDDNL - GetDC () failed\n");
-	  return FALSE;
-	}
-
-      /* Only change the video mode when different than current mode */
-      if (!pScreenInfo->fMultipleMonitors
-	  && (pScreenInfo->dwWidth != GetSystemMetrics (SM_CXSCREEN)
-	      || pScreenInfo->dwHeight != GetSystemMetrics (SM_CYSCREEN)
-	      || pScreenInfo->dwBPP != GetDeviceCaps (hdc, BITSPIXEL)
-	      || pScreenInfo->dwRefreshRate != 0))
-	{
-	  winDebug ("winAllocateFBShadowDDNL - Changing video mode\n");
-
-	  /* Change the video mode to the mode requested */
-	  ddrval = IDirectDraw4_SetDisplayMode (pScreenPriv->pdd4,
-						pScreenInfo->dwWidth,
-						pScreenInfo->dwHeight,
-						pScreenInfo->dwBPP,
-						pScreenInfo->dwRefreshRate,
-						0);	       
-	  if (FAILED (ddrval))
-	    {
-	      ErrorF ("winAllocateFBShadowDDNL - Could not set "
-		      "full screen display mode: %08x\n",
-		      (unsigned int) ddrval);
-	      return FALSE;
-	    }
-	}
-      else
-	{
-	  winDebug ("winAllocateFBShadowDDNL - Not changing video mode\n");
-	}
-
-      /* Release our DC */
-      ReleaseDC (NULL, hdc);
-      hdc = NULL;
-    }
-  else
-    {
-      /* Set the cooperative level for windowed mode */
-      ddrval = IDirectDraw4_SetCooperativeLevel (pScreenPriv->pdd4,
-						 pScreenPriv->hwndScreen,
-						 DDSCL_NORMAL);
-      if (FAILED (ddrval))
-	{
-	  ErrorF ("winAllocateFBShadowDDNL - Could not set "
-		  "cooperative level: %08x\n",
-		  (unsigned int) ddrval);
-	  return FALSE;
-	}
-    }
-
-  /* Create the primary surface */
-  if (!winCreatePrimarySurfaceShadowDDNL (pScreen))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - winCreatePrimarySurfaceShadowDDNL "
-	      "failed\n");
-      return FALSE;
-    }
-
-  /* Get primary surface's pixel format */
-  ZeroMemory (&ddpfPrimary, sizeof (ddpfPrimary));
-  ddpfPrimary.dwSize = sizeof (ddpfPrimary);
-  ddrval = IDirectDrawSurface4_GetPixelFormat (pScreenPriv->pddsPrimary4,
-					       &ddpfPrimary);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Could not get primary "
-	      "pixformat: %08x\n",
-	      (unsigned int) ddrval);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDDNL - Primary masks: %08x %08x %08x "
-	  "dwRGBBitCount: %d\n",
-	  ddpfPrimary.u2.dwRBitMask,
-	  ddpfPrimary.u3.dwGBitMask,
-	  ddpfPrimary.u4.dwBBitMask,
-	  ddpfPrimary.u1.dwRGBBitCount);
-#endif
-
-  /* Describe the shadow surface to be created */
-  /*
-   * NOTE: Do not use a DDSCAPS_VIDEOMEMORY surface,
-   * as drawing, locking, and unlocking take forever
-   * with video memory surfaces.  In addition,
-   * video memory is a somewhat scarce resource,
-   * so you shouldn't be allocating video memory when
-   * you have the option of using system memory instead.
-   */
-  ZeroMemory (&ddsdShadow, sizeof (ddsdShadow));
-  ddsdShadow.dwSize = sizeof (ddsdShadow);
-  ddsdShadow.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH
-    | DDSD_LPSURFACE | DDSD_PITCH | DDSD_PIXELFORMAT;
-  ddsdShadow.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
-  ddsdShadow.dwHeight = pScreenInfo->dwHeight;
-  ddsdShadow.dwWidth = pScreenInfo->dwWidth;
-  ddsdShadow.u1.lPitch = pScreenInfo->dwPaddedWidth;
-  ddsdShadow.lpSurface = lpSurface;
-  ddsdShadow.u4.ddpfPixelFormat = ddpfPrimary;
-  
-  winDebug ("winAllocateFBShadowDDNL - lPitch: %d\n",
-	  (int) pScreenInfo->dwPaddedWidth);
-
-  /* Create the shadow surface */
-  ddrval = IDirectDraw4_CreateSurface (pScreenPriv->pdd4,
-				       &ddsdShadow,
-				       &pScreenPriv->pddsShadow4,
-				       NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winAllocateFBShadowDDNL - Could not create shadow "
-	      "surface: %08x\n", (unsigned int) ddrval);
-      return FALSE;
-    }
-  
-#if CYGDEBUG || YES
-  winDebug ("winAllocateFBShadowDDNL - Created shadow pitch: %d\n",
-	  (int) ddsdShadow.u1.lPitch);
-#endif
-
-  /* Grab the pitch from the surface desc */
-  pScreenInfo->dwStride = (ddsdShadow.u1.lPitch * 8)
-    / pScreenInfo->dwBPP;
-
-#if CYGDEBUG || YES
-  winDebug ("winAllocateFBShadowDDNL - Created shadow stride: %d\n",
-	  (int) pScreenInfo->dwStride);
-#endif
-
-  /* Save the pointer to our surface memory */
-  pScreenInfo->pfb = lpSurface;
-  
-  /* Grab the masks from the surface description */
-  pScreenPriv->dwRedMask = ddsdShadow.u4.ddpfPixelFormat.u2.dwRBitMask;
-  pScreenPriv->dwGreenMask = ddsdShadow.u4.ddpfPixelFormat.u3.dwGBitMask;
-  pScreenPriv->dwBlueMask = ddsdShadow.u4.ddpfPixelFormat.u4.dwBBitMask;
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowDDNL - Returning\n");
-#endif
-
-  return TRUE;
-}
-
-
-#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
-/*
- * Create a DirectDraw surface for the new multi-window window
- */
-
-static
-Bool
-winFinishCreateWindowsWindowDDNL (WindowPtr pWin)
-{
-  winWindowPriv(pWin);
-  winPrivScreenPtr	pScreenPriv = pWinPriv->pScreenPriv;
-  HRESULT		ddrval = DD_OK;
-  DDSURFACEDESC2	ddsd;
-  int			iWidth, iHeight;
-  int			iX, iY;
-
-  winDebug ("\nwinFinishCreateWindowsWindowDDNL!\n\n");
-
-  iX = pWin->drawable.x + GetSystemMetrics (SM_XVIRTUALSCREEN);
-  iY = pWin->drawable.y + GetSystemMetrics (SM_YVIRTUALSCREEN);
-  
-  iWidth = pWin->drawable.width;
-  iHeight = pWin->drawable.height;
-
-  /* Describe the primary surface */
-  ZeroMemory (&ddsd, sizeof (ddsd));
-  ddsd.dwSize = sizeof (ddsd);
-  ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
-  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
-  ddsd.dwHeight = iHeight;
-  ddsd.dwWidth = iWidth;
-
-  /* Create the primary surface */
-  ddrval = IDirectDraw4_CreateSurface (pScreenPriv->pdd4,
-				       &ddsd,
-				       &pWinPriv->pddsPrimary4,
-				       NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winFinishCreateWindowsWindowDDNL - Could not create primary "
-	      "surface: %08x\n",
-	      (unsigned int)ddrval);
-      return FALSE;
-    }
-  return TRUE;
-}
-#endif
-
-
-/*
- * Transfer the damaged regions of the shadow framebuffer to the display.
- */
-
-static void
-winShadowUpdateDDNL (ScreenPtr pScreen, 
-		     shadowBufPtr pBuf)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  RegionPtr		damage = &pBuf->damage;
-  HRESULT		ddrval = DD_OK;
-  RECT			rcDest, rcSrc;
-  POINT			ptOrigin;
-  DWORD			dwBox = REGION_NUM_RECTS (damage);
-  BoxPtr		pBox = REGION_RECTS (damage);
-  HRGN			hrgnTemp = NULL, hrgnCombined = NULL;
-
-  /*
-   * Return immediately if the app is not active
-   * and we are fullscreen, or if we have a bad display depth
-   */
-  if ((!pScreenPriv->fActive && pScreenInfo->fFullScreen)
-      || pScreenPriv->fBadDepth) return;
-
-  /* Get the origin of the window in the screen coords */
-  ptOrigin.x = pScreenInfo->dwXOffset;
-  ptOrigin.y = pScreenInfo->dwYOffset;
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&ptOrigin, 1);
-
-  /*
-   * Handle small regions with multiple blits,
-   * handle large regions by creating a clipping region and 
-   * doing a single blit constrained to that clipping region.
-   */
-  if (pScreenInfo->dwClipUpdatesNBoxes == 0
-      || dwBox < pScreenInfo->dwClipUpdatesNBoxes)
-    {
-      /* Loop through all boxes in the damaged region */
-      while (dwBox--)
-	{
-	  /* Assign damage box to source rectangle */
-	  rcSrc.left = pBox->x1;
-	  rcSrc.top = pBox->y1;
-	  rcSrc.right = pBox->x2;
-	  rcSrc.bottom = pBox->y2;
-	  
-	  /* Calculate destination rectangle */
-	  rcDest.left = ptOrigin.x + rcSrc.left;
-	  rcDest.top = ptOrigin.y + rcSrc.top;
-	  rcDest.right = ptOrigin.x + rcSrc.right;
-	  rcDest.bottom = ptOrigin.y + rcSrc.bottom;
-	  
-	  /* Blit the damaged areas */
-	  ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
-					    &rcDest,
-					    pScreenPriv->pddsShadow4,
-					    &rcSrc,
-					    DDBLT_WAIT,
-					    NULL);
-	  if (FAILED (ddrval))
-	    {
-	      static int	s_iFailCount = 0;
-	      
-	      if (s_iFailCount < FAIL_MSG_MAX_BLT)
-		{
-		  ErrorF ("winShadowUpdateDDNL - IDirectDrawSurface4_Blt () "
-			  "failed: %08x\n",
-			  (unsigned int) ddrval);
-		  
-		  ++s_iFailCount;
-
-		  if (s_iFailCount == FAIL_MSG_MAX_BLT)
-		    {
-		      ErrorF ("winShadowUpdateDDNL - IDirectDrawSurface4_Blt "
-			      "failure message maximum (%d) reached.  No "
-			      "more failure messages will be printed.\n",
-			      FAIL_MSG_MAX_BLT);
-		    }
-		}
-	    }
-	  
-	  /* Get a pointer to the next box */
-	  ++pBox;
-	}
-    }
-  else
-    {
-      BoxPtr		pBoxExtents = REGION_EXTENTS (pScreen, damage);
-
-      /* Compute a GDI region from the damaged region */
-      hrgnCombined = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
-      dwBox--;
-      pBox++;
-      while (dwBox--)
-	{
-	  hrgnTemp = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
-	  CombineRgn (hrgnCombined, hrgnCombined, hrgnTemp, RGN_OR);
-	  DeleteObject (hrgnTemp);
-	  pBox++;
-	}
-
-      /* Install the GDI region as a clipping region */
-      SelectClipRgn (pScreenPriv->hdcScreen, hrgnCombined);
-      DeleteObject (hrgnCombined);
-      hrgnCombined = NULL;
-
-#if CYGDEBUG
-      winDebug ("winShadowUpdateDDNL - be x1 %d y1 %d x2 %d y2 %d\n",
-	      pBoxExtents->x1, pBoxExtents->y1,
-	      pBoxExtents->x2, pBoxExtents->y2);
-#endif
-
-      /* Calculating a bounding box for the source is easy */
-      rcSrc.left = pBoxExtents->x1;
-      rcSrc.top = pBoxExtents->y1;
-      rcSrc.right = pBoxExtents->x2;
-      rcSrc.bottom = pBoxExtents->y2;
-
-      /* Calculating a bounding box for the destination is trickier */
-      rcDest.left = ptOrigin.x + rcSrc.left;
-      rcDest.top = ptOrigin.y + rcSrc.top;
-      rcDest.right = ptOrigin.x + rcSrc.right;
-      rcDest.bottom = ptOrigin.y + rcSrc.bottom;
-
-      /* Our Blt should be clipped to the invalidated region */
-      ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
-					&rcDest,
-					pScreenPriv->pddsShadow4,
-					&rcSrc,
-					DDBLT_WAIT,
-					NULL);
-
-      /* Reset the clip region */
-      SelectClipRgn (pScreenPriv->hdcScreen, NULL);
-    }
-}
-
-
-/*
- * Call the wrapped CloseScreen function.
- *
- * Free our resources and private structures.
- */
-
-static Bool
-winCloseScreenShadowDDNL (int nIndex, ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  Bool			fReturn;
-
-#if CYGDEBUG
-  winDebug ("winCloseScreenShadowDDNL - Freeing screen resources\n");
-#endif
-
-  /* Flag that the screen is closed */
-  pScreenPriv->fClosed = TRUE;
-  pScreenPriv->fActive = FALSE;
-
-  /* Call the wrapped CloseScreen procedure */
-  WIN_UNWRAP(CloseScreen);
-  fReturn = (*pScreen->CloseScreen) (nIndex, pScreen);
-
-  /* Free the screen DC */
-  ReleaseDC (pScreenPriv->hwndScreen, pScreenPriv->hdcScreen);
-
-  /* Delete the window property */
-  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
-
-  /* Free the shadow surface, if there is one */
-  if (pScreenPriv->pddsShadow4)
-    {
-      IDirectDrawSurface4_Release (pScreenPriv->pddsShadow4);
-      free (pScreenInfo->pfb);
-      pScreenInfo->pfb = NULL;
-      pScreenPriv->pddsShadow4 = NULL;
-    }
-
-  /* Detach the clipper from the primary surface and release the clipper. */
-  if (pScreenPriv->pddcPrimary)
-    {
-      /* Detach the clipper */
-      IDirectDrawSurface4_SetClipper (pScreenPriv->pddsPrimary4,
-				      NULL);
-
-      /* Release the clipper object */
-      IDirectDrawClipper_Release (pScreenPriv->pddcPrimary);
-      pScreenPriv->pddcPrimary = NULL;
-    }
-
-  /* Release the primary surface, if there is one */
-  if (pScreenPriv->pddsPrimary4)
-    {
-      IDirectDrawSurface4_Release (pScreenPriv->pddsPrimary4);
-      pScreenPriv->pddsPrimary4 = NULL;
-    }
-
-  /* Free the DirectDraw4 object, if there is one */
-  if (pScreenPriv->pdd4)
-    {
-      IDirectDraw4_RestoreDisplayMode (pScreenPriv->pdd4);
-      IDirectDraw4_Release (pScreenPriv->pdd4);
-      pScreenPriv->pdd4 = NULL;
-    }
-
-  /* Free the DirectDraw object, if there is one */
-  if (pScreenPriv->pdd)
-    {
-      IDirectDraw_Release (pScreenPriv->pdd);
-      pScreenPriv->pdd = NULL;
-    }
-
-  /* Delete tray icon, if we have one */
-  if (!pScreenInfo->fNoTrayIcon)
-    winDeleteNotifyIcon (pScreenPriv);
-
-  /* Free the exit confirmation dialog box, if it exists */
-  if (g_hDlgExit != NULL)
-    {
-      DestroyWindow (g_hDlgExit);
-      g_hDlgExit = NULL;
-    }
-
-  /* Kill our window */
-  if (pScreenPriv->hwndScreen)
-    {
-      DestroyWindow (pScreenPriv->hwndScreen);
-      pScreenPriv->hwndScreen = NULL;
-    }
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  /* Destroy the thread startup mutex */
-  pthread_mutex_destroy (&pScreenPriv->pmServerStarted);
-#endif
-
-  /* Kill our screeninfo's pointer to the screen */
-  pScreenInfo->pScreen = NULL;
-
-  /* Invalidate the ScreenInfo's fb pointer */
-  pScreenInfo->pfb = NULL;
-
-  /* Free the screen privates for this screen */
-  free ((pointer) pScreenPriv);
-
-  return fReturn;
-}
-
-
-/*
- * Tell mi what sort of visuals we need.
- *
- * Generally we only need one visual, as our screen can only
- * handle one format at a time, I believe.  You may want
- * to verify that last sentence.
- */
-
-static Bool
-winInitVisualsShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  DWORD			dwRedBits, dwGreenBits, dwBlueBits;
-
-  /* Count the number of ones in each color mask */
-  dwRedBits = winCountBits (pScreenPriv->dwRedMask);
-  dwGreenBits = winCountBits (pScreenPriv->dwGreenMask);
-  dwBlueBits = winCountBits (pScreenPriv->dwBlueMask);
-  
-  /* Store the maximum number of ones in a color mask as the bitsPerRGB */
-  if (dwRedBits == 0 || dwGreenBits == 0 || dwBlueBits == 0)
-    pScreenPriv->dwBitsPerRGB = 8;
-  else if (dwRedBits > dwGreenBits && dwRedBits > dwBlueBits)
-    pScreenPriv->dwBitsPerRGB = dwRedBits;
-  else if (dwGreenBits > dwRedBits && dwGreenBits > dwBlueBits)
-    pScreenPriv->dwBitsPerRGB = dwGreenBits;
-  else
-    pScreenPriv->dwBitsPerRGB = dwBlueBits;
-
-  winDebug ("winInitVisualsShadowDDNL - Masks %08x %08x %08x BPRGB %d d %d "
-	  "bpp %d\n",
-	  (unsigned int) pScreenPriv->dwRedMask,
-	  (unsigned int) pScreenPriv->dwGreenMask,
-	  (unsigned int) pScreenPriv->dwBlueMask,
-	  (int) pScreenPriv->dwBitsPerRGB,
-	  (int) pScreenInfo->dwDepth,
-	  (int) pScreenInfo->dwBPP);
-
-  /* Create a single visual according to the Windows screen depth */
-  switch (pScreenInfo->dwDepth)
-    {
-    case 24:
-    case 16:
-    case 15:
-#if defined(XFree86Server)
-      /* Setup the real visual */
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     TrueColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     -1,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDDNL - miSetVisualTypesAndMasks "
-		  "failed for TrueColor\n");
-	  return FALSE;
-	}
-
-#ifdef XWIN_EMULATEPSEUDO
-      if (!pScreenInfo->fEmulatePseudo)
-	break;
-
-      /* Setup a pseudocolor visual */
-      if (!miSetVisualTypesAndMasks (8,
-				     PseudoColorMask,
-				     8,
-				     -1,
-				     0,
-				     0,
-				     0))
-	{
-	  ErrorF ("winInitVisualsShadowDDNL - miSetVisualTypesAndMasks "
-		  "failed for PseudoColor\n");
-	  return FALSE;
-	}
-#endif
-#else /* XFree86Server */
-      /* Setup the real visual */
-      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     TrueColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDDNL - fbSetVisualTypesAndMasks "
-		  "failed for TrueColor\n");
-	  return FALSE;
-	}
-
-#ifdef XWIN_EMULATEPSEUDO
-      if (!pScreenInfo->fEmulatePseudo)
-	break;
-
-      /* Setup a pseudocolor visual */
-      if (!fbSetVisualTypesAndMasks (8,
-				     PseudoColorMask,
-				     8,
-				     0,
-				     0,
-				     0))
-	{
-	  ErrorF ("winInitVisualsShadowDDNL - fbSetVisualTypesAndMasks "
-		  "failed for PseudoColor\n");
-	  return FALSE;
-	}
-#endif
-#endif /* XFree86Server */
-      break;
-
-    case 8:
-#if defined(XFree86Server)
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     pScreenInfo->fFullScreen 
-				     ? PseudoColorMask : StaticColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenInfo->fFullScreen 
-				     ? PseudoColor : StaticColor,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDDNL - miSetVisualTypesAndMasks "
-		  "failed\n");
-	  return FALSE;
-	}
-#else /* XFree86Server */
-        if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     pScreenInfo->fFullScreen 
-				     ? PseudoColorMask : StaticColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowDDNL - fbSetVisualTypesAndMasks "
-		  "failed\n");
-	  return FALSE;
-	}    
-#endif /* XFree86Server */
-      break;
-
-    default:
-      ErrorF ("winInitVisualsShadowDDNL - Unknown screen depth\n");
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winInitVisualsShadowDDNL - Returning\n");
-#endif
-
-  return TRUE;
-}
-
-
-/*
- * Adjust the user proposed video mode
- */
-
-static Bool
-winAdjustVideoModeShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  HDC			hdc = NULL;
-  DWORD			dwBPP;
-
-  /* We're in serious trouble if we can't get a DC */
-  hdc = GetDC (NULL);
-  if (hdc == NULL)
-    {
-      ErrorF ("winAdjustVideoModeShadowDDNL - GetDC () failed\n");
-      return FALSE;
-    }
-
-  /* Query GDI for current display depth */
-  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
-
-  /* DirectDraw can only change the depth in fullscreen mode */
-  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
-    {
-      /* No -depth parameter passed, let the user know the depth being used */
-      winErrorFVerb (2, "winAdjustVideoModeShadowDDNL - Using Windows display "
-	      "depth of %d bits per pixel\n", (int) dwBPP);
-
-      /* Use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-  else if (pScreenInfo->fFullScreen
-	   && pScreenInfo->dwBPP != dwBPP)
-    {
-      /* FullScreen, and GDI depth differs from -depth parameter */
-      winErrorFVerb (2, "winAdjustVideoModeShadowDDNL - FullScreen, using command "
-	      "line bpp: %d\n", (int) pScreenInfo->dwBPP);
-    }
-  else if (dwBPP != pScreenInfo->dwBPP)
-    {
-      /* Windowed, and GDI depth differs from -depth parameter */
-      winErrorFVerb (2, "winAdjustVideoModeShadowDDNL - Windowed, command line "
-	      "bpp: %d, using bpp: %d\n",
-	      (int) pScreenInfo->dwBPP, (int) dwBPP);
-
-      /* We'll use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-
-  /* See if the shadow bitmap will be larger than the DIB size limit */
-  if (pScreenInfo->dwWidth * pScreenInfo->dwHeight * pScreenInfo->dwBPP
-      >= WIN_DIB_MAXIMUM_SIZE)
-    {
-      winErrorFVerb (1, "winAdjustVideoModeShadowDDNL - Requested DirectDraw surface "
-	      "will be larger than %d MB.  The surface may fail to be "
-	      "allocated on Windows 95, 98, or Me, due to a %d MB limit in "
-	      "DIB size.  This limit does not apply to Windows NT/2000, and "
-	      "this message may be ignored on those platforms.\n",
-	      WIN_DIB_MAXIMUM_SIZE_MB, WIN_DIB_MAXIMUM_SIZE_MB);
-    }
-  
-  /* Release our DC */
-  ReleaseDC (NULL, hdc);
-
-  return TRUE;
-}
-
-
-/*
- * Blt exposed regions to the screen
- */
-
-static Bool
-winBltExposedRegionsShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  RECT			rcSrc, rcDest;
-  POINT			ptOrigin;
-  HDC			hdcUpdate;
-  PAINTSTRUCT		ps;
-  HRESULT		ddrval = DD_OK;
-  Bool			fReturn = TRUE;
-  int			i;
-
-  /* Quite common case. The primary surface was lost (maybe because of depth
-   * change). Try to create a new primary surface. Bail out if this fails */
-  if (pScreenPriv->pddsPrimary4 == NULL && pScreenPriv->fRetryCreateSurface &&
-      !winCreatePrimarySurfaceShadowDDNL(pScreen))
-    {
-      Sleep(100);
-      return FALSE;
-    }
-  if (pScreenPriv->pddsPrimary4 == NULL)
-    return FALSE;  
-  
-  /* BeginPaint gives us an hdc that clips to the invalidated region */
-  hdcUpdate = BeginPaint (pScreenPriv->hwndScreen, &ps);
-  if (hdcUpdate == NULL)
-    {
-      fReturn = FALSE;
-      ErrorF ("winBltExposedRegionsShadowDDNL - BeginPaint () returned "
-	      "a NULL device context handle.  Aborting blit attempt.\n");
-      goto winBltExposedRegionsShadowDDNL_Exit;
-    }
-
-  /* Get the origin of the window in the screen coords */
-  ptOrigin.x = pScreenInfo->dwXOffset;
-  ptOrigin.y = pScreenInfo->dwYOffset;
-
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&ptOrigin, 1);
-  rcDest.left = ptOrigin.x;
-  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
-  rcDest.top = ptOrigin.y;
-  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
-
-  /* Source can be entire shadow surface, as Blt should clip for us */
-  rcSrc.left = 0;
-  rcSrc.top = 0;
-  rcSrc.right = pScreenInfo->dwWidth;
-  rcSrc.bottom = pScreenInfo->dwHeight;
-
-  /* Try to regain the primary surface and blit again if we've lost it */
-  for (i = 0; i <= WIN_REGAIN_SURFACE_RETRIES; ++i)
-    {
-      /* Our Blt should be clipped to the invalidated region */
-      ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
-					&rcDest,
-					pScreenPriv->pddsShadow4,
-					&rcSrc,
-					DDBLT_WAIT,
-					NULL);
-      if (ddrval == DDERR_SURFACELOST)
-	{
-	  /* Surface was lost */
-	  winErrorFVerb (1, "winBltExposedRegionsShadowDDNL - "
-          "IDirectDrawSurface4_Blt reported that the primary "
-          "surface was lost, trying to restore, retry: %d\n", i + 1);
-
-	  /* Try to restore the surface, once */
-	  
-	  ddrval = IDirectDrawSurface4_Restore (pScreenPriv->pddsPrimary4);
-	  winDebug ("winBltExposedRegionsShadowDDNL - "
-		  "IDirectDrawSurface4_Restore returned: ");
-	  if (ddrval == DD_OK)
-	    winDebug ("DD_OK\n");
-	  else if (ddrval == DDERR_WRONGMODE)
-	    winDebug ("DDERR_WRONGMODE\n");
-	  else if (ddrval == DDERR_INCOMPATIBLEPRIMARY)
-	    winDebug ("DDERR_INCOMPATIBLEPRIMARY\n");
-	  else if (ddrval == DDERR_UNSUPPORTED)
-	    winDebug ("DDERR_UNSUPPORTED\n");
-	  else if (ddrval == DDERR_INVALIDPARAMS)
-	    winDebug ("DDERR_INVALIDPARAMS\n");
-	  else if (ddrval == DDERR_INVALIDOBJECT)
-	    winDebug ("DDERR_INVALIDOBJECT\n");
-	  else
-	    winDebug ("unknown error: %08x\n", (unsigned int) ddrval);
-	  
-	  /* Loop around to try the blit one more time */
-	  continue;
-	}  
-      else if (FAILED (ddrval))
-	{
-	  fReturn = FALSE;
-	  winErrorFVerb (1, "winBltExposedRegionsShadowDDNL - "
-		  "IDirectDrawSurface4_Blt failed, but surface not "
-		  "lost: %08x %d\n",
-		  (unsigned int) ddrval, (int) ddrval);
-	  goto winBltExposedRegionsShadowDDNL_Exit;
-	}
-      else
-	{
-	  /* Success, stop looping */
-	  break;
-	}
-    }
-
- winBltExposedRegionsShadowDDNL_Exit:
-  /* EndPaint frees the DC */
-  if (hdcUpdate != NULL)
-    EndPaint (pScreenPriv->hwndScreen, &ps);
-  return fReturn;
-}
-
-
-/*
- * Do any engine-specific application-activation processing
- */
-
-static Bool
-winActivateAppShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-
-  /*
-   * Do we have a surface?
-   * Are we active?
-   * Are we full screen?
-   */
-  if (pScreenPriv != NULL
-      && pScreenPriv->pddsPrimary4 != NULL
-      && pScreenPriv->fActive)
-    {
-      /* Primary surface was lost, restore it */
-      IDirectDrawSurface4_Restore (pScreenPriv->pddsPrimary4);
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Reblit the shadow framebuffer to the screen.
- */
-
-static Bool
-winRedrawScreenShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  HRESULT		ddrval = DD_OK;
-  RECT			rcSrc, rcDest;
-  POINT			ptOrigin;
-
-  /* Get the origin of the window in the screen coords */
-  ptOrigin.x = pScreenInfo->dwXOffset;
-  ptOrigin.y = pScreenInfo->dwYOffset;
-  MapWindowPoints (pScreenPriv->hwndScreen,
-		   HWND_DESKTOP,
-		   (LPPOINT)&ptOrigin, 1);
-  rcDest.left = ptOrigin.x;
-  rcDest.right = ptOrigin.x + pScreenInfo->dwWidth;
-  rcDest.top = ptOrigin.y;
-  rcDest.bottom = ptOrigin.y + pScreenInfo->dwHeight;
-
-  /* Source can be entire shadow surface, as Blt should clip for us */
-  rcSrc.left = 0;
-  rcSrc.top = 0;
-  rcSrc.right = pScreenInfo->dwWidth;
-  rcSrc.bottom = pScreenInfo->dwHeight;
-
-  /* Redraw the whole window, to take account for the new colors */
-  ddrval = IDirectDrawSurface4_Blt (pScreenPriv->pddsPrimary4,
-				    &rcDest,
-				    pScreenPriv->pddsShadow4,
-				    &rcSrc,
-				    DDBLT_WAIT,
-				    NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winRedrawScreenShadowDDNL - IDirectDrawSurface4_Blt () "
-	      "failed: %08x\n",
-	      (unsigned int) ddrval);
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Realize the currently installed colormap
- */
-
-static Bool
-winRealizeInstalledPaletteShadowDDNL (ScreenPtr pScreen)
-{
-  return TRUE;
-}
-
-
-/*
- * Install the specified colormap
- */
-
-static Bool
-winInstallColormapShadowDDNL (ColormapPtr pColormap)
-{
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  HRESULT		ddrval = DD_OK;
-
-  /* Install the DirectDraw palette on the primary surface */
-  ddrval = IDirectDrawSurface4_SetPalette (pScreenPriv->pddsPrimary4,
-					   pCmapPriv->lpDDPalette);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winInstallColormapShadowDDNL - Failed installing the "
-	      "DirectDraw palette.\n");
-      return FALSE;
-    }
-
-  /* Save a pointer to the newly installed colormap */
-  pScreenPriv->pcmapInstalled = pColormap;
-
-  return TRUE;
-}
-
-
-/*
- * Store the specified colors in the specified colormap
- */
-
-static Bool
-winStoreColorsShadowDDNL (ColormapPtr pColormap, 
-			  int ndef,
-			  xColorItem *pdefs)
-{
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  ColormapPtr		curpmap = pScreenPriv->pcmapInstalled;
-  HRESULT		ddrval = DD_OK;
-  
-  /* Put the X colormap entries into the Windows logical palette */
-  ddrval = IDirectDrawPalette_SetEntries (pCmapPriv->lpDDPalette,
-					  0,
-					  pdefs[0].pixel,
-					  ndef,
-					  pCmapPriv->peColors 
-					  + pdefs[0].pixel);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winStoreColorsShadowDDNL - SetEntries () failed: %08x\n", ddrval);
-      return FALSE;
-    }
-
-  /* Don't install the DirectDraw palette if the colormap is not installed */
-  if (pColormap != curpmap)
-    {
-      return TRUE;
-    }
-
-  if (!winInstallColormapShadowDDNL (pColormap))
-    {
-      ErrorF ("winStoreColorsShadowDDNL - Failed installing colormap\n");
-      return FALSE;
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Colormap initialization procedure
- */
-
-static Bool
-winCreateColormapShadowDDNL (ColormapPtr pColormap)
-{
-  HRESULT		ddrval = DD_OK;
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  
-  /* Create a DirectDraw palette */
-  ddrval = IDirectDraw4_CreatePalette (pScreenPriv->pdd4,
-				       DDPCAPS_8BIT | DDPCAPS_ALLOW256,
-				       pCmapPriv->peColors,
-				       &pCmapPriv->lpDDPalette,
-				       NULL);
-  if (FAILED (ddrval))
-    {
-      ErrorF ("winCreateColormapShadowDDNL - CreatePalette failed\n");
-      return FALSE;
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Colormap destruction procedure
- */
-
-static Bool
-winDestroyColormapShadowDDNL (ColormapPtr pColormap)
-{
-  winScreenPriv(pColormap->pScreen);
-  winCmapPriv(pColormap);
-  HRESULT		ddrval = DD_OK;
-
-  /*
-   * Is colormap to be destroyed the default?
-   *
-   * Non-default colormaps should have had winUninstallColormap
-   * called on them before we get here.  The default colormap
-   * will not have had winUninstallColormap called on it.  Thus,
-   * we need to handle the default colormap in a special way.
-   */
-  if (pColormap->flags & IsDefault)
-    {
-#if CYGDEBUG
-      winDebug ("winDestroyColormapShadowDDNL - Destroying default colormap\n");
-#endif
-      
-      /*
-       * FIXME: Walk the list of all screens, popping the default
-       * palette out of each screen device context.
-       */
-      
-      /* Pop the palette out of the primary surface */
-      ddrval = IDirectDrawSurface4_SetPalette (pScreenPriv->pddsPrimary4,
-					       NULL);
-      if (FAILED (ddrval))
-	{
-	  ErrorF ("winDestroyColormapShadowDDNL - Failed freeing the "
-		  "default colormap DirectDraw palette.\n");
-	  return FALSE;
-	}
-
-      /* Clear our private installed colormap pointer */
-      pScreenPriv->pcmapInstalled = NULL;
-    }
-  
-  /* Release the palette */
-  IDirectDrawPalette_Release (pCmapPriv->lpDDPalette);
- 
-  /* Invalidate the colormap privates */
-  pCmapPriv->lpDDPalette = NULL;
-
-  return TRUE;
-}
-
-
-/*
- * Set pointers to our engine specific functions
- */
-
-Bool
-winSetEngineFunctionsShadowDDNL (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  
-  /* Set our pointers */
-  pScreenPriv->pwinAllocateFB = winAllocateFBShadowDDNL;
-  pScreenPriv->pwinShadowUpdate = winShadowUpdateDDNL;
-  pScreenPriv->pwinCloseScreen = winCloseScreenShadowDDNL;
-  pScreenPriv->pwinInitVisuals = winInitVisualsShadowDDNL;
-  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModeShadowDDNL;
-  if (pScreenInfo->fFullScreen)
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
-  else
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
-  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitFB;
-  pScreenPriv->pwinBltExposedRegions = winBltExposedRegionsShadowDDNL;
-  pScreenPriv->pwinActivateApp = winActivateAppShadowDDNL;
-  pScreenPriv->pwinRedrawScreen = winRedrawScreenShadowDDNL;
-  pScreenPriv->pwinRealizeInstalledPalette
-    = winRealizeInstalledPaletteShadowDDNL;
-  pScreenPriv->pwinInstallColormap = winInstallColormapShadowDDNL;
-  pScreenPriv->pwinStoreColors = winStoreColorsShadowDDNL;
-  pScreenPriv->pwinCreateColormap = winCreateColormapShadowDDNL;
-  pScreenPriv->pwinDestroyColormap = winDestroyColormapShadowDDNL;
-  pScreenPriv->pwinHotKeyAltTab = (winHotKeyAltTabProcPtr) (void (*)(void))NoopDDA;
-  pScreenPriv->pwinCreatePrimarySurface = winCreatePrimarySurfaceShadowDDNL;
-  pScreenPriv->pwinReleasePrimarySurface = winReleasePrimarySurfaceShadowDDNL;
-#ifdef XWIN_MULTIWINDOW
-  pScreenPriv->pwinFinishCreateWindowsWindow
-    = winFinishCreateWindowsWindowDDNL;
-#endif
-
-  return TRUE;
-}
diff --git a/hw/xwin/winshadgdi.c b/hw/xwin/winshadgdi.c
deleted file mode 100644
index 04cc2f7..0000000
--- a/hw/xwin/winshadgdi.c
+++ /dev/null
@@ -1,1324 +0,0 @@
-/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * External symbols
- */
-
-#ifdef XWIN_MULTIWINDOW
-extern DWORD			g_dwCurrentThreadID;
-#endif
-extern HWND			g_hDlgExit;
-
-
-/*
- * Local function prototypes
- */
-
-#ifdef XWIN_MULTIWINDOW
-static wBOOL CALLBACK
-winRedrawAllProcShadowGDI (HWND hwnd, LPARAM lParam);
-
-static wBOOL CALLBACK
-winRedrawDamagedWindowShadowGDI (HWND hwnd, LPARAM lParam);
-#endif
-
-static Bool
-winAllocateFBShadowGDI (ScreenPtr pScreen);
-
-static void
-winShadowUpdateGDI (ScreenPtr pScreen, 
-		    shadowBufPtr pBuf);
-
-static Bool
-winCloseScreenShadowGDI (int nIndex, ScreenPtr pScreen);
-
-static Bool
-winInitVisualsShadowGDI (ScreenPtr pScreen);
-
-static Bool
-winAdjustVideoModeShadowGDI (ScreenPtr pScreen);
-
-static Bool
-winBltExposedRegionsShadowGDI (ScreenPtr pScreen);
-
-static Bool
-winActivateAppShadowGDI (ScreenPtr pScreen);
-
-static Bool
-winRedrawScreenShadowGDI (ScreenPtr pScreen);
-
-static Bool
-winRealizeInstalledPaletteShadowGDI (ScreenPtr pScreen);
-
-static Bool
-winInstallColormapShadowGDI (ColormapPtr pColormap);
-
-static Bool
-winStoreColorsShadowGDI (ColormapPtr pmap, 
-			 int ndef,
-			 xColorItem *pdefs);
-
-static Bool
-winCreateColormapShadowGDI (ColormapPtr pColormap);
-
-static Bool
-winDestroyColormapShadowGDI (ColormapPtr pColormap);
-
-
-/*
- * Internal function to get the DIB format that is compatible with the screen
- */
-
-static
-Bool
-winQueryScreenDIBFormat (ScreenPtr pScreen, BITMAPINFOHEADER *pbmih)
-{
-  winScreenPriv(pScreen);
-  HBITMAP		hbmp;
-#if CYGDEBUG
-  LPDWORD		pdw = NULL;
-#endif
-  
-  /* Create a memory bitmap compatible with the screen */
-  hbmp = CreateCompatibleBitmap (pScreenPriv->hdcScreen, 1, 1);
-  if (hbmp == NULL)
-    {
-      ErrorF ("winQueryScreenDIBFormat - CreateCompatibleBitmap failed\n");
-      return FALSE;
-    }
-  
-  /* Initialize our bitmap info header */
-  ZeroMemory (pbmih, sizeof (BITMAPINFOHEADER) + 256 * sizeof (RGBQUAD));
-  pbmih->biSize = sizeof (BITMAPINFOHEADER);
-
-  /* Get the biBitCount */
-  if (!GetDIBits (pScreenPriv->hdcScreen,
-		  hbmp,
-		  0, 1,
-		  NULL,
-		  (BITMAPINFO*) pbmih,
-		  DIB_RGB_COLORS))
-    {
-      ErrorF ("winQueryScreenDIBFormat - First call to GetDIBits failed\n");
-      DeleteObject (hbmp);
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  /* Get a pointer to bitfields */
-  pdw = (DWORD*) ((CARD8*)pbmih + sizeof (BITMAPINFOHEADER));
-
-  winDebug ("winQueryScreenDIBFormat - First call masks: %08x %08x %08x\n",
-	  pdw[0], pdw[1], pdw[2]);
-#endif
-
-  /* Get optimal color table, or the optimal bitfields */
-  if (!GetDIBits (pScreenPriv->hdcScreen,
-		  hbmp,
-		  0, 1,
-		  NULL,
-		  (BITMAPINFO*)pbmih,
-		  DIB_RGB_COLORS))
-    {
-      ErrorF ("winQueryScreenDIBFormat - Second call to GetDIBits "
-	      "failed\n");
-      DeleteObject (hbmp);
-      return FALSE;
-    }
-
-  /* Free memory */
-  DeleteObject (hbmp);
-  
-  return TRUE;
-}
-
-
-/*
- * Internal function to determine the GDI bits per rgb and bit masks
- */
-
-static
-Bool
-winQueryRGBBitsAndMasks (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  BITMAPINFOHEADER	*pbmih = NULL;
-  Bool			fReturn = TRUE;
-  LPDWORD		pdw = NULL;
-  DWORD			dwRedBits, dwGreenBits, dwBlueBits;
-
-  /* Color masks for 8 bpp are standardized */
-  if (GetDeviceCaps (pScreenPriv->hdcScreen, RASTERCAPS) & RC_PALETTE)
-    {
-      /* 
-       * RGB BPP for 8 bit palletes is always 8
-       * and the color masks are always 0.
-       */
-      pScreenPriv->dwBitsPerRGB = 8;
-      pScreenPriv->dwRedMask = 0x0L;
-      pScreenPriv->dwGreenMask = 0x0L;
-      pScreenPriv->dwBlueMask = 0x0L;
-      return TRUE;
-    }
-
-  /* Color masks for 24 bpp are standardized */
-  if (GetDeviceCaps (pScreenPriv->hdcScreen, PLANES)
-      * GetDeviceCaps (pScreenPriv->hdcScreen, BITSPIXEL) == 24)
-    {
-      ErrorF ("winQueryRGBBitsAndMasks - GetDeviceCaps (BITSPIXEL) "
-	      "returned 24 for the screen.  Using default 24bpp masks.\n");
-
-      /* 8 bits per primary color */
-      pScreenPriv->dwBitsPerRGB = 8;
-
-      /* Set screen privates masks */
-      pScreenPriv->dwRedMask = WIN_24BPP_MASK_RED;
-      pScreenPriv->dwGreenMask = WIN_24BPP_MASK_GREEN;
-      pScreenPriv->dwBlueMask = WIN_24BPP_MASK_BLUE;
-      
-      return TRUE;
-    }
-
-  /* Allocate a bitmap header and color table */
-  pbmih = (BITMAPINFOHEADER*) malloc (sizeof (BITMAPINFOHEADER)
-				      + 256  * sizeof (RGBQUAD));
-  if (pbmih == NULL)
-    {
-      ErrorF ("winQueryRGBBitsAndMasks - malloc failed\n");
-      return FALSE;
-    }
-
-  /* Get screen description */
-  if (winQueryScreenDIBFormat (pScreen, pbmih))
-    {
-      /* Get a pointer to bitfields */
-      pdw = (DWORD*) ((CARD8*)pbmih + sizeof (BITMAPINFOHEADER));
-      
-#if CYGDEBUG
-      winDebug ("%s - Masks: %08x %08x %08x\n", __FUNCTION__,
-	      pdw[0], pdw[1], pdw[2]);
-      winDebug ("%s - Bitmap: %dx%d %d bpp %d planes\n", __FUNCTION__,
-              pbmih->biWidth, pbmih->biHeight, pbmih->biBitCount, pbmih->biPlanes);
-      winDebug ("%s - Compression: %d %s\n", __FUNCTION__,
-              pbmih->biCompression,
-              (pbmih->biCompression == BI_RGB?"(BI_RGB)":
-               (pbmih->biCompression == BI_RLE8?"(BI_RLE8)":
-                (pbmih->biCompression == BI_RLE4?"(BI_RLE4)":
-                 (pbmih->biCompression == BI_BITFIELDS?"(BI_BITFIELDS)":""
-                 )))));
-#endif
-
-      /* Handle BI_RGB case, which is returned by Wine */
-      if (pbmih->biCompression == BI_RGB)
-        {
-	  dwRedBits = 5;
-	  dwGreenBits = 5;
-	  dwBlueBits = 5;
-	  
-	  pScreenPriv->dwBitsPerRGB = 5;
-	  
-	  /* Set screen privates masks */
-	  pScreenPriv->dwRedMask = 0x7c00;
-	  pScreenPriv->dwGreenMask = 0x03e0;
-	  pScreenPriv->dwBlueMask = 0x001f;
-        }
-      else 
-        {
-          /* Count the number of bits in each mask */
-          dwRedBits = winCountBits (pdw[0]);
-          dwGreenBits = winCountBits (pdw[1]);
-          dwBlueBits = winCountBits (pdw[2]);
-
-	  /* Find maximum bits per red, green, blue */
-	  if (dwRedBits > dwGreenBits && dwRedBits > dwBlueBits)
-	    pScreenPriv->dwBitsPerRGB = dwRedBits;
-	  else if (dwGreenBits > dwRedBits && dwGreenBits > dwBlueBits)
-	    pScreenPriv->dwBitsPerRGB = dwGreenBits;
-	  else
-	    pScreenPriv->dwBitsPerRGB = dwBlueBits;
-
-	  /* Set screen privates masks */
-	  pScreenPriv->dwRedMask = pdw[0];
-	  pScreenPriv->dwGreenMask = pdw[1];
-	  pScreenPriv->dwBlueMask = pdw[2];
-	}
-    }
-  else
-    {
-      ErrorF ("winQueryRGBBitsAndMasks - winQueryScreenDIBFormat failed\n");
-      free (pbmih);
-      fReturn = FALSE;
-    }
-
-  /* Free memory */
-  free (pbmih);
-
-  return fReturn;
-}
-
-
-#ifdef XWIN_MULTIWINDOW
-/*
- * Redraw all ---?
- */
-
-static wBOOL CALLBACK
-winRedrawAllProcShadowGDI (HWND hwnd, LPARAM lParam)
-{
-  if (hwnd == (HWND)lParam)
-    return TRUE;  
-  InvalidateRect (hwnd, NULL, FALSE);
-  UpdateWindow (hwnd);
-  return TRUE;
-}
-
-static wBOOL CALLBACK
-winRedrawDamagedWindowShadowGDI (HWND hwnd, LPARAM lParam)
-{
-  BoxPtr pDamage = (BoxPtr)lParam;
-  RECT rcClient, rcDamage, rcRedraw;
-  POINT topLeft, bottomRight;
-  
-  if (IsIconic (hwnd))
-    return TRUE; /* Don't care minimized windows */
-  
-  /* Convert the damaged area from Screen coords to Client coords */
-  topLeft.x = pDamage->x1; topLeft.y = pDamage->y1;
-  bottomRight.x = pDamage->x2; bottomRight.y = pDamage->y2;
-  topLeft.x += GetSystemMetrics (SM_XVIRTUALSCREEN);
-  bottomRight.x += GetSystemMetrics (SM_XVIRTUALSCREEN);
-  topLeft.y += GetSystemMetrics (SM_YVIRTUALSCREEN);
-  bottomRight.y += GetSystemMetrics (SM_YVIRTUALSCREEN);
-  ScreenToClient (hwnd, &topLeft);
-  ScreenToClient (hwnd, &bottomRight);
-  SetRect (&rcDamage, topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
-
-  GetClientRect (hwnd, &rcClient);
-
-  if (IntersectRect (&rcRedraw, &rcClient, &rcDamage))
-    {
-      InvalidateRect (hwnd, &rcRedraw, FALSE);
-      UpdateWindow (hwnd);
-    }
-  return TRUE;
-}
-#endif
-
-
-/*
- * Allocate a DIB for the shadow framebuffer GDI server
- */
-
-static Bool
-winAllocateFBShadowGDI (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  BITMAPINFOHEADER	*pbmih = NULL;
-  DIBSECTION		dibsection;
-  Bool			fReturn = TRUE;
-
-  /* Get device contexts for the screen and shadow bitmap */
-  pScreenPriv->hdcScreen = GetDC (pScreenPriv->hwndScreen);
-  pScreenPriv->hdcShadow = CreateCompatibleDC (pScreenPriv->hdcScreen);
-
-  /* Allocate bitmap info header */
-  pbmih = (BITMAPINFOHEADER*) malloc (sizeof (BITMAPINFOHEADER)
-				      + 256 * sizeof (RGBQUAD));
-  if (pbmih == NULL)
-    {
-      ErrorF ("winAllocateFBShadowGDI - malloc () failed\n");
-      return FALSE;
-    }
-
-  /* Query the screen format */
-  fReturn = winQueryScreenDIBFormat (pScreen, pbmih);
-
-  /* Describe shadow bitmap to be created */
-  pbmih->biWidth = pScreenInfo->dwWidth;
-  pbmih->biHeight = -pScreenInfo->dwHeight;
-  
-  ErrorF ("winAllocateFBShadowGDI - Creating DIB with width: %d height: %d "
-	  "depth: %d\n",
-	  (int) pbmih->biWidth, (int) -pbmih->biHeight, pbmih->biBitCount);
-
-  /* Create a DI shadow bitmap with a bit pointer */
-  pScreenPriv->hbmpShadow = CreateDIBSection (pScreenPriv->hdcScreen,
-					      (BITMAPINFO *) pbmih,
-					      DIB_RGB_COLORS,
-					      (VOID**) &pScreenInfo->pfb,
-					      NULL,
-					      0);
-  if (pScreenPriv->hbmpShadow == NULL || pScreenInfo->pfb == NULL)
-    {
-      winW32Error (2, "winAllocateFBShadowGDI - CreateDIBSection failed:");
-      return FALSE;
-    }
-  else
-    {
-#if CYGDEBUG
-      winDebug ("winAllocateFBShadowGDI - Shadow buffer allocated\n");
-#endif
-    }
-
-  /* Get information about the bitmap that was allocated */
-  GetObject (pScreenPriv->hbmpShadow,
-	     sizeof (dibsection),
-	     &dibsection);
-
-#if CYGDEBUG || YES
-  /* Print information about bitmap allocated */
-  winDebug ("winAllocateFBShadowGDI - Dibsection width: %d height: %d "
-	  "depth: %d size image: %d\n",
-	  (int) dibsection.dsBmih.biWidth, (int) dibsection.dsBmih.biHeight,
-	  dibsection.dsBmih.biBitCount,
-	  (int) dibsection.dsBmih.biSizeImage);
-#endif
-
-  /* Select the shadow bitmap into the shadow DC */
-  SelectObject (pScreenPriv->hdcShadow,
-		pScreenPriv->hbmpShadow);
-
-#if CYGDEBUG
-  winDebug ("winAllocateFBShadowGDI - Attempting a shadow blit\n");
-#endif
-
-  /* Do a test blit from the shadow to the screen, I think */
-  fReturn = BitBlt (pScreenPriv->hdcScreen,
-		    0, 0,
-		    pScreenInfo->dwWidth, pScreenInfo->dwHeight,
-		    pScreenPriv->hdcShadow,
-		    0, 0,
-		    SRCCOPY);
-  if (fReturn)
-    {
-#if CYGDEBUG
-      winDebug ("winAllocateFBShadowGDI - Shadow blit success\n");
-#endif
-    }
-  else
-    {
-      winW32Error (2, "winAllocateFBShadowGDI - Shadow blit failure\n");
-#if 0      
-      return FALSE;
-#else 
-      /* ago: ignore this error. The blit fails with wine, but does not 
-       * cause any problems later. */
-
-      fReturn = TRUE;
-#endif      
-    }
-
-  /* Look for height weirdness */
-  if (dibsection.dsBmih.biHeight < 0)
-    {
-      dibsection.dsBmih.biHeight = -dibsection.dsBmih.biHeight;
-    }
-
-  /* Set screeninfo stride */
-  pScreenInfo->dwStride = ((dibsection.dsBmih.biSizeImage
-			    / dibsection.dsBmih.biHeight)
-			   * 8) / pScreenInfo->dwBPP;
-
-#if CYGDEBUG || YES
-  winDebug ("winAllocateFBShadowGDI - Created shadow stride: %d\n",
-	  (int) pScreenInfo->dwStride);
-#endif
-
-  /* See if the shadow bitmap will be larger than the DIB size limit */
-  if (pScreenInfo->dwWidth * pScreenInfo->dwHeight * pScreenInfo->dwBPP
-      >= WIN_DIB_MAXIMUM_SIZE)
-    {
-      ErrorF ("winAllocateFBShadowGDI - Requested DIB (bitmap) "
-	      "will be larger than %d MB.  The surface may fail to be "
-	      "allocated on Windows 95, 98, or Me, due to a %d MB limit in "
-	      "DIB size.  This limit does not apply to Windows NT/2000, and "
-	      "this message may be ignored on those platforms.\n",
-	      WIN_DIB_MAXIMUM_SIZE_MB, WIN_DIB_MAXIMUM_SIZE_MB);
-    }
-
-  /* Determine our color masks */
-  if (!winQueryRGBBitsAndMasks (pScreen))
-    {
-      ErrorF ("winAllocateFBShadowGDI - winQueryRGBBitsAndMasks failed\n");
-      return FALSE;
-    }
-
-#ifdef XWIN_MULTIWINDOW
-  /* Redraw all windows */
-  if (pScreenInfo->fMultiWindow)
-    EnumThreadWindows (g_dwCurrentThreadID, winRedrawAllProcShadowGDI, 0);
-#endif
-
-  return fReturn;
-}
-
-
-/*
- * Blit the damaged regions of the shadow fb to the screen
- */
-
-static void
-winShadowUpdateGDI (ScreenPtr pScreen, 
-		    shadowBufPtr pBuf)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  RegionPtr		damage = &pBuf->damage;
-  DWORD			dwBox = REGION_NUM_RECTS (damage);
-  BoxPtr		pBox = REGION_RECTS (damage);
-  int			x, y, w, h;
-  HRGN			hrgnTemp = NULL, hrgnCombined = NULL;
-#ifdef XWIN_UPDATESTATS
-  static DWORD		s_dwNonUnitRegions = 0;
-  static DWORD		s_dwTotalUpdates = 0;
-  static DWORD		s_dwTotalBoxes = 0;
-#endif
-  BoxPtr		pBoxExtents = REGION_EXTENTS (pScreen, damage);
-
-  /*
-   * Return immediately if the app is not active
-   * and we are fullscreen, or if we have a bad display depth
-   */
-  if ((!pScreenPriv->fActive && pScreenInfo->fFullScreen)
-      || pScreenPriv->fBadDepth) return;
-
-#ifdef XWIN_UPDATESTATS
-  ++s_dwTotalUpdates;
-  s_dwTotalBoxes += dwBox;
-
-  if (dwBox != 1)
-    {
-      ++s_dwNonUnitRegions;
-      ErrorF ("winShadowUpdatGDI - dwBox: %d\n", dwBox);
-    }
-  
-  if ((s_dwTotalUpdates % 100) == 0)
-    ErrorF ("winShadowUpdateGDI - %d%% non-unity regions, avg boxes: %d "
-	    "nu: %d tu: %d\n",
-	    (s_dwNonUnitRegions * 100) / s_dwTotalUpdates,
-	    s_dwTotalBoxes / s_dwTotalUpdates,
-	    s_dwNonUnitRegions, s_dwTotalUpdates);
-#endif /* XWIN_UPDATESTATS */
-
-  /*
-   * Handle small regions with multiple blits,
-   * handle large regions by creating a clipping region and 
-   * doing a single blit constrained to that clipping region.
-   */
-  if (!pScreenInfo->fMultiWindow &&
-      (pScreenInfo->dwClipUpdatesNBoxes == 0 ||
-      dwBox < pScreenInfo->dwClipUpdatesNBoxes))
-    {
-      /* Loop through all boxes in the damaged region */
-      while (dwBox--)
-	{
-	  /*
-	   * Calculate x offset, y offset, width, and height for
-	   * current damage box
-	   */
-	  x = pBox->x1;
-	  y = pBox->y1;
-	  w = pBox->x2 - pBox->x1;
-	  h = pBox->y2 - pBox->y1;
-	  
-	  BitBlt (pScreenPriv->hdcScreen,
-		  x, y,
-		  w, h,
-		  pScreenPriv->hdcShadow,
-		  x, y,
-		  SRCCOPY);
-	  
-	  /* Get a pointer to the next box */
-	  ++pBox;
-	}
-    }
-  else if (!pScreenInfo->fMultiWindow)
-    {
-      /* Compute a GDI region from the damaged region */
-      hrgnCombined = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
-      dwBox--;
-      pBox++;
-      while (dwBox--)
-	{
-	  hrgnTemp = CreateRectRgn (pBox->x1, pBox->y1, pBox->x2, pBox->y2);
-	  CombineRgn (hrgnCombined, hrgnCombined, hrgnTemp, RGN_OR);
-	  DeleteObject (hrgnTemp);
-	  pBox++;
-	}
-      
-      /* Install the GDI region as a clipping region */
-      SelectClipRgn (pScreenPriv->hdcScreen, hrgnCombined);
-      DeleteObject (hrgnCombined);
-      hrgnCombined = NULL;
-      
-      /*
-       * Blit the shadow buffer to the screen,
-       * constrained to the clipping region.
-       */
-      BitBlt (pScreenPriv->hdcScreen,
-	      pBoxExtents->x1, pBoxExtents->y1,
-	      pBoxExtents->x2 - pBoxExtents->x1,
-	      pBoxExtents->y2 - pBoxExtents->y1,
-	      pScreenPriv->hdcShadow,
-	      pBoxExtents->x1, pBoxExtents->y1,
-	      SRCCOPY);
-
-      /* Reset the clip region */
-      SelectClipRgn (pScreenPriv->hdcScreen, NULL);
-    }
-
-#ifdef XWIN_MULTIWINDOW
-  /* Redraw all multiwindow windows */
-  if (pScreenInfo->fMultiWindow)
-    EnumThreadWindows (g_dwCurrentThreadID,
-		       winRedrawDamagedWindowShadowGDI,
-		       (LPARAM)pBoxExtents);
-#endif
-}
-
-
-/* See Porting Layer Definition - p. 33 */
-/*
- * We wrap whatever CloseScreen procedure was specified by fb;
- * a pointer to said procedure is stored in our privates.
- */
-
-static Bool
-winCloseScreenShadowGDI (int nIndex, ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  Bool			fReturn;
-
-#if CYGDEBUG
-  winDebug ("winCloseScreenShadowGDI - Freeing screen resources\n");
-#endif
-
-  /* Flag that the screen is closed */
-  pScreenPriv->fClosed = TRUE;
-  pScreenPriv->fActive = FALSE;
-
-  /* Call the wrapped CloseScreen procedure */
-  WIN_UNWRAP(CloseScreen);
-  fReturn = (*pScreen->CloseScreen) (nIndex, pScreen);
-
-  /* Delete the window property */
-  RemoveProp (pScreenPriv->hwndScreen, WIN_SCR_PROP);
-
-  /* Free the shadow DC; which allows the bitmap to be freed */
-  DeleteDC (pScreenPriv->hdcShadow);
-  
-  /* Free the shadow bitmap */
-  DeleteObject (pScreenPriv->hbmpShadow);
-
-  /* Free the screen DC */
-  ReleaseDC (pScreenPriv->hwndScreen, pScreenPriv->hdcScreen);
-
-  /* Delete tray icon, if we have one */
-  if (!pScreenInfo->fNoTrayIcon)
-    winDeleteNotifyIcon (pScreenPriv);
-
-  /* Free the exit confirmation dialog box, if it exists */
-  if (g_hDlgExit != NULL)
-    {
-      DestroyWindow (g_hDlgExit);
-      g_hDlgExit = NULL;
-    }
-
-  /* Kill our window */
-  if (pScreenPriv->hwndScreen)
-    {
-      DestroyWindow (pScreenPriv->hwndScreen);
-      pScreenPriv->hwndScreen = NULL;
-    }
-
-#if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
-  /* Destroy the thread startup mutex */
-  pthread_mutex_destroy (&pScreenPriv->pmServerStarted);
-#endif
-
-  /* Invalidate our screeninfo's pointer to the screen */
-  pScreenInfo->pScreen = NULL;
-
-  /* Invalidate the ScreenInfo's fb pointer */
-  pScreenInfo->pfb = NULL;
-
-  /* Free the screen privates for this screen */
-  free ((pointer) pScreenPriv);
-
-  return fReturn;
-}
-
-
-/*
- * Tell mi what sort of visuals we need.
- * 
- * Generally we only need one visual, as our screen can only
- * handle one format at a time, I believe.  You may want
- * to verify that last sentence.
- */
-
-static Bool
-winInitVisualsShadowGDI (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-
-  /* Display debugging information */
-  ErrorF ("winInitVisualsShadowGDI - Masks %08x %08x %08x BPRGB %d d %d "
-	  "bpp %d\n",
-	  (unsigned int) pScreenPriv->dwRedMask,
-	  (unsigned int) pScreenPriv->dwGreenMask,
-	  (unsigned int) pScreenPriv->dwBlueMask,
-	  (int) pScreenPriv->dwBitsPerRGB,
-	  (int) pScreenInfo->dwDepth,
-	  (int) pScreenInfo->dwBPP);
-
-  /* Create a single visual according to the Windows screen depth */
-  switch (pScreenInfo->dwDepth)
-    {
-    case 24:
-    case 16:
-    case 15:
-#if defined(XFree86Server)
-      /* Setup the real visual */
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     TrueColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     -1,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowGDI - miSetVisualTypesAndMasks "
-		  "failed\n");
-	  return FALSE;
-	}
-
-#ifdef XWIN_EMULATEPSEUDO
-      if (!pScreenInfo->fEmulatePseudo)
-	break;
-
-      /* Setup a pseudocolor visual */
-      if (!miSetVisualTypesAndMasks (8,
-				     PseudoColorMask,
-				     8,
-				     -1,
-				     0,
-				     0,
-				     0))
-	{
-	  ErrorF ("winInitVisualsShadowGDI - miSetVisualTypesAndMasks "
-		  "failed for PseudoColor\n");
-	  return FALSE;
-	}
-#endif
-#else /* XFree86Server */
-      /* Setup the real visual */
-      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     TrueColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowGDI - fbSetVisualTypesAndMasks "
-		  "failed for TrueColor\n");
-	  return FALSE;
-	}
-
-#ifdef XWIN_EMULATEPSEUDO
-      if (!pScreenInfo->fEmulatePseudo)
-	break;
-
-      /* Setup a pseudocolor visual */
-      if (!fbSetVisualTypesAndMasks (8,
-				     PseudoColorMask,
-				     8,
-				     0,
-				     0,
-				     0))
-	{
-	  ErrorF ("winInitVisualsShadowGDI - fbSetVisualTypesAndMasks "
-		  "failed for PseudoColor\n");
-	  return FALSE;
-	}
-#endif
-#endif /* XFree86Server */
-      break;
-
-    case 8:
-#if defined(XFree86Server)
-      if (!miSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     PseudoColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     PseudoColor,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowGDI - miSetVisualTypesAndMasks "
-		  "failed\n");
-	  return FALSE;
-	}
-#else /* XFree86Server */
-      if (!fbSetVisualTypesAndMasks (pScreenInfo->dwDepth,
-				     PseudoColorMask,
-				     pScreenPriv->dwBitsPerRGB,
-				     pScreenPriv->dwRedMask,
-				     pScreenPriv->dwGreenMask,
-				     pScreenPriv->dwBlueMask))
-	{
-	  ErrorF ("winInitVisualsShadowGDI - fbSetVisualTypesAndMasks "
-		  "failed\n");
-	  return FALSE;
-	}
-#endif
-      break;
-
-    default:
-      ErrorF ("winInitVisualsShadowGDI - Unknown screen depth\n");
-      return FALSE;
-    }
-
-#if CYGDEBUG
-  winDebug ("winInitVisualsShadowGDI - Returning\n");
-#endif
-
-  return TRUE;
-}
-
-
-/*
- * Adjust the proposed video mode
- */
-
-static Bool
-winAdjustVideoModeShadowGDI (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  HDC			hdc;
-  DWORD			dwBPP;
-  
-  hdc = GetDC (NULL);
-
-  /* We're in serious trouble if we can't get a DC */
-  if (hdc == NULL)
-    {
-      ErrorF ("winAdjustVideoModeShadowGDI - GetDC () failed\n");
-      return FALSE;
-    }
-
-  /* Query GDI for current display depth */
-  dwBPP = GetDeviceCaps (hdc, BITSPIXEL);
-
-  /* GDI cannot change the screen depth */
-  if (pScreenInfo->dwBPP == WIN_DEFAULT_BPP)
-    {
-      /* No -depth parameter passed, let the user know the depth being used */
-      ErrorF ("winAdjustVideoModeShadowGDI - Using Windows display "
-	      "depth of %d bits per pixel\n", (int) dwBPP);
-
-      /* Use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-  else if (dwBPP != pScreenInfo->dwBPP)
-    {
-      /* Warn user if GDI depth is different than -depth parameter */
-      ErrorF ("winAdjustVideoModeShadowGDI - Command line bpp: %d, "\
-	      "using bpp: %d\n", (int) pScreenInfo->dwBPP, (int) dwBPP);
-
-      /* We'll use GDI's depth */
-      pScreenInfo->dwBPP = dwBPP;
-    }
-  
-  /* Release our DC */
-  ReleaseDC (NULL, hdc);
-  hdc = NULL;
-
-  return TRUE;
-}
-
-
-/*
- * Blt exposed regions to the screen
- */
-
-static Bool
-winBltExposedRegionsShadowGDI (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  winPrivCmapPtr	pCmapPriv = NULL;
-  HDC			hdcUpdate;
-  PAINTSTRUCT		ps;
-
-  /* BeginPaint gives us an hdc that clips to the invalidated region */
-  hdcUpdate = BeginPaint (pScreenPriv->hwndScreen, &ps);
-
-  /* Realize the palette, if we have one */
-  if (pScreenPriv->pcmapInstalled != NULL)
-    {
-      pCmapPriv = winGetCmapPriv (pScreenPriv->pcmapInstalled);
-      
-      SelectPalette (hdcUpdate, pCmapPriv->hPalette, FALSE);
-      RealizePalette (hdcUpdate);
-    }
-
-  /* Our BitBlt will be clipped to the invalidated region */
-  BitBlt (hdcUpdate,
-	  0, 0,
-	  pScreenInfo->dwWidth, pScreenInfo->dwHeight,
-	  pScreenPriv->hdcShadow,
-	  0, 0,
-	  SRCCOPY);
-
-  /* EndPaint frees the DC */
-  EndPaint (pScreenPriv->hwndScreen, &ps);
-
-#ifdef XWIN_MULTIWINDOW
-  /* Redraw all windows */
-  if (pScreenInfo->fMultiWindow)
-    EnumThreadWindows(g_dwCurrentThreadID, winRedrawAllProcShadowGDI, 
-            (LPARAM)pScreenPriv->hwndScreen);
-#endif
-
-  return TRUE;
-}
-
-
-/*
- * Do any engine-specific appliation-activation processing
- */
-
-static Bool
-winActivateAppShadowGDI (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-
-  /*
-   * 2004/04/12 - Harold - We perform the restoring or minimizing
-   * manually for ShadowGDI in fullscreen modes so that this engine
-   * will perform just like ShadowDD and ShadowDDNL in fullscreen mode;
-   * if we do not do this then our fullscreen window will appear in the
-   * z-order when it is deactivated and it can be uncovered by resizing
-   * or minimizing another window that is on top of it, which is not how
-   * the DirectDraw engines work.  Therefore we keep this code here to
-   * make sure that all engines work the same in fullscreen mode.
-   */
-
-  /*
-   * Are we active?
-   * Are we fullscreen?
-   */
-  if (pScreenPriv->fActive
-      && pScreenInfo->fFullScreen)
-    {
-      /*
-       * Activating, attempt to bring our window 
-       * to the top of the display
-       */
-      ShowWindow (pScreenPriv->hwndScreen, SW_RESTORE);
-    }
-  else if (!pScreenPriv->fActive
-	   && pScreenInfo->fFullScreen)
-    {
-      /*
-       * Deactivating, stuff our window onto the
-       * task bar.
-       */
-      ShowWindow (pScreenPriv->hwndScreen, SW_MINIMIZE);
-    }
-
-  return TRUE;
-}
-
-
-/*
- * Reblit the shadow framebuffer to the screen.
- */
-
-static Bool
-winRedrawScreenShadowGDI (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-
-  /* Redraw the whole window, to take account for the new colors */
-  BitBlt (pScreenPriv->hdcScreen,
-	  0, 0,
-	  pScreenInfo->dwWidth, pScreenInfo->dwHeight,
-	  pScreenPriv->hdcShadow,
-	  0, 0,
-	  SRCCOPY);
-
-#ifdef XWIN_MULTIWINDOW
-  /* Redraw all windows */
-  if (pScreenInfo->fMultiWindow)
-    EnumThreadWindows(g_dwCurrentThreadID, winRedrawAllProcShadowGDI, 0);
-#endif
-
-  return TRUE;
-}
-
-
-
-/*
- * Realize the currently installed colormap
- */
-
-static Bool
-winRealizeInstalledPaletteShadowGDI (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winPrivCmapPtr	pCmapPriv = NULL;
-
-#if CYGDEBUG
-  winDebug ("winRealizeInstalledPaletteShadowGDI\n");
-#endif
-
-  /* Don't do anything if there is not a colormap */
-  if (pScreenPriv->pcmapInstalled == NULL)
-    {
-#if CYGDEBUG
-      winDebug ("winRealizeInstalledPaletteShadowGDI - No colormap "
-	      "installed\n");
-#endif
-      return TRUE;
-    }
-
-  pCmapPriv = winGetCmapPriv (pScreenPriv->pcmapInstalled);
-  
-  /* Realize our palette for the screen */
-  if (RealizePalette (pScreenPriv->hdcScreen) == GDI_ERROR)
-    {
-      ErrorF ("winRealizeInstalledPaletteShadowGDI - RealizePalette () "
-	      "failed\n");
-      return FALSE;
-    }
-  
-  /* Set the DIB color table */
-  if (SetDIBColorTable (pScreenPriv->hdcShadow,
-			0,
-			WIN_NUM_PALETTE_ENTRIES,
-			pCmapPriv->rgbColors) == 0)
-    {
-      ErrorF ("winRealizeInstalledPaletteShadowGDI - SetDIBColorTable () "
-	      "failed\n");
-      return FALSE;
-    }
-  
-  return TRUE;
-}
-
-
-/*
- * Install the specified colormap
- */
-
-static Bool
-winInstallColormapShadowGDI (ColormapPtr pColormap)
-{
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  winCmapPriv(pColormap);
-
-  /*
-   * Tell Windows to install the new colormap
-   */
-  if (SelectPalette (pScreenPriv->hdcScreen,
-		     pCmapPriv->hPalette,
-		     FALSE) == NULL)
-    {
-      ErrorF ("winInstallColormapShadowGDI - SelectPalette () failed\n");
-      return FALSE;
-    }
-      
-  /* Realize the palette */
-  if (GDI_ERROR == RealizePalette (pScreenPriv->hdcScreen))
-    {
-      ErrorF ("winInstallColormapShadowGDI - RealizePalette () failed\n");
-      return FALSE;
-    }
-
-  /* Set the DIB color table */
-  if (SetDIBColorTable (pScreenPriv->hdcShadow,
-			0,
-			WIN_NUM_PALETTE_ENTRIES,
-			pCmapPriv->rgbColors) == 0)
-    {
-      ErrorF ("winInstallColormapShadowGDI - SetDIBColorTable () failed\n");
-      return FALSE;
-    }
-
-  /* Redraw the whole window, to take account for the new colors */
-  BitBlt (pScreenPriv->hdcScreen,
-	  0, 0,
-	  pScreenInfo->dwWidth, pScreenInfo->dwHeight,
-	  pScreenPriv->hdcShadow,
-	  0, 0,
-	  SRCCOPY);
-
-  /* Save a pointer to the newly installed colormap */
-  pScreenPriv->pcmapInstalled = pColormap;
-
-#ifdef XWIN_MULTIWINDOW
-  /* Redraw all windows */
-  if (pScreenInfo->fMultiWindow)
-    EnumThreadWindows (g_dwCurrentThreadID, winRedrawAllProcShadowGDI, 0);
-#endif
-
-  return TRUE;
-}
-
-
-/*
- * Store the specified colors in the specified colormap
- */
-
-static Bool
-winStoreColorsShadowGDI (ColormapPtr pColormap,
-			 int ndef,
-			 xColorItem *pdefs)
-{
-  ScreenPtr		pScreen = pColormap->pScreen;
-  winScreenPriv(pScreen);
-  winCmapPriv(pColormap);
-  ColormapPtr curpmap = pScreenPriv->pcmapInstalled;
-  
-  /* Put the X colormap entries into the Windows logical palette */
-  if (SetPaletteEntries (pCmapPriv->hPalette,
-			 pdefs[0].pixel,
-			 ndef,
-			 pCmapPriv->peColors + pdefs[0].pixel) == 0)
-    {
-      ErrorF ("winStoreColorsShadowGDI - SetPaletteEntries () failed\n");
-      return FALSE;
-    }
-
-  /* Don't install the Windows palette if the colormap is not installed */
-  if (pColormap != curpmap)
-    {
-      return TRUE;
-    }
-
-  /* Try to install the newly modified colormap */
-  if (!winInstallColormapShadowGDI (pColormap))
-    {
-      ErrorF ("winInstallColormapShadowGDI - winInstallColormapShadowGDI "
-	      "failed\n");
-      return FALSE;
-    }
-
-#if 0
-  /* Tell Windows that the palette has changed */
-  RealizePalette (pScreenPriv->hdcScreen);
-  
-  /* Set the DIB color table */
-  if (SetDIBColorTable (pScreenPriv->hdcShadow,
-			pdefs[0].pixel,
-			ndef,
-			pCmapPriv->rgbColors + pdefs[0].pixel) == 0)
-    {
-      ErrorF ("winInstallColormapShadowGDI - SetDIBColorTable () failed\n");
-      return FALSE;
-    }
-
-  /* Save a pointer to the newly installed colormap */
-  pScreenPriv->pcmapInstalled = pColormap;
-#endif
-
-  return TRUE;
-}
-
-
-/*
- * Colormap initialization procedure
- */
-
-static Bool
-winCreateColormapShadowGDI (ColormapPtr pColormap)
-{
-  LPLOGPALETTE		lpPaletteNew = NULL;
-  DWORD			dwEntriesMax;
-  VisualPtr		pVisual;
-  HPALETTE		hpalNew = NULL;
-  winCmapPriv(pColormap);
-
-  /* Get a pointer to the visual that the colormap belongs to */
-  pVisual = pColormap->pVisual;
-
-  /* Get the maximum number of palette entries for this visual */
-  dwEntriesMax = pVisual->ColormapEntries;
-
-  /* Allocate a Windows logical color palette with max entries */
-  lpPaletteNew = malloc (sizeof (LOGPALETTE)
-			 + (dwEntriesMax - 1) * sizeof (PALETTEENTRY));
-  if (lpPaletteNew == NULL)
-    {
-      ErrorF ("winCreateColormapShadowGDI - Couldn't allocate palette "
-	      "with %d entries\n",
-	      (int) dwEntriesMax);
-      return FALSE;
-    }
-
-  /* Zero out the colormap */
-  ZeroMemory (lpPaletteNew, sizeof (LOGPALETTE)
-	      + (dwEntriesMax - 1) * sizeof (PALETTEENTRY));
-  
-  /* Set the logical palette structure */
-  lpPaletteNew->palVersion = 0x0300;
-  lpPaletteNew->palNumEntries = dwEntriesMax;
-
-  /* Tell Windows to create the palette */
-  hpalNew = CreatePalette (lpPaletteNew);
-  if (hpalNew == NULL)
-    {
-      ErrorF ("winCreateColormapShadowGDI - CreatePalette () failed\n");
-      free (lpPaletteNew);
-      return FALSE;
-    }
-
-  /* Save the Windows logical palette handle in the X colormaps' privates */
-  pCmapPriv->hPalette = hpalNew;
-
-  /* Free the palette initialization memory */
-  free (lpPaletteNew);
-
-  return TRUE;
-}
-
-
-/*
- * Colormap destruction procedure
- */
-
-static Bool
-winDestroyColormapShadowGDI (ColormapPtr pColormap)
-{
-  winScreenPriv(pColormap->pScreen);
-  winCmapPriv(pColormap);
-
-  /*
-   * Is colormap to be destroyed the default?
-   *
-   * Non-default colormaps should have had winUninstallColormap
-   * called on them before we get here.  The default colormap
-   * will not have had winUninstallColormap called on it.  Thus,
-   * we need to handle the default colormap in a special way.
-   */
-  if (pColormap->flags & IsDefault)
-    {
-#if CYGDEBUG
-      winDebug ("winDestroyColormapShadowGDI - Destroying default "
-	      "colormap\n");
-#endif
-      
-      /*
-       * FIXME: Walk the list of all screens, popping the default
-       * palette out of each screen device context.
-       */
-      
-      /* Pop the palette out of the device context */
-      SelectPalette (pScreenPriv->hdcScreen,
-		     GetStockObject (DEFAULT_PALETTE),
-		     FALSE);
-
-      /* Clear our private installed colormap pointer */
-      pScreenPriv->pcmapInstalled = NULL;
-    }
-  
-  /* Try to delete the logical palette */
-  if (DeleteObject (pCmapPriv->hPalette) == 0)
-    {
-      ErrorF ("winDestroyColormap - DeleteObject () failed\n");
-      return FALSE;
-    }
-  
-  /* Invalidate the colormap privates */
-  pCmapPriv->hPalette = NULL;
-
-  return TRUE;
-}
-
-
-/*
- * Set engine specific funtions
- */
-
-Bool
-winSetEngineFunctionsShadowGDI (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  
-  /* Set our pointers */
-  pScreenPriv->pwinAllocateFB = winAllocateFBShadowGDI;
-  pScreenPriv->pwinShadowUpdate = winShadowUpdateGDI;
-  pScreenPriv->pwinCloseScreen = winCloseScreenShadowGDI;
-  pScreenPriv->pwinInitVisuals = winInitVisualsShadowGDI;
-  pScreenPriv->pwinAdjustVideoMode = winAdjustVideoModeShadowGDI;
-  if (pScreenInfo->fFullScreen)
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowFullScreen;
-  else
-    pScreenPriv->pwinCreateBoundingWindow = winCreateBoundingWindowWindowed;
-  pScreenPriv->pwinFinishScreenInit = winFinishScreenInitFB;
-  pScreenPriv->pwinBltExposedRegions = winBltExposedRegionsShadowGDI;
-  pScreenPriv->pwinActivateApp = winActivateAppShadowGDI;
-  pScreenPriv->pwinRedrawScreen = winRedrawScreenShadowGDI;
-  pScreenPriv->pwinRealizeInstalledPalette = 
-    winRealizeInstalledPaletteShadowGDI;
-  pScreenPriv->pwinInstallColormap = winInstallColormapShadowGDI;
-  pScreenPriv->pwinStoreColors = winStoreColorsShadowGDI;
-  pScreenPriv->pwinCreateColormap = winCreateColormapShadowGDI;
-  pScreenPriv->pwinDestroyColormap = winDestroyColormapShadowGDI;
-  pScreenPriv->pwinHotKeyAltTab = (winHotKeyAltTabProcPtr) (void (*)(void))NoopDDA;
-  pScreenPriv->pwinCreatePrimarySurface
-    = (winCreatePrimarySurfaceProcPtr) (void (*)(void))NoopDDA;
-  pScreenPriv->pwinReleasePrimarySurface
-    = (winReleasePrimarySurfaceProcPtr) (void (*)(void))NoopDDA;
-#ifdef XWIN_MULTIWINDOW
-  pScreenPriv->pwinFinishCreateWindowsWindow =
-    (winFinishCreateWindowsWindowProcPtr) (void (*)(void))NoopDDA;
-#endif
-
-  return TRUE;
-}
diff --git a/hw/xwin/wintrayicon.c b/hw/xwin/wintrayicon.c
deleted file mode 100755
index 054a8e9..0000000
--- a/hw/xwin/wintrayicon.c
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Early Ehlinger
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include <shellapi.h>
-#include "winprefs.h"
-
-/*
- * Initialize the tray icon
- */
-
-void
-winInitNotifyIcon (winPrivScreenPtr pScreenPriv)
-{
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  NOTIFYICONDATA	nid = {0};
-  
-  nid.cbSize = sizeof (NOTIFYICONDATA);
-  nid.hWnd = pScreenPriv->hwndScreen;
-  nid.uID = pScreenInfo->dwScreen;
-  nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
-  nid.uCallbackMessage = WM_TRAYICON;
-  nid.hIcon = (HICON)winTaskbarIcon ();
-
-  /* Save handle to the icon so it can be freed later */
-  pScreenPriv->hiconNotifyIcon = nid.hIcon;
-
-  /* Set display and screen-specific tooltip text */
-  snprintf (nid.szTip,
-	    sizeof (nid.szTip),
-	    PROJECT_NAME " Server - %s:%d",
-	    display, 
-	    (int) pScreenInfo->dwScreen);
-
-  /* Add the tray icon */
-  if (!Shell_NotifyIcon (NIM_ADD, &nid))
-    ErrorF ("winInitNotifyIcon - Shell_NotifyIcon Failed\n");
-}
-
-
-/*
- * Delete the tray icon
- */
-
-void
-winDeleteNotifyIcon (winPrivScreenPtr pScreenPriv)
-{
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-  NOTIFYICONDATA	nid = {0};
-  
-#if 0
-  ErrorF ("winDeleteNotifyIcon\n");
-#endif
-
-  nid.cbSize = sizeof (NOTIFYICONDATA);
-  nid.hWnd = pScreenPriv->hwndScreen;
-  nid.uID = pScreenInfo->dwScreen;
-  
-  /* Delete the tray icon */
-  if (!Shell_NotifyIcon (NIM_DELETE, &nid))
-    {
-      ErrorF ("winDeleteNotifyIcon - Shell_NotifyIcon failed\n");
-      return;
-    }
-
-  /* Free the icon that was loaded */
-  if (pScreenPriv->hiconNotifyIcon != NULL
-      && DestroyIcon (pScreenPriv->hiconNotifyIcon) == 0)
-    {
-      ErrorF ("winDeleteNotifyIcon - DestroyIcon failed\n");
-    }
-  pScreenPriv->hiconNotifyIcon = NULL;
-}
-
-
-/*
- * Process messages intended for the tray icon
- */
-
-LRESULT
-winHandleIconMessage (HWND hwnd, UINT message,
-		      WPARAM wParam, LPARAM lParam,
-		      winPrivScreenPtr pScreenPriv)
-{
-#if defined(XWIN_MULTIWINDOWEXTWM) || defined(XWIN_MULTIWINDOW)
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
-#endif
-
-  switch (lParam)
-    {
-    case WM_LBUTTONUP:
-      /* Restack and bring all windows to top */
-      SetForegroundWindow (hwnd);
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-      if (pScreenInfo->fMWExtWM)
-	winMWExtWMRestackWindows (pScreenInfo->pScreen);
-#endif
-      break;
-
-    case WM_LBUTTONDBLCLK:
-      /* Display Exit dialog box */
-      winDisplayExitDialog (pScreenPriv);
-      break;
-
-    case WM_RBUTTONUP:
-      {
-	POINT		ptCursor;
-	HMENU		hmenuPopup;
-	HMENU		hmenuTray;
-
-	/* Get cursor position */
-	GetCursorPos (&ptCursor);
-
-	/* Load tray icon menu resource */
-	hmenuPopup = LoadMenu (g_hInstance,
-			       MAKEINTRESOURCE(IDM_TRAYICON_MENU));
-	if (!hmenuPopup)
-	  ErrorF ("winHandleIconMessage - LoadMenu failed\n");
-
-	/* Get actual tray icon menu */
-	hmenuTray = GetSubMenu (hmenuPopup, 0);
-
-#ifdef XWIN_MULTIWINDOW
-	/* Check for MultiWindow mode */
-	if (pScreenInfo->fMultiWindow)
-	  {
-	    MENUITEMINFO		mii = {0};
-	    
-	    /* Root is shown, remove the check box */
-	    
-	    /* Setup menu item info structure */
-	    mii.cbSize = sizeof (MENUITEMINFO);
-	    mii.fMask = MIIM_STATE;
-	    mii.fState = MFS_CHECKED;
-	    
-	    /* Unheck box if root is shown */
-	    if (pScreenPriv->fRootWindowShown)
-	      mii.fState = MFS_UNCHECKED;
-
-	    /* Set menu state */
-	    SetMenuItemInfo (hmenuTray, ID_APP_HIDE_ROOT, FALSE, &mii);
-	  }
-	else
-#endif
-	  {
-	    /* Remove Hide Root Window button */
-	    RemoveMenu (hmenuTray,
-			ID_APP_HIDE_ROOT,
-			MF_BYCOMMAND);
-	  }
-
-	SetupRootMenu ((unsigned long)hmenuTray);
-
-	/*
-	 * NOTE: This three-step procedure is required for
-	 * proper popup menu operation.  Without the
-	 * call to SetForegroundWindow the
-	 * popup menu will often not disappear when you click
-	 * outside of it.  Without the PostMessage the second
-	 * time you display the popup menu it might immediately
-	 * disappear.
-	 */
-	SetForegroundWindow (hwnd);
-	TrackPopupMenuEx (hmenuTray,
-			  TPM_LEFTALIGN | TPM_BOTTOMALIGN | TPM_RIGHTBUTTON,
-			  ptCursor.x, ptCursor.y,
-			  hwnd,
-			  NULL);
-	PostMessage (hwnd, WM_NULL, 0, 0);
-
-	/* Free menu */
-	DestroyMenu (hmenuPopup);
-      }
-      break;
-    }
-
-  return 0;
-}
diff --git a/hw/xwin/winvalargs.c b/hw/xwin/winvalargs.c
deleted file mode 100755
index 038e097..0000000
--- a/hw/xwin/winvalargs.c
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winmsg.h"
-
-
-/*
- * References to external symbols
- */
-
-extern int			g_iNumScreens;
-extern winScreenInfo		g_ScreenInfo[];
-extern Bool			g_fXdmcpEnabled;
-
-
-/*
- * Prototypes
- */
-
-Bool
-winValidateArgs (void);
-
-
-/*
- * winValidateArgs - Look for invalid argument combinations
- */
-
-Bool
-winValidateArgs (void)
-{
-  int		i;
-  int		iMaxConsecutiveScreen = 0;
-  BOOL		fHasNormalScreen0 = FALSE;
-
-  /*
-   * Check for a malformed set of -screen parameters.
-   * Examples of malformed parameters:
-   *	XWin -screen 1
-   *	XWin -screen 0 -screen 2
-   *	XWin -screen 1 -screen 2
-   */
-  for (i = 0; i < MAXSCREENS; i++)
-    {
-      if (g_ScreenInfo[i].fExplicitScreen)
-	iMaxConsecutiveScreen = i + 1;
-    }
-  winErrorFVerb (2, "winValidateArgs - g_iNumScreens: %d "
-		 "iMaxConsecutiveScreen: %d\n",
-		 g_iNumScreens, iMaxConsecutiveScreen);
-  if (g_iNumScreens < iMaxConsecutiveScreen)
-    {
-      ErrorF ("winValidateArgs - Malformed set of screen parameter(s).  "
-	      "Screens must be specified consecutively starting with "
-	      "screen 0.  That is, you cannot have only a screen 1, nor "
-	      "could you have screen 0 and screen 2.  You instead must "
-	      "have screen 0, or screen 0 and screen 1, respectively.  Of "
-	      "you can specify as many screens as you want from 0 up to "
-	      "%d.\n", MAXSCREENS - 1);
-      return FALSE;
-    }
-
-  /* Loop through all screens */
-  for (i = 0; i < g_iNumScreens; ++i)
-    {
-      /*
-       * Check for any combination of
-       * -multiwindow, -mwextwm, and -rootless.
-       */
-      {
-	int		iCount = 0;
-
-	/* Count conflicting options */
-#ifdef XWIN_MULTIWINDOW
-	if (g_ScreenInfo[i].fMultiWindow)
-	  ++iCount;
-#endif
-#ifdef XWIN_MULTIWINDOWEXTWM
-	if (g_ScreenInfo[i].fMWExtWM)
-	  ++iCount;
-#endif
-	if (g_ScreenInfo[i].fRootless)
-	  ++iCount;
-
-	/* Check if the first screen is without rootless and multiwindow */ 
-	if (iCount == 0 && i == 0)
-	  fHasNormalScreen0 = TRUE;  
-
-	/* Fail if two or more conflicting options */
-	if (iCount > 1)
-	  {
-	    ErrorF ("winValidateArgs - Only one of -multiwindow, -mwextwm, "
-		    "and -rootless can be specific at a time.\n");
-	    return FALSE;
-	  }
-      }
-
-      /* Check for -multiwindow or -mwextwm and Xdmcp */
-      /* allow xdmcp if screen 0 is normal. */
-      if (g_fXdmcpEnabled && !fHasNormalScreen0
-	  && (FALSE
-#ifdef XWIN_MULTIWINDOW
-	      || g_ScreenInfo[i].fMultiWindow
-#endif
-#ifdef XWIN_MULTIWINDOWEXTWM
-	      || g_ScreenInfo[i].fMWExtWM
-#endif
-	      )
-	  )
-	{
-	  ErrorF ("winValidateArgs - Xdmcp (-query, -broadcast, or -indirect) "
-		  "is invalid with -multiwindow or -mwextwm.\n");
-	  return FALSE;
-	}
-
-      /* Check for -multiwindow, -mwextwm, or -rootless and fullscreen */
-      if (g_ScreenInfo[i].fFullScreen
-	  && (FALSE
-#ifdef XWIN_MULTIWINDOW
-	      || g_ScreenInfo[i].fMultiWindow
-#endif
-#ifdef XWIN_MULTIWINDOWEXTWM
-	      || g_ScreenInfo[i].fMWExtWM
-#endif
-	      || g_ScreenInfo[i].fRootless)
-	  )
-	{
-	  ErrorF ("winValidateArgs - -fullscreen is invalid with "
-		  "-multiwindow, -mwextwm, or -rootless.\n");
-	  return FALSE;
-	}
-      
-      /* Check for !fullscreen and any fullscreen-only parameters */
-      if (!g_ScreenInfo[i].fFullScreen
-	  && (g_ScreenInfo[i].dwRefreshRate != WIN_DEFAULT_BPP
-	      || g_ScreenInfo[i].dwBPP != WIN_DEFAULT_REFRESH))
-	{
-	  ErrorF ("winValidateArgs - -refresh and -depth are only valid "
-		  "with -fullscreen.\n");
-	  return FALSE;
-	}
-
-      /* Check for fullscreen and any non-fullscreen parameters */
-      if (g_ScreenInfo[i].fFullScreen
-	  && (g_ScreenInfo[i].fScrollbars
-	      || !g_ScreenInfo[i].fDecoration
-	      || g_ScreenInfo[i].fLessPointer))
-	{
-	  ErrorF ("winValidateArgs - -fullscreen is invalid with "
-		  "-scrollbars, -nodecoration, or -lesspointer.\n");
-	  return FALSE;
-	}
-    }
-
-  winDebug ("winValidateArgs - Returning.\n");
-
-  return TRUE;
-}
diff --git a/hw/xwin/winvideo.c b/hw/xwin/winvideo.c
deleted file mode 100755
index 529ca76..0000000
--- a/hw/xwin/winvideo.c
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors:	Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include <X11/extensions/Xv.h>
-#include <X11/extensions/Xvproto.h>
-
-void
-winInitVideo (ScreenPtr pScreen);
-
-/*
- * winInitVideo - Initialize support for the X Video (Xv) Extension.
- */
-
-void
-winInitVideo (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo; 
-
-  if (pScreenInfo->dwBPP > 8) 
-    {
-      
-    }
-  
-
-}
-
-
-
-
-
-
-
-#if 0
-#include "../xfree86/common/xf86.h"
-#include "../Xext/xvdix.h"
-#include "../xfree86/common/xf86xv.h"
-#include <X11/extensions/Xv.h>
-#endif
-
-#include "win.h"
-
-
-
-#if 0
-/* client libraries expect an encoding */
-static XF86VideoEncodingRec DummyEncoding[1] =
-{
- {
-   0,
-   "XV_IMAGE",
-   IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT,
-   {1, 1}
- }
-};
-
-#define NUM_FORMATS 3
-
-static XF86VideoFormatRec Formats[NUM_FORMATS] = 
-{
-  {15, TrueColor}, {16, TrueColor}, {24, TrueColor}
-};
-
-#define NUM_ATTRIBUTES 3
-
-static XF86AttributeRec Attributes[NUM_ATTRIBUTES] =
-{
-   {XvSettable | XvGettable, 0, (1 << 24) - 1, "XV_COLORKEY"},
-   {XvSettable | XvGettable, -128, 127, "XV_BRIGHTNESS"},
-   {XvSettable | XvGettable, 0, 255, "XV_CONTRAST"}
-};
-
-#define NUM_IMAGES 4
-
-static XF86ImageRec Images[NUM_IMAGES] =
-{
-	XVIMAGE_YUY2,
-	XVIMAGE_YV12,
-	XVIMAGE_I420,
-	XVIMAGE_UYVY
-};
-
-
-
-/*
- * winInitVideo - Initialize support for the X Video (Xv) Extension.
- */
-
-void
-winInitVideo (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo; 
-  XF86VideoAdaptorPtr	newAdaptor = NULL;
-
-  if (pScreenInfo->dwBPP > 8) 
-    {
-      newAdaptor = I810SetupImageVideo (pScreen);
-      I810InitOffscreenImages (pScreen);
-    }
-  
-    xf86XVScreenInit (pScreen, adaptors, 1);
-}
-
-
-static XF86VideoAdaptorPtr 
-winSetupImageVideo (ScreenPtr pScreen)
-{
-    ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
-#if 0
-    I810Ptr pI810 = I810PTR(pScrn);
-#endif
-    XF86VideoAdaptorPtr adapt;
-
-    if (!(adapt = xcalloc (1, sizeof(XF86VideoAdaptorRec))))
-      return NULL;
-
-    adapt->type = XvWindowMask | XvInputMask | XvImageMask;
-    adapt->flags = VIDEO_OVERLAID_IMAGES | VIDEO_CLIP_TO_VIEWPORT;
-    adapt->name = PROJECT_NAME " Video Overlay";
-    adapt->nEncodings = 1;
-    adapt->pEncodings = DummyEncoding;
-    adapt->nFormats = NUM_FORMATS;
-    adapt->pFormats = Formats;
-    adapt->nPorts = 1;
-    adapt->pPortPrivates = NULL;
-
-    adapt->pPortPrivates[0].ptr = NULL;
-    adapt->pAttributes = Attributes;
-    adapt->nImages = NUM_IMAGES;
-    adapt->nAttributes = NUM_ATTRIBUTES;
-    adapt->pImages = Images;
-    adapt->PutVideo = NULL;
-    adapt->PutStill = NULL;
-    adapt->GetVideo = NULL;
-    adapt->GetStill = NULL;
-#if 0
-    adapt->StopVideo = I810StopVideo;
-    adapt->SetPortAttribute = I810SetPortAttribute;
-    adapt->GetPortAttribute = I810GetPortAttribute;
-    adapt->QueryBestSize = I810QueryBestSize;
-    adapt->PutImage = I810PutImage;
-    adapt->QueryImageAttributes = I810QueryImageAttributes;
-#endif
-
-#if 0
-    pPriv->colorKey = pI810->colorKey & ((1 << pScrn->depth) - 1);
-#endif
-    pPriv->videoStatus = 0;
-    pPriv->brightness = 0;
-    pPriv->contrast = 64;
-    pPriv->linear = NULL;
-    pPriv->currentBuf = 0;
-
-#if 0
-    /* gotta uninit this someplace */
-    REGION_NULL(pScreen, &pPriv->clip);
-#endif
-
-#if 0
-    pI810->adaptor = adapt;
-
-    pI810->BlockHandler = pScreen->BlockHandler;
-    pScreen->BlockHandler = I810BlockHandler;
-#endif
-
-#if 0
-    xvBrightness = MAKE_ATOM("XV_BRIGHTNESS");
-    xvContrast   = MAKE_ATOM("XV_CONTRAST");
-    xvColorKey   = MAKE_ATOM("XV_COLORKEY");
-#endif
-
-#if 0
-    I810ResetVideo(pScrn);
-#endif
-
-    return adapt;
-}
-#endif
diff --git a/hw/xwin/winwakeup.c b/hw/xwin/winwakeup.c
deleted file mode 100644
index e1eece3..0000000
--- a/hw/xwin/winwakeup.c
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * References to external symbols
- */
-
-extern HWND			g_hDlgDepthChange;
-extern HWND			g_hDlgExit;
-extern HWND			g_hDlgAbout;
-
-
-/* See Porting Layer Definition - p. 7 */
-void
-winWakeupHandler (int nScreen,
-		  pointer pWakeupData,
-		  unsigned long ulResult,
-		  pointer pReadmask)
-{
-  MSG			msg;
-
-  /* Process all messages on our queue */
-  while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
-    {
-      if ((g_hDlgDepthChange == 0
-	   || !IsDialogMessage (g_hDlgDepthChange, &msg))
-	  && (g_hDlgExit == 0
-	      || !IsDialogMessage (g_hDlgExit, &msg))
-	  && (g_hDlgAbout == 0
-	      || !IsDialogMessage (g_hDlgAbout, &msg)))
-	{
-	  DispatchMessage (&msg);
-	}
-    }
-}
diff --git a/hw/xwin/winwin32rootless.c b/hw/xwin/winwin32rootless.c
deleted file mode 100755
index 6f4e2c9..0000000
--- a/hw/xwin/winwin32rootless.c
+++ /dev/null
@@ -1,1092 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Kensuke Matsuzaki
- *		Earle F. Philhower, III
- *		Harold L Hunt II
- */
-/*
- * Look at hw/darwin/quartz/xpr/xprFrame.c and hw/darwin/quartz/cr/crFrame.c
- */
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include <winuser.h>
-#define _WINDOWSWM_SERVER_
-#include "windowswmstr.h"
-#include "dixevents.h"
-#include "winmultiwindowclass.h"
-#include "winprefs.h"
-#include <X11/Xatom.h>
-
-
-/*
- * Constant defines
- */
-
-#define MOUSE_POLLING_INTERVAL		500
-
-#define ULW_COLORKEY	0x00000001
-#define ULW_ALPHA	0x00000002
-#define ULW_OPAQUE	0x00000004
-#define AC_SRC_ALPHA	0x01
-
-/*
- * Local function
- */
-
-DEFINE_ATOM_HELPER(AtmWindowsWmNativeHwnd, WINDOWSWM_NATIVE_HWND)
-static void
-winMWExtWMSetNativeProperty (RootlessWindowPtr pFrame);
-
-/*
- * Global variables
- */
-
-Bool			g_fNoConfigureWindow = FALSE;
-
-
-extern void winSelectIcons(WindowPtr pWin, HICON *pIcon, HICON *pSmallIcon);
-
-/*
- * Internal function to get the DIB format that is compatible with the screen
- * Fixme: Share code with winshadgdi.c
- */
-
-static
-Bool
-winMWExtWMQueryDIBFormat (win32RootlessWindowPtr pRLWinPriv, BITMAPINFOHEADER *pbmih)
-{
-  HBITMAP		hbmp;
-#if CYGMULTIWINDOW_DEBUG
-  LPDWORD		pdw = NULL;
-#endif
-  
-  /* Create a memory bitmap compatible with the screen */
-  hbmp = CreateCompatibleBitmap (pRLWinPriv->hdcScreen, 1, 1);
-  if (hbmp == NULL)
-    {
-      ErrorF ("winMWExtWMQueryDIBFormat - CreateCompatibleBitmap failed\n");
-      return FALSE;
-    }
-  
-  /* Initialize our bitmap info header */
-  ZeroMemory (pbmih, sizeof (BITMAPINFOHEADER) + 256 * sizeof (RGBQUAD));
-  pbmih->biSize = sizeof (BITMAPINFOHEADER);
-
-  /* Get the biBitCount */
-  if (!GetDIBits (pRLWinPriv->hdcScreen,
-		  hbmp,
-		  0, 1,
-		  NULL,
-		  (BITMAPINFO*) pbmih,
-		  DIB_RGB_COLORS))
-    {
-      ErrorF ("winMWExtWMQueryDIBFormat - First call to GetDIBits failed\n");
-      DeleteObject (hbmp);
-      return FALSE;
-    }
-
-#if CYGMULTIWINDOW_DEBUG
-  /* Get a pointer to bitfields */
-  pdw = (DWORD*) ((CARD8*)pbmih + sizeof (BITMAPINFOHEADER));
-
-  winDebug ("winMWExtWMQueryDIBFormat - First call masks: %08x %08x %08x\n",
-	  (unsigned int)pdw[0], (unsigned int)pdw[1], (unsigned int)pdw[2]);
-#endif
-
-  /* Get optimal color table, or the optimal bitfields */
-  if (!GetDIBits (pRLWinPriv->hdcScreen,
-		  hbmp,
-		  0, 1,
-		  NULL,
-		  (BITMAPINFO*)pbmih,
-		  DIB_RGB_COLORS))
-    {
-      ErrorF ("winMWExtWMQueryDIBFormat - Second call to GetDIBits "
-	      "failed\n");
-      DeleteObject (hbmp);
-      return FALSE;
-    }
-
-  /* Free memory */
-  DeleteObject (hbmp);
-  
-  return TRUE;
-}
-
-static HRGN
-winMWExtWMCreateRgnFromRegion (RegionPtr pShape)
-{
-  int		nRects;
-  BoxPtr	pRects, pEnd;
-  HRGN		hRgn, hRgnRect;
-
-  if (pShape == NULL) return NULL;
-
-  nRects = REGION_NUM_RECTS(pShape);
-  pRects = REGION_RECTS(pShape);
-  
-  hRgn = CreateRectRgn (0, 0, 0, 0);
-  if (hRgn == NULL)
-    {
-      ErrorF ("winReshape - Initial CreateRectRgn (%d, %d, %d, %d) "
-	      "failed: %d\n",
-	      0, 0, 0, 0, (int) GetLastError ());
-    }
-
-  /* Loop through all rectangles in the X region */
-  for (pEnd = pRects + nRects; pRects < pEnd; pRects++)
-    {
-      /* Create a Windows region for the X rectangle */
-      hRgnRect = CreateRectRgn (pRects->x1,
-				pRects->y1,
-				pRects->x2,
-				pRects->y2);
-      if (hRgnRect == NULL)
-	{
-	  ErrorF ("winReshape - Loop CreateRectRgn (%d, %d, %d, %d) "
-		  "failed: %d\n",
-		  pRects->x1,
-		  pRects->y1,
-		  pRects->x2,
-		  pRects->y2,
-		  (int) GetLastError ());
-	}
-      
-      /* Merge the Windows region with the accumulated region */
-      if (CombineRgn (hRgn, hRgn, hRgnRect, RGN_OR) == ERROR)
-	{
-	  ErrorF ("winReshape - CombineRgn () failed: %d\n",
-		  (int) GetLastError ());
-	}
-      
-      /* Delete the temporary Windows region */
-      DeleteObject (hRgnRect);
-    }
-  
-  return hRgn;
-}
-
-static void
-InitWin32RootlessEngine (win32RootlessWindowPtr pRLWinPriv)
-{
-  pRLWinPriv->hdcScreen = GetDC (pRLWinPriv->hWnd);
-  pRLWinPriv->hdcShadow = CreateCompatibleDC (pRLWinPriv->hdcScreen);
-  pRLWinPriv->hbmpShadow = NULL;
-
-  /* Allocate bitmap info header */
-  pRLWinPriv->pbmihShadow = (BITMAPINFOHEADER*) malloc (sizeof (BITMAPINFOHEADER)
-							+ 256 * sizeof (RGBQUAD));
-  if (pRLWinPriv->pbmihShadow == NULL)
-    {
-      ErrorF ("InitWin32RootlessEngine - malloc () failed\n");
-      return;
-    }
-  
-  /* Query the screen format */
-  winMWExtWMQueryDIBFormat (pRLWinPriv,
-				  pRLWinPriv->pbmihShadow);
-}
-
-Bool
-winMWExtWMCreateFrame (RootlessWindowPtr pFrame, ScreenPtr pScreen,
-			     int newX, int newY, RegionPtr pShape)
-{
-#define CLASS_NAME_LENGTH 512
-  Bool				fResult = TRUE;
-  win32RootlessWindowPtr	pRLWinPriv;
-  WNDCLASSEX			wc;
-  char				pszClass[CLASS_NAME_LENGTH], pszWindowID[12];
-  HICON				hIcon;
-  HICON				hIconSmall;
-  char				*res_name, *res_class, *res_role;
-  static int			s_iWindowID = 0;
- 
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMCreateFrame %d %d - %d %d\n",
-	  newX, newY, pFrame->width, pFrame->height);
-#endif
-
-  pRLWinPriv = (win32RootlessWindowPtr) malloc (sizeof (win32RootlessWindowRec));
-  pRLWinPriv->pFrame = pFrame;
-  pRLWinPriv->pfb = NULL;
-  pRLWinPriv->hbmpShadow = NULL;
-  pRLWinPriv->hdcShadow = NULL;
-  pRLWinPriv->hdcScreen = NULL;
-  pRLWinPriv->pbmihShadow = NULL;
-  pRLWinPriv->fResized = TRUE;
-  pRLWinPriv->fClose = FALSE;
-  pRLWinPriv->fRestackingNow = FALSE;
-  pRLWinPriv->fDestroyed = FALSE;
-  pRLWinPriv->fMovingOrSizing = FALSE;
-  
-  // Store the implementation private frame ID
-  pFrame->wid = (RootlessFrameID) pRLWinPriv;
-
-  winSelectIcons(pFrame->win, &hIcon, &hIconSmall); 
-  
-  /* Set standard class name prefix so we can identify window easily */
-  strncpy (pszClass, WINDOW_CLASS_X, sizeof(pszClass));
-
-  if (winMultiWindowGetClassHint (pFrame->win, &res_name, &res_class))
-    {
-      strncat (pszClass, "-", 1);
-      strncat (pszClass, res_name, CLASS_NAME_LENGTH - strlen (pszClass));
-      strncat (pszClass, "-", 1);
-      strncat (pszClass, res_class, CLASS_NAME_LENGTH - strlen (pszClass));
-      
-      /* Check if a window class is provided by the WM_WINDOW_ROLE property,
-       * if not use the WM_CLASS information.
-       * For further information see:
-       * http://tronche.com/gui/x/icccm/sec-5.html
-       */
-      if (winMultiWindowGetWindowRole (pFrame->win, &res_role) )
-	{
-	  strcat (pszClass, "-");
-	  strcat (pszClass, res_role);
-	  free (res_role);
-	}
-
-      free (res_name);
-      free (res_class);
-    }
-
-  /* Add incrementing window ID to make unique class name */
-  snprintf (pszWindowID, sizeof(pszWindowID), "-%x", s_iWindowID++);
-  pszWindowID[sizeof(pszWindowID)-1] = 0;
-  strcat (pszClass, pszWindowID);
-
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winCreateWindowsWindow - Creating class: %s\n", pszClass);
-#endif
-
-  /* Setup our window class */
-  wc.cbSize = sizeof(wc);
-  wc.style = CS_HREDRAW | CS_VREDRAW;
-  wc.lpfnWndProc = winMWExtWMWindowProc;
-  wc.cbClsExtra = 0;
-  wc.cbWndExtra = 0;
-  wc.hInstance = g_hInstance;
-  wc.hIcon = hIcon;
-  wc.hIconSm = hIconSmall;
-  wc.hCursor = 0;
-  wc.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
-  wc.lpszMenuName = NULL;
-  wc.lpszClassName = pszClass;
-  RegisterClassEx (&wc);
-
-  /* Create the window */
-  g_fNoConfigureWindow = TRUE;
-  pRLWinPriv->hWnd = CreateWindowExA (WS_EX_TOOLWINDOW,		/* Extended styles */
-				      pszClass,			/* Class name */
-				      WINDOW_TITLE_X,		/* Window name */
-				      WS_POPUP | WS_CLIPCHILDREN,
-				      newX,			/* Horizontal position */
-				      newY,			/* Vertical position */
-				      pFrame->width,		/* Right edge */ 
-				      pFrame->height,		/* Bottom edge */
-				      (HWND) NULL,		/* No parent or owner window */
-				      (HMENU) NULL,		/* No menu */
-				      GetModuleHandle (NULL),	/* Instance handle */
-				      pRLWinPriv);		/* ScreenPrivates */
-  if (pRLWinPriv->hWnd == NULL)
-    {
-      ErrorF ("winMWExtWMCreateFrame - CreateWindowExA () failed: %d\n",
-	      (int) GetLastError ());
-      fResult = FALSE;
-    }
-
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMCreateFrame - ShowWindow\n");
-#endif
-
-  //ShowWindow (pRLWinPriv->hWnd, SW_SHOWNOACTIVATE);
-  g_fNoConfigureWindow = FALSE;
-  
-  if (pShape != NULL)
-    {
-      winMWExtWMReshapeFrame (pFrame->wid, pShape);
-    }
-
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMCreateFrame - (%08x) %08x\n",
-	  (int) pFrame->wid, (int) pRLWinPriv->hWnd);
-#if 0
-  {
-   WindowPtr		pWin2 = NULL;
-   win32RootlessWindowPtr pRLWinPriv2 = NULL;
-
-   /* Check if the Windows window property for our X window pointer is valid */
-   if ((pWin2 = (WindowPtr)GetProp (pRLWinPriv->hWnd, WIN_WINDOW_PROP)) != NULL)
-     {
-       pRLWinPriv2 = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin2, FALSE);
-     }
-   winDebug ("winMWExtWMCreateFrame2 (%08x) %08x\n",
-	   pRLWinPriv2, pRLWinPriv2->hWnd);
-   if (pRLWinPriv != pRLWinPriv2 || pRLWinPriv->hWnd != pRLWinPriv2->hWnd)
-     {
-       winDebug ("Error param missmatch\n");
-     }
- }
-#endif
-#endif
-
-  winMWExtWMSetNativeProperty (pFrame);
-
-  return fResult;
-}
-
-void
-winMWExtWMDestroyFrame (RootlessFrameID wid)
-{
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
-  HICON			hiconClass;
-  HICON			hiconSmClass;
-  HMODULE		hInstance;
-  int			iReturn;
-  char			pszClass[CLASS_NAME_LENGTH];
-
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMDestroyFrame (%08x) %08x\n",
-	  (int) pRLWinPriv, (int) pRLWinPriv->hWnd);
-#if 0
- {
-   WindowPtr		pWin2 = NULL;
-   win32RootlessWindowPtr pRLWinPriv2 = NULL;
-
-   /* Check if the Windows window property for our X window pointer is valid */
-   if ((pWin2 = (WindowPtr)GetProp (pRLWinPriv->hWnd, WIN_WINDOW_PROP)) != NULL)
-     {
-       pRLWinPriv2 = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin2, FALSE);
-     }
-   winDebug ("winMWExtWMDestroyFrame2 (%08x) %08x\n",
-	   pRLWinPriv2, pRLWinPriv2->hWnd);
-   if (pRLWinPriv != pRLWinPriv2 || pRLWinPriv->hWnd != pRLWinPriv2->hWnd)
-     {
-       winDebug ("Error param missmatch\n");
-       *(int*)0 = 1;//raise exseption
-     }
- }
-#endif
-#endif
-
-  /* Store the info we need to destroy after this window is gone */
-  hInstance = (HINSTANCE) GetClassLong (pRLWinPriv->hWnd, GCL_HMODULE);
-  hiconClass = (HICON) GetClassLong (pRLWinPriv->hWnd, GCL_HICON);
-  hiconSmClass = (HICON) GetClassLong (pRLWinPriv->hWnd, GCL_HICONSM);
-  iReturn = GetClassName (pRLWinPriv->hWnd, pszClass, CLASS_NAME_LENGTH);
-
-  pRLWinPriv->fClose = TRUE;
-  pRLWinPriv->fDestroyed = TRUE;
-
-  /* Destroy the Windows window */
-  DestroyWindow (pRLWinPriv->hWnd);
-
-  /* Only if we were able to get the name */
-  if (iReturn)
-    { 
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMDestroyFrame - Unregistering %s: ", pszClass);
-#endif
-      iReturn = UnregisterClass (pszClass, hInstance);
-      
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMDestroyFramew - %d Deleting Icon: ", iReturn);
-#endif
-      
-      winDestroyIcon(hiconClass);
-      winDestroyIcon(hiconSmClass);
-    }
-
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMDestroyFrame - done\n");
-#endif
-}
-
-void
-winMWExtWMMoveFrame (RootlessFrameID wid, ScreenPtr pScreen, int iNewX, int iNewY)
-{
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
-  RECT rcNew;
-  DWORD dwExStyle;
-  DWORD dwStyle;
-  int iX, iY, iWidth, iHeight;
-
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMMoveFrame (%08x) (%d %d)\n", (int) pRLWinPriv, iNewX, iNewY);
-#endif
-
-  /* Get the Windows window style and extended style */
-  dwExStyle = GetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE);
-  dwStyle = GetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE);
-
-  /* Get the X and Y location of the X window */
-  iX = iNewX + GetSystemMetrics (SM_XVIRTUALSCREEN);
-  iY = iNewY + GetSystemMetrics (SM_YVIRTUALSCREEN);
-
-  /* Get the height and width of the X window */
-  iWidth = pRLWinPriv->pFrame->width;
-  iHeight = pRLWinPriv->pFrame->height;
-
-  /* Store the origin, height, and width in a rectangle structure */
-  SetRect (&rcNew, iX, iY, iX + iWidth, iY + iHeight);
-
-#ifdef CYGMULTIWINDOW_DEBUG
-          winDebug("\tWindow {%d, %d, %d, %d}, {%d, %d}\n", 
-              rcNew.left, rcNew.top, rcNew.right, rcNew.bottom,
-              rcNew.right - rcNew.left, rcNew.bottom - rcNew.top);
-#endif
-  /*
-   * Calculate the required size of the Windows window rectangle,
-   * given the size of the Windows window client area.
-   */
-  AdjustWindowRectEx (&rcNew, dwStyle, FALSE, dwExStyle);
-
-#ifdef CYGMULTIWINDOW_DEBUG
-          winDebug("\tAdjusted {%d, %d, %d, %d}, {%d, %d}\n", 
-              rcNew.left, rcNew.top, rcNew.right, rcNew.bottom,
-              rcNew.right - rcNew.left, rcNew.bottom - rcNew.top);
-#endif
-  g_fNoConfigureWindow = TRUE;
-  SetWindowPos (pRLWinPriv->hWnd, NULL, rcNew.left, rcNew.top, 0, 0,
-		SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER);
-  g_fNoConfigureWindow = FALSE;
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMMoveFrame (%08x) done\n", (int) pRLWinPriv);
-#endif
-}
-
-void
-winMWExtWMResizeFrame (RootlessFrameID wid, ScreenPtr pScreen,
-			     int iNewX, int iNewY,
-			     unsigned int uiNewWidth, unsigned int uiNewHeight,
-			     unsigned int uiGravity)
-{
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
-  RECT rcNew;
-  RECT rcOld;
-  DWORD dwExStyle;
-  DWORD dwStyle;
-  int iX, iY;
-
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMResizeFrame (%08x) (%d %d)-(%d %d)\n",
-	  (int) pRLWinPriv, iNewX, iNewY, uiNewWidth, uiNewHeight);
-#endif
-
-  pRLWinPriv->fResized = TRUE;
-
-  /* Get the Windows window style and extended style */
-  dwExStyle = GetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE);
-  dwStyle = GetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE);
-
-  /* Get the X and Y location of the X window */
-  iX = iNewX + GetSystemMetrics (SM_XVIRTUALSCREEN);
-  iY = iNewY + GetSystemMetrics (SM_YVIRTUALSCREEN);
-
-  /* Store the origin, height, and width in a rectangle structure */
-  SetRect (&rcNew, iX, iY, iX + uiNewWidth, iY + uiNewHeight);
-
-  /*
-   * Calculate the required size of the Windows window rectangle,
-   * given the size of the Windows window client area.
-   */
-  AdjustWindowRectEx (&rcNew, dwStyle, FALSE, dwExStyle);
-
-  /* Get a rectangle describing the old Windows window */
-  GetWindowRect (pRLWinPriv->hWnd, &rcOld);
-
-  /* Check if the old rectangle and new rectangle are the same */
-  if (!EqualRect (&rcNew, &rcOld))
-    {
-
-      g_fNoConfigureWindow = TRUE;
-      MoveWindow (pRLWinPriv->hWnd,
-		  rcNew.left, rcNew.top,
-		  rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
-		  TRUE);
-      g_fNoConfigureWindow = FALSE;
-    }
-}
-
-void
-winMWExtWMRestackFrame (RootlessFrameID wid, RootlessFrameID nextWid)
-{
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
-  win32RootlessWindowPtr pRLNextWinPriv = (win32RootlessWindowPtr) nextWid;
-  winScreenPriv(pRLWinPriv->pFrame->win->drawable.pScreen);
-  winScreenInfo *pScreenInfo = NULL;
-  DWORD dwCurrentProcessID = GetCurrentProcessId ();
-  DWORD dwWindowProcessID = 0;
-  HWND hWnd;
-  Bool fFirst = TRUE;
-  Bool fNeedRestack = TRUE;
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMRestackFrame (%08x)\n", (int) pRLWinPriv);
-#endif
-
-  if (pScreenPriv->fRestacking) return;
-
-  if (pScreenPriv) pScreenInfo = pScreenPriv->pScreenInfo;
-
-  pRLWinPriv->fRestackingNow = TRUE;
-
-  /* Show window */
-  if(!IsWindowVisible (pRLWinPriv->hWnd))
-    ShowWindow (pRLWinPriv->hWnd, SW_SHOWNOACTIVATE);
-
-  if (pRLNextWinPriv == NULL)
-    {
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("Win %08x is top\n", pRLWinPriv);
-#endif
-      pScreenPriv->widTop = wid;
-      SetWindowPos (pRLWinPriv->hWnd, HWND_TOP,
-		    0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
-    }
-  else if (winIsInternalWMRunning(pScreenInfo))
-    {
-      /* using mulwinidow wm */
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("Win %08x is not top\n", pRLWinPriv);
-#endif
-      for (hWnd = GetNextWindow (pRLWinPriv->hWnd, GW_HWNDPREV);
-	   fNeedRestack && hWnd != NULL;
-	   hWnd = GetNextWindow (hWnd, GW_HWNDPREV))
-	{
-	  GetWindowThreadProcessId (hWnd, &dwWindowProcessID);
-
-	  if ((dwWindowProcessID == dwCurrentProcessID)
-	      && GetProp (hWnd, WIN_WINDOW_PROP))
-	    {
-	      if (hWnd == pRLNextWinPriv->hWnd)
-		{
-		  /* Enable interleave X window and Windows window */
-		  if (!fFirst)
-		    {
-#if CYGMULTIWINDOW_DEBUG
-		      winDebug ("raise: Insert after Win %08x\n", pRLNextWinPriv);
-#endif
-		      SetWindowPos (pRLWinPriv->hWnd, pRLNextWinPriv->hWnd,
-				    0, 0, 0, 0,
-				    SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
-		    }
-		  else
-		    {
-#if CYGMULTIWINDOW_DEBUG
-		      winDebug ("No change\n");
-#endif
-		    }
-		  fNeedRestack = FALSE;
-		  break;
-		}
-	      if (fFirst) fFirst = FALSE;
-	    }
-	}
-
-      for (hWnd = GetNextWindow (pRLWinPriv->hWnd, GW_HWNDNEXT);
-	   fNeedRestack && hWnd != NULL;
-	   hWnd = GetNextWindow (hWnd, GW_HWNDNEXT))
-	{
-	  GetWindowThreadProcessId (hWnd, &dwWindowProcessID);
-
-	  if ((dwWindowProcessID == dwCurrentProcessID)
-	      && GetProp (hWnd, WIN_WINDOW_PROP))
-	    {
-	      if (hWnd == pRLNextWinPriv->hWnd)
-		{
-#if CYGMULTIWINDOW_DEBUG
-		  winDebug ("lower: Insert after Win %08x\n", pRLNextWinPriv);
-#endif
-		  SetWindowPos (pRLWinPriv->hWnd, pRLNextWinPriv->hWnd,
-				0, 0, 0, 0,
-				SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
-		  fNeedRestack = FALSE;
-		  break;
-		}
-	    }
-	}
-    }
-  else
-    {
-      /* using general wm like twm, wmaker etc.
-	 Interleave X window and Windows window will cause problem. */
-      SetWindowPos (pRLWinPriv->hWnd, pRLNextWinPriv->hWnd,
-		    0, 0, 0, 0,
-		    SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
-#if 0
-#endif
-    }
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMRestackFrame - done (%08x)\n", (int) pRLWinPriv);
-#endif
-
-  pRLWinPriv->fRestackingNow = FALSE;
-}
-
-void
-winMWExtWMReshapeFrame (RootlessFrameID wid, RegionPtr pShape)
-{
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
-  HRGN hRgn, hRgnWindow, hRgnClient;
-  RECT rcWindow, rcClient;
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMReshapeFrame (%08x)\n", (int) pRLWinPriv);
-#endif
-
-  hRgn = winMWExtWMCreateRgnFromRegion (pShape);
-  
-  /* Create region for non-client area */
-  GetWindowRect (pRLWinPriv->hWnd, &rcWindow);
-  GetClientRect (pRLWinPriv->hWnd, &rcClient);
-  MapWindowPoints (pRLWinPriv->hWnd, HWND_DESKTOP, (LPPOINT)&rcClient, 2);
-  OffsetRgn (hRgn, rcClient.left - rcWindow.left, rcClient.top - rcWindow.top);
-  OffsetRect (&rcClient, -rcWindow.left, -rcWindow.top);
-  OffsetRect (&rcWindow, -rcWindow.left, -rcWindow.top);
-  hRgnWindow = CreateRectRgnIndirect (&rcWindow);
-  hRgnClient = CreateRectRgnIndirect (&rcClient);
-  CombineRgn (hRgnWindow, hRgnWindow, hRgnClient, RGN_DIFF);
-  CombineRgn (hRgn, hRgnWindow, hRgn, RGN_OR);
-
-
-  SetWindowRgn (pRLWinPriv->hWnd, hRgn, TRUE);
-
-  DeleteObject (hRgnWindow);
-  DeleteObject (hRgnClient);
-}
-
-void
-winMWExtWMUnmapFrame (RootlessFrameID wid)
-{
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMUnmapFrame (%08x)\n", (int) pRLWinPriv);
-#endif
-
-  g_fNoConfigureWindow = TRUE;
-  //ShowWindow (pRLWinPriv->hWnd, SW_MINIMIZE);
-  ShowWindow (pRLWinPriv->hWnd, SW_HIDE);
-  g_fNoConfigureWindow = FALSE;
-}
-
-/*
- * Fixme: Code sharing with winshadgdi.c and other engine support
- */
-void
-winMWExtWMStartDrawing (RootlessFrameID wid, char **pixelData, int *bytesPerRow)
-{
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
-  winPrivScreenPtr	pScreenPriv = NULL;
-  winScreenInfo		*pScreenInfo = NULL;
-  ScreenPtr		pScreen = NULL;
-  DIBSECTION		dibsection;
-  Bool			fReturn = TRUE;
-  HDC			hdcNew;
-  HBITMAP		hbmpNew;
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMStartDrawing (%08x) %08x\n", (int) pRLWinPriv, pRLWinPriv->fDestroyed);
-#endif
-
-  if (!pRLWinPriv->fDestroyed)
-    {
-      pScreen = pRLWinPriv->pFrame->win->drawable.pScreen;
-      if (pScreen) pScreenPriv = winGetScreenPriv(pScreen);
-      if (pScreenPriv) pScreenInfo = pScreenPriv->pScreenInfo;
-      
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("\tpScreenPriv %08X\n", (int) pScreenPriv);
-      winDebug ("\tpScreenInfo %08X\n", (int) pScreenInfo);
-      winDebug ("\t(%d, %d)\n", (int)pRLWinPriv->pFrame->width,
-		(int) pRLWinPriv->pFrame->height);
-#endif
-      if (pRLWinPriv->hdcScreen == NULL)
-	{
-	  InitWin32RootlessEngine (pRLWinPriv);
-	}
-      
-      if (pRLWinPriv->fResized)
-	{
-          /* width * bpp must be multiple of 4 to match 32bit alignment */
-	  int stridesize;
-	  int misalignment;
-         
-	  pRLWinPriv->pbmihShadow->biWidth = pRLWinPriv->pFrame->width;
-	  pRLWinPriv->pbmihShadow->biHeight = -pRLWinPriv->pFrame->height;
- 
-	  stridesize = pRLWinPriv->pFrame->width * (pScreenInfo->dwBPP >> 3);
-	  misalignment = stridesize & 3; 
-	  if (misalignment != 0)
-	  {
-	    stridesize += 4 - misalignment;
-	    pRLWinPriv->pbmihShadow->biWidth = stridesize / (pScreenInfo->dwBPP >> 3);
-	    winDebug("\tresizing to %d (was %d)\n", 
-		    pRLWinPriv->pbmihShadow->biWidth, pRLWinPriv->pFrame->width);
-	  }
-	  
-	  hdcNew = CreateCompatibleDC (pRLWinPriv->hdcScreen);
-	  /* Create a DI shadow bitmap with a bit pointer */
-	  hbmpNew = CreateDIBSection (pRLWinPriv->hdcScreen,
-				      (BITMAPINFO *) pRLWinPriv->pbmihShadow,
-				      DIB_RGB_COLORS,
-				      (VOID**) &pRLWinPriv->pfb,
-				      NULL,
-				      0);
-	  if (hbmpNew == NULL || pRLWinPriv->pfb == NULL)
-	    {
-	      ErrorF ("winMWExtWMStartDrawing - CreateDIBSection failed\n");
-	      //return FALSE;
-	    }
-	  else
-	    {
-#if CYGMULTIWINDOW_DEBUG
-	      winDebug ("winMWExtWMStartDrawing - Shadow buffer allocated\n");
-#endif
-	    }
-	  
-	  /* Get information about the bitmap that was allocated */
-	  GetObject (hbmpNew, sizeof (dibsection), &dibsection);
-	  
-#if CYGMULTIWINDOW_DEBUG
-	  /* Print information about bitmap allocated */
-	  winDebug ("winMWExtWMStartDrawing - Dibsection width: %d height: %d "
-		    "depth: %d size image: %d\n",
-		    (unsigned int)dibsection.dsBmih.biWidth,
-		    (unsigned int)dibsection.dsBmih.biHeight,
-		    (unsigned int)dibsection.dsBmih.biBitCount,
-		    (unsigned int)dibsection.dsBmih.biSizeImage);
-#endif
-	  
-	  /* Select the shadow bitmap into the shadow DC */
-	  SelectObject (hdcNew, hbmpNew);
-	  
-#if CYGMULTIWINDOW_DEBUG
-	  winDebug ("winMWExtWMStartDrawing - Attempting a shadow blit\n");
-#endif
-	  
-	  /* Blit from the old shadow to the new shadow */
-	  fReturn = BitBlt (hdcNew,
-			    0, 0,
-			    pRLWinPriv->pFrame->width, pRLWinPriv->pFrame->height,
-			    pRLWinPriv->hdcShadow,
-			    0, 0,
-			    SRCCOPY);
-	  if (fReturn)
-	    {
-#if CYGMULTIWINDOW_DEBUG
-	      winDebug ("winMWExtWMStartDrawing - Shadow blit success\n");
-#endif
-	    }
-	  else
-	    {
-	      ErrorF ("winMWExtWMStartDrawing - Shadow blit failure\n");
-	    }
-	  
-	  /* Look for height weirdness */
-	  if (dibsection.dsBmih.biHeight < 0)
-	    {
-	      /* FIXME: Figure out why biHeight is sometimes negative */
-	      ErrorF ("winMWExtWMStartDrawing - WEIRDNESS - "
-                  "biHeight still negative: %d\n", 
-                  (int) dibsection.dsBmih.biHeight);
-	      ErrorF ("winMWExtWMStartDrawing - WEIRDNESS - "
-                  "Flipping biHeight sign\n");
-	      dibsection.dsBmih.biHeight = -dibsection.dsBmih.biHeight;
-	    }
-	  
-	  pRLWinPriv->dwWidthBytes = dibsection.dsBm.bmWidthBytes;
-	  
-#if CYGMULTIWINDOW_DEBUG
-	  winDebug ("winMWExtWMStartDrawing - bytesPerRow: %d\n",
-		    (unsigned int)dibsection.dsBm.bmWidthBytes);
-#endif
-	  
-	  /* Free the old shadow bitmap */
-	  DeleteObject (pRLWinPriv->hdcShadow);
-	  DeleteObject (pRLWinPriv->hbmpShadow);
-	  
-	  pRLWinPriv->hdcShadow = hdcNew;
-	  pRLWinPriv->hbmpShadow = hbmpNew;
-	  
-	  pRLWinPriv->fResized = FALSE;
-#if CYGMULTIWINDOW_DEBUG && FALSE
-	  winDebug ("winMWExtWMStartDrawing - 0x%08x %d\n",
-		(unsigned int)pRLWinPriv->pfb, 
-		(unsigned int)dibsection.dsBm.bmWidthBytes);
-#endif
-	}
-    }
-  else
-    {
-      ErrorF ("winMWExtWMStartDrawing - Already window was destroyed \n"); 
-    }
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMStartDrawing - done (0x%08x) 0x%08x %d\n",
-	    (int) pRLWinPriv,
-	    (unsigned int)pRLWinPriv->pfb, (unsigned int)pRLWinPriv->dwWidthBytes);
-#endif
-  *pixelData = pRLWinPriv->pfb;
-  *bytesPerRow = pRLWinPriv->dwWidthBytes;
-}
-
-void
-winMWExtWMStopDrawing (RootlessFrameID wid, Bool fFlush)
-{
-#if 0
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
-  BLENDFUNCTION bfBlend;
-  SIZE szWin;
-  POINT ptSrc;
-#if CYGMULTIWINDOW_DEBUG || TRUE
-  winDebug ("winMWExtWMStopDrawing (%08x)\n", pRLWinPriv);
-#endif
-  szWin.cx = pRLWinPriv->dwWidth;
-  szWin.cy = pRLWinPriv->dwHeight;
-  ptSrc.x = 0;
-  ptSrc.y = 0;
-  bfBlend.BlendOp = AC_SRC_OVER;
-  bfBlend.BlendFlags = 0;
-  bfBlend.SourceConstantAlpha = 255;
-  bfBlend.AlphaFormat = AC_SRC_ALPHA;
-
-  if (!UpdateLayeredWindow (pRLWinPriv->hWnd,
-			    NULL, NULL, &szWin,
-			    pRLWinPriv->hdcShadow, &ptSrc,
-			    0, &bfBlend, ULW_ALPHA))
-    {
-      ErrorF ("winMWExtWMStopDrawing - UpdateLayeredWindow failed\n");
-    }
-#endif
-}
-
-void
-winMWExtWMUpdateRegion (RootlessFrameID wid, RegionPtr pDamage)
-{
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
-#if 0
-  BLENDFUNCTION bfBlend;
-  SIZE szWin;
-  POINT ptSrc;
-#endif
-#if CYGMULTIWINDOW_DEBUG && 0
-  winDebug ("winMWExtWMUpdateRegion (%08x)\n", pRLWinPriv);
-#endif
-#if 0
-  szWin.cx = pRLWinPriv->dwWidth;
-  szWin.cy = pRLWinPriv->dwHeight;
-  ptSrc.x = 0;
-  ptSrc.y = 0;
-  bfBlend.BlendOp = AC_SRC_OVER;
-  bfBlend.BlendFlags = 0;
-  bfBlend.SourceConstantAlpha = 255;
-  bfBlend.AlphaFormat = AC_SRC_ALPHA;
-
-  if (!UpdateLayeredWindow (pRLWinPriv->hWnd,
-			    NULL, NULL, &szWin,
-			    pRLWinPriv->hdcShadow, &ptSrc,
-			    0, &bfBlend, ULW_ALPHA))
-    {
-      LPVOID lpMsgBuf;
-      
-      /* Display a fancy error message */
-      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | 
-		     FORMAT_MESSAGE_FROM_SYSTEM | 
-		     FORMAT_MESSAGE_IGNORE_INSERTS,
-		     NULL,
-		     GetLastError (),
-		     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-		     (LPTSTR) &lpMsgBuf,
-		     0, NULL);
-      
-      ErrorF ("winMWExtWMUpdateRegion - UpdateLayeredWindow failed: %s\n",
-	      (LPSTR)lpMsgBuf);
-      LocalFree (lpMsgBuf);
-    }
-#endif
-  if (!g_fNoConfigureWindow) UpdateWindow (pRLWinPriv->hWnd);
-}
-
-void
-winMWExtWMDamageRects (RootlessFrameID wid, int nCount, const BoxRec *pRects,
-			     int shift_x, int shift_y)
-{
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
-  const BoxRec *pEnd;
-#if CYGMULTIWINDOW_DEBUG && 0
-  winDebug ("winMWExtWMDamageRects (%08x, %d, %08x, %d, %d)\n",
-	    pRLWinPriv, nCount, pRects, shift_x, shift_y);
-#endif
-
-  for (pEnd = pRects + nCount; pRects < pEnd; pRects++) {
-        RECT rcDmg;
-        rcDmg.left = pRects->x1 + shift_x;
-        rcDmg.top = pRects->y1 + shift_y;
-        rcDmg.right = pRects->x2 + shift_x;
-        rcDmg.bottom = pRects->y2 + shift_y;
-
-	InvalidateRect (pRLWinPriv->hWnd, &rcDmg, FALSE);
-    }
-}
-
-void
-winMWExtWMRootlessSwitchWindow (RootlessWindowPtr pFrame, WindowPtr oldWin)
-{
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) pFrame->wid;
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMRootlessSwitchWindow (%08x) %08x\n",
-	    (int) pRLWinPriv, (int) pRLWinPriv->hWnd);
-#endif
-  pRLWinPriv->pFrame = pFrame;
-  pRLWinPriv->fResized = TRUE;
-
-  /* Set the window extended style flags */
-  SetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE, WS_EX_TOOLWINDOW);
-
-  /* Set the window standard style flags */
-  SetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE,
-		    WS_POPUP | WS_CLIPCHILDREN);
-
-  DeleteProperty (serverClient, oldWin, AtmWindowsWmNativeHwnd ());
-  winMWExtWMSetNativeProperty (pFrame);
-#if CYGMULTIWINDOW_DEBUG
-#if 0
- {
-   WindowPtr		pWin2 = NULL;
-   win32RootlessWindowPtr pRLWinPriv2 = NULL;
-
-   /* Check if the Windows window property for our X window pointer is valid */
-   if ((pWin2 = (WindowPtr)GetProp (pRLWinPriv->hWnd, WIN_WINDOW_PROP)) != NULL)
-     {
-       pRLWinPriv2 = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin2, FALSE);
-     }
-   winDebug ("winMWExtWMSwitchFrame2 (%08x) %08x\n",
-	   pRLWinPriv2, pRLWinPriv2->hWnd);
-   if (pRLWinPriv != pRLWinPriv2 || pRLWinPriv->hWnd != pRLWinPriv2->hWnd)
-     {
-       winDebug ("Error param missmatch\n");
-     }
- }
-#endif
-#endif
-}
-
-void
-winMWExtWMCopyBytes (unsigned int width, unsigned int height,
-			   const void *src, unsigned int srcRowBytes,
-			   void *dst, unsigned int dstRowBytes)
-{
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMCopyBytes - Not implemented\n");
-#endif
-}
-
-void
-winMWExtWMFillBytes (unsigned int width, unsigned int height, unsigned int value,
-			   void *dst, unsigned int dstRowBytes)
-{
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMFillBytes - Not implemented\n");
-#endif
-}
-
-int
-winMWExtWMCompositePixels (unsigned int width, unsigned int height, unsigned int function,
-				 void *src[2], unsigned int srcRowBytes[2],
-				 void *mask, unsigned int maskRowBytes,
-				 void *dst[2], unsigned int dstRowBytes[2])
-{
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMCompositePixels - Not implemented\n");
-#endif
-  return 0;
-}
-
-
-void
-winMWExtWMCopyWindow (RootlessFrameID wid, int nDstRects, const BoxRec *pDstRects,
-			    int nDx, int nDy)
-{
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
-  const BoxRec *pEnd;
-  RECT rcDmg;
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMCopyWindow (%08x, %d, %08x, %d, %d)\n",
-	  (int) pRLWinPriv, nDstRects, (int) pDstRects, nDx, nDy);
-#endif
-
-  for (pEnd = pDstRects + nDstRects; pDstRects < pEnd; pDstRects++)
-    {
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("BitBlt (%d, %d, %d, %d) (%d, %d)\n",
-	      pDstRects->x1, pDstRects->y1,
-	      pDstRects->x2 - pDstRects->x1,
-	      pDstRects->y2 - pDstRects->y1,
-	      pDstRects->x1 + nDx,
-	      pDstRects->y1 + nDy);
-#endif
-
-      if (!BitBlt (pRLWinPriv->hdcShadow,
-		   pDstRects->x1, pDstRects->y1,
-		   pDstRects->x2 - pDstRects->x1,
-		   pDstRects->y2 - pDstRects->y1,
-		   pRLWinPriv->hdcShadow,
-		   pDstRects->x1 + nDx,  pDstRects->y1 + nDy,
-		   SRCCOPY))
-	{
-	  ErrorF ("winMWExtWMCopyWindow - BitBlt failed.\n");
-	}
-      
-      rcDmg.left = pDstRects->x1;
-      rcDmg.top = pDstRects->y1;
-      rcDmg.right = pDstRects->x2;
-      rcDmg.bottom = pDstRects->y2;
-      
-      InvalidateRect (pRLWinPriv->hWnd, &rcDmg, FALSE);
-    }
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMCopyWindow - done\n");
-#endif
-}
-
-
-/*
- * winMWExtWMSetNativeProperty
- */
-
-static void
-winMWExtWMSetNativeProperty (RootlessWindowPtr pFrame)
-{
-  win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) pFrame->wid;
-  long lData;
-
-  /* FIXME: move this to WindowsWM extension */
-
-  lData = (long) pRLWinPriv->hWnd;
-  dixChangeWindowProperty(serverClient, pFrame->win, AtmWindowsWmNativeHwnd(),
-			  XA_INTEGER, 32, PropModeReplace, 1, &lData, TRUE);
-}
diff --git a/hw/xwin/winwin32rootlesswindow.c b/hw/xwin/winwin32rootlesswindow.c
deleted file mode 100755
index dedcd7a..0000000
--- a/hw/xwin/winwin32rootlesswindow.c
+++ /dev/null
@@ -1,476 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Kensuke Matsuzaki
- *		Earle F. Philhower, III
- *		Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winprefs.h"
-
-#if 0
-/*
- * winMWExtWMReorderWindows
- */
-
-void
-winMWExtWMReorderWindows (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  HWND hwnd = NULL;
-  win32RootlessWindowPtr pRLWin = NULL;
-  win32RootlessWindowPtr pRLWinSib = NULL;
-  DWORD dwCurrentProcessID = GetCurrentProcessId ();
-  DWORD dwWindowProcessID = 0;
-  XID vlist[2];
-
-#if CYGMULTIWINDOW_DEBUG && FALSE
-  winDebug ("winMWExtWMReorderWindows\n");
-#endif
-
-  pScreenPriv->fRestacking = TRUE;
-
-  if (pScreenPriv->fWindowOrderChanged)
-    {
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMReorderWindows - Need to restack\n");
-#endif
-      hwnd = GetTopWindow (NULL);
-
-      while (hwnd)
-	{
-	  GetWindowThreadProcessId (hwnd, &dwWindowProcessID);
-
-	  if ((dwWindowProcessID == dwCurrentProcessID)
-	      && GetProp (hwnd, WIN_WINDOW_PROP))
-	    {
-	      pRLWinSib = pRLWin;
-	      pRLWin = (win32RootlessWindowPtr)GetProp (hwnd, WIN_WINDOW_PROP);
-	      
-	      if (pRLWinSib)
-		{
-		  vlist[0] = pRLWinSib->pFrame->win->drawable.id;
-		  vlist[1] = Below;
-
-		  ConfigureWindow (pRLWin->pFrame->win, CWSibling | CWStackMode,
-				   vlist, wClient(pRLWin->pFrame->win));
-		}
-	      else
-		{
-		  /* 1st window - raise to the top */
-		  vlist[0] = Above;
-
-		  ConfigureWindow (pRLWin->pFrame->win, CWStackMode,
-				   vlist, wClient(pRLWin->pFrame->win));
-		}
-	    }
-	  hwnd = GetNextWindow (hwnd, GW_HWNDNEXT);
-	}
-    }
-
-  pScreenPriv->fRestacking = FALSE;
-  pScreenPriv->fWindowOrderChanged = FALSE;
-}
-#endif
-
-
-/*
- * winMWExtWMMoveXWindow
- */
-
-void
-winMWExtWMMoveXWindow (WindowPtr pWin, int x, int y)
-{
-  CARD32 *vlist = malloc(sizeof(CARD32)*2);
-
-  vlist[0] = x;
-  vlist[1] = y;
-  ConfigureWindow (pWin, CWX | CWY, vlist, wClient(pWin));
-  free(vlist);
-}
-
-
-/*
- * winMWExtWMResizeXWindow
- */
-
-void
-winMWExtWMResizeXWindow (WindowPtr pWin, int w, int h)
-{
-  CARD32 *vlist = malloc(sizeof(CARD32)*2);
-
-  vlist[0] = w;
-  vlist[1] = h;
-  ConfigureWindow (pWin, CWWidth | CWHeight, vlist, wClient(pWin));
-  free(vlist);
-}
-
-
-/*
- * winMWExtWMMoveResizeXWindow
- */
-
-void
-winMWExtWMMoveResizeXWindow (WindowPtr pWin, int x, int y, int w, int h)
-{
-  CARD32 *vlist = malloc(sizeof(long)*4);
-
-  vlist[0] = x;
-  vlist[1] = y;
-  vlist[2] = w;
-  vlist[3] = h;
-
-  ConfigureWindow (pWin, CWX | CWY | CWWidth | CWHeight, vlist, wClient(pWin));
-  free(vlist);
-}
-
-
-/*
- * winMWExtWMUpdateIcon
- * Change the Windows window icon
- */
-
-void
-winMWExtWMUpdateIcon (Window id)
-{
-  WindowPtr		pWin;
-  HICON			hIcon, hiconOld;
-
-  pWin = (WindowPtr) LookupIDByType (id, RT_WINDOW);
-  hIcon = (HICON)winOverrideIcon ((unsigned long)pWin);
-
-  if (!hIcon)
-    hIcon = winXIconToHICON (pWin, GetSystemMetrics(SM_CXICON));
-
-  if (hIcon)
-    {
-      win32RootlessWindowPtr pRLWinPriv
-	= (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, FALSE);
-
-      if (pRLWinPriv->hWnd)
-	{
-	  hiconOld = (HICON) SetClassLong (pRLWinPriv->hWnd,
-					   GCL_HICON,
-					   (int) hIcon);
-	  
-          winDestroyIcon(hiconOld);
-	}
-    }
-}
-
-
-/*
- * winMWExtWMDecorateWindow - Update window style. Called by EnumWindows.
- */
-
-wBOOL CALLBACK
-winMWExtWMDecorateWindow (HWND hwnd, LPARAM lParam)
-{
-  win32RootlessWindowPtr pRLWinPriv = NULL;
-  ScreenPtr		pScreen = NULL;
-  winPrivScreenPtr	pScreenPriv = NULL;
-  winScreenInfo		*pScreenInfo = NULL;
-
-  /* Check if the Windows window property for our X window pointer is valid */
-  if ((pRLWinPriv = (win32RootlessWindowPtr)GetProp (hwnd, WIN_WINDOW_PROP)) != NULL)
-    {
-      pScreen				= pRLWinPriv->pFrame->win->drawable.pScreen;
-      if (pScreen) pScreenPriv		= winGetScreenPriv(pScreen);
-      if (pScreenPriv) pScreenInfo	= pScreenPriv->pScreenInfo;
-      if (pRLWinPriv && pScreenInfo) winMWExtWMUpdateWindowDecoration (pRLWinPriv, pScreenInfo);
-    }
-  return TRUE;
-}
-
-
-/*
- * winMWExtWMUpdateWindowDecoration - Update window style.
- */
-
-void
-winMWExtWMUpdateWindowDecoration (win32RootlessWindowPtr pRLWinPriv,
-				  winScreenInfoPtr pScreenInfo)
-{
-  Bool		fDecorate = FALSE;
-  DWORD		dwExStyle = 0;
-  DWORD		dwStyle = 0;
-  WINDOWPLACEMENT wndPlace;
-  UINT		showCmd = 0;
-
-  wndPlace.length = sizeof (WINDOWPLACEMENT);
-
-  /* Get current window placement */
-  GetWindowPlacement (pRLWinPriv->hWnd, &wndPlace);
-
-  if (winIsInternalWMRunning(pScreenInfo))
-    {
-      if (!pRLWinPriv->pFrame->win->overrideRedirect)
-	fDecorate = TRUE;
-    }
-#if 0
-  if (wndPlace.showCmd == SW_HIDE)
-    return;//showCmd = SWP_HIDEWINDOW;
-  else
-    showCmd = SWP_SHOWWINDOW;
-#else
-  if (wndPlace.showCmd == SW_HIDE)
-    return;
-
-  if (IsWindowVisible (pRLWinPriv->hWnd))
-    showCmd = SWP_SHOWWINDOW;
-#endif
-
-  showCmd |= SWP_NOMOVE | SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOZORDER;
-
-  winDebug ("winMWExtWMUpdateWindowDecoration %08x %s\n",
-	    (int)pRLWinPriv, fDecorate?"Decorate":"Bare");
-
-  /* Get the standard and extended window style information */
-  dwExStyle = GetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE);
-  dwStyle = GetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE);
-
-  if (fDecorate)
-    {
-      RECT		rcNew;
-      int		iDx, iDy;
-      winWMMessageRec	wmMsg;
-      winScreenPriv(pScreenInfo->pScreen);
-
-      /* */
-      if (!(dwExStyle & WS_EX_APPWINDOW))
-	{
-	  winDebug ("\tBare=>Decorate\n");
-	  /* Setup a rectangle with the X window position and size */
-	  SetRect (&rcNew,
-		   pRLWinPriv->pFrame->x,
-		   pRLWinPriv->pFrame->y,
-		   pRLWinPriv->pFrame->x + pRLWinPriv->pFrame->width,
-		   pRLWinPriv->pFrame->y + pRLWinPriv->pFrame->height);
-
-#ifdef CYGMULTIWINDOW_DEBUG
-          winDebug("\tWindow extend {%d, %d, %d, %d}, {%d, %d}\n", 
-              rcNew.left, rcNew.top, rcNew.right, rcNew.bottom,
-              rcNew.right - rcNew.left, rcNew.bottom - rcNew.top);
-#endif
-	  /* */
-	  AdjustWindowRectEx (&rcNew,
-			      WS_POPUP | WS_SIZEBOX | WS_OVERLAPPEDWINDOW,
-			      FALSE,
-			      WS_EX_APPWINDOW);
-
-#ifdef CYGMULTIWINDOW_DEBUG
-          winDebug("\tAdjusted {%d, %d, %d, %d}, {%d, %d}\n", 
-              rcNew.left, rcNew.top, rcNew.right, rcNew.bottom,
-              rcNew.right - rcNew.left, rcNew.bottom - rcNew.top);
-#endif
-	  /* Calculate position deltas */
-	  iDx = pRLWinPriv->pFrame->x - rcNew.left;
-	  iDy = pRLWinPriv->pFrame->y - rcNew.top;
-
-	  /* Calculate new rectangle */
-	  rcNew.left += iDx;
-	  rcNew.right += iDx;
-	  rcNew.top += iDy;
-	  rcNew.bottom += iDy;
-
-	  /* Set the window extended style flags */
-	  SetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE, WS_EX_APPWINDOW);
-
-	  /* Set the window standard style flags */
-	  SetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE,
-			    WS_POPUP | WS_SIZEBOX | WS_OVERLAPPEDWINDOW);
-
-#ifdef CYGMULTIWINDOW_DEBUG
-          winDebug("\tWindowStyle: %08x %08x\n",
-              WS_POPUP | WS_SIZEBOX | WS_OVERLAPPEDWINDOW,
-              WS_EX_APPWINDOW);
-#endif
-	  /* Position the Windows window */
-#ifdef CYGMULTIWINDOW_DEBUG
-          winDebug("\tMoved {%d, %d, %d, %d}, {%d, %d}\n", 
-              rcNew.left, rcNew.top, rcNew.right, rcNew.bottom,
-              rcNew.right - rcNew.left, rcNew.bottom - rcNew.top);
-#endif
-	  SetWindowPos (pRLWinPriv->hWnd, NULL,
-			rcNew.left, rcNew.top,
-			rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
-			showCmd);
-            
-
-	  wmMsg.hwndWindow = pRLWinPriv->hWnd;
-	  wmMsg.iWindow	= (Window)pRLWinPriv->pFrame->win->drawable.id;
-	  wmMsg.msg = WM_WM_NAME_EVENT;
-	  winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
-
-	  winMWExtWMReshapeFrame ((RootlessFrameID)pRLWinPriv ,
-				  wBoundingShape(pRLWinPriv->pFrame->win));
-	}
-    }
-  else
-    {
-      RECT		rcNew;
-
-      /* */
-      if (dwExStyle & WS_EX_APPWINDOW)
-	{
-	  winDebug ("\tDecorate=>Bare\n");
-	  /* Setup a rectangle with the X window position and size */
-	  SetRect (&rcNew,
-		   pRLWinPriv->pFrame->x,
-		   pRLWinPriv->pFrame->y,
-		   pRLWinPriv->pFrame->x + pRLWinPriv->pFrame->width,
-		   pRLWinPriv->pFrame->y + pRLWinPriv->pFrame->height);
-#if 0
-	  /* */
-	  AdjustWindowRectEx (&rcNew,
-			      WS_POPUP | WS_CLIPCHILDREN,
-			      FALSE,
-			      WS_EX_TOOLWINDOW);
-
-	  /* Calculate position deltas */
-	  iDx = pRLWinPriv->pFrame->x - rcNew.left;
-	  iDy = pRLWinPriv->pFrame->y - rcNew.top;
-
-	  /* Calculate new rectangle */
-	  rcNew.left += iDx;
-	  rcNew.right += iDx;
-	  rcNew.top += iDy;
-	  rcNew.bottom += iDy;
-#endif
-
-	  /* Hide window temporary to remove from taskbar. */
-	  ShowWindow( pRLWinPriv->hWnd, SW_HIDE );
-
-	  /* Set the window extended style flags */
-	  SetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE, WS_EX_TOOLWINDOW);
-
-	  /* Set the window standard style flags */
-	  SetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE,
-			    WS_POPUP | WS_CLIPCHILDREN);
-
-	  /* Position the Windows window */
-	  SetWindowPos (pRLWinPriv->hWnd, NULL,
-			rcNew.left, rcNew.top,
-			rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
-			showCmd);
-
-	  winMWExtWMReshapeFrame ((RootlessFrameID)pRLWinPriv ,
-				  wBoundingShape(pRLWinPriv->pFrame->win));
-	}
-    }
-}
-
-
-/*
- * winIsInternalWMRunning (winScreenInfoPtr pScreenInfo)
- */
-Bool
-winIsInternalWMRunning (winScreenInfoPtr pScreenInfo)
-{
-  return pScreenInfo->fInternalWM && !pScreenInfo->fAnotherWMRunning;
-}
-
-
-/*
- * winMWExtWMRestackWindows
- */
-
-void
-winMWExtWMRestackWindows (ScreenPtr pScreen)
-{
-  winScreenPriv(pScreen);
-  WindowPtr pRoot = WindowTable[pScreen->myNum];
-  WindowPtr pWin = NULL;
-  WindowPtr pWinPrev = NULL;
-  win32RootlessWindowPtr pRLWin = NULL;
-  win32RootlessWindowPtr pRLWinPrev = NULL;
-  int  nWindow = 0;
-  HDWP hWinPosInfo = NULL;
-
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMRestackWindows\n");
-#endif
-
-  pScreenPriv->fRestacking = TRUE;
-
-  if (pRoot != NULL)
-    {
-      for (pWin = pRoot->firstChild; pWin; pWin = pWin->nextSib)
-	nWindow ++;
-
-      hWinPosInfo = BeginDeferWindowPos(nWindow);
-
-      for (pWin = pRoot->firstChild; pWin; pWin = pWin->nextSib)
-	{
-	  if (pWin->realized)
-	    {
-	      UINT uFlags;
-
-	      pRLWin = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, FALSE);
-	      if (pRLWin == NULL) continue;
-
-	      if (pWinPrev)
-		pRLWinPrev = (win32RootlessWindowPtr) RootlessFrameForWindow (pWinPrev, FALSE);
-
-	      uFlags = SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW;
-	      if (pRLWinPrev != NULL) uFlags |= SWP_NOACTIVATE;
-
-#if CYGMULTIWINDOW_DEBUG
-	      winDebug ("winMWExtWMRestackWindows - DeferWindowPos (%08x, %08x)\n",
-			pRLWin->hWnd,
-			pRLWinPrev ? pRLWinPrev->hWnd : HWND_TOP);
-#endif
-	      hWinPosInfo = DeferWindowPos (hWinPosInfo, pRLWin->hWnd,
-					    pRLWinPrev ? pRLWinPrev->hWnd : HWND_TOP,
-					    0, 0, 0, 0,
-					    uFlags);
-	      if (hWinPosInfo == NULL)
-		{
-		  ErrorF ("winMWExtWMRestackWindows - DeferWindowPos () failed: %d\n",
-			  (int) GetLastError ());
-		  return;
-		}
-	      pWinPrev = pWin;
-	    }
-	}
-      if (!EndDeferWindowPos (hWinPosInfo))
-	{
-	  ErrorF ("winMWExtWMRestackWindows - EndDeferWindowPos () failed: %d\n",
-		  (int) GetLastError ());
-	  return;
-	}
-    }
-
-#if CYGMULTIWINDOW_DEBUG
-  winDebug ("winMWExtWMRestackWindows - done\n");
-#endif
-  pScreenPriv->fRestacking = FALSE;
-}
diff --git a/hw/xwin/winwin32rootlesswndproc.c b/hw/xwin/winwin32rootlesswndproc.c
deleted file mode 100755
index 859aafd..0000000
--- a/hw/xwin/winwin32rootlesswndproc.c
+++ /dev/null
@@ -1,1325 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Kensuke Matsuzaki
- *		Earle F. Philhower, III
- *		Harold L Hunt II
- */
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include <winuser.h>
-#define _WINDOWSWM_SERVER_
-#include "windowswmstr.h"
-#include "dixevents.h"
-#include "propertyst.h"
-#include <X11/Xatom.h>
-#include "winmultiwindowclass.h"
-#include "winmsg.h"
-#include "inputstr.h"
-
-
-/*
- * Constant defines
- */
-
-#define MOUSE_POLLING_INTERVAL		500
-#define MOUSE_ACTIVATE_DEFAULT		TRUE
-#define RAISE_ON_CLICK_DEFAULT		FALSE
-
-
-/*
- * Global variables
- */
-
-extern Bool			g_fNoConfigureWindow;
-extern Bool			g_fSoftwareCursor;
-
-
-/*
- * Local globals
- */
-
-static UINT_PTR		g_uipMousePollingTimerID = 0;
-
-
-/*
- * Local function
- */
-
-DEFINE_ATOM_HELPER(AtmWindowsWmRaiseOnClick, WINDOWSWM_RAISE_ON_CLICK)
-DEFINE_ATOM_HELPER(AtmWindowsWMMouseActivate, WINDOWSWM_MOUSE_ACTIVATE)
-/* DEFINE_ATOM_HELPER(AtmWindowsWMClientWindow, WINDOWSWM_CLIENT_WINDOW) */
-
-/*
- * ConstrainSize - Taken from TWM sources - Respects hints for sizing
- */
-#define makemult(a,b) ((b==1) ? (a) : (((int)((a)/(b))) * (b)) )
-static void
-ConstrainSize (WinXSizeHints hints, int *widthp, int *heightp)
-{
-  int minWidth, minHeight, maxWidth, maxHeight, xinc, yinc, delta;
-  int baseWidth, baseHeight;
-  int dwidth = *widthp, dheight = *heightp;
-  
-  if (hints.flags & PMinSize)
-    {
-      minWidth = hints.min_width;
-      minHeight = hints.min_height;
-    }
-  else if (hints.flags & PBaseSize)
-    {
-      minWidth = hints.base_width;
-      minHeight = hints.base_height;
-    }
-  else
-    minWidth = minHeight = 1;
-  
-  if (hints.flags & PBaseSize)
-    {
-      baseWidth = hints.base_width;
-      baseHeight = hints.base_height;
-    } 
-  else if (hints.flags & PMinSize)
-    {
-      baseWidth = hints.min_width;
-      baseHeight = hints.min_height;
-    }
-  else
-    baseWidth = baseHeight = 0;
-
-  if (hints.flags & PMaxSize)
-    {
-      maxWidth = hints.max_width;
-      maxHeight = hints.max_height;
-    }
-  else
-    {
-      maxWidth = MAXINT;
-      maxHeight = MAXINT;
-    }
-
-  if (hints.flags & PResizeInc)
-    {
-      xinc = hints.width_inc;
-      yinc = hints.height_inc;
-    }
-  else
-    xinc = yinc = 1;
-
-  /*
-   * First, clamp to min and max values
-   */
-  if (dwidth < minWidth)
-    dwidth = minWidth;
-  if (dheight < minHeight)
-    dheight = minHeight;
-
-  if (dwidth > maxWidth)
-    dwidth = maxWidth;
-  if (dheight > maxHeight)
-    dheight = maxHeight;
-
-  /*
-   * Second, fit to base + N * inc
-   */
-  dwidth = ((dwidth - baseWidth) / xinc * xinc) + baseWidth;
-  dheight = ((dheight - baseHeight) / yinc * yinc) + baseHeight;
-  
-  /*
-   * Third, adjust for aspect ratio
-   */
-
-  /*
-   * The math looks like this:
-   *
-   * minAspectX    dwidth     maxAspectX
-   * ---------- <= ------- <= ----------
-   * minAspectY    dheight    maxAspectY
-   *
-   * If that is multiplied out, then the width and height are
-   * invalid in the following situations:
-   *
-   * minAspectX * dheight > minAspectY * dwidth
-   * maxAspectX * dheight < maxAspectY * dwidth
-   * 
-   */
-  
-  if (hints.flags & PAspect)
-    {
-      if (hints.min_aspect.x * dheight > hints.min_aspect.y * dwidth)
-        {
-	  delta = makemult(hints.min_aspect.x * dheight / hints.min_aspect.y - dwidth, xinc);
-	  if (dwidth + delta <= maxWidth)
-	    dwidth += delta;
-	  else
-            {
-	      delta = makemult(dheight - dwidth*hints.min_aspect.y/hints.min_aspect.x, yinc);
-	      if (dheight - delta >= minHeight)
-		dheight -= delta;
-            }
-        }
-      
-      if (hints.max_aspect.x * dheight < hints.max_aspect.y * dwidth)
-        {
-	  delta = makemult(dwidth * hints.max_aspect.y / hints.max_aspect.x - dheight, yinc);
-	  if (dheight + delta <= maxHeight)
-	    dheight += delta;
-	  else
-            {
-	      delta = makemult(dwidth - hints.max_aspect.x*dheight/hints.max_aspect.y, xinc);
-	      if (dwidth - delta >= minWidth)
-		dwidth -= delta;
-            }
-        }
-    }
-  
-  /* Return computed values */
-  *widthp = dwidth;
-  *heightp = dheight;
-}
-#undef makemult
-
-
-
-/*
- * ValidateSizing - Ensures size request respects hints
- */
-static int
-ValidateSizing (HWND hwnd, WindowPtr pWin,
-		WPARAM wParam, LPARAM lParam)
-{
-  WinXSizeHints sizeHints;
-  RECT *rect;
-  int iWidth, iHeight, iTopBorder;
-  POINT pt;
-
-  /* Invalid input checking */
-  if (pWin==NULL || lParam==0)
-    {
-      ErrorF ("Invalid input checking\n");
-      return FALSE;
-    }
-
-  /* No size hints, no checking */
-  if (!winMultiWindowGetWMNormalHints (pWin, &sizeHints))
-    {
-      ErrorF ("No size hints, no checking\n");
-      return FALSE;
-    }
-  
-  /* Avoid divide-by-zero */
-  if (sizeHints.flags & PResizeInc)
-    {
-      if (sizeHints.width_inc == 0) sizeHints.width_inc = 1;
-      if (sizeHints.height_inc == 0) sizeHints.height_inc = 1;
-    }
-  
-  rect = (RECT*)lParam;
-  
-  iWidth = rect->right - rect->left;
-  iHeight = rect->bottom - rect->top;
-
-  /* Get title bar height, there must be an easier way?! */
-  pt.x = pt.y = 0;
-  ClientToScreen(hwnd, &pt);
-  iTopBorder = pt.y - rect->top;
-  
-  /* Now remove size of any borders */
-  iWidth -= 2 * GetSystemMetrics(SM_CXSIZEFRAME);
-  iHeight -= GetSystemMetrics(SM_CYSIZEFRAME) + iTopBorder;
-
-  /* Constrain the size to legal values */
-  ConstrainSize (sizeHints, &iWidth, &iHeight);
-
-  /* Add back the borders */
-  iWidth += 2 * GetSystemMetrics(SM_CXSIZEFRAME);
-  iHeight += GetSystemMetrics(SM_CYSIZEFRAME) + iTopBorder;
-
-  /* Adjust size according to where we're dragging from */
-  switch(wParam) {
-  case WMSZ_TOP:
-  case WMSZ_TOPRIGHT:
-  case WMSZ_BOTTOM:
-  case WMSZ_BOTTOMRIGHT:
-  case WMSZ_RIGHT:
-    rect->right = rect->left + iWidth;
-    break;
-  default:
-    rect->left = rect->right - iWidth;
-    break;
-  }
-  switch(wParam) {
-  case WMSZ_BOTTOM:
-  case WMSZ_BOTTOMRIGHT:
-  case WMSZ_BOTTOMLEFT:
-  case WMSZ_RIGHT:
-  case WMSZ_LEFT:
-    rect->bottom = rect->top + iHeight;
-    break;
-  default:
-    rect->top = rect->bottom - iHeight;
-    break;
-  }
-  return TRUE;
-}
-
-
-/*
- * IsRaiseOnClick
- */
-
-static Bool
-IsRaiseOnClick (WindowPtr pWin)
-{
-
-  struct _Window	*pwin;
-  struct _Property	*prop;  
-  WindowPtr		pRoot = GetCurrentRootWindow ();
-
-  if (!pWin)
-    {
-      ErrorF ("IsRaiseOnClick - no prop use default value:%d\n",
-	      RAISE_ON_CLICK_DEFAULT);
-      return RAISE_ON_CLICK_DEFAULT;
-    } 
-
-  pwin = (struct _Window*) pWin;
-
-  if (pwin->optional)
-    prop = (struct _Property *) pwin->optional->userProps;
-  else
-    prop = NULL;
-
-  while (prop)
-    {
-      if (prop->propertyName == AtmWindowsWmRaiseOnClick ()
-	  && prop->type == XA_INTEGER
-	  && prop->format == 32)
-	{
-	  return *(int*)prop->data;
-	}
-      else
-	prop = prop->next;
-    }
-
-  if (pWin != pRoot)
-    {
-      return IsRaiseOnClick (pRoot);
-    }
-  else
-    {
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("IsRaiseOnClick - no prop use default value:%d\n",
-		RAISE_ON_CLICK_DEFAULT);
-#endif
-      return RAISE_ON_CLICK_DEFAULT;
-    }
-}
-
-
-/*
- * IsMouseActive
- */
-
-static Bool
-IsMouseActive (WindowPtr pWin)
-{
-
-  struct _Window	*pwin;
-  struct _Property	*prop;
-  WindowPtr		pRoot = GetCurrentRootWindow ();
-
-  if (!pWin)
-    {
-      ErrorF ("IsMouseActive - pWin was NULL use default value:%d\n",
-	      MOUSE_ACTIVATE_DEFAULT);
-      return MOUSE_ACTIVATE_DEFAULT;
-    } 
-
-  pwin = (struct _Window*) pWin;
-
-  if (pwin->optional)
-    prop = (struct _Property *) pwin->optional->userProps;
-  else
-    prop = NULL;
-
-  while (prop)
-    {
-      if (prop->propertyName == AtmWindowsWMMouseActivate ()
-	  && prop->type == XA_INTEGER
-	  && prop->format == 32)
-	{
-	  return *(int*)prop->data;
-	}
-      else
-	prop = prop->next;
-    }
-
-  if (pWin != pRoot)
-    {
-      return IsMouseActive (pRoot);
-    }
-  else
-    {
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("IsMouseActive - no prop use default value:%d\n",
-		MOUSE_ACTIVATE_DEFAULT);
-#endif
-      return MOUSE_ACTIVATE_DEFAULT;
-    }
-}
-
-
-/*
- * winMWExtWMWindowProc - Window procedure
- */
-
-LRESULT CALLBACK
-winMWExtWMWindowProc (HWND hwnd, UINT message, 
-			    WPARAM wParam, LPARAM lParam)
-{
-  WindowPtr		pWin = NULL;
-  win32RootlessWindowPtr pRLWinPriv = NULL;
-  ScreenPtr		pScreen = NULL;
-  winPrivScreenPtr	pScreenPriv = NULL;
-  winScreenInfo		*pScreenInfo = NULL;
-  HWND			hwndScreen = NULL;
-  POINT			ptMouse;
-  static Bool		s_fTracking = FALSE;
-  HDC			hdcUpdate;
-  PAINTSTRUCT		ps;
-  LPWINDOWPOS		pWinPos = NULL;
-  RECT			rcClient;
-  winWMMessageRec	wmMsg;
-  Bool			fWMMsgInitialized = FALSE;
-
-  /* Check if the Windows window property for our X window pointer is valid */
-  if ((pRLWinPriv = (win32RootlessWindowPtr)GetProp (hwnd, WIN_WINDOW_PROP)) != NULL)
-    {
-      pWin = pRLWinPriv->pFrame->win;
-      pScreen				= pWin->drawable.pScreen;
-      if (pScreen) pScreenPriv		= winGetScreenPriv(pScreen);
-      if (pScreenPriv) pScreenInfo	= pScreenPriv->pScreenInfo;
-      if (pScreenPriv) hwndScreen	= pScreenPriv->hwndScreen;
-
-      wmMsg.msg		= 0;
-      wmMsg.hwndWindow	= hwnd;
-      wmMsg.iWindow	= (Window)pWin->drawable.id;
-
-      wmMsg.iX		= pRLWinPriv->pFrame->x;
-      wmMsg.iY		= pRLWinPriv->pFrame->y;
-      wmMsg.iWidth	= pRLWinPriv->pFrame->width;
-      wmMsg.iHeight	= pRLWinPriv->pFrame->height;
-
-      fWMMsgInitialized = TRUE;
-#if CYGDEBUG
-      winDebugWin32Message("winMWExtWMWindowProc", hwnd, message, wParam, lParam);
-
-      winDebug ("\thWnd %08X\n", hwnd);
-      winDebug ("\tpScreenPriv %08X\n", pScreenPriv);
-      winDebug ("\tpScreenInfo %08X\n", pScreenInfo);
-      winDebug ("\thwndScreen %08X\n", hwndScreen);
-      winDebug ("winMWExtWMWindowProc (%08x) %08x %08x %08x\n",
-	      pRLWinPriv, message, wParam, lParam);
-#endif
-    }
-  /* Branch on message type */
-  switch (message)
-    {
-    case WM_CREATE:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_CREATE\n");
-#endif
-      /* */
-      SetProp (hwnd,
-	       WIN_WINDOW_PROP,
-	       (HANDLE)((LPCREATESTRUCT) lParam)->lpCreateParams);
-      return 0;
-
-    case WM_CLOSE:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_CLOSE %d\n", pRLWinPriv->fClose);
-#endif
-      /* Tell window-manager to close window */
-      if (pRLWinPriv->fClose)
-	{
-	  DestroyWindow (hwnd);
-	}
-      else
-	{
-	  if (winIsInternalWMRunning(pScreenInfo))
-	    {
-	      /* Tell our Window Manager thread to kill the window */
-	      wmMsg.msg = WM_WM_KILL;
-	      if (fWMMsgInitialized)
-		winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
-	    }
-	  winWindowsWMSendEvent(WindowsWMControllerNotify,
-				WindowsWMControllerNotifyMask,
-				1,
-				WindowsWMCloseWindow,
-				pWin->drawable.id,
-				0, 0, 0, 0);
-	}
-      return 0;
-
-    case WM_DESTROY:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_DESTROY\n");
-#endif
-      /* Free the shaodw DC; which allows the bitmap to be freed */
-      DeleteDC (pRLWinPriv->hdcShadow);
-      pRLWinPriv->hdcShadow = NULL;
-      
-      /* Free the shadow bitmap */
-      DeleteObject (pRLWinPriv->hbmpShadow);
-      pRLWinPriv->hbmpShadow = NULL;
-      
-      /* Free the screen DC */
-      ReleaseDC (pRLWinPriv->hWnd, pRLWinPriv->hdcScreen);
-      pRLWinPriv->hdcScreen = NULL;
-
-      /* Free shadow buffer info header */
-      free (pRLWinPriv->pbmihShadow);
-      pRLWinPriv->pbmihShadow = NULL;
-      
-      pRLWinPriv->fResized = FALSE;
-      pRLWinPriv->pfb = NULL;
-      free (pRLWinPriv);
-      RemoveProp (hwnd, WIN_WINDOW_PROP);
-      break;
-
-    case WM_MOUSEMOVE:
-#if CYGMULTIWINDOW_DEBUG && 0
-      winDebug ("winMWExtWMWindowProc - WM_MOUSEMOVE\n");
-#endif
-      /* Unpack the client area mouse coordinates */
-      ptMouse.x = GET_X_LPARAM(lParam);
-      ptMouse.y = GET_Y_LPARAM(lParam);
-
-      /* Translate the client area mouse coordinates to screen coordinates */
-      ClientToScreen (hwnd, &ptMouse);
-
-      /* Screen Coords from (-X, -Y) -> Root Window (0, 0) */
-      ptMouse.x -= GetSystemMetrics (SM_XVIRTUALSCREEN);
-      ptMouse.y -= GetSystemMetrics (SM_YVIRTUALSCREEN);
-
-      /* We can't do anything without privates */
-      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
-	break;
-
-      /* Has the mouse pointer crossed screens? */
-      if (pScreen != miPointerGetScreen(inputInfo.pointer))
-	miPointerSetScreen (inputInfo.pointer, pScreenInfo->dwScreen,
-			       ptMouse.x - pScreenInfo->dwXOffset,
-			       ptMouse.y - pScreenInfo->dwYOffset);
-
-      /* Are we tracking yet? */
-      if (!s_fTracking)
-	{
-	  TRACKMOUSEEVENT		tme;
-	  
-	  /* Setup data structure */
-	  ZeroMemory (&tme, sizeof (tme));
-	  tme.cbSize = sizeof (tme);
-	  tme.dwFlags = TME_LEAVE;
-	  tme.hwndTrack = hwnd;
-
-	  /* Call the tracking function */
-	  if (!(*g_fpTrackMouseEvent) (&tme))
-	    ErrorF ("winMWExtWMWindowProc - _TrackMouseEvent failed\n");
-
-	  /* Flag that we are tracking now */
-	  s_fTracking = TRUE;
-	}
-      
-      /* Kill the timer used to poll mouse events */
-      if (g_uipMousePollingTimerID != 0)
-	{
-	  KillTimer (pScreenPriv->hwndScreen, WIN_POLLING_MOUSE_TIMER_ID);
-	  g_uipMousePollingTimerID = 0;
-	}
-
-      /* Deliver absolute cursor position to X Server */
-      miPointerAbsoluteCursor (ptMouse.x - pScreenInfo->dwXOffset,
-			       ptMouse.y - pScreenInfo->dwYOffset,
-			       g_c32LastInputEventTime = GetTickCount ());
-      return 0;
-      
-    case WM_NCMOUSEMOVE:
-#if CYGMULTIWINDOW_DEBUG && 0
-      winDebug ("winMWExtWMWindowProc - WM_NCMOUSEMOVE\n");
-#endif
-      /*
-       * We break instead of returning 0 since we need to call
-       * DefWindowProc to get the mouse cursor changes
-       * and min/max/close button highlighting in Windows XP.
-       * The Platform SDK says that you should return 0 if you
-       * process this message, but it fails to mention that you
-       * will give up any default functionality if you do return 0.
-       */
-      
-      /* We can't do anything without privates */
-      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
-	break;
-
-      /*
-       * Timer to poll mouse events.  This is needed to make
-       * programs like xeyes follow the mouse properly.
-       */
-      if (g_uipMousePollingTimerID == 0)
-	g_uipMousePollingTimerID = SetTimer (pScreenPriv->hwndScreen,
-					     WIN_POLLING_MOUSE_TIMER_ID,
-					     MOUSE_POLLING_INTERVAL,
-					     NULL);
-      break;
-
-    case WM_MOUSELEAVE:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_MOUSELEAVE\n");
-#endif
-      /* Mouse has left our client area */
-
-      /* Flag that we are no longer tracking */
-      s_fTracking = FALSE;
-
-      /*
-       * Timer to poll mouse events.  This is needed to make
-       * programs like xeyes follow the mouse properly.
-       */
-      if (g_uipMousePollingTimerID == 0)
-	g_uipMousePollingTimerID = SetTimer (pScreenPriv->hwndScreen,
-					     WIN_POLLING_MOUSE_TIMER_ID,
-					     MOUSE_POLLING_INTERVAL,
-					     NULL);
-      return 0;
-
-    case WM_LBUTTONDBLCLK:
-    case WM_LBUTTONDOWN:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_LBUTTONDBLCLK\n");
-#endif
-      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
-	break;
-      SetCapture (hwnd);
-      return winMouseButtonsHandle (pScreen, ButtonPress, Button1, wParam);
-      
-    case WM_LBUTTONUP:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_LBUTTONUP\n");
-#endif
-      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
-	break;
-      ReleaseCapture ();
-      return winMouseButtonsHandle (pScreen, ButtonRelease, Button1, wParam);
-
-    case WM_MBUTTONDBLCLK:
-    case WM_MBUTTONDOWN:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_MBUTTONDBLCLK\n");
-#endif
-      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
-	break;
-      SetCapture (hwnd);
-      return winMouseButtonsHandle (pScreen, ButtonPress, Button2, wParam);
-      
-    case WM_MBUTTONUP:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_MBUTTONUP\n");
-#endif
-      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
-	break;
-      ReleaseCapture ();
-      return winMouseButtonsHandle (pScreen, ButtonRelease, Button2, wParam);
-      
-    case WM_RBUTTONDBLCLK:
-    case WM_RBUTTONDOWN:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_RBUTTONDBLCLK\n");
-#endif
-      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
-	break;
-      SetCapture (hwnd);
-      return winMouseButtonsHandle (pScreen, ButtonPress, Button3, wParam);
-      
-    case WM_RBUTTONUP:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_RBUTTONUP\n");
-#endif
-      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
-	break;
-      ReleaseCapture ();
-      return winMouseButtonsHandle (pScreen, ButtonRelease, Button3, wParam);
-
-    case WM_XBUTTONDBLCLK:
-    case WM_XBUTTONDOWN:
-      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
-	break;
-      SetCapture (hwnd);
-      return winMouseButtonsHandle (pScreen, ButtonPress, HIWORD(wParam) + 5, wParam);
-    case WM_XBUTTONUP:
-      if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
-	break;
-      ReleaseCapture ();
-      return winMouseButtonsHandle (pScreen, ButtonRelease, HIWORD(wParam) + 5, wParam);
-
-    case WM_MOUSEWHEEL:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_MOUSEWHEEL\n");
-#endif
-      
-      /* Pass the message to the root window */
-      SendMessage (hwndScreen, message, wParam, lParam);
-      return 0;
-
-    case WM_MOUSEACTIVATE:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_MOUSEACTIVATE\n");
-#endif
-#if 1
-      /* Check if this window needs to be made active when clicked */
-      if (winIsInternalWMRunning(pScreenInfo) && pWin->overrideRedirect)
-	{
-#if CYGMULTIWINDOW_DEBUG
-	  winDebug ("winMWExtWMWindowProc - WM_MOUSEACTIVATE - "
-		    "MA_NOACTIVATE\n");
-#endif
-
-	  /* */
-	  return MA_NOACTIVATE;
-	}
-#endif
-      if (!winIsInternalWMRunning(pScreenInfo) && !IsMouseActive (pWin))
-	return MA_NOACTIVATE;
-
-      break;
-
-    case WM_KILLFOCUS:
-      /* Pop any pressed keys since we are losing keyboard focus */
-      winKeybdReleaseKeys ();
-      return 0;
-
-    case WM_SYSDEADCHAR:
-    case WM_DEADCHAR:
-      /*
-       * NOTE: We do nothing with WM_*CHAR messages,
-       * nor does the root window, so we can just toss these messages.
-       */
-      return 0;
-
-    case WM_SYSKEYDOWN:
-    case WM_KEYDOWN:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_*KEYDOWN\n");
-#endif
-
-      /*
-       * Don't pass Alt-F4 key combo to root window,
-       * let Windows translate to WM_CLOSE and close this top-level window.
-       *
-       * NOTE: We purposely don't check the fUseWinKillKey setting because
-       * it should only apply to the key handling for the root window,
-       * not for top-level window-manager windows.
-       *
-       * ALSO NOTE: We do pass Ctrl-Alt-Backspace to the root window
-       * because that is a key combo that no X app should be expecting to
-       * receive, since it has historically been used to shutdown the X server.
-       * Passing Ctrl-Alt-Backspace to the root window preserves that
-       * behavior, assuming that -unixkill has been passed as a parameter.
-       */
-      if (wParam == VK_F4 && (GetKeyState (VK_MENU) & 0x8000))
-	  break;
-
-      /* Pass the message to the root window */
-      SendMessage (hwndScreen, message, wParam, lParam);
-      return 0;
-
-    case WM_SYSKEYUP:
-    case WM_KEYUP:
-
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_*KEYUP\n");
-#endif
-
-      /* Pass the message to the root window */
-      SendMessage (hwndScreen, message, wParam, lParam);
-      return 0;
-
-    case WM_HOTKEY:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_HOTKEY\n");
-#endif
-
-      /* Pass the message to the root window */
-      SendMessage (hwndScreen, message, wParam, lParam);
-      return 0;
-
-    case WM_PAINT:
-    
-      /* BeginPaint gives us an hdc that clips to the invalidated region */
-      hdcUpdate = BeginPaint (hwnd, &ps);
-
-      /* Try to copy from the shadow buffer */
-      if (!BitBlt (hdcUpdate,
-		   ps.rcPaint.left, ps.rcPaint.top,
-		   ps.rcPaint.right - ps.rcPaint.left,
-		   ps.rcPaint.bottom - ps.rcPaint.top,
-		   pRLWinPriv->hdcShadow,
-		   ps.rcPaint.left, ps.rcPaint.top,
-		   SRCCOPY))
-	{
-	  LPVOID lpMsgBuf;
-	  
-	  /* Display a fancy error message */
-	  FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | 
-			 FORMAT_MESSAGE_FROM_SYSTEM | 
-			 FORMAT_MESSAGE_IGNORE_INSERTS,
-			 NULL,
-			 GetLastError (),
-			 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-			 (LPTSTR) &lpMsgBuf,
-			 0, NULL);
-
-	  ErrorF ("winMWExtWMWindowProc - BitBlt failed: %s\n",
-		  (LPSTR)lpMsgBuf);
-	  LocalFree (lpMsgBuf);
-	}
-
-      /* EndPaint frees the DC */
-      EndPaint (hwnd, &ps);
-      break;
-
-    case WM_ACTIVATE:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_ACTIVATE\n");
-#endif
-      if (LOWORD(wParam) != WA_INACTIVE)
-	{
-	  if (winIsInternalWMRunning(pScreenInfo))
-	    {
-#if 0
-	      /* Raise the window to the top in Z order */
-	      wmMsg.msg = WM_WM_RAISE;
-	      if (fWMMsgInitialized)
-		winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
-#endif
-	      /* Tell our Window Manager thread to activate the window */
-	      wmMsg.msg = WM_WM_ACTIVATE;
-	      if (fWMMsgInitialized)
-		if (!pWin || !pWin->overrideRedirect) /* for OOo menus */
-		  winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
-	    }
-	  winWindowsWMSendEvent(WindowsWMControllerNotify,
-				WindowsWMControllerNotifyMask,
-				1,
-				WindowsWMActivateWindow,
-				pWin->drawable.id,
-				0, 0,
-				0, 0);
-	}
-      return 0;
-
-#if 1
-    case WM_WINDOWPOSCHANGING:
-      pWinPos = (LPWINDOWPOS)lParam;
-      if (!(pWinPos->flags & SWP_NOZORDER))
-	{
-	  if (pRLWinPriv->fRestackingNow || pScreenPriv->fRestacking)
-	    {
-#if CYGMULTIWINDOW_DEBUG
-	      winDebug ("Win %08x is now restacking.\n", (unsigned int)pRLWinPriv);
-#endif
-	      break;
-	    }
-
-	  if (winIsInternalWMRunning(pScreenInfo) || IsRaiseOnClick (pWin))
-	    {
-#if CYGMULTIWINDOW_DEBUG
-	      winDebug ("Win %08x has WINDOWSWM_RAISE_ON_CLICK.\n", (unsigned int)pRLWinPriv);
-#endif
-	      break;
-	    }
-
-#if CYGMULTIWINDOW_DEBUG
-	  winDebug ("Win %08x forbid to change z order (%08x).\n",
-		    (unsigned int)pRLWinPriv, (unsigned int)pWinPos->hwndInsertAfter);
-#endif
-	  pWinPos->flags |= SWP_NOZORDER;
-	}
-      break;
-#endif
-
-    case WM_MOVE:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_MOVE - %d ms\n",
-		(unsigned int)GetTickCount ());
-#endif
-      if (g_fNoConfigureWindow) break;
-#if 0
-      /* Bail if Windows window is not actually moving */
-      if (pRLWinPriv->dwX == (short) LOWORD(lParam)
-	  && pRLWinPriv->dwY == (short) HIWORD(lParam))
-	break;
-
-      /* Also bail if we're maximizing, we'll do the whole thing in WM_SIZE */
-      {
-	WINDOWPLACEMENT windPlace;
-	windPlace.length = sizeof (WINDOWPLACEMENT);
-
-	/* Get current window placement */
-	GetWindowPlacement (hwnd, &windPlace);
-
-	/* Bail if maximizing */
-	if (windPlace.showCmd == SW_MAXIMIZE
-	    || windPlace.showCmd == SW_SHOWMAXIMIZED)
-	  break;
-      }
-#endif
-
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("\t(%d, %d)\n", (short) LOWORD(lParam), (short) HIWORD(lParam));
-#endif
-      if (!pRLWinPriv->fMovingOrSizing)
-	{
-	  if (winIsInternalWMRunning(pScreenInfo))
-	    winAdjustXWindow (pWin, hwnd);
-
-	  winMWExtWMMoveXWindow (pWin,
-				 (LOWORD(lParam) - wBorderWidth (pWin)
-				  - GetSystemMetrics (SM_XVIRTUALSCREEN)),
-				 (HIWORD(lParam) - wBorderWidth (pWin)
-				  - GetSystemMetrics (SM_YVIRTUALSCREEN)));
-	}
-      return 0;
-
-    case WM_SHOWWINDOW:
-#if CYGMULTIWINDOW_DEBUG || TRUE
-      winDebug ("winMWExtWMWindowProc - WM_SHOWWINDOW - %d ms\n",
-		(unsigned int)GetTickCount ());
-#endif
-      /* Bail out if the window is being hidden */
-      if (!wParam)
-	return 0;
-
-      if (!pScreenInfo->fInternalWM)//XXXX
-	return 0;
-
-      winMWExtWMUpdateWindowDecoration (pRLWinPriv, pScreenInfo);
-
-      if (winIsInternalWMRunning(pScreenInfo))
-	{
-#if CYGMULTIWINDOW_DEBUG || TRUE
-	  winDebug ("\tMapWindow\n");
-#endif
-	  /* Tell X to map the window */
-	   MapWindow (pWin, wClient(pWin));
-
-	  if (!pRLWinPriv->pFrame->win->overrideRedirect)
-	    /* Bring the Windows window to the foreground */
-	    SetForegroundWindow (hwnd);
-
-	  /* Setup the Window Manager message */
-	  wmMsg.msg = WM_WM_MAP;
-	  wmMsg.iWidth = pRLWinPriv->pFrame->width;
-	  wmMsg.iHeight = pRLWinPriv->pFrame->height;
-
-	  /* Tell our Window Manager thread to map the window */
-	  if (fWMMsgInitialized)
-	    winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
-	}
-      break;
-
-    case WM_SIZING:
-      /* Need to legalize the size according to WM_NORMAL_HINTS */
-      /* for applications like xterm */
-      return ValidateSizing (hwnd, pWin, wParam, lParam);
-
-    case WM_WINDOWPOSCHANGED:
-      {
-	pWinPos = (LPWINDOWPOS) lParam;
-#if CYGMULTIWINDOW_DEBUG
-        winDebug("winMWExtWMWindowProc - WM_WINDOWPOSCHANGED\n");
-	winDebug("\tflags: %s%s%s%s%s%s%s%s%s%s%s%s\n",
-	(pWinPos->flags & SWP_DRAWFRAME)?"SWP_DRAWFRAME ":"",
-	(pWinPos->flags & SWP_FRAMECHANGED)?"SWP_FRAMECHANGED ":"",
-	(pWinPos->flags & SWP_HIDEWINDOW)?"SWP_HIDEWINDOW ":"",
-	(pWinPos->flags & SWP_NOACTIVATE)?"SWP_NOACTIVATE ":"",
-	(pWinPos->flags & SWP_NOCOPYBITS)?"SWP_NOCOPYBITS ":"",
-	(pWinPos->flags & SWP_NOMOVE)?"SWP_NOMOVE ":"",
-	(pWinPos->flags & SWP_NOOWNERZORDER)?"SWP_NOOWNERZORDER ":"",
-	(pWinPos->flags & SWP_NOSIZE)?"SWP_NOSIZE ":"",
-	(pWinPos->flags & SWP_NOREDRAW)?"SWP_NOREDRAW ":"",
-	(pWinPos->flags & SWP_NOSENDCHANGING)?"SWP_NOSENDCHANGING ":"",
-	(pWinPos->flags & SWP_NOZORDER)?"SWP_NOZORDER ":"",
-	(pWinPos->flags & SWP_SHOWWINDOW)?"SWP_SHOWWINDOW ":"");
-	winDebug("\tno_configure: %s\n", (g_fNoConfigureWindow?"Yes":"No"));
-	winDebug("\textend: (%d, %d, %d, %d)\n",
-            pWinPos->x, pWinPos->y, pWinPos->cx, pWinPos->cy);
-
-#endif
-	if (pWinPos->flags & SWP_HIDEWINDOW) break;
-
-	/* Reorder if window z order was changed */
-	if ((pScreenPriv != NULL)
-	    && !(pWinPos->flags & SWP_NOZORDER)
-	    && !(pWinPos->flags & SWP_SHOWWINDOW)
-	    && winIsInternalWMRunning(pScreenInfo))
-	  {
-#if CYGMULTIWINDOW_DEBUG
-	    winDebug ("\twindow z order was changed\n");
-#endif
-	    if (pWinPos->hwndInsertAfter == HWND_TOP
-		||pWinPos->hwndInsertAfter == HWND_TOPMOST
-		||pWinPos->hwndInsertAfter == HWND_NOTOPMOST)
-	      {
-#if CYGMULTIWINDOW_DEBUG
-		winDebug ("\traise to top\n");
-#endif
-		/* Raise the window to the top in Z order */
-		wmMsg.msg = WM_WM_RAISE;
-		if (fWMMsgInitialized)
-		  winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
-	      }
-#if 1
-	    else if (pWinPos->hwndInsertAfter == HWND_BOTTOM)
-	      {
-	      }
-	    else
-	      {
-		/* Check if this window is top of X windows. */
-		HWND hWndAbove = NULL;
-		DWORD dwCurrentProcessID = GetCurrentProcessId ();
-		DWORD dwWindowProcessID = 0;
-
-		for (hWndAbove = pWinPos->hwndInsertAfter;
-		     hWndAbove != NULL;
-		     hWndAbove = GetNextWindow (hWndAbove, GW_HWNDPREV))
-		  {
-		    /* Ignore other XWin process's window */
-		    GetWindowThreadProcessId (hWndAbove, &dwWindowProcessID);
-
-		    if ((dwWindowProcessID == dwCurrentProcessID)
-			&& GetProp (hWndAbove, WIN_WINDOW_PROP)
-			&& !IsWindowVisible (hWndAbove)
-			&& !IsIconic (hWndAbove) ) /* ignore minimized windows */
-		      break;
-		  }
-		/* If this is top of X windows in Windows stack,
-		   raise it in X stack. */
-		if (hWndAbove == NULL)
-		  {
-#if CYGMULTIWINDOW_DEBUG
-		    winDebug ("\traise to top\n");
-#endif
-		    /* Raise the window to the top in Z order */
-		    wmMsg.msg = WM_WM_RAISE;
-		    if (fWMMsgInitialized)
-		      winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
-		  }
-	      }
-#endif
-	  }
-
-	if (!(pWinPos->flags & SWP_NOSIZE)) {
-	  if (IsIconic(hwnd)){
-#if CYGMULTIWINDOW_DEBUG
-	    winDebug ("\tIconic -> MINIMIZED\n");
-#endif
-	    if (winIsInternalWMRunning(pScreenInfo))
-	      {
-	      /* Raise the window to the top in Z order */
-		wmMsg.msg = WM_WM_LOWER;
-		if (fWMMsgInitialized)
-		  winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
-	      }
-	    winWindowsWMSendEvent(WindowsWMControllerNotify,
-				  WindowsWMControllerNotifyMask,
-				  1,
-				  WindowsWMMinimizeWindow,
-				  pWin->drawable.id,
-				  0, 0, 0, 0);
-	  } else if (IsZoomed(hwnd)){
-#if CYGMULTIWINDOW_DEBUG
-	    winDebug ("\tZoomed -> MAXIMIZED\n");
-#endif
-	    winWindowsWMSendEvent(WindowsWMControllerNotify,
-				  WindowsWMControllerNotifyMask,
-				  1,
-				  WindowsWMMaximizeWindow,
-				  pWin->drawable.id,
-				  0, 0, 0, 0);
-	  } else {
-#if CYGMULTIWINDOW_DEBUG
-	    winDebug ("\tnone -> RESTORED\n");
-#endif
-	    winWindowsWMSendEvent(WindowsWMControllerNotify,
-				  WindowsWMControllerNotifyMask,
-				  1,
-				  WindowsWMRestoreWindow,
-				  pWin->drawable.id,
-				  0, 0, 0, 0);
-	  }
-	}
-	if (!g_fNoConfigureWindow ) {
-
-	  if (!pRLWinPriv->fMovingOrSizing
-	      /*&& (pWinPos->flags & SWP_SHOWWINDOW)*/) {
-	    GetClientRect (hwnd, &rcClient);
-	    MapWindowPoints (hwnd, HWND_DESKTOP, (LPPOINT)&rcClient, 2);
-
-	    if (!(pWinPos->flags & SWP_NOMOVE)
-		&&!(pWinPos->flags & SWP_NOSIZE)) {
-#if CYGMULTIWINDOW_DEBUG
-	      winDebug ("\tmove & resize\n");
-#endif
-	      if (winIsInternalWMRunning(pScreenInfo))
-                winAdjustXWindow (pWin, hwnd);
-
-	      winMWExtWMMoveResizeXWindow (pWin,
-					   rcClient.left - wBorderWidth (pWin)
-					   - GetSystemMetrics (SM_XVIRTUALSCREEN),
-					   rcClient.top - wBorderWidth (pWin)
-					   - GetSystemMetrics (SM_YVIRTUALSCREEN),
-					   rcClient.right - rcClient.left
-					   - wBorderWidth (pWin)*2,
-					   rcClient.bottom - rcClient.top
-					   - wBorderWidth (pWin)*2);
-	    } else if (!(pWinPos->flags & SWP_NOMOVE)) {
-#if CYGMULTIWINDOW_DEBUG
-	      winDebug ("\tmove\n");
-#endif
-	      if (winIsInternalWMRunning(pScreenInfo))
-                winAdjustXWindow (pWin, hwnd);
-
-	      winMWExtWMMoveResizeXWindow (pWin,
-					   rcClient.left - wBorderWidth (pWin)
-					   - GetSystemMetrics (SM_XVIRTUALSCREEN),
-					   rcClient.top - wBorderWidth (pWin)
-					   - GetSystemMetrics (SM_YVIRTUALSCREEN),
-					   rcClient.right - rcClient.left
-					   - wBorderWidth (pWin)*2,
-					   rcClient.bottom - rcClient.top
-					   - wBorderWidth (pWin)*2);
-	    } else if (!(pWinPos->flags & SWP_NOMOVE)) {
-#if CYGMULTIWINDOW_DEBUG
-	      winDebug ("\tmove\n");
-#endif
-	      if (winIsInternalWMRunning(pScreenInfo))
-                winAdjustXWindow (pWin, hwnd); 
-
-	      winMWExtWMMoveXWindow (pWin,
-				     rcClient.left - wBorderWidth (pWin)
-				     - GetSystemMetrics (SM_XVIRTUALSCREEN),
-				     rcClient.top - wBorderWidth (pWin)
-				     - GetSystemMetrics (SM_YVIRTUALSCREEN));
-	    } else if (!(pWinPos->flags & SWP_NOSIZE)) {
-#if CYGMULTIWINDOW_DEBUG
-	      winDebug ("\tresize\n");
-#endif
-	      if (winIsInternalWMRunning(pScreenInfo))
-                winAdjustXWindow (pWin, hwnd); 
-
-	      winMWExtWMResizeXWindow (pWin,
-				       rcClient.right - rcClient.left
-				       - wBorderWidth (pWin)*2,
-				       rcClient.bottom - rcClient.top
-				       - wBorderWidth (pWin)*2);
-	    }
-	  }
-	}
-      }
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_WINDOWPOSCHANGED - done.\n");
-#endif
-      return 0;
-
-    case WM_SIZE:
-      /* see dix/window.c */
-      /* FIXME: Maximize/Restore? */
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_SIZE - %d ms\n",
-		(unsigned int)GetTickCount ());
-#endif
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("\t(%d, %d) %d\n", (short) LOWORD(lParam), (short) HIWORD(lParam), g_fNoConfigureWindow);
-#endif
-      if (g_fNoConfigureWindow) break;
-
-      /* Branch on type of resizing occurring */
-      switch (wParam)
-	{
-	case SIZE_MINIMIZED:
-#if CYGMULTIWINDOW_DEBUG
-	  winDebug ("\tSIZE_MINIMIZED\n");
-#endif
-	  if (winIsInternalWMRunning(pScreenInfo))
-	    {
-	      /* Raise the window to the top in Z order */
-	      wmMsg.msg = WM_WM_LOWER;
-	      if (fWMMsgInitialized)
-		winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
-	    }
-	  winWindowsWMSendEvent(WindowsWMControllerNotify,
-				WindowsWMControllerNotifyMask,
-				1,
-				WindowsWMMinimizeWindow,
-				pWin->drawable.id,
-				0, 0,
-				LOWORD(lParam), HIWORD(lParam));
-	  break;
-
-	case SIZE_RESTORED:
-#if CYGMULTIWINDOW_DEBUG
-	  winDebug ("\tSIZE_RESTORED\n");
-#endif
-	  winWindowsWMSendEvent(WindowsWMControllerNotify,
-				WindowsWMControllerNotifyMask,
-				1,
-				WindowsWMRestoreWindow,
-				pWin->drawable.id,
-				0, 0,
-				LOWORD(lParam), HIWORD(lParam));
-	  break;
-
-	case SIZE_MAXIMIZED:
-#if CYGMULTIWINDOW_DEBUG
-	  winDebug ("\tSIZE_MAXIMIZED\n");
-#endif
-	  winWindowsWMSendEvent(WindowsWMControllerNotify,
-				WindowsWMControllerNotifyMask,
-				1,
-				WindowsWMMaximizeWindow,
-				pWin->drawable.id,
-				0, 0,
-				LOWORD(lParam), HIWORD(lParam));
-	  break;
-	}
-
-      /* Perform the resize and notify the X client */
-      if (!pRLWinPriv->fMovingOrSizing)
-	{
-	  if (winIsInternalWMRunning(pScreenInfo))
-            winAdjustXWindow (pWin, hwnd);
-
-	  winMWExtWMResizeXWindow (pWin,
-				   (short) LOWORD(lParam)
-				   - wBorderWidth (pWin)*2,
-				   (short) HIWORD(lParam)
-				   - wBorderWidth (pWin)*2);
-	}
-      break;
-
-    case WM_ACTIVATEAPP:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_ACTIVATEAPP - %d ms\n",
-		(unsigned int)GetTickCount ());
-#endif
-      if (wParam)
-	{
-	  if (winIsInternalWMRunning(pScreenInfo))
-	    {
-	    }
-	  else
-	    {
-	    }
-	  winWindowsWMSendEvent(WindowsWMActivationNotify,
-				WindowsWMActivationNotifyMask,
-				1,
-				WindowsWMIsActive,
-				pWin->drawable.id,
-				0, 0,
-				0, 0);
-	}
-      else
-	{
-	  winWindowsWMSendEvent(WindowsWMActivationNotify,
-				WindowsWMActivationNotifyMask,
-				1,
-				WindowsWMIsInactive,
-				pWin->drawable.id,
-				0, 0,
-				0, 0);
-	}
-      break;
-
-    case WM_SETCURSOR:
-      if (LOWORD(lParam) == HTCLIENT)
-	{
-	  if (!g_fSoftwareCursor) SetCursor (pScreenPriv->cursor.handle);
-	  return TRUE;
-	}
-      break;
-
-    case WM_ENTERSIZEMOVE:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_ENTERSIZEMOVE - %d ms\n",
-		(unsigned int)GetTickCount ());
-#endif
-      pRLWinPriv->fMovingOrSizing = TRUE;
-      break;
-
-    case WM_EXITSIZEMOVE:
-#if CYGMULTIWINDOW_DEBUG
-      winDebug ("winMWExtWMWindowProc - WM_EXITSIZEMOVE - %d ms\n",
-		(unsigned int)GetTickCount ());
-#endif
-      pRLWinPriv->fMovingOrSizing = FALSE;
-
-      GetClientRect (hwnd, &rcClient);
-
-      MapWindowPoints (hwnd, HWND_DESKTOP, (LPPOINT)&rcClient, 2);
-
-      if (winIsInternalWMRunning(pScreenInfo))
-        winAdjustXWindow (pWin, hwnd); 
-
-      winMWExtWMMoveResizeXWindow (pWin,
-				   rcClient.left - wBorderWidth (pWin)
-				   - GetSystemMetrics (SM_XVIRTUALSCREEN),
-				   rcClient.top - wBorderWidth (pWin)
-				   - GetSystemMetrics (SM_YVIRTUALSCREEN),
-				   rcClient.right - rcClient.left
-				   - wBorderWidth (pWin)*2,
-				   rcClient.bottom - rcClient.top
-				   - wBorderWidth (pWin)*2);
-      break;
-
-    case WM_MANAGE:
-      ErrorF ("winMWExtWMWindowProc - WM_MANAGE\n");
-      break;
-
-    case WM_UNMANAGE:
-      ErrorF ("winMWExtWMWindowProc - WM_UNMANAGE\n");
-      break;
-
-    default:
-      break;
-    }
-
-  return DefWindowProc (hwnd, message, wParam, lParam);
-}
diff --git a/hw/xwin/winwindow.c b/hw/xwin/winwindow.c
deleted file mode 100644
index 1600996..0000000
--- a/hw/xwin/winwindow.c
+++ /dev/null
@@ -1,649 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Harold L Hunt II
- *		Kensuke Matsuzaki
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-
-/*
- * Prototypes for local functions
- */
-
-static int
-winAddRgn (WindowPtr pWindow, pointer data);
-
-static
-void
-winUpdateRgnRootless (WindowPtr pWindow);
-
-#ifdef SHAPE
-static
-void
-winReshapeRootless (WindowPtr pWin);
-#endif
-
-
-#ifdef XWIN_NATIVEGDI
-/* See Porting Layer Definition - p. 37 */
-/* See mfb/mfbwindow.c - mfbCreateWindow() */
-
-Bool
-winCreateWindowNativeGDI (WindowPtr pWin)
-{
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winTrace ("winCreateWindowNativeGDI (%p)\n", pWin);
-#endif
-
-  WIN_UNWRAP(CreateWindow);
-  fResult = (*pScreen->CreateWindow) (pWin);
-  WIN_WRAP(CreateWindow, winCreateWindowNativeGDI);
-
-  return fResult;
-}
-
-
-/* See Porting Layer Definition - p. 37 */
-/* See mfb/mfbwindow.c - mfbDestroyWindow() */
-
-Bool
-winDestroyWindowNativeGDI (WindowPtr pWin)
-{
-  Bool			fResult = TRUE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winTrace ("winDestroyWindowNativeGDI (%p)\n", pWin);
-#endif
-
-  WIN_UNWRAP(DestroyWindow); 
-  fResult = (*pScreen->DestroyWindow)(pWin);
-  WIN_WRAP(DestroyWindow, winDestroyWindowNativeGDI);
-
-  return fResult;
-}
-
-
-/* See Porting Layer Definition - p. 37 */
-/* See mfb/mfbwindow.c - mfbPositionWindow() */
-
-Bool
-winPositionWindowNativeGDI (WindowPtr pWin, int x, int y)
-{
-  Bool			fResult = TRUE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winTrace ("winPositionWindowNativeGDI (%p)\n", pWin);
-#endif
-
-  WIN_UNWRAP(PositionWindow);
-  fResult = (*pScreen->PositionWindow)(pWin, x, y);
-  WIN_WRAP(PositionWindow, winPositionWindowNativeGDI);
-
-  return fResult;
-}
-
-
-/* See Porting Layer Definition - p. 39 */
-/* See mfb/mfbwindow.c - mfbCopyWindow() */
-
-void 
-winCopyWindowNativeGDI (WindowPtr pWin,
-			DDXPointRec ptOldOrg,
-			RegionPtr prgnSrc)
-{
-  DDXPointPtr		pptSrc;
-  DDXPointPtr		ppt;
-  RegionPtr		prgnDst;
-  BoxPtr		pBox;
-  int			dx, dy;
-  int			i, nbox;
-  WindowPtr		pwinRoot;
-  BoxPtr		pBoxDst;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winScreenPriv(pScreen);
-
-#if 0
-  ErrorF ("winCopyWindow\n");
-#endif
-
-  /* Get a pointer to the root window */
-  pwinRoot = WindowTable[pWin->drawable.pScreen->myNum];
-
-  /* Create a region for the destination */
-  prgnDst = REGION_CREATE(pWin->drawable.pScreen, NULL, 1);
-
-  /* Calculate the shift from the source to the destination */
-  dx = ptOldOrg.x - pWin->drawable.x;
-  dy = ptOldOrg.y - pWin->drawable.y;
-
-  /* Translate the region from the destination to the source? */
-  REGION_TRANSLATE(pWin->drawable.pScreen, prgnSrc, -dx, -dy);
-  REGION_INTERSECT(pWin->drawable.pScreen, prgnDst, &pWin->borderClip,
-		   prgnSrc);
-
-  /* Get a pointer to the first box in the region to be copied */
-  pBox = REGION_RECTS(prgnDst);
-  
-  /* Get the number of boxes in the region */
-  nbox = REGION_NUM_RECTS(prgnDst);
-
-  /* Allocate source points for each box */
-  if(!(pptSrc = (DDXPointPtr )xalloc(nbox * sizeof(DDXPointRec))))
-    return;
-
-  /* Set an iterator pointer */
-  ppt = pptSrc;
-
-  /* Calculate the source point of each box? */
-  for (i = nbox; --i >= 0; ppt++, pBox++)
-    {
-      ppt->x = pBox->x1 + dx;
-      ppt->y = pBox->y1 + dy;
-    }
-
-  /* Setup loop pointers again */
-  pBoxDst = REGION_RECTS(prgnDst);
-  ppt = pptSrc;
-
-#if 0
-  ErrorF ("winCopyWindow - x1\tx2\ty1\ty2\tx\ty\n");
-#endif
-
-  /* BitBlt each source to the destination point */
-  for (i = nbox; --i >= 0; pBoxDst++, ppt++)
-    {
-#if 0
-      ErrorF ("winCopyWindow - %d\t%d\t%d\t%d\t%d\t%d\n",
-	      pBoxDst->x1, pBoxDst->x2, pBoxDst->y1, pBoxDst->y2,
-	      ppt->x, ppt->y);
-#endif
-
-      BitBlt (pScreenPriv->hdcScreen,
-	      pBoxDst->x1, pBoxDst->y1,
-	      pBoxDst->x2 - pBoxDst->x1, pBoxDst->y2 - pBoxDst->y1,
-	      pScreenPriv->hdcScreen,
-	      ppt->x, ppt->y,
-	      SRCCOPY);
-    }
-
-  /* Cleanup the regions, etc. */
-  xfree(pptSrc);
-  REGION_DESTROY(pWin->drawable.pScreen, prgnDst);
-}
-
-
-/* See Porting Layer Definition - p. 37 */
-/* See mfb/mfbwindow.c - mfbChangeWindowAttributes() */
-
-Bool
-winChangeWindowAttributesNativeGDI (WindowPtr pWin, unsigned long mask)
-{
-  Bool			fResult = TRUE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winTrace ("winChangeWindowAttributesNativeGDI (%p)\n", pWin);
-#endif
-  
-  WIN_UNWRAP(ChangeWindowAttributes); 
-  fResult = (*pScreen->ChangeWindowAttributes)(pWin, mask);
-  WIN_WRAP(ChangeWindowAttributes, winChangeWindowAttributesNativeGDI);
-  
-  /*
-   * NOTE: We do not currently need to do anything here.
-   */
-
-  return fResult;
-}
-
-
-/* See Porting Layer Definition - p. 37
- * Also referred to as UnrealizeWindow
- */
-
-Bool
-winUnmapWindowNativeGDI (WindowPtr pWin)
-{
-  Bool			fResult = TRUE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winTrace ("winUnmapWindowNativeGDI (%p)\n", pWin);
-#endif
-
-  WIN_UNWRAP(UnrealizeWindow); 
-  fResult = (*pScreen->UnrealizeWindow)(pWin);
-  WIN_WRAP(UnrealizeWindow, winUnmapWindowNativeGDI);
-  
-  return fResult;
-}
-
-
-/* See Porting Layer Definition - p. 37
- * Also referred to as RealizeWindow
- */
-
-Bool
-winMapWindowNativeGDI (WindowPtr pWin)
-{
-  Bool			fResult = TRUE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winTrace ("winMapWindowNativeGDI (%p)\n", pWin);
-#endif
-
-  WIN_UNWRAP(RealizeWindow); 
-  fResult = (*pScreen->RealizeWindow)(pWin);
-  WIN_WRAP(RealizeWindow, winMapWindowMultiWindow);
-  
-  return fResult;
-
-}
-#endif
-
-
-/* See Porting Layer Definition - p. 37 */
-/* See mfb/mfbwindow.c - mfbCreateWindow() */
-
-Bool
-winCreateWindowRootless (WindowPtr pWin)
-{
-  Bool			fResult = FALSE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winTrace ("winCreateWindowRootless (%p)\n", pWin);
-#endif
-
-  WIN_UNWRAP(CreateWindow);
-  fResult = (*pScreen->CreateWindow) (pWin);
-  WIN_WRAP(CreateWindow, winCreateWindowRootless);
-  
-  pWinPriv->hRgn = NULL;
-  
-  return fResult;
-}
-
-
-/* See Porting Layer Definition - p. 37 */
-/* See mfb/mfbwindow.c - mfbDestroyWindow() */
-
-Bool
-winDestroyWindowRootless (WindowPtr pWin)
-{
-  Bool			fResult = FALSE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winTrace ("winDestroyWindowRootless (%p)\n", pWin);
-#endif
-
-  WIN_UNWRAP(DestroyWindow); 
-  fResult = (*pScreen->DestroyWindow)(pWin);
-  WIN_WRAP(DestroyWindow, winDestroyWindowRootless);
-  
-  if (pWinPriv->hRgn != NULL)
-    {
-      DeleteObject(pWinPriv->hRgn);
-      pWinPriv->hRgn = NULL;
-    }
-  
-  winUpdateRgnRootless (pWin);
-  
-  return fResult;
-}
-
-
-/* See Porting Layer Definition - p. 37 */
-/* See mfb/mfbwindow.c - mfbPositionWindow() */
-
-Bool
-winPositionWindowRootless (WindowPtr pWin, int x, int y)
-{
-  Bool			fResult = FALSE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-
-#if CYGDEBUG
-  winTrace ("winPositionWindowRootless (%p)\n", pWin);
-#endif
-
-  WIN_UNWRAP(PositionWindow);
-  fResult = (*pScreen->PositionWindow)(pWin, x, y);
-  WIN_WRAP(PositionWindow, winPositionWindowRootless);
-  
-  winUpdateRgnRootless (pWin);
-  
-  return fResult;
-}
-
-
-/* See Porting Layer Definition - p. 37 */
-/* See mfb/mfbwindow.c - mfbChangeWindowAttributes() */
-
-Bool
-winChangeWindowAttributesRootless (WindowPtr pWin, unsigned long mask)
-{
-  Bool			fResult = FALSE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winTrace ("winChangeWindowAttributesRootless (%p)\n", pWin);
-#endif
-
-  WIN_UNWRAP(ChangeWindowAttributes); 
-  fResult = (*pScreen->ChangeWindowAttributes)(pWin, mask);
-  WIN_WRAP(ChangeWindowAttributes, winChangeWindowAttributesRootless);
-
-  winUpdateRgnRootless (pWin);
-  
-  return fResult;
-}
-
-
-/* See Porting Layer Definition - p. 37
- * Also referred to as UnrealizeWindow
- */
-
-Bool
-winUnmapWindowRootless (WindowPtr pWin)
-{
-  Bool			fResult = FALSE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winTrace ("winUnmapWindowRootless (%p)\n", pWin);
-#endif
-
-  WIN_UNWRAP(UnrealizeWindow); 
-  fResult = (*pScreen->UnrealizeWindow)(pWin);
-  WIN_WRAP(UnrealizeWindow, winUnmapWindowRootless);
-  
-  if (pWinPriv->hRgn != NULL)
-    {
-      DeleteObject(pWinPriv->hRgn);
-      pWinPriv->hRgn = NULL;
-    }
-  
-  winUpdateRgnRootless (pWin);
-  
-  return fResult;
-}
-
-
-/* See Porting Layer Definition - p. 37
- * Also referred to as RealizeWindow
- */
-
-Bool
-winMapWindowRootless (WindowPtr pWin)
-{
-  Bool			fResult = FALSE;
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winTrace ("winMapWindowRootless (%p)\n", pWin);
-#endif
-
-  WIN_UNWRAP(RealizeWindow); 
-  fResult = (*pScreen->RealizeWindow)(pWin);
-  WIN_WRAP(RealizeWindow, winMapWindowRootless);
-
-#ifdef SHAPE
-  winReshapeRootless (pWin);
-#endif
-  
-  winUpdateRgnRootless (pWin);
-  
-  return fResult;
-}
-
-
-#ifdef SHAPE
-void
-winSetShapeRootless (WindowPtr pWin)
-{
-  ScreenPtr		pScreen = pWin->drawable.pScreen;
-  winWindowPriv(pWin);
-  winScreenPriv(pScreen);
-
-#if CYGDEBUG
-  winTrace ("winSetShapeRootless (%p)\n", pWin);
-#endif
-
-  WIN_UNWRAP(SetShape); 
-  (*pScreen->SetShape)(pWin);
-  WIN_WRAP(SetShape, winSetShapeRootless);
-  
-  winReshapeRootless (pWin);
-  winUpdateRgnRootless (pWin);
-  
-  return;
-}
-#endif
-
-
-/*
- * Local function for adding a region to the Windows window region
- */
-
-static
-int
-winAddRgn (WindowPtr pWin, pointer data)
-{
-  int		iX, iY, iWidth, iHeight, iBorder;
-  HRGN		hRgn = *(HRGN*)data;
-  HRGN		hRgnWin;
-  winWindowPriv(pWin);
-  
-  /* If pWin is not Root */
-  if (pWin->parent != NULL) 
-    {
-#if CYGDEBUG
-      winDebug ("winAddRgn ()\n");
-#endif
-      if (pWin->mapped)
-	{
-	  iBorder = wBorderWidth (pWin);
-	  
-	  iX = pWin->drawable.x - iBorder;
-	  iY = pWin->drawable.y - iBorder;
-	  
-	  iWidth = pWin->drawable.width + iBorder * 2;
-	  iHeight = pWin->drawable.height + iBorder * 2;
-	  
-	  hRgnWin = CreateRectRgn (0, 0, iWidth, iHeight);
-	  
-	  if (hRgnWin == NULL)
-	    {
-	      ErrorF ("winAddRgn - CreateRectRgn () failed\n");
-	      ErrorF ("  Rect %d %d %d %d\n",
-		      iX, iY, iX + iWidth, iY + iHeight);
-	    }
-	  
-	  if (pWinPriv->hRgn)
-	    {
-	      if (CombineRgn (hRgnWin, hRgnWin, pWinPriv->hRgn, RGN_AND)
-		  == ERROR)
-		{
-		  ErrorF ("winAddRgn - CombineRgn () failed\n");
-		}
-	    }
-	  
-	  OffsetRgn (hRgnWin, iX, iY);
-
-	  if (CombineRgn (hRgn, hRgn, hRgnWin, RGN_OR) == ERROR)
-	    {
-	      ErrorF ("winAddRgn - CombineRgn () failed\n");
-	    }
-	  
-	  DeleteObject (hRgnWin);
-	}
-      return WT_DONTWALKCHILDREN;
-    }
-  else
-    {
-      return WT_WALKCHILDREN;
-    }
-}
-
-
-/*
- * Local function to update the Windows window's region
- */
-
-static
-void
-winUpdateRgnRootless (WindowPtr pWin)
-{
-  HRGN		hRgn = CreateRectRgn (0, 0, 0, 0);
-  
-  if (hRgn != NULL)
-    {
-      WalkTree (pWin->drawable.pScreen, winAddRgn, &hRgn);
-      SetWindowRgn (winGetScreenPriv(pWin->drawable.pScreen)->hwndScreen,
-		    hRgn, TRUE);
-    }
-  else
-    {
-      ErrorF ("winUpdateRgnRootless - CreateRectRgn failed.\n");
-    }
-}
-
-
-#ifdef SHAPE
-static
-void
-winReshapeRootless (WindowPtr pWin)
-{
-  int		nRects;
-  /* ScreenPtr	pScreen = pWin->drawable.pScreen;*/
-  RegionRec	rrNewShape;
-  BoxPtr	pShape, pRects, pEnd;
-  HRGN		hRgn, hRgnRect;
-  winWindowPriv(pWin);
-
-#if CYGDEBUG
-  winDebug ("winReshapeRootless ()\n");
-#endif
-
-  /* Bail if the window is the root window */
-  if (pWin->parent == NULL)
-    return;
-
-  /* Bail if the window is not top level */
-  if (pWin->parent->parent != NULL)
-    return;
-
-  /* Free any existing window region stored in the window privates */
-  if (pWinPriv->hRgn != NULL)
-    {
-      DeleteObject (pWinPriv->hRgn);
-      pWinPriv->hRgn = NULL;
-    }
-  
-  /* Bail if the window has no bounding region defined */
-  if (!wBoundingShape (pWin))
-    return;
-
-  REGION_NULL(pScreen, &rrNewShape);
-  REGION_COPY(pScreen, &rrNewShape, wBoundingShape(pWin));
-  REGION_TRANSLATE(pScreen, &rrNewShape, pWin->borderWidth,
-                   pWin->borderWidth);
-  
-  nRects = REGION_NUM_RECTS(&rrNewShape);
-  pShape = REGION_RECTS(&rrNewShape);
-  
-  if (nRects > 0)
-    {
-      /* Create initial empty Windows region */
-      hRgn = CreateRectRgn (0, 0, 0, 0);
-
-      /* Loop through all rectangles in the X region */
-      for (pRects = pShape, pEnd = pShape + nRects; pRects < pEnd; pRects++)
-        {
-	  /* Create a Windows region for the X rectangle */
-	  hRgnRect = CreateRectRgn (pRects->x1, pRects->y1,
-				    pRects->x2, pRects->y2);
-	  if (hRgnRect == NULL)
-	    {
-	      ErrorF("winReshapeRootless - CreateRectRgn() failed\n");
-	    }
-
-	  /* Merge the Windows region with the accumulated region */
-	  if (CombineRgn (hRgn, hRgn, hRgnRect, RGN_OR) == ERROR)
-	    {
-	      ErrorF("winReshapeRootless - CombineRgn() failed\n");
-	    }
-
-	  /* Delete the temporary Windows region */
-	  DeleteObject (hRgnRect);
-        }
-      
-      /* Save a handle to the composite region in the window privates */
-      pWinPriv->hRgn = hRgn;
-    }
-
-  REGION_UNINIT(pScreen, &rrNewShape);
-  
-  return;
-}
-#endif
diff --git a/hw/xwin/winwindow.h b/hw/xwin/winwindow.h
deleted file mode 100644
index 9c49d64..0000000
--- a/hw/xwin/winwindow.h
+++ /dev/null
@@ -1,150 +0,0 @@
-#if !defined(_WINWINDOW_H_)
-#define _WINWINDOW_H_
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Kensuke Matsuzaki
- */
-
-#ifndef NO
-#define NO			0
-#endif
-#ifndef YES
-#define YES			1
-#endif
-
-/* Constant strings */
-#ifndef PROJECT_NAME
-#  define PROJECT_NAME		"Cygwin/X"
-#endif
-#define WINDOW_CLASS		"cygwin/x"
-#define WINDOW_TITLE		PROJECT_NAME " - %s:%d"
-#define WINDOW_TITLE_XDMCP	PROJECT_NAME " - %s"
-#define WIN_SCR_PROP		"cyg_screen_prop rl"
-#define WINDOW_CLASS_X		"cygwin/x X rl"
-#define WINDOW_TITLE_X		PROJECT_NAME " X"
-#define WIN_WINDOW_PROP		"cyg_window_prop_rl"
-#ifdef HAS_DEVWINDOWS
-# define WIN_MSG_QUEUE_FNAME	"/dev/windows"
-#endif
-#define WIN_WID_PROP		"cyg_wid_prop_rl"
-#define WIN_NEEDMANAGE_PROP	"cyg_override_redirect_prop_rl"
-#ifndef CYGMULTIWINDOW_DEBUG
-#define CYGMULTIWINDOW_DEBUG    NO
-#endif
-#ifndef CYGWINDOWING_DEBUG
-#define CYGWINDOWING_DEBUG	NO
-#endif
-
-typedef struct _winPrivScreenRec *winPrivScreenPtr;
-
-
-/*
- * Window privates
- */
-
-typedef struct
-{
-  DWORD			dwDummy;
-  HRGN			hRgn;
-  HWND			hWnd;
-  winPrivScreenPtr	pScreenPriv;
-  Bool			fXKilled;
-
-  /* Privates used by primary fb DirectDraw server */
-  LPDDSURFACEDESC	pddsdPrimary;
-
-  /* Privates used by shadow fb DirectDraw Nonlocking server */
-  LPDIRECTDRAWSURFACE4	pddsPrimary4;
-
-  /* Privates used by both shadow fb DirectDraw servers */
-  LPDIRECTDRAWCLIPPER	pddcPrimary;
-} winPrivWinRec, *winPrivWinPtr;
-
-#ifdef XWIN_MULTIWINDOW
-typedef struct _winWMMessageRec{
-  DWORD			dwID;
-  DWORD			msg;
-  int			iWindow;
-  HWND			hwndWindow;
-  int			iX, iY;
-  int			iWidth, iHeight;
-} winWMMessageRec, *winWMMessagePtr;
-
-
-/*
- * winmultiwindowwm.c
- */
-
-#define		WM_WM_MOVE		(WM_USER + 1)
-#define		WM_WM_SIZE		(WM_USER + 2)
-#define		WM_WM_RAISE		(WM_USER + 3)
-#define		WM_WM_LOWER		(WM_USER + 4)
-#define		WM_WM_MAP		(WM_USER + 5)
-#define		WM_WM_UNMAP		(WM_USER + 6)
-#define		WM_WM_KILL		(WM_USER + 7)
-#define		WM_WM_ACTIVATE		(WM_USER + 8)
-#define		WM_WM_NAME_EVENT	(WM_USER + 9)
-#define		WM_WM_HINTS_EVENT	(WM_USER + 10)
-#define		WM_WM_CHANGE_STATE	(WM_USER + 11)
-#define		WM_MANAGE		(WM_USER + 100)
-#define		WM_UNMANAGE		(WM_USER + 102)
-
-void
-winSendMessageToWM (void *pWMInfo, winWMMessagePtr msg);
-
-Bool
-winInitWM (void **ppWMInfo,
-	   pthread_t *ptWMProc,
-	   pthread_t *ptXMsgProc,
-	   pthread_mutex_t *ppmServerStarted,
-	   int dwScreen,
-	   HWND hwndScreen,
-	   BOOL allowOtherWM);
-
-void
-winDeinitMultiWindowWM (void);
-
-void
-winMinimizeWindow (Window id);
-
-
-/*
- * winmultiwindowicons.c
- */
-
-void
-winUpdateIcon (Window id);
-
-void 
-winInitGlobalIcons (void);
-
-void 
-winDestroyIcon(HICON hIcon);
-
-#endif /* XWIN_MULTIWINDOW */
-#endif
diff --git a/hw/xwin/winwindowswm.c b/hw/xwin/winwindowswm.c
deleted file mode 100755
index e1994de..0000000
--- a/hw/xwin/winwindowswm.c
+++ /dev/null
@@ -1,663 +0,0 @@
-/* WindowsWM extension is based on AppleWM extension */
-/**************************************************************************
-
-Copyright (c) 2002 Apple Computer, Inc. All Rights Reserved.
-Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
-
-Permission is hereby granted, free of charge, to any person obtaining a
-copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sub license, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice (including the
-next paragraph) shall be included in all copies or substantial portions
-of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
-IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
-ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-**************************************************************************/
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-
-#define NEED_REPLIES
-#define NEED_EVENTS
-#include "misc.h"
-#include "dixstruct.h"
-#include "extnsionst.h"
-#include "colormapst.h"
-#include "cursorstr.h"
-#include "scrnintstr.h"
-#include "servermd.h"
-#include "swaprep.h"
-#define _WINDOWSWM_SERVER_
-#include "windowswmstr.h"
-
-static int WMErrorBase;
-
-static DISPATCH_PROC(ProcWindowsWMDispatch);
-static DISPATCH_PROC(SProcWindowsWMDispatch);
-
-static void WindowsWMResetProc(ExtensionEntry* extEntry);
-
-static unsigned char WMReqCode = 0;
-static int WMEventBase = 0;
-
-static RESTYPE ClientType, EventType; /* resource types for event masks */
-static XID eventResource;
-
-/* Currently selected events */
-static unsigned int eventMask = 0;
-
-static int WMFreeClient (pointer data, XID id);
-static int WMFreeEvents (pointer data, XID id);
-static void SNotifyEvent(xWindowsWMNotifyEvent *from, xWindowsWMNotifyEvent *to);
-
-typedef struct _WMEvent *WMEventPtr;
-typedef struct _WMEvent {
-  WMEventPtr      next;
-  ClientPtr	    client;
-  XID		    clientResource;
-  unsigned int    mask;
-} WMEventRec;
-
-static inline BoxRec
-make_box (int x, int y, int w, int h)
-{
-  BoxRec r;
-  r.x1 = x;
-  r.y1 = y;
-  r.x2 = x + w;
-  r.y2 = y + h;
-  return r;
-}
-
-void
-winWindowsWMExtensionInit ()
-{
-  ExtensionEntry* extEntry;
-
-  ClientType = CreateNewResourceType(WMFreeClient);
-  EventType = CreateNewResourceType(WMFreeEvents);
-  eventResource = FakeClientID(0);
-
-  if (ClientType && EventType &&
-      (extEntry = AddExtension(WINDOWSWMNAME,
-			       WindowsWMNumberEvents,
-			       WindowsWMNumberErrors,
-			       ProcWindowsWMDispatch,
-			       SProcWindowsWMDispatch,
-			       WindowsWMResetProc,
-			       StandardMinorOpcode)))
-    {
-      WMReqCode = (unsigned char)extEntry->base;
-      WMErrorBase = extEntry->errorBase;
-      WMEventBase = extEntry->eventBase;
-      EventSwapVector[WMEventBase] = (EventSwapPtr) SNotifyEvent;
-    }
-}
-
-/*ARGSUSED*/
-static void
-WindowsWMResetProc (ExtensionEntry* extEntry)
-{
-}
-
-static int
-ProcWindowsWMQueryVersion(register ClientPtr client)
-{
-  xWindowsWMQueryVersionReply rep;
-  register int n;
-
-  REQUEST_SIZE_MATCH(xWindowsWMQueryVersionReq);
-  rep.type = X_Reply;
-  rep.length = 0;
-  rep.sequenceNumber = client->sequence;
-  rep.majorVersion = WINDOWS_WM_MAJOR_VERSION;
-  rep.minorVersion = WINDOWS_WM_MINOR_VERSION;
-  rep.patchVersion = WINDOWS_WM_PATCH_VERSION;
-  if (client->swapped)
-    {
-      swaps(&rep.sequenceNumber, n);
-      swapl(&rep.length, n);
-    }
-  WriteToClient(client, sizeof(xWindowsWMQueryVersionReply), (char *)&rep);
-  return (client->noClientException);
-}
-
-
-/* events */
-
-static inline void
-updateEventMask (WMEventPtr *pHead)
-{
-  WMEventPtr pCur;
-
-  eventMask = 0;
-  for (pCur = *pHead; pCur != NULL; pCur = pCur->next)
-    eventMask |= pCur->mask;
-}
-
-/*ARGSUSED*/
-static int
-WMFreeClient (pointer data, XID id)
-{
-  WMEventPtr   pEvent;
-  WMEventPtr   *pHead, pCur, pPrev;
-
-  pEvent = (WMEventPtr) data;
-  pHead = (WMEventPtr *) LookupIDByType(eventResource, EventType);
-  if (pHead)
-    {
-      pPrev = 0;
-      for (pCur = *pHead; pCur && pCur != pEvent; pCur=pCur->next)
-	pPrev = pCur;
-      if (pCur)
-	{
-	  if (pPrev)
-	    pPrev->next = pEvent->next;
-	  else
-	    *pHead = pEvent->next;
-	}
-      updateEventMask (pHead);
-    }
-  xfree ((pointer) pEvent);
-  return 1;
-}
-
-/*ARGSUSED*/
-static int
-WMFreeEvents (pointer data, XID id)
-{
-  WMEventPtr   *pHead, pCur, pNext;
-  
-  pHead = (WMEventPtr *) data;
-  for (pCur = *pHead; pCur; pCur = pNext)
-    {
-      pNext = pCur->next;
-      FreeResource (pCur->clientResource, ClientType);
-      xfree ((pointer) pCur);
-    }
-  xfree ((pointer) pHead);
-  eventMask = 0;
-  return 1;
-}
-
-static int
-ProcWindowsWMSelectInput (register ClientPtr client)
-{
-  REQUEST(xWindowsWMSelectInputReq);
-  WMEventPtr		pEvent, pNewEvent, *pHead;
-  XID			clientResource;
-
-  REQUEST_SIZE_MATCH (xWindowsWMSelectInputReq);
-  pHead = (WMEventPtr *)SecurityLookupIDByType(client, eventResource,
-					       EventType, DixWriteAccess);
-  if (stuff->mask != 0)
-    {
-      if (pHead)
-	{
-	  /* check for existing entry. */
-	  for (pEvent = *pHead; pEvent; pEvent = pEvent->next)
-	    {
-	      if (pEvent->client == client)
-		{
-		  pEvent->mask = stuff->mask;
-		  updateEventMask (pHead);
-		  return Success;
-		}
-	    }
-	}
-      
-      /* build the entry */
-      pNewEvent = (WMEventPtr) xalloc (sizeof (WMEventRec));
-      if (!pNewEvent)
-	return BadAlloc;
-      pNewEvent->next = 0;
-      pNewEvent->client = client;
-      pNewEvent->mask = stuff->mask;
-      /*
-       * add a resource that will be deleted when
-       * the client goes away
-       */
-      clientResource = FakeClientID (client->index);
-      pNewEvent->clientResource = clientResource;
-      if (!AddResource (clientResource, ClientType, (pointer)pNewEvent))
-	return BadAlloc;
-      /*
-       * create a resource to contain a pointer to the list
-       * of clients selecting input.  This must be indirect as
-       * the list may be arbitrarily rearranged which cannot be
-       * done through the resource database.
-       */
-      if (!pHead)
-	{
-	  pHead = (WMEventPtr *) xalloc (sizeof (WMEventPtr));
-	  if (!pHead ||
-	      !AddResource (eventResource, EventType, (pointer)pHead))
-	    {
-	      FreeResource (clientResource, RT_NONE);
-	      return BadAlloc;
-	    }
-	  *pHead = 0;
-	}
-      pNewEvent->next = *pHead;
-      *pHead = pNewEvent;
-      updateEventMask (pHead);
-    }
-  else if (stuff->mask == 0)
-    {
-      /* delete the interest */
-      if (pHead)
-	{
-	  pNewEvent = 0;
-	  for (pEvent = *pHead; pEvent; pEvent = pEvent->next)
-	    {
-	      if (pEvent->client == client)
-		break;
-	      pNewEvent = pEvent;
-	    }
-	  if (pEvent)
-	    {
-	      FreeResource (pEvent->clientResource, ClientType);
-	      if (pNewEvent)
-		pNewEvent->next = pEvent->next;
-	      else
-		*pHead = pEvent->next;
-	      xfree (pEvent);
-	      updateEventMask (pHead);
-	    }
-	}
-    }
-  else
-    {
-      client->errorValue = stuff->mask;
-      return BadValue;
-    }
-  return Success;
-}
-
-/*
- * deliver the event
- */
-
-void
-winWindowsWMSendEvent (int type, unsigned int mask, int which, int arg,
-		       Window window, int x, int y, int w, int h)
-{
-  WMEventPtr		*pHead, pEvent;
-  ClientPtr		client;
-  xWindowsWMNotifyEvent se;
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("winWindowsWMSendEvent %d %d %d %d,  %d %d - %d %d\n",
-	  type, mask, which, arg, x, y, w, h);
-#endif
-  pHead = (WMEventPtr *) LookupIDByType(eventResource, EventType);
-  if (!pHead)
-    return;
-  for (pEvent = *pHead; pEvent; pEvent = pEvent->next)
-    {
-      client = pEvent->client;
-#if CYGMULTIWINDOW_DEBUG
-      ErrorF ("winWindowsWMSendEvent - x%08x\n", (int) client);
-#endif
-      if ((pEvent->mask & mask) == 0
-	  || client == serverClient || client->clientGone)
-	{
-	  continue;
-	}
-#if CYGMULTIWINDOW_DEBUG 
-      ErrorF ("winWindowsWMSendEvent - send\n");
-#endif
-      se.type = type + WMEventBase;
-      se.kind = which;
-      se.window = window;
-      se.arg = arg;
-      se.x = x;
-      se.y = y;
-      se.w = w;
-      se.h = h;
-      se.sequenceNumber = client->sequence;
-      se.time = currentTime.milliseconds;
-      WriteEventsToClient (client, 1, (xEvent *) &se);
-    }
-}
-
-/* Safe to call from any thread. */
-unsigned int
-WindowsWMSelectedEvents (void)
-{
-  return eventMask;
-}
-
-
-/* general utility functions */
-
-static int
-ProcWindowsWMDisableUpdate (register ClientPtr client)
-{
-  REQUEST_SIZE_MATCH(xWindowsWMDisableUpdateReq);
-
-  //winDisableUpdate();
-
-  return (client->noClientException);
-}
-
-static int
-ProcWindowsWMReenableUpdate (register ClientPtr client)
-{
-  REQUEST_SIZE_MATCH(xWindowsWMReenableUpdateReq);
-
-  //winEnableUpdate(); 
-
-  return (client->noClientException);
-}
-
-
-/* window functions */
-
-static int
-ProcWindowsWMSetFrontProcess (register ClientPtr client)
-{
-  REQUEST_SIZE_MATCH(xWindowsWMSetFrontProcessReq);
-  
-  //QuartzMessageMainThread(kWindowsSetFrontProcess, NULL, 0);
-  
-  return (client->noClientException);
-}
-
-
-/* frame functions */
-
-static int
-ProcWindowsWMFrameGetRect (register ClientPtr client)
-{
-  xWindowsWMFrameGetRectReply rep;
-  BoxRec ir;
-  RECT rcNew;
-  REQUEST(xWindowsWMFrameGetRectReq);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameGetRect %d %d\n",
-	  (sizeof(xWindowsWMFrameGetRectReq) >> 2), (int) client->req_len);
-#endif
-  
-  REQUEST_SIZE_MATCH(xWindowsWMFrameGetRectReq);
-  rep.type = X_Reply;
-  rep.length = 0;
-  rep.sequenceNumber = client->sequence;
-
-  ir = make_box (stuff->ix, stuff->iy, stuff->iw, stuff->ih);
-
-  if (stuff->frame_rect != 0)
-    {
-      ErrorF ("ProcWindowsWMFrameGetRect - stuff->frame_rect != 0\n");
-      return BadValue;
-    }
-
-  /* Store the origin, height, and width in a rectangle structure */
-  SetRect (&rcNew, stuff->ix, stuff->iy,
-	   stuff->ix + stuff->iw, stuff->iy + stuff->ih);
-    
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameGetRect - %d %d %d %d\n",
-	  stuff->ix, stuff->iy, stuff->ix + stuff->iw, stuff->iy + stuff->ih);
-#endif
-
-  /*
-   * Calculate the required size of the Windows window rectangle,
-   * given the size of the Windows window client area.
-   */
-  AdjustWindowRectEx (&rcNew, stuff->frame_style, FALSE, stuff->frame_style_ex);
-  rep.x = rcNew.left;
-  rep.y = rcNew.top;
-  rep.w = rcNew.right - rcNew.left;
-  rep.h = rcNew.bottom - rcNew.top;
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameGetRect - %d %d %d %d\n",
-	  rep.x, rep.y, rep.w, rep.h);
-#endif
-
-  WriteToClient(client, sizeof(xWindowsWMFrameGetRectReply), (char *)&rep);
-  return (client->noClientException);
-}
-
-
-static int
-ProcWindowsWMFrameDraw (register ClientPtr client)
-{
-  REQUEST(xWindowsWMFrameDrawReq);
-  WindowPtr pWin;
-  win32RootlessWindowPtr pRLWinPriv;
-  RECT rcNew;
-  int nCmdShow, rc;
-  RegionRec newShape;
-  ScreenPtr pScreen;
-
-  REQUEST_SIZE_MATCH (xWindowsWMFrameDrawReq);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameDraw\n");
-#endif
-  rc = dixLookupWindow(&pWin, stuff->window, client, DixReadAccess);
-  if (rc != Success)
-      return rc;
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameDraw - Window found\n");
-#endif
-
-  pRLWinPriv = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, TRUE);
-  if (pRLWinPriv == 0) return BadWindow;
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameDraw - HWND 0x%08x 0x%08x 0x%08x\n",
-	  (int) pRLWinPriv->hWnd, (int) stuff->frame_style,
-	  (int) stuff->frame_style_ex);
-  ErrorF ("ProcWindowsWMFrameDraw - %d %d %d %d\n",
-	  stuff->ix, stuff->iy, stuff->iw, stuff->ih);
-#endif
-
-  /* Store the origin, height, and width in a rectangle structure */
-  SetRect (&rcNew, stuff->ix, stuff->iy,
-	   stuff->ix + stuff->iw, stuff->iy + stuff->ih);
-
-  /*
-   * Calculate the required size of the Windows window rectangle,
-   * given the size of the Windows window client area.
-   */
-  AdjustWindowRectEx (&rcNew, stuff->frame_style, FALSE, stuff->frame_style_ex);
-  
-  /* Set the window extended style flags */
-  if (!SetWindowLongPtr (pRLWinPriv->hWnd, GWL_EXSTYLE, stuff->frame_style_ex))
-    {
-      return BadValue;
-    }
-
-  /* Set the window standard style flags */
-  if (!SetWindowLongPtr (pRLWinPriv->hWnd, GWL_STYLE, stuff->frame_style))
-    {
-      return BadValue;
-    }
-
-  /* Flush the window style */
-  if (!SetWindowPos (pRLWinPriv->hWnd, NULL,
-		     rcNew.left, rcNew.top,
-		     rcNew.right - rcNew.left, rcNew.bottom - rcNew.top,
-		     SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE))
-    {
-      return BadValue;
-    }
-  if (!IsWindowVisible(pRLWinPriv->hWnd))
-    nCmdShow = SW_HIDE;
-  else 
-    nCmdShow = SW_SHOWNA;
-
-  ShowWindow (pRLWinPriv->hWnd, nCmdShow);
-
-  winMWExtWMUpdateIcon (pWin->drawable.id);
-
-  if (wBoundingShape(pWin) != NULL)
-    {
-      pScreen = pWin->drawable.pScreen;
-      /* wBoundingShape is relative to *inner* origin of window.
-	 Translate by borderWidth to get the outside-relative position. */
-      
-      REGION_NULL(pScreen, &newShape);
-      REGION_COPY(pScreen, &newShape, wBoundingShape(pWin));
-      REGION_TRANSLATE(pScreen, &newShape, pWin->borderWidth, pWin->borderWidth);
-      winMWExtWMReshapeFrame (pRLWinPriv, &newShape);
-      REGION_UNINIT(pScreen, &newShape);
-    }
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameDraw - done\n");
-#endif
-
-  return (client->noClientException);
-}
-
-static int
-ProcWindowsWMFrameSetTitle(
-			   register ClientPtr client
-			   )
-{
-  unsigned int title_length, title_max;
-  unsigned char *title_bytes;
-  REQUEST(xWindowsWMFrameSetTitleReq);
-  WindowPtr pWin;
-  win32RootlessWindowPtr pRLWinPriv;
-  int rc;
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameSetTitle\n");
-#endif
-
-  REQUEST_AT_LEAST_SIZE(xWindowsWMFrameSetTitleReq);
-
-  rc = dixLookupWindow(&pWin, stuff->window, client, DixReadAccess);
-  if (rc != Success)
-      return rc;
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameSetTitle - Window found\n");
-#endif
-
-  title_length = stuff->title_length;
-  title_max = (stuff->length << 2) - sizeof(xWindowsWMFrameSetTitleReq);
-
-  if (title_max < title_length)
-    return BadValue;
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameSetTitle - length is valid\n");
-#endif
-
-  title_bytes = malloc (title_length+1);
-  strncpy (title_bytes, (unsigned char *) &stuff[1], title_length);
-  title_bytes[title_length] = '\0';
-
-  pRLWinPriv = (win32RootlessWindowPtr) RootlessFrameForWindow (pWin, FALSE);
-
-  if (pRLWinPriv == 0)
-    {
-      free (title_bytes);
-      return BadWindow;
-    }
-    
-  /* Flush the window style */
-  SetWindowText (pRLWinPriv->hWnd, title_bytes);
-
-  free (title_bytes);
-
-#if CYGMULTIWINDOW_DEBUG
-  ErrorF ("ProcWindowsWMFrameSetTitle - done\n");
-#endif
-
-  return (client->noClientException);
-}
-
-
-/* dispatch */
-
-static int
-ProcWindowsWMDispatch (register ClientPtr client)
-{
-  REQUEST(xReq);
-
-  switch (stuff->data)
-    {
-    case X_WindowsWMQueryVersion:
-      return ProcWindowsWMQueryVersion(client);
-    }
-
-  if (!LocalClient(client))
-    return WMErrorBase + WindowsWMClientNotLocal;
-
-  switch (stuff->data)
-    {
-    case X_WindowsWMSelectInput:
-      return ProcWindowsWMSelectInput(client);
-    case X_WindowsWMDisableUpdate:
-      return ProcWindowsWMDisableUpdate(client);
-    case X_WindowsWMReenableUpdate:
-      return ProcWindowsWMReenableUpdate(client);
-    case X_WindowsWMSetFrontProcess:
-      return ProcWindowsWMSetFrontProcess(client);
-    case X_WindowsWMFrameGetRect:
-      return ProcWindowsWMFrameGetRect(client);
-    case X_WindowsWMFrameDraw:
-      return ProcWindowsWMFrameDraw(client);
-    case X_WindowsWMFrameSetTitle:
-      return ProcWindowsWMFrameSetTitle(client);
-    default:
-      return BadRequest;
-    }
-}
-
-static void
-SNotifyEvent (xWindowsWMNotifyEvent *from, xWindowsWMNotifyEvent *to)
-{
-  to->type = from->type;
-  to->kind = from->kind;
-  cpswaps (from->sequenceNumber, to->sequenceNumber);
-  cpswapl (from->window, to->window);
-  cpswapl (from->time, to->time);
-  cpswapl (from->arg, to->arg);
-}
-
-static int
-SProcWindowsWMQueryVersion (register ClientPtr client)
-{
-  register int n;
-  REQUEST(xWindowsWMQueryVersionReq);
-  swaps(&stuff->length, n);
-  return ProcWindowsWMQueryVersion(client);
-}
-
-static int
-SProcWindowsWMDispatch (register ClientPtr client)
-{
-  REQUEST(xReq);
-
-  /* It is bound to be non-local when there is byte swapping */
-  if (!LocalClient(client))
-    return WMErrorBase + WindowsWMClientNotLocal;
-
-  /* only local clients are allowed WM access */
-  switch (stuff->data)
-    {
-    case X_WindowsWMQueryVersion:
-      return SProcWindowsWMQueryVersion(client);
-    default:
-      return BadRequest;
-    }
-}
diff --git a/hw/xwin/winwndproc.c b/hw/xwin/winwndproc.c
deleted file mode 100644
index 29ea81f..0000000
--- a/hw/xwin/winwndproc.c
+++ /dev/null
@@ -1,1288 +0,0 @@
-/*
- *Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
- *
- *Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- *"Software"), to deal in the Software without restriction, including
- *without limitation the rights to use, copy, modify, merge, publish,
- *distribute, sublicense, and/or sell copies of the Software, and to
- *permit persons to whom the Software is furnished to do so, subject to
- *the following conditions:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
- *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- *Except as contained in this notice, the name of the XFree86 Project
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from the XFree86 Project.
- *
- * Authors:	Dakshinamurthy Karra
- *		Suhaib M Siddiqi
- *		Peter Busch
- *		Harold L Hunt II
- *		MATSUZAKI Kensuke
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include <commctrl.h>
-#include "winprefs.h"
-#include "winconfig.h"
-#include "winmsg.h"
-#include "inputstr.h"
-
-#ifdef XKB
-extern BOOL winCheckKeyPressed(WPARAM wParam, LPARAM lParam);
-#endif
-extern void winFixShiftKeys (int iScanCode);
-
-
-/*
- * Global variables
- */
-
-Bool				g_fCursor = TRUE;
-Bool				g_fButton[3] = { FALSE, FALSE, FALSE };
-
-
-/*
- * References to external symbols
- */
-
-extern Bool			g_fClipboard;
-extern HWND			g_hDlgDepthChange;
-extern Bool			g_fKeyboardHookLL;
-extern HWND			g_hwndKeyboardFocus;
-extern Bool			g_fSoftwareCursor;
-extern DWORD			g_dwCurrentThreadID;
-
-
-/*
- * Called by winWakeupHandler
- * Processes current Windows message
- */
-
-LRESULT CALLBACK
-winWindowProc (HWND hwnd, UINT message, 
-	       WPARAM wParam, LPARAM lParam)
-{
-  static winPrivScreenPtr	s_pScreenPriv = NULL;
-  static winScreenInfo		*s_pScreenInfo = NULL;
-  static ScreenPtr		s_pScreen = NULL;
-  static HWND			s_hwndLastPrivates = NULL;
-  static HINSTANCE		s_hInstance;
-  static Bool			s_fTracking = FALSE;
-  static unsigned long		s_ulServerGeneration = 0;
-  static UINT			s_uTaskbarRestart = 0;
-  int				iScanCode;
-  int				i;
-
-#if CYGDEBUG
-  winDebugWin32Message("winWindowProc", hwnd, message, wParam, lParam);
-#endif
-  
-  /* Watch for server regeneration */
-  if (g_ulServerGeneration != s_ulServerGeneration)
-    {
-      /* Store new server generation */
-      s_ulServerGeneration = g_ulServerGeneration;
-    }
-
-  /* Only retrieve new privates pointers if window handle is null or changed */
-  if ((s_pScreenPriv == NULL || hwnd != s_hwndLastPrivates)
-      && (s_pScreenPriv = GetProp (hwnd, WIN_SCR_PROP)) != NULL)
-    {
-#if CYGDEBUG
-      winDebug ("winWindowProc - Setting privates handle\n");
-#endif
-      s_pScreenInfo = s_pScreenPriv->pScreenInfo;
-      s_pScreen = s_pScreenInfo->pScreen;
-      s_hwndLastPrivates = hwnd;
-    }
-  else if (s_pScreenPriv == NULL)
-    {
-      /* For safety, handle case that should never happen */
-      s_pScreenInfo = NULL;
-      s_pScreen = NULL;
-      s_hwndLastPrivates = NULL;
-    }
-
-  /* Branch on message type */
-  switch (message)
-    {
-    case WM_TRAYICON:
-      return winHandleIconMessage (hwnd, message, wParam, lParam,
-				   s_pScreenPriv);
-
-    case WM_CREATE:
-#if CYGDEBUG
-      winDebug ("winWindowProc - WM_CREATE\n");
-#endif
-      
-      /*
-       * Add a property to our display window that references
-       * this screens' privates.
-       *
-       * This allows the window procedure to refer to the
-       * appropriate window DC and shadow DC for the window that
-       * it is processing.  We use this to repaint exposed
-       * areas of our display window.
-       */
-      s_pScreenPriv = ((LPCREATESTRUCT) lParam)->lpCreateParams;
-      s_hInstance = ((LPCREATESTRUCT) lParam)->hInstance;
-      s_pScreenInfo = s_pScreenPriv->pScreenInfo;
-      s_pScreen = s_pScreenInfo->pScreen;
-      s_hwndLastPrivates = hwnd;
-      s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
-      SetProp (hwnd, WIN_SCR_PROP, s_pScreenPriv);
-
-      /* Setup tray icon */
-      if (!s_pScreenInfo->fNoTrayIcon)
-	{
-	  /*
-	   * NOTE: The WM_CREATE message is processed before CreateWindowEx
-	   * returns, so s_pScreenPriv->hwndScreen is invalid at this point.
-	   * We go ahead and copy our hwnd parameter over top of the screen
-	   * privates hwndScreen so that we have a valid value for
-	   * that member.  Otherwise, the tray icon will disappear
-	   * the first time you move the mouse over top of it.
-	   */
-	  
-	  s_pScreenPriv->hwndScreen = hwnd;
-
-	  winInitNotifyIcon (s_pScreenPriv);
-	}
-      return 0;
-
-    case WM_DISPLAYCHANGE:
-      /* We cannot handle a display mode change during initialization */
-      if (s_pScreenInfo == NULL)
-	FatalError ("winWindowProc - WM_DISPLAYCHANGE - The display "
-		    "mode changed while we were intializing.  This is "
-		    "very bad and unexpected.  Exiting.\n");
-
-      /*
-       * We do not care about display changes with
-       * fullscreen DirectDraw engines, because those engines set
-       * their own mode when they become active.
-       */
-      if (s_pScreenInfo->fFullScreen
-	  && (s_pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
-	      || s_pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL
-#ifdef XWIN_PRIMARYFB
-	      || s_pScreenInfo->dwEngine == WIN_SERVER_PRIMARY_DD
-#endif
-	      ))
-	{
-	  /* 
-	   * Store the new display dimensions and depth.
-	   * We do this here for future compatibility in case we
-	   * ever allow switching from fullscreen to windowed mode.
-	   */
-	  s_pScreenPriv->dwLastWindowsWidth = GetSystemMetrics (SM_CXSCREEN);
-	  s_pScreenPriv->dwLastWindowsHeight = GetSystemMetrics (SM_CYSCREEN);
-	  s_pScreenPriv->dwLastWindowsBitsPixel
-	    = GetDeviceCaps (s_pScreenPriv->hdcScreen, BITSPIXEL);	  
-	  break;
-	}
-      
-      ErrorF ("winWindowProc - WM_DISPLAYCHANGE - orig bpp: %d, last bpp: %d, "
-	      "new bpp: %d\n",
-	      (int) s_pScreenInfo->dwBPP,
-	      (int) s_pScreenPriv->dwLastWindowsBitsPixel,
-	      wParam);
-
-      ErrorF ("winWindowProc - WM_DISPLAYCHANGE - new width: %d "
-	      "new height: %d\n",
-	      LOWORD (lParam), HIWORD (lParam));
-
-      /*
-       * TrueColor --> TrueColor depth changes are disruptive for:
-       *	Windowed:
-       *		Shadow DirectDraw
-       *		Shadow DirectDraw Non-Locking
-       *		Primary DirectDraw
-       *
-       * TrueColor --> TrueColor depth changes are non-optimal for:
-       *	Windowed:
-       *		Shadow GDI
-       *
-       *	FullScreen:
-       *		Shadow GDI
-       *
-       * TrueColor --> PseudoColor or vice versa are disruptive for:
-       *	Windowed:
-       *		Shadow DirectDraw
-       *		Shadow DirectDraw Non-Locking
-       *		Primary DirectDraw
-       *		Shadow GDI
-       */
-
-      /*
-       * Check for a disruptive change in depth.
-       * We can only display a message for a disruptive depth change,
-       * we cannot do anything to correct the situation.
-       */
-      if ((s_pScreenInfo->dwBPP != wParam)
-	  && (s_pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
-	      || s_pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL
-#ifdef XWIN_PRIMARYFB
-	      || s_pScreenInfo->dwEngine == WIN_SERVER_PRIMARY_DD
-#endif
-	      ))
-	{
-	  /* Cannot display the visual until the depth is restored */
-	  ErrorF ("winWindowProc - Disruptive change in depth\n");
-
-	  /* Display Exit dialog */
-	  winDisplayDepthChangeDialog (s_pScreenPriv);
-
-	  /* Flag that we have an invalid screen depth */
-	  s_pScreenPriv->fBadDepth = TRUE;
-
-	  /* Minimize the display window */
-	  ShowWindow (hwnd, SW_MINIMIZE);
-	}
-      else
-	{
-	  /* Flag that we have a valid screen depth */
-	  s_pScreenPriv->fBadDepth = FALSE;
-	}
-      
-      /*
-       * Check for a change in display dimensions.
-       * We can simply recreate the same-sized primary surface when
-       * the display dimensions change.
-       */
-      if (s_pScreenPriv->dwLastWindowsWidth != LOWORD (lParam)
-	  || s_pScreenPriv->dwLastWindowsHeight != HIWORD (lParam))
-	{
-	  /*
-	   * NOTE: The non-DirectDraw engines set the ReleasePrimarySurface
-	   * and CreatePrimarySurface function pointers to point
-	   * to the no operation function, NoopDDA.  This allows us
-	   * to blindly call these functions, even if they are not
-	   * relevant to the current engine (e.g., Shadow GDI).
-	   */
-
-#if CYGDEBUG
-	  winDebug ("winWindowProc - WM_DISPLAYCHANGE - Dimensions changed\n");
-#endif
-	  
-	  /* Release the old primary surface */
-	  (*s_pScreenPriv->pwinReleasePrimarySurface) (s_pScreen);
-
-#if CYGDEBUG
-	  winDebug ("winWindowProc - WM_DISPLAYCHANGE - Released "
-		  "primary surface\n");
-#endif
-
-	  /* Create the new primary surface */
-	  (*s_pScreenPriv->pwinCreatePrimarySurface) (s_pScreen);
-
-#if CYGDEBUG
-	  winDebug ("winWindowProc - WM_DISPLAYCHANGE - Recreated "
-		  "primary surface\n");
-#endif
-
-#if 0
-	  /* Multi-Window mode uses RandR for resizes */
-	  if (s_pScreenInfo->fMultiWindow)
-	    {
-	      RRSetScreenConfig ();
-	    }
-#endif
-	}
-      else
-	{
-#if CYGDEBUG
-	  winDebug ("winWindowProc - WM_DISPLAYCHANGE - Dimensions did not "
-		  "change\n");
-#endif
-	}
-
-      /* Store the new display dimensions and depth */
-      if (s_pScreenInfo->fMultipleMonitors)
-	{
-	  s_pScreenPriv->dwLastWindowsWidth
-	    = GetSystemMetrics (SM_CXVIRTUALSCREEN);
-	  s_pScreenPriv->dwLastWindowsHeight
-	    = GetSystemMetrics (SM_CYVIRTUALSCREEN);
-	}
-      else
-	{
-	  s_pScreenPriv->dwLastWindowsWidth
-	    = GetSystemMetrics (SM_CXSCREEN);
-	  s_pScreenPriv->dwLastWindowsHeight
-	    = GetSystemMetrics (SM_CYSCREEN);
-	}
-      s_pScreenPriv->dwLastWindowsBitsPixel
-	= GetDeviceCaps (s_pScreenPriv->hdcScreen, BITSPIXEL);
-      break;
-
-    case WM_SIZE:
-      {
-	SCROLLINFO		si;
-	RECT			rcWindow;
-	int			iWidth, iHeight;
-
-#if CYGDEBUG
-	winDebug ("winWindowProc - WM_SIZE\n");
-#endif
-
-	/* Break if we do not use scrollbars */
-	if (!s_pScreenInfo->fScrollbars
-	    || !s_pScreenInfo->fDecoration
-#ifdef XWIN_MULTIWINDOWEXTWM
-	    || s_pScreenInfo->fMWExtWM
-#endif
-	    || s_pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOW
-	    || s_pScreenInfo->fMultiWindow
-#endif
-	    || s_pScreenInfo->fFullScreen)
-	  break;
-
-	/* No need to resize if we get minimized */
-	if (wParam == SIZE_MINIMIZED)
-	  return 0;
-
-	/*
-	 * Get the size of the whole window, including client area,
-	 * scrollbars, and non-client area decorations (caption, borders).
-	 * We do this because we need to check if the client area
-	 * without scrollbars is large enough to display the whole visual.
-	 * The new client area size passed by lParam already subtracts
-	 * the size of the scrollbars if they are currently displayed.
-	 * So checking is LOWORD(lParam) == visual_width and
-	 * HIWORD(lParam) == visual_height will never tell us to hide
-	 * the scrollbars because the client area would always be too small.
-	 * GetClientRect returns the same sizes given by lParam, so we
-	 * cannot use GetClientRect either.
-	 */
-	GetWindowRect (hwnd, &rcWindow);
-	iWidth = rcWindow.right - rcWindow.left;
-	iHeight = rcWindow.bottom - rcWindow.top;
-
-	ErrorF ("winWindowProc - WM_SIZE - window w: %d h: %d, "
-		"new client area w: %d h: %d\n",
-		iWidth, iHeight, LOWORD (lParam), HIWORD (lParam));
-
-	/* Subtract the frame size from the window size. */
-	iWidth -= 2 * GetSystemMetrics (SM_CXSIZEFRAME);
-	iHeight -= (2 * GetSystemMetrics (SM_CYSIZEFRAME)
-		    + GetSystemMetrics (SM_CYCAPTION));
-
-	/*
-	 * Update scrollbar page sizes.
-	 * NOTE: If page size == range, then the scrollbar is
-	 * automatically hidden.
-	 */
-
-	/* Is the naked client area large enough to show the whole visual? */
-	if (iWidth < s_pScreenInfo->dwWidth
-	    || iHeight < s_pScreenInfo->dwHeight)
-	  {
-	    /* Client area too small to display visual, use scrollbars */
-	    iWidth -= GetSystemMetrics (SM_CXVSCROLL);
-	    iHeight -= GetSystemMetrics (SM_CYHSCROLL);
-	  }
-	
-	/* Set the horizontal scrollbar page size */
-	si.cbSize = sizeof (si);
-	si.fMask = SIF_PAGE | SIF_RANGE;
-	si.nMin = 0;
-	si.nMax = s_pScreenInfo->dwWidth - 1;
-	si.nPage = iWidth;
-	SetScrollInfo (hwnd, SB_HORZ, &si, TRUE);
-	
-	/* Set the vertical scrollbar page size */
-	si.cbSize = sizeof (si);
-	si.fMask = SIF_PAGE | SIF_RANGE;
-	si.nMin = 0;
-	si.nMax = s_pScreenInfo->dwHeight - 1;
-	si.nPage = iHeight;
-	SetScrollInfo (hwnd, SB_VERT, &si, TRUE);
-
-	/*
-	 * NOTE: Scrollbars may have moved if they were at the 
-	 * far right/bottom, so we query their current position.
-	 */
-	
-	/* Get the horizontal scrollbar position and set the offset */
-	si.cbSize = sizeof (si);
-	si.fMask = SIF_POS;
-	GetScrollInfo (hwnd, SB_HORZ, &si);
-	s_pScreenInfo->dwXOffset = -si.nPos;
-	
-	/* Get the vertical scrollbar position and set the offset */
-	si.cbSize = sizeof (si);
-	si.fMask = SIF_POS;
-	GetScrollInfo (hwnd, SB_VERT, &si);
-	s_pScreenInfo->dwYOffset = -si.nPos;
-      }
-      return 0;
-
-    case WM_VSCROLL:
-      {
-	SCROLLINFO		si;
-	int			iVertPos;
-
-#if CYGDEBUG
-	winDebug ("winWindowProc - WM_VSCROLL\n");
-#endif
-      
-	/* Get vertical scroll bar info */
-	si.cbSize = sizeof (si);
-	si.fMask = SIF_ALL;
-	GetScrollInfo (hwnd, SB_VERT, &si);
-
-	/* Save the vertical position for comparison later */
-	iVertPos = si.nPos;
-
-	/*
-	 * Don't forget:
-	 * moving the scrollbar to the DOWN, scroll the content UP
-	 */
-	switch (LOWORD(wParam))
-	  {
-	  case SB_TOP:
-	    si.nPos = si.nMin;
-	    break;
-	  
-	  case SB_BOTTOM:
-	    si.nPos = si.nMax - si.nPage + 1;
-	    break;
-
-	  case SB_LINEUP:
-	    si.nPos -= 1;
-	    break;
-	  
-	  case SB_LINEDOWN:
-	    si.nPos += 1;
-	    break;
-	  
-	  case SB_PAGEUP:
-	    si.nPos -= si.nPage;
-	    break;
-	  
-	  case SB_PAGEDOWN:
-	    si.nPos += si.nPage;
-	    break;
-
-	  case SB_THUMBTRACK:
-	    si.nPos = si.nTrackPos;
-	    break;
-
-	  default:
-	    break;
-	  }
-
-	/*
-	 * We retrieve the position after setting it,
-	 * because Windows may adjust it.
-	 */
-	si.fMask = SIF_POS;
-	SetScrollInfo (hwnd, SB_VERT, &si, TRUE);
-	GetScrollInfo (hwnd, SB_VERT, &si);
-      
-	/* Scroll the window if the position has changed */
-	if (si.nPos != iVertPos)
-	  {
-	    /* Save the new offset for bit block transfers, etc. */
-	    s_pScreenInfo->dwYOffset = -si.nPos;
-
-	    /* Change displayed region in the window */
-	    ScrollWindowEx (hwnd,
-			    0,
-			    iVertPos - si.nPos,
-			    NULL,
-			    NULL,
-			    NULL,
-			    NULL,
-			    SW_INVALIDATE);
-	  
-	    /* Redraw the window contents */
-	    UpdateWindow (hwnd);
-	  }
-      }
-      return 0;
-
-    case WM_HSCROLL:
-      {
-	SCROLLINFO		si;
-	int			iHorzPos;
-
-#if CYGDEBUG
-	winDebug ("winWindowProc - WM_HSCROLL\n");
-#endif
-      
-	/* Get horizontal scroll bar info */
-	si.cbSize = sizeof (si);
-	si.fMask = SIF_ALL;
-	GetScrollInfo (hwnd, SB_HORZ, &si);
-
-	/* Save the horizontal position for comparison later */
-	iHorzPos = si.nPos;
-
-	/*
-	 * Don't forget:
-	 * moving the scrollbar to the RIGHT, scroll the content LEFT
-	 */
-	switch (LOWORD(wParam))
-	  {
-	  case SB_LEFT:
-	    si.nPos = si.nMin;
-	    break;
-	  
-	  case SB_RIGHT:
-	    si.nPos = si.nMax - si.nPage + 1;
-	    break;
-
-	  case SB_LINELEFT:
-	    si.nPos -= 1;
-	    break;
-	  
-	  case SB_LINERIGHT:
-	    si.nPos += 1;
-	    break;
-	  
-	  case SB_PAGELEFT:
-	    si.nPos -= si.nPage;
-	    break;
-	  
-	  case SB_PAGERIGHT:
-	    si.nPos += si.nPage;
-	    break;
-
-	  case SB_THUMBTRACK:
-	    si.nPos = si.nTrackPos;
-	    break;
-
-	  default:
-	    break;
-	  }
-
-	/*
-	 * We retrieve the position after setting it,
-	 * because Windows may adjust it.
-	 */
-	si.fMask = SIF_POS;
-	SetScrollInfo (hwnd, SB_HORZ, &si, TRUE);
-	GetScrollInfo (hwnd, SB_HORZ, &si);
-      
-	/* Scroll the window if the position has changed */
-	if (si.nPos != iHorzPos)
-	  {
-	    /* Save the new offset for bit block transfers, etc. */
-	    s_pScreenInfo->dwXOffset = -si.nPos;
-
-	    /* Change displayed region in the window */
-	    ScrollWindowEx (hwnd,
-			    iHorzPos - si.nPos,
-			    0,
-			    NULL,
-			    NULL,
-			    NULL,
-			    NULL,
-			    SW_INVALIDATE);
-	  
-	    /* Redraw the window contents */
-	    UpdateWindow (hwnd);
-	  }
-      }
-      return 0;
-
-    case WM_GETMINMAXINFO:
-      {
-	MINMAXINFO		*pMinMaxInfo = (MINMAXINFO *) lParam;
-	int			iCaptionHeight;
-	int			iBorderHeight, iBorderWidth;
-
-#if CYGDEBUG	
-	winDebug ("winWindowProc - WM_GETMINMAXINFO - pScreenInfo: %08x\n",
-		s_pScreenInfo);
-#endif
-
-	/* Can't do anything without screen info */
-	if (s_pScreenInfo == NULL
-	    || !s_pScreenInfo->fScrollbars
-	    || s_pScreenInfo->fFullScreen
-	    || !s_pScreenInfo->fDecoration
-#ifdef XWIN_MULTIWINDOWEXTWM
-	    || s_pScreenInfo->fMWExtWM
-#endif
-	    || s_pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOW
-	    || s_pScreenInfo->fMultiWindow
-#endif
-	    )
-	  break;
-
-	/*
-	 * Here we can override the maximum tracking size, which
-	 * is the largest size that can be assigned to our window
-	 * via the sizing border.
-	 */
-
-	/*
-	 * FIXME: Do we only need to do this once, since our visual size
-	 * does not change?  Does Windows store this value statically
-	 * once we have set it once?
-	 */
-
-	/* Get the border and caption sizes */
-	iCaptionHeight = GetSystemMetrics (SM_CYCAPTION);
-	iBorderWidth = 2 * GetSystemMetrics (SM_CXSIZEFRAME);
-	iBorderHeight = 2 * GetSystemMetrics (SM_CYSIZEFRAME);
-	
-	/* Allow the full visual to be displayed */
-	pMinMaxInfo->ptMaxTrackSize.x
-	  = s_pScreenInfo->dwWidth + iBorderWidth;
-	pMinMaxInfo->ptMaxTrackSize.y
-	  = s_pScreenInfo->dwHeight + iBorderHeight + iCaptionHeight;
-      }
-      return 0;
-
-    case WM_ERASEBKGND:
-#if CYGDEBUG
-      winDebug ("winWindowProc - WM_ERASEBKGND\n");
-#endif
-      /*
-       * Pretend that we did erase the background but we don't care,
-       * the application uses the full window estate. This avoids some
-       * flickering when resizing.
-       */
-      return TRUE;
-
-    case WM_PAINT:
-#if CYGDEBUG
-      winDebug ("winWindowProc - WM_PAINT\n");
-#endif
-      /* Only paint if we have privates and the server is enabled */
-      if (s_pScreenPriv == NULL
-	  || !s_pScreenPriv->fEnabled
-	  || (s_pScreenInfo->fFullScreen && !s_pScreenPriv->fActive)
-	  || s_pScreenPriv->fBadDepth)
-	{
-	  /* We don't want to paint */
-	  break;
-	}
-
-      /* Break out here if we don't have a valid paint routine */
-      if (s_pScreenPriv->pwinBltExposedRegions == NULL)
-	break;
-      
-      /* Call the engine dependent repainter */
-      (*s_pScreenPriv->pwinBltExposedRegions) (s_pScreen);
-      return 0;
-
-    case WM_PALETTECHANGED:
-      {
-#if CYGDEBUG
-	winDebug ("winWindowProc - WM_PALETTECHANGED\n");
-#endif
-	/*
-	 * Don't process if we don't have privates or a colormap,
-	 * or if we have an invalid depth.
-	 */
-	if (s_pScreenPriv == NULL
-	    || s_pScreenPriv->pcmapInstalled == NULL
-	    || s_pScreenPriv->fBadDepth)
-	  break;
-
-	/* Return if we caused the palette to change */
-	if ((HWND) wParam == hwnd)
-	  {
-	    /* Redraw the screen */
-	    (*s_pScreenPriv->pwinRedrawScreen) (s_pScreen);
-	    return 0;
-	  }
-	
-	/* Reinstall the windows palette */
-	(*s_pScreenPriv->pwinRealizeInstalledPalette) (s_pScreen);
-	
-	/* Redraw the screen */
-	(*s_pScreenPriv->pwinRedrawScreen) (s_pScreen);
-	return 0;
-      }
-
-    case WM_MOUSEMOVE:
-      /* We can't do anything without privates */
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-
-      /* Has the mouse pointer crossed screens? */
-      if (s_pScreen != miPointerGetScreen(inputInfo.pointer))
-	miPointerSetScreen (inputInfo.pointer, s_pScreenInfo->dwScreen,
-			       GET_X_LPARAM(lParam)-s_pScreenInfo->dwXOffset,
-			       GET_Y_LPARAM(lParam)-s_pScreenInfo->dwYOffset);
-
-      /* Are we tracking yet? */
-      if (!s_fTracking)
-	{
-	  TRACKMOUSEEVENT		tme;
-	  
-	  /* Setup data structure */
-	  ZeroMemory (&tme, sizeof (tme));
-	  tme.cbSize = sizeof (tme);
-	  tme.dwFlags = TME_LEAVE;
-	  tme.hwndTrack = hwnd;
-
-	  /* Call the tracking function */
-	  if (!(*g_fpTrackMouseEvent) (&tme))
-	    ErrorF ("winWindowProc - _TrackMouseEvent failed\n");
-
-	  /* Flag that we are tracking now */
-	  s_fTracking = TRUE;
-	}
-
-      /* Hide or show the Windows mouse cursor */
-      if (g_fSoftwareCursor && g_fCursor && (s_pScreenPriv->fActive || s_pScreenInfo->fLessPointer))
-	{
-	  /* Hide Windows cursor */
-	  g_fCursor = FALSE;
-	  ShowCursor (FALSE);
-	}
-      else if (g_fSoftwareCursor && !g_fCursor && !s_pScreenPriv->fActive
-	       && !s_pScreenInfo->fLessPointer)
-	{
-	  /* Show Windows cursor */
-	  g_fCursor = TRUE;
-	  ShowCursor (TRUE);
-	}
-      
-      /* Deliver absolute cursor position to X Server */
-      miPointerAbsoluteCursor (GET_X_LPARAM(lParam)-s_pScreenInfo->dwXOffset,
-			       GET_Y_LPARAM(lParam)-s_pScreenInfo->dwYOffset,
-			       g_c32LastInputEventTime = GetTickCount ());
-      return 0;
-
-    case WM_NCMOUSEMOVE:
-      /*
-       * We break instead of returning 0 since we need to call
-       * DefWindowProc to get the mouse cursor changes
-       * and min/max/close button highlighting in Windows XP.
-       * The Platform SDK says that you should return 0 if you
-       * process this message, but it fails to mention that you
-       * will give up any default functionality if you do return 0.
-       */
-      
-      /* We can't do anything without privates */
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      
-      /* Non-client mouse movement, show Windows cursor */
-      if (g_fSoftwareCursor && !g_fCursor)
-	{
-	  g_fCursor = TRUE;
-	  ShowCursor (TRUE);
-	}
-      break;
-
-    case WM_MOUSELEAVE:
-      /* Mouse has left our client area */
-
-      /* Flag that we are no longer tracking */
-      s_fTracking = FALSE;
-
-      /* Show the mouse cursor, if necessary */
-      if (g_fSoftwareCursor && !g_fCursor)
-	{
-	  g_fCursor = TRUE;
-	  ShowCursor (TRUE);
-	}
-      return 0;
-
-    case WM_LBUTTONDBLCLK:
-    case WM_LBUTTONDOWN:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      if (s_pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOWEXTWM
-	  || s_pScreenInfo->fMWExtWM
-#endif
-	  )
-	SetCapture (hwnd);
-      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button1, wParam);
-      
-    case WM_LBUTTONUP:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      if (s_pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOWEXTWM
-	  || s_pScreenInfo->fMWExtWM
-#endif
-	  )
-	ReleaseCapture ();
-      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button1, wParam);
-
-    case WM_MBUTTONDBLCLK:
-    case WM_MBUTTONDOWN:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      if (s_pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOWEXTWM
-	  || s_pScreenInfo->fMWExtWM
-#endif
-	  )
-	SetCapture (hwnd);
-      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button2, wParam);
-      
-    case WM_MBUTTONUP:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      if (s_pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOWEXTWM
-	  || s_pScreenInfo->fMWExtWM
-#endif
-	  )
-	ReleaseCapture ();
-      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button2, wParam);
-      
-    case WM_RBUTTONDBLCLK:
-    case WM_RBUTTONDOWN:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      if (s_pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOWEXTWM
-	  || s_pScreenInfo->fMWExtWM
-#endif
-	  )
-	SetCapture (hwnd);
-      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button3, wParam);
-      
-    case WM_RBUTTONUP:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      if (s_pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOWEXTWM
-	  || s_pScreenInfo->fMWExtWM
-#endif
-	  )
-	ReleaseCapture ();
-      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button3, wParam);
-
-    case WM_XBUTTONDBLCLK:
-    case WM_XBUTTONDOWN:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      if (s_pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOWEXTWM
-	  || s_pScreenInfo->fMWExtWM
-#endif
-	  )
-	SetCapture (hwnd);
-      return winMouseButtonsHandle (s_pScreen, ButtonPress, HIWORD(wParam) + 5, wParam);
-    case WM_XBUTTONUP:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-      if (s_pScreenInfo->fRootless
-#ifdef XWIN_MULTIWINDOWEXTWM
-	  || s_pScreenInfo->fMWExtWM
-#endif
-	  )
-	ReleaseCapture ();
-      return winMouseButtonsHandle (s_pScreen, ButtonRelease, HIWORD(wParam) + 5, wParam);
-
-    case WM_TIMER:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-
-      /* Branch on the timer id */
-      switch (wParam)
-	{
-	case WIN_E3B_TIMER_ID:
-	  /* Send delayed button press */
-	  winMouseButtonsSendEvent (ButtonPress,
-				    s_pScreenPriv->iE3BCachedPress);
-
-	  /* Kill this timer */
-	  KillTimer (s_pScreenPriv->hwndScreen, WIN_E3B_TIMER_ID);
-
-	  /* Clear screen privates flags */
-	  s_pScreenPriv->iE3BCachedPress = 0;
-	  break;
-
-	case WIN_POLLING_MOUSE_TIMER_ID:
-	  {
-	    POINT		point;
-	    WPARAM		wL, wM, wR, wShift, wCtrl;
-	    LPARAM		lPos;
-	    
-	    /* Get the current position of the mouse cursor */
-	    GetCursorPos (&point);
-	    
-	    /* Map from screen (-X, -Y) to root (0, 0) */
-	    point.x -= GetSystemMetrics (SM_XVIRTUALSCREEN);
-	    point.y -= GetSystemMetrics (SM_YVIRTUALSCREEN);
-	    
-	    /* Deliver absolute cursor position to X Server */
-	    miPointerAbsoluteCursor (point.x, point.y,
-				     g_c32LastInputEventTime = GetTickCount());
-
-	    /* Check if a button was released but we didn't see it */
-	    GetCursorPos (&point);
-	    wL = (GetKeyState (VK_LBUTTON) & 0x8000)?MK_LBUTTON:0;
-	    wM = (GetKeyState (VK_MBUTTON) & 0x8000)?MK_MBUTTON:0;
-	    wR = (GetKeyState (VK_RBUTTON) & 0x8000)?MK_RBUTTON:0;
-	    wShift = (GetKeyState (VK_SHIFT) & 0x8000)?MK_SHIFT:0;
-	    wCtrl = (GetKeyState (VK_CONTROL) & 0x8000)?MK_CONTROL:0;
-	    lPos = MAKELPARAM(point.x, point.y);
-	    if (g_fButton[0] & !wL)
-	    PostMessage (hwnd, WM_LBUTTONUP, wCtrl|wM|wR|wShift, lPos);
-	    if (g_fButton[1] & !wM)
-	      PostMessage (hwnd, WM_MBUTTONUP, wCtrl|wL|wR|wShift, lPos);
-	    if (g_fButton[2] & !wR)
-	      PostMessage (hwnd, WM_RBUTTONUP, wCtrl|wL|wM|wShift, lPos);
-	  }
-	}
-      return 0;
-
-    case WM_CTLCOLORSCROLLBAR:
-      FatalError ("winWindowProc - WM_CTLCOLORSCROLLBAR - We are not "
-		  "supposed to get this message.  Exiting.\n");
-      return 0;
-
-    case WM_MOUSEWHEEL:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-#if CYGDEBUG
-      winDebug ("winWindowProc - WM_MOUSEWHEEL\n");
-#endif
-      winMouseWheel (s_pScreen, GET_WHEEL_DELTA_WPARAM(wParam));
-      break;
-
-    case WM_SETFOCUS:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-
-      /* Save handle of our main window that last received focus */
-      g_hwndKeyboardFocus = hwnd;
-
-      /* Restore the state of all mode keys */
-      winRestoreModeKeyStates ();
-
-      /* Add the keyboard hook if possible */
-      if (g_fKeyboardHookLL)
-	g_fKeyboardHookLL = winInstallKeyboardHookLL ();
-      return 0;
-
-    case WM_KILLFOCUS:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-
-      /* Clear handle of our main window that last received focus */
-      g_hwndKeyboardFocus = NULL;
-
-      /* Release any pressed keys */
-      winKeybdReleaseKeys ();
-
-      /* Remove our keyboard hook if it is installed */
-      winRemoveKeyboardHookLL ();
-      return 0;
-
-    case WM_SYSKEYDOWN:
-    case WM_KEYDOWN:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-
-      /*
-       * FIXME: Catching Alt-F4 like this is really terrible.  This should
-       * be generalized to handle other Windows keyboard signals.  Actually,
-       * the list keys to catch and the actions to perform when caught should
-       * be configurable; that way user's can customize the keys that they
-       * need to have passed through to their window manager or apps, or they
-       * can remap certain actions to new key codes that do not conflict
-       * with the X apps that they are using.  Yeah, that'll take awhile.
-       */
-      if ((s_pScreenInfo->fUseWinKillKey && wParam == VK_F4
-	   && (GetKeyState (VK_MENU) & 0x8000))
-	  || (s_pScreenInfo->fUseUnixKillKey && wParam == VK_BACK
-	      && (GetKeyState (VK_MENU) & 0x8000)
-	      && (GetKeyState (VK_CONTROL) & 0x8000)))
-	{
-	  /*
-	   * Better leave this message here, just in case some unsuspecting
-	   * user enters Alt + F4 and is surprised when the application
-	   * quits.
-	   */
-	  ErrorF ("winWindowProc - WM_*KEYDOWN - Closekey hit, quitting\n");
-	  
-	  /* Display Exit dialog */
-	  winDisplayExitDialog (s_pScreenPriv);
-	  return 0;
-	}
-      
-      /*
-       * Don't do anything for the Windows keys, as focus will soon
-       * be returned to Windows.  We may be able to trap the Windows keys,
-       * but we should determine if that is desirable before doing so.
-       */
-      if ((wParam == VK_LWIN || wParam == VK_RWIN) && !g_fKeyboardHookLL)
-	break;
-
-#ifdef XKB
-      /* 
-       * Discard presses generated from Windows auto-repeat
-       * ago: Only discard them if XKB is not disabled 
-       */
-      if (!g_winInfo.xkb.disable && (lParam & (1<<30)))
-      {
-        switch (wParam)
-        {
-          /* ago: Pressing LControl while RControl is pressed is 
-           * Indicated as repeat. Fix this!
-           */
-          case VK_CONTROL:
-          case VK_SHIFT:
-            if (winCheckKeyPressed(wParam, lParam))
-              return 0;
-            break;
-          default:
-            return 0;
-        }
-      } 
-#endif 
-      
-      /* Discard fake Ctrl_L presses that precede AltGR on non-US keyboards */
-      if (winIsFakeCtrl_L (message, wParam, lParam))
-	return 0;
-      
-      /* Translate Windows key code to X scan code */
-      winTranslateKey (wParam, lParam, &iScanCode);
-
-      /* Ignore repeats for CapsLock */
-      if (wParam == VK_CAPITAL)
-	lParam = 1;
-
-      /* Send the key event(s) */
-      for (i = 0; i < LOWORD(lParam); ++i)
-	winSendKeyEvent (iScanCode, TRUE);
-      return 0;
-
-    case WM_SYSKEYUP:
-    case WM_KEYUP:
-      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
-	break;
-
-      /*
-       * Don't do anything for the Windows keys, as focus will soon
-       * be returned to Windows.  We may be able to trap the Windows keys,
-       * but we should determine if that is desirable before doing so.
-       */
-      if ((wParam == VK_LWIN || wParam == VK_RWIN) && !g_fKeyboardHookLL)
-	break;
-
-      /* Ignore the fake Ctrl_L that follows an AltGr release */
-      if (winIsFakeCtrl_L (message, wParam, lParam))
-	return 0;
-
-      /* Enqueue a keyup event */
-      winTranslateKey (wParam, lParam, &iScanCode);
-      winSendKeyEvent (iScanCode, FALSE);
-
-      /* Release all pressed shift keys */
-      if (wParam == VK_SHIFT) 
-        winFixShiftKeys (iScanCode);
-      return 0;
-
-    case WM_HOTKEY:
-      if (s_pScreenPriv == NULL)
-	break;
-
-      /* Call the engine-specific hot key handler */
-      (*s_pScreenPriv->pwinHotKeyAltTab) (s_pScreen);
-      return 0;
-
-    case WM_ACTIVATE:
-      if (s_pScreenPriv == NULL
-	  || s_pScreenInfo->fIgnoreInput)
-	break;
-
-      /* TODO: Override display of window when we have a bad depth */
-      if (LOWORD(wParam) != WA_INACTIVE && s_pScreenPriv->fBadDepth)
-	{
-	  ErrorF ("winWindowProc - WM_ACTIVATE - Bad depth, trying "
-		  "to override window activation\n");
-
-	  /* Minimize the window */
-	  ShowWindow (hwnd, SW_MINIMIZE);
-
-	  /* Display dialog box */
-	  if (g_hDlgDepthChange != NULL)
-	    {
-	      /* Make the existing dialog box active */
-	      SetActiveWindow (g_hDlgDepthChange);
-	    }
-	  else
-	    {
-	      /* TODO: Recreate the dialog box and bring to the top */
-	      ShowWindow (g_hDlgDepthChange, SW_SHOWDEFAULT);
-	    }
-
-	  /* Don't do any other processing of this message */
-	  return 0;
-	}
-
-#if CYGDEBUG
-      winDebug ("winWindowProc - WM_ACTIVATE\n");
-#endif
-
-      /*
-       * Focus is being changed to another window.
-       * The other window may or may not belong to
-       * our process.
-       */
-
-      /* Clear any lingering wheel delta */
-      s_pScreenPriv->iDeltaZ = 0;
-
-      /* Reshow the Windows mouse cursor if we are being deactivated */
-      if (g_fSoftwareCursor && LOWORD(wParam) == WA_INACTIVE
-	  && !g_fCursor)
-	{
-	  /* Show Windows cursor */
-	  g_fCursor = TRUE;
-	  ShowCursor (TRUE);
-	}
-      return 0;
-
-    case WM_ACTIVATEAPP:
-      if (s_pScreenPriv == NULL
-	  || s_pScreenInfo->fIgnoreInput)
-	break;
-
-#if CYGDEBUG || TRUE
-      winDebug ("winWindowProc - WM_ACTIVATEAPP\n");
-#endif
-
-      /* Activate or deactivate */
-      s_pScreenPriv->fActive = wParam;
-
-      /* Reshow the Windows mouse cursor if we are being deactivated */
-      if (g_fSoftwareCursor && !s_pScreenPriv->fActive
-	  && !g_fCursor)
-	{
-	  /* Show Windows cursor */
-	  g_fCursor = TRUE;
-	  ShowCursor (TRUE);
-	}
-
-#ifdef XWIN_CLIPBOARD
-      /* Make sure the clipboard chain is ok. */
-      winFixClipboardChain ();
-#endif
-
-      /* Call engine specific screen activation/deactivation function */
-      (*s_pScreenPriv->pwinActivateApp) (s_pScreen);
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-      if (s_pScreenPriv->fActive)
-	{
-	  /* Restack all window unless using built-in wm. */
-	  if (s_pScreenInfo->fInternalWM && s_pScreenInfo->fAnotherWMRunning)
-	    winMWExtWMRestackWindows (s_pScreen);
-	}
-#endif
-
-      return 0;
-
-    case WM_COMMAND:
-      switch (LOWORD (wParam))
-	{
-	case ID_APP_EXIT:
-	  /* Display Exit dialog */
-	  winDisplayExitDialog (s_pScreenPriv);
-	  return 0;
-
-#ifdef XWIN_MULTIWINDOW
-	case ID_APP_HIDE_ROOT:
-	  if (s_pScreenPriv->fRootWindowShown)
-	    ShowWindow (s_pScreenPriv->hwndScreen, SW_HIDE);
-	  else
-	    ShowWindow (s_pScreenPriv->hwndScreen, SW_SHOW);
-	  s_pScreenPriv->fRootWindowShown = !s_pScreenPriv->fRootWindowShown;
-	  return 0;
-#endif
-
-	case ID_APP_ABOUT:
-	  /* Display the About box */
-	  winDisplayAboutDialog (s_pScreenPriv);
-	  return 0;
-
-	default:
-	  /* It's probably one of the custom menus... */
-	  if (HandleCustomWM_COMMAND (0, LOWORD (wParam)))
-	    return 0;
-	}
-      break;
-
-    case WM_ENDSESSION:
-    case WM_GIVEUP:
-      /* Tell X that we are giving up */
-#ifdef XWIN_MULTIWINDOW
-      if (s_pScreenInfo->fMultiWindow)
-	winDeinitMultiWindowWM ();
-#endif
-      GiveUp (0);
-      return 0;
-
-    case WM_CLOSE:
-      /* Display Exit dialog */
-      winDisplayExitDialog (s_pScreenPriv);
-      return 0;
-
-    case WM_SETCURSOR:
-      if (LOWORD(lParam) == HTCLIENT)
-	{
-	  if (!g_fSoftwareCursor) SetCursor (s_pScreenPriv->cursor.handle);
-	  return TRUE;
-	}
-      break;
-
-#ifdef XWIN_MULTIWINDOWEXTWM
-    case WM_MANAGE:
-      ErrorF ("winWindowProc - WM_MANAGE\n");
-      s_pScreenInfo->fAnotherWMRunning = FALSE;
-
-      if (s_pScreenInfo->fInternalWM)
-	{
-	  EnumThreadWindows (g_dwCurrentThreadID, winMWExtWMDecorateWindow, 0);
-	  //RootlessRepositionWindows (s_pScreen);
-	}
-      break;
-
-    case WM_UNMANAGE:
-      ErrorF ("winWindowProc - WM_UNMANAGE\n");
-      s_pScreenInfo->fAnotherWMRunning = TRUE;
-
-      if (s_pScreenInfo->fInternalWM)
-	{
-	  EnumThreadWindows (g_dwCurrentThreadID, winMWExtWMDecorateWindow, 0);
-	  winMWExtWMRestackWindows (s_pScreen);
-	}
-      break;
-#endif
-
-    default:
-      if(message == s_uTaskbarRestart)
-	{
-	  winInitNotifyIcon (s_pScreenPriv);
-	}
-      break;
-    }
-
-  return DefWindowProc (hwnd, message, wParam, lParam);
-}
diff --git a/hw/xwin/xlaunch/COPYING b/hw/xwin/xlaunch/COPYING
deleted file mode 100755
index c7fa844..0000000
--- a/hw/xwin/xlaunch/COPYING
+++ /dev/null
@@ -1,25 +0,0 @@
-
- Copyright (c) 2005 Alexander Gottwald
-
- Permission is hereby granted, free of charge, to any person obtaining a
- copy of this software and associated documentation files (the "Software"),
- to deal in the Software without restriction, including without limitation
- the rights to use, copy, modify, merge, publish, distribute, sublicense,
- and/or sell copies of the Software, and to permit persons to whom the
- Software is furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- Except as contained in this notice, the name(s) of the above copyright
- holders shall not be used in advertising or otherwise to promote the sale,
- use or other dealings in this Software without prior written authorization.
-
diff --git a/hw/xwin/xlaunch/Makefile b/hw/xwin/xlaunch/Makefile
deleted file mode 100755
index f7cf923..0000000
--- a/hw/xwin/xlaunch/Makefile
+++ /dev/null
@@ -1,79 +0,0 @@
-#
-# Copyright (c) 2005 Alexander Gottwald
-#
-# Permission is hereby granted, free of charge, to any person obtaining a
-# copy of this software and associated documentation files (the "Software"),
-# to deal in the Software without restriction, including without limitation
-# the rights to use, copy, modify, merge, publish, distribute, sublicense,
-# and/or sell copies of the Software, and to permit persons to whom the
-# Software is furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-# THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
-# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-# DEALINGS IN THE SOFTWARE.
-#
-# Except as contained in this notice, the name(s) of the above copyright
-# holders shall not be used in advertising or otherwise to promote the sale,
-# use or other dealings in this Software without prior written authorization.
-#
-WINDRES=windres
-
-TARGET=mingw
-#DEBUG_FLAGS=-D_DEBUG
-
-OS_FLAGS_mingw=-mno-cygwin
-OS_FLAGS=$(OS_FLAGS_$(TARGET)) $(DEBUG_FLAGS)
-
-X11_DIR_$(TARGET)=/usr/X11R6
-X11_DIR_mingw=../../../../../exports
-X11_DIR=$(X11_DIR_$(TARGET))
-X11_INCLUDE=-I$(X11_DIR)/include
-X11_LIBDIR=-L$(X11_DIR)/lib
-X11_LIBS_$(TARGET)=-lX11
-X11_LIBS_mingw=-lX11 -lwsock32
-X11_LIBS=$(X11_LIBS_$(TARGET))
-
-PROGRAMFILES:=$(shell cygpath -u $(PROGRAMFILES))
-#MSXML_DIR=$(PROGRAMFILES)/MSXML 4.0
-MSXML_DIR=$(PROGRAMFILES)/Microsoft XML Parser SDK
-MSXML_INCLUDE="-I$(MSXML_DIR)/inc"
-MSXML_LIBDIR="-L$(MSXML_DIR)/lib"
-MSXML_LIBS=
-
-
-CXXFLAGS=-g $(OS_FLAGS) $(X11_INCLUDE) $(MSXML_INCLUDE)
-LDFLAGS=-mwindows $(X11_LIBDIR) $(MSXML_LIBDIR)
-LIBS=-lcomctl32 -lole32 -loleaut32 $(X11_LIBS) $(MSXML_LIBS)
-all:xlaunch.exe
-%.res: %.rc
-	$(WINDRES) -O coff -o $@ $<
-
-WINDOW_PARTS=window util dialog wizard
-WINDOW_OBJECTS=$(foreach file,$(WINDOW_PARTS),window/$(file).o) 
-
-RESOURCES_IMAGES=resources/multiwindow.bmp resources/fullscreen.bmp \
-	resources/windowed.bmp resources/nodecoration.bmp
-
-resources/resources.res: resources/resources.rc resources/resources.h \
-	resources/images.rc resources/dialog.rc resources/strings.rc \
-	$(RESOURCES_IMAGES)
-xlaunch.exe: $(WINDOW_OBJECTS) main.o config.o resources/resources.res
-	$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ $^ $(LIBS)
-
-
-window/dialog.o: window/dialog.cc window/dialog.h window/window.h window/util.h
-window/frame.o: window/frame.cc window/frame.h window/window.h
-window/util.o: window/util.cc window/util.h
-window/window.o: window/window.cc window/window.h window/util.h
-window/wizard.o: window/wizard.cc window/wizard.h window/dialog.h \
-  window/window.h window/util.h
-main.o: main.cc window/util.h window/wizard.h window/dialog.h \
-  window/window.h resources/resources.h config.h
-config.o: config.cc config.h
diff --git a/hw/xwin/xlaunch/config.cc b/hw/xwin/xlaunch/config.cc
deleted file mode 100644
index b6bf65a..0000000
--- a/hw/xwin/xlaunch/config.cc
+++ /dev/null
@@ -1,282 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#include "config.h"
-#include "window/util.h"
-#include <msxml2.h>
-#include <stdexcept>
-
-const CLSID CLSID_DOMDocument40 = {0x88d969c0,0xf192,0x11d4,0xa6,0x5f,0x00,0x40,0x96,0x32,0x51,0xe5};
-const CLSID CLSID_DOMDocument30 = {0xf5078f32,0xc551,0x11d3,0x89,0xb9,0x00,0x00,0xf8,0x1f,0xe2,0x21};
-const IID IID_IXMLDOMDocument2 = {0x2933BF95,0x7B36,0x11d2,0xB2,0x0E,0x00,0xC0,0x4F,0x98,0x3E,0x60};
-
-#define HRCALL(x, msg) if (FAILED(x)) { throw std::runtime_error("OLE Error:" msg " failed"); };
-
-char *wcconvert(const wchar_t *wstr)
-{
-    int chars = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
-    if (chars == 0)
-	throw win32_error("WideCharToMultiByte");
-    char *mbstr = new char[chars];
-    chars = WideCharToMultiByte(CP_ACP, 0, wstr, -1, mbstr, chars, NULL, NULL);
-    if (chars == 0)
-	throw win32_error("WideCharToMultiByte");
-    return mbstr;
-}
-
-wchar_t *mbconvert(const char *mbstr)
-{
-    int chars = MultiByteToWideChar(CP_ACP, 0, mbstr, -1, NULL, 0);
-    if (chars == 0)
-	throw win32_error("MultiByteToWideChar");
-    wchar_t *wstr = new wchar_t[chars];
-    chars = MultiByteToWideChar(CP_ACP, 0, mbstr, -1, wstr, chars);
-    if (chars == 0)
-	throw win32_error("MultiByteToWideChar");
-    return wstr;
-}
-
-VARIANT VariantString(const char *filename)
-{
-
-    wchar_t *str = mbconvert(filename);
-
-    VARIANT var;
-    VariantInit(&var);
-    V_BSTR(&var) = SysAllocString(str);
-    V_VT(&var) = VT_BSTR;
-
-    delete [] str;
-    return var;
-}
-
-VARIANT VariantString(const wchar_t *str)
-{
-   VARIANT var;
-   VariantInit(&var);
-   V_BSTR(&var) = SysAllocString(str);
-   V_VT(&var) = VT_BSTR;
-   return var;
-}
-
-IXMLDOMDocument2 *CreateDocument()
-{
-    IXMLDOMDocument2 *doc = NULL;
-    
-    CoInitialize(NULL);
-
-    HRCALL(CoCreateInstance(CLSID_DOMDocument40, NULL, CLSCTX_INPROC_SERVER,
-                      IID_IXMLDOMDocument2, (void**)&doc), "CoCreateInstance");
-
-    try {
-      	HRCALL(doc->put_async(VARIANT_FALSE), "put_async");
-	HRCALL(doc->put_validateOnParse(VARIANT_FALSE), "put_validateOnParse");
-	HRCALL(doc->put_resolveExternals(VARIANT_FALSE), "put_resolveExternals");
-
-	IXMLDOMProcessingInstruction *pi = NULL;
-	IXMLDOMElement *root = NULL;
-     	BSTR xml = SysAllocString(L"xml");
-	BSTR ver = SysAllocString(L"version='1.0'");
-	HRCALL(doc->createProcessingInstruction(xml,ver, &pi), 
-		"createProcessingInstruction");
-	HRCALL(doc->appendChild(pi, NULL),
-		"appendChild");
-	pi->Release();
-	SysFreeString(xml);
-	SysFreeString(ver);
-
-	BSTR elemname = SysAllocString(L"XLaunch");
-	HRCALL(doc->createElement(elemname, &root), "createElement");
-	HRCALL(doc->appendChild(root, NULL), "appendChild");
-	SysFreeString(elemname);
-    } catch (...)
-    {
-	doc->Release();
-	throw;
-    }
-    return doc;
-}
-
-void setAttribute(IXMLDOMElement *elem, const wchar_t *name, const wchar_t *value)
-{
-    BSTR str = SysAllocString(name);
-    VARIANT var = VariantString(value);
-    HRCALL(elem->setAttribute(str, var), "setAttribute");
-    VariantClear(&var);
-    SysFreeString(str);
-}
-
-void setAttribute(IXMLDOMElement *elem, const wchar_t *name, const char *value)
-{
-    wchar_t *wstr = mbconvert(value);
-    setAttribute(elem, name, wstr);
-    delete [] wstr;
-    return;
-}
-
-void CConfig::Save(const char *filename)
-{
-    IXMLDOMDocument2 *doc = CreateDocument();
-    IXMLDOMElement *root = NULL;
-
-    HRCALL(doc->get_documentElement(&root), "get_documentElement");
-
-    switch (window)
-    {
-	case MultiWindow:
-	    setAttribute(root, L"WindowMode", L"MultiWindow");
-	    break;
-	case Fullscreen:
-	    setAttribute(root, L"WindowMode", L"Fullscreen");
-	    break;
-	default:
-	case Windowed:
-	    setAttribute(root, L"WindowMode", L"Windowed");
-	    break;
-	case Nodecoration:
-	    setAttribute(root, L"WindowMode", L"Nodecoration");
-	    break;
-    }
-    switch (client)
-    {
-	default:
-	case NoClient:
-	    setAttribute(root, L"ClientMode", L"NoClient");
-	    break;
-	case StartProgram:
-	    setAttribute(root, L"ClientMode", L"StartProgram");
-	    break;
-	case XDMCP:
-	    setAttribute(root, L"ClientMode", L"XDMCP");
-	    break;
-    }
-    setAttribute(root, L"LocalClient", local?L"True":L"False");
-    setAttribute(root, L"Display", display.c_str());
-    setAttribute(root, L"Program", program.c_str());
-    setAttribute(root, L"RemoteProtocol", protocol.c_str());
-    setAttribute(root, L"RemoteHost", host.c_str());
-    setAttribute(root, L"RemoteUser", user.c_str());
-    setAttribute(root, L"XDMCPHost", xdmcp_host.c_str());
-    setAttribute(root, L"XDMCPBroadcast", broadcast?L"True":L"False");
-    setAttribute(root, L"XDMCPIndirect", indirect?L"True":L"False");
-    setAttribute(root, L"Clipboard", clipboard?L"True":L"False");
-    setAttribute(root, L"ExtraParams", extra_params.c_str());
-
-    VARIANT var = VariantString(filename);
-    HRCALL(doc->save(var), "save");
-    VariantClear(&var);
-
-
-    root->Release();
-    doc->Release();
-}
-
-BOOL getAttribute(IXMLDOMElement *elem, const wchar_t *name, std::string &ret)
-{
-    VARIANT var;
-    HRCALL(elem->getAttribute((OLECHAR*)name, &var), "getAttribute"); 
-    if (V_VT(&var) != VT_NULL && V_VT(&var) == VT_BSTR)
-    {
-	char *str = wcconvert(V_BSTR(&var));
-	ret = str;
-	delete [] str;
-	return true;
-    }
-    return false;
-}
-
-BOOL getAttributeBool(IXMLDOMElement *elem, const wchar_t *name, bool &ret)
-{
-    std::string str;
-    if (getAttribute(elem, name, str))
-    {
-	if (str == "True")
-	    ret = true;
-	else
-	    ret = false;
-	return true;
-    }
-    return false;
-}
-
-
-void CConfig::Load(const char *filename)
-{
-    IXMLDOMDocument2 *doc = CreateDocument();
-    IXMLDOMElement *root = NULL;
-
-    VARIANT var = VariantString(filename);
-    VARIANT_BOOL status;
-    HRCALL(doc->load(var, &status), "load");
-    VariantClear(&var);
-
-    if (status == VARIANT_FALSE)
-    {
-	doc->Release();
-	return;
-    }
-
-    HRCALL(doc->get_documentElement(&root), "get_documentElement");
-
-    std::string windowMode;
-    std::string clientMode;
-
-    if (getAttribute(root, L"WindowMode", windowMode))
-    {
-	if (windowMode == "MultiWindow")
-	    window = MultiWindow;
-	else if (windowMode == "Fullscreen")
-	    window = Fullscreen;
-	else if (windowMode == "Windowed")
-	    window = Windowed;
-	else if (windowMode == "Nodecoration")
-	    window = Nodecoration;
-    }
-    if (getAttribute(root, L"ClientMode", clientMode))
-    {
-	if (clientMode == "NoClient")
-	    client = NoClient;
-	else if (clientMode == "StartProgram")
-	    client = StartProgram;
-	else if (clientMode == "XDMCP")
-	    client = XDMCP;
-    }
-    
-    getAttributeBool(root, L"LocalClient", local);
-    getAttribute(root, L"Display", display);
-    getAttribute(root, L"Program", program);
-    getAttribute(root, L"RemoteProtocol", protocol);
-    getAttribute(root, L"RemoteHost", host);
-    getAttribute(root, L"RemoteUser", user);
-    getAttribute(root, L"XDMCPHost", xdmcp_host);
-    getAttributeBool(root, L"XDMCPBroadcast", broadcast);
-    getAttributeBool(root, L"XDMCPIndirect", indirect);
-    getAttributeBool(root, L"Clipboard", clipboard);
-    getAttribute(root, L"ExtraParams", extra_params);
-    
-
-    doc->Release();
-}
-
diff --git a/hw/xwin/xlaunch/config.h b/hw/xwin/xlaunch/config.h
deleted file mode 100644
index f0aed3c..0000000
--- a/hw/xwin/xlaunch/config.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#ifndef __CONFIG_H__
-#define __CONFIG_H__
-
-#include <string>
-struct CConfig
-{
-    enum {MultiWindow, Fullscreen, Windowed, Nodecoration} window;
-    enum {NoClient, StartProgram, XDMCP} client;
-    bool local;
-    std::string display;
-    std::string protocol;
-    std::string program;
-    std::string host;
-    std::string user;
-    bool broadcast;
-    bool indirect;
-    std::string xdmcp_host;
-    bool clipboard;
-    std::string extra_params;
-#ifdef _DEBUG
-    CConfig() : window(MultiWindow), client(StartProgram), local(false), display("1"), 
-                protocol("Putty"), program("xterm"), host("lupus"), user("ago"),
-                broadcast(false), indirect(false), xdmcp_host("lupus"),
-                clipboard(true), extra_params() {};
-#else
-    CConfig() : window(MultiWindow), client(StartProgram), local(false), display("0"), 
-                protocol("Putty"), program("xterm"), host(""), user(""), 
-                broadcast(true), indirect(false), xdmcp_host(""),
-                clipboard(true), extra_params() {};
-#endif
-    void Load(const char* filename);
-    void Save(const char* filename);
-};
-
-#endif
diff --git a/hw/xwin/xlaunch/main.cc b/hw/xwin/xlaunch/main.cc
deleted file mode 100755
index 2247d3a..0000000
--- a/hw/xwin/xlaunch/main.cc
+++ /dev/null
@@ -1,700 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#include "window/util.h"
-#include "window/wizard.h"
-#include "resources/resources.h"
-#include "config.h"
-#include <prsht.h>
-#include <commctrl.h>
-
-#include <stdexcept>
-
-#include <X11/Xlib.h>
-
-/// @brief Send WM_ENDSESSION to all program windows.
-/// This will shutdown the started xserver
-BOOL CALLBACK KillWindowsProc(HWND hwnd, LPARAM lParam)
-{
-    SendMessage(hwnd, WM_ENDSESSION, 0, 0);
-    return TRUE;
-}
-
-/// @brief Actual wizard implementation.
-/// This is based on generic CWizard but handles the special dialogs
-class CMyWizard : public CWizard 
-{
-    public:
-    private:
-	CConfig config; /// Storage for config options.
-    public:
-        /// @brief Constructor.
-        /// Set wizard pages.
-        CMyWizard() : CWizard() 
-        {
-            AddPage(IDD_DISPLAY, IDS_DISPLAY_TITLE, IDS_DISPLAY_SUBTITLE);
-            AddPage(IDD_CLIENTS, IDS_CLIENTS_TITLE, IDS_CLIENTS_SUBTITLE);
-            AddPage(IDD_PROGRAM, IDS_PROGRAM_TITLE, IDS_PROGRAM_SUBTITLE);
-            AddPage(IDD_XDMCP, IDS_XDMCP_TITLE, IDS_XDMCP_SUBTITLE);
-            //AddPage(IDD_FONTPATH, IDS_FONTPATH_TITLE, IDS_FONTPATH_SUBTITLE);
-            AddPage(IDD_CLIPBOARD, IDS_CLIPBOARD_TITLE, IDS_CLIPBOARD_SUBTITLE);
-            AddPage(IDD_FINISH, IDS_FINISH_TITLE, IDS_FINISH_SUBTITLE);
-        }
-
-	virtual void LoadConfig(const char *filename)
-	{
-	    try {
-		config.Load(filename);
-	    } catch (std::runtime_error &e)
-	    {
-		printf("Fehler: %s\n", e.what());
-	    }
-	}
-
-        /// @brief Handle the PSN_WIZNEXT message.
-        /// @param hwndDlg Handle to active page dialog.
-        /// @param index Index of current page.
-        /// @return TRUE if the message was handled. FALSE otherwise. 
-	virtual BOOL WizardNext(HWND hwndDlg, unsigned index)
-	{
-#ifdef _DEBUG
-	    printf("%s %d\n", __FUNCTION__, index);
-#endif
-	    switch (PageID(index))
-	    {
-		case IDD_DISPLAY:
-                    // Check for select window mode
-		    if (IsDlgButtonChecked(hwndDlg, IDC_MULTIWINDOW))
-			config.window = CConfig::MultiWindow;
-		    else if (IsDlgButtonChecked(hwndDlg, IDC_FULLSCREEN))
-			config.window = CConfig::Fullscreen;
-		    else if (IsDlgButtonChecked(hwndDlg, IDC_WINDOWED))
-			config.window = CConfig::Windowed;
-		    else if (IsDlgButtonChecked(hwndDlg, IDC_NODECORATION))
-			config.window = CConfig::Nodecoration;
-		    else
-		    {
-			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
-			return TRUE;
-		    }
-                    // Get selected display number
-		    {
-			char buffer[512];
-			GetDlgItemText(hwndDlg, IDC_DISPLAY, buffer, 512);
-			buffer[511] = 0;
-			config.display = buffer;
-                    }
-                    // Check for valid input
-                    if (config.display.empty())
-			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
-                    else
-                        SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIENTS);
-		    return TRUE;
-		case IDD_CLIENTS:
-                    // Check for select client startup method
-		    if (IsDlgButtonChecked(hwndDlg, IDC_CLIENT))
-		    {
-			config.client = CConfig::StartProgram;
-			SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_PROGRAM);
-		    } else if (IsDlgButtonChecked(hwndDlg, IDC_XDMCP))
-		    {
-			config.client = CConfig::XDMCP;
-			SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_XDMCP);
-		    } else if (IsDlgButtonChecked(hwndDlg, IDC_CLIENT_NONE))
-		    {
-			config.client = CConfig::NoClient;
-			SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIPBOARD);
-		    } else
-			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
-		    return TRUE;
-		case IDD_PROGRAM:
-                    // Check wether local or remote client should be started
-		    if (IsDlgButtonChecked(hwndDlg, IDC_CLIENT_LOCAL))
-			config.local = true;
-		    else if (IsDlgButtonChecked(hwndDlg, IDC_CLIENT_REMOTE))
-			config.local = false;
-		    else
-		    {
-			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
-			return TRUE;
-		    }
-                    // Read program, user and host name
-		    {
-			char buffer[512];
-			GetDlgItemText(hwndDlg, IDC_CLIENT_USER, buffer, 512);
-			buffer[511] = 0;
-			config.user = buffer;
-			GetDlgItemText(hwndDlg, IDC_CLIENT_HOST, buffer, 512);
-			buffer[511] = 0;
-			config.host = buffer;
-			GetDlgItemText(hwndDlg, IDC_CLIENT_PROGRAM, buffer, 512);
-			buffer[511] = 0;
-			config.program = buffer;
-		    }
-                    // Check for valid input
-		    if (!config.local && (config.host.empty() || config.program.empty()))
-			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
-		    else
-			SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIPBOARD);
-		    return TRUE;
-		case IDD_XDMCP:
-                    // Check for broadcast
-		    if (IsDlgButtonChecked(hwndDlg, IDC_XDMCP_BROADCAST))
-			config.broadcast = true;
-		    else if (IsDlgButtonChecked(hwndDlg, IDC_XDMCP_QUERY))
-			config.broadcast = false;
-		    else
-		    {
-			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
-			return TRUE;
-		    }
-                    // Check for indirect mode
-		    if (IsDlgButtonChecked(hwndDlg, IDC_XDMCP_INDIRECT))
-			config.indirect = true;
-		    else
-			config.indirect = false;
-                    // Read hostname
-		    {
-			char buffer[512];
-			GetDlgItemText(hwndDlg, IDC_XDMCP_HOST, buffer, 512);
-			buffer[511] = 0;
-			config.xdmcp_host = buffer;
-		    }
-                    // Check for valid input
-		    if (!config.broadcast && config.xdmcp_host.empty())
-			SetWindowLong(hwndDlg, DWL_MSGRESULT, -1);
-		    else	
-			SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIPBOARD);
-		    return TRUE;
-                case IDD_CLIPBOARD:
-                    // check for clipboard
-                    if (IsDlgButtonChecked(hwndDlg, IDC_CLIPBOARD))
-                        config.clipboard = true;
-                    else
-                        config.clipboard = false;
-                    // read parameters
-		    {
-			char buffer[512];
-			GetDlgItemText(hwndDlg, IDC_EXTRA_PARAMS, buffer, 512);
-			buffer[511] = 0;
-			config.extra_params = buffer;
-		    }
-                    SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_FINISH);
-                    return TRUE;
-		default:
-		    break;
-	    }
-	    return FALSE;
-	}
-        /// @brief Handle PSN_WIZFINISH message.
-        /// @param hwndDlg Handle to active page dialog.
-        /// @param index Index of current page.
-        /// @return TRUE if the message was handled. FALSE otherwise. 
-	virtual BOOL WizardFinish(HWND hwndDlg, unsigned index)
-	{
-#ifdef _DEBUG
-	    printf("finish %d\n", index);
-#endif
-	    return FALSE;
-	}
-        /// @brief Handle PSN_WIZBACK message.
-        /// Basicly handles switching to proper page (skipping XDMCP or program page
-        /// if required).
-        /// @param hwndDlg Handle to active page dialog.
-        /// @param index Index of current page.
-        /// @return TRUE if the message was handled. FALSE otherwise. 
-	virtual BOOL WizardBack(HWND hwndDlg, unsigned index)
-	{
-	    switch (PageID(index))
-	    {
-		case IDD_PROGRAM:
-		case IDD_XDMCP:
-		    SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIENTS);
-		    return TRUE;
-		case IDD_FONTPATH:
-                case IDD_CLIPBOARD: // temporary. fontpath is disabled
-		    switch (config.client)
-		    {
-			case CConfig::NoClient:	
-			    SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIENTS);
-			    return TRUE;
-			case CConfig::StartProgram:
-			    SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_PROGRAM);
-			    return TRUE;
-			case CConfig::XDMCP:
-			    SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_XDMCP);
-			    return TRUE;
-		    }
-		    break;
-	    }
-	    return FALSE;
-	}
-        /// @brief Handle PSN_SETACTIVE message.
-        /// @param hwndDlg Handle to active page dialog.
-        /// @param index Index of current page.
-        /// @return TRUE if the message was handled. FALSE otherwise. 
-	virtual BOOL WizardActivate(HWND hwndDlg, unsigned index)
-	{
-#ifdef _DEBUG
-	    printf("%s %d\n", __FUNCTION__, index);
-#endif
-	    switch (PageID(index))
-	    {
-		case IDD_CLIENTS:
-                    // Enable or disable XDMCP radiobutton and text
-		    EnableWindow(GetDlgItem(hwndDlg, IDC_XDMCP), config.window != CConfig::MultiWindow);
-		    EnableWindow(GetDlgItem(hwndDlg, IDC_XDMCP_DESC), config.window != CConfig::MultiWindow);
-		    break;
-	    }
-	    return FALSE;
-	}
-    protected:
-        /// @brief Enable or disable the control for remote clients.
-        /// @param hwndDlg Handle to active page dialog.
-        /// @param state State of control group.
-	void EnableRemoteProgramGroup(HWND hwndDlg, BOOL state)
-	{
-	    EnableWindow(GetDlgItem(hwndDlg, IDC_CLIENT_PROTOCOL), state);
-	    EnableWindow(GetDlgItem(hwndDlg, IDC_CLIENT_HOST), state);
-	    EnableWindow(GetDlgItem(hwndDlg, IDC_CLIENT_USER), state);
-	    EnableWindow(GetDlgItem(hwndDlg, IDC_CLIENT_PROTOCOL_DESC), state);
-	    EnableWindow(GetDlgItem(hwndDlg, IDC_CLIENT_HOST_DESC), state);
-	    EnableWindow(GetDlgItem(hwndDlg, IDC_CLIENT_USER_DESC), state);
-	}
-        /// @brief Enable or disable the control for XDMCP connection.
-        /// @param hwndDlg Handle to active page dialog.
-        /// @param state State of control group.
-	void EnableXDMCPQueryGroup(HWND hwndDlg, BOOL state)
-	{
-	    EnableWindow(GetDlgItem(hwndDlg, IDC_XDMCP_HOST), state);
-	    EnableWindow(GetDlgItem(hwndDlg, IDC_XDMCP_INDIRECT), state);
-	}
-        /// @brief Fill program box with default values.
-        /// @param hwndDlg Handle to active page dialog.
-	void FillProgramBox(HWND hwndDlg)
-	{
-	    HWND cbwnd = GetDlgItem(hwndDlg, IDC_CLIENT_PROGRAM);
-	    if (cbwnd == NULL)
-		return;
-	    SendMessage(cbwnd, CB_RESETCONTENT, 0, 0);
-	    SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) "xterm");
-	    SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) "startkde");
-	    SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) "gnome-session");
-	    SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) ".xinitrc");
-	    SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) "wmaker");
-	    SendMessage(cbwnd, CB_SETCURSEL, 0, 0);
-	}
-        /// @brief Fill protocol box with default values.
-        /// @param hwndDlg Handle to active page dialog.
-	void FillProtocolBox(HWND hwndDlg)
-	{
-	    HWND cbwnd = GetDlgItem(hwndDlg, IDC_CLIENT_PROTOCOL);
-	    if (cbwnd == NULL)
-		return;
-	    SendMessage(cbwnd, CB_RESETCONTENT, 0, 0);
-	    SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) "Putty");
-	    //SendMessage(cbwnd, CB_ADDSTRING, 0, (LPARAM) "OpenSSH");
-	    SendMessage(cbwnd, CB_SETCURSEL, 0, 0);
-	}
-	void ShowSaveDialog(HWND parent)
-	{
-	    char szTitle[512];
-	    char szFilter[512];
-	    char szFileTitle[512];
-	    char szFile[MAX_PATH];
-	    HINSTANCE hInst = GetModuleHandle(NULL);
-	    
-	    LoadString(hInst, IDS_SAVE_TITLE, szTitle, sizeof(szTitle));
-	    LoadString(hInst, IDS_SAVE_FILETITLE, szFileTitle, sizeof(szFileTitle));
-	    LoadString(hInst, IDS_SAVE_FILTER, szFilter, sizeof(szFilter));
-	    for (unsigned i=0; szFilter[i]; i++) 
-		if (szFilter[i] == '%') 
-		    szFilter[i] = '\0'; 
-
-	    strcpy(szFile, "config.xlaunch");
-
-	    OPENFILENAME ofn;
-	    memset(&ofn, 0, sizeof(OPENFILENAME));
-	    ofn.lStructSize = sizeof(OPENFILENAME); 
-	    ofn.hwndOwner = parent; 
-	    ofn.lpstrFilter = szFilter; 
-	    ofn.lpstrFile= szFile; 
-	    ofn.nMaxFile = sizeof(szFile)/ sizeof(*szFile); 
-	    ofn.lpstrFileTitle = szFileTitle; 
-	    ofn.nMaxFileTitle = sizeof(szFileTitle); 
-	    ofn.lpstrInitialDir = (LPSTR)NULL; 
-	    ofn.Flags = OFN_SHOWHELP | OFN_OVERWRITEPROMPT; 
-	    ofn.lpstrTitle = szTitle;
-
-	    if (GetSaveFileName(&ofn))
-	    {
-		try {
-      		    config.Save(ofn.lpstrFile);
-		} catch (std::runtime_error &e)
-		{
-		    printf("Fehler: %s\n", e.what());
-		}
-	    } 
-	}
-    public:
-	   
-        /// @brief Handle messages fo the dialog pages.
-        /// @param hwndDlg Handle of active dialog.
-        /// @param uMsg Message code.
-        /// @param wParam Message parameter.
-        /// @param lParam Message parameter.
-        /// @param psp Handle to sheet paramters. 
-        virtual INT_PTR PageDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam, PROPSHEETPAGE *psp)
-        {
-            HWND hwnd;
-            switch (uMsg)
-            {
-                case WM_INITDIALOG:
-                    switch (PageID(PageIndex(psp)))
-                    {
-                        case IDD_DISPLAY:
-                            // Init display dialog. Enable correct check buttons
-			    switch (config.window)
-			    {
-				default:
-				case CConfig::MultiWindow:
-				    CheckRadioButton(hwndDlg, IDC_MULTIWINDOW, IDC_NODECORATION, IDC_MULTIWINDOW);
-				    break;
-				case  CConfig::Fullscreen:
-				    CheckRadioButton(hwndDlg, IDC_MULTIWINDOW, IDC_NODECORATION, IDC_FULLSCREEN);
-				    break;
-				case  CConfig::Windowed:
-				    CheckRadioButton(hwndDlg, IDC_MULTIWINDOW, IDC_NODECORATION, IDC_WINDOWED);
-				    break;
-				case  CConfig::Nodecoration:
-				    CheckRadioButton(hwndDlg, IDC_MULTIWINDOW, IDC_NODECORATION, IDC_NODECORATION);
-				    break;
-			    }
-                            // Set display number
-                            SetDlgItemText(hwndDlg, IDC_DISPLAY, config.display.c_str());
-                            break;
-                        case IDD_CLIENTS:
-                            // Init client dialog. Enable correct check buttons
-			    switch (config.client)
-			    {
-				default:
-				case CConfig::NoClient:
-				    CheckRadioButton(hwndDlg, IDC_CLIENT_NONE, IDC_CLIENT, IDC_CLIENT_NONE);
-				    break;
-				case CConfig::StartProgram:
-				    CheckRadioButton(hwndDlg, IDC_CLIENT_NONE, IDC_CLIENT, IDC_CLIENT);
-				    break;
-				case CConfig::XDMCP:
-				    CheckRadioButton(hwndDlg, IDC_CLIENT_NONE, IDC_CLIENT, IDC_XDMCP);
-				    break;
-			    }
-                            break;
-			case IDD_PROGRAM:
-                            // Init program dialog. Check local and remote buttons 
-                            CheckRadioButton(hwndDlg, IDC_CLIENT_LOCAL, IDC_CLIENT_REMOTE, config.local?IDC_CLIENT_LOCAL:IDC_CLIENT_REMOTE);
-			    EnableRemoteProgramGroup(hwndDlg, config.local?FALSE:TRUE);
-                            // Fill combo boxes
-			    FillProgramBox(hwndDlg);
-			    FillProtocolBox(hwndDlg);
-                            // Set edit fields
-			    if (!config.program.empty())
-			       	SetDlgItemText(hwndDlg, IDC_CLIENT_PROGRAM, config.program.c_str());
-			    SetDlgItemText(hwndDlg, IDC_CLIENT_USER, config.user.c_str());
-			    SetDlgItemText(hwndDlg, IDC_CLIENT_HOST, config.host.c_str());
-			    break;
-			case IDD_XDMCP:
-                            // Init XDMCP dialog. Check broadcast and indirect button
-                            CheckRadioButton(hwndDlg, IDC_XDMCP_QUERY, IDC_XDMCP_BROADCAST, config.broadcast?IDC_XDMCP_BROADCAST:IDC_XDMCP_QUERY);
-                            CheckDlgButton(hwndDlg, IDC_XDMCP_INDIRECT, config.indirect?BST_CHECKED:BST_UNCHECKED);
-			    EnableXDMCPQueryGroup(hwndDlg, config.broadcast?FALSE:TRUE);
-                            // Set hostname
-			    SetDlgItemText(hwndDlg, IDC_XDMCP_HOST, config.xdmcp_host.c_str());
-			    break;
-                        case IDD_CLIPBOARD:
-                            CheckDlgButton(hwndDlg, IDC_CLIPBOARD, config.clipboard?BST_CHECKED:BST_UNCHECKED);
-                            SetDlgItemText(hwndDlg, IDC_EXTRA_PARAMS, config.extra_params.c_str());
-                            break;
-
-                    }
-                case WM_COMMAND:
-                    // Handle control messages
-                    switch (LOWORD(wParam))
-                    {
-                        // Handle clicks on images. Check proper radiobutton
-                        case IDC_MULTIWINDOW_IMG:
-                        case IDC_FULLSCREEN_IMG:
-                        case IDC_WINDOWED_IMG:
-                        case IDC_NODECORATION_IMG:
-                            CheckRadioButton(hwndDlg, IDC_MULTIWINDOW, IDC_NODECORATION, LOWORD(wParam)-4);
-                            SetFocus(GetDlgItem(hwndDlg, LOWORD(wParam)-4));
-                            break;
-                        // Disable unavailable controls 
-                        case IDC_CLIENT_REMOTE:
-                        case IDC_CLIENT_LOCAL:
-			    EnableRemoteProgramGroup(hwndDlg, LOWORD(wParam) == IDC_CLIENT_REMOTE);
-                            break;
-			case IDC_XDMCP_QUERY:
-			case IDC_XDMCP_BROADCAST:
-			    EnableXDMCPQueryGroup(hwndDlg, LOWORD(wParam) == IDC_XDMCP_QUERY);
-			    break;
-			case IDC_FINISH_SAVE:
-			    ShowSaveDialog(hwndDlg);
-			    break;
-                    }
-            }
-            // pass messages to parent
-            return CWizard::PageDispatch(hwndDlg, uMsg, wParam, lParam, psp);
-        }
-        
-        /// @brief Try to connect to server.
-        /// Repeat until successful, server died or maximum number of retries
-        /// reached.
-        Display *WaitForServer(HANDLE serverProcess)
-        {
-            int     ncycles  = 120;         /* # of cycles to wait */
-            int     cycles;                 /* Wait cycle count */
-            Display *xd;
-
-            for (cycles = 0; cycles < ncycles; cycles++) {
-                if ((xd = XOpenDisplay(NULL))) {
-                    return xd;
-                }
-                else {
-                    if (WaitForSingleObject(serverProcess, 1000) == WAIT_TIMEOUT)
-                        continue;
-                }
-            }
-            return NULL;
-        }
-               
-        /// @brief Do the actual start of Xming and clients
-	void StartUp()
-	{
-	    std::string buffer;
-	    std::string client;
-
-            // Construct display strings
-	    std::string display_id = ":" + config.display;
-	    std::string display = "localhost" + display_id + ":0";
-
-#ifdef _DEBUG
-            // Debug only: Switch to Xming installation directory
-	    SetCurrentDirectory("C:\\Programme\\Xming");
-#endif	    
-
-            // Build Xming commandline
-	    buffer = "Xming " + display_id + " ";
-	    switch (config.window)
-	    {
-		case CConfig::MultiWindow:
-		    buffer += "-multiwindow ";
-		    break;
-		case CConfig::Fullscreen:
-		    buffer += "-fullscreen ";
-		    break;
-		case CConfig::Nodecoration:
-		    buffer += "-nodecoration ";
-		    break;
-		default:
-		    break;
-	    }
-            // Add XDMCP parameter
-	    if (config.client == CConfig::XDMCP)
-	    {
-		if (config.broadcast)
-		    buffer += "-broadcast ";
-		else 
-		{
-		    if (config.indirect)
-			buffer += "-indirect ";
-		    else
-			buffer += "-query ";
-		    buffer += config.xdmcp_host;
-            buffer += " ";
-		}
-	    }
-            if (config.clipboard)
-                buffer += "-clipboard ";
-            if (!config.extra_params.empty())
-            {
-                buffer += config.extra_params;
-                buffer += " ";
-            }
-            
-            // Construct client commandline
-	    if (config.client == CConfig::StartProgram)
-	    {
-		if (!config.local)
-		{
-		    char cmdline[512];
-                    std::string host = config.host;
-                    if (!config.user.empty())
-                        host = config.user + "@" + config.host;
-		    if (config.protocol == "Putty")
-			snprintf(cmdline,512,"plink -X %s %s", 
-                                host.c_str(),config.program.c_str());
-		    else
-			snprintf(cmdline,512,"ssh -Y %s %s", 
-                                host.c_str(),config.program.c_str());
-		    client += cmdline;
-		} else
-		    client += config.program.c_str();
-	    }
-
-            // Prepare program startup
-     	    STARTUPINFO si, sic;
-	    PROCESS_INFORMATION pi, pic;
-	    HANDLE handles[2];
-	    DWORD hcount = 0; 
-            Display *dpy = NULL;
-
-	    ZeroMemory( &si, sizeof(si) );
-	    si.cb = sizeof(si);
-	    ZeroMemory( &pi, sizeof(pi) );
-	    ZeroMemory( &sic, sizeof(sic) );
-	    sic.cb = sizeof(sic);
-	    ZeroMemory( &pic, sizeof(pic) );
-
-	    // Start Xming process. 
-#ifdef _DEBUG
-	    printf("%s\n", buffer.c_str());
-#endif
-	    if( !CreateProcess( NULL, (CHAR*)buffer.c_str(), NULL, NULL, 
-                        FALSE, 0, NULL, NULL, &si, &pi )) 
-		throw win32_error("CreateProcess failed");
-	    handles[hcount++] = pi.hProcess;
-
-	    if (!client.empty())
-	    {
-                // Set DISPLAY variable
-		SetEnvironmentVariable("DISPLAY",display.c_str());
-
-                // Wait for server to startup
-                dpy = WaitForServer(pi.hProcess);
-                if (dpy == NULL)
-                {
-                    while (hcount--)
-                        TerminateProcess(handles[hcount], (DWORD)-1);
-		    throw std::runtime_error("Connection to server failed");
-                }
-                
-#ifdef _DEBUG
-		printf("%s\n", client.c_str());
-#endif
-
-                // Hide a console window 
-                // FIXME: This may make it impossible to enter the password
-		sic.dwFlags = STARTF_USESHOWWINDOW;
-		sic.wShowWindow = SW_HIDE;
-
-		// Start the child process. 
-		if( !CreateProcess( NULL, (CHAR*)client.c_str(), NULL, NULL,
-                            FALSE, 0, NULL, NULL, &sic, &pic )) 
-		{
-                    DWORD err = GetLastError();
-                    while (hcount--)
-                        TerminateProcess(handles[hcount], (DWORD)-1);
-		    throw win32_error("CreateProcess failed", err);
-		}
-		handles[hcount++] = pic.hProcess;
-	    }
-
-	    // Wait until any child process exits.
-	    DWORD ret = WaitForMultipleObjects(hcount, handles, FALSE, INFINITE );
-
-#ifdef _DEBUG
-	    printf("killing process!\n");
-#endif
-            // Check if Xming is still running
-	    DWORD exitcode;
-	    GetExitCodeProcess(pi.hProcess, &exitcode);
-	    unsigned counter = 0;
-	    while (exitcode == STILL_ACTIVE)
-	    {
-		if (++counter > 10)
-		    TerminateProcess(pi.hProcess, (DWORD)-1);
-		else
-		    // Shutdown Xming (the soft way!)
-		    EnumThreadWindows(pi.dwThreadId, KillWindowsProc, 0);
-		Sleep(500);
-		GetExitCodeProcess(pi.hProcess, &exitcode);
-	    }
-	    // Kill the client
-    	    TerminateProcess(pic.hProcess, (DWORD)-1);
-
-	    // Close process and thread handles. 
-	    CloseHandle( pi.hProcess );
-	    CloseHandle( pi.hThread );
-	    CloseHandle( pic.hProcess );
-	    CloseHandle( pic.hThread );
-	}
-};
-
-int main(int argc, char **argv)
-{
-    try {
-        InitCommonControls();
-        CMyWizard dialog;
-
-	bool skip_wizard = false;
-
-	for (int i = 1; i < argc; i++)
-	{
-	    if (argv[i] == NULL)
-		continue;
-	    
-	    std::string arg(argv[i]);
-	    if (arg == "-load" && i + 1 < argc)
-	    {
-		i++;
-		dialog.LoadConfig(argv[i]);
-		continue;
-	    }
-	    if (arg == "-run" && i + 1 < argc)
-	    {
-		i++;
-		dialog.LoadConfig(argv[i]);
-		skip_wizard = true;
-		continue;
-	    }
-	}
-
-	int ret = 0; 
-        if (skip_wizard || (ret =dialog.ShowModal()) != 0)
-	    dialog.StartUp();
-#ifdef _DEBUG
-	printf("return %d\n", ret);
-#endif
-	return 0;
-    } catch (std::runtime_error &e)
-    {
-        printf("Fehler: %s\n", e.what());
-        return -1;
-    }
-}
-
-
-
-
diff --git a/hw/xwin/xlaunch/resources/dialog.rc b/hw/xwin/xlaunch/resources/dialog.rc
deleted file mode 100755
index 8b00df4..0000000
--- a/hw/xwin/xlaunch/resources/dialog.rc
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#include <windows.h>
-#include "resources.h"
-
-#ifndef STR_CAPTION_DISPLAY
-#include "strings.rc"
-#endif
-
-IDD_DISPLAY DIALOGEX 0, 0, 317, 143
-STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_CENTERMOUSE
-CAPTION STR_CAPTION_DISPLAY
-FONT 8, "MS Shell Dlg", 400, 0, 0x1
-BEGIN
-    AUTORADIOBUTTON STR_MULTIWINDOW,IDC_MULTIWINDOW,7,25,70,24,BS_MULTILINE|BS_TOP
-    AUTORADIOBUTTON STR_FULLSCREEN,IDC_FULLSCREEN,157,25,70,24,BS_MULTILINE|BS_TOP
-    AUTORADIOBUTTON STR_WINDOWED,IDC_WINDOWED,7,75,70,24,BS_MULTILINE|BS_TOP
-    AUTORADIOBUTTON STR_NODECORATION,IDC_NODECORATION,157,75,70,24,BS_MULTILINE|BS_TOP
-
-    CONTROL         "IMG_MULTIWINDOW",IDC_MULTIWINDOW_IMG,"Static",SS_BITMAP | SS_NOTIFY,80,10,0,0
-    CONTROL         "IMG_FULLSCREEN",IDC_FULLSCREEN_IMG,"Static",SS_BITMAP | SS_NOTIFY,230,10,0,0
-    CONTROL         "IMG_WINDOWED",IDC_WINDOWED_IMG,"Static",SS_BITMAP | SS_NOTIFY,80,60,0,0
-    CONTROL         "IMG_NODECORATION",IDC_NODECORATION_IMG,"Static",SS_BITMAP | SS_NOTIFY,230,60,0,0
-
-    LTEXT           STR_DISPLAY_DESC,IDC_DISPLAY_DESC,7,120,64,12
-    EDITTEXT        IDC_DISPLAY,80,118,67,12,ES_NUMBER
-END
-
-IDD_CLIENTS DIALOGEX 0, 0, 317, 143
-STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_CENTERMOUSE
-CAPTION STR_CAPTION_CLIENTS
-FONT 8, "MS Shell Dlg", 400, 0, 0x1
-BEGIN
-    AUTORADIOBUTTON STR_CLIENT_NONE,IDC_CLIENT_NONE,7,14,300,10
-    AUTORADIOBUTTON STR_CLIENT,IDC_CLIENT,7,56,300,10
-    AUTORADIOBUTTON STR_XDMCP,IDC_XDMCP,7,98,300,10
-
-    LTEXT           STR_CLIENT_NONE_DESC,IDC_CLIENT_NONE_DESC,19,28,280,27
-    LTEXT           STR_CLIENT_DESC,IDC_CLIENT_DESC,19,70,280,27
-    LTEXT           STR_XDMCP_DESC,IDC_XDMCP_DESC,19,112,280,27
-END
-
-IDD_PROGRAM DIALOGEX 0, 0, 317, 143
-STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_CENTERMOUSE
-CAPTION STR_CAPTION_PROGRAM
-FONT 8, "MS Shell Dlg", 400, 0, 0x1
-BEGIN
-    LTEXT           STR_CLIENT_PROGRAM_DESC,IDC_CLIENT_PROGRAM_DESC,7,14,64,10
-    COMBOBOX        IDC_CLIENT_PROGRAM,70,12,64,54,CBS_DROPDOWN | WS_VSCROLL
-
-    AUTORADIOBUTTON STR_CLIENT_LOCAL,IDC_CLIENT_LOCAL,7,28,300,10
-    AUTORADIOBUTTON STR_CLIENT_REMOTE,IDC_CLIENT_REMOTE,7,42,300,10
-    
-    LTEXT           STR_CLIENT_PROTOCOL_DESC,IDC_CLIENT_PROTOCOL_DESC,19,56,70,10
-    COMBOBOX        IDC_CLIENT_PROTOCOL,100,54,64,54,CBS_DROPDOWNLIST | WS_VSCROLL
-    
-    LTEXT           STR_CLIENT_HOST_DESC,IDC_CLIENT_HOST_DESC,19,70,70,10
-    LTEXT           STR_CLIENT_USER_DESC,IDC_CLIENT_USER_DESC,19,84,70,10
-    EDITTEXT        IDC_CLIENT_HOST,100,68,64,12
-    EDITTEXT        IDC_CLIENT_USER,100,82,64,12
-END
-
-IDD_XDMCP DIALOGEX 0, 0, 317, 143
-STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_CENTERMOUSE
-CAPTION STR_CAPTION_XDMCP
-FONT 8, "MS Shell Dlg", 400, 0, 0x1
-BEGIN
-    AUTORADIOBUTTON STR_XDMCP_QUERY, IDC_XDMCP_QUERY,7,14,64,10
-    EDITTEXT        IDC_XDMCP_HOST,78,12,64,12
-    AUTOCHECKBOX    STR_XDMCP_INDIRECT,IDC_XDMCP_INDIRECT,19,28,280,10
-    AUTORADIOBUTTON STR_XDMCP_BROADCAST, IDC_XDMCP_BROADCAST,7,42,300,10
-    LTEXT           STR_XDMCP_QUERY_DESC,IDC_XDMCP_QUERY_DESC,7,56,300,42
-END
-
-IDD_CLIPBOARD DIALOGEX 0, 0, 317, 143
-STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_CENTERMOUSE
-CAPTION STR_CAPTION_CLIPBOARD
-FONT 8, "MS Shell Dlg", 400, 0, 0x1
-BEGIN
-    AUTOCHECKBOX    STR_CLIPBOARD,IDC_CLIPBOARD,7,14,300,10
-    LTEXT           STR_CLIPBOARD_DESC,IDC_CLIPBOARD_DESC,19,28,280,27
-
-    LTEXT           STR_EXTRA_PARAMS_DESC,IDC_EXTRA_PARAMS_DESC,7,56,280,10
-    EDITTEXT        IDC_EXTRA_PARAMS,7,70,128,12
-END
-
-IDD_FINISH DIALOGEX 0, 0, 317, 143
-STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_CENTERMOUSE
-CAPTION STR_CAPTION_FINISH
-FONT 8, "MS Shell Dlg", 400, 0, 0x1
-BEGIN
-    LTEXT           STR_FINISH_DESC,IDC_FINISH_DESC,7,14,300,28
-    LTEXT           STR_FINISH_SAVE_DESC,IDC_FINISH_SAVE_DESC,7,56,300,12
-    PUSHBUTTON      STR_FINISH_SAVE,IDC_FINISH_SAVE,7,68,75,14 
-END
diff --git a/hw/xwin/xlaunch/resources/fullscreen.bmp b/hw/xwin/xlaunch/resources/fullscreen.bmp
deleted file mode 100755
index 0d051f0..0000000
Binary files a/hw/xwin/xlaunch/resources/fullscreen.bmp and /dev/null differ
diff --git a/hw/xwin/xlaunch/resources/images.rc b/hw/xwin/xlaunch/resources/images.rc
deleted file mode 100755
index 2eac53c..0000000
--- a/hw/xwin/xlaunch/resources/images.rc
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-IMG_MULTIWINDOW BITMAP "resources\\multiwindow.bmp"
-IMG_WINDOWED BITMAP "resources\\windowed.bmp"
-IMG_FULLSCREEN BITMAP "resources\\fullscreen.bmp"
-IMG_NODECORATION BITMAP "resources\\nodecoration.bmp"
diff --git a/hw/xwin/xlaunch/resources/multiwindow.bmp b/hw/xwin/xlaunch/resources/multiwindow.bmp
deleted file mode 100755
index 0755c87..0000000
Binary files a/hw/xwin/xlaunch/resources/multiwindow.bmp and /dev/null differ
diff --git a/hw/xwin/xlaunch/resources/nodecoration.bmp b/hw/xwin/xlaunch/resources/nodecoration.bmp
deleted file mode 100755
index e9e1ce6..0000000
Binary files a/hw/xwin/xlaunch/resources/nodecoration.bmp and /dev/null differ
diff --git a/hw/xwin/xlaunch/resources/resources.h b/hw/xwin/xlaunch/resources/resources.h
deleted file mode 100755
index 4700051..0000000
--- a/hw/xwin/xlaunch/resources/resources.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-
-#define IDC_STATIC -1
-
-#define IDD_WELCOME             100
-#define IDD_FINISH              101
-#define IDD_DISPLAY             102
-#define IDD_CLIENTS             103
-#define IDD_PROGRAM             104
-#define IDD_XDMCP               105
-#define IDD_FONTPATH            106
-#define IDD_CLIPBOARD           107
-
-#define IDS_DISPLAY_TITLE       300
-#define IDS_DISPLAY_SUBTITLE    301
-#define IDS_CLIENTS_TITLE       302
-#define IDS_CLIENTS_SUBTITLE    303
-#define IDS_PROGRAM_TITLE       304
-#define IDS_PROGRAM_SUBTITLE    305
-#define IDS_XDMCP_TITLE         306
-#define IDS_XDMCP_SUBTITLE      307
-#define IDS_FONTPATH_TITLE      308
-#define IDS_FONTPATH_SUBTITLE   309
-#define IDS_FINISH_TITLE        310
-#define IDS_FINISH_SUBTITLE     311
-#define IDS_CLIPBOARD_TITLE     312
-#define IDS_CLIPBOARD_SUBTITLE  313
-#define IDS_SAVE_TITLE          320
-#define IDS_SAVE_FILETITLE      321
-#define IDS_SAVE_FILTER         322
-                
-#define IDC_MULTIWINDOW         200
-#define IDC_WINDOWED            201
-#define IDC_FULLSCREEN          202
-#define IDC_NODECORATION        203
-#define IDC_MULTIWINDOW_IMG     204
-#define IDC_WINDOWED_IMG        205
-#define IDC_FULLSCREEN_IMG      206
-#define IDC_NODECORATION_IMG    207
-#define IDC_DISPLAY             208
-#define IDC_DISPLAY_DESC        209
-
-#define IDC_CLIENT_NONE         210
-#define IDC_XDMCP               211
-#define IDC_CLIENT              212
-#define IDC_CLIENT_LOCAL        213
-#define IDC_CLIENT_REMOTE       214
-#define IDC_CLIENT_HOST         215
-#define IDC_CLIENT_USER         216
-#define IDC_CLIENT_PROTOCOL     217
-#define IDC_CLIENT_CONFIGURE    218
-#define IDC_CLIENT_PROGRAM      219
-#define IDC_XDMCP_QUERY         220
-#define IDC_XDMCP_BROADCAST     221
-#define IDC_XDMCP_INDIRECT      222
-#define IDC_XDMCP_HOST          223
-#define IDC_CLIENT_NONE_DESC    224
-#define IDC_XDMCP_DESC          225
-#define IDC_CLIENT_DESC         226
-#define IDC_XDMCP_QUERY_DESC    227
-#define IDC_CLIENT_PROGRAM_DESC 228
-#define IDC_CLIENT_HOST_DESC    229
-#define IDC_CLIENT_USER_DESC    230
-#define IDC_CLIENT_PROTOCOL_DESC 231
-
-#define IDC_FONTPATH_DESC        240
-
-#define IDC_FINISH_DESC		 250
-#define IDC_FINISH_SAVE		 251
-#define IDC_FINISH_SAVE_DESC     252
-
-#define IDC_CLIPBOARD            260
-#define IDC_CLIPBOARD_DESC       261
-#define IDC_EXTRA_PARAMS         262
-#define IDC_EXTRA_PARAMS_DESC    263
diff --git a/hw/xwin/xlaunch/resources/resources.rc b/hw/xwin/xlaunch/resources/resources.rc
deleted file mode 100755
index 07fd52f..0000000
--- a/hw/xwin/xlaunch/resources/resources.rc
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#include <windows.h>
-
-#include "resources.h"
-#include "images.rc"
-#include "dialog.rc"
diff --git a/hw/xwin/xlaunch/resources/strings.rc b/hw/xwin/xlaunch/resources/strings.rc
deleted file mode 100644
index 5a9cd28..0000000
--- a/hw/xwin/xlaunch/resources/strings.rc
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-
-#define STR_CAPTION_DISPLAY         "Display settings"
-#define STR_MULTIWINDOW             "Multiple windows"
-#define STR_FULLSCREEN              "Fullscreen"
-#define STR_WINDOWED                "One large window"
-#define STR_NODECORATION            "One window without titlebar"
-#define STR_DISPLAY_DESC            "Display number"
-
-#define STR_CAPTION_CLIENTS         "Client startup"
-#define STR_CLIENT_NONE             "Start no client"
-#define STR_CLIENT_NONE_DESC		"This will just start the xserver. You will be able to start local clients later."
-#define STR_CLIENT					"Start a program"
-#define STR_CLIENT_DESC				"This will start a local or remote program which will connect to the xserver. You will be able to start local clients later too. Remote programs are started using SSH."
-#define STR_XDMCP					"Open session via XDMCP"
-#define STR_XDMCP_DESC				"This will start a remote XDMCP session. Starting local clients later is limited. This option is not available with the ""Multiple windows"" mode."
-
-#define STR_CAPTION_PROGRAM         "Start program"
-#define STR_CLIENT_PROGRAM_DESC     "Start program"
-#define STR_CLIENT_LOCAL            "Start program on this computer"
-#define STR_CLIENT_REMOTE           "Start program on remote computer"
-#define STR_CLIENT_PROTOCOL_DESC    "Connect using"
-#define STR_CLIENT_HOST_DESC        "Connect to computer"
-#define STR_CLIENT_USER_DESC        "Login as user"
-
-
-#define STR_CAPTION_XDMCP           "XDMCP settings"
-#define STR_XDMCP_QUERY             "Connect to host"
-#define STR_XDMCP_INDIRECT          "Use indirect connect"
-#define STR_XDMCP_BROADCAST         "Search for hosts (broadcast)"
-#define STR_XDMCP_QUERY_DESC        "Some XDMCP servers must be configured to allow remote connections. Please check the documentation about configuring XDMCP servers."
-
-
-#define STR_CAPTION_FONTPATH        "Fontpath settings"
-
-#define STR_CAPTION_CLIPBOARD       "Clipboard settings"
-#define STR_CLIPBOARD               "Clipboard"
-#define STR_CLIPBOARD_DESC          "Start the integrated clipboard manager"
-#define STR_EXTRA_PARAMS_DESC       "Additional parameters for Xming"
-
-#define STR_CAPTION_FINISH          "Finish configuration"
-#define STR_FINISH_DESC	            "Configuration is complete. Clish Finish to start Xming."
-#define STR_FINISH_SAVE_DESC        "You may also save the configuration for later use."
-#define STR_FINISH_SAVE	            "Save configuration"
-
-#define STR_DISPLAY_TITLE           "Select display settings"
-#define STR_DISPLAY_SUBTITLE        "Choose how Xming display programs"
-#define STR_CLIENTS_TITLE           "Select how to start clients"
-#define STR_CLIENTS_SUBTITLE        ""
-#define STR_PROGRAM_TITLE           "Specify the program to start"
-#define STR_PROGRAM_SUBTITLE        ""
-#define STR_XDMCP_TITLE             "Configure a remote XDMCP connection"
-#define STR_XDMCP_SUBTITLE          ""
-#define STR_FONTPATH_TITLE          "Define font locations"
-#define STR_FONTPATH_SUBTITLE       ""
-#define STR_FINISH_TITLE            "Configuration complete"
-#define STR_FINISH_SUBTITLE         ""
-#define STR_CLIPBOARD_TITLE         "Clipboard settings"
-#define STR_CLIPBOARD_SUBTITLE      ""
-
-#define STR_SAVE_TITLE              "Save configuration"
-#define STR_SAVE_FILETITLE          "Filename"
-#define STR_SAVE_FILTER             "Xlaunch Files (*.xlaunch)%*.xlaunch%%"
-
-STRINGTABLE
-BEGIN
-    IDS_DISPLAY_TITLE       STR_DISPLAY_TITLE       
-    IDS_DISPLAY_SUBTITLE    STR_DISPLAY_SUBTITLE    
-    IDS_CLIENTS_TITLE       STR_CLIENTS_TITLE       
-    IDS_CLIENTS_SUBTITLE    STR_CLIENTS_SUBTITLE    
-    IDS_PROGRAM_TITLE       STR_PROGRAM_TITLE       
-    IDS_PROGRAM_SUBTITLE    STR_PROGRAM_SUBTITLE    
-    IDS_XDMCP_TITLE         STR_XDMCP_TITLE         
-    IDS_XDMCP_SUBTITLE      STR_XDMCP_SUBTITLE      
-    IDS_FONTPATH_TITLE      STR_FONTPATH_TITLE      
-    IDS_FONTPATH_SUBTITLE   STR_FONTPATH_SUBTITLE   
-    IDS_FINISH_TITLE        STR_FINISH_TITLE      
-    IDS_FINISH_SUBTITLE     STR_FINISH_SUBTITLE   
-    IDS_CLIPBOARD_TITLE     STR_CLIPBOARD_TITLE      
-    IDS_CLIPBOARD_SUBTITLE  STR_CLIPBOARD_SUBTITLE   
-    IDS_SAVE_TITLE	    STR_SAVE_TITLE
-    IDS_SAVE_FILETITLE      STR_SAVE_FILETITLE
-    IDS_SAVE_FILTER         STR_SAVE_FILTER
-END
diff --git a/hw/xwin/xlaunch/resources/windowed.bmp b/hw/xwin/xlaunch/resources/windowed.bmp
deleted file mode 100755
index 9eff2bf..0000000
Binary files a/hw/xwin/xlaunch/resources/windowed.bmp and /dev/null differ
diff --git a/hw/xwin/xlaunch/window/dialog.cc b/hw/xwin/xlaunch/window/dialog.cc
deleted file mode 100755
index 76e5c35..0000000
--- a/hw/xwin/xlaunch/window/dialog.cc
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#include <stdio.h>
-#include "dialog.h"
-#include "util.h"
-
-CBaseDialog::CBaseDialog() : CWindow(""), result(0)
-{
-}
-
-CDialog::CDialog(const char *res) : CBaseDialog(), resourcename(res) 
-{
-}
-
-HWND CDialog::CreateWindowHandle()
-{
-    HWND ret = CreateDialog(
-            GetModuleHandle(NULL),
-            resourcename.c_str(),
-            NULL,
-            DialogProc);
-    if (ret == NULL)
-        throw win32_error("CreateDialog failed");
-    return ret;
-}
-
-INT_PTR CALLBACK CBaseDialog::DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
-{
-    MessageDebug::debug(hwndDlg, uMsg, wParam, lParam, __FUNCTION__);
-	CBaseDialog* dialog = (CDialog*)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
-	if (dialog != NULL)
-	    return dialog->DlgDispatch(hwndDlg, uMsg, wParam, lParam);
-    return FALSE;
-}
-
-INT_PTR CBaseDialog::DlgDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
-{
-    switch (uMsg)
-    {
-        case WM_COMMAND:
-            switch (LOWORD(wParam))
-            {
-                case IDOK:
-                case IDCANCEL:
-                    result = wParam;
-                    EndDialog(hwndDlg, wParam);
-                    DestroyWindow(hwndDlg);
-                    return TRUE;
-            }
-            break;
-    }
-    return FALSE;
-}
-
-INT_PTR CDialog::DlgDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
-{
-    return CBaseDialog::DlgDispatch(hwndDlg, uMsg, wParam, lParam);
-}
-
-int CBaseDialog::Execute()
-{
-    return CWindow::ShowModal();
-}
diff --git a/hw/xwin/xlaunch/window/dialog.h b/hw/xwin/xlaunch/window/dialog.h
deleted file mode 100755
index 073394b..0000000
--- a/hw/xwin/xlaunch/window/dialog.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#ifndef __DIALOG_H__
-#define __DIALOG_H__
-
-#include "window.h"
-class CBaseDialog : public CWindow
-{
-    private:
-        int result;
-    protected:
-        static INT_PTR CALLBACK DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
-        virtual INT_PTR DlgDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
-    public:
-        CBaseDialog();
-        int Execute();
-};
-
-class CDialog : public CBaseDialog
-{
-    private:
-        std::string resourcename;
-    protected:
-        virtual INT_PTR DlgDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
-        virtual HWND CreateWindowHandle();
-    public:
-        CDialog(const char *res);
-};
-
-
-#endif
diff --git a/hw/xwin/xlaunch/window/util.cc b/hw/xwin/xlaunch/window/util.cc
deleted file mode 100644
index fb7e872..0000000
--- a/hw/xwin/xlaunch/window/util.cc
+++ /dev/null
@@ -1,1112 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#include "util.h"
-
-std::string win32_error::message(DWORD errorcode)
-{
-    LPVOID lpMsgBuf;
-    if (!FormatMessage( 
-                FORMAT_MESSAGE_ALLOCATE_BUFFER | 
-                FORMAT_MESSAGE_FROM_SYSTEM | 
-                FORMAT_MESSAGE_IGNORE_INSERTS,
-                NULL,
-                errorcode,
-                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
-                (LPTSTR) &lpMsgBuf,
-                0,
-                NULL ))
-    {
-        return "Unknown error in FormatMessage";
-    }
-
-    std::string ret((LPCTSTR)lpMsgBuf);
-    LocalFree( lpMsgBuf );
-    return ret;
-}
-
-void MessageDebug::debug(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, const char *prefix)
-{
-#ifdef _DEBUG
-    static const char *psn_notify[] = {
-        "PSN_SETACTIVE",
-        "PSN_KILLACTIVE",
-        "PSN_APPLY",
-        "PSN_RESET",
-        NULL,
-        "PSN_HELP",
-        "PSN_WIZBACK",
-        "PSN_WIZNEXT",
-        "PSN_WIZFINISH",
-        "PSN_QUERYCANCEL" };
-    if (uMsg == WM_NOTIFY)
-    {
-        LPNMHDR pnmh = (LPNMHDR)lParam;
-        int psn_index = -(int)pnmh->code - 200;
-        if (psn_index >= 0 && psn_index < 10 && psn_notify[psn_index])
-            printf("%s: %08x %04x WM_NOTIFY (%s)\n", prefix, hwnd, wParam, psn_notify[psn_index]);
-        else if (pnmh->code < NOTIFY_NAMES_LEN && notify_names[pnmh->code])
-            printf("%s: %08x %04x WM_NOTIFY (%s)\n", prefix, hwnd, wParam, notify_names[pnmh->code]);
-        else
-            printf("%s: %08x %04x WM_NOTIFY (%u)\n", prefix, hwnd, wParam, pnmh->code);
-    }   
-    else if (uMsg >= MESSAGE_NAMES_LEN)
-        if (uMsg >= WM_USER)
-            printf("%s: %08x %04x %08x WM_USER + %d\n", prefix, hwnd, wParam, lParam, uMsg - WM_USER); 
-        else
-            printf("%s: %08x %04x %08x %d\n", prefix, hwnd, wParam, lParam, uMsg);
-    else if (uMsg >= 0 && uMsg < MESSAGE_NAMES_LEN && message_names[uMsg])
-        printf("%s: %08x %04x %08x %s\n", prefix, hwnd, wParam, lParam, message_names[uMsg]);
-#endif
-}
-
-
-const char * MessageDebug::message_names[MESSAGE_NAMES_LEN] = {
-	"WM_NULL",
-	"WM_CREATE",
-	"WM_DESTROY",
-	"WM_MOVE",
-	"4",
-	"WM_SIZE",
-	"WM_ACTIVATE",
-	"WM_SETFOCUS",
-	"WM_KILLFOCUS",
-	"9",
-	"WM_ENABLE",
-	"WM_SETREDRAW",
-	"WM_SETTEXT",
-	"WM_GETTEXT",
-	"WM_GETTEXTLENGTH",
-	"WM_PAINT",
-	"WM_CLOSE",
-	"WM_QUERYENDSESSION",
-	"WM_QUIT",
-	"WM_QUERYOPEN",
-	"WM_ERASEBKGND",
-	"WM_SYSCOLORCHANGE",
-	"WM_ENDSESSION",
-	"23",
-	"WM_SHOWWINDOW",
-	"25",
-	"WM_WININICHANGE",
-	"WM_DEVMODECHANGE",
-	"WM_ACTIVATEAPP",
-	"WM_FONTCHANGE",
-	"WM_TIMECHANGE",
-	"WM_CANCELMODE",
-	NULL /* WM_SETCURSOR */,
-	"WM_MOUSEACTIVATE",
-	"WM_CHILDACTIVATE",
-	"WM_QUEUESYNC",
-	"WM_GETMINMAXINFO",
-	"37",
-	"WM_PAINTICON",
-	"WM_ICONERASEBKGND",
-	"WM_NEXTDLGCTL",
-	"41",
-	"WM_SPOOLERSTATUS",
-	"WM_DRAWITEM",
-	"WM_MEASUREITEM",
-	"WM_DELETEITEM",
-	"WM_VKEYTOITEM",
-	"WM_CHARTOITEM",
-	"WM_SETFONT",
-	"WM_GETFONT",
-	"WM_SETHOTKEY",
-	"WM_GETHOTKEY",
-	"52",
-	"53",
-	"54",
-	"WM_QUERYDRAGICON",
-	"56",
-	"WM_COMPAREITEM",
-	"58",
-	"59",
-	"60",
-	"61",
-	"62",
-	"63",
-	"64",
-	"WM_COMPACTING",
-	"66",
-	"67",
-	"WM_COMMNOTIFY",
-	"69",
-	"WM_WINDOWPOSCHANGING",
-	"WM_WINDOWPOSCHANGED",
-	"WM_POWER",
-	"73",
-	"WM_COPYDATA",
-	"WM_CANCELJOURNAL",
-	"76",
-	"77",
-	"WM_NOTIFY",
-	"79",
-	"WM_INPUTLANGCHANGEREQUEST",
-	"WM_INPUTLANGCHANGE",
-	"WM_TCARD",
-	"WM_HELP",
-	"WM_USERCHANGED",
-	"WM_NOTIFYFORMAT",
-	"86",
-	"87",
-	"88",
-	"89",
-	"90",
-	"91",
-	"92",
-	"93",
-	"94",
-	"95",
-	"96",
-	"97",
-	"98",
-	"99",
-	"100",
-	"101",
-	"102",
-	"103",
-	"104",
-	"105",
-	"106",
-	"107",
-	"108",
-	"109",
-	"110",
-	"111",
-	"112",
-	"113",
-	"114",
-	"115",
-	"116",
-	"117",
-	"118",
-	"119",
-	"120",
-	"121",
-	"122",
-	"WM_CONTEXTMENU",
-	"WM_STYLECHANGING",
-	"WM_STYLECHANGED",
-	"WM_DISPLAYCHANGE",
-	"WM_GETICON",
-	"WM_SETICON",
-	"WM_NCCREATE",
-	"WM_NCDESTROY",
-	"WM_NCCALCSIZE",
-	NULL /* WM_NCHITTEST */,
-	"WM_NCPAINT",
-	"WM_NCACTIVATE",
-	"WM_GETDLGCODE",
-	"WM_SYNCPAINT",
-	"137",
-	"138",
-	"139",
-	"140",
-	"141",
-	"142",
-	"143",
-	"144",
-	"145",
-	"146",
-	"147",
-	"148",
-	"149",
-	"150",
-	"151",
-	"152",
-	"153",
-	"154",
-	"155",
-	"156",
-	"157",
-	"158",
-	"159",
-	NULL /* WM_NCMOUSEMOVE */,
-	"WM_NCLBUTTONDOWN",
-	"WM_NCLBUTTONUP",
-	"WM_NCLBUTTONDBLCLK",
-	"WM_NCRBUTTONDOWN",
-	"WM_NCRBUTTONUP",
-	"WM_NCRBUTTONDBLCLK",
-	"WM_NCMBUTTONDOWN",
-	"WM_NCMBUTTONUP",
-	"WM_NCMBUTTONDBLCLK",
-	"170",
-	"171",
-	"172",
-	"173",
-	"174",
-	"175",
-	"176",
-	"177",
-	"178",
-	"179",
-	"180",
-	"181",
-	"182",
-	"183",
-	"184",
-	"185",
-	"186",
-	"187",
-	"188",
-	"189",
-	"190",
-	"191",
-	"192",
-	"193",
-	"194",
-	"195",
-	"196",
-	"197",
-	"198",
-	"199",
-	"200",
-	"201",
-	"202",
-	"203",
-	"204",
-	"205",
-	"206",
-	"207",
-	"208",
-	"209",
-	"210",
-	"211",
-	"212",
-	"213",
-	"214",
-	"215",
-	"216",
-	"217",
-	"218",
-	"219",
-	"220",
-	"221",
-	"222",
-	"223",
-	"224",
-	"225",
-	"226",
-	"227",
-	"228",
-	"229",
-	"230",
-	"231",
-	"232",
-	"233",
-	"234",
-	"235",
-	"236",
-	"237",
-	"238",
-	"239",
-	"240",
-	"241",
-	"242",
-	"243",
-	"244",
-	"245",
-	"246",
-	"247",
-	"248",
-	"249",
-	"250",
-	"251",
-	"252",
-	"253",
-	"254",
-	"255",
-	"WM_KEYDOWN",
-	"WM_KEYUP",
-	"WM_CHAR",
-	"WM_DEADCHAR",
-	"WM_SYSKEYDOWN",
-	"WM_SYSKEYUP",
-	"WM_SYSCHAR",
-	"WM_SYSDEADCHAR",
-	"WM_CONVERTREQUESTEX",
-	"265",
-	"266",
-	"267",
-	"268",
-	"WM_IME_STARTCOMPOSITION",
-	"WM_IME_ENDCOMPOSITION",
-	"WM_IME_KEYLAST",
-	"WM_INITDIALOG",
-	"WM_COMMAND",
-	"WM_SYSCOMMAND",
-	NULL /* WM_TIMER */,
-	"WM_HSCROLL",
-	"WM_VSCROLL",
-	"WM_INITMENU",
-	"WM_INITMENUPOPUP",
-	"280",
-	"281",
-	"282",
-	"283",
-	"284",
-	"285",
-	"286",
-	"WM_MENUSELECT",
-	"WM_MENUCHAR",
-	"WM_ENTERIDLE",
-	"290",
-	"291",
-	"292",
-	"293",
-	"294",
-	"295",
-	"296",
-	"297",
-	"298",
-	"299",
-	"300",
-	"301",
-	"302",
-	"303",
-	"304",
-	"305",
-	"WM_CTLCOLORMSGBOX",
-	"WM_CTLCOLOREDIT",
-	"WM_CTLCOLORLISTBOX",
-	"WM_CTLCOLORBTN",
-	"WM_CTLCOLORDLG",
-	"WM_CTLCOLORSCROLLBAR",
-	"WM_CTLCOLORSTATIC",
-	"313",
-	"314",
-	"315",
-	"316",
-	"317",
-	"318",
-	"319",
-	"320",
-	"321",
-	"322",
-	"323",
-	"324",
-	"325",
-	"326",
-	"327",
-	"328",
-	"329",
-	"330",
-	"331",
-	"332",
-	"333",
-	"334",
-	"335",
-	"336",
-	"337",
-	"338",
-	"339",
-	"340",
-	"341",
-	"342",
-	"343",
-	"344",
-	"345",
-	"346",
-	"347",
-	"348",
-	"349",
-	"350",
-	"351",
-	"352",
-	"353",
-	"354",
-	"355",
-	"356",
-	"357",
-	"358",
-	"359",
-	"360",
-	"361",
-	"362",
-	"363",
-	"364",
-	"365",
-	"366",
-	"367",
-	"368",
-	"369",
-	"370",
-	"371",
-	"372",
-	"373",
-	"374",
-	"375",
-	"376",
-	"377",
-	"378",
-	"379",
-	"380",
-	"381",
-	"382",
-	"383",
-	"384",
-	"385",
-	"386",
-	"387",
-	"388",
-	"389",
-	"390",
-	"391",
-	"392",
-	"393",
-	"394",
-	"395",
-	"396",
-	"397",
-	"398",
-	"399",
-	"400",
-	"401",
-	"402",
-	"403",
-	"404",
-	"405",
-	"406",
-	"407",
-	"408",
-	"409",
-	"410",
-	"411",
-	"412",
-	"413",
-	"414",
-	"415",
-	"416",
-	"417",
-	"418",
-	"419",
-	"420",
-	"421",
-	"422",
-	"423",
-	"424",
-	"425",
-	"426",
-	"427",
-	"428",
-	"429",
-	"430",
-	"431",
-	"432",
-	"433",
-	"434",
-	"435",
-	"436",
-	"437",
-	"438",
-	"439",
-	"440",
-	"441",
-	"442",
-	"443",
-	"444",
-	"445",
-	"446",
-	"447",
-	"448",
-	"449",
-	"450",
-	"451",
-	"452",
-	"453",
-	"454",
-	"455",
-	"456",
-	"457",
-	"458",
-	"459",
-	"460",
-	"461",
-	"462",
-	"463",
-	"464",
-	"465",
-	"466",
-	"467",
-	"468",
-	"469",
-	"470",
-	"471",
-	"472",
-	"473",
-	"474",
-	"475",
-	"476",
-	"477",
-	"478",
-	"479",
-	"480",
-	"481",
-	"482",
-	"483",
-	"484",
-	"485",
-	"486",
-	"487",
-	"488",
-	"489",
-	"490",
-	"491",
-	"492",
-	"493",
-	"494",
-	"495",
-	"496",
-	"497",
-	"498",
-	"499",
-	"500",
-	"501",
-	"502",
-	"503",
-	"504",
-	"505",
-	"506",
-	"507",
-	"508",
-	"509",
-	"510",
-	"511",
-	NULL /* WM_MOUSEMOVE */,
-	"WM_LBUTTONDOWN",
-	"WM_LBUTTONUP",
-	"WM_LBUTTONDBLCLK",
-	"WM_RBUTTONDOWN",
-	"WM_RBUTTONUP",
-	"WM_RBUTTONDBLCLK",
-	"WM_MBUTTONDOWN",
-	"WM_MBUTTONUP",
-	"WM_MBUTTONDBLCLK",
-	"WM_MOUSEWHEEL",
-	"WM_XBUTTONDOWN",
-	"WM_XBUTTONUP",
-	"WM_XBUTTONDBLCLK",
-	"526",
-	"527",
-	"WM_PARENTNOTIFY",
-	"WM_ENTERMENULOOP",
-	"WM_EXITMENULOOP",
-	"WM_NEXTMENU",
-	"WM_SIZING",
-	"WM_CAPTURECHANGED",
-	"WM_MOVING",
-	"535",
-	"WM_POWERBROADCAST",
-	"WM_DEVICECHANGE",
-	"538",
-	"539",
-	"540",
-	"541",
-	"542",
-	"543",
-	"WM_MDICREATE",
-	"WM_MDIDESTROY",
-	"WM_MDIACTIVATE",
-	"WM_MDIRESTORE",
-	"WM_MDINEXT",
-	"WM_MDIMAXIMIZE",
-	"WM_MDITILE",
-	"WM_MDICASCADE",
-	"WM_MDIICONARRANGE",
-	"WM_MDIGETACTIVE",
-	"554",
-	"555",
-	"556",
-	"557",
-	"558",
-	"559",
-	"WM_MDISETMENU",
-	"WM_ENTERSIZEMOVE",
-	"WM_EXITSIZEMOVE",
-	"WM_DROPFILES",
-	"WM_MDIREFRESHMENU",
-	"565",
-	"566",
-	"567",
-	"568",
-	"569",
-	"570",
-	"571",
-	"572",
-	"573",
-	"574",
-	"575",
-	"576",
-	"577",
-	"578",
-	"579",
-	"580",
-	"581",
-	"582",
-	"583",
-	"584",
-	"585",
-	"586",
-	"587",
-	"588",
-	"589",
-	"590",
-	"591",
-	"592",
-	"593",
-	"594",
-	"595",
-	"596",
-	"597",
-	"598",
-	"599",
-	"600",
-	"601",
-	"602",
-	"603",
-	"604",
-	"605",
-	"606",
-	"607",
-	"608",
-	"609",
-	"610",
-	"611",
-	"612",
-	"613",
-	"614",
-	"615",
-	"616",
-	"617",
-	"618",
-	"619",
-	"620",
-	"621",
-	"622",
-	"623",
-	"624",
-	"625",
-	"626",
-	"627",
-	"628",
-	"629",
-	"630",
-	"631",
-	"632",
-	"633",
-	"634",
-	"635",
-	"636",
-	"637",
-	"638",
-	"639",
-	"640",
-	"WM_IME_SETCONTEXT",
-	"WM_IME_NOTIFY",
-	"WM_IME_CONTROL",
-	"WM_IME_COMPOSITIONFULL",
-	"WM_IME_SELECT",
-	"WM_IME_CHAR",
-	"647",
-	"648",
-	"649",
-	"650",
-	"651",
-	"652",
-	"653",
-	"654",
-	"655",
-	"WM_IME_KEYDOWN",
-	"WM_IME_KEYUP",
-	"658",
-	"659",
-	"660",
-	"661",
-	"662",
-	"663",
-	"664",
-	"665",
-	"666",
-	"667",
-	"668",
-	"669",
-	"670",
-	"671",
-	"672",
-	"WM_MOUSEHOVER",
-	"674",
-	"WM_MOUSELEAVE",
-	"676",
-	"677",
-	"678",
-	"679",
-	"680",
-	"681",
-	"682",
-	"683",
-	"684",
-	"685",
-	"686",
-	"687",
-	"688",
-	"689",
-	"690",
-	"691",
-	"692",
-	"693",
-	"694",
-	"695",
-	"696",
-	"697",
-	"698",
-	"699",
-	"700",
-	"701",
-	"702",
-	"703",
-	"704",
-	"705",
-	"706",
-	"707",
-	"708",
-	"709",
-	"710",
-	"711",
-	"712",
-	"713",
-	"714",
-	"715",
-	"716",
-	"717",
-	"718",
-	"719",
-	"720",
-	"721",
-	"722",
-	"723",
-	"724",
-	"725",
-	"726",
-	"727",
-	"728",
-	"729",
-	"730",
-	"731",
-	"732",
-	"733",
-	"734",
-	"735",
-	"736",
-	"737",
-	"738",
-	"739",
-	"740",
-	"741",
-	"742",
-	"743",
-	"744",
-	"745",
-	"746",
-	"747",
-	"748",
-	"749",
-	"750",
-	"751",
-	"752",
-	"753",
-	"754",
-	"755",
-	"756",
-	"757",
-	"758",
-	"759",
-	"760",
-	"761",
-	"762",
-	"763",
-	"764",
-	"765",
-	"766",
-	"767",
-	"WM_CUT",
-	"WM_COPY",
-	"WM_PASTE",
-	"WM_CLEAR",
-	"WM_UNDO",
-	"WM_RENDERFORMAT",
-	"WM_RENDERALLFORMATS",
-	"WM_DESTROYCLIPBOARD",
-	"WM_DRAWCLIPBOARD",
-	"WM_PAINTCLIPBOARD",
-	"WM_VSCROLLCLIPBOARD",
-	"WM_SIZECLIPBOARD",
-	"WM_ASKCBFORMATNAME",
-	"WM_CHANGECBCHAIN",
-	"WM_HSCROLLCLIPBOARD",
-	"WM_QUERYNEWPALETTE",
-	"WM_PALETTEISCHANGING",
-	"WM_PALETTECHANGED",
-	"WM_HOTKEY",
-	"787",
-	"788",
-	"789",
-	"790",
-	"WM_PRINT",
-	"WM_PRINTCLIENT",
-	"793",
-	"794",
-	"795",
-	"796",
-	"797",
-	"798",
-	"799",
-	"800",
-	"801",
-	"802",
-	"803",
-	"804",
-	"805",
-	"806",
-	"807",
-	"808",
-	"809",
-	"810",
-	"811",
-	"812",
-	"813",
-	"814",
-	"815",
-	"816",
-	"817",
-	"818",
-	"819",
-	"820",
-	"821",
-	"822",
-	"823",
-	"824",
-	"825",
-	"826",
-	"827",
-	"828",
-	"829",
-	"830",
-	"831",
-	"832",
-	"833",
-	"834",
-	"835",
-	"836",
-	"837",
-	"838",
-	"839",
-	"840",
-	"841",
-	"842",
-	"843",
-	"844",
-	"845",
-	"846",
-	"847",
-	"848",
-	"849",
-	"850",
-	"851",
-	"852",
-	"853",
-	"854",
-	"855",
-	"856",
-	"857",
-	"858",
-	"859",
-	"860",
-	"861",
-	"862",
-	"863",
-	"864",
-	"865",
-	"866",
-	"867",
-	"868",
-	"869",
-	"870",
-	"871",
-	"872",
-	"873",
-	"874",
-	"875",
-	"876",
-	"877",
-	"878",
-	"879",
-	"880",
-	"881",
-	"882",
-	"883",
-	"884",
-	"885",
-	"886",
-	"887",
-	"888",
-	"889",
-	"890",
-	"891",
-	"892",
-	"893",
-	"894",
-	"895",
-	"896",
-	"897",
-	"898",
-	"899",
-	"900",
-	"901",
-	"902",
-	"903",
-	"904",
-	"905",
-	"906",
-	"907",
-	"908",
-	"909",
-	"910",
-	"911",
-	"912",
-	"913",
-	"914",
-	"915",
-	"916",
-	"917",
-	"918",
-	"919",
-	"920",
-	"921",
-	"922",
-	"923",
-	"924",
-	"925",
-	"926",
-	"927",
-	"928",
-	"929",
-	"930",
-	"931",
-	"932",
-	"933",
-	"934",
-	"935",
-	"936",
-	"937",
-	"938",
-	"939",
-	"940",
-	"941",
-	"942",
-	"943",
-	"944",
-	"945",
-	"946",
-	"947",
-	"948",
-	"949",
-	"950",
-	"951",
-	"952",
-	"953",
-	"954",
-	"955",
-	"956",
-	"957",
-	"958",
-	"959",
-	"960",
-	"961",
-	"962",
-	"963",
-	"964",
-	"965",
-	"966",
-	"967",
-	"968",
-	"969",
-	"970",
-	"971",
-	"972",
-	"973",
-	"974",
-	"975",
-	"976",
-	"977",
-	"978",
-	"979",
-	"980",
-	"981",
-	"982",
-	"983",
-	"984",
-	"985",
-	"986",
-	"987",
-	"988",
-	"989",
-	"990",
-	"991",
-	"992",
-	"993",
-	"994",
-	"995",
-	"996",
-	"997",
-	"998",
-	"999",
-	"1000",
-	"1001",
-	"1002",
-	"1003",
-	"1004",
-	"1005",
-	"1006",
-	"1007",
-	"1008",
-	"1009",
-	"1010",
-	"1011",
-	"1012",
-	"1013",
-	"1014",
-	"1015",
-	"1016",
-	"1017",
-	"1018",
-	"1019",
-	"1020",
-	"1021",
-	"1022",
-	"1023"
-};
-
diff --git a/hw/xwin/xlaunch/window/util.h b/hw/xwin/xlaunch/window/util.h
deleted file mode 100644
index cd21da6..0000000
--- a/hw/xwin/xlaunch/window/util.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#ifndef __UTIL_H__
-#define __UTIL_H__
-
-#include <windows.h>
-#include <stdexcept>
-
-
-class win32_error : public std::runtime_error
-{
-    public:
-        static std::string message(DWORD code);
-        DWORD errorcode;
-        win32_error(const std::string &msg,DWORD code = GetLastError()) : std::runtime_error(msg + ":" + message(code)), errorcode(code) {};
-};
-
-#define MESSAGE_NAMES_LEN 1024
-#define NOTIFY_NAMES_LEN 0
-class MessageDebug
-{
-    protected:
-        static const char * message_names[MESSAGE_NAMES_LEN];
-        static const char * notify_names[NOTIFY_NAMES_LEN];
-    public:
-        static void debug(HWND handle, UINT uMsg, WPARAM wParam, LPARAM lParam, const char *prefix);
-};
-
-
-#endif
diff --git a/hw/xwin/xlaunch/window/window.cc b/hw/xwin/xlaunch/window/window.cc
deleted file mode 100755
index cca3a48..0000000
--- a/hw/xwin/xlaunch/window/window.cc
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-
-#include "window.h"
-#include "util.h"
-#include <stdio.h>
-#include <stdexcept>
-
-CWindow::CWindowClass CWindow::windowClass("CWINDOWCLASS", DefWindowProc);
-
-CWindow::CWindowClass::CWindowClass(const char *_name, WNDPROC _wndproc) : 
-    wndproc(_wndproc), atom(0), classname(_name)
-{
-    Register();
-}
-
-CWindow::CWindowClass::~CWindowClass()
-{
-    UnregisterClass(classname.c_str(), GetModuleHandle(NULL));
-}
-
-void CWindow::CWindowClass::Register()
-{
-    WNDCLASSEX wndclass;
-    memset(&wndclass, 0, sizeof(wndclass));
-    wndclass.cbSize = sizeof(wndclass);
-    wndclass.style = 0;
-    wndclass.lpfnWndProc = wndproc;
-    wndclass.cbClsExtra = 0;
-    wndclass.cbWndExtra = 0;
-    wndclass.hInstance = GetModuleHandle(NULL); 
-    wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
-    wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
-    wndclass.hbrBackground = (HBRUSH)(1 + COLOR_BTNFACE);
-    wndclass.lpszMenuName = NULL;
-    wndclass.lpszClassName = classname.c_str();
-    wndclass.hIconSm = NULL;
-    atom = RegisterClassEx(&wndclass);
-    if (atom == 0)
-        throw win32_error("RegisterClassEx failed");
-}
-
-CWindow::CWindow(const char *_title) : title(_title), hwnd(NULL), parent(NULL), bounds(), owndproc(NULL), showing(FALSE)
-{
-    style = WS_CHILD;
-    exstyle = 0;
-}
-
-HWND CWindow::CreateWindowHandle()
-{
-    HWND ret = CreateWindowEx(
-            exstyle,
-            GetClassName(),
-            title.c_str(),
-            style,
-            bounds.left,
-            bounds.top,
-            bounds.width,
-            bounds.height,
-            parent,
-            NULL,
-            GetModuleHandle(NULL),
-            0
-            );
-    if (ret == NULL)
-        throw win32_error("CreateWindowEx failed");
-    return ret;
-}
-
-void CWindow::Create()
-{
-    if (hwnd != NULL)
-        return;
-    hwnd = CreateWindowHandle();
-    if (hwnd == NULL)
-        throw win32_error("Could not create window");
-
-    // Reset the error code
-    DWORD err = 0;
-    SetLastError(err);
-    
-    // Attach the object reference to the window handle
-    SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)this);
-    err = GetLastError();
-    if (err != 0)
-        throw win32_error("SetWindowLongPtr failed",err);
-    
-    // Set the window proc
-    owndproc = (WNDPROC)SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)WindowProc);
-    err = GetLastError();
-    if (err != 0)
-        throw win32_error("SetWindowLongPtr failed",err);
-}
-
-const char *CWindow::GetClassName()
-{
-    return windowClass.GetClassName();
-}
-
-LRESULT CALLBACK CWindow::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
-{
-    MessageDebug::debug(hwnd, uMsg, wParam, lParam, __FUNCTION__);
-    CWindow* window = (CWindow*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
-    if (window != NULL)
-        return window->Dispatch(hwnd, uMsg, wParam, lParam);
-    return DefWindowProc(hwnd, uMsg, wParam, lParam);
-}
-
-LRESULT CWindow::Dispatch(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
-{
-    switch (uMsg)
-    {
-        case WM_SIZE:
-            bounds.width = LOWORD(lParam);
-            bounds.height = LOWORD(lParam);
-            break;
-        case WM_MOVE:
-            bounds.left = LOWORD(lParam);
-            bounds.top = LOWORD(lParam);
-            break;
-        case WM_DESTROY:
-            showing = FALSE;
-            break;
-    }
-    if (owndproc)
-        return CallWindowProc(owndproc, hwnd, uMsg, wParam, lParam);
-    else
-        return DefWindowProc(hwnd, uMsg, wParam, lParam);
-}
-
-void CWindow::Show()
-{
-    if (hwnd == NULL)
-        Create();
-    ShowWindow(hwnd, SW_SHOWNORMAL);
-}
-
-int CWindow::ShowModal()
-{
-    MSG msg;
-    BOOL bRet;
-    showing = TRUE;
-    Show();
-
-    while( showing && (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
-    { 
-        if (bRet == -1)
-        {
-            // handle the error and possibly exit
-        }
-        else
-        {
-            TranslateMessage(&msg); 
-            DispatchMessage(&msg); 
-        }
-    }
-    return 0; 
-}
-
-void CWindow::SetLeft(int left)
-{
-    bounds.left = left;
-    if (hwnd)
-        if (!SetWindowPos(hwnd, NULL, 
-                bounds.left, bounds.top,
-                0, 0, 
-                SWP_NOZORDER |  SWP_NOSIZE))
-            throw win32_error("SetWindowPos failed");
-}
-
-void CWindow::SetTop(int top)
-{
-    bounds.top = top;
-    if (hwnd)
-        if (!SetWindowPos(hwnd, NULL, 
-                bounds.left, bounds.top,
-                0, 0, 
-                SWP_NOZORDER |  SWP_NOSIZE))
-            throw win32_error("SetWindowPos failed");
-}
-
-void CWindow::SetWidth(int width)
-{
-    bounds.width = width;
-    if (hwnd)
-        if (!SetWindowPos(hwnd, NULL,
-                0, 0, 
-                bounds.width, bounds.height, 
-                SWP_NOZORDER |  SWP_NOMOVE))
-            throw win32_error("SetWindowPos failed");
-}
-void CWindow::SetHeight(int height)
-{
-    bounds.height = height;
-    if (hwnd)
-        if (!SetWindowPos(hwnd, NULL,
-                0, 0, 
-                bounds.width, bounds.height,
-                SWP_NOZORDER |  SWP_NOMOVE))
-            throw win32_error("SetWindowPos failed");
-}
-
-void CWindow::SetBounds(int left, int top, int width, int height)
-{
-    bounds = CBoundary(left, top, width, height);
-    if (hwnd)
-        if (!SetWindowPos(hwnd, NULL, 
-                bounds.left, bounds.top, 
-                bounds.width, bounds.height, 
-                SWP_NOZORDER))
-            throw win32_error("SetWindowPos failed");
-}
-
-void CWindow::SetBounds(const RECT &rect)
-{
-    bounds = rect;
-    if (hwnd)
-        if (!SetWindowPos(hwnd, NULL, 
-                bounds.left, bounds.top, 
-                bounds.width, bounds.height, 
-                SWP_NOZORDER))
-            throw win32_error("SetWindowPos failed");
-}
-
-HWND CWindow::GetHandle()
-{
-    if (hwnd == NULL)
-        Create();
-    return hwnd;
-}
-
-void CWindow::SetParent(CWindow *window)
-{
-    parent = window->GetHandle();
-    if (hwnd != NULL)
-        if (::SetParent(hwnd, parent) == NULL)
-            throw win32_error("SetParent failed");
-        
-}
-
-void CWindow::SetStyle(DWORD style)
-{
-    this->style = style;
-    SetLastError(0);
-    if (hwnd)
-        SetWindowLong(hwnd, GWL_STYLE, style);
-    int err = GetLastError();
-    if (err != 0)
-        throw win32_error("SetWindowLong failed", err);
-}
-
-void CWindow::SetExStyle(DWORD exstyle)
-{
-    this->exstyle = exstyle;
-    SetLastError(0);
-    if (hwnd)
-        SetWindowLong(hwnd, GWL_EXSTYLE, exstyle);
-    int err = GetLastError();
-    if (err != 0)
-        throw win32_error("SetWindowWLong failed", err);
-}
diff --git a/hw/xwin/xlaunch/window/window.h b/hw/xwin/xlaunch/window/window.h
deleted file mode 100755
index baf4014..0000000
--- a/hw/xwin/xlaunch/window/window.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#ifndef __WINDOW_H__
-#define __WINDOW_H__
-
-#include <windows.h>
-#include <string>
-
-class CDialog;
-class CWindow
-{
-    friend class CDialog;
-    public:
-        struct CBoundary
-        {
-            int left;
-            int top;
-            int width;
-            int height;
-            CBoundary() : 
-                left(0), top(0), width(0), height(0) {};
-            CBoundary(int x, int y, int w, int h) : 
-                left(x), top(y), width(w), height(h) {};
-            CBoundary(const RECT &r) : 
-                left(r.left), top(r.top), width(r.right-r.left), height(r.bottom-r.top) {};
-        };
-        class CWindowClass
-        {
-            private:
-                WNDPROC wndproc;
-                ATOM atom;
-                std::string classname;
-            protected:
-                void Register();
-            public:
-                CWindowClass(const char *name, WNDPROC wndproc);
-                ~CWindowClass();
-                const char *GetClassName() { return classname.c_str(); };
-        };
-    private:
-        static CWindowClass windowClass;
-
-        std::string title;
-        DWORD exstyle;
-        DWORD style;
-        CBoundary bounds;
-        HWND hwnd; 
-        HWND parent;
-        WNDPROC owndproc;
-
-        BOOL showing;
-
-    protected:
-
-        virtual const char *GetClassName();
-	virtual HWND CreateWindowHandle();
-        static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
-    public:
-        CWindow(const char *title);
-	virtual void Create();
-
-        virtual int ShowModal();
-
-        void Show();
-        void Hide();
-
-        void SetWidth(int width);
-        void SetHeight(int height);
-        void SetLeft(int left);
-        void SetTop(int top);
-        int GetWidth() { return bounds.width; };
-        int GetHeight() { return bounds.height; };
-        int GetLeft() { return bounds.left; };
-        int GetTop() { return bounds.top; };
-
-        void SetBounds(int left, int top, int width, int height);
-        void SetBounds(const RECT &rect);
-
-        void SetStyle(DWORD style);
-        DWORD GetStyle() { return style; };
-        
-        void SetExStyle(DWORD exstyle);
-        DWORD GetExStyle() { return exstyle; };
-
-        HWND GetHandle();
-        void SetParent(CWindow *window);
-
-        virtual LRESULT Dispatch(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
-};
-
-#endif
diff --git a/hw/xwin/xlaunch/window/wizard.cc b/hw/xwin/xlaunch/window/wizard.cc
deleted file mode 100755
index 9d6c711..0000000
--- a/hw/xwin/xlaunch/window/wizard.cc
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#include "wizard.h"
-#include "util.h"
-
-CWizard::CWizard() : pages() 
-{
-};
-
-void CWizard::AddPage(const PROPSHEETPAGE &page)
-{
-    pages.push_back(page);
-}
-
-void CWizard::AddPage(const char *page, HINSTANCE instance)
-{
-    PROPSHEETPAGE psp;
-    if (instance == NULL)
-        instance = GetModuleHandle(NULL);
-    
-    memset(&psp, 0, sizeof(psp));
-    psp.dwSize = sizeof(PROPSHEETPAGE);
-    psp.dwFlags = PSP_DEFAULT;
-    psp.hInstance = instance;
-    psp.pszTemplate = page;
-    psp.pfnDlgProc = WizardDialogProc;
-    psp.lParam = (LPARAM)this;
-
-    AddPage(psp);
-}
-
-void CWizard::AddPage(DWORD id, DWORD title, DWORD subtitle, HINSTANCE instance)
-{
-    PROPSHEETPAGE psp;
-    if (instance == NULL)
-        instance = GetModuleHandle(NULL);
-    
-    memset(&psp, 0, sizeof(psp));
-    psp.dwSize = sizeof(PROPSHEETPAGE);
-    psp.dwFlags = PSP_DEFAULT;
-#if _WIN32_IE >= 0x0500
-    if (title != 0)
-    {
-        psp.dwFlags |= PSP_USEHEADERTITLE;
-        psp.pszHeaderTitle = MAKEINTRESOURCE(title);
-    }
-    if (subtitle != 0)
-    {
-        psp.dwFlags |= PSP_USEHEADERSUBTITLE;
-        psp.pszHeaderSubTitle = MAKEINTRESOURCE(subtitle);
-    }
-#endif
-		
-    psp.hInstance = instance;
-    psp.pszTemplate = MAKEINTRESOURCE(id);
-    psp.pfnDlgProc = WizardDialogProc;
-    psp.lParam = (LPARAM)this;
-
-    AddPage(psp);
-}
-
-HWND CWizard::CreateWindowHandle()
-{
-    PROPSHEETHEADER psh;
-    HWND ret;
-    
-    PrepareSheetHeader(psh, FALSE);
-    ret = (HWND)PropertySheet(&psh);
-    free(psh.phpage);
-    if (ret == NULL)
-        throw win32_error("PropertySheet failed");
-    return ret;
-}
-
-int CWizard::ShowModal()
-{
-    PROPSHEETHEADER psh;
-    int ret;
-    
-    PrepareSheetHeader(psh, TRUE);
-    ret = PropertySheet(&psh);
-    free(psh.phpage);
-    return ret;
-}
-
-void CWizard::PrepareSheetHeader(PROPSHEETHEADER &psh, BOOL modal)
-{
-    HPROPSHEETPAGE *phpage = (HPROPSHEETPAGE*)malloc(pages.size() * sizeof(HPROPSHEETPAGE));
-    DWORD modeflag;
-
-    if (modal)
-        modeflag = 0;
-    else
-        modeflag = PSH_MODELESS;
-    
-    for (unsigned i = 0; i < pages.size(); i++)
-    {
-        phpage[i] = CreatePropertySheetPage(&pages[i]);
-        if (phpage[i] == NULL)
-        {
-            DWORD err = GetLastError();
-            free(phpage);
-            throw win32_error("CreatePropertySheetPage failed", err);
-        }
-    }
-
-    memset(&psh, 0, sizeof(psh));
-    psh.dwSize = sizeof(PROPSHEETHEADER);
-#if _WIN32_IE >= 0x0500
-    psh.dwFlags = PSH_WIZARD97 | modeflag;
-#else
-    psh.dwFlags = PSH_WIZARD | modeflag;
-#endif
-    psh.hwndParent = NULL;
-    psh.hInstance = GetModuleHandle(NULL);
-    psh.pszIcon = NULL;
-    psh.pszCaption = (LPSTR) "Cell Properties";
-    psh.nPages = pages.size(); 
-    psh.nStartPage = 0;
-    psh.phpage = phpage;
-    psh.pfnCallback = NULL;
-}
-
-DWORD CWizard::PageID(unsigned index)
-{
-    if (index < pages.size() && IS_INTRESOURCE(pages[index].pszTemplate))
-	return (DWORD)pages[index].pszTemplate;
-    return (DWORD)-1;
-}
-
-unsigned CWizard::PageIndex(PROPSHEETPAGE *psp)
-{
-    for (unsigned i = 0; i < pages.size(); i++)
-    {
-	if (IS_INTRESOURCE(psp->pszTemplate) || IS_INTRESOURCE(pages[i].pszTemplate ))
-	{
-	    if (psp->pszTemplate == pages[i].pszTemplate)
-		return i;
-	}	    
-	else if (psp->pszTemplate && pages[i].pszTemplate)
-	{
-	    if (strcmp(psp->pszTemplate, pages[i].pszTemplate) == 0)
-		return i;
-	}
-    }
-    return (unsigned)-1;
-}
-
-INT_PTR CWizard::DlgDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
-{
-    return CBaseDialog::DlgDispatch(hwndDlg, uMsg, wParam, lParam);
-}
-
-INT_PTR CWizard::PageDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam, PROPSHEETPAGE *psp)
-{
-    LPNMHDR pnmh = (LPNMHDR)lParam;
-    DWORD flags; 
-    unsigned pageindex;
-    switch (uMsg)
-    {
-	case WM_NOTIFY:
-	    switch (pnmh->code)
-	    {
-		case PSN_SETACTIVE:
-#ifdef _DEBUG
-                    printf("PSN_SETACTIVE %d\n", PageIndex(psp));
-#endif
-		    pageindex = PageIndex(psp);
-		    if (pageindex != (unsigned)-1)
-		    {
-			flags = 0;
-			if (pageindex > 0)
-			    flags |= PSWIZB_BACK;
-			if ((unsigned)pageindex + 1 == pages.size())
-			    flags |= PSWIZB_FINISH;
-			if ((unsigned)pageindex + 1 < pages.size())
-                            flags |= PSWIZB_NEXT;
-                        PropSheet_SetWizButtons(GetParent(hwndDlg), flags);
-		    }
-		    WizardActivate(hwndDlg, pageindex);
-		    break;
-		case PSN_WIZNEXT:
-                    if (WizardNext(hwndDlg, PageIndex(psp)))
-                        return TRUE;
-		    break;
-		case PSN_WIZBACK:
-                    if (WizardBack(hwndDlg, PageIndex(psp)))
-                        return TRUE;
-		    break;
-                case PSN_WIZFINISH:
-                    if (WizardFinish(hwndDlg, PageIndex(psp)))
-                        return TRUE;
-                    DestroyWindow(GetParent(hwndDlg));
-		case PSN_RESET:
-                    if (WizardReset(hwndDlg, PageIndex(psp)))
-                        return TRUE;
-                    DestroyWindow(GetParent(hwndDlg));
-		    break;
-	    }
-    }
-    return DlgDispatch(hwndDlg, uMsg, wParam, lParam);
-}
-
-
-INT_PTR CALLBACK CWizard::WizardDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
-{
-    MessageDebug::debug(hwndDlg, uMsg, wParam, lParam, __FUNCTION__);
-    PROPSHEETPAGE *psp = (PROPSHEETPAGE*)lParam;
-    switch (uMsg)
-    {
-	case WM_INITDIALOG:
-	    SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)psp);
-	    break;
-    }
-    psp = (PROPSHEETPAGE*)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
-    CWizard* wizard = psp?(CWizard*)psp->lParam:NULL;
-    if (wizard != NULL)
-        return wizard->PageDispatch(hwndDlg, uMsg, wParam, lParam, psp);
-    return FALSE;
-}
-
diff --git a/hw/xwin/xlaunch/window/wizard.h b/hw/xwin/xlaunch/window/wizard.h
deleted file mode 100755
index a2361c5..0000000
--- a/hw/xwin/xlaunch/window/wizard.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2005 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#ifndef __WIZARD_H__
-#define __WIZARD_H__
-
-#include "dialog.h"
-#include <vector>
-
-#define _WIN32_IE 0x0500
-#include <prsht.h>
-
-class CWizard : public CBaseDialog
-{
-    private:
-        std::vector<PROPSHEETPAGE> pages;
-        void PrepareSheetHeader(PROPSHEETHEADER &psh, BOOL modal);
-    protected:
-        virtual HWND CreateWindowHandle();
-        static INT_PTR CALLBACK WizardDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
-        virtual INT_PTR DlgDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
-        virtual INT_PTR PageDispatch(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam, PROPSHEETPAGE *psp);
-        virtual unsigned PageIndex(PROPSHEETPAGE *psp);
-	virtual DWORD PageID(unsigned index);
-        virtual BOOL WizardNext(HWND hwndDlg, unsigned index) { return FALSE; }
-        virtual BOOL WizardBack(HWND hwndDlg, unsigned index) { return FALSE; } 
-        virtual BOOL WizardFinish(HWND hwndDlg, unsigned index) { return FALSE; }
-        virtual BOOL WizardReset(HWND hwndDlg, unsigned index) { return FALSE; }
-        virtual BOOL WizardActivate(HWND hwndDlg, unsigned index) { return FALSE; }
-    public:
-        CWizard();
-        void AddPage(const PROPSHEETPAGE &page);
-        void AddPage(const char *page, HINSTANCE instance = NULL);
-        void AddPage(DWORD id, DWORD title, DWORD subtitle, HINSTANCE instance = NULL);
-        virtual int ShowModal();
-};
-#endif
diff --git a/include/xwin-config.h.in b/include/xwin-config.h.in
deleted file mode 100644
index c8de110..0000000
--- a/include/xwin-config.h.in
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * xwin-config.h.in
- *
- * This file has all defines used in the xwin ddx
- *
- */
-#include <dix-config.h>
-
-/* Winsock networking */
-#undef HAS_WINSOCK
-
-/* Cygwin has /dev/windows for signaling new win32 messages */
-#undef HAS_DEVWINDOWS
-
-/* Switch on debug messages */ 
-#undef CYGDEBUG
-#undef CYGWINDOWING_DEBUG
-#undef CYGMULTIWINDOW_DEBUG
-
-/* Define to 1 if unsigned long is 64 bits. */
-#undef _XSERVER64
-
-/* Do we require our own snprintf? */
-#undef NEED_SNPRINTF
commit 587c010a1cd733fded4d49dc339df0634bda8be6
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Sat Apr 19 09:27:21 2008 -0700

    Rootless: Kill off rlAccel

diff --git a/configure.ac b/configure.ac
index 64efc4c..fcecc7a 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2134,7 +2134,6 @@ miext/damage/Makefile
 miext/shadow/Makefile
 miext/cw/Makefile
 miext/rootless/Makefile
-miext/rootless/accel/Makefile
 os/Makefile
 randr/Makefile
 render/Makefile
diff --git a/miext/rootless/Makefile.am b/miext/rootless/Makefile.am
index dc85170..f09300d 100644
--- a/miext/rootless/Makefile.am
+++ b/miext/rootless/Makefile.am
@@ -1,8 +1,6 @@
 AM_CFLAGS = $(DIX_CFLAGS) $(XSERVER_CFLAGS)
 AM_CPPFLAGS = -I$(top_srcdir)/hw/xfree86/os-support
 
-SUBDIRS = accel
-
 noinst_LTLIBRARIES = librootless.la
 librootless_la_SOURCES = \
 	rootlessCommon.c \
diff --git a/miext/rootless/accel/Makefile.am b/miext/rootless/accel/Makefile.am
deleted file mode 100644
index ca41653..0000000
--- a/miext/rootless/accel/Makefile.am
+++ /dev/null
@@ -1,15 +0,0 @@
-AM_CFLAGS = $(DIX_CFLAGS) $(XSERVER_CFLAGS)
-AM_CPPFLAGS = -I$(srcdir)/.. -I$(top_srcdir)/hw/xfree86/os-support
-
-noinst_LTLIBRARIES = librlAccel.la
-librlAccel_la_SOURCES = \
-	rlAccel.c \
-	rlBlt.c \
-	rlCopy.c \
-	rlFill.c \
-	rlFillRect.c \
-	rlFillSpans.c \
-	rlGlyph.c \
-	rlSolid.c
-
-EXTRA_DIST = rlAccel.h
diff --git a/miext/rootless/accel/rlAccel.c b/miext/rootless/accel/rlAccel.c
deleted file mode 100644
index f3cb215..0000000
--- a/miext/rootless/accel/rlAccel.c
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Support for accelerated rootless code
- */
-/*
- * Copyright (c) 2004 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-
-/*
- * The accelerated rootless code replaces some GC operations from fb with
- * versions that call the rootless acceleration functions where appropriate.
- * To work properly, this must be wrapped directly on top of fb. Nothing
- * underneath this layer besides fb will get called.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "rootless.h"
-#include "rlAccel.h"
-
-typedef struct _rlAccelScreenRec {
-    CreateGCProcPtr CreateGC;
-    CloseScreenProcPtr CloseScreen;
-} rlAccelScreenRec, *rlAccelScreenPtr;
-
-static DevPrivateKey rlAccelScreenPrivateKey = &rlAccelScreenPrivateKey;
-
-#define RLACCELREC(pScreen) ((rlAccelScreenRec *) \
-    dixLookupPrivate(&(pScreen)->devPrivates, rlAccelScreenPrivateKey))
-
-#define SETRLACCELREC(pScreen, v) \
-    dixSetPrivate(&(pScreen)->devPrivates, rlAccelScreenPrivateKey, v)
-
-/* This is mostly identical to fbGCOps. */
-static GCOps rlAccelOps = {
-    rlFillSpans,
-    fbSetSpans,
-    fbPutImage,
-    rlCopyArea,
-    fbCopyPlane,
-    fbPolyPoint,
-    fbPolyLine,
-    fbPolySegment,
-    fbPolyRectangle,
-    fbPolyArc,
-    miFillPolygon,
-    rlPolyFillRect,
-    fbPolyFillArc,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    rlImageGlyphBlt,
-    fbPolyGlyphBlt,
-    fbPushPixels
-};
-
-
-/*
- * Screen function to create a graphics context
- */
-static Bool
-rlCreateGC(GCPtr pGC)
-{
-    ScreenPtr pScreen = pGC->pScreen;
-    rlAccelScreenRec *s = RLACCELREC(pScreen);
-    Bool result;
-
-    // Unwrap and call
-    pScreen->CreateGC = s->CreateGC;
-    result = s->CreateGC(pGC);
-
-    // Accelerated GC ops replace some fb GC ops
-    pGC->ops = &rlAccelOps;
-
-    // Rewrap
-    s->CreateGC = pScreen->CreateGC;
-    pScreen->CreateGC = rlCreateGC;
-
-    return result;
-}
-
-
-/*
- * Clean up when closing a screen on server reset
- */
-static Bool
-rlCloseScreen (int iScreen, ScreenPtr pScreen)
-{
-    rlAccelScreenRec *s = RLACCELREC(pScreen);
-    Bool result;
-
-    // Unwrap
-    pScreen->CloseScreen = s->CloseScreen;
-    result = pScreen->CloseScreen(iScreen, pScreen);
-
-    xfree(s);
-
-    return result;
-}
-
-
-/*
- * RootlessAccelInit
- *  Called by the rootless implementation to initialize accelerated
- *  rootless drawing.
- */
-Bool
-RootlessAccelInit(ScreenPtr pScreen)
-{
-    rlAccelScreenRec *s;
-
-    s = xalloc(sizeof(rlAccelScreenRec));
-    if (!s) return FALSE;
-    SETRLACCELREC(pScreen, s);
-
-    // Wrap the screen functions we need
-    s->CreateGC = pScreen->CreateGC;
-    pScreen->CreateGC = rlCreateGC;
-    s->CloseScreen = pScreen->CloseScreen;
-    pScreen->CloseScreen = rlCloseScreen;
-
-    return TRUE;
-}
diff --git a/miext/rootless/accel/rlAccel.h b/miext/rootless/accel/rlAccel.h
deleted file mode 100644
index a3fc632..0000000
--- a/miext/rootless/accel/rlAccel.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Rootless Acceleration Code
- */
-/*
- * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "fb.h"
-
-/*
- * rlBlt.c
- */
-void
-rlBlt (FbBits   *srcLine,
-       FbStride	srcStride,
-       int	srcX,
-
-       ScreenPtr pDstScreen,
-       FbBits   *dstLine,
-       FbStride dstStride,
-       int	dstX,
-
-       int	width,
-       int	height,
-
-       int	alu,
-       FbBits	pm,
-       int	bpp,
-
-       Bool	reverse,
-       Bool	upsidedown);
-
-/*
- * rlCopy.c
- */
-RegionPtr
-rlCopyArea (DrawablePtr	pSrcDrawable,
-	    DrawablePtr	pDstDrawable,
-	    GCPtr	pGC,
-	    int		xIn, 
-	    int		yIn,
-	    int		widthSrc, 
-	    int		heightSrc,
-	    int		xOut, 
-	    int		yOut);
-
-/*
- * rlFill.c
- */
-void
-rlFill (DrawablePtr pDrawable,
-	GCPtr	    pGC,
-	int	    x,
-	int	    y,
-	int	    width,
-	int	    height);
-
-void
-rlSolidBoxClipped (DrawablePtr	pDrawable,
-		   RegionPtr	pClip,
-		   int		x1,
-		   int		y1,
-		   int		x2,
-		   int		y2,
-		   FbBits	and,
-		   FbBits	xor);
-
-/*
- * rlFillRect.c
- */
-void
-rlPolyFillRect(DrawablePtr  pDrawable, 
-	       GCPtr	    pGC, 
-	       int	    nrect,
-	       xRectangle   *prect);
-
-/*
- * rlFillSpans.c
- */
-void
-rlFillSpans (DrawablePtr    pDrawable,
-	     GCPtr	    pGC,
-	     int	    n,
-	     DDXPointPtr    ppt,
-	     int	    *pwidth,
-	     int	    fSorted);
-
-/*
- * rlGlyph.c
- */
-void
-rlImageGlyphBlt (DrawablePtr	pDrawable,
-		 GCPtr		pGC,
-		 int		x, 
-		 int		y,
-		 unsigned int	nglyph,
-		 CharInfoPtr	*ppciInit,
-		 pointer	pglyphBase);
-
-/*
- * rlSolid.c
- */
-void
-rlSolid (ScreenPtr  pScreen,
-         FbBits	    *dst,
-	 FbStride   dstStride,
-	 int	    dstX,
-	 int	    bpp,
-
-	 int	    width,
-	 int	    height,
-
-	 FbBits	    and,
-	 FbBits	    xor);
diff --git a/miext/rootless/accel/rlBlt.c b/miext/rootless/accel/rlBlt.c
deleted file mode 100644
index b5fe740..0000000
--- a/miext/rootless/accel/rlBlt.c
+++ /dev/null
@@ -1,408 +0,0 @@
-/*
- * Accelerated rootless blit
- */
-/*
- * This code is largely copied from fbBlt.c.
- *
- * Copyright © 1998 Keith Packard
- * Copyright (c) 2002 Apple Computer, Inc. All Rights Reserved.
- * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Keith Packard not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Keith Packard makes no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.
- *
- * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS SOFTWARE.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <stddef.h> /* For NULL */
-#include <string.h>
-#include "fb.h"
-#include "rootlessCommon.h"
-#include "rlAccel.h"
-
-#define InitializeShifts(sx,dx,ls,rs) { \
-    if (sx != dx) { \
-	if (sx > dx) { \
-	    ls = sx - dx; \
-	    rs = FB_UNIT - ls; \
-	} else { \
-	    rs = dx - sx; \
-	    ls = FB_UNIT - rs; \
-	} \
-    } \
-}
-
-void
-rlBlt (FbBits   *srcLine,
-       FbStride	srcStride,
-       int	srcX,
-
-       ScreenPtr pDstScreen,
-       FbBits   *dstLine,
-       FbStride dstStride,
-       int	dstX,
-
-       int	width,
-       int	height,
-
-       int	alu,
-       FbBits	pm,
-       int	bpp,
-
-       Bool	reverse,
-       Bool	upsidedown)
-{
-    FbBits  *src, *dst;
-    int	    leftShift, rightShift;
-    FbBits  startmask, endmask;
-    FbBits  bits, bits1;
-    int	    n, nmiddle;
-    Bool    destInvarient;
-    int	    startbyte, endbyte;
-    FbDeclareMergeRop ();
-
-#ifdef FB_24BIT
-    if (bpp == 24 && !FbCheck24Pix (pm))
-    {
-	fbBlt24 (srcLine, srcStride, srcX, dstLine, dstStride, dstX,
-		 width, height, alu, pm, reverse, upsidedown);
-	return;
-    }
-#endif
-
-    if (alu == GXcopy && pm == FB_ALLONES && !reverse &&
-            !(srcX & 7) && !(dstX & 7) && !(width & 7)) {
-        int i;
-        CARD8 *src = (CARD8 *) srcLine;
-        CARD8 *dst = (CARD8 *) dstLine;
-        
-        srcStride *= sizeof(FbBits);
-        dstStride *= sizeof(FbBits);
-        width >>= 3;
-        src += (srcX >> 3);
-        dst += (dstX >> 3);
-
-        if (!upsidedown)
-            for (i = 0; i < height; i++)
-                memcpy(dst + i * dstStride, src + i * srcStride, width);
-        else
-            for (i = height - 1; i >= 0; i--)
-                memcpy(dst + i * dstStride, src + i * srcStride, width);
-
-        return;
-    }
-
-    FbInitializeMergeRop(alu, pm);
-    destInvarient = FbDestInvarientMergeRop();
-    if (upsidedown)
-    {
-	srcLine += (height - 1) * (srcStride);
-	dstLine += (height - 1) * (dstStride);
-	srcStride = -srcStride;
-	dstStride = -dstStride;
-    }
-    FbMaskBitsBytes (dstX, width, destInvarient, startmask, startbyte,
-		     nmiddle, endmask, endbyte);
-
-    /*
-     * Beginning of the rootless acceleration code
-     */
-    if (!startmask && !endmask && alu == GXcopy &&
-        height * nmiddle * sizeof(*dst) > rootless_CopyBytes_threshold)
-    {
-	if (pm == FB_ALLONES && SCREENREC(pDstScreen)->imp->CopyBytes)
-	{
-	    SCREENREC(pDstScreen)->imp->CopyBytes(
-                            nmiddle * sizeof(*dst), height,
-                            (char *) srcLine + (srcX >> 3),
-                            srcStride * sizeof (*src),
-                            (char *) dstLine + (dstX >> 3),
-                            dstStride * sizeof (*dst));
-	    return;
-	}
-
-	/* FIXME: the pm test here isn't super-wonderful - just because
-	   we don't care about the top eight bits doesn't necessarily
-	   mean we want them set to 255. But doing this does give a
-	   factor of two performance improvement when copying from a
-	   pixmap to a window, which is pretty common.. */
-
-	else if (bpp == 32 && sizeof(FbBits) == 4 &&
-                 pm == 0x00FFFFFFUL && !reverse &&
-                 SCREENREC(pDstScreen)->imp->CompositePixels)
-	{
-	    /* need to copy XRGB to ARGB. */
-
-	    void *src[2], *dest[2];
-	    unsigned int src_rowbytes[2], dest_rowbytes[2];
-            unsigned int fn;
-
-	    src[0] = (char *) srcLine + (srcX >> 3);
-	    src[1] = NULL;
-	    src_rowbytes[0] = srcStride * sizeof(*src);
-	    src_rowbytes[1] = 0;
-
-	    dest[0] = (char *) dstLine + (dstX >> 3);
-	    dest[1] = dest[0];
-	    dest_rowbytes[0] = dstStride * sizeof(*dst);
-	    dest_rowbytes[1] = dest_rowbytes[0];
-
-	    fn = RL_COMPOSITE_FUNCTION(RL_COMPOSITE_SRC, RL_DEPTH_ARGB8888,
-                                       RL_DEPTH_NIL, RL_DEPTH_ARGB8888);
-
-            if (SCREENREC(pDstScreen)->imp->CompositePixels(
-                                nmiddle, height,
-                                fn, src, src_rowbytes,
-                                NULL, 0, dest, dest_rowbytes) == Success)
-            {
-                return;
-            }
-	}
-    }
-    /* End of the rootless acceleration code */
-
-    if (reverse)
-    {
-	srcLine += ((srcX + width - 1) >> FB_SHIFT) + 1;
-	dstLine += ((dstX + width - 1) >> FB_SHIFT) + 1;
-	srcX = (srcX + width - 1) & FB_MASK;
-	dstX = (dstX + width - 1) & FB_MASK;
-    }
-    else
-    {
-	srcLine += srcX >> FB_SHIFT;
-	dstLine += dstX >> FB_SHIFT;
-	srcX &= FB_MASK;
-	dstX &= FB_MASK;
-    }
-    if (srcX == dstX)
-    {
-	while (height--)
-	{
-	    src = srcLine;
-	    srcLine += srcStride;
-	    dst = dstLine;
-	    dstLine += dstStride;
-	    if (reverse)
-	    {
-		if (endmask)
-		{
-		    bits = *--src;
-		    --dst;
-		    FbDoRightMaskByteMergeRop(dst, bits, endbyte, endmask);
-		}
-		n = nmiddle;
-		if (destInvarient)
-		{
-		    while (n--)
-			*--dst = FbDoDestInvarientMergeRop(*--src);
-		}
-		else
-		{
-		    while (n--)
-		    {
-			bits = *--src;
-			--dst;
-			*dst = FbDoMergeRop (bits, *dst);
-		    }
-		}
-		if (startmask)
-		{
-		    bits = *--src;
-		    --dst;
-		    FbDoLeftMaskByteMergeRop(dst, bits, startbyte, startmask);
-		}
-	    }
-	    else
-	    {
-		if (startmask)
-		{
-		    bits = *src++;
-		    FbDoLeftMaskByteMergeRop(dst, bits, startbyte, startmask);
-		    dst++;
-		}
-		n = nmiddle;
-		if (destInvarient)
-		{
-#if 0
-		    /*
-		     * This provides some speedup on screen->screen blts
-		     * over the PCI bus, usually about 10%.  But fb
-		     * isn't usually used for this operation...
-		     */
-		    if (_ca2 + 1 == 0 && _cx2 == 0)
-		    {
-			FbBits	t1, t2, t3, t4;
-			while (n >= 4)
-			{
-			    t1 = *src++;
-			    t2 = *src++;
-			    t3 = *src++;
-			    t4 = *src++;
-			    *dst++ = t1;
-			    *dst++ = t2;
-			    *dst++ = t3;
-			    *dst++ = t4;
-			    n -= 4;
-			}
-		    }
-#endif
-		    while (n--)
-			*dst++ = FbDoDestInvarientMergeRop(*src++);
-		}
-		else
-		{
-		    while (n--)
-		    {
-			bits = *src++;
-			*dst = FbDoMergeRop (bits, *dst);
-			dst++;
-		    }
-		}
-		if (endmask)
-		{
-		    bits = *src;
-		    FbDoRightMaskByteMergeRop(dst, bits, endbyte, endmask);
-		}
-	    }
-	}
-    }
-    else
-    {
-	if (srcX > dstX)
-	{
-	    leftShift = srcX - dstX;
-	    rightShift = FB_UNIT - leftShift;
-	}
-	else
-	{
-	    rightShift = dstX - srcX;
-	    leftShift = FB_UNIT - rightShift;
-	}
-	while (height--)
-	{
-	    src = srcLine;
-	    srcLine += srcStride;
-	    dst = dstLine;
-	    dstLine += dstStride;
-	    
-	    bits1 = 0;
-	    if (reverse)
-	    {
-		if (srcX < dstX)
-		    bits1 = *--src;
-		if (endmask)
-		{
-		    bits = FbScrRight(bits1, rightShift);
-		    if (FbScrRight(endmask, leftShift))
-		    {
-			bits1 = *--src;
-			bits |= FbScrLeft(bits1, leftShift);
-		    }
-		    --dst;
-		    FbDoRightMaskByteMergeRop(dst, bits, endbyte, endmask);
-		}
-		n = nmiddle;
-		if (destInvarient)
-		{
-		    while (n--)
-		    {
-			bits = FbScrRight(bits1, rightShift);
-			bits1 = *--src;
-			bits |= FbScrLeft(bits1, leftShift);
-			--dst;
-			*dst = FbDoDestInvarientMergeRop(bits);
-		    }
-		}
-		else
-		{
-		    while (n--)
-		    {
-			bits = FbScrRight(bits1, rightShift);
-			bits1 = *--src;
-			bits |= FbScrLeft(bits1, leftShift);
-			--dst;
-			*dst = FbDoMergeRop(bits, *dst);
-		    }
-		}
-		if (startmask)
-		{
-		    bits = FbScrRight(bits1, rightShift);
-		    if (FbScrRight(startmask, leftShift))
-		    {
-			bits1 = *--src;
-			bits |= FbScrLeft(bits1, leftShift);
-		    }
-		    --dst;
-		    FbDoLeftMaskByteMergeRop (dst, bits, startbyte, startmask);
-		}
-	    }
-	    else
-	    {
-		if (srcX > dstX)
-		    bits1 = *src++;
-		if (startmask)
-		{
-		    bits = FbScrLeft(bits1, leftShift); 
-		    if (FbScrLeft(startmask, rightShift))
-		    {
-			bits1 = *src++;
-			bits |= FbScrRight(bits1, rightShift);
-		    }
-		    FbDoLeftMaskByteMergeRop (dst, bits, startbyte, startmask);
-		    dst++;
-		}
-		n = nmiddle;
-		if (destInvarient)
-		{
-		    while (n--)
-		    {
-			bits = FbScrLeft(bits1, leftShift);
-			bits1 = *src++;
-			bits |= FbScrRight(bits1, rightShift);
-			*dst = FbDoDestInvarientMergeRop(bits);
-			dst++;
-		    }
-		}
-		else
-		{
-		    while (n--)
-		    {
-			bits = FbScrLeft(bits1, leftShift);
-			bits1 = *src++;
-			bits |= FbScrRight(bits1, rightShift);
-			*dst = FbDoMergeRop(bits, *dst);
-			dst++;
-		    }
-		}
-		if (endmask)
-		{
-		    bits = FbScrLeft(bits1, leftShift);
-		    if (FbScrLeft(endmask, rightShift))
-		    {
-			bits1 = *src;
-			bits |= FbScrRight(bits1, rightShift);
-		    }
-		    FbDoRightMaskByteMergeRop (dst, bits, endbyte, endmask);
-		}
-	    }
-	}
-    }
-}
diff --git a/miext/rootless/accel/rlCopy.c b/miext/rootless/accel/rlCopy.c
deleted file mode 100644
index df6fc11..0000000
--- a/miext/rootless/accel/rlCopy.c
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * This code is largely copied from fbcopy.c.
- *
- * Copyright © 1998 Keith Packard
- * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Keith Packard not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Keith Packard makes no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.
- *
- * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS SOFTWARE.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "fb.h"
-#include "rlAccel.h"
-
-
-void
-rlCopyNtoN (DrawablePtr	pSrcDrawable,
-	    DrawablePtr	pDstDrawable,
-	    GCPtr	pGC,
-	    BoxPtr	pbox,
-	    int		nbox,
-	    int		dx,
-	    int		dy,
-	    Bool	reverse,
-	    Bool	upsidedown,
-	    Pixel	bitplane,
-	    void	*closure)
-{
-    CARD8	alu = pGC ? pGC->alu : GXcopy;
-    FbBits	pm = pGC ? fbGetGCPrivate(pGC)->pm : FB_ALLONES;
-    FbBits	*src;
-    FbStride	srcStride;
-    int		srcBpp;
-    int		srcXoff, srcYoff;
-    FbBits	*dst;
-    FbStride	dstStride;
-    int		dstBpp;
-    int		dstXoff, dstYoff;
-    
-    fbGetDrawable (pSrcDrawable, src, srcStride, srcBpp, srcXoff, srcYoff);
-    fbGetDrawable (pDstDrawable, dst, dstStride, dstBpp, dstXoff, dstYoff);
-    
-    while (nbox--)
-    {
-	rlBlt (src + (pbox->y1 + dy + srcYoff) * srcStride,
-	       srcStride,
-	       (pbox->x1 + dx + srcXoff) * srcBpp,
-    
-	       pDstDrawable->pScreen,
-               dst + (pbox->y1 + dstYoff) * dstStride,
-	       dstStride,
-	       (pbox->x1 + dstXoff) * dstBpp,
-    
-	       (pbox->x2 - pbox->x1) * dstBpp,
-	       (pbox->y2 - pbox->y1),
-    
-	       alu,
-	       pm,
-	       dstBpp,
-    
-	       reverse,
-	       upsidedown);
-	pbox++;
-    }
-}
-
-RegionPtr
-rlCopyArea (DrawablePtr	pSrcDrawable,
-	    DrawablePtr	pDstDrawable,
-	    GCPtr	pGC,
-	    int		xIn, 
-	    int		yIn,
-	    int		widthSrc, 
-	    int		heightSrc,
-	    int		xOut, 
-	    int		yOut)
-{
-    fbCopyProc	copy;
-    
-#ifdef FB_24_32BIT
-    if (pSrcDrawable->bitsPerPixel != pDstDrawable->bitsPerPixel)
-	copy = fb24_32CopyMtoN;
-    else
-#endif
-	copy = rlCopyNtoN;
-    return fbDoCopy (pSrcDrawable, pDstDrawable, pGC, xIn, yIn,
-		     widthSrc, heightSrc, xOut, yOut, copy, 0, 0);
-}
diff --git a/miext/rootless/accel/rlFill.c b/miext/rootless/accel/rlFill.c
deleted file mode 100644
index a80c776..0000000
--- a/miext/rootless/accel/rlFill.c
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * This code is largely copied from fbfill.c.
- *
- * Copyright © 1998 Keith Packard
- * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Keith Packard not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Keith Packard makes no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.
- *
- * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS SOFTWARE.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "fb.h"
-#include "rlAccel.h"
-
-
-void
-rlFill (DrawablePtr pDrawable,
-	GCPtr	    pGC,
-	int	    x,
-	int	    y,
-	int	    width,
-	int	    height)
-{
-    FbBits	    *dst;
-    FbStride	    dstStride;
-    int		    dstBpp;
-    int		    dstXoff, dstYoff;
-    FbGCPrivPtr	    pPriv = fbGetGCPrivate(pGC);
-    
-    fbGetDrawable (pDrawable, dst, dstStride, dstBpp, dstXoff, dstYoff);
-
-    switch (pGC->fillStyle) {
-    case FillSolid:
-	rlSolid (pDrawable->pScreen,
-                 dst + (y + dstYoff) * dstStride, 
-		 dstStride, 
-		 (x + dstXoff) * dstBpp,
-		 dstBpp,
-		 width * dstBpp, height,
-		 pPriv->and, pPriv->xor);
-	break;
-    case FillStippled:
-    case FillOpaqueStippled: {
-	PixmapPtr   pStip = pGC->stipple;
-	int	    stipWidth = pStip->drawable.width;
-	int	    stipHeight = pStip->drawable.height;
-	
-	if (dstBpp == 1)
-	{
-	    int		alu;
-	    FbBits	*stip;
-	    FbStride    stipStride;
-	    int		stipBpp;
-	    int		stipXoff, stipYoff; /* XXX assumed to be zero */
-
-	    if (pGC->fillStyle == FillStippled)
-		alu = FbStipple1Rop(pGC->alu,pGC->fgPixel);
-	    else
-		alu = FbOpaqueStipple1Rop(pGC->alu,pGC->fgPixel,pGC->bgPixel);
-	    fbGetDrawable (&pStip->drawable, stip, stipStride, stipBpp, stipXoff, stipYoff);
-	    fbTile (dst + (y + dstYoff) * dstStride,
-		    dstStride,
-		    x + dstXoff,
-		    width, height,
-		    stip,
-		    stipStride,
-		    stipWidth,
-		    stipHeight,
-		    alu,
-		    pPriv->pm,
-		    dstBpp,
-		    
-		    (pGC->patOrg.x + pDrawable->x + dstXoff),
-		    pGC->patOrg.y + pDrawable->y - y);
-	}
-	else
-	{
-	    FbStip	*stip;
-	    FbStride    stipStride;
-	    int		stipBpp;
-	    int		stipXoff, stipYoff; /* XXX assumed to be zero */
-	    FbBits	fgand, fgxor, bgand, bgxor;
-
-	    fgand = pPriv->and;
-	    fgxor = pPriv->xor;
-	    if (pGC->fillStyle == FillStippled)
-	    {
-		bgand = fbAnd(GXnoop,(FbBits) 0,FB_ALLONES);
-		bgxor = fbXor(GXnoop,(FbBits) 0,FB_ALLONES);
-	    }
-	    else
-	    {
-		bgand = pPriv->bgand;
-		bgxor = pPriv->bgxor;
-	    }
-
-	    fbGetStipDrawable (&pStip->drawable, stip, stipStride, stipBpp, stipXoff, stipYoff);
-	    fbStipple (dst + (y + dstYoff) * dstStride, 
-		       dstStride, 
-		       (x + dstXoff) * dstBpp,
-		       dstBpp,
-		       width * dstBpp, height,
-		       stip,
-		       stipStride,
-		       stipWidth,
-		       stipHeight,
-		       pPriv->evenStipple,
-		       fgand, fgxor,
-		       bgand, bgxor,
-		       pGC->patOrg.x + pDrawable->x + dstXoff,
-		       pGC->patOrg.y + pDrawable->y - y);
-	}
-	break;
-    }
-    case FillTiled: {
-	PixmapPtr   pTile = pGC->tile.pixmap;
-	FbBits	    *tile;
-	FbStride    tileStride;
-	int	    tileBpp;
-	int	    tileWidth;
-	int	    tileHeight;
-	int	    tileXoff, tileYoff; /* XXX assumed to be zero */
-	
-	fbGetDrawable (&pTile->drawable, tile, tileStride, tileBpp, tileXoff, tileYoff);
-	tileWidth = pTile->drawable.width;
-	tileHeight = pTile->drawable.height;
-	fbTile (dst + (y + dstYoff) * dstStride, 
-		dstStride, 
-		(x + dstXoff) * dstBpp, 
-		width * dstBpp, height,
-		tile,
-		tileStride,
-		tileWidth * tileBpp,
-		tileHeight,
-		pGC->alu,
-		pPriv->pm,
-		dstBpp,
-		(pGC->patOrg.x + pDrawable->x + dstXoff) * dstBpp,
-		pGC->patOrg.y + pDrawable->y - y);
-	break;
-    }
-    }
-    fbValidateDrawable (pDrawable);
-}
-
-void
-rlSolidBoxClipped (DrawablePtr	pDrawable,
-		   RegionPtr	pClip,
-		   int		x1,
-		   int		y1,
-		   int		x2,
-		   int		y2,
-		   FbBits	and,
-		   FbBits	xor)
-{
-    FbBits	*dst;
-    FbStride	dstStride;
-    int		dstBpp;
-    int		dstXoff, dstYoff;
-    BoxPtr	pbox;
-    int		nbox;
-    int		partX1, partX2, partY1, partY2;
-
-    fbGetDrawable (pDrawable, dst, dstStride, dstBpp, dstXoff, dstYoff);
-    
-    for (nbox = REGION_NUM_RECTS(pClip), pbox = REGION_RECTS(pClip); 
-	 nbox--; 
-	 pbox++)
-    {
-	partX1 = pbox->x1;
-	if (partX1 < x1)
-	    partX1 = x1;
-	
-	partX2 = pbox->x2;
-	if (partX2 > x2)
-	    partX2 = x2;
-	
-	if (partX2 <= partX1)
-	    continue;
-	
-	partY1 = pbox->y1;
-	if (partY1 < y1)
-	    partY1 = y1;
-	
-	partY2 = pbox->y2;
-	if (partY2 > y2)
-	    partY2 = y2;
-	
-	if (partY2 <= partY1)
-	    continue;
-	
-	rlSolid (pDrawable->pScreen,
-                 dst + (partY1 + dstYoff) * dstStride,
-		 dstStride,
-		 (partX1 + dstXoff) * dstBpp,
-		 dstBpp,
-
-		 (partX2 - partX1) * dstBpp,
-		 (partY2 - partY1),
-		 and, xor);
-    }
-}
diff --git a/miext/rootless/accel/rlFillRect.c b/miext/rootless/accel/rlFillRect.c
deleted file mode 100644
index 6efed3b..0000000
--- a/miext/rootless/accel/rlFillRect.c
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * This code is largely copied from fbfillrect.c.
- *
- * Copyright © 1998 Keith Packard
- * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Keith Packard not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Keith Packard makes no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.
- *
- * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS SOFTWARE.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "fb.h"
-#include "rlAccel.h"
-
-
-void
-rlPolyFillRect(DrawablePtr  pDrawable, 
-	       GCPtr	    pGC, 
-	       int	    nrect,
-	       xRectangle   *prect)
-{
-    RegionPtr	    pClip = fbGetCompositeClip(pGC);
-    register BoxPtr pbox;
-    BoxPtr	    pextent;
-    int		    extentX1, extentX2, extentY1, extentY2;
-    int		    fullX1, fullX2, fullY1, fullY2;
-    int		    partX1, partX2, partY1, partY2;
-    int		    xorg, yorg;
-    int		    n;
-
-    xorg = pDrawable->x;
-    yorg = pDrawable->y;
-    
-    pextent = REGION_EXTENTS(pGC->pScreen, pClip);
-    extentX1 = pextent->x1;
-    extentY1 = pextent->y1;
-    extentX2 = pextent->x2;
-    extentY2 = pextent->y2;
-    while (nrect--)
-    {
-	fullX1 = prect->x + xorg;
-	fullY1 = prect->y + yorg;
-	fullX2 = fullX1 + (int) prect->width;
-	fullY2 = fullY1 + (int) prect->height;
-	prect++;
-	
-	if (fullX1 < extentX1)
-	    fullX1 = extentX1;
-
-	if (fullY1 < extentY1)
-	    fullY1 = extentY1;
-
-	if (fullX2 > extentX2)
-	    fullX2 = extentX2;
-	
-	if (fullY2 > extentY2)
-	    fullY2 = extentY2;
-
-	if ((fullX1 >= fullX2) || (fullY1 >= fullY2))
-	    continue;
-	n = REGION_NUM_RECTS (pClip);
-	if (n == 1)
-	{
-	    rlFill (pDrawable,
-		    pGC,
-		    fullX1, fullY1, fullX2-fullX1, fullY2-fullY1);
-	}
-	else
-	{
-	    pbox = REGION_RECTS(pClip);
-	    /* 
-	     * clip the rectangle to each box in the clip region
-	     * this is logically equivalent to calling Intersect()
-	     */
-	    while(n--)
-	    {
-		partX1 = pbox->x1;
-		if (partX1 < fullX1)
-		    partX1 = fullX1;
-		partY1 = pbox->y1;
-		if (partY1 < fullY1)
-		    partY1 = fullY1;
-		partX2 = pbox->x2;
-		if (partX2 > fullX2)
-		    partX2 = fullX2;
-		partY2 = pbox->y2;
-		if (partY2 > fullY2)
-		    partY2 = fullY2;
-    
-		pbox++;
-		
-		if (partX1 < partX2 && partY1 < partY2)
-		    rlFill (pDrawable, pGC,
-			    partX1, partY1,
-			    partX2 - partX1, partY2 - partY1);
-	    }
-	}
-    }
-}
diff --git a/miext/rootless/accel/rlFillSpans.c b/miext/rootless/accel/rlFillSpans.c
deleted file mode 100644
index ab8bff0..0000000
--- a/miext/rootless/accel/rlFillSpans.c
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * This code is largely copied from fbfillsp.c.
- *
- * Copyright © 1998 Keith Packard
- * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Keith Packard not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Keith Packard makes no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.
- *
- * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS SOFTWARE.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "fb.h"
-#include "rlAccel.h"
-
-
-void
-rlFillSpans (DrawablePtr    pDrawable,
-	     GCPtr	    pGC,
-	     int	    n,
-	     DDXPointPtr    ppt,
-	     int	    *pwidth,
-	     int	    fSorted)
-{
-    RegionPtr	    pClip = fbGetCompositeClip(pGC);
-    BoxPtr	    pextent, pbox;
-    int		    nbox;
-    int		    extentX1, extentX2, extentY1, extentY2;
-    int		    fullX1, fullX2, fullY1;
-    int		    partX1, partX2;
-    
-    pextent = REGION_EXTENTS(pGC->pScreen, pClip);
-    extentX1 = pextent->x1;
-    extentY1 = pextent->y1;
-    extentX2 = pextent->x2;
-    extentY2 = pextent->y2;
-    while (n--)
-    {
-	fullX1 = ppt->x;
-	fullY1 = ppt->y;
-	fullX2 = fullX1 + (int) *pwidth;
-	ppt++;
-	pwidth++;
-	
-	if (fullY1 < extentY1 || extentY2 <= fullY1)
-	    continue;
-	
-	if (fullX1 < extentX1)
-	    fullX1 = extentX1;
-
-	if (fullX2 > extentX2)
-	    fullX2 = extentX2;
-	
-	if (fullX1 >= fullX2)
-	    continue;
-	
-	nbox = REGION_NUM_RECTS (pClip);
-	if (nbox == 1)
-	{
-	    rlFill (pDrawable,
-		    pGC,
-		    fullX1, fullY1, fullX2-fullX1, 1);
-	}
-	else
-	{
-	    pbox = REGION_RECTS(pClip);
-	    while(nbox--)
-	    {
-		if (pbox->y1 <= fullY1 && fullY1 < pbox->y2)
-		{
-		    partX1 = pbox->x1;
-		    if (partX1 < fullX1)
-			partX1 = fullX1;
-		    partX2 = pbox->x2;
-		    if (partX2 > fullX2)
-			partX2 = fullX2;
-		    if (partX2 > partX1)
-		    {
-			rlFill (pDrawable, pGC,
-				partX1, fullY1,
-				partX2 - partX1, 1);
-		    }
-		}
-		pbox++;
-	    }
-	}
-    }
-}
diff --git a/miext/rootless/accel/rlGlyph.c b/miext/rootless/accel/rlGlyph.c
deleted file mode 100644
index 82cd06c..0000000
--- a/miext/rootless/accel/rlGlyph.c
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * This code is largely copied from fbglyph.c.
- *
- * Copyright © 1998 Keith Packard
- * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Keith Packard not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Keith Packard makes no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.
- *
- * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS SOFTWARE.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "fb.h"
-#include <X11/fonts/fontstruct.h>
-#include "dixfontstr.h"
-#include "rlAccel.h"
-
-      
-void
-rlImageGlyphBlt (DrawablePtr	pDrawable,
-		 GCPtr		pGC,
-		 int		x, 
-		 int		y,
-		 unsigned int	nglyph,
-		 CharInfoPtr	*ppciInit,
-		 pointer	pglyphBase)
-{
-    FbGCPrivPtr	    pPriv = fbGetGCPrivate(pGC);
-    CharInfoPtr	    *ppci;
-    CharInfoPtr	    pci;
-    unsigned char   *pglyph;		/* pointer bits in glyph */
-    int		    gWidth, gHeight;	/* width and height of glyph */
-    FbStride	    gStride;		/* stride of glyph */
-    Bool	    opaque;
-    int		    n;
-    int		    gx, gy;
-#ifndef FBNOPIXADDR
-    void	    (*glyph) (FbBits *,
-			      FbStride,
-			      int,
-			      FbStip *,
-			      FbBits,
-			      int,
-			      int);
-    FbBits	    *dst = 0;
-    FbStride	    dstStride = 0;
-    int		    dstBpp = 0;
-    int		    dstXoff = 0, dstYoff = 0;
-    
-    glyph = 0;
-    if (pPriv->and == 0)
-    {
-	fbGetDrawable (pDrawable, dst, dstStride, dstBpp, dstXoff, dstYoff);
-	switch (dstBpp) {
-	case 8:	    glyph = fbGlyph8; break;
-	case 16:    glyph = fbGlyph16; break;
-#ifdef FB_24BIT
-	case 24:    glyph = fbGlyph24; break;
-#endif
-	case 32:    glyph = fbGlyph32; break;
-	}
-    }
-#endif
-    
-    x += pDrawable->x;
-    y += pDrawable->y;
-
-    if (TERMINALFONT (pGC->font)
-#ifndef FBNOPIXADDR
-	&& !glyph
-#endif
-	)
-    {
-	opaque = TRUE;
-    }
-    else
-    {
-	int		xBack, widthBack;
-	int		yBack, heightBack;
-	
-	ppci = ppciInit;
-	n = nglyph;
-	widthBack = 0;
-	while (n--)
-	    widthBack += (*ppci++)->metrics.characterWidth;
-	
-        xBack = x;
-	if (widthBack < 0)
-	{
-	    xBack += widthBack;
-	    widthBack = -widthBack;
-	}
-	yBack = y - FONTASCENT(pGC->font);
-	heightBack = FONTASCENT(pGC->font) + FONTDESCENT(pGC->font);
-	rlSolidBoxClipped (pDrawable,
-			   fbGetCompositeClip(pGC),
-			   xBack,
-			   yBack,
-			   xBack + widthBack,
-			   yBack + heightBack,
-			   fbAnd(GXcopy,pPriv->bg,pPriv->pm),
-			   fbXor(GXcopy,pPriv->bg,pPriv->pm));
-	opaque = FALSE;
-    }
-
-    ppci = ppciInit;
-    while (nglyph--)
-    {
-	pci = *ppci++;
-	pglyph = FONTGLYPHBITS(pglyphBase, pci);
-	gWidth = GLYPHWIDTHPIXELS(pci);
-	gHeight = GLYPHHEIGHTPIXELS(pci);
-	if (gWidth && gHeight)
-	{
-	    gx = x + pci->metrics.leftSideBearing;
-	    gy = y - pci->metrics.ascent; 
-#ifndef FBNOPIXADDR
-	    if (glyph && gWidth <= sizeof (FbStip) * 8 &&
-		fbGlyphIn (fbGetCompositeClip(pGC), gx, gy, gWidth, gHeight))
-	    {
-		(*glyph) (dst + (gy + dstYoff) * dstStride,
-			  dstStride,
-			  dstBpp,
-			  (FbStip *) pglyph,
-			  pPriv->fg,
-			  gx + dstXoff,
-			  gHeight);
-	    }
-	    else
-#endif
-	    {
-		gStride = GLYPHWIDTHBYTESPADDED(pci) / sizeof (FbStip);
-		fbPutXYImage (pDrawable,
-			      fbGetCompositeClip(pGC),
-			      pPriv->fg,
-			      pPriv->bg,
-			      pPriv->pm,
-			      GXcopy,
-			      opaque,
-    
-			      gx,
-			      gy,
-			      gWidth, gHeight,
-    
-			      (FbStip *) pglyph,
-			      gStride,
-			      0);
-	    }
-	}
-	x += pci->metrics.characterWidth;
-    }
-}
diff --git a/miext/rootless/accel/rlSolid.c b/miext/rootless/accel/rlSolid.c
deleted file mode 100644
index fa4160f..0000000
--- a/miext/rootless/accel/rlSolid.c
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Accelerated rootless fill
- */
-/*
- * This code is largely copied from fbsolid.c.
- *
- * Copyright © 1998 Keith Packard
- * Copyright (c) 2002 Apple Computer, Inc. All Rights Reserved.
- * Copyright (c) 2003 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Keith Packard not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Keith Packard makes no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.
- *
- * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS SOFTWARE.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "fb.h"
-#include "rootlessCommon.h"
-
-
-void
-rlSolid (ScreenPtr  pScreen,
-         FbBits	    *dst,
-	 FbStride   dstStride,
-	 int	    dstX,
-	 int	    bpp,
-
-	 int	    width,
-	 int	    height,
-
-	 FbBits	    and,
-	 FbBits	    xor)
-{
-    FbBits  startmask, endmask;
-    int	    n, nmiddle;
-    int	    startbyte, endbyte;
-
-#ifdef FB_24BIT
-    if (bpp == 24 && (!FbCheck24Pix(and) || !FbCheck24Pix(xor)))
-    {
-	fbSolid24 (dst, dstStride, dstX, width, height, and, xor);
-	return;
-    }
-#endif
-	
-    dst += dstX >> FB_SHIFT;
-    dstX &= FB_MASK;
-    FbMaskBitsBytes(dstX, width, and == 0, startmask, startbyte, 
-		    nmiddle, endmask, endbyte);
-
-    /*
-     * Beginning of the rootless acceleration code
-     */
-    if (!startmask && !endmask && !and &&
-        height * nmiddle * sizeof (*dst) > rootless_FillBytes_threshold &&
-        SCREENREC(pScreen)->imp->FillBytes)
-    {
-	if (bpp <= 8)
-	    xor |= xor << 8;
-	if (bpp <= 16)
-	    xor |= xor << 16;
-
-	SCREENREC(pScreen)->imp->FillBytes(nmiddle * sizeof (*dst), height,
-                                           xor, (char *) dst + (dstX >> 3),
-                                           dstStride * sizeof (*dst));
-	return;
-    }
-    /* End of the rootless acceleration code */
-
-    if (startmask)
-	dstStride--;
-    dstStride -= nmiddle;
-    while (height--)
-    {
-	if (startmask)
-	{
-	    FbDoLeftMaskByteRRop(dst,startbyte,startmask,and,xor);
-	    dst++;
-	}
-	n = nmiddle;
-	if (!and)
-	    while (n--)
-		*dst++ = xor;
-	else
-	    while (n--)
-	    {
-		*dst = FbDoRRop (*dst, and, xor);
-		dst++;
-	    }
-	if (endmask)
-	    FbDoRightMaskByteRRop(dst,endbyte,endmask,and,xor);
-	dst += dstStride;
-    }
-}
commit d3d00d92586c3e1cbc88087c930b65c8b3832fcc
Author: Tilman Sauerbeck <tilman at code-monkey.de>
Date:   Sat Apr 19 12:54:40 2008 +0200

    Removed fbpseudocolor.h from sdk_HEADERS.

diff --git a/fb/Makefile.am b/fb/Makefile.am
index 2f03238..3994269 100644
--- a/fb/Makefile.am
+++ b/fb/Makefile.am
@@ -7,7 +7,7 @@ INCLUDES = \
 AM_CFLAGS = $(DIX_CFLAGS)
 
 if XORG
-sdk_HEADERS = fb.h fbrop.h fbpseudocolor.h fboverlay.h wfbrename.h
+sdk_HEADERS = fb.h fbrop.h fboverlay.h wfbrename.h
 endif
 
 libfb_la_CFLAGS = $(AM_CFLAGS)
commit 5bdc4198795ffd011bb07cffe3817e4cded87f60
Author: Adam Jackson <ajax at redhat.com>
Date:   Sat Apr 19 04:06:19 2008 -0400

    Remove fbpseudocolor
    
    "An experimental pseudocolor emulation layer.  Not fully completed,
    currently only works for 16bpp."  That was almost four years ago.
    It still doesn't work, only one driver even attempts to use it, it
    contains an ad-hoc implementation of damage, and should really be
    done up in Composite now anyway.

diff --git a/fb/Makefile.am b/fb/Makefile.am
index e34aaba..2f03238 100644
--- a/fb/Makefile.am
+++ b/fb/Makefile.am
@@ -49,9 +49,7 @@ libfb_la_SOURCES = 	\
 	fbtile.c	\
 	fbtrap.c	\
 	fbutil.c	\
-	fbwindow.c	\
-	fbpseudocolor.c \
-	fbpseudocolor.h
+	fbwindow.c
 
 libwfb_la_SOURCES = $(libfb_la_SOURCES)
 
diff --git a/fb/fbpseudocolor.c b/fb/fbpseudocolor.c
deleted file mode 100644
index 06cf159..0000000
--- a/fb/fbpseudocolor.c
+++ /dev/null
@@ -1,2248 +0,0 @@
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <string.h>
-
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include "scrnintstr.h"
-#include "colormapst.h"
-#include "glyphstr.h"
-#include "resource.h"
-#include <X11/fonts/font.h>
-#include "dixfontstr.h"
-#include <X11/fonts/fontstruct.h>
-#include "micmap.h"
-#include "fb.h"
-#include "fbpseudocolor.h"
-
-static Bool xxCreateGC(GCPtr pGC);
-static void xxValidateGC(GCPtr pGC, unsigned long changes, DrawablePtr pDraw);
-static void xxDestroyGC(GCPtr pGC);
-static void xxChangeGC (GCPtr pGC, unsigned long   mask);
-static void xxCopyGC (GCPtr pGCSrc, unsigned long   mask, GCPtr pGCDst);
-static void xxChangeClip (GCPtr pGC, int type, pointer pvalue, int nrects);
-
-static void xxCopyClip(GCPtr pgcDst, GCPtr pgcSrc);
-static void xxDestroyClip(GCPtr pGC);
-static void xxFillSpans(DrawablePtr pDraw, GC *pGC, int nInit,
-			DDXPointPtr pptInit, int *pwidthInit, int fSorted);
-static void xxSetSpans(DrawablePtr pDraw, GCPtr	pGC, char *pcharsrc,
-		       DDXPointPtr pptInit, int	*pwidthInit, int nspans,
-		       int fSorted);
-static void xxPutImage(DrawablePtr pDraw, GCPtr	pGC, int depth, int x, int y,
-		       int w, int h,int	leftPad, int format, char *pImage);
-static RegionPtr xxCopyPlane(DrawablePtr pSrc,
-			     DrawablePtr pDst, GCPtr pGC,int srcx, int srcy,
-			     int width, int height, int	dstx, int dsty,
-			     unsigned long bitPlane);
-static void xxPolyPoint(DrawablePtr pDraw, GCPtr pGC, int mode, int npt,
-			xPoint *pptInit);
-static void xxPolylines(DrawablePtr pDraw, GCPtr pGC, int mode,
-			int npt, DDXPointPtr pptInit);
-static void xxPolySegment(DrawablePtr pDraw, GCPtr pGC, int nseg,
-			  xSegment *pSeg);
-static void xxPolyRectangle(DrawablePtr  pDraw, GCPtr pGC, int nRects,
-			    xRectangle  *pRects);
-static void xxPolyArc( DrawablePtr pDraw, GCPtr	pGC, int narcs, xArc *parcs);
-static void xxFillPolygon(DrawablePtr pDraw, GCPtr pGC, int shape,
-			  int mode, int count, DDXPointPtr pptInit);
-static void xxPolyFillRect(DrawablePtr pDraw, GCPtr pGC, int nRectsInit, 
-			   xRectangle *pRectsInit);
-static RegionPtr xxCopyArea(DrawablePtr pSrc, DrawablePtr pDst, GC *pGC,
-			    int srcx, int srcy, int width, int height,
-			    int dstx, int dsty);
-static void xxPolyFillArc(DrawablePtr pDraw, GCPtr pGC, int narcs,
-			  xArc *parcs);
-static int xxPolyText8(DrawablePtr pDraw, GCPtr	pGC, int x, int	y, int count,
-		       char *chars);
-static int xxPolyText16(DrawablePtr pDraw, GCPtr pGC, int x, int y,
-			int count, unsigned short *chars);
-static void xxImageText8(DrawablePtr pDraw, GCPtr pGC, int x, 
-			 int y, int count, char	*chars);
-static void xxImageText16(DrawablePtr pDraw, GCPtr pGC, int x, int y,
-			  int count, unsigned short *chars);
-static void xxImageGlyphBlt(DrawablePtr pDraw, GCPtr pGC, int x, int y,
-			    unsigned int nglyph, CharInfoPtr *ppci,
-			    pointer pglyphBase);
-static void xxPolyGlyphBlt(DrawablePtr pDraw, GCPtr pGC, int x, int y,
-			   unsigned int nglyph, CharInfoPtr *ppci,
-			   pointer pglyphBase);
-static void xxPushPixels(GCPtr pGC, PixmapPtr pBitMap, DrawablePtr pDraw,
-			 int	dx, int dy, int xOrg, int yOrg);
-static void
-xxComposite (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst,
-	     INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask,
-	     INT16 xDst, INT16 yDst, CARD16 width, CARD16 height);
-static void
-xxGlyphs (CARD8 op, PicturePtr pSrc, PicturePtr pDst,
-	  PictFormatPtr maskFormat, INT16 xSrc, INT16 ySrc, int nlist,
-	  GlyphListPtr list, GlyphPtr *glyphs);
-
-
-typedef struct _xxCmapPrivRec {
-    CARD32* cmap;
-    ColormapPtr pmap;
-    Bool dirty;
-    struct _xxCmapPrivRec *next;
-} xxCmapPrivRec, *xxCmapPrivPtr;
-
-
-typedef struct {
-    CloseScreenProcPtr		CloseScreen;
-    CreateScreenResourcesProcPtr CreateScreenResources;
-    CreateWindowProcPtr		CreateWindow;
-    CopyWindowProcPtr		CopyWindow;
-    WindowExposuresProcPtr	WindowExposures;
-    CreateGCProcPtr		CreateGC;
-    CreateColormapProcPtr	CreateColormap;
-    DestroyColormapProcPtr	DestroyColormap;
-    InstallColormapProcPtr	InstallColormap;
-    UninstallColormapProcPtr	UninstallColormap;
-    ListInstalledColormapsProcPtr ListInstalledColormaps;
-    StoreColorsProcPtr		StoreColors;
-#ifdef RENDER
-    CompositeProcPtr		Composite;
-    GlyphsProcPtr		Glyphs;
-#endif    
-    PixmapPtr			pPixmap;
-    char *			addr;
-    pointer			pBits;
-    RegionRec			region;
-    VisualPtr			bVisual;
-    RegionRec			bRegion;
-    int				myDepth;
-    int				depth;
-    ColormapPtr			baseCmap;
-    ColormapPtr*		InstalledCmaps;
-    xxCmapPrivPtr		Cmaps;
-    int				numInstalledColormaps;
-    int				colormapDirty;
-    xxSyncFunc			sync;
-} xxScrPrivRec, *xxScrPrivPtr;
-
-#define xxGetScrPriv(s)	((xxScrPrivPtr) \
-    dixLookupPrivate(&(s)->devPrivates, xxScrPrivateKey))
-#define xxScrPriv(s)     xxScrPrivPtr pScrPriv = xxGetScrPriv(s)
-
-#define xxGetCmapPriv(s) ((xxCmapPrivPtr) \
-    dixLookupPrivate(&(s)->devPrivates, xxColormapPrivateKey))
-#define xxCmapPriv(s)    xxCmapPrivPtr pCmapPriv = xxGetCmapPriv(s);
-
-typedef struct _xxGCPriv {
-    GCOps   *ops;
-    GCFuncs *funcs;
-} xxGCPrivRec, *xxGCPrivPtr;
-
-#define xxGetGCPriv(pGC) ((xxGCPrivPtr) \
-    dixLookupPrivate(&(pGC)->devPrivates, xxGCPrivateKey))
-#define xxGCPriv(pGC)   xxGCPrivPtr  pGCPriv = xxGetGCPriv(pGC)
-
-static DevPrivateKey xxScrPrivateKey = &xxScrPrivateKey;
-static DevPrivateKey xxGCPrivateKey = &xxGCPrivateKey;
-static DevPrivateKey xxColormapPrivateKey = &xxColormapPrivateKey;
-
-
-#define wrap(priv,real,mem,func) {\
-    priv->mem = real->mem; \
-    real->mem = func; \
-}
-
-#define unwrap(priv,real,mem) {\
-    real->mem = priv->mem; \
-}
-
-#define MARK_DIRTY (1 << 31)
-
-#define MAX_NUM_XX_INSTALLED_CMAPS 255
-/* #define DEBUG  */
-#ifdef DEBUG
-# define DBG ErrorF
-# define DBG_ARGS(x) ErrorF x
-# define PRINT_RECTS(rec) {\
-       int i;\
-       BoxPtr box;\
-       ErrorF("RECTS: %i\n",REGION_NUM_RECTS(&rec));\
-       if (REGION_NUM_RECTS(&rec) > 1)  { \
-          for (i = 0; i < REGION_NUM_RECTS(&rec); i++ ) {\
-             box = REGION_BOX(&rec,i);\
-	     ErrorF("x1: %hi x2: %hi y1: %hi y2: %hi\n", \
-             box->x1,box->x2,box->y1,box->y2);\
-          }\
-       } else { \
-             box = &(rec.extents); \
-	     ErrorF("x1: %hi x2: %hi y1: %hi y2: %hi\n", \
-             box->x1,box->x2,box->y1,box->y2);\
-       } \
-}
-#else
-# define DBG(x)
-# define DBG_ARGS(x)
-# define PRINT_RECTS(rec)
-#endif
-
-#if 0
-static void xxCopyPseudocolorRegion(ScreenPtr pScreen, RegionPtr pReg,
-				    xxCmapPrivPtr pCmapPriv);
-static void xxUpdateFb(ScreenPtr pScreen);
-
-
-static void
-xxUpdateWindowImmediately(WindowPtr pWin)
-{
-    xxScrPriv(pWin->drawable.pScreen);
-    xxCmapPrivPtr pCmapPriv;
-    ColormapPtr pmap;
-	    
-    pmap = (ColormapPtr)LookupIDByType(wColormap(pWin),RT_COLORMAP);
-    
-    if (pmap && (pCmapPriv = xxGetCmapPriv(pmap)) != (pointer)-1) {
-	xxCopyPseudocolorRegion(pWin->drawable.pScreen,
-				&pScrPriv->region, pCmapPriv);
-    }
-}
-#else
-# define xxUpdateWindowImmediately(x)
-#endif
-
-static ColormapPtr
-xxGetBaseColormap(ScreenPtr pScreen)
-{
-    xxScrPriv(pScreen);
-    DepthPtr pDepth = pScreen->allowedDepths;
-    int i,j,k;
-    ColormapPtr pDefMap
-	=  (ColormapPtr) LookupIDByType(pScreen->defColormap,RT_COLORMAP);
-    ColormapPtr cmap = NULL;
-    VisualPtr pVisual = NULL;
-	
-    for (i = 0; i < pScreen->numDepths; i++, pDepth++)
-	if (pDepth->depth == pScrPriv->depth) {
-	    for (j = 0; j < pDepth->numVids; j++) {
-		if (pDefMap->pVisual->vid == pDepth->vids[j]
-		    && pDefMap->pVisual->class == TrueColor) {
-		    cmap = pDefMap;
-		    break;
-		}
-		if (!pVisual) {
-		    for (k = 0; k < pScreen->numVisuals; k++) {
-			if (pScreen->visuals[k].class == TrueColor
-			    && pScreen->visuals[k].vid
-			    == pDepth->vids[j]) {
-			    pVisual = &pScreen->visuals[k];
-			    break;
-			}
-		    }
-		}
-	    }
-	    if (cmap)
-		break;
-	}
-	    
-    if (!cmap) {
-	CreateColormap(FakeClientID(0),pScreen,pVisual,&cmap,AllocNone,0);
-    }
-    
-    return cmap;
-}
-
-static Bool
-xxCreateScreenResources(ScreenPtr pScreen)
-{
-    PixmapPtr		pPix;
-    xxScrPriv(pScreen);
-    Bool		ret;
-    PixmapPtr		pPixmap;
-    BoxRec		box;
-    int			depth = pScrPriv->myDepth;
-    pointer		pBits;
-    
-    unwrap (pScrPriv,pScreen, CreateScreenResources);
-    ret = pScreen->CreateScreenResources(pScreen);
-    wrap(pScrPriv,pScreen,CreateScreenResources,xxCreateScreenResources);
-
-    if (!ret) return FALSE;
-    
-    pScrPriv->pBits = NULL;
-    if (pScrPriv->addr)
-	pBits = pScrPriv->addr;
-    else
-	pBits = xalloc(pScreen->width * pScreen->height
-		       * (BitsPerPixel(depth) >> 3));
-    if (!pBits) return FALSE;
-    
-    pPixmap = (*pScreen->CreatePixmap)(pScreen, 0, 0, depth, 0);
-    if (!pPixmap) {
-	xfree(pBits);
-	return FALSE;
-    }
-    if (!(*pScreen->ModifyPixmapHeader)(pPixmap, pScreen->width,
-					pScreen->height, depth,
-					BitsPerPixel(depth),
-					PixmapBytePad(pScreen->width, depth),
-					pBits)) {
-	xfree(pBits);
-	return FALSE;
-    }
-    if (pScreen->rootDepth == pScrPriv->myDepth) {
-	pPix = (PixmapPtr)pScreen->devPrivate;    
-	if (!(*pScreen->ModifyPixmapHeader)(pPix, 0,0, pScrPriv->depth,
-					    BitsPerPixel(pScrPriv->depth),
-					    PixmapBytePad(pScreen->width,
-							  pScrPriv->depth),
-					    0)) {
-	    xfree(pBits);
-	    return FALSE;
-	}
-    }
-
-    pScrPriv->baseCmap = xxGetBaseColormap(pScreen);
-    
-    pScrPriv->pBits = pBits;
-    pScrPriv->pPixmap = pPixmap;
-    box.x1 = 0;
-    box.y1 = 0;
-    box.x2 = pScreen->width;
-    box.y2 = pScreen->height;
-    REGION_NULL(pScreen, &pScrPriv->region);
-    REGION_INIT(pScreen, &pScrPriv->bRegion, &box, 0);
-    
-    return TRUE;
-}
-
-static Bool
-xxCloseScreen (int iScreen, ScreenPtr pScreen)
-{
-    xxScrPriv(pScreen);
-    Bool		ret;
-
-    (*pScreen->DestroyPixmap)(pScrPriv->pPixmap);
-    /* We don't need to free the baseColormap as FreeClientResourcess
-       will have taken care of it. */
-    REGION_UNINIT (pScreen, &pScrPriv->region);
-    
-    unwrap (pScrPriv,pScreen, CloseScreen);
-    ret = pScreen->CloseScreen(iScreen,pScreen);
-
-    xfree(pScrPriv->pBits);
-    xfree(pScrPriv->InstalledCmaps);
-    xfree(pScrPriv);
-    
-    return TRUE;
-}
-
-static Bool
-xxMyVisual(ScreenPtr pScreen, VisualID vid)
-{
-    xxScrPriv(pScreen);
-    DepthPtr pDepth = pScreen->allowedDepths;
-    int i,j;
-    
-    for (i = 0; i < pScreen->numDepths; i++, pDepth++)
-	if (pDepth->depth == pScrPriv->myDepth) {
-	    for (j = 0; j < pDepth->numVids; j++) {
-		if (vid == pDepth->vids[j]) {
-		    return TRUE;
-		}
-	    }
-	}
-    return FALSE;
-}
-
-static Bool
-xxInitColormapPrivate(ColormapPtr pmap)
-{
-    xxScrPriv(pmap->pScreen);
-    xxCmapPrivPtr	pCmapPriv;
-    pointer		cmap;
-
-    dixSetPrivate(&pmap->devPrivates, xxColormapPrivateKey, (pointer) -1);
-    
-    if (xxMyVisual(pmap->pScreen,pmap->pVisual->vid)) {
-	DBG("CreateColormap\n");
-	pCmapPriv = (xxCmapPrivPtr) xalloc (sizeof (xxCmapPrivRec));
-	if (!pCmapPriv)
-	    return FALSE;
-	dixSetPrivate(&pmap->devPrivates, xxColormapPrivateKey, pCmapPriv);
-	cmap = xalloc(sizeof (CARD32) * (1 << pScrPriv->myDepth));
-	if (!cmap)
-	return FALSE;
-
-	memset(cmap,0,sizeof (CARD32) * (1 << pScrPriv->myDepth));
-	
-	pCmapPriv->cmap = cmap;
-	pCmapPriv->dirty = FALSE;
-	pCmapPriv->pmap = pmap;
-	pCmapPriv->next = pScrPriv->Cmaps;
-	pScrPriv->Cmaps = pCmapPriv;
-    }
-    return TRUE;
-}
-
-
-static Bool
-xxCreateColormap(ColormapPtr pmap)
-{
-    xxScrPriv(pmap->pScreen);
-    Bool		ret;
-    
-    if (!xxInitColormapPrivate(pmap)) return FALSE;
-    
-    unwrap(pScrPriv,pmap->pScreen, CreateColormap);
-    ret = pmap->pScreen->CreateColormap(pmap);
-    wrap(pScrPriv,pmap->pScreen,CreateColormap,xxCreateColormap);
-    
-    return ret;
-}
-
-static int
-xxCmapInstalled(ColormapPtr pmap)
-{
-    xxScrPriv(pmap->pScreen);
-    int i;
-    
-    for (i = 0; i < pScrPriv->numInstalledColormaps; i++)
-	if (pScrPriv->InstalledCmaps[i] == pmap)
-	    break;
-	if (i == pScrPriv->numInstalledColormaps) /* not installed */
-	    return -1;
-	return i;
-}
-
-static void
-xxInstalledCmapDelete(ScreenPtr pScreen, int num)
-{
-    xxScrPriv(pScreen);
-    int i;
-
-    pScrPriv->numInstalledColormaps--;
-    
-    for (i = num; i < pScrPriv->numInstalledColormaps; i++)
-	pScrPriv->InstalledCmaps[i] = pScrPriv->InstalledCmaps[i+1];
-}
-
-static void
-xxDestroyColormap(ColormapPtr pmap)
-{
-    xxScrPriv(pmap->pScreen);
-    xxCmapPriv(pmap);
-
-    if (pCmapPriv != (pointer) -1) {
-	xxCmapPrivPtr tmpCmapPriv = pScrPriv->Cmaps;
-	xxCmapPrivPtr *prevCmapPriv = &pScrPriv->Cmaps;
-	int n;
-	
-	DBG("DestroyColormap\n");
-
-	if ((n = xxCmapInstalled(pmap)) != -1)
-	    xxInstalledCmapDelete(pmap->pScreen,n);
-
-	while (tmpCmapPriv) {
-	    if (tmpCmapPriv->pmap == pmap) {
-		*prevCmapPriv = tmpCmapPriv->next;
-		break;
-	    }
-	    prevCmapPriv = &tmpCmapPriv->next;
-	    tmpCmapPriv = tmpCmapPriv->next;
-	}
-	
-	xfree(pCmapPriv->cmap);
-	xfree(pCmapPriv);
-    }
-
-    unwrap(pScrPriv,pmap->pScreen, DestroyColormap);
-    pmap->pScreen->DestroyColormap(pmap);
-    wrap(pScrPriv,pmap->pScreen,DestroyColormap,xxDestroyColormap);
-}
-
-#define Shift(v,d)  ((d) < 0 ? ((v) >> (-d)) : ((v) << (d)))
-
-static int
-xxComputeCmapShift (unsigned long mask)
-{
-    int	shift;
-    unsigned long   bit;
-    
-    shift = 16;
-    bit = 0x80000000;
-    while (!(mask & bit))
-    {
-	shift--;
-	bit >>= 1;
-    }
-    return shift;
-}
-
-static void
-xxStoreColors(ColormapPtr pmap, int nColors, xColorItem *pColors)
-{
-    xxScrPriv(pmap->pScreen);
-    xxCmapPriv(pmap);
-
-    if (pCmapPriv != (pointer) -1) {
-
-	xColorItem	*expanddefs;
-	int		i;
-	VisualPtr	bVisual;
-	int		rs, gs, bs;
-
-	if (nColors == 0) return;
-
-	DBG("StoreColors\n");
-	
-	expanddefs = xalloc(sizeof(xColorItem)
-				    * (1 <<  pScrPriv->myDepth));
-	if (!expanddefs) return;
-	
-	bVisual = pScrPriv->bVisual;
-
-	DBG("StoreColors\n");
-
-	rs = xxComputeCmapShift(bVisual->redMask);
-	gs = xxComputeCmapShift(bVisual->greenMask);
-	bs = xxComputeCmapShift(bVisual->blueMask);
-	
-	if ((pmap->pVisual->class | DynamicClass) == DirectColor) {
-	    nColors = miExpandDirectColors(pmap, nColors, pColors, expanddefs);
-	    pColors = expanddefs;
-	}
-
-	for (i = 0; i < nColors; i++) {
-	    DBG_ARGS(("index: %i r 0x%x g 0x%x b 0x%x\n", pColors->pixel,
-		   pColors->red, pColors->green, pColors->blue));
-	    pCmapPriv->cmap[pColors->pixel] = MARK_DIRTY
-		| (Shift(pColors->red, rs) & bVisual->redMask)
-		| (Shift(pColors->green, gs) & bVisual->greenMask)
-		| (Shift(pColors->blue, bs)  & bVisual->blueMask);
-	    pColors++;
-	}
-
-	xfree(expanddefs);
-
-	pCmapPriv->dirty = TRUE;
-	pScrPriv->colormapDirty = TRUE;
-	
-	return;
-    }
-    
-    unwrap(pScrPriv,pmap->pScreen, StoreColors);
-    pmap->pScreen->StoreColors(pmap,nColors,pColors);
-    wrap(pScrPriv,pmap->pScreen,StoreColors,xxStoreColors);
-}
-
-static void
-xxInstallColormap(ColormapPtr pmap)
-{
-    int i;
-    xxScrPriv(pmap->pScreen);
-    xxCmapPriv(pmap);
-    
-    if (pCmapPriv != (pointer) -1) {
-	Pixel		*pixels;
-	xrgb		*colors;
-	int		i;
-	VisualPtr	pVisual;
-	xColorItem	*defs;
-
-	DBG("InstallColormap\n");
-
-	if (xxCmapInstalled(pmap) != -1)
-	    return;
-
-	if (!pScrPriv->numInstalledColormaps) {
-	    unwrap(pScrPriv,pmap->pScreen, InstallColormap);
-	    pmap->pScreen->InstallColormap(pScrPriv->baseCmap);
-	    wrap(pScrPriv,pmap->pScreen,InstallColormap,xxInstallColormap);
-	}
-	    
-	pixels = xalloc(sizeof(Pixel) * (1 <<  pScrPriv->myDepth));
-	colors = xalloc(sizeof(xrgb) * (1 <<  pScrPriv->myDepth));
-	defs = xalloc(sizeof(xColorItem) * (1 << pScrPriv->myDepth));
-	
-	if (!pixels || !colors)
-	    return;
-
-	/* if we have more than max installed delete the oldest */
-	if (pScrPriv->numInstalledColormaps == MAX_NUM_XX_INSTALLED_CMAPS)
-	    xxInstalledCmapDelete(pmap->pScreen,0);
-	
-	pScrPriv->InstalledCmaps[pScrPriv->numInstalledColormaps] = pmap;
-	pScrPriv->numInstalledColormaps++;
-	
-	pVisual = pScrPriv->bVisual;
-	
-	for (i = 0; i < (1 <<  pScrPriv->myDepth); i++)
-	    pixels[i] = i;
-	
-	QueryColors (pmap, (1 << pScrPriv->myDepth), pixels, colors);
-
-	for (i = 0; i < (1 <<  pScrPriv->myDepth); i++) {
-	    defs[i].pixel = pixels[i];
-            defs[i].red = colors[i].red;
-            defs[i].green = colors[i].green;
-            defs[i].blue = colors[i].blue;
-            defs[i].flags =  DoRed|DoGreen|DoBlue;
-        }
-	xxStoreColors(pmap,(1 <<  pScrPriv->myDepth),defs);
-
-	xfree(pixels);
-	xfree(colors);
-	xfree(defs);
-
-	return;
-    } 
-
-    for (i = pScrPriv->numInstalledColormaps; i ; i--)
-	WalkTree(pmap->pScreen, TellLostMap,
-		 (char *)&pScrPriv->InstalledCmaps[i-1]->mid);
-    
-    pScrPriv->numInstalledColormaps = 0;
-     
-    unwrap(pScrPriv,pmap->pScreen, InstallColormap);
-    pmap->pScreen->InstallColormap(pmap);
-    wrap(pScrPriv,pmap->pScreen,InstallColormap,xxInstallColormap);
-}
-
-static void
-xxUninstallColormap(ColormapPtr pmap)
-{
-    xxScrPriv(pmap->pScreen);
-    xxCmapPriv(pmap);
-
-    if (pCmapPriv != (pointer) -1) {
-	int num;
-	
-	if ((num = xxCmapInstalled(pmap)) == -1)
-	    return;
-	
-	DBG("UninstallColormap\n");
-	xxInstalledCmapDelete(pmap->pScreen,num);
-
-	return;
-    } 
-    
-    unwrap(pScrPriv,pmap->pScreen, UninstallColormap);
-    pmap->pScreen->UninstallColormap(pmap);
-    wrap(pScrPriv,pmap->pScreen,UninstallColormap,xxUninstallColormap);
-	
-}
-
-static int
-xxListInstalledColormaps(ScreenPtr pScreen, Colormap *pCmapIds)
-{
-    int			n,i;
-    xxScrPriv(pScreen);
-
-    unwrap(pScrPriv,pScreen, ListInstalledColormaps);
-    n = pScreen->ListInstalledColormaps(pScreen, pCmapIds);
-    wrap (pScrPriv,pScreen,ListInstalledColormaps,xxListInstalledColormaps);
-
-    pCmapIds += n;
-
-    for (i = 0; i < pScrPriv->numInstalledColormaps; i++) {
-	*pCmapIds++ = pScrPriv->InstalledCmaps[i]->mid;
-	n++;
-    }
-
-    return n;
-}
-
-static Bool
-xxCreateWindow(WindowPtr pWin)
-{
-    xxScrPriv(pWin->drawable.pScreen);
-    
-    if (pWin->drawable.class != InputOutput
-	|| pScrPriv->myDepth != pWin->drawable.depth) {
-	Bool ret;
-	DBG("CreateWindow NoPseudo\n");
-	unwrap (pScrPriv, pWin->drawable.pScreen, CreateWindow);
-	ret = pWin->drawable.pScreen->CreateWindow(pWin);
-	wrap(pScrPriv, pWin->drawable.pScreen, CreateWindow, xxCreateWindow);
-
-	return ret;
-    }
-    
-    DBG("CreateWindow\n");
-
-    dixSetPrivate(&pWin->devPrivates, fbGetWinPrivateKey(), pScrPriv->pPixmap);
-    PRINT_RECTS(pScrPriv->region);
-	if (!pWin->parent) {
-	REGION_EMPTY (pWin->drawable.pScreen, &pScrPriv->region);
-    }
-    PRINT_RECTS(pScrPriv->region);
-    
-    return TRUE;
-}
-
-static void
-xxWalkChildren(WindowPtr pWin, RegionPtr pReg, PixmapPtr pPixmap)
-{
-    
-    WindowPtr		pCurWin = pWin;
-    
-    do {
-	if (fbGetWindowPixmap(pCurWin) == pPixmap) {
-	    DBG("WalkWindow Add\n");
-	    REGION_UNION(pWin->drawable.pScreen,pReg,pReg,
-			 &pCurWin->borderClip);
-	} else {
-	    DBG("WalkWindow Sub\n");
-	    REGION_SUBTRACT(pWin->drawable.pScreen,pReg,pReg,
-			    &pCurWin->borderClip);
-	}
-	if (pCurWin->lastChild)
-	    xxWalkChildren(pCurWin->lastChild,pReg, pPixmap);
-    } while ((pCurWin = pCurWin->prevSib));
-}
-
-static void
-xxPickMyWindows(WindowPtr pWin, RegionPtr pRgn)
-{
-    ScreenPtr		pScreen = pWin->drawable.pScreen;
-    xxScrPriv(pScreen);
-
-    if (fbGetWindowPixmap(pWin) == pScrPriv->pPixmap) {
-	REGION_UNION(pWin->drawable.pScreen,pRgn,pRgn,&pWin->borderClip);
-    }
-    if (pWin->lastChild)
-	xxWalkChildren(pWin->lastChild,pRgn,pScrPriv->pPixmap);
-}
-
-static void
-xxCopyWindow(WindowPtr	pWin,
-	     DDXPointRec	ptOldOrg,
-	     RegionPtr	prgnSrc)
-{
-    ScreenPtr		pScreen = pWin->drawable.pScreen;
-    xxScrPriv(pScreen);
-    RegionRec		rgn;
-    RegionRec		rgn_new;
-    int			dx, dy;
-    PixmapPtr pPixmap = fbGetWindowPixmap(pWin);
-
-    DBG("xxCopyWindow\n");
-
-    dx = ptOldOrg.x - pWin->drawable.x;
-    dy = ptOldOrg.y - pWin->drawable.y;
-
-    REGION_NULL(pScreen, &rgn_new);
-    REGION_UNION(pScreen, &rgn_new,&rgn_new,prgnSrc);
-    REGION_TRANSLATE(pScreen,&rgn_new,-dx,-dy);
-
-    REGION_NULL(pScreen, &rgn);
-    xxPickMyWindows(pWin,&rgn);
-
-    unwrap (pScrPriv, pScreen, CopyWindow);
-    dixSetPrivate(&pWin->devPrivates, fbGetWinPrivateKey(),
-		  fbGetScreenPixmap(pScreen));
-    pScreen->CopyWindow(pWin, ptOldOrg, prgnSrc);
-    dixSetPrivate(&pWin->devPrivates, fbGetWinPrivateKey(), pPixmap);
-    wrap(pScrPriv, pScreen, CopyWindow, xxCopyWindow);
-
-    REGION_INTERSECT(pScreen,&rgn,&rgn,&rgn_new);
-    if (REGION_NOTEMPTY (pScreen,&rgn)) {
-	fbCopyRegion(&pScrPriv->pPixmap->drawable,&pScrPriv->pPixmap->drawable,
-		     0,&rgn,dx,dy,fbCopyWindowProc,0,(void*)0);
-	REGION_TRANSLATE(pScreen,&rgn,dx,dy);
-	REGION_INTERSECT(pScreen,&rgn_new,&pScrPriv->region,&rgn);
-	REGION_SUBTRACT(pScreen,&pScrPriv->region,&pScrPriv->region,&rgn);
-	REGION_TRANSLATE(pScreen,&rgn_new,-dx,-dy);
-	REGION_UNION(pScreen,&pScrPriv->region,&pScrPriv->region,&rgn_new);
-    }
-#if 1
-    REGION_UNINIT(pScreen,&rgn_new);
-    REGION_UNINIT(pScreen,&rgn);
-#endif
-}
-
-static void
-xxWindowExposures (WindowPtr	pWin,
-			  RegionPtr	prgn,
-			  RegionPtr	other_exposed)
-{
-    xxScrPriv(pWin->drawable.pScreen);
-
-    if (fbGetWindowPixmap(pWin) == pScrPriv->pPixmap) {
-	DBG("WindowExposures\n");
-	PRINT_RECTS(pScrPriv->region);
-	REGION_UNION(pWin->drawable.pScreen,&pScrPriv->region,
-		     &pScrPriv->region,
-		     prgn);
-	PRINT_RECTS(pScrPriv->region);
-    } else {
-	DBG("WindowExposures NonPseudo\n");
-	PRINT_RECTS(pScrPriv->region);
-	REGION_SUBTRACT(pWin->drawable.pScreen,&pScrPriv->region,
-		     &pScrPriv->region,
-		     prgn);
-	PRINT_RECTS(pScrPriv->region);
-    }
-    unwrap (pScrPriv, pWin->drawable.pScreen, WindowExposures);
-    pWin->drawable.pScreen->WindowExposures(pWin, prgn, other_exposed);
-    wrap(pScrPriv, pWin->drawable.pScreen, WindowExposures, xxWindowExposures);
-}
-
-static void
-xxCopyPseudocolorRegion(ScreenPtr pScreen, RegionPtr pReg,
-			xxCmapPrivPtr pCmapPriv)
-{
-    xxScrPriv(pScreen);
-    CARD32		mask = (1 << pScrPriv->myDepth) - 1;
-    int			num = REGION_NUM_RECTS(pReg);
-    BoxPtr		pbox = REGION_RECTS(pReg);
-    int			width, height;
-    CARD8		*src;
-    CARD16		*dst, *dst_base;
-    int			dst_stride;
-    register CARD32	*cmap = pCmapPriv->cmap;
-    register CARD8      *s;
-    register CARD16     *d;
-    int w;
-
-    fbPrepareAccess((DrawablePtr)pScreen->devPrivate);
-
-    dst_base = (CARD16*) ((PixmapPtr)pScreen->devPrivate)->devPrivate.ptr;
-    dst_stride = (int)((PixmapPtr)pScreen->devPrivate)->devKind
-	/ sizeof (CARD16);
-
-    while (num--) {
-	height = pbox->y2 - pbox->y1;
-	width = pbox->x2 - pbox->x1;
-	
-	src = (unsigned char *) pScrPriv->pBits
-	    + (pbox->y1 * pScreen->width) + pbox->x1;
-	dst = dst_base + (pbox->y1 * dst_stride) + pbox->x1;
-	while (height--) {
-	    w = width;
-	    s = src;
-	    d = dst;
-
-	    while(w--) {
-		*(d++) = (CARD16)*(cmap + ((*(s++)) & mask));
-	    }
-	    src += pScreen->width;
-	    dst += dst_stride;
-	}
-	pbox++;
-    }
-
-    fbFinishAccess(&((PixmapPtr)pScreen->devPrivate)->drawable);
-}
-
-static void
-xxUpdateCmapPseudocolorRegion(ScreenPtr pScreen, RegionPtr pReg,
-			xxCmapPrivPtr pCmapPriv)
-{
-    xxScrPriv(pScreen);
-    CARD32		mask = (1 << pScrPriv->myDepth) - 1;
-    int			num = REGION_NUM_RECTS(pReg);
-    BoxPtr		pbox = REGION_RECTS(pReg);
-    int			width, height;
-    CARD8		*src;
-    CARD16		*dst, *dst_base;
-    int			dst_stride;
-    register CARD32	val;
-    register CARD32	*cmap = pCmapPriv->cmap;
-    register CARD8      *s;
-    register CARD16     *d;
-    int w;
-
-    dst_base = (CARD16*) ((PixmapPtr)pScreen->devPrivate)->devPrivate.ptr;
-    dst_stride = (int)((PixmapPtr)pScreen->devPrivate)->devKind
-	/ sizeof (CARD16);
-
-    while (num--) {
-
-	height = pbox->y2 - pbox->y1;
-	width = pbox->x2 - pbox->x1;
-	
-	src = (unsigned char *) pScrPriv->pBits
-	    + (pbox->y1 * pScreen->width) + pbox->x1;
-	dst = dst_base + (pbox->y1 * dst_stride) + pbox->x1;
-	while (height--) {
-	    w = width;
-	    s = src;
-	    d = dst;
-	    while(w--) {
-		val = *(cmap + ((*(s++)) & mask));
-      		if (val & MARK_DIRTY) {
-		    *d = (CARD16) val;
-		}
-		d++;
-	    }
-	    src += pScreen->width;
-	    dst += dst_stride;
-	}
-	pbox++;
-    }
-}
-
-static void
-xxGetWindowRegion(WindowPtr pWin,RegionPtr winreg)
-{
-    REGION_NULL(pWin->drawable.pScreen,winreg);
-    /* get visible part of the border ...Argh */
-    REGION_SUBTRACT(pWin->drawable.pScreen,winreg,&pWin->borderSize,
-		    &pWin->winSize);
-    REGION_INTERSECT(pWin->drawable.pScreen,winreg,winreg,
-		     &pWin->borderClip);
-    /* add window interior excluding children */
-    REGION_UNION(pWin->drawable.pScreen,winreg,winreg,
-		 &pWin->clipList);
-}
-
-static int
-xxUpdateRegion(WindowPtr pWin, pointer unused)
-{
-    ScreenPtr pScreen = pWin->drawable.pScreen;
-    xxScrPriv(pScreen);
-    ColormapPtr pmap = (pointer) -1;
-    RegionRec		winreg, rgni;
-    
-    if (pScrPriv->myDepth == pWin->drawable.depth) {
-	xxCmapPrivPtr pCmapPriv = (pointer)-1;
-	xxGetWindowRegion(pWin,&winreg);
-
-	if (pScrPriv->colormapDirty) {
-
-	    pmap = (ColormapPtr)LookupIDByType(wColormap(pWin),RT_COLORMAP);
-	    if (!pmap)
-		goto CONTINUE; /* return ? */
-
-	    pCmapPriv = xxGetCmapPriv(pmap);
-	    if (pCmapPriv == (pointer) -1)
-		return WT_WALKCHILDREN;
-	    if (!pCmapPriv->dirty)
-		goto CONTINUE;
-
-	    REGION_NULL (pScreen, &rgni);
-	    /* This will be taken care of when damaged regions are updated */
-	    REGION_SUBTRACT(pScreen, &rgni, &winreg, &pScrPriv->region);
-	    if (REGION_NOTEMPTY (pScreen,&rgni))
-		xxUpdateCmapPseudocolorRegion(pScreen,&rgni, pCmapPriv);
-	}
-    CONTINUE:
-
-	REGION_NULL (pScreen, &rgni);
-	REGION_INTERSECT (pScreen, &rgni, &winreg, &pScrPriv->region);
-	
-	if (REGION_NOTEMPTY (pScreen,&rgni)) {
-	    if (pmap == (pointer) -1) {
-		pmap =
-		    (ColormapPtr)LookupIDByType(wColormap(pWin),RT_COLORMAP);
-		if (!pmap) /* return ? */
-		    pmap = (ColormapPtr)LookupIDByType(pScreen->defColormap,
-						       RT_COLORMAP);
-		pCmapPriv = xxGetCmapPriv(pmap);
-	    }
-	    
-	    if (pCmapPriv != (pointer)-1)
-		xxCopyPseudocolorRegion(pScreen,&rgni, pCmapPriv);
-	    REGION_SUBTRACT(pScreen, &pScrPriv->region, &pScrPriv->region,
-			    &rgni);
-	}
-#if 1
-	REGION_UNINIT(pScreen,&rgni);
-	REGION_UNINIT(pScreen,&winreg);
-#endif
-    }
-    return WT_WALKCHILDREN;
-}
-
-
-static void
-xxUpdateFb(ScreenPtr pScreen)
-{
-    xxScrPriv(pScreen);
-
-    DBG("Update FB\n");
-    PRINT_RECTS(pScrPriv->region);
-
-    if (pScrPriv->sync)
-	pScrPriv->sync(pScreen); /*@!@*/
-    
-    WalkTree(pScreen,xxUpdateRegion,NULL);
-#if 0
-    if (REGION_NOTEMPTY (pScreen,&pScrPriv->region)) {
-	ColormapPtr pmap = (pointer) -1;
-	xxCmapPrivPtr pCmapPriv;
-	
-	pmap = (ColormapPtr)LookupIDByType(pScreen->defColormap,
-					   RT_COLORMAP);
-	pCmapPriv = xxGetCmapPriv(pmap);
-	if (pCmapPriv != (pointer)-1)
-	    xxCopyPseudocolorRegion(pScreen,&pScrPriv->region, pCmapPriv);
-	REGION_SUBTRACT(pScreen, &pScrPriv->region, &pScrPriv->region,
-			&pScrPriv->region);
-    }
-#endif
-    if (pScrPriv->colormapDirty) {
-	xxCmapPrivPtr pCmap = pScrPriv->Cmaps;
-
-	while (pCmap) {
-	    int j;
-
-	    if (pCmap->dirty) {
-		for (j = 0; j < (1 <<  pScrPriv->myDepth); j++) 
-		    pCmap->cmap[j] &= ~MARK_DIRTY;
-		pCmap->dirty = FALSE;
-	    }
-	    pCmap = pCmap->next;
-	}
-	pScrPriv->colormapDirty = FALSE;
-    }
-}
-
-static void
-xxBlockHandler (pointer	data,
-		OSTimePtr pTimeout,
-		pointer pRead)
-{
-    ScreenPtr	pScreen = (ScreenPtr) data;
-    xxScrPriv(pScreen);
-
-    if (REGION_NOTEMPTY (pScreen,&pScrPriv->region) || pScrPriv->colormapDirty)
-	xxUpdateFb (pScreen);
-}
-
-static void
-xxWakeupHandler (pointer data, int i, pointer LastSelectMask)
-{
-}
-
-Bool
-xxSetup(ScreenPtr pScreen, int myDepth, int baseDepth, char* addr, xxSyncFunc sync)
-{
-    xxScrPrivPtr	pScrPriv;
-    DepthPtr		pDepths;
-    ColormapPtr		pDefMap;
-    int i,j,k;
-    
-#ifdef RENDER
-    PictureScreenPtr	ps = GetPictureScreenIfSet(pScreen);
-#endif
-
-    if (!dixRequestPrivate(xxGCPrivateKey, sizeof (xxGCPrivRec)))
-	return FALSE;
-
-    pScrPriv = (xxScrPrivPtr) xalloc (sizeof (xxScrPrivRec));
-    if (!pScrPriv)
-	return FALSE;
-    
-    if (baseDepth)
-	pScrPriv->depth = baseDepth;
-    else {
-	pDepths = pScreen->allowedDepths;
-        for (i = 0; i < pScreen->numDepths; i++, pDepths++)
-	    if (pDepths->depth != myDepth)
-		pScrPriv->depth = pDepths->depth;
-    }
-    if (!pScrPriv->depth)
-	return FALSE;
-    
-    pDepths = pScreen->allowedDepths;
-    for (i = 0; i < pScreen->numDepths; i++, pDepths++)
-	if (pDepths->depth == pScrPriv->depth) {
-	    for (j = 0; i < pDepths->numVids; j++) {
-		for (k = 0; k < pScreen->numVisuals; k++) {
-		    if (pScreen->visuals[k].vid
-			== pDepths[i].vids[j]
-			&& pScreen->visuals[k].class == TrueColor) {
-			pScrPriv->bVisual =  &pScreen->visuals[k];
-			goto DONE;
-		    }
-		}
-	    }
-	}
-    
- DONE:
-    if (!pScrPriv->bVisual)
-	return FALSE;
-
-    pScrPriv->myDepth = myDepth;
-    pScrPriv->numInstalledColormaps = 0;
-    pScrPriv->colormapDirty = FALSE;
-    pScrPriv->Cmaps = NULL;
-    pScrPriv->sync = sync;
-    
-    pScreen->maxInstalledCmaps += MAX_NUM_XX_INSTALLED_CMAPS;
-    pScrPriv->InstalledCmaps = xcalloc(MAX_NUM_XX_INSTALLED_CMAPS,
-				       sizeof(ColormapPtr));
-    if (!pScrPriv->InstalledCmaps)
-	return FALSE;
-
-    
-    if (!RegisterBlockAndWakeupHandlers (xxBlockHandler,
-					 xxWakeupHandler,
-					 (pointer) pScreen))
-	return FALSE;
-
-    wrap (pScrPriv, pScreen, CloseScreen, xxCloseScreen);
-    wrap (pScrPriv, pScreen, CreateScreenResources, xxCreateScreenResources);
-    wrap (pScrPriv, pScreen, CreateWindow, xxCreateWindow);
-    wrap (pScrPriv, pScreen, CopyWindow, xxCopyWindow);
-#if 0 /* can we leave this out even with backing store enabled ? */
-    wrap (pScrPriv, pScreen, WindowExposures, xxWindowExposures);
-#endif
-    wrap (pScrPriv, pScreen, CreateGC, xxCreateGC);
-    wrap (pScrPriv, pScreen, CreateColormap, xxCreateColormap);
-    wrap (pScrPriv, pScreen, DestroyColormap, xxDestroyColormap);
-    wrap (pScrPriv, pScreen, InstallColormap, xxInstallColormap);
-    wrap (pScrPriv, pScreen, UninstallColormap, xxUninstallColormap);
-    wrap (pScrPriv, pScreen, ListInstalledColormaps, xxListInstalledColormaps);
-    wrap (pScrPriv, pScreen, StoreColors, xxStoreColors);
-#ifdef RENDER
-    if (ps) {
-	wrap (pScrPriv, ps, Glyphs, xxGlyphs);
-	wrap (pScrPriv, ps, Composite, xxComposite);
-    }
-#endif
-    pScrPriv->addr = addr;
-    dixSetPrivate(&pScreen->devPrivates, xxScrPrivateKey, pScrPriv);
-
-    pDefMap = (ColormapPtr) LookupIDByType(pScreen->defColormap, RT_COLORMAP);
-    if (!xxInitColormapPrivate(pDefMap))
-	return FALSE;
-    
-    return TRUE;
-}
-
-GCFuncs xxGCFuncs = {
-    xxValidateGC, xxChangeGC, xxCopyGC, xxDestroyGC,
-    xxChangeClip, xxDestroyClip, xxCopyClip
-};
-
-static GCOps xxGCOps = {
-    xxFillSpans, xxSetSpans, 
-    xxPutImage, xxCopyArea, 
-    xxCopyPlane, xxPolyPoint, 
-    xxPolylines, xxPolySegment, 
-    xxPolyRectangle, xxPolyArc, 
-    xxFillPolygon, xxPolyFillRect, 
-    xxPolyFillArc, xxPolyText8, 
-    xxPolyText16, xxImageText8, 
-    xxImageText16, xxImageGlyphBlt, 
-    xxPolyGlyphBlt, xxPushPixels,
-    {NULL}		/* devPrivate */
-};
-
-#define IS_VISIBLE(pDraw) (pDraw->type == DRAWABLE_WINDOW \
-	   && (fbGetWindowPixmap((WindowPtr) pDraw) == pScrPriv->pPixmap))
-
-#define TRANSLATE_BOX(box, pDraw) { \
-    box.x1 += pDraw->x; \
-    box.x2 += pDraw->x; \
-    box.y1 += pDraw->y; \
-    box.y2 += pDraw->y; \
-    }
-
-#define TRIM_BOX(box, pGC) { \
-    BoxPtr extents = &pGC->pCompositeClip->extents;\
-    if(box.x1 < extents->x1) box.x1 = extents->x1; \
-    if(box.x2 > extents->x2) box.x2 = extents->x2; \
-    if(box.y1 < extents->y1) box.y1 = extents->y1; \
-    if(box.y2 > extents->y2) box.y2 = extents->y2; \
-    }
-
-#define BOX_NOT_EMPTY(box) \
-    (((box.x2 - box.x1) > 0) && ((box.y2 - box.y1) > 0))
-
-
-#define _ADD_BOX(box,pGC) {\
-    if (BOX_NOT_EMPTY(box)) { \
-       RegionRec region; \
-       ScreenPtr pScreen = pGC->pScreen;\
-       REGION_INIT (pScreen, &region, &box, 1); \
-       REGION_INTERSECT(pScreen,&region,&region,\
-                                 (pGC)->pCompositeClip);\
-       if (REGION_NOTEMPTY(pScreen,&region)) { \
-           xxScrPriv(pScreen);\
-	   PRINT_RECTS(pScrPriv->region);\
-           REGION_UNION(pScreen,&pScrPriv->region,&pScrPriv->region,&region);\
-	   PRINT_RECTS(pScrPriv->region);\
-           REGION_UNINIT(pScreen,&region);\
-       }\
-   }\
-}
-
-#define TRANSLATE_AND_ADD_BOX(box,pGC) {\
-         TRANSLATE_BOX(box,pDraw); \
-         TRIM_BOX(box,pGC); \
-         _ADD_BOX(box,pGC); \
-}
-
-#define ADD_BOX(box,pGC) { \
-        TRIM_BOX(box,pGC); \
-        _ADD_BOX(box,pGC); \
-}
-
-#define XX_GC_FUNC_PROLOGUE(pGC) \
-    xxGCPriv(pGC); \
-    unwrap(pGCPriv, pGC, funcs); \
-    if (pGCPriv->ops) unwrap(pGCPriv, pGC, ops)
-
-#define XX_GC_FUNC_EPILOGUE(pGC) \
-    wrap(pGCPriv, pGC, funcs, &xxGCFuncs);  \
-    if (pGCPriv->ops) wrap(pGCPriv, pGC, ops, &xxGCOps)
-
-static Bool
-xxCreateGC(GCPtr pGC)
-{
-    ScreenPtr		pScreen = pGC->pScreen;
-    xxScrPriv(pScreen);
-    xxGCPriv(pGC);
-    Bool ret;
-
-    unwrap (pScrPriv, pScreen, CreateGC);
-    if((ret = (*pScreen->CreateGC) (pGC))) {
-	pGCPriv->ops = NULL;
-	pGCPriv->funcs = pGC->funcs;
-	pGC->funcs = &xxGCFuncs;
-    }
-    wrap (pScrPriv, pScreen, CreateGC, xxCreateGC);
-
-    return ret;
-}
-
-static void
-xxValidateGC(
-   GCPtr         pGC,
-   unsigned long changes,
-   DrawablePtr   pDraw 
-){
-    XX_GC_FUNC_PROLOGUE (pGC);
-    (*pGC->funcs->ValidateGC)(pGC, changes, pDraw);
-    if(pDraw->type == DRAWABLE_WINDOW)
-	pGCPriv->ops = pGC->ops;  /* just so it's not NULL */
-    else 
-	pGCPriv->ops = NULL;
-    XX_GC_FUNC_EPILOGUE (pGC);
-}
-
-static void
-xxDestroyGC(GCPtr pGC)
-{
-    XX_GC_FUNC_PROLOGUE (pGC);
-    (*pGC->funcs->DestroyGC)(pGC);
-    XX_GC_FUNC_EPILOGUE (pGC);
-}
-
-static void
-xxChangeGC (
-    GCPtr	    pGC,
-    unsigned long   mask
-){
-    XX_GC_FUNC_PROLOGUE (pGC);
-    (*pGC->funcs->ChangeGC) (pGC, mask);
-    XX_GC_FUNC_EPILOGUE (pGC);
-}
-
-static void
-xxCopyGC (
-    GCPtr	    pGCSrc, 
-    unsigned long   mask,
-    GCPtr	    pGCDst
-){
-    XX_GC_FUNC_PROLOGUE (pGCDst);
-    (*pGCDst->funcs->CopyGC) (pGCSrc, mask, pGCDst);
-    XX_GC_FUNC_EPILOGUE (pGCDst);
-}
-
-static void
-xxChangeClip (
-    GCPtr   pGC,
-    int		type,
-    pointer	pvalue,
-    int		nrects 
-){
-    XX_GC_FUNC_PROLOGUE (pGC);
-    (*pGC->funcs->ChangeClip) (pGC, type, pvalue, nrects);
-    XX_GC_FUNC_EPILOGUE (pGC);
-}
-
-static void
-xxCopyClip(GCPtr pgcDst, GCPtr pgcSrc)
-{
-    XX_GC_FUNC_PROLOGUE (pgcDst);
-    (* pgcDst->funcs->CopyClip)(pgcDst, pgcSrc);
-    XX_GC_FUNC_EPILOGUE (pgcDst);
-}
-
-static void
-xxDestroyClip(GCPtr pGC)
-{
-    XX_GC_FUNC_PROLOGUE (pGC);
-    (* pGC->funcs->DestroyClip)(pGC);
-    XX_GC_FUNC_EPILOGUE (pGC);
-}
-
-#define XX_GC_OP_PROLOGUE(pGC,pDraw) \
-    xxScrPriv(pDraw->pScreen); \
-    xxGCPriv(pGC);  \
-    GCFuncs *oldFuncs = pGC->funcs; \
-    unwrap(pGCPriv, pGC, funcs);  \
-    unwrap(pGCPriv, pGC, ops); \
-	
-#define XX_GC_OP_EPILOGUE(pGC,pDraw) \
-    wrap(pGCPriv, pGC, funcs, oldFuncs); \
-    wrap(pGCPriv, pGC, ops, &xxGCOps)
-
-static void
-xxFillSpans(
-    DrawablePtr pDraw,
-    GC		*pGC,
-    int		nInit,	
-    DDXPointPtr pptInit,	
-    int 	*pwidthInit,		
-    int 	fSorted 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);    
-
-    if(IS_VISIBLE(pDraw) && nInit) {
-	DDXPointPtr ppt = pptInit;
-	int *pwidth = pwidthInit;
-	int i = nInit;
-	BoxRec box;
-
-	DBG("FillSpans\n");
-	box.x1 = ppt->x;
-	box.x2 = box.x1 + *pwidth;
-	box.y2 = box.y1 = ppt->y;
-
-	while(--i) {
-	   ppt++;
-	   pwidthInit++;
-	   if(box.x1 > ppt->x) box.x1 = ppt->x;
-	   if(box.x2 < (ppt->x + *pwidth)) 
-		box.x2 = ppt->x + *pwidth;
-	   if(box.y1 > ppt->y) box.y1 = ppt->y;
-	   else if(box.y2 < ppt->y) box.y2 = ppt->y;
-	}
-
-	box.y2++;
-
-	(*pGC->ops->FillSpans)(pDraw, pGC, nInit, pptInit, pwidthInit, fSorted);
-
-	
-	TRANSLATE_AND_ADD_BOX(box, pGC);
-    } else
-	(*pGC->ops->FillSpans)(pDraw, pGC, nInit, pptInit, pwidthInit, fSorted);
-
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-}
-
-static void
-xxSetSpans(
-    DrawablePtr		pDraw,
-    GCPtr		pGC,
-    char		*pcharsrc,
-    DDXPointPtr 	pptInit,
-    int			*pwidthInit,
-    int			nspans,
-    int			fSorted 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw) && nspans) {
-	DDXPointPtr ppt = pptInit;
-	int *pwidth = pwidthInit;
-	int i = nspans;
-	BoxRec box;
-
-	DBG("SetSpans\n");
-	box.x1 = ppt->x;
-	box.x2 = box.x1 + *pwidth;
-	box.y2 = box.y1 = ppt->y;
-
-	while(--i) {
-	   ppt++;
-	   pwidth++;
-	   if(box.x1 > ppt->x) box.x1 = ppt->x;
-	   if(box.x2 < (ppt->x + *pwidth)) 
-		box.x2 = ppt->x + *pwidth;
-	   if(box.y1 > ppt->y) box.y1 = ppt->y;
-	   else if(box.y2 < ppt->y) box.y2 = ppt->y;
-	}
-
-	box.y2++;
-
-	(*pGC->ops->SetSpans)(pDraw, pGC, pcharsrc, pptInit, 
-				pwidthInit, nspans, fSorted);
-
-	TRANSLATE_AND_ADD_BOX(box, pGC);
-    } else
-	(*pGC->ops->SetSpans)(pDraw, pGC, pcharsrc, pptInit, 
-				pwidthInit, nspans, fSorted);
-
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-}
-
-static void
-xxPutImage(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		depth, 
-    int x, int y, int w, int h,
-    int		leftPad,
-    int		format,
-    char 	*pImage 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    (*pGC->ops->PutImage)(pDraw, pGC, depth, x, y, w, h, 
-		leftPad, format, pImage);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-    if(IS_VISIBLE(pDraw)) {
-	BoxRec box;
-
-	DBG("PutImage\n");
-	box.x1 = x + pDraw->x;
-	box.x2 = box.x1 + w;
-	box.y1 = y + pDraw->y;
-	box.y2 = box.y1 + h;
-
-	ADD_BOX(box, pGC);
-    }
-}
-
-static RegionPtr
-xxCopyArea(
-    DrawablePtr pSrc,
-    DrawablePtr pDst,
-    GC *pGC,
-    int srcx, int srcy,
-    int width, int height,
-    int dstx, int dsty 
-){
-    RegionPtr ret;
-    XX_GC_OP_PROLOGUE(pGC, pDst);
-    DBG("xxCopyArea\n");
-    ret = (*pGC->ops->CopyArea)(pSrc, pDst,
-            pGC, srcx, srcy, width, height, dstx, dsty);
-    XX_GC_OP_EPILOGUE(pGC, pDst);
-
-    if(IS_VISIBLE(pDst)) {
-	BoxRec box;
-
-	DBG("CopyArea\n");
-	box.x1 = dstx + pDst->x;
-	box.x2 = box.x1 + width;
-	box.y1 = dsty + pDst->y;
-	box.y2 = box.y1 + height;
-
-	ADD_BOX(box, pGC);
-    }
-
-    return ret;
-}
-
-static RegionPtr
-xxCopyPlane(
-    DrawablePtr	pSrc,
-    DrawablePtr	pDst,
-    GCPtr pGC,
-    int	srcx, int srcy,
-    int	width, int height,
-    int	dstx, int dsty,
-    unsigned long bitPlane 
-){
-    RegionPtr ret;
-    XX_GC_OP_PROLOGUE(pGC, pDst);
-    ret = (*pGC->ops->CopyPlane)(pSrc, pDst,
-	       pGC, srcx, srcy, width, height, dstx, dsty, bitPlane);
-    XX_GC_OP_EPILOGUE(pGC, pDst);
-
-    if(IS_VISIBLE(pDst)) {
-	BoxRec box;
-
-	DBG("CopyPlane\n");
-	box.x1 = dstx + pDst->x;
-	box.x2 = box.x1 + width;
-	box.y1 = dsty + pDst->y;
-	box.y2 = box.y1 + height;
-
-	ADD_BOX(box, pGC);
-    }
-
-    return ret;
-}
-
-static void
-xxPolyPoint(
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    int mode,
-    int npt,
-    xPoint *pptInit 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    (*pGC->ops->PolyPoint)(pDraw, pGC, mode, npt, pptInit);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw) && npt) {
-	BoxRec box;
-
-	DBG("PolyPoint\n");
-	box.x2 = box.x1 = pptInit->x;
-	box.y2 = box.y1 = pptInit->y;
-
-	/* this could be slow if the points were spread out */
-
-	while(--npt) {
-	   pptInit++;
-	   if(box.x1 > pptInit->x) box.x1 = pptInit->x;
-	   else if(box.x2 < pptInit->x) box.x2 = pptInit->x;
-	   if(box.y1 > pptInit->y) box.y1 = pptInit->y;
-	   else if(box.y2 < pptInit->y) box.y2 = pptInit->y;
-	}
-
-	box.x2++;
-	box.y2++;
-
-	TRANSLATE_AND_ADD_BOX(box, pGC);
-    }
-}
-
-static void
-xxPolylines(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		mode,		
-    int		npt,		
-    DDXPointPtr pptInit 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    (*pGC->ops->Polylines)(pDraw, pGC, mode, npt, pptInit);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-
-    if(IS_VISIBLE(pDraw) && npt) {
-	BoxRec box;
-	int extra = pGC->lineWidth >> 1;
-
-	DBG("PolyLine\n");
-	box.x2 = box.x1 = pptInit->x;
-	box.y2 = box.y1 = pptInit->y;
-
-	if(npt > 1) {
-	   if(pGC->joinStyle == JoinMiter)
-		extra = 6 * pGC->lineWidth;
-	   else if(pGC->capStyle == CapProjecting)
-		extra = pGC->lineWidth;
-        }
-
-	if(mode == CoordModePrevious) {
-	   int x = box.x1;
-	   int y = box.y1;
-	   while(--npt) {
-		pptInit++;
-		x += pptInit->x;
-		y += pptInit->y;
-		if(box.x1 > x) box.x1 = x;
-		else if(box.x2 < x) box.x2 = x;
-		if(box.y1 > y) box.y1 = y;
-		else if(box.y2 < y) box.y2 = y;
-	    }
-	} else {
-	   while(--npt) {
-		pptInit++;
-		if(box.x1 > pptInit->x) box.x1 = pptInit->x;
-		else if(box.x2 < pptInit->x) box.x2 = pptInit->x;
-		if(box.y1 > pptInit->y) box.y1 = pptInit->y;
-		else if(box.y2 < pptInit->y) box.y2 = pptInit->y;
-	    }
-	}
-
-	box.x2++;
-	box.y2++;
-
-	if(extra) {
-	   box.x1 -= extra;
-	   box.x2 += extra;
-	   box.y1 -= extra;
-	   box.y2 += extra;
-        }
-
-	TRANSLATE_AND_ADD_BOX(box, pGC);
-    }
-}
-
-static void 
-xxPolySegment(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		nseg,
-    xSegment	*pSeg
-    ){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    (*pGC->ops->PolySegment)(pDraw, pGC, nseg, pSeg);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw) && nseg) {
-	BoxRec box;
-	int extra = pGC->lineWidth;
-
-	DBG("PolySegment\n");
-        if(pGC->capStyle != CapProjecting)	
-	   extra >>= 1;
-
-	if(pSeg->x2 > pSeg->x1) {
-	    box.x1 = pSeg->x1;
-	    box.x2 = pSeg->x2;
-	} else {
-	    box.x2 = pSeg->x1;
-	    box.x1 = pSeg->x2;
-	}
-
-	if(pSeg->y2 > pSeg->y1) {
-	    box.y1 = pSeg->y1;
-	    box.y2 = pSeg->y2;
-	} else {
-	    box.y2 = pSeg->y1;
-	    box.y1 = pSeg->y2;
-	}
-
-	while(--nseg) {
-	    pSeg++;
-	    if(pSeg->x2 > pSeg->x1) {
-		if(pSeg->x1 < box.x1) box.x1 = pSeg->x1;
-		if(pSeg->x2 > box.x2) box.x2 = pSeg->x2;
-	    } else {
-		if(pSeg->x2 < box.x1) box.x1 = pSeg->x2;
-		if(pSeg->x1 > box.x2) box.x2 = pSeg->x1;
-	    }
-	    if(pSeg->y2 > pSeg->y1) {
-		if(pSeg->y1 < box.y1) box.y1 = pSeg->y1;
-		if(pSeg->y2 > box.y2) box.y2 = pSeg->y2;
-	    } else {
-		if(pSeg->y2 < box.y1) box.y1 = pSeg->y2;
-		if(pSeg->y1 > box.y2) box.y2 = pSeg->y1;
-	    }
-	}
-
-	box.x2++;
-	box.y2++;
-
-	if(extra) {
-	   box.x1 -= extra;
-	   box.x2 += extra;
-	   box.y1 -= extra;
-	   box.y2 += extra;
-        }
-	
-	TRANSLATE_AND_ADD_BOX(box, pGC);
-    }
-}
-
-static void
-xxPolyRectangle(
-    DrawablePtr  pDraw,
-    GCPtr        pGC,
-    int	         nRects,
-    xRectangle  *pRects 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    (*pGC->ops->PolyRectangle)(pDraw, pGC, nRects, pRects);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw) && nRects) 
-    {
-	BoxRec box;
-	int offset1, offset2, offset3;
-
-	DBG("PolyRectangle\n");
-	offset2 = pGC->lineWidth;
-	if(!offset2) offset2 = 1;
-	offset1 = offset2 >> 1;
-	offset3 = offset2 - offset1;
-
-	while(nRects--) 
-	{
-	    box.x1 = pRects->x - offset1;
-	    box.y1 = pRects->y - offset1;
-	    box.x2 = box.x1 + pRects->width + offset2;
-	    box.y2 = box.y1 + offset2;		
-	    TRANSLATE_AND_ADD_BOX(box, pGC);
-	    box.x1 = pRects->x - offset1;
-	    box.y1 = pRects->y + offset3;
-	    box.x2 = box.x1 + offset2;
-	    box.y2 = box.y1 + pRects->height - offset2;		
-	    TRANSLATE_AND_ADD_BOX(box, pGC);
-	    box.x1 = pRects->x + pRects->width - offset1;
-	    box.y1 = pRects->y + offset3;
-	    box.x2 = box.x1 + offset2;
-	    box.y2 = box.y1 + pRects->height - offset2;		
-	    TRANSLATE_AND_ADD_BOX(box, pGC);
-	    box.x1 = pRects->x - offset1;
-	    box.y1 = pRects->y + pRects->height - offset1;
-	    box.x2 = box.x1 + pRects->width + offset2;
-	    box.y2 = box.y1 + offset2;		
-	    TRANSLATE_AND_ADD_BOX(box, pGC);
-
-	    pRects++;
-	}
-    }
-}
-
-static void
-xxPolyArc(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		narcs,
-    xArc	*parcs 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    (*pGC->ops->PolyArc)(pDraw, pGC, narcs, parcs);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw) && narcs) {
-	int extra = pGC->lineWidth >> 1;
-	BoxRec box;
-
-	DBG("PolyArc\n");
-	box.x1 = parcs->x;
-	box.x2 = box.x1 + parcs->width;
-	box.y1 = parcs->y;
-	box.y2 = box.y1 + parcs->height;
-
-	/* should I break these up instead ? */
-
-	while(--narcs) {
-	   parcs++;
-	   if(box.x1 > parcs->x) box.x1 = parcs->x;
-	   if(box.x2 < (parcs->x + parcs->width))
-		box.x2 = parcs->x + parcs->width;
-	   if(box.y1 > parcs->y) box.y1 = parcs->y;
-	   if(box.y2 < (parcs->y + parcs->height))
-		box.y2 = parcs->y + parcs->height;
-        }
-
-	if(extra) {
-	   box.x1 -= extra;
-	   box.x2 += extra;
-	   box.y1 -= extra;
-	   box.y2 += extra;
-        }
-
-	box.x2++;
-	box.y2++;
-
-	TRANSLATE_AND_ADD_BOX(box, pGC);
-    }
-}
-
-static void
-xxFillPolygon(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		shape,
-    int		mode,
-    int		count,
-    DDXPointPtr	pptInit 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw) && (count > 2)) {
-	DDXPointPtr ppt = pptInit;
-	int i = count;
-	BoxRec box;
-
-	DBG("FillPolygon\n");
-	box.x2 = box.x1 = ppt->x;
-	box.y2 = box.y1 = ppt->y;
-
-	if(mode != CoordModeOrigin) {
-	   int x = box.x1;
-	   int y = box.y1;
-	   while(--i) {
-		ppt++;
-		x += ppt->x;
-		y += ppt->y;
-		if(box.x1 > x) box.x1 = x;
-		else if(box.x2 < x) box.x2 = x;
-		if(box.y1 > y) box.y1 = y;
-		else if(box.y2 < y) box.y2 = y;
-	    }
-	} else {
-	   while(--i) {
-		ppt++;
-		if(box.x1 > ppt->x) box.x1 = ppt->x;
-		else if(box.x2 < ppt->x) box.x2 = ppt->x;
-		if(box.y1 > ppt->y) box.y1 = ppt->y;
-		else if(box.y2 < ppt->y) box.y2 = ppt->y;
-	    }
-	}
-
-	box.x2++;
-	box.y2++;
-
-	(*pGC->ops->FillPolygon)(pDraw, pGC, shape, mode, count, pptInit);
-
-	TRANSLATE_AND_ADD_BOX(box, pGC);
-    } else
-	(*pGC->ops->FillPolygon)(pDraw, pGC, shape, mode, count, pptInit);
-
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-}
-
-static void 
-xxPolyFillRect(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		nRectsInit, 
-    xRectangle	*pRectsInit 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw) && nRectsInit) {
-	BoxRec box;
-	xRectangle *pRects = pRectsInit;
-	int nRects = nRectsInit;
-
-	DBG("PolyFillRect\n");
-	box.x1 = pRects->x;
-	box.x2 = box.x1 + pRects->width;
-	box.y1 = pRects->y;
-	box.y2 = box.y1 + pRects->height;
-
-	while(--nRects) {
-	    pRects++;
-	    if(box.x1 > pRects->x) box.x1 = pRects->x;
-	    if(box.x2 < (pRects->x + pRects->width))
-		box.x2 = pRects->x + pRects->width;
-	    if(box.y1 > pRects->y) box.y1 = pRects->y;
-	    if(box.y2 < (pRects->y + pRects->height))
-		box.y2 = pRects->y + pRects->height;
-	}
-
-	/* cfb messes with the pRectsInit so we have to do our
-	   calculations first */
-
-	(*pGC->ops->PolyFillRect)(pDraw, pGC, nRectsInit, pRectsInit);
-
-	TRANSLATE_AND_ADD_BOX(box, pGC);
-    } else
-	(*pGC->ops->PolyFillRect)(pDraw, pGC, nRectsInit, pRectsInit);
-
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-}
-
-static void
-xxPolyFillArc(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		narcs,
-    xArc	*parcs 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    (*pGC->ops->PolyFillArc)(pDraw, pGC, narcs, parcs);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw) && narcs) {
-	BoxRec box;
-
-	DBG("PolyFillArc\n");
-	box.x1 = parcs->x;
-	box.x2 = box.x1 + parcs->width;
-	box.y1 = parcs->y;
-	box.y2 = box.y1 + parcs->height;
-
-	/* should I break these up instead ? */
-
-	while(--narcs) {
-	   parcs++;
-	   if(box.x1 > parcs->x) box.x1 = parcs->x;
-	   if(box.x2 < (parcs->x + parcs->width))
-		box.x2 = parcs->x + parcs->width;
-	   if(box.y1 > parcs->y) box.y1 = parcs->y;
-	   if(box.y2 < (parcs->y + parcs->height))
-		box.y2 = parcs->y + parcs->height;
-        }
-
-	TRANSLATE_AND_ADD_BOX(box, pGC);
-    }
-}
-
-static int
-xxPolyText8(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		x, 
-    int 	y,
-    int 	count,
-    char	*chars 
-){
-    int width;
-
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    width = (*pGC->ops->PolyText8)(pDraw, pGC, x, y, count, chars);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-    width -= x;
-
-    if(IS_VISIBLE(pDraw) && (width > 0)) {
-	BoxRec box;
-
-	DBG("PolyText8\n");
-	/* ugh */
-	box.x1 = pDraw->x + x + FONTMINBOUNDS(pGC->font, leftSideBearing);
-	box.x2 = pDraw->x + x + FONTMAXBOUNDS(pGC->font, rightSideBearing);
-
-	if(count > 1) {
-	   if(width > 0) box.x2 += width;
-	   else box.x1 += width;
-	}
-
-	box.y1 = pDraw->y + y - FONTMAXBOUNDS(pGC->font, ascent);
-	box.y2 = pDraw->y + y + FONTMAXBOUNDS(pGC->font, descent);
-
-	ADD_BOX(box,  pGC);
-    }
-
-    return (width + x);
-}
-
-static int
-xxPolyText16(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		x,
-    int		y,
-    int 	count,
-    unsigned short *chars 
-){
-    int width;
-
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    width = (*pGC->ops->PolyText16)(pDraw, pGC, x, y, count, chars);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-    width -= x;
-
-    if(IS_VISIBLE(pDraw) && (width > 0)) {
-	BoxRec box;
-
-	DBG("PolyText16\n");
-	/* ugh */
-	box.x1 = pDraw->x + x + FONTMINBOUNDS(pGC->font, leftSideBearing);
-	box.x2 = pDraw->x + x + FONTMAXBOUNDS(pGC->font, rightSideBearing);
-
-	if(count > 1) {
-	   if(width > 0) box.x2 += width;
-	   else box.x1 += width;
-	}
-
-	box.y1 = pDraw->y + y - FONTMAXBOUNDS(pGC->font, ascent);
-	box.y2 = pDraw->y + y + FONTMAXBOUNDS(pGC->font, descent);
-
-	ADD_BOX(box, pGC);
-    }
-
-    return (width + x);
-}
-
-static void
-xxImageText8(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		x, 
-    int		y,
-    int 	count,
-    char	*chars 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    (*pGC->ops->ImageText8)(pDraw, pGC, x, y, count, chars);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw) && count) {
-	int top, bot, Min, Max;
-	BoxRec box;
-
-	DBG("ImageText8\n");
-	top = max(FONTMAXBOUNDS(pGC->font, ascent), FONTASCENT(pGC->font));
-	bot = max(FONTMAXBOUNDS(pGC->font, descent), FONTDESCENT(pGC->font));
-
-	Min = count * FONTMINBOUNDS(pGC->font, characterWidth);
-	if(Min > 0) Min = 0;
-	Max = count * FONTMAXBOUNDS(pGC->font, characterWidth);	
-	if(Max < 0) Max = 0;
-
-	/* ugh */
-	box.x1 = pDraw->x + x + Min +
-		FONTMINBOUNDS(pGC->font, leftSideBearing);
-	box.x2 = pDraw->x + x + Max + 
-		FONTMAXBOUNDS(pGC->font, rightSideBearing);
-
-	box.y1 = pDraw->y + y - top;
-	box.y2 = pDraw->y + y + bot;
-
-	ADD_BOX(box, pGC);
-    }
-}
-
-static void
-xxImageText16(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		x,
-    int		y,
-    int 	count,
-    unsigned short *chars 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    (*pGC->ops->ImageText16)(pDraw, pGC, x, y, count, chars);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw) && count) {
-	int top, bot, Min, Max;
-	BoxRec box;
-
-	DBG("ImageText16\n");
-	top = max(FONTMAXBOUNDS(pGC->font, ascent), FONTASCENT(pGC->font));
-	bot = max(FONTMAXBOUNDS(pGC->font, descent), FONTDESCENT(pGC->font));
-
-	Min = count * FONTMINBOUNDS(pGC->font, characterWidth);
-	if(Min > 0) Min = 0;
-	Max = count * FONTMAXBOUNDS(pGC->font, characterWidth);	
-	if(Max < 0) Max = 0;
-
-	/* ugh */
-	box.x1 = pDraw->x + x + Min +
-		FONTMINBOUNDS(pGC->font, leftSideBearing);
-	box.x2 = pDraw->x + x + Max + 
-		FONTMAXBOUNDS(pGC->font, rightSideBearing);
-
-	box.y1 = pDraw->y + y - top;
-	box.y2 = pDraw->y + y + bot;
-
-	ADD_BOX(box, pGC);
-    }
-}
-
-static void
-xxImageGlyphBlt(
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    int x, int y,
-    unsigned int nglyph,
-    CharInfoPtr *ppci,
-    pointer pglyphBase 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    (*pGC->ops->ImageGlyphBlt)(pDraw, pGC, x, y, nglyph, 
-					ppci, pglyphBase);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw) && nglyph) {
-	int top, bot, width = 0;
-	BoxRec box;
-
-	DBG("ImageGlyphBlt\n");
-	top = max(FONTMAXBOUNDS(pGC->font, ascent), FONTASCENT(pGC->font));
-	bot = max(FONTMAXBOUNDS(pGC->font, descent), FONTDESCENT(pGC->font));
-
-	box.x1 = ppci[0]->metrics.leftSideBearing;
-	if(box.x1 > 0) box.x1 = 0;
-	box.x2 = ppci[nglyph - 1]->metrics.rightSideBearing - 
-		ppci[nglyph - 1]->metrics.characterWidth;
-	if(box.x2 < 0) box.x2 = 0;
-
-	box.x2 += pDraw->x + x;
-	box.x1 += pDraw->x + x;
-	   
-	while(nglyph--) {
-	    width += (*ppci)->metrics.characterWidth;
-	    ppci++;
-	}
-
-	if(width > 0) 
-	   box.x2 += width;
-	else 
-	   box.x1 += width;
-
-	box.y1 = pDraw->y + y - top;
-	box.y2 = pDraw->y + y + bot;
-
-	ADD_BOX(box, pGC);
-    }
-}
-
-static void
-xxPolyGlyphBlt(
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    int x, int y,
-    unsigned int nglyph,
-    CharInfoPtr *ppci,
-    pointer pglyphBase 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    (*pGC->ops->PolyGlyphBlt)(pDraw, pGC, x, y, nglyph, 
-				ppci, pglyphBase);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw) && nglyph) {
-	BoxRec box;
-
-	DBG("PolyGlyphBlt\n");
-	/* ugh */
-	box.x1 = pDraw->x + x + ppci[0]->metrics.leftSideBearing;
-	box.x2 = pDraw->x + x + ppci[nglyph - 1]->metrics.rightSideBearing;
-
-	if(nglyph > 1) {
-	    int width = 0;
-
-	    while(--nglyph) { 
-		width += (*ppci)->metrics.characterWidth;
-		ppci++;
-	    }
-	
-	    if(width > 0) box.x2 += width;
-	    else box.x1 += width;
-	}
-
-	box.y1 = pDraw->y + y - FONTMAXBOUNDS(pGC->font, ascent);
-	box.y2 = pDraw->y + y + FONTMAXBOUNDS(pGC->font, descent);
-
-	ADD_BOX(box, pGC);
-    }
-}
-
-static void
-xxPushPixels(
-    GCPtr	pGC,
-    PixmapPtr	pBitMap,
-    DrawablePtr pDraw,
-    int	dx, int dy, int xOrg, int yOrg 
-){
-    XX_GC_OP_PROLOGUE(pGC, pDraw);
-    (*pGC->ops->PushPixels)(pGC, pBitMap, pDraw, dx, dy, xOrg, yOrg);
-    XX_GC_OP_EPILOGUE(pGC, pDraw);
-
-    if(IS_VISIBLE(pDraw)) {
-	BoxRec box;
-
-	DBG("PushPixels\n");
-	box.x1 = xOrg + pDraw->x;
-	box.x2 = box.x1 + dx;
-	box.y1 = yOrg + pDraw->y;
-	box.y2 = box.y1 + dy;
-
-	ADD_BOX(box, pGC);
-    }
-}
-
-
-#ifdef RENDER
-#define RENDER_MAKE_BOX(pDrawable,X,Y,W,H) { \
-    box.x1 = X + pDrawable->x; \
-    box.x2 = X + pDrawable->x + W; \
-    box.y1 = Y + pDrawable->y; \
-    box.y2 = Y + pDrawable->y + H; \
-}
-
-#define RENDER_ADD_BOX(pScreen,box) {\
-    if (BOX_NOT_EMPTY(box)) { \
-       RegionRec region; \
-       xxScrPriv(pScreen);\
-       ScreenPtr pScreen = pScreen;\
-       REGION_INIT (pScreen, &region, &box, 1); \
-       PRINT_RECTS(pScrPriv->region);\
-       REGION_UNION(pScreen,&pScrPriv->region,&pScrPriv->region,&region);\
-       PRINT_RECTS(pScrPriv->region);\
-       REGION_UNINIT(pScreen,&region);\
-   }\
-}
-
-static void
-xxComposite (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst,
-	     INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask,
-    INT16 xDst, INT16 yDst, CARD16 width, CARD16 height)
-{
-    ScreenPtr		pScreen = pDst->pDrawable->pScreen;
-    PictureScreenPtr	ps = GetPictureScreen(pScreen);
-    xxScrPriv(pScreen);
-    BoxRec		box;
-
-    unwrap (pScrPriv, ps, Composite);
-    (*ps->Composite) (op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask,
-		      xDst, yDst, width, height);
-    wrap (pScrPriv, ps, Composite, xxComposite);
-    if (pDst->pDrawable->type == DRAWABLE_WINDOW) {
-	RENDER_MAKE_BOX(pDst->pDrawable, xDst, yDst, width, height);
-	RENDER_ADD_BOX(pScreen,box);
-    }
-}
-
-
-static void
-xxGlyphs (CARD8 op, PicturePtr pSrc, PicturePtr pDst,
-	  PictFormatPtr maskFormat, INT16 xSrc, INT16 ySrc, int nlist,
-	  GlyphListPtr list, GlyphPtr *glyphs)
-{
-    ScreenPtr		pScreen = pDst->pDrawable->pScreen;
-    PictureScreenPtr	ps = GetPictureScreen(pScreen);
-    xxScrPriv(pScreen);
-    int			x, y;
-    int			n;
-    GlyphPtr		glyph;
-    BoxRec		box;
-
-    unwrap (pScrPriv, ps, Glyphs);
-    (*ps->Glyphs) (op, pSrc, pDst, maskFormat, xSrc, ySrc,
-		   nlist, list, glyphs);
-    wrap (pScrPriv, ps, Glyphs, xxGlyphs);
-    if (pDst->pDrawable->type == DRAWABLE_WINDOW)
-    {
-	x = xSrc;
-	y = ySrc;
-	while (nlist--)
-	{
-	    x += list->xOff;
-	    y += list->yOff;
-	    n = list->len;
-	    while (n--)
-	    {
-		glyph = *glyphs++;
-		RENDER_MAKE_BOX(pDst->pDrawable,
-				x - glyph->info.x, y - glyph->info.y,
-				glyph->info.width, glyph->info.height);
-		RENDER_ADD_BOX(pScreen,box);
-		x += glyph->info.xOff;
-		y += glyph->info.yOff;
-	    }
-	    list++;
-	}
-    }
-}
-#endif
-
-void
-xxPrintVisuals(void)
-{
-    int k,i,j;
-    DepthPtr pDepth;
-    VisualPtr pVisual;
-
-    for (k = 0; k < screenInfo.numScreens; k++) {
-	ScreenPtr pScreen = screenInfo.screens[k];
-	
-	pDepth = pScreen->allowedDepths;
-	for (i = 0; i < pScreen->numDepths; i++, pDepth++)
-	    for (j = 0; j < pDepth->numVids; j++) {
-		ErrorF("depth: %i vid: 0x%lx\n",
-		       pDepth->depth, pDepth->vids[j]);
-	    }
-	
-	pVisual = pScreen->visuals;
-	for (i = 0; i < pScreen->numVisuals; i++, pVisual++)
-	    ErrorF("vid: 0x%x rm: 0x%lx gm: 0x%lx bm: 0x%lx\n",
-		   (unsigned int)pVisual->vid,
-		   pVisual->redMask,
-		   pVisual->greenMask,
-		   pVisual->blueMask);
-    }
-}
-
-
diff --git a/fb/fbpseudocolor.h b/fb/fbpseudocolor.h
deleted file mode 100644
index 64de71d..0000000
--- a/fb/fbpseudocolor.h
+++ /dev/null
@@ -1,20 +0,0 @@
-#ifndef _FB_XX_H_
-# define  _FB_XX_H_
-
-typedef void (*xxSyncFunc)(ScreenPtr);
-extern Bool xxSetup(ScreenPtr pScreen, int myDepth,
-		    int baseDepth, char *addr, xxSyncFunc sync);
-extern void xxPrintVisuals(void);
-
-
-#endif /* _FB_XX_H_ */
-
-
-
-
-
-
-
-
-
-
diff --git a/fb/wfbrename.h b/fb/wfbrename.h
index dc05285..73ee510 100644
--- a/fb/wfbrename.h
+++ b/fb/wfbrename.h
@@ -187,12 +187,4 @@
 #define fbZeroSegment wfbZeroSegment
 #define free_pixman_pict wfb_free_pixman_pict
 #define image_from_pict wfb_image_from_pict
-#define xxScrPrivateKey wfbxxScrPrivateKey
-#define xxGCPrivateKey wfbxxGCPrivateKey
-#define xxColormapPrivateKey wfbxxColormapPrivateKey
-#define xxGeneration wfbxxGeneration
-#define xxPrintVisuals wfbxxPrintVisuals
-#define xxGCFuncs wfbxxGCFuncs
-#define xxGCOps wfbxxGCOps
-#define xxSetup wfbxxSetup
 #define composeFunctions wfbComposeFunctions
commit 60ff56050b64183cb6e58f54223c8a3ddc2e704b
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Fri Apr 18 22:17:53 2008 -0700

    Revert "Optimize dixLookupPrivate for repeated lookups of the same private."
    
    The patch was wildly unsafe for SIGIO, and made everything full of
    crashy crashy fail.
    
    This reverts commit 9b30cc524867a0ad3d0d2227e167f4284830ab4e.

diff --git a/include/privates.h b/include/privates.h
index 093d177..8d59b72 100644
--- a/include/privates.h
+++ b/include/privates.h
@@ -46,20 +46,13 @@ dixAllocatePrivate(PrivateRec **privates, const DevPrivateKey key);
 static _X_INLINE pointer
 dixLookupPrivate(PrivateRec **privates, const DevPrivateKey key)
 {
-    PrivateRec *rec, *prev;
+    PrivateRec *rec = *privates;
     pointer *ptr;
 
-    for (rec = *privates, prev = NULL; rec; prev = rec, rec = rec->next) {
-	if (rec->key != key)
-	    continue;
-
-	if (prev) {
-	    prev->next = rec->next;
-	    rec->next = *privates;
-	    *privates = rec;
-	}
-
-	return rec->value;
+    while (rec) {
+	if (rec->key == key)
+	    return rec->value;
+	rec = rec->next;
     }
 
     ptr = dixAllocatePrivate(privates, key);
commit ed9dabb47c467dbf49836b631d5d6bda4b0d98b0
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri Apr 18 20:30:43 2008 -0700

    Last of the spam... I promise...
    (cherry picked from commit 45ebee4f729b148a75e925a4863b4eb850c88f8e)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 90a0005..3df19de 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -34,7 +34,7 @@
 #endif
 
 #include "quartzForeground.h"
-
+#include "quartzCommon.h"
 #import "X11Application.h"
 
 # include "darwin.h"
@@ -43,10 +43,6 @@
 # define _APPLEWM_SERVER_
 # include "X11/extensions/applewm.h"
 # include "micmap.h"
-<<<<<<< HEAD:hw/xquartz/X11Application.m
-=======
-
->>>>>>> bc50d41... XQuartz: More sanitization of the namespace:hw/xquartz/X11Application.m
 #include <mach/mach.h>
 #include <unistd.h>
 #include <pthread.h>
commit 49f2bb4681fdee9e45f952ef0ac9c34a090117de
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri Apr 18 20:25:38 2008 -0700

    XQuartz: More sanitization of the namespace
    (cherry picked from commit bc50d41f9d1aec04f0de0478cbd5036f1fe9b81e)

diff --git a/hw/xquartz/X11Application.h b/hw/xquartz/X11Application.h
index 9d1ee41..47c605c 100644
--- a/hw/xquartz/X11Application.h
+++ b/hw/xquartz/X11Application.h
@@ -31,7 +31,7 @@
 #define X11APPLICATION_H 1
 
 #if __OBJC__
-#import <Cocoa/Cocoa.h>
+
 #import "X11Controller.h"
 
 @interface X11Application : NSApplication {
@@ -55,7 +55,7 @@
 - (void) prefs_set_string:(NSString *)key value:(NSString *)value;
 - (void) prefs_synchronize;
 
-- (BOOL) x_active;
+- (OSX_BOOL) x_active;
 
 @end
 
diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 30cb9f6..90a0005 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -43,6 +43,10 @@
 # define _APPLEWM_SERVER_
 # include "X11/extensions/applewm.h"
 # include "micmap.h"
+<<<<<<< HEAD:hw/xquartz/X11Application.m
+=======
+
+>>>>>>> bc50d41... XQuartz: More sanitization of the namespace:hw/xquartz/X11Application.m
 #include <mach/mach.h>
 #include <unistd.h>
 #include <pthread.h>
@@ -151,7 +155,7 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
     [self orderFrontStandardAboutPanelWithOptions: dict];
 }
 
-- (void) activateX:(BOOL)state {
+- (void) activateX:(OSX_BOOL)state {
     /* Create a TSM document that supports full Unicode input, and
 	 have it activated while X is active (unless using the old
 	 keymapping files) */
@@ -185,7 +189,7 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 
 - (void) sendEvent:(NSEvent *)e {
  	NSEventType type;
-	BOOL for_appkit, for_x;
+	OSX_BOOL for_appkit, for_x;
 
 	type = [e type];
 
@@ -644,7 +648,7 @@ static NSMutableArray * cfarray_to_nsarray (CFArrayRef in) {
 			     AppleWMCopyToPasteboard);
 }
 
-- (BOOL) x_active {
+- (OSX_BOOL) x_active {
     return _x_active;
 }
 
diff --git a/hw/xquartz/X11Controller.h b/hw/xquartz/X11Controller.h
index 8d6a38f..c5994bd 100644
--- a/hw/xquartz/X11Controller.h
+++ b/hw/xquartz/X11Controller.h
@@ -32,7 +32,7 @@
 
 #if __OBJC__
 
-#import <Cocoa/Cocoa.h>
+#include "sanitizedCocoa.h"
 #include "xpr/x-list.h"
 
 @interface X11Controller : NSObject
@@ -67,14 +67,14 @@
     int checked_window_item;
     x_list *pending_apps;
 
-    BOOL finished_launching;
-    BOOL can_quit;
+    OSX_BOOL finished_launching;
+    OSX_BOOL can_quit;
 }
 
 - (void) set_window_menu:(NSArray *)list;
 - (void) set_window_menu_check:(NSNumber *)n;
 - (void) set_apps_menu:(NSArray *)list;
-- (void) set_can_quit:(BOOL)state;
+- (void) set_can_quit:(OSX_BOOL)state;
 - (void) server_ready;
 
 - (IBAction) apps_table_show:(id)sender;
diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index 1f23569..f2dee2c 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -600,7 +600,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 #endif
 }
 
-- (void) set_can_quit:(BOOL)state
+- (void) set_can_quit:(OSX_BOOL)state
 {
   can_quit = state;
 }
@@ -667,7 +667,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
   AHLookupAnchor ((CFStringRef)NSLocalizedString(@"Mac Help", no comment), CFSTR ("mchlp2276"));
 }
 
-- (BOOL) validateMenuItem:(NSMenuItem *)item
+- (OSX_BOOL) validateMenuItem:(NSMenuItem *)item
 {
   NSMenu *menu = [item menu];
 	
@@ -739,7 +739,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
   pending_apps = NULL;
 }
 
-- (BOOL) application:(NSApplication *)app openFile:(NSString *)filename
+- (OSX_BOOL) application:(NSApplication *)app openFile:(NSString *)filename
 {
     const char *name = [filename UTF8String];
     
@@ -752,8 +752,8 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
     return YES;
 }
 
-- (BOOL) applicationShouldHandleReopen:(NSApplication *)app
-                     hasVisibleWindows:(BOOL)hasVis {
+- (OSX_BOOL) applicationShouldHandleReopen:(NSApplication *)app
+                     hasVisibleWindows:(OSX_BOOL)hasVis {
     DarwinSendDDXEvent(kXquartzBringAllToFront, 0);
     return YES;
 }
commit c2f0d020b5d7950267aa3df391a7a72b9ae5883b
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri Apr 18 20:10:57 2008 -0700

    XQuartz: Removed unneccessary include
    (cherry picked from commit 45ff59e69eddfcceafced31cf6e73e381d0f6914)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index fe9bb25..30cb9f6 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -34,7 +34,7 @@
 #endif
 
 #include "quartzForeground.h"
-#include "quartzCommon.h"
+
 #import "X11Application.h"
 
 # include "darwin.h"
commit 5183fea6d38de4bcf657e9c2a983dfd81a2a223f
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri Apr 18 20:06:17 2008 -0700

    XQuartz: Handled sanitization of namespace better
    (cherry picked from commit 8cb23d672177da919257c885804cecd18cf9af88)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 6691a25..fe9bb25 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -26,22 +26,17 @@
  copyright holders shall not be used in advertising or otherwise to
  promote the sale, use or other dealings in this Software without
  prior written authorization. */
-#include <Carbon/Carbon.h>
-#include "quartzCommon.h"
+
+#include "sanitizedCarbon.h"
 
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
-#define BOOL X_BOOL
-//#undef GetWindowAttributes
-//#undef ChangeWindowAttributes
-#undef BOOL
 
 #include "quartzForeground.h"
+#include "quartzCommon.h"
 #import "X11Application.h"
 
-/* ouch! */
-#define BOOL X_BOOL
 # include "darwin.h"
 # include "darwinEvents.h"
 # include "quartz.h"
diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index 2fd9886..1f23569 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -27,6 +27,8 @@
    promote the sale, use or other dealings in this Software without
    prior written authorization. */
 
+#include "sanitizedCarbon.h"
+
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
@@ -37,17 +39,13 @@
 
 #import "X11Controller.h"
 #import "X11Application.h"
-#import <Carbon/Carbon.h>
 
-/* ouch! */
-#define BOOL X_BOOL
 #include "opaque.h"
-# include "darwin.h"
-# include "quartz.h"
-# define _APPLEWM_SERVER_
-# include "X11/extensions/applewm.h"
-# include "applewmExt.h"
-#undef BOOL
+#include "darwin.h"
+#include "quartz.h"
+#define _APPLEWM_SERVER_
+#include "X11/extensions/applewm.h"
+#include "applewmExt.h"
 
 #include <stdio.h>
 #include <unistd.h>
diff --git a/hw/xquartz/applewm.c b/hw/xquartz/applewm.c
index 072e57f..ba86f10 100644
--- a/hw/xquartz/applewm.c
+++ b/hw/xquartz/applewm.c
@@ -25,6 +25,8 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 **************************************************************************/
 
+#include "sanitizedCarbon.h"
+
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index d69e6b7..afa292f 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -284,7 +284,7 @@ static void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, in
                 break;
                 
             case kXquartzSetRootClip:
-                QuartzSetRootClip((BOOL)xe[i].u.clientMessage.u.l.longs0);
+                QuartzSetRootClip((Bool)xe[i].u.clientMessage.u.l.longs0);
                 break;
                 
             case kXquartzQuit:
diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index fb9f13c..4d03d02 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -28,6 +28,8 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
+#include "sanitizedCarbon.h"
+
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
diff --git a/hw/xquartz/quartzAudio.c b/hw/xquartz/quartzAudio.c
index 5dee32f..d3698d7 100644
--- a/hw/xquartz/quartzAudio.c
+++ b/hw/xquartz/quartzAudio.c
@@ -36,6 +36,8 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
+#include "sanitizedCarbon.h"
+
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
diff --git a/hw/xquartz/quartzCocoa.m b/hw/xquartz/quartzCocoa.m
index d8f9c69..aa4b9fb 100644
--- a/hw/xquartz/quartzCocoa.m
+++ b/hw/xquartz/quartzCocoa.m
@@ -32,6 +32,8 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
+#include "sanitizedCocoa.h"
+
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
@@ -40,12 +42,8 @@
 #include "inputstr.h"
 #include "quartzPasteboard.h"
 
-#define BOOL xBOOL
 #include "darwin.h"
 
-#include <Cocoa/Cocoa.h>
-#undef BOOL
-
 #include "pseudoramiX.h"
 
 extern void FatalError(const char *, ...);
diff --git a/hw/xquartz/quartzCommon.h b/hw/xquartz/quartzCommon.h
index 40675bc..e63c2b7 100644
--- a/hw/xquartz/quartzCommon.h
+++ b/hw/xquartz/quartzCommon.h
@@ -35,18 +35,6 @@
 #ifndef _QUARTZCOMMON_H
 #define _QUARTZCOMMON_H
 
-// QuickDraw in ApplicationServices has the following conflicts with
-// the basic X server headers. Use QD_<name> to use the QuickDraw
-// definition of any of these symbols, or the normal name for the
-// X11 definition.
-#define Cursor       QD_Cursor
-#define WindowPtr    QD_WindowPtr
-#define Picture      QD_Picture
-#include <ApplicationServices/ApplicationServices.h>
-#include <Carbon/Carbon.h>
-#undef Cursor
-#undef WindowPtr
-#undef Picture
 #include <X11/Xdefs.h>
 #include "privates.h"
 
diff --git a/hw/xquartz/quartzKeyboard.c b/hw/xquartz/quartzKeyboard.c
index fd0c3cc..698f39a 100644
--- a/hw/xquartz/quartzKeyboard.c
+++ b/hw/xquartz/quartzKeyboard.c
@@ -34,6 +34,8 @@
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
+#include "sanitizedCarbon.h"
+
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
@@ -51,15 +53,6 @@
 #include <sys/stat.h>
 
 #include "quartzCommon.h"
-
-#undef GetWindowAttributes
-#undef ChangeWindowAttributes
-
-#include <CoreServices/CoreServices.h>
-#include <Carbon/Carbon.h>
-#include <IOKit/hidsystem/event_status_driver.h>
-#include <IOKit/hidsystem/ev_keymap.h>
-#include <architecture/byte_order.h>  // For the NXSwap*
 #include "darwin.h"
 
 #include "quartzKeyboard.h"
diff --git a/hw/xquartz/quartzStartup.c b/hw/xquartz/quartzStartup.c
index 5ac3017..233e6e6 100644
--- a/hw/xquartz/quartzStartup.c
+++ b/hw/xquartz/quartzStartup.c
@@ -27,6 +27,8 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
+#include "sanitizedCarbon.h"
+
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
diff --git a/hw/xquartz/sanitizedCarbon.h b/hw/xquartz/sanitizedCarbon.h
new file mode 100644
index 0000000..cc6ef19
--- /dev/null
+++ b/hw/xquartz/sanitizedCarbon.h
@@ -0,0 +1,32 @@
+/*
+ * Don't #include any of the AppKit, etc stuff directly since it will
+ * pollute the X11 namespace.
+ */
+
+#ifndef _XQ_SANITIZED_CARBON_H_
+#define _XQ_SANITIZED_CARBON_H_
+
+// QuickDraw in ApplicationServices has the following conflicts with
+// the basic X server headers. Use QD_<name> to use the QuickDraw
+// definition of any of these symbols, or the normal name for the
+// X11 definition.
+#define Cursor       QD_Cursor
+#define WindowPtr    QD_WindowPtr
+#define Picture      QD_Picture
+#define BOOL         OSX_BOOL
+#define EventType    HIT_EventType
+
+#include <ApplicationServices/ApplicationServices.h>
+#include <CoreServices/CoreServices.h>
+#include <Carbon/Carbon.h>
+#include <IOKit/hidsystem/event_status_driver.h>
+#include <IOKit/hidsystem/ev_keymap.h>
+#include <architecture/byte_order.h>  // For the NXSwap*
+
+#undef Cursor
+#undef WindowPtr
+#undef Picture
+#undef BOOL
+#undef EventType
+
+#endif  /* _XQ_SANITIZED_CARBON_H_ */
diff --git a/hw/xquartz/sanitizedCocoa.h b/hw/xquartz/sanitizedCocoa.h
new file mode 100644
index 0000000..58de64c
--- /dev/null
+++ b/hw/xquartz/sanitizedCocoa.h
@@ -0,0 +1,27 @@
+/*
+ * Don't #include any of the AppKit, etc stuff directly since it will
+ * pollute the X11 namespace.
+ */
+
+#ifndef _XQ_SANITIZED_COCOA_H_
+#define _XQ_SANITIZED_COCOA_H_
+
+// QuickDraw in ApplicationServices has the following conflicts with
+// the basic X server headers. Use QD_<name> to use the QuickDraw
+// definition of any of these symbols, or the normal name for the
+// X11 definition.
+#define Cursor       QD_Cursor
+#define WindowPtr    QD_WindowPtr
+#define Picture      QD_Picture
+#define BOOL         OSX_BOOL
+#define EventType    HIT_EventType
+
+#include <Cocoa/Cocoa.h>
+
+#undef Cursor
+#undef WindowPtr
+#undef Picture
+#undef BOOL
+#undef EventType
+
+#endif  /* _XQ_SANITIZED_COCOA_H_ */
diff --git a/hw/xquartz/xpr/xprCursor.c b/hw/xquartz/xpr/xprCursor.c
index a42c30c..76ab75c 100644
--- a/hw/xquartz/xpr/xprCursor.c
+++ b/hw/xquartz/xpr/xprCursor.c
@@ -29,6 +29,8 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
+#include "sanitizedCarbon.h"
+
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index 8219046..f685d4a 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -27,6 +27,8 @@
  * use or other dealings in this Software without prior written authorization.
  */
 
+#include "sanitizedCarbon.h"
+
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
diff --git a/include/window.h b/include/window.h
index ca2e57e..52b3982 100644
--- a/include/window.h
+++ b/include/window.h
@@ -134,7 +134,7 @@ extern int ChangeWindowAttributes(
 /* Quartz support on Mac OS X uses the HIToolbox
    framework whose GetWindowAttributes function conflicts here. */
 #ifdef __APPLE__
-#define GetWindowAttributes(w,c) Darwin_X_GetWindowAttributes(w,c)
+#define GetWindowAttributes(w,c,x) Darwin_X_GetWindowAttributes(w,c,x)
 extern void Darwin_X_GetWindowAttributes(
 #else
 extern void GetWindowAttributes(
commit edd3fb784bad893550ee270e0a09f22f99783cf5
Author: Ben Byer <bbyer at bbyer.local>
Date:   Fri Apr 18 17:17:01 2008 -0700

    random flailing
    (cherry picked from commit 7fb9b2dc615a3bd1a3c087438af7a8b88265cfaa)

diff --git a/hw/xquartz/X11Application.h b/hw/xquartz/X11Application.h
index ea9a6b7..9d1ee41 100644
--- a/hw/xquartz/X11Application.h
+++ b/hw/xquartz/X11Application.h
@@ -31,7 +31,6 @@
 #define X11APPLICATION_H 1
 
 #if __OBJC__
-
 #import <Cocoa/Cocoa.h>
 #import "X11Controller.h"
 
diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 31ac563..6691a25 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -26,16 +26,19 @@
  copyright holders shall not be used in advertising or otherwise to
  promote the sale, use or other dealings in this Software without
  prior written authorization. */
+#include <Carbon/Carbon.h>
+#include "quartzCommon.h"
 
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
+#define BOOL X_BOOL
+//#undef GetWindowAttributes
+//#undef ChangeWindowAttributes
+#undef BOOL
 
-#include "quartzCommon.h"
 #include "quartzForeground.h"
-
 #import "X11Application.h"
-#include <Carbon/Carbon.h>
 
 /* ouch! */
 #define BOOL X_BOOL
@@ -45,8 +48,6 @@
 # define _APPLEWM_SERVER_
 # include "X11/extensions/applewm.h"
 # include "micmap.h"
-#undef BOOL
-
 #include <mach/mach.h>
 #include <unistd.h>
 #include <pthread.h>
@@ -188,10 +189,6 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 }
 
 - (void) sendEvent:(NSEvent *)e {
-  NSEventType type;
-  BOOL for_appkit, for_x;
-  
-  type = [e type];
  	NSEventType type;
 	BOOL for_appkit, for_x;
 
@@ -242,6 +239,7 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 							|| [e keyCode] == 53 /*Esc*/)) {
 						swallow_up = 0;
 						for_x = NO;
+					}
 			} else {
 			/* If we saw a key equivalent on the down, don't pass
 	   			the up through to X. */
@@ -641,8 +639,8 @@ static NSMutableArray * cfarray_to_nsarray (CFArrayRef in) {
     if(darwinDesiredDepth == 8)
         darwinDesiredDepth = -1;
 	
-    enable_stereo = [self prefs_get_boolean:@PREFS_ENABLE_STEREO
-                     default:false];
+//    enable_stereo = [self prefs_get_boolean:@PREFS_ENABLE_STEREO
+//                     default:false];
 }
 
 /* This will end up at the end of the responder chain. */
diff --git a/hw/xquartz/quartzCommon.h b/hw/xquartz/quartzCommon.h
index c4bd2d8..40675bc 100644
--- a/hw/xquartz/quartzCommon.h
+++ b/hw/xquartz/quartzCommon.h
@@ -43,6 +43,7 @@
 #define WindowPtr    QD_WindowPtr
 #define Picture      QD_Picture
 #include <ApplicationServices/ApplicationServices.h>
+#include <Carbon/Carbon.h>
 #undef Cursor
 #undef WindowPtr
 #undef Picture
diff --git a/hw/xquartz/quartzKeyboard.c b/hw/xquartz/quartzKeyboard.c
index e8d9968..fd0c3cc 100644
--- a/hw/xquartz/quartzKeyboard.c
+++ b/hw/xquartz/quartzKeyboard.c
@@ -52,6 +52,9 @@
 
 #include "quartzCommon.h"
 
+#undef GetWindowAttributes
+#undef ChangeWindowAttributes
+
 #include <CoreServices/CoreServices.h>
 #include <Carbon/Carbon.h>
 #include <IOKit/hidsystem/event_status_driver.h>
diff --git a/include/window.h b/include/window.h
index 52b3982..ca2e57e 100644
--- a/include/window.h
+++ b/include/window.h
@@ -134,7 +134,7 @@ extern int ChangeWindowAttributes(
 /* Quartz support on Mac OS X uses the HIToolbox
    framework whose GetWindowAttributes function conflicts here. */
 #ifdef __APPLE__
-#define GetWindowAttributes(w,c,x) Darwin_X_GetWindowAttributes(w,c,x)
+#define GetWindowAttributes(w,c) Darwin_X_GetWindowAttributes(w,c)
 extern void Darwin_X_GetWindowAttributes(
 #else
 extern void GetWindowAttributes(
diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index 17fe690..a6002bb 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -1427,7 +1427,7 @@ RootlessReparentWindow(WindowPtr pWin, WindowPtr pPriorParent)
     
     pWin->rootlessUnhittable = FALSE;
     
-    DeleteProperty (pWin, xa_native_window_id ());
+    DeleteProperty (serverClient, pWin, xa_native_window_id ());
 
     if (WINREC(pTopWin) != NULL) {
         /* We're screwed. */
commit a7503615a6893749d512f75d37646273f31b9dbf
Author: Adam Jackson <ajax at redhat.com>
Date:   Fri Apr 18 19:56:41 2008 -0400

    Death to TOG-CUP.
    
    If you still care about 8bpp visuals that much, fix Composite to provide
    synthetic visuals.

diff --git a/Xext/Makefile.am b/Xext/Makefile.am
index 9e35ae1..b03feda 100644
--- a/Xext/Makefile.am
+++ b/Xext/Makefile.am
@@ -104,13 +104,6 @@ if XPRINT
 BUILTIN_SRCS += $(XPRINT_SRCS)
 endif
 
-# Colormap Utilization Protocol: Less flashing when switching between
-# PsuedoColor apps and better sharing of limited colormap slots
-CUP_SRCS = cup.c
-if CUP
-MODULE_SRCS  += $(CUP_SRCS)
-endif
-
 # Multi-buffering extension
 MULTIBUFFER_SRCS = mbuf.c
 EXTRA_MULTIBUFFER_SRCS = mbufbf.c mbufpx.c
@@ -157,7 +150,6 @@ EXTRA_DIST = \
 	$(XINERAMA_SRCS) \
 	$(XEVIE_SRCS) \
 	$(XPRINT_SRCS) \
-	$(CUP_SRCS) \
 	$(MULTIBUFFER_SRCS) \
 	$(EXTRA_MULTIBUFFER_SRCS) \
 	$(FONTCACHE_SRCS) \
diff --git a/Xext/cup.c b/Xext/cup.c
deleted file mode 100644
index fd1409e..0000000
--- a/Xext/cup.c
+++ /dev/null
@@ -1,342 +0,0 @@
-/*
-
-Copyright 1997, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-*/
-
-#define NEED_REPLIES
-#define NEED_EVENTS
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include "misc.h"
-#include "dixstruct.h"
-#include "extnsionst.h"
-#include "colormapst.h"
-#include "scrnintstr.h"
-#include "servermd.h"
-#include "swapreq.h"
-#define _XCUP_SERVER_
-#include <X11/extensions/Xcupstr.h>
-#include <X11/Xfuncproto.h>
-
-#include "../os/osdep.h"
-
-#include "modinit.h"
-
-static int		ProcDispatch(ClientPtr client);
-static int              SProcDispatch(ClientPtr client);
-static void		ResetProc(ExtensionEntry* extEntry);
-
-#if defined(WIN32) || defined(TESTWIN32)
-#define HAVE_SPECIAL_DESKTOP_COLORS
-#endif
-
-static xColorItem citems[] = {
-#ifndef HAVE_SPECIAL_DESKTOP_COLORS
-#define CUP_BLACK_PIXEL 0
-#define CUP_WHITE_PIXEL 1
-  /*  pix     red   green    blue        */ 
-    {   0,      0,      0,      0, 0, 0 },
-    {   1, 0xffff, 0xffff, 0xffff, 0, 0 }
-#else
-#ifndef WIN32
-    /* 
-	This approximates the MS-Windows desktop colormap for testing 
-        purposes but has black and white pixels in the typical Unix 
-        locations, which should be switched if necessary if your system
-        has blackPixel and whitePixel swapped. No entries are provided
-        for colormap entries 254 and 255 because AllocColor/FindColor
-        will reuse entries zero and one.
-    */
-    {   0,      0,      0,      0, 0, 0 },
-    {   1, 0xffff, 0xffff, 0xffff, 0, 0 },
-    {   2, 0x8000,      0,      0, 0, 0 },
-    {   3,      0, 0x8000,      0, 0, 0 },
-    {   4, 0x8000, 0x8000,      0, 0, 0 },
-    {   5,      0,      0, 0x8000, 0, 0 },
-    {   6, 0x8000,      0, 0x8000, 0, 0 },
-    {   7,      0, 0x8000, 0x8000, 0, 0 },
-    {   8, 0xc000, 0xc000, 0xc000, 0, 0 },
-    {   9, 0xc000, 0xdc00, 0xc000, 0, 0 },
-    { 246, 0xa000, 0xa000, 0xa000, 0, 0 },
-    { 247, 0x8000, 0x8000, 0x8000, 0, 0 },
-    { 248, 0xffff,      0,      0, 0, 0 },
-    { 249,      0, 0xffff,      0, 0, 0 },
-    { 250, 0xffff, 0xffff,      0, 0, 0 },
-    { 251,      0,      0, 0xffff, 0, 0 },
-    { 252, 0xffff,      0, 0xffff, 0, 0 },
-    { 253,      0, 0xffff, 0xffff, 0, 0 }
-#else
-    /* 
-	this is the MS-Windows desktop, adjusted for X's 16-bit color
-	specifications.
-    */
-    {   0,      0,      0,      0, 0, 0 },
-    {   1, 0x8000,      0,      0, 0, 0 },
-    {   2,      0, 0x8000,      0, 0, 0 },
-    {   3, 0x8000, 0x8000,      0, 0, 0 },
-    {   4,      0,      0, 0x8000, 0, 0 },
-    {   5, 0x8000,      0, 0x8000, 0, 0 },
-    {   6,      0, 0x8000, 0x8000, 0, 0 },
-    {   7, 0xc000, 0xc000, 0xc000, 0, 0 },
-    {   8, 0xc000, 0xdc00, 0xc000, 0, 0 },
-    {   9, 0xa600, 0xca00, 0xf000, 0, 0 },
-    { 246, 0xff00, 0xfb00, 0xf000, 0, 0 },
-    { 247, 0xa000, 0xa000, 0xa400, 0, 0 },
-    { 248, 0x8000, 0x8000, 0x8000, 0, 0 },
-    { 249, 0xff00,      0,      0, 0, 0 },
-    { 250,      0, 0xff00,      0, 0, 0 },
-    { 251, 0xff00, 0xff00,      0, 0, 0 },
-    { 252,      0,      0, 0xff00, 0, 0 },
-    { 253, 0xff00,      0, 0xff00, 0, 0 },
-    { 254,      0, 0xff00, 0xff00, 0, 0 },
-    { 255, 0xff00, 0xff00, 0xff00, 0, 0 }
-#endif
-#endif
-};
-#define NUM_DESKTOP_COLORS (sizeof citems / sizeof citems[0])
-
-void
-XcupExtensionInit (INITARGS)
-{
-    (void) AddExtension (XCUPNAME,
-			0,
-			XcupNumberErrors,
-			ProcDispatch,
-			SProcDispatch,
-			ResetProc,
-			StandardMinorOpcode);
-
-    /* PC servers initialize the desktop colors (citems) here! */
-}
-
-/*ARGSUSED*/
-static 
-void ResetProc(
-    ExtensionEntry* extEntry)
-{
-}
-
-static 
-int ProcQueryVersion(
-    register ClientPtr client)
-{
-    /* REQUEST (xXcupQueryVersionReq); */
-    xXcupQueryVersionReply rep;
-    register int n;
-
-    REQUEST_SIZE_MATCH (xXcupQueryVersionReq);
-    rep.type = X_Reply;
-    rep.length = 0;
-    rep.sequence_number = client->sequence;
-    rep.server_major_version = XCUP_MAJOR_VERSION;
-    rep.server_minor_version = XCUP_MINOR_VERSION;
-    if (client->swapped) {
-    	swaps (&rep.sequence_number, n);
-    	swapl (&rep.length, n);
-    	swaps (&rep.server_major_version, n);
-    	swaps (&rep.server_minor_version, n);
-    }
-    WriteToClient (client, sizeof (xXcupQueryVersionReply), (char *)&rep);
-    return client->noClientException;
-}
-
-static
-int ProcGetReservedColormapEntries(
-    register ClientPtr client)
-{
-    REQUEST (xXcupGetReservedColormapEntriesReq);
-    xXcupGetReservedColormapEntriesReply rep;
-    xColorItem* cptr;
-    register int n;
-
-    REQUEST_SIZE_MATCH (xXcupGetReservedColormapEntriesReq);
-
-    if (stuff->screen >= screenInfo.numScreens)
-	return BadValue;
-
-#ifndef HAVE_SPECIAL_DESKTOP_COLORS
-    citems[CUP_BLACK_PIXEL].pixel = 
-	screenInfo.screens[stuff->screen]->blackPixel;
-    citems[CUP_WHITE_PIXEL].pixel = 
-	screenInfo.screens[stuff->screen]->whitePixel;
-#endif
-
-    rep.type = X_Reply;
-    rep.sequence_number = client->sequence;
-    rep.length = NUM_DESKTOP_COLORS * 3;
-    if (client->swapped) {
-    	swaps (&rep.sequence_number, n);
-    	swapl (&rep.length, n);
-    }
-    WriteToClient (client, sizeof (xXcupGetReservedColormapEntriesReply), (char *)&rep);
-    for (n = 0, cptr = citems; n < NUM_DESKTOP_COLORS; n++, cptr++) {
-	if (client->swapped) SwapColorItem (cptr);
-	WriteToClient (client, SIZEOF(xColorItem), (char *)cptr);
-    }
-    return client->noClientException;
-}
-
-static
-int ProcStoreColors(
-    register ClientPtr client)
-{
-    REQUEST (xXcupStoreColorsReq);
-    ColormapPtr pcmp;
-    int rc;
-
-    REQUEST_AT_LEAST_SIZE (xXcupStoreColorsReq);
-    rc = dixLookupResource((pointer *)&pcmp, stuff->cmap, RT_COLORMAP,
-			   client, DixAddAccess);
-
-    if (rc == Success) {
-	int ncolors, n;
-	xXcupStoreColorsReply rep;
-	xColorItem* cptr;
-
-	if (!(pcmp->class & DynamicClass))
-	    return BadMatch;
-
-	ncolors = (client->req_len << 2) - SIZEOF (xXcupStoreColorsReq);
-	if (ncolors % SIZEOF(xColorItem))
-	    return BadLength;
-
-	ncolors /= SIZEOF (xColorItem);
-
-
-	for (n = 0, cptr = (xColorItem*) &stuff[1]; n < ncolors; n++) {
-	    Pixel pixel = cptr->pixel;
-
-	    if (AllocColor (pcmp,
-			    &cptr->red, &cptr->green, &cptr->blue,
-			    &pixel, client->index) == Success) {
-		cptr->pixel = pixel;
-		cptr->flags = 0x08;
-	    } else
-		cptr->flags = 0;
-	    cptr = (xColorItem*) (((char*)cptr) + SIZEOF(xColorItem));
-	}
-
-	rep.type = X_Reply;
-	rep.sequence_number = client->sequence;
-	rep.length = ncolors * 3;
-	if (client->swapped) {
-    	    swaps (&rep.sequence_number, n);
-    	    swapl (&rep.length, n);
-	}
-	WriteToClient (client, sizeof (xXcupGetReservedColormapEntriesReply), (char *)&rep);
-	for (n = 0, cptr = (xColorItem*) &stuff[1]; n < ncolors; n++) {
-	    if (client->swapped) SwapColorItem (cptr);
-	    WriteToClient (client, SIZEOF(xColorItem), (char *)cptr);
-	    cptr = (xColorItem*) (((char*)cptr) + SIZEOF(xColorItem));
-	}
-	return client->noClientException;
-    } else {
-	client->errorValue = stuff->cmap;
-	return (rc == BadValue) ? BadColor : rc;
-    }
-}
-
-static 
-int ProcDispatch(
-    register ClientPtr client)
-{
-    REQUEST (xReq);
-    switch (stuff->data)
-    {
-    case X_XcupQueryVersion:
-	return ProcQueryVersion (client);
-    case X_XcupGetReservedColormapEntries:
-	return ProcGetReservedColormapEntries (client);
-    case X_XcupStoreColors:
-	return ProcStoreColors (client);
-    default:
-	return BadRequest;
-    }
-}
-
-static 
-int SProcQueryVersion(
-    register ClientPtr client)
-{
-    register int n;
-
-    REQUEST(xXcupQueryVersionReq);
-    swaps(&stuff->length, n);
-    return ProcQueryVersion(client);
-}
-
-static 
-int SProcGetReservedColormapEntries(
-    ClientPtr client)
-{
-    register int n;
-
-    REQUEST (xXcupGetReservedColormapEntriesReq);
-    swaps (&stuff->length, n);
-    swapl (&stuff->screen, n);
-    REQUEST_AT_LEAST_SIZE (xXcupGetReservedColormapEntriesReq);
-    return ProcGetReservedColormapEntries (client);
-}
-
-static 
-int SProcXcupStoreColors(
-    ClientPtr client)
-{
-    register int n;
-    int count;
-    xColorItem* pItem;
-
-    REQUEST (xXcupStoreColorsReq);
-    swaps (&stuff->length, n);
-    REQUEST_AT_LEAST_SIZE (xXcupStoreColorsReq);
-    swapl(&stuff->cmap, n);
-    pItem = (xColorItem*) &stuff[1];
-    for(count = LengthRestB(stuff)/sizeof(xColorItem); --count >= 0; )
-        SwapColorItem(pItem++);
-    return ProcStoreColors (client);
-}
-
-static 
-int SProcDispatch(
-    register ClientPtr client)
-{
-    REQUEST(xReq);
-    switch (stuff->data)
-    {
-    case X_XcupQueryVersion:
-	return SProcQueryVersion (client);
-    case X_XcupGetReservedColormapEntries:
-	return SProcGetReservedColormapEntries (client);
-    case X_XcupStoreColors:
-	return SProcXcupStoreColors (client);
-    default:
-	return BadRequest;
-    }
-}
-
-
diff --git a/hw/dmx/dmx-config.h b/hw/dmx/dmx-config.h
index df77f09..4a2dfe0 100644
--- a/hw/dmx/dmx-config.h
+++ b/hw/dmx/dmx-config.h
@@ -83,7 +83,6 @@
 #undef XF86MISC
 #undef XFreeXDGA
 #undef XF86DRI
-#undef TOGCUP
 #undef SCREENSAVER
 #undef RANDR
 #undef XFIXES
diff --git a/hw/xfree86/dixmods/extmod/modinit.c b/hw/xfree86/dixmods/extmod/modinit.c
index fe499fe..f8440f1 100644
--- a/hw/xfree86/dixmods/extmod/modinit.c
+++ b/hw/xfree86/dixmods/extmod/modinit.c
@@ -155,15 +155,6 @@ static ExtensionModule extensionModules[] = {
 	NULL
     },
 #endif
-#ifdef TOGCUP
-    {
-	XcupExtensionInit,
-	XCUPNAME,
-	&noXcupExtension,
-	NULL,
-	NULL
-    },
-#endif
 #ifdef XV
     {
 	XvExtensionInit,
diff --git a/hw/xfree86/dixmods/extmod/modinit.h b/hw/xfree86/dixmods/extmod/modinit.h
index 6c87b15..7282e6e 100644
--- a/hw/xfree86/dixmods/extmod/modinit.h
+++ b/hw/xfree86/dixmods/extmod/modinit.h
@@ -83,12 +83,6 @@ extern void FontCacheExtensionInit(INITARGS);
 #include "fontcachstr.h"
 #endif
 
-#ifdef TOGCUP
-extern void XcupExtensionInit(INITARGS);
-#define _XCUP_SERVER_
-#include <X11/extensions/Xcupstr.h>
-#endif
-
 #ifdef XV
 extern void XvExtensionInit(INITARGS);
 extern void XvMCExtensionInit(INITARGS);
diff --git a/hw/xfree86/loader/dixsym.c b/hw/xfree86/loader/dixsym.c
index 78a2123..61dec59 100644
--- a/hw/xfree86/loader/dixsym.c
+++ b/hw/xfree86/loader/dixsym.c
@@ -388,9 +388,6 @@ _X_HIDDEN void *dixLookupTab[] = {
 #ifdef XSYNC
     SYMVAR(noSyncExtension)
 #endif
-#ifdef TOGCUP
-    SYMVAR(noXcupExtension)
-#endif
 #ifdef RES
     SYMVAR(noResExtension)
 #endif
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index 42d108f..1779082 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -413,9 +413,6 @@
 /* Support Xv extension */
 #undef XV
 
-/* Build TOG-CUP extension */
-#undef TOGCUP
-
 /* Build Multibuffer extension */
 #undef MULTIBUFFER
 
diff --git a/include/globals.h b/include/globals.h
index 62794f5..9e5060d 100644
--- a/include/globals.h
+++ b/include/globals.h
@@ -106,10 +106,6 @@ extern Bool noSecurityExtension;
 extern Bool noSyncExtension;
 #endif
 
-#ifdef TOGCUP
-extern Bool noXcupExtension;
-#endif
-
 #ifdef RES
 extern Bool noResExtension;
 #endif
diff --git a/mi/miinitext.c b/mi/miinitext.c
index d9f910c..8689ee4 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -160,9 +160,6 @@ extern Bool noSecurityExtension;
 #ifdef XSYNC
 extern Bool noSyncExtension;
 #endif
-#ifdef TOGCUP
-extern Bool noXcupExtension;
-#endif
 #ifdef RES
 extern Bool noResExtension;
 #endif
@@ -331,9 +328,6 @@ extern void GlxExtensionInit(INITARGS);
 #ifdef XF86DRI
 extern void XFree86DRIExtensionInit(INITARGS);
 #endif
-#ifdef TOGCUP
-extern void XcupExtensionInit(INITARGS);
-#endif
 #ifdef DPMSExtension
 extern void DPMSExtensionInit(INITARGS);
 #endif
@@ -421,9 +415,6 @@ static ExtensionToggle ExtensionToggleList[] =
 #ifdef XSYNC
     { "SYNC", &noSyncExtension },
 #endif
-#ifdef TOGCUP
-    { "TOG-CUP", &noXcupExtension },
-#endif
 #ifdef RES
     { "X-Resource", &noResExtension },
 #endif
@@ -568,9 +559,6 @@ InitExtensions(argc, argv)
 #ifdef XPRINT
     XpExtensionInit(); /* server-specific extension, cannot be disabled */
 #endif
-#ifdef TOGCUP
-    if (!noXcupExtension) XcupExtensionInit();
-#endif
 #if defined(DPMSExtension) && !defined(NO_HW_ONLY_EXTS)
     if (!noDPMSExtension) DPMSExtensionInit();
 #endif
diff --git a/os/utils.c b/os/utils.c
index f394fe5..07296df 100644
--- a/os/utils.c
+++ b/os/utils.c
@@ -180,9 +180,6 @@ _X_EXPORT Bool noSecurityExtension = FALSE;
 #ifdef XSYNC
 _X_EXPORT Bool noSyncExtension = FALSE;
 #endif
-#ifdef TOGCUP
-_X_EXPORT Bool noXcupExtension = FALSE;
-#endif
 #ifdef RES
 _X_EXPORT Bool noResExtension = FALSE;
 #endif
commit 4da9ec16e9725ebb9817b49e33ea1035b6aff09a
Author: Adam Jackson <ajax at redhat.com>
Date:   Fri Apr 18 19:54:09 2008 -0400

    Remove appgroup mentions from configure.ac

diff --git a/configure.ac b/configure.ac
index bbb3743..64efc4c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -544,7 +544,6 @@ AC_ARG_ENABLE(xf86misc,       AS_HELP_STRING([--disable-xf86misc], [Build XF86Mi
 AC_ARG_ENABLE(xace,           AS_HELP_STRING([--disable-xace], [Build X-ACE extension (default: enabled)]), [XACE=$enableval], [XACE=yes])
 AC_ARG_ENABLE(xselinux,       AS_HELP_STRING([--disable-xselinux], [Build SELinux extension (default: disabled)]), [XSELINUX=$enableval], [XSELINUX=no])
 AC_ARG_ENABLE(xcsecurity,     AS_HELP_STRING([--disable-xcsecurity], [Build Security extension (default: disabled)]), [XCSECURITY=$enableval], [XCSECURITY=no])
-AC_ARG_ENABLE(appgroup,       AS_HELP_STRING([--disable-appgroup], [Build XC-APPGROUP extension (default: disabled)]), [APPGROUP=$enableval], [APPGROUP=$XCSECURITY])
 AC_ARG_ENABLE(xcalibrate,     AS_HELP_STRING([--enable-xcalibrate], [Build XCalibrate extension (default: disabled)]), [XCALIBRATE=$enableval], [XCALIBRATE=no])
 AC_ARG_ENABLE(tslib,          AS_HELP_STRING([--enable-tslib], [Build kdrive tslib touchscreen support (default: disabled)]), [TSLIB=$enableval], [TSLIB=no])
 AC_ARG_ENABLE(xevie,          AS_HELP_STRING([--disable-xevie], [Build XEvIE extension (default: enabled)]), [XEVIE=$enableval], [XEVIE=yes])
@@ -930,14 +929,6 @@ if test "x$XEVIE" = xyes; then
 	REQUIRED_MODULES="$REQUIRED_MODULES evieproto"
 fi
 
-AM_CONDITIONAL(APPGROUP, [test "x$APPGROUP" = xyes])
-if test "x$APPGROUP" = xyes; then
-	if test "x$XACE" != xyes || test "x$XCSECURITY" != xyes; then
-		AC_MSG_ERROR([cannot build APPGROUP extension without X-ACE and XC-SECURITY])
-	fi
-	AC_DEFINE(XAPPGROUP, 1, [Build APPGROUP extension])
-fi
-
 AM_CONDITIONAL(CUP, [test "x$CUP" = xyes])
 if test "x$CUP" = xyes; then
 	AC_DEFINE(TOGCUP, 1, [Build TOG-CUP extension])
commit 25827fde68d3bb02a2b7e05fae53a1d97edf1f76
Author: Eric Anholt <eric at anholt.net>
Date:   Fri Apr 18 15:32:04 2008 -0700

    Nuke the MIT-SUNDRY-NONSTANDARD extension.
    
    This extension provided bug-compatibility with pre-X11R6, but has been
    stubbed out in our server since 2006 to return BadRequest when you actually
    asked for it.

diff --git a/Xext/Makefile.am b/Xext/Makefile.am
index ef2e335..9e35ae1 100644
--- a/Xext/Makefile.am
+++ b/Xext/Makefile.am
@@ -28,7 +28,6 @@ BUILTIN_SRCS =			\
 # Sources always included in libXextmodule.la & libXext.la
 MODULE_SRCS =			\
 	bigreq.c		\
-	mitmisc.c		\
 	shape.c			\
 	sync.c			\
 	xcmisc.c
diff --git a/Xext/mitmisc.c b/Xext/mitmisc.c
deleted file mode 100644
index e793d4d..0000000
--- a/Xext/mitmisc.c
+++ /dev/null
@@ -1,155 +0,0 @@
-/************************************************************
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-********************************************************/
-
-/* RANDOM CRUFT! THIS HAS NO OFFICIAL X CONSORTIUM OR X PROJECT TEAM  BLESSING */
-
-
-#define NEED_EVENTS
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include "misc.h"
-#include "os.h"
-#include "dixstruct.h"
-#include "extnsionst.h"
-#define _MITMISC_SERVER_
-#include <X11/extensions/mitmiscstr.h>
-#include "modinit.h"
-
-static void MITResetProc(
-    ExtensionEntry * /* extEntry */
-);
-
-static DISPATCH_PROC(ProcMITDispatch);
-static DISPATCH_PROC(ProcMITGetBugMode);
-static DISPATCH_PROC(ProcMITSetBugMode);
-static DISPATCH_PROC(SProcMITDispatch);
-static DISPATCH_PROC(SProcMITGetBugMode);
-static DISPATCH_PROC(SProcMITSetBugMode);
-
-void
-MITMiscExtensionInit(INITARGS)
-{
-    AddExtension(MITMISCNAME, 0, 0,
-		 ProcMITDispatch, SProcMITDispatch,
-		 MITResetProc, StandardMinorOpcode);
-}
-
-/*ARGSUSED*/
-static void
-MITResetProc (extEntry)
-ExtensionEntry	*extEntry;
-{
-}
-
-static int
-ProcMITSetBugMode(client)
-    register ClientPtr client;
-{
-    REQUEST(xMITSetBugModeReq);
-
-    REQUEST_SIZE_MATCH(xMITSetBugModeReq);
-    if (stuff->onOff != xFalse)
-        return BadRequest;
-    return(client->noClientException);
-}
-
-static int
-ProcMITGetBugMode(client)
-    register ClientPtr client;
-{
-    xMITGetBugModeReply rep;
-    register int n;
-
-    REQUEST_SIZE_MATCH(xMITGetBugModeReq);
-    rep.type = X_Reply;
-    rep.length = 0;
-    rep.sequenceNumber = client->sequence;
-    rep.onOff = FALSE;
-    if (client->swapped) {
-    	swaps(&rep.sequenceNumber, n);
-    	swapl(&rep.length, n);
-    }
-    WriteToClient(client, sizeof(xMITGetBugModeReply), (char *)&rep);
-    return(client->noClientException);
-}
-
-static int
-ProcMITDispatch (client)
-    register ClientPtr	client;
-{
-    REQUEST(xReq);
-    switch (stuff->data)
-    {
-    case X_MITSetBugMode:
-	return ProcMITSetBugMode(client);
-    case X_MITGetBugMode:
-	return ProcMITGetBugMode(client);
-    default:
-	return BadRequest;
-    }
-}
-
-static int
-SProcMITSetBugMode(client)
-    register ClientPtr	client;
-{
-    register int n;
-    REQUEST(xMITSetBugModeReq);
-
-    swaps(&stuff->length, n);
-    return ProcMITSetBugMode(client);
-}
-
-static int
-SProcMITGetBugMode(client)
-    register ClientPtr	client;
-{
-    register int n;
-    REQUEST(xMITGetBugModeReq);
-
-    swaps(&stuff->length, n);
-    return ProcMITGetBugMode(client);
-}
-
-static int
-SProcMITDispatch (client)
-    register ClientPtr	client;
-{
-    REQUEST(xReq);
-    switch (stuff->data)
-    {
-    case X_MITSetBugMode:
-	return SProcMITSetBugMode(client);
-    case X_MITGetBugMode:
-	return SProcMITGetBugMode(client);
-    default:
-	return BadRequest;
-    }
-}
diff --git a/configure.ac b/configure.ac
index ffe79f2..bbb3743 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1106,7 +1106,6 @@ if test "x$DEBUGGING" = xyes; then
 fi
 AM_CONDITIONAL(DEBUG, [test "x$DEBUGGING" = xyes])
 
-AC_DEFINE(MITMISC, 1, [Support MIT Misc extension])
 AC_DEFINE(XTEST, 1, [Support XTest extension])
 AC_DEFINE(XSYNC, 1, [Support XSync extension])
 AC_DEFINE(XCMISC, 1, [Support XCMisc extension])
diff --git a/hw/dmx/dmx-config.h b/hw/dmx/dmx-config.h
index 343fdab..df77f09 100644
--- a/hw/dmx/dmx-config.h
+++ b/hw/dmx/dmx-config.h
@@ -84,7 +84,6 @@
 #undef XFreeXDGA
 #undef XF86DRI
 #undef TOGCUP
-#undef MITMISC
 #undef SCREENSAVER
 #undef RANDR
 #undef XFIXES
diff --git a/hw/xfree86/dixmods/extmod/modinit.c b/hw/xfree86/dixmods/extmod/modinit.c
index 3b6b36a..fe499fe 100644
--- a/hw/xfree86/dixmods/extmod/modinit.c
+++ b/hw/xfree86/dixmods/extmod/modinit.c
@@ -65,15 +65,6 @@ static ExtensionModule extensionModules[] = {
 	NULL
     },
 #endif
-#ifdef MITMISC
-    {
-	MITMiscExtensionInit,
-	MITMISCNAME,
-	&noMITMiscExtension,
-	NULL,
-	NULL
-    },
-#endif
 #ifdef notyet
     {
 	XTestExtensionInit,
diff --git a/hw/xfree86/dixmods/extmod/modinit.h b/hw/xfree86/dixmods/extmod/modinit.h
index 3224850..6c87b15 100644
--- a/hw/xfree86/dixmods/extmod/modinit.h
+++ b/hw/xfree86/dixmods/extmod/modinit.h
@@ -18,12 +18,6 @@ extern void MultibufferExtensionInit(INITARGS);
 #include <X11/extensions/multibufst.h>
 #endif
 
-#ifdef MITMISC
-extern void MITMiscExtensionInit(INITARGS);
-#define _MITMISC_SERVER_
-#include <X11/extensions/mitmiscstr.h>
-#endif
-
 #ifdef XTEST
 extern void XTestExtensionInit(INITARGS);
 #define _XTEST_SERVER_
diff --git a/hw/xfree86/loader/dixsym.c b/hw/xfree86/loader/dixsym.c
index 8093a79..78a2123 100644
--- a/hw/xfree86/loader/dixsym.c
+++ b/hw/xfree86/loader/dixsym.c
@@ -370,9 +370,6 @@ _X_HIDDEN void *dixLookupTab[] = {
 #ifdef MITSHM
     SYMVAR(noMITShmExtension)
 #endif
-#ifdef MITMISC
-    SYMVAR(noMITMiscExtension)
-#endif
 #ifdef MULTIBUFFER
     SYMVAR(noMultibufferExtension)
 #endif
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index 53d1046..42d108f 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -258,9 +258,6 @@
 /* Support os-specific local connections */
 #undef LOCALCONN
 
-/* Support MIT Misc extension */
-#undef MITMISC
-
 /* Support MIT-SHM Extension */
 #undef MITSHM
 
diff --git a/include/globals.h b/include/globals.h
index cfb6c2c..62794f5 100644
--- a/include/globals.h
+++ b/include/globals.h
@@ -82,10 +82,6 @@ extern Bool noScreenSaverExtension;
 extern Bool noMITShmExtension;
 #endif
 
-#ifdef MITMISC
-extern Bool noMITMiscExtension;
-#endif
-
 #ifdef MULTIBUFFER
 extern Bool noMultibufferExtension;
 #endif
diff --git a/include/xorg-server.h.in b/include/xorg-server.h.in
index 72b4551..5a253c7 100644
--- a/include/xorg-server.h.in
+++ b/include/xorg-server.h.in
@@ -46,9 +46,6 @@
 /* Support IPv6 for TCP connections */
 #undef IPv6
 
-/* Support MIT Misc extension */
-#undef MITMISC
-
 /* Support MIT-SHM Extension */
 #undef MITSHM
 
diff --git a/mi/miinitext.c b/mi/miinitext.c
index 74ec282..d9f910c 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -142,9 +142,6 @@ extern Bool noScreenSaverExtension;
 #ifdef MITSHM
 extern Bool noMITShmExtension;
 #endif
-#ifdef MITMISC
-extern Bool noMITMiscExtension;
-#endif
 #ifdef MULTIBUFFER
 extern Bool noMultibufferExtension;
 #endif
@@ -276,9 +273,6 @@ extern void XTestExtensionInit(INITARGS);
 #ifdef BIGREQS
 extern void BigReqExtensionInit(INITARGS);
 #endif
-#ifdef MITMISC
-extern void MITMiscExtensionInit(INITARGS);
-#endif
 #ifdef XIDLE
 extern void XIdleExtensionInit(INITARGS);
 #endif
@@ -409,9 +403,6 @@ static ExtensionToggle ExtensionToggleList[] =
 #ifdef MITSHM
     { SHMNAME, &noMITShmExtension },
 #endif
-#ifdef MITMISC
-    { "MIT-SUNDRY-NONSTANDARD", &noMITMiscExtension },
-#endif
 #ifdef MULTIBUFFER
     { "Multi-Buffering", &noMultibufferExtension },
 #endif
@@ -538,9 +529,6 @@ InitExtensions(argc, argv)
 #ifdef BIGREQS
     if (!noBigReqExtension) BigReqExtensionInit();
 #endif
-#ifdef MITMISC
-    if (!noMITMiscExtension) MITMiscExtensionInit();
-#endif
 #ifdef XIDLE
     if (!noXIdleExtension) XIdleExtensionInit();
 #endif
diff --git a/os/utils.c b/os/utils.c
index 4210e5d..f394fe5 100644
--- a/os/utils.c
+++ b/os/utils.c
@@ -162,9 +162,6 @@ _X_EXPORT Bool noScreenSaverExtension = FALSE;
 #ifdef MITSHM
 _X_EXPORT Bool noMITShmExtension = FALSE;
 #endif
-#ifdef MITMISC
-_X_EXPORT Bool noMITMiscExtension = FALSE;
-#endif
 #ifdef MULTIBUFFER
 _X_EXPORT Bool noMultibufferExtension = FALSE;
 #endif
commit 13adef8a17d8815f4db2aaac30ae04438e125343
Author: Adam Jackson <ajax at redhat.com>
Date:   Fri Apr 18 19:01:06 2008 -0400

    Finish deleting EVI

diff --git a/Xext/EVI.c b/Xext/EVI.c
deleted file mode 100644
index a637bae..0000000
--- a/Xext/EVI.c
+++ /dev/null
@@ -1,200 +0,0 @@
-/************************************************************
-Copyright (c) 1997 by Silicon Graphics Computer Systems, Inc.
-Permission to use, copy, modify, and distribute this
-software and its documentation for any purpose and without
-fee is hereby granted, provided that the above copyright
-notice appear in all copies and that both that copyright
-notice and this permission notice appear in supporting
-documentation, and that the name of Silicon Graphics not be
-used in advertising or publicity pertaining to distribution
-of the software without specific prior written permission.
-Silicon Graphics makes no representation about the suitability
-of this software for any purpose. It is provided "as is"
-without any express or implied warranty.
-SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
-SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
-GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
-DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
-DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
-THE USE OR PERFORMANCE OF THIS SOFTWARE.
-********************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include "dixstruct.h"
-#include "extnsionst.h"
-#include "dix.h"
-#define _XEVI_SERVER_
-#include <X11/extensions/XEVIstr.h>
-#include "EVIstruct.h"
-#include "modinit.h"
-#include "scrnintstr.h"
-
-static EviPrivPtr eviPriv;
-
-static int
-ProcEVIQueryVersion(ClientPtr client)
-{
-    /* REQUEST(xEVIQueryVersionReq); */
-    xEVIQueryVersionReply rep;
-    register int n;
-    REQUEST_SIZE_MATCH (xEVIQueryVersionReq);
-    rep.type = X_Reply;
-    rep.length = 0;
-    rep.sequenceNumber = client->sequence;
-    rep.majorVersion = XEVI_MAJOR_VERSION;
-    rep.minorVersion = XEVI_MAJOR_VERSION;
-    if (client->swapped) {
-    	swaps(&rep.sequenceNumber, n);
-    	swapl(&rep.length, n);
-	swaps(&rep.majorVersion, n);
-	swaps(&rep.minorVersion, n);
-    }
-    WriteToClient(client, sizeof (xEVIQueryVersionReply), (char *)&rep);
-    return (client->noClientException);
-}
-#define swapEviInfo(eviInfo, l)				\
-{							\
-   int l1 = l; 						\
-   xExtendedVisualInfo *eviInfo1 = eviInfo;		\
-   while (l1-- > 0) {					\
-       swapl(&eviInfo1->core_visual_id, n);		\
-       swapl(&eviInfo1->transparency_value, n);		\
-       swaps(&eviInfo1->num_colormap_conflicts, n);	\
-       eviInfo1++;					\
-   }							\
-}
-#define swapVisual(visual, l)				\
-{							\
-    int l1 = l;						\
-    VisualID32 *visual1 = visual;				\
-    while (l1-- > 0) {					\
-       swapl(visual1, n);				\
-       visual1++;					\
-    }							\
-}
-
-static int
-ProcEVIGetVisualInfo(ClientPtr client)
-{
-    REQUEST(xEVIGetVisualInfoReq);
-    xEVIGetVisualInfoReply rep;
-    int i, n, n_conflict, n_info, sz_info, sz_conflict;
-    VisualID32 *conflict;
-    unsigned int total_visuals = 0;
-    xExtendedVisualInfo *eviInfo;
-    int status;
-
-    /*
-     * do this first, otherwise REQUEST_FIXED_SIZE can overflow.  we assume
-     * here that you don't have more than 2^32 visuals over all your screens;
-     * this seems like a safe assumption.
-     */
-    for (i = 0; i < screenInfo.numScreens; i++)
-	total_visuals += screenInfo.screens[i]->numVisuals;
-    if (stuff->n_visual > total_visuals)
-	return BadValue;
-
-    REQUEST_FIXED_SIZE(xEVIGetVisualInfoReq, stuff->n_visual * sz_VisualID32);
-    status = eviPriv->getVisualInfo((VisualID32 *)&stuff[1], (int)stuff->n_visual,
-		&eviInfo, &n_info, &conflict, &n_conflict);
-    if (status != Success)
-	return status;
-    sz_info = n_info * sz_xExtendedVisualInfo;
-    sz_conflict = n_conflict * sz_VisualID32;
-    rep.type = X_Reply;
-    rep.n_info = n_info;
-    rep.n_conflicts = n_conflict;
-    rep.sequenceNumber = client->sequence;
-    rep.length = (sz_info + sz_conflict) >> 2;
-    if (client->swapped) {
-    	swaps(&rep.sequenceNumber, n);
-    	swapl(&rep.length, n);
-    	swapl(&rep.n_info, n);
-    	swapl(&rep.n_conflicts, n);
-	swapEviInfo(eviInfo, n_info);
-	swapVisual(conflict, n_conflict);
-    }
-    WriteToClient(client, sz_xEVIGetVisualInfoReply, (char *)&rep);
-    WriteToClient(client, sz_info, (char *)eviInfo);
-    WriteToClient(client, sz_conflict, (char *)conflict);
-    eviPriv->freeVisualInfo(eviInfo, conflict);
-    return (client->noClientException);
-}
-
-static int
-ProcEVIDispatch(ClientPtr client)
-{
-    REQUEST(xReq);
-    switch (stuff->data) {
-    case X_EVIQueryVersion:
-	return ProcEVIQueryVersion (client);
-    case X_EVIGetVisualInfo:
-	return ProcEVIGetVisualInfo (client);
-    default:
-	return BadRequest;
-    }
-}
-
-static int
-SProcEVIQueryVersion(ClientPtr client)
-{
-   REQUEST(xEVIQueryVersionReq);
-   int n;
-   swaps(&stuff->length, n);
-   return ProcEVIQueryVersion(client);
-}
-
-static int
-SProcEVIGetVisualInfo(ClientPtr client)
-{
-    register int n;
-    REQUEST(xEVIGetVisualInfoReq);
-    swaps(&stuff->length, n);
-    return ProcEVIGetVisualInfo(client);
-}
-
-static int
-SProcEVIDispatch(ClientPtr client)
-{
-    REQUEST(xReq);
-    switch (stuff->data)
-    {
-    case X_EVIQueryVersion:
-	return SProcEVIQueryVersion (client);
-    case X_EVIGetVisualInfo:
-	return SProcEVIGetVisualInfo (client);
-    default:
-	return BadRequest;
-    }
-}
-
-/*ARGSUSED*/
-static void
-EVIResetProc(ExtensionEntry *extEntry)
-{
-    eviDDXReset();
-}
-
-/****************
- * XEVIExtensionInit
- *
- * Called from InitExtensions in main() or from QueryExtension() if the
- * extension is dynamically loaded.
- *
- ****************/
-void
-EVIExtensionInit(INITARGS)
-{
-    if (AddExtension(EVINAME, 0, 0,
-		     ProcEVIDispatch, SProcEVIDispatch,
-		     EVIResetProc, StandardMinorOpcode)) {
-	eviPriv = eviDDXInit();
-    }
-}
diff --git a/Xext/sampleEVI.c b/Xext/sampleEVI.c
deleted file mode 100644
index b871bfd..0000000
--- a/Xext/sampleEVI.c
+++ /dev/null
@@ -1,123 +0,0 @@
-/************************************************************
-Copyright (c) 1997 by Silicon Graphics Computer Systems, Inc.
-Permission to use, copy, modify, and distribute this
-software and its documentation for any purpose and without
-fee is hereby granted, provided that the above copyright
-notice appear in all copies and that both that copyright
-notice and this permission notice appear in supporting
-documentation, and that the name of Silicon Graphics not be
-used in advertising or publicity pertaining to distribution
-of the software without specific prior written permission.
-Silicon Graphics makes no representation about the suitability
-of this software for any purpose. It is provided "as is"
-without any express or implied warranty.
-SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
-SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
-GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
-DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
-DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
-THE USE OR PERFORMANCE OF THIS SOFTWARE.
-********************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include "dixstruct.h"
-#include "extnsionst.h"
-#include "dix.h"
-#define _XEVI_SERVER_
-#include <X11/extensions/XEVIstr.h>
-#include "EVIstruct.h"
-#include "scrnintstr.h"
-
-#if HAVE_STDINT_H
-#include <stdint.h>
-#elif !defined(UINT32_MAX)
-#define UINT32_MAX 0xffffffffU
-#endif
-
-static int sampleGetVisualInfo(
-    VisualID32 *visual,
-    int n_visual,
-    xExtendedVisualInfo **evi_rn,
-    int *n_info_rn,
-    VisualID32 **conflict_rn,
-    int *n_conflict_rn)
-{
-    unsigned int max_sz_evi;
-    VisualID32 *temp_conflict;
-    xExtendedVisualInfo *evi;
-    unsigned int max_visuals = 0, max_sz_conflict, sz_conflict = 0;
-    register int visualI, scrI, sz_evi = 0, conflictI, n_conflict;
-
-    if (n_visual > UINT32_MAX/(sz_xExtendedVisualInfo * screenInfo.numScreens))
-	return BadAlloc;
-    max_sz_evi = n_visual * sz_xExtendedVisualInfo * screenInfo.numScreens;
-    
-    for (scrI = 0; scrI < screenInfo.numScreens; scrI++) {
-        if (screenInfo.screens[scrI]->numVisuals > max_visuals)
-            max_visuals = screenInfo.screens[scrI]->numVisuals;
-    }
-
-    if (n_visual > UINT32_MAX/(sz_VisualID32 * screenInfo.numScreens 
-			       * max_visuals)) 
-	return BadAlloc;
-    max_sz_conflict = n_visual * sz_VisualID32 * screenInfo.numScreens * max_visuals;
-
-    *evi_rn = evi = (xExtendedVisualInfo *)xalloc(max_sz_evi);
-    if (!*evi_rn)
-         return BadAlloc;
-
-    temp_conflict = (VisualID32 *)xalloc(max_sz_conflict);
-    if (!temp_conflict) {
-        xfree(*evi_rn);
-        return BadAlloc;
-    }
-
-    for (scrI = 0; scrI < screenInfo.numScreens; scrI++) {
-        for (visualI = 0; visualI < n_visual; visualI++) {
-	    evi[sz_evi].core_visual_id = visual[visualI];
-	    evi[sz_evi].screen = scrI;
-	    evi[sz_evi].level = 0;
-	    evi[sz_evi].transparency_type = XEVI_TRANSPARENCY_NONE;
-	    evi[sz_evi].transparency_value = 0;
-	    evi[sz_evi].min_hw_colormaps = 1;
-	    evi[sz_evi].max_hw_colormaps = 1;
-	    evi[sz_evi].num_colormap_conflicts = n_conflict = 0;
-	    for (conflictI = 0; conflictI < n_conflict; conflictI++)
-		temp_conflict[sz_conflict++] = visual[visualI];
-	    sz_evi++;
-	}
-    }
-    *conflict_rn = temp_conflict;
-    *n_conflict_rn = sz_conflict;
-    *n_info_rn = sz_evi;
-    return Success;
-}
-
-static void sampleFreeVisualInfo(
-    xExtendedVisualInfo *evi,
-    VisualID32 *conflict)
-{
-    if (evi)
-        xfree(evi);
-    if (conflict)
-    	xfree(conflict);
-}
-
-EviPrivPtr eviDDXInit(void)
-{
-    static EviPrivRec eviPriv;
-    eviPriv.getVisualInfo = sampleGetVisualInfo;
-    eviPriv.freeVisualInfo = sampleFreeVisualInfo;
-    return &eviPriv;
-}
-
-void eviDDXReset(void)
-{
-}
commit eafaf40fb3368ca7e4cf48336fdb7a6c9f536bfa
Author: Adam Jackson <ajax at redhat.com>
Date:   Fri Apr 18 18:50:05 2008 -0400

    Death to APPGROUP.

diff --git a/Xext/Makefile.am b/Xext/Makefile.am
index 4a2925f..ef2e335 100644
--- a/Xext/Makefile.am
+++ b/Xext/Makefile.am
@@ -105,12 +105,6 @@ if XPRINT
 BUILTIN_SRCS += $(XPRINT_SRCS)
 endif
 
-# AppGroup
-APPGROUP_SRCS = appgroup.c appgroup.h
-if APPGROUP
-BUILTIN_SRCS += $(APPGROUP_SRCS)
-endif
-
 # Colormap Utilization Protocol: Less flashing when switching between
 # PsuedoColor apps and better sharing of limited colormap slots
 CUP_SRCS = cup.c
@@ -164,7 +158,6 @@ EXTRA_DIST = \
 	$(XINERAMA_SRCS) \
 	$(XEVIE_SRCS) \
 	$(XPRINT_SRCS) \
-	$(APPGROUP_SRCS) \
 	$(CUP_SRCS) \
 	$(MULTIBUFFER_SRCS) \
 	$(EXTRA_MULTIBUFFER_SRCS) \
diff --git a/Xext/appgroup.c b/Xext/appgroup.c
deleted file mode 100644
index c40782d..0000000
--- a/Xext/appgroup.c
+++ /dev/null
@@ -1,775 +0,0 @@
-/*
-Copyright 1996, 1998, 2001  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
-OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall
-not be used in advertising or otherwise to promote the sale, use or
-other dealings in this Software without prior written authorization
-from The Open Group.
-*/
-
-#define NEED_REPLIES
-#define NEED_EVENTS
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include "misc.h"
-#include "dixstruct.h"
-#include "extnsionst.h"
-#include "scrnintstr.h"
-#include "windowstr.h"
-#include "colormapst.h"
-#include "servermd.h"
-#define _XAG_SERVER_
-#include <X11/extensions/Xagstr.h>
-#include "xacestr.h"
-#include "securitysrv.h"
-#include <X11/Xfuncproto.h>
-
-#define XSERV_t
-#include <X11/Xtrans/Xtrans.h>
-#include "../os/osdep.h"
-
-#include <stdio.h>
-
-#include "modinit.h"
-#include "appgroup.h"
-
-typedef struct _AppGroupRec {
-    struct _AppGroupRec* next;
-    XID			appgroupId;
-    ClientPtr*		clients;
-    int			nclients;
-    ClientPtr		leader;
-    Bool		single_screen;
-    Window		default_root;
-    VisualID		root_visual;
-    Colormap		default_colormap;    
-    Pixel		black_pixel;
-    Pixel		white_pixel;
-    xConnSetupPrefix	connSetupPrefix;
-    char*		ConnectionInfo;
-} AppGroupRec, *AppGroupPtr;
-
-static int		ProcXagDispatch(ClientPtr client);
-static int              SProcXagDispatch(ClientPtr client);
-static void		XagResetProc(ExtensionEntry* extEntry);
-
-static int		XagCallbackRefCount = 0;
-
-static RESTYPE		RT_APPGROUP;
-static AppGroupPtr	appGrpList = NULL;
-
-extern xConnSetupPrefix connSetupPrefix;
-extern char* ConnectionInfo;
-extern int connBlockScreenStart;
-
-static 
-int XagAppGroupFree(
-    pointer what,
-    XID id) /* unused */
-{
-    int i;
-    AppGroupPtr pAppGrp = (AppGroupPtr) what;
-
-    if (pAppGrp->leader)
-	for (i = 0; i < pAppGrp->nclients; i++) {
-	    if (pAppGrp->clients[i] == NULL) continue;
-	    CloseDownClient (pAppGrp->clients[i]);
-	}
-
-    if (pAppGrp == appGrpList)
-	appGrpList = appGrpList->next;
-    else {
-	AppGroupPtr tpAppGrp;
-	for (tpAppGrp = appGrpList; 
-	    tpAppGrp->next != NULL; 
-	    tpAppGrp = tpAppGrp->next) {
-	    if (tpAppGrp->next == pAppGrp) {
-		tpAppGrp->next = tpAppGrp->next->next;
-		break;
-	    }
-	}
-    }
-    (void) xfree (pAppGrp->clients);
-    (void) xfree (pAppGrp->ConnectionInfo);
-    (void) xfree (what);
-    return Success;
-}
-
-static void XagClientStateChange(
-    CallbackListPtr* pcbl,
-    pointer nulldata,
-    pointer calldata)
-{
-    NewClientInfoRec* pci = (NewClientInfoRec*) calldata;
-    ClientPtr pClient = pci->client;
-    AppGroupPtr pAppGrp = pClient->appgroup;
-    int slot;
-
-    if (!pAppGrp)
-	return;
-
-    switch (pClient->clientState) {
-    case ClientStateAuthenticating:
-    case ClientStateRunning: 
-    case ClientStateCheckingSecurity:
-	break;
-
-    case ClientStateInitial: 
-    case ClientStateCheckedSecurity:
-	slot = -1;
-	/* see the comment above about Initial vs. CheckedSecurity */
-	if (pAppGrp->nclients != 0) {
-	    /* if this client already in AppGroup, don't add it again */
-	    int i;
-	    for (i = 0; i < pAppGrp->nclients; i++)
-		if (pClient == pAppGrp->clients[i]) return;
-		if (slot == -1 && pAppGrp->clients[i] == NULL)
-			slot = i;
-	}
-	if (slot == -1) {
-	    slot = pAppGrp->nclients++;
-	    pAppGrp->clients = (ClientPtr*) xrealloc (pAppGrp->clients, 
-				pAppGrp->nclients * sizeof (ClientPtr));
-	}
-	pAppGrp->clients[slot] = pClient;
-	pClient->appgroup = pAppGrp;
-	break;
-
-    case ClientStateGone:
-    case ClientStateRetained: /* client disconnected, dump it */
-	{
-	    int i;
-	    for (i = 0; i < pAppGrp->nclients; i++)
-		if (pAppGrp->clients[i] == pClient) {
-		    pAppGrp->clients[i] = NULL;
-		    break;
-		}
-	}
-	pClient->appgroup = NULL; /* redundant, pClient will be freed */
-	break;
-    }
-}
-
-/*ARGSUSED*/
-static 
-void XagResetProc(
-    ExtensionEntry* extEntry)
-{
-    DeleteCallback (&ClientStateCallback, XagClientStateChange, NULL);
-    XagCallbackRefCount = 0;
-    while (appGrpList) XagAppGroupFree ((pointer) appGrpList, 0);
-}
-
-static 
-int ProcXagQueryVersion(
-    register ClientPtr client)
-{
-    /* REQUEST (xXagQueryVersionReq); */
-    xXagQueryVersionReply rep;
-    register int n;
-
-    REQUEST_SIZE_MATCH (xXagQueryVersionReq);
-    rep.type = X_Reply;
-    rep.length = 0;
-    rep.sequence_number = client->sequence;
-    rep.server_major_version = XAG_MAJOR_VERSION;
-    rep.server_minor_version = XAG_MINOR_VERSION;
-    if (client->swapped) {
-    	swaps (&rep.sequence_number, n);
-    	swapl (&rep.length, n);
-    	swaps (&rep.server_major_version, n);
-    	swaps (&rep.server_minor_version, n);
-    }
-    WriteToClient (client, sizeof (xXagQueryVersionReply), (char *)&rep);
-    return client->noClientException;
-}
-
-static 
-void ProcessAttr(
-    AppGroupPtr pAppGrp,
-    ClientPtr client,
-    unsigned int attrib_mask,
-    CARD32* attribs)
-{
-    int i;
-
-    for (i = 0; i <= XagNappGroupLeader; i++) {
-	switch (attrib_mask & (1 << i)) {
-	case XagSingleScreenMask:
-	    pAppGrp->single_screen = *attribs;
-	    break;
-	case XagDefaultRootMask:
-	    pAppGrp->default_root = *attribs;
-	    break;
-	case XagRootVisualMask:
-	    pAppGrp->root_visual = *attribs;
-	    break;
-	case XagDefaultColormapMask:
-	    pAppGrp->default_colormap = *attribs;
-	    break;
-	case XagBlackPixelMask:
-	    pAppGrp->black_pixel = *attribs;
-	    break;
-	case XagWhitePixelMask:
-	    pAppGrp->white_pixel = *attribs;
-	    break;
-	case XagAppGroupLeaderMask:
-	    pAppGrp->leader = client;
-	    break;
-	default: continue;
-	}
-	attribs++;
-    }
-}
-
-static 
-void CreateConnectionInfo(
-    AppGroupPtr pAppGrp)
-{
-    xWindowRoot* rootp;
-    xWindowRoot* roots[MAXSCREENS];
-    unsigned int rootlens[MAXSCREENS];
-    xDepth* depth;
-    int olen;
-    int snum, i;
-
-    rootp = (xWindowRoot*) (ConnectionInfo + connBlockScreenStart);
-    for (snum = 0; snum < screenInfo.numScreens; snum++) {
-
-	rootlens[snum] = sizeof (xWindowRoot);
-	roots[snum] = rootp;
-
-	depth = (xDepth*) (rootp + 1);
-	for (i = 0; i < rootp->nDepths; i++) {
-	    rootlens[snum] += sizeof (xDepth) + 
-			      depth->nVisuals * sizeof (xVisualType);
-	    depth = (xDepth *)(((char*)(depth + 1)) +
-		depth->nVisuals * sizeof (xVisualType));
-	}
-	rootp = (xWindowRoot*) depth;
-    }
-    snum = 0;
-    if (pAppGrp->default_root) {
-	for (; snum < screenInfo.numVideoScreens; snum++) {
-	    if (roots[snum]->windowId == pAppGrp->default_root)
-		break;
-        }
-    }
-    olen = connBlockScreenStart + rootlens[snum];
-    for (i = screenInfo.numVideoScreens; i < screenInfo.numScreens; i++)
-	olen += rootlens[i];
-    pAppGrp->ConnectionInfo = (char*) xalloc (olen);
-    if (!pAppGrp->ConnectionInfo)
-	return;
-    memmove (pAppGrp->ConnectionInfo, ConnectionInfo, connBlockScreenStart);
-    ((xConnSetup*) (pAppGrp->ConnectionInfo))->numRoots = 
-	1 + screenInfo.numScreens - screenInfo.numVideoScreens;
-    memmove (pAppGrp->ConnectionInfo + connBlockScreenStart,
-	     (void*) roots[snum], rootlens[snum]);
-    rootp = (xWindowRoot*) (pAppGrp->ConnectionInfo + connBlockScreenStart);
-    if (pAppGrp->default_colormap) {
-	rootp->defaultColormap = pAppGrp->default_colormap;
-	rootp->whitePixel = pAppGrp->white_pixel;
-	rootp->blackPixel = pAppGrp->black_pixel;
-    }
-    if (pAppGrp->root_visual)
-	rootp->rootVisualID = pAppGrp->root_visual;
-    rootp = (xWindowRoot*) (((char*)rootp) + rootlens[snum]);
-    for (i = screenInfo.numVideoScreens; i < screenInfo.numScreens; i++) {
-	memmove ((void*) rootp, (void*) roots[i], rootlens[i]);
-	rootp = (xWindowRoot*) (((char*) rootp) + rootlens[i]);
-    }
-    pAppGrp->connSetupPrefix = connSetupPrefix;
-    pAppGrp->connSetupPrefix.length = olen >> 2;
-}
-
-static 
-AppGroupPtr CreateAppGroup(
-    ClientPtr client,
-    XID appgroupId,
-    unsigned int attrib_mask,
-    CARD32* attribs)
-{
-    AppGroupPtr pAppGrp;
-
-    pAppGrp = (AppGroupPtr) xalloc (sizeof(AppGroupRec));
-    if (pAppGrp) {
-	pAppGrp->next = appGrpList;
-	appGrpList = pAppGrp;
-	pAppGrp->appgroupId = appgroupId;
-	pAppGrp->clients = (ClientPtr*) xalloc (0);
-	pAppGrp->nclients = 0;
-	pAppGrp->leader = NULL;
-	pAppGrp->default_root = 0;
-	pAppGrp->root_visual = 0;
-	pAppGrp->default_colormap = 0;
-	pAppGrp->black_pixel = -1;
-	pAppGrp->white_pixel = -1;
-	pAppGrp->ConnectionInfo = NULL;
-	ProcessAttr (pAppGrp, client, attrib_mask, attribs);
-    }
-    return pAppGrp;
-}
-
-static 
-int AttrValidate(
-    ClientPtr client,
-    int attrib_mask,
-    AppGroupPtr pAppGrp)
-{
-    WindowPtr pWin;
-    int idepth, ivids, found, rc;
-    ScreenPtr pScreen;
-    DepthPtr pDepth;
-    ColormapPtr pColormap;
-
-    rc = dixLookupWindow(&pWin, pAppGrp->default_root, client,
-			 DixGetAttrAccess);
-    if (rc != Success)
-	return rc;
-    pScreen = pWin->drawable.pScreen;
-    if (WindowTable[pScreen->myNum]->drawable.id != pAppGrp->default_root)
-	return BadWindow;
-    pDepth = pScreen->allowedDepths;
-    if (pAppGrp->root_visual) {
-	found = FALSE;
-	for (idepth = 0; idepth < pScreen->numDepths; idepth++, pDepth++) {
-	    for (ivids = 0; ivids < pDepth->numVids; ivids++) {
-		if (pAppGrp->root_visual == pDepth->vids[ivids]) {
-		    found = TRUE;
-		    break;
-		}
-	    }
-	}
-	if (!found)
-	    return BadMatch;
-    }
-    if (pAppGrp->default_colormap) {
-
-	rc = dixLookupResource((pointer *)&pColormap, pAppGrp->default_colormap,
-			       RT_COLORMAP, client, DixUseAccess);
-	if (rc != Success)
-	    return rc;
-	if (pColormap->pScreen != pScreen)
-	    return BadColor;
-	if (pColormap->pVisual->vid != (pAppGrp->root_visual ? pAppGrp->root_visual : pScreen->rootVisual))
-	    return BadMatch;
-    }
-    return client->noClientException;
-}
-
-static int ProcXagCreate (
-    register ClientPtr client)
-{
-    REQUEST (xXagCreateReq);
-    AppGroupPtr pAppGrp;
-    int ret;
-
-    REQUEST_AT_LEAST_SIZE (xXagCreateReq);
-
-    LEGAL_NEW_RESOURCE (stuff->app_group, client);
-    pAppGrp = CreateAppGroup (client, stuff->app_group, 
-		stuff->attrib_mask, (CARD32*) &stuff[1]);
-    if (!pAppGrp)
-	return BadAlloc;
-    ret = AttrValidate (client, stuff->attrib_mask, pAppGrp);
-    if (ret != Success) {
-	XagAppGroupFree ((pointer)pAppGrp, (XID)0);
-	return ret;
-    }
-    if (pAppGrp->single_screen) {
-	CreateConnectionInfo (pAppGrp);
-	if (!pAppGrp->ConnectionInfo)
-	    return BadAlloc;
-    }
-    if (!AddResource (stuff->app_group, RT_APPGROUP, (pointer)pAppGrp))
-	return BadAlloc;
-    if (XagCallbackRefCount++ == 0)
-	(void) AddCallback (&ClientStateCallback, XagClientStateChange, NULL);
-    return client->noClientException;
-}
-
-static int ProcXagDestroy(
-    register ClientPtr client)
-{
-    AppGroupPtr pAppGrp;
-    REQUEST (xXagDestroyReq);
-
-    REQUEST_SIZE_MATCH (xXagDestroyReq);
-    pAppGrp = (AppGroupPtr)SecurityLookupIDByType (client, 
-		(XID)stuff->app_group, RT_APPGROUP, DixReadAccess);
-    if (!pAppGrp) return XagBadAppGroup;
-    FreeResource ((XID)stuff->app_group, RT_NONE);
-    if (--XagCallbackRefCount == 0)
-	(void) DeleteCallback (&ClientStateCallback, XagClientStateChange, NULL);
-    return client->noClientException;
-}
-
-static 
-int ProcXagGetAttr(
-    register ClientPtr client)
-{
-    AppGroupPtr pAppGrp;
-    REQUEST (xXagGetAttrReq);
-    xXagGetAttrReply rep;
-    int n;
-
-    REQUEST_SIZE_MATCH (xXagGetAttrReq);
-    pAppGrp = (AppGroupPtr)SecurityLookupIDByType (client, 
-		(XID)stuff->app_group, RT_APPGROUP, DixReadAccess);
-    if (!pAppGrp) return XagBadAppGroup;
-    rep.type = X_Reply;
-    rep.length = 0;
-    rep.sequence_number = client->sequence;
-    rep.default_root = pAppGrp->default_root;
-    rep.root_visual = pAppGrp->root_visual;
-    rep.default_colormap = pAppGrp->default_colormap;
-    rep.black_pixel = pAppGrp->black_pixel;
-    rep.white_pixel = pAppGrp->white_pixel;
-    rep.single_screen = pAppGrp->single_screen;
-    rep.app_group_leader = (pAppGrp->leader) ? 1 : 0;
-    if (client->swapped) {
-    	swaps (&rep.sequence_number, n);
-    	swapl (&rep.length, n);
-    	swapl (&rep.default_root, n);
-    	swapl (&rep.root_visual, n);
-    	swapl (&rep.default_colormap, n);
-    	swapl (&rep.black_pixel, n);
-    	swapl (&rep.white_pixel, n);
-    }
-    WriteToClient (client, sizeof (xXagGetAttrReply), (char *)&rep);
-    return client->noClientException;
-}
-
-static 
-int ProcXagQuery(
-    register ClientPtr client)
-{
-    ClientPtr pClient;
-    AppGroupPtr pAppGrp;
-    REQUEST (xXagQueryReq);
-    int n, rc;
-
-    REQUEST_SIZE_MATCH (xXagQueryReq);
-    rc = dixLookupClient(&pClient, stuff->resource, client, DixGetAttrAccess);
-    if (rc != Success)
-	return rc;
-
-    for (pAppGrp = appGrpList; pAppGrp != NULL; pAppGrp = pAppGrp->next)
-	for (n = 0; n < pAppGrp->nclients; n++)
-	    if (pAppGrp->clients[n] == pClient) {
-		xXagQueryReply rep;
-
-		rep.type = X_Reply;
-		rep.length = 0;
-		rep.sequence_number = client->sequence;
-		rep.app_group = pAppGrp->appgroupId;
-		if (client->swapped) {
-		    swaps (&rep.sequence_number, n);
-		    swapl (&rep.length, n);
-		    swapl (&rep.app_group, n);
-		}
-		WriteToClient (client, sizeof (xXagQueryReply), (char *)&rep);
-		return client->noClientException;
-	    }
-
-    return BadMatch;
-}
-
-static 
-int ProcXagCreateAssoc(
-    register ClientPtr client)
-{
-    REQUEST (xXagCreateAssocReq);
-
-    REQUEST_SIZE_MATCH (xXagCreateAssocReq);
-#ifdef WIN32
-    if (stuff->window_type != XagWindowTypeWin32)
-#else
-    if (stuff->window_type != XagWindowTypeX11)
-#endif
-	return BadMatch;
-#if defined(WIN32) || defined(__CYGWIN__) /* and Mac, etc */
-    if (!LocalClient (client))
-	return BadAccess;
-#endif
-
-/* Macintosh, OS/2, and MS-Windows servers have some work to do here */
-
-    return client->noClientException;
-}
-
-static 
-int ProcXagDestroyAssoc(
-    register ClientPtr client)
-{
-    /* REQUEST (xXagDestroyAssocReq); */
-
-    REQUEST_SIZE_MATCH (xXagDestroyAssocReq);
-/* Macintosh, OS/2, and MS-Windows servers have some work to do here */
-    return client->noClientException;
-}
-
-static 
-int ProcXagDispatch (
-    register ClientPtr client)
-{
-    REQUEST (xReq);
-    switch (stuff->data)
-    {
-    case X_XagQueryVersion:
-	return ProcXagQueryVersion (client);
-    case X_XagCreate:
-	return ProcXagCreate (client);
-    case X_XagDestroy:
-	return ProcXagDestroy (client);
-    case X_XagGetAttr:
-	return ProcXagGetAttr (client);
-    case X_XagQuery:
-	return ProcXagQuery (client);
-    case X_XagCreateAssoc:
-	return ProcXagCreateAssoc (client);
-    case X_XagDestroyAssoc:
-	return ProcXagDestroyAssoc (client);
-    default:
-	return BadRequest;
-    }
-}
-
-static 
-int SProcXagQueryVersion(
-    register ClientPtr client)
-{
-    register int n;
-    REQUEST(xXagQueryVersionReq);
-    swaps(&stuff->length, n);
-    return ProcXagQueryVersion(client);
-}
-
-static 
-int SProcXagCreate(
-    ClientPtr client)
-{
-    register int n;
-    REQUEST (xXagCreateReq);
-    swaps (&stuff->length, n);
-    REQUEST_AT_LEAST_SIZE (xXagCreateReq);
-    swapl (&stuff->app_group, n);
-    swapl (&stuff->attrib_mask, n);
-    SwapRestL (stuff);
-    return ProcXagCreate (client);
-}
-
-static 
-int SProcXagDestroy(
-    ClientPtr client)
-{
-    register int n;
-    REQUEST (xXagDestroyReq);
-    swaps (&stuff->length, n);
-    REQUEST_SIZE_MATCH (xXagDestroyReq);
-    swapl (&stuff->app_group, n);
-    return ProcXagDestroy (client);
-}
-
-static 
-int SProcXagGetAttr(
-    ClientPtr client)
-{
-    register int n;
-    REQUEST (xXagGetAttrReq);
-    swaps (&stuff->length, n);
-    REQUEST_SIZE_MATCH (xXagGetAttrReq);
-    swapl (&stuff->app_group, n);
-    return ProcXagGetAttr (client);
-}
-
-static 
-int SProcXagQuery(
-    ClientPtr client)
-{
-    register int n;
-    REQUEST (xXagQueryReq);
-    swaps (&stuff->length, n);
-    REQUEST_SIZE_MATCH (xXagQueryReq);
-    swapl (&stuff->resource, n);
-    return ProcXagQuery (client);
-}
-
-static 
-int SProcXagCreateAssoc(
-    ClientPtr client)
-{
-    register int n;
-    REQUEST (xXagCreateAssocReq);
-    swaps (&stuff->length, n);
-    REQUEST_SIZE_MATCH (xXagCreateAssocReq);
-    swapl (&stuff->window, n);
-    swapl (&stuff->window_type, n);
-    swaps (&stuff->system_window_len, n);
-    return ProcXagCreateAssoc (client);
-}
-
-static 
-int SProcXagDestroyAssoc(
-    ClientPtr client)
-{
-    register int n;
-    REQUEST (xXagDestroyAssocReq);
-    swaps (&stuff->length, n);
-    REQUEST_SIZE_MATCH (xXagDestroyAssocReq);
-    swapl (&stuff->window, n);
-    return ProcXagDestroyAssoc (client);
-}
-
-static 
-int SProcXagDispatch(
-    register ClientPtr client)
-{
-    REQUEST(xReq);
-    switch (stuff->data)
-    {
-    case X_XagQueryVersion:
-	return SProcXagQueryVersion (client);
-    case X_XagCreate:
-	return SProcXagCreate (client);
-    case X_XagDestroy:
-	return SProcXagDestroy (client);
-    case X_XagGetAttr:
-	return SProcXagGetAttr (client);
-    case X_XagQuery:
-	return SProcXagQuery (client);
-    case X_XagCreateAssoc:
-	return SProcXagCreateAssoc (client);
-    case X_XagDestroyAssoc:
-	return SProcXagDestroyAssoc (client);
-    default:
-	return BadRequest;
-    }
-}
-
-Colormap XagDefaultColormap(
-    ClientPtr client)
-{
-    return (client->appgroup ? client->appgroup->default_colormap : None);
-}
-
-VisualID XagRootVisual(
-    ClientPtr client)
-{
-    return (client->appgroup ? client->appgroup->root_visual : 0);
-}
-
-ClientPtr XagLeader(
-    ClientPtr client)
-{
-    return (client->appgroup ? client->appgroup->leader : NULL);
-}
-
-/*
- * Return whether the Map request event should be sent to the appgroup leader.
- * We don't want to send it to the leader when the window is on a different
- * screen, e.g. a print screen.
- */
-Bool XagIsControlledRoot(
-    ClientPtr client,
-    WindowPtr pParent)
-{
-    if (client->appgroup) {
-	if (client->appgroup->single_screen && 
-	    pParent->drawable.id == client->appgroup->default_root)
-	    return TRUE;
-	else if (!pParent->parent)
-	    return TRUE;
-	else
-	    return FALSE;
-    }
-    return FALSE; 
-}
-
-void XagConnectionInfo(
-    ClientPtr client,
-    xConnSetupPrefix** conn_prefix,
-    char** conn_info,
-    int* num_screen)
-{
-    if (client->appgroup && client->appgroup->ConnectionInfo) {
-	*conn_prefix = &client->appgroup->connSetupPrefix;
-	*conn_info = client->appgroup->ConnectionInfo;
-	*num_screen = ((xConnSetup*)(client->appgroup->ConnectionInfo))->numRoots;
-    } 
-}
-
-XID XagId(
-    ClientPtr client)
-{
-    return (client->appgroup ? client->appgroup->appgroupId : 0);
-}
-
-static void XagCallClientStateChange(
-    CallbackListPtr *pcbl,
-    pointer nulldata,
-    pointer calldata)
-{
-    XaceAuthAvailRec* rec = (XaceAuthAvailRec*) calldata;
-    ClientPtr pClient = rec->client;
-
-    if (!pClient->appgroup) {
-	SecurityAuthorizationPtr pAuth;
-	XID authId = rec->authId;
-
-	/* can't use SecurityLookupIDByType here -- client
-	 * security state hasn't been setup yet.
-	 */
-	pAuth = (SecurityAuthorizationPtr)LookupIDByType(authId,
-				SecurityAuthorizationResType);
-	if (!pAuth)
-	    return;
-
-	pClient->appgroup = (AppGroupPtr)LookupIDByType(pAuth->group,
-							RT_APPGROUP);
-    }
-
-    if (pClient->appgroup) {
-	NewClientInfoRec clientinfo;
-
-	clientinfo.client = pClient;
-	XagClientStateChange (NULL, NULL, (pointer)&clientinfo);
-    }
-}
-
-void
-XagExtensionInit(INITARGS)
-{
-    if (AddExtension (XAGNAME,
-		      0,
-		      XagNumberErrors,
-		      ProcXagDispatch,
-		      SProcXagDispatch,
-		      XagResetProc,
-		      StandardMinorOpcode)) {
-	RT_APPGROUP = CreateNewResourceType (XagAppGroupFree);
-	XaceRegisterCallback(XACE_AUTH_AVAIL, XagCallClientStateChange, NULL);
-    }
-}
diff --git a/Xext/appgroup.h b/Xext/appgroup.h
deleted file mode 100644
index 778da5d..0000000
--- a/Xext/appgroup.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
-Copyright 1996, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
-OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall
-not be used in advertising or otherwise to promote the sale, use or
-other dealings in this Software without prior written authorization
-from The Open Group.
-*/
-
-#ifndef _APPGROUP_SRV_H_
-#define _APPGROUP_SRV_H_
-
-#include <X11/Xfuncproto.h>
-
-_XFUNCPROTOBEGIN
-
-extern void XagConnectionInfo(
-    ClientPtr			/* client */,
-    xConnSetupPrefix**		/* conn_prefix */,
-    char**			/* conn_info */,
-    int*			/* num_screens */
-);
-
-extern VisualID XagRootVisual(
-    ClientPtr			/* client */
-);
-
-extern Colormap XagDefaultColormap(
-    ClientPtr			/* client */
-);
-
-extern ClientPtr XagLeader(
-    ClientPtr			/* client */
-);
-
-extern Bool XagIsControlledRoot (
-    ClientPtr			/* client */,
-    WindowPtr			/* pParent */
-);
-
-extern XID XagId (
-    ClientPtr			/* client */
-);
-
-_XFUNCPROTOEND
-
-#endif /* _APPGROUP_SRV_H_ */
-
-
-
diff --git a/Xext/security.c b/Xext/security.c
index e82b976..b599030 100644
--- a/Xext/security.c
+++ b/Xext/security.c
@@ -38,9 +38,6 @@ in this Software without prior written authorization from The Open Group.
 #include "xacestr.h"
 #include "securitysrv.h"
 #include <X11/extensions/securstr.h>
-#ifdef XAPPGROUP
-#include "appgroup.h"
-#endif
 #include "modinit.h"
 
 /* Extension stuff */
@@ -833,11 +830,6 @@ SecurityResource(CallbackListPtr *pcbl, pointer unused, pointer calldata)
     if (SecurityDoCheck(subj, obj, requested, allowed) == Success)
 	return;
 
-#ifdef XAPPGROUP
-    if (rec->id == XagDefaultColormap(rec->client))
-	return;
-#endif
-
     SecurityAudit("Security: denied client %d access %x to resource 0x%x "
 		  "of client %d on request %s\n", rec->client->index,
 		  requested, rec->id, cid,
diff --git a/dix/dispatch.c b/dix/dispatch.c
index bb8b0c4..5025953 100644
--- a/dix/dispatch.c
+++ b/dix/dispatch.c
@@ -136,9 +136,6 @@ int ProcInitialConnection();
 #endif
 #include "privates.h"
 #include "xace.h"
-#ifdef XAPPGROUP
-#include "appgroup.h"
-#endif
 #ifdef XKB
 #ifndef XKB_IN_SERVER
 #define XKB_IN_SERVER
@@ -3516,9 +3513,6 @@ void InitClient(ClientPtr client, int i, pointer ospriv)
     }
 #endif
     client->replyBytesRemaining = 0;
-#ifdef XAPPGROUP
-    client->appgroup = NULL;
-#endif
     client->fontResFunc = NULL;
 #ifdef SMART_SCHEDULE
     client->smart_priority = 0;
@@ -3643,9 +3637,6 @@ SendConnSetup(ClientPtr client, char *reason)
 
     client->requestVector = client->swapped ? SwappedProcVector : ProcVector;
     client->sequence = 0;
-#ifdef XAPPGROUP
-    XagConnectionInfo (client, &lconnSetupPrefix, &lConnectionInfo, &numScreens);
-#endif
     ((xConnSetup *)lConnectionInfo)->ridBase = client->clientAsMask;
     ((xConnSetup *)lConnectionInfo)->ridMask = RESOURCE_ID_MASK;
 #ifdef MATCH_CLIENT_ENDIAN
diff --git a/dix/window.c b/dix/window.c
index 499f58e..168e940 100644
--- a/dix/window.c
+++ b/dix/window.c
@@ -123,9 +123,6 @@ Equipment Corporation.
 #include "dixevents.h"
 #include "globals.h"
 
-#ifdef XAPPGROUP
-#include "appgroup.h"
-#endif
 #include "privates.h"
 #include "xace.h"
 
@@ -603,14 +600,6 @@ CreateWindow(Window wid, WindowPtr pParent, int x, int y, unsigned w,
     if (!ancwopt)
 	ancwopt = FindWindowWithOptional(pParent)->optional;
     if (visual == CopyFromParent) {
-#ifdef XAPPGROUP
-	VisualID ag_visual;
-
-	if (client->appgroup && !pParent->parent &&
-	    (ag_visual = XagRootVisual (client)))
-	    visual = ag_visual;
-	else
-#endif
 	visual = ancwopt->visual;
     }
 
@@ -1290,22 +1279,6 @@ ChangeWindowAttributes(WindowPtr pWin, Mask vmask, XID *vlist, ClientPtr client)
 	    pVlist++;
 	    if (cmap == CopyFromParent)
 	    {
-#ifdef XAPPGROUP
-		Colormap ag_colormap;
-		ClientPtr win_owner;
-
-		/*
-		 * win_owner == client for CreateWindow, other clients
-		 * can ChangeWindowAttributes
-		 */
-		win_owner = clients[CLIENT_ID(pWin->drawable.id)];
-
-		if ( win_owner && win_owner->appgroup &&
-		    !pWin->parent->parent &&
-		    (ag_colormap = XagDefaultColormap (win_owner)))
-		    cmap = ag_colormap;
-		else
-#endif
 		if (pWin->parent &&
 		    (!pWin->optional ||
 		     pWin->optional->visual == wVisual (pWin->parent)))
@@ -2234,10 +2207,6 @@ ConfigureWindow(WindowPtr pWin, Mask mask, XID *vlist, ClientPtr client)
 		   h = pWin->drawable.height,
 		   bw = pWin->borderWidth;
     int rc, action, smode = Above;
-#ifdef XAPPGROUP
-    ClientPtr win_owner;
-    ClientPtr ag_leader = NULL;
-#endif
     xEvent event;
 
     if ((pWin->drawable.class == InputOnly) && (mask & IllegalInputOnlyConfigureMask))
@@ -2333,17 +2302,9 @@ ConfigureWindow(WindowPtr pWin, Mask mask, XID *vlist, ClientPtr client)
     else
 	pSib = pWin->nextSib;
 
-#ifdef XAPPGROUP
-    win_owner = clients[CLIENT_ID(pWin->drawable.id)];
-    ag_leader = XagLeader (win_owner);
-#endif
 
     if ((!pWin->overrideRedirect) && 
 	(RedirectSend(pParent)
-#ifdef XAPPGROUP
-	|| (win_owner->appgroup && ag_leader && 
-	    XagIsControlledRoot (client, pParent))
-#endif
 	))
     {
 	event.u.u.type = ConfigureRequest;
@@ -2368,16 +2329,6 @@ ConfigureWindow(WindowPtr pWin, Mask mask, XID *vlist, ClientPtr client)
 	event.u.configureRequest.height = h;
 	event.u.configureRequest.borderWidth = bw;
 	event.u.configureRequest.valueMask = mask;
-#ifdef XAPPGROUP
-	/* make sure if the ag_leader maps the window it goes to the wm */
-	if (ag_leader && ag_leader != client && 
-	    XagIsControlledRoot (client, pParent)) {
-	    event.u.configureRequest.parent = XagId (win_owner);
-	    (void) TryClientEvents (ag_leader, &event, 1,
-				    NoEventMask, NoEventMask, NullGrab);
-	    return Success;
-	}
-#endif
 	event.u.configureRequest.parent = pParent->drawable.id;
 	if (MaybeDeliverEventsToClient(pParent, &event, 1,
 		SubstructureRedirectMask, client) == 1)
@@ -2754,31 +2705,13 @@ MapWindow(WindowPtr pWin, ClientPtr client)
     {
 	xEvent event;
 	Bool anyMarked;
-#ifdef XAPPGROUP
-	ClientPtr win_owner = clients[CLIENT_ID(pWin->drawable.id)];
-	ClientPtr ag_leader = XagLeader (win_owner);
-#endif
 
 	if ((!pWin->overrideRedirect) && 
 	    (RedirectSend(pParent)
-#ifdef XAPPGROUP
-	    || (win_owner->appgroup && ag_leader &&
-		XagIsControlledRoot (client, pParent))
-#endif
 	))
 	{
 	    event.u.u.type = MapRequest;
 	    event.u.mapRequest.window = pWin->drawable.id;
-#ifdef XAPPGROUP
-	    /* make sure if the ag_leader maps the window it goes to the wm */
-	    if (ag_leader && ag_leader != client &&
-		XagIsControlledRoot (client, pParent)) {
-		event.u.mapRequest.parent = XagId (win_owner);
-		(void) TryClientEvents (ag_leader, &event, 1,
-					NoEventMask, NoEventMask, NullGrab);
-		return Success;
-	    }
-#endif
 	    event.u.mapRequest.parent = pParent->drawable.id;
 
 	    if (MaybeDeliverEventsToClient(pParent, &event, 1,
diff --git a/hw/dmx/dmxextension.c b/hw/dmx/dmxextension.c
index 560468c..aaa50d5 100644
--- a/hw/dmx/dmxextension.c
+++ b/hw/dmx/dmxextension.c
@@ -1350,7 +1350,6 @@ int dmxAttachScreen(int idx, DMXScreenAttributesPtr attr)
  * RTContext
  * TagResType
  * StalledResType
- * RT_APPGROUP
  * SecurityAuthorizationResType
  * RTEventClient
  * __glXContextRes
diff --git a/hw/xfree86/dixmods/extmod/modinit.h b/hw/xfree86/dixmods/extmod/modinit.h
index bfbf443..3224850 100644
--- a/hw/xfree86/dixmods/extmod/modinit.h
+++ b/hw/xfree86/dixmods/extmod/modinit.h
@@ -129,14 +129,6 @@ extern void SecurityExtensionInit(INITARGS);
 #endif
 
 #if 1
-extern void XagExtensionInit(INITARGS);
-#endif
-
-#if 1
-extern void XpExtensionInit(INITARGS);
-#endif
-
-#if 1
 extern void PanoramiXExtensionInit(int argc, char *argv[]);
 #endif
 
diff --git a/hw/xfree86/loader/dixsym.c b/hw/xfree86/loader/dixsym.c
index a95dbe9..8093a79 100644
--- a/hw/xfree86/loader/dixsym.c
+++ b/hw/xfree86/loader/dixsym.c
@@ -397,9 +397,6 @@ _X_HIDDEN void *dixLookupTab[] = {
 #ifdef RES
     SYMVAR(noResExtension)
 #endif
-#ifdef XAPPGROUP
-    SYMVAR(noXagExtension)
-#endif
 #ifdef XCMISC
     SYMVAR(noXCMiscExtension)
 #endif
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index 4556223..53d1046 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -416,9 +416,6 @@
 /* Support Xv extension */
 #undef XV
 
-/* Build APPGROUP extension */
-#undef XAPPGROUP
-
 /* Build TOG-CUP extension */
 #undef TOGCUP
 
diff --git a/include/dixstruct.h b/include/dixstruct.h
index d44b9cf..18d161a 100644
--- a/include/dixstruct.h
+++ b/include/dixstruct.h
@@ -125,9 +125,7 @@ typedef struct _Client {
     int         requestLogIndex;
 #endif
     unsigned long replyBytesRemaining;
-#ifdef XAPPGROUP
-    struct _AppGroupRec*	appgroup;
-#endif
+    void *appgroup; /* Can't remove, ABI */
     struct _FontResolution * (*fontResFunc) (    /* no need for font.h */
 		ClientPtr	/* pClient */,
 		int *		/* num */);
diff --git a/include/globals.h b/include/globals.h
index 1cedc0d..cfb6c2c 100644
--- a/include/globals.h
+++ b/include/globals.h
@@ -118,10 +118,6 @@ extern Bool noXcupExtension;
 extern Bool noResExtension;
 #endif
 
-#ifdef XAPPGROUP
-extern Bool noXagExtension;
-#endif
-
 #ifdef XCMISC
 extern Bool noXCMiscExtension;
 #endif
diff --git a/mi/miinitext.c b/mi/miinitext.c
index 568bc9e..74ec282 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -169,9 +169,6 @@ extern Bool noXcupExtension;
 #ifdef RES
 extern Bool noResExtension;
 #endif
-#ifdef XAPPGROUP
-extern Bool noXagExtension;
-#endif
 #ifdef XCMISC
 extern Bool noXCMiscExtension;
 #endif
@@ -240,10 +237,6 @@ typedef void (*InitExtension)(INITARGS);
 #ifdef XPRINT
 #include <X11/extensions/Print.h>
 #endif
-#ifdef XAPPGROUP
-#define _XAG_SERVER_
-#include <X11/extensions/Xagstr.h>
-#endif
 #ifdef XCSECURITY
 #include "securitysrv.h"
 #include <X11/extensions/securstr.h>
@@ -314,9 +307,6 @@ extern void RecordExtensionInit(INITARGS);
 #ifdef DBE
 extern void DbeExtensionInit(INITARGS);
 #endif
-#ifdef XAPPGROUP
-extern void XagExtensionInit(INITARGS);
-#endif
 #ifdef XCSECURITY
 extern void SecurityExtensionInit(INITARGS);
 #endif
@@ -446,9 +436,6 @@ static ExtensionToggle ExtensionToggleList[] =
 #ifdef RES
     { "X-Resource", &noResExtension },
 #endif
-#ifdef XAPPGROUP
-    { "XC-APPGROUP", &noXagExtension },
-#endif
 #ifdef XCMISC
     { "XC-MISC", &noXCMiscExtension },
 #endif
@@ -584,9 +571,6 @@ InitExtensions(argc, argv)
 #ifdef DBE
     if (!noDbeExtension) DbeExtensionInit();
 #endif
-#ifdef XAPPGROUP
-    if (!noXagExtension) XagExtensionInit();
-#endif
 #ifdef XCSECURITY
     if (!noSecurityExtension) SecurityExtensionInit();
 #endif
@@ -678,9 +662,6 @@ static ExtensionModule staticExtensions[] = {
 #ifdef XKB
     { XkbExtensionInit, XkbName, &noXkbExtension, NULL, NULL },
 #endif
-#ifdef XAPPGROUP
-    { XagExtensionInit, XAGNAME, &noXagExtension, NULL, NULL },
-#endif
 #ifdef XCSECURITY
     { SecurityExtensionInit, SECURITY_EXTENSION_NAME, &noSecurityExtension, NULL, NULL },
 #endif
diff --git a/os/connection.c b/os/connection.c
index 1ae50fe..3965936 100644
--- a/os/connection.c
+++ b/os/connection.c
@@ -139,9 +139,6 @@ SOFTWARE.
 #include <X11/Xpoll.h>
 #include "opaque.h"
 #include "dixstruct.h"
-#ifdef XAPPGROUP
-#include "appgroup.h"
-#endif
 #include "xace.h"
 
 #ifdef X_NOT_POSIX
diff --git a/os/utils.c b/os/utils.c
index 5486010..4210e5d 100644
--- a/os/utils.c
+++ b/os/utils.c
@@ -189,9 +189,6 @@ _X_EXPORT Bool noXcupExtension = FALSE;
 #ifdef RES
 _X_EXPORT Bool noResExtension = FALSE;
 #endif
-#ifdef XAPPGROUP
-_X_EXPORT Bool noXagExtension = FALSE;
-#endif
 #ifdef XCMISC
 _X_EXPORT Bool noXCMiscExtension = FALSE;
 #endif
commit f6617b4127125516583f321c961d70f762f728be
Author: Adam Jackson <ajax at redhat.com>
Date:   Fri Apr 18 18:28:01 2008 -0400

    Death to Extended Visual Information.

diff --git a/Xext/Makefile.am b/Xext/Makefile.am
index 648736d..4a2925f 100644
--- a/Xext/Makefile.am
+++ b/Xext/Makefile.am
@@ -118,12 +118,6 @@ if CUP
 MODULE_SRCS  += $(CUP_SRCS)
 endif
 
-# Extended Visual Information
-EVI_SRCS = EVI.c sampleEVI.c EVIstruct.h
-if EVI
-MODULE_SRCS  += $(EVI_SRCS)
-endif
-
 # Multi-buffering extension
 MULTIBUFFER_SRCS = mbuf.c
 EXTRA_MULTIBUFFER_SRCS = mbufbf.c mbufpx.c
@@ -172,7 +166,6 @@ EXTRA_DIST = \
 	$(XPRINT_SRCS) \
 	$(APPGROUP_SRCS) \
 	$(CUP_SRCS) \
-	$(EVI_SRCS) \
 	$(MULTIBUFFER_SRCS) \
 	$(EXTRA_MULTIBUFFER_SRCS) \
 	$(FONTCACHE_SRCS) \
diff --git a/configure.ac b/configure.ac
index 9669f47..ffe79f2 100644
--- a/configure.ac
+++ b/configure.ac
@@ -549,7 +549,6 @@ AC_ARG_ENABLE(xcalibrate,     AS_HELP_STRING([--enable-xcalibrate], [Build XCali
 AC_ARG_ENABLE(tslib,          AS_HELP_STRING([--enable-tslib], [Build kdrive tslib touchscreen support (default: disabled)]), [TSLIB=$enableval], [TSLIB=no])
 AC_ARG_ENABLE(xevie,          AS_HELP_STRING([--disable-xevie], [Build XEvIE extension (default: enabled)]), [XEVIE=$enableval], [XEVIE=yes])
 AC_ARG_ENABLE(cup,            AS_HELP_STRING([--disable-cup], [Build TOG-CUP extension (default: enabled)]), [CUP=$enableval], [CUP=yes])
-AC_ARG_ENABLE(evi,            AS_HELP_STRING([--disable-evi], [Build Extended-Visual-Information extension (default: enabled)]), [EVI=$enableval], [EVI=yes])
 AC_ARG_ENABLE(multibuffer,    AS_HELP_STRING([--enable-multibuffer], [Build Multibuffer extension (default: disabled)]), [MULTIBUFFER=$enableval], [MULTIBUFFER=no])
 AC_ARG_ENABLE(fontcache,      AS_HELP_STRING([--enable-fontcache], [Build FontCache extension (default: disabled)]), [FONTCACHE=$enableval], [FONTCACHE=no])
 AC_ARG_ENABLE(dbe,            AS_HELP_STRING([--disable-dbe], [Build DBE extension (default: enabled)]), [DBE=$enableval], [DBE=yes])
@@ -945,12 +944,6 @@ if test "x$CUP" = xyes; then
 	# Requires xextproto which is always required
 fi
 
-AM_CONDITIONAL(EVI, [test "x$EVI" = xyes])
-if test "x$EVI" = xyes; then
-	AC_DEFINE(EVI, 1, [Build Extended-Visual-Information extension])
-	# Requires xextproto which is always required
-fi
-
 AM_CONDITIONAL(MULTIBUFFER, [test "x$MULTIBUFFER" = xyes])
 if test "x$MULTIBUFFER" = xyes; then
 	AC_DEFINE(MULTIBUFFER, 1, [Build Multibuffer extension])
diff --git a/hw/xfree86/dixmods/extmod/modinit.c b/hw/xfree86/dixmods/extmod/modinit.c
index 8c8a4ce..3b6b36a 100644
--- a/hw/xfree86/dixmods/extmod/modinit.c
+++ b/hw/xfree86/dixmods/extmod/modinit.c
@@ -173,15 +173,6 @@ static ExtensionModule extensionModules[] = {
 	NULL
     },
 #endif
-#ifdef EVI
-    {
-	EVIExtensionInit,
-	EVINAME,
-	&noEVIExtension,
-	NULL,
-	NULL
-    },
-#endif
 #ifdef XV
     {
 	XvExtensionInit,
diff --git a/hw/xfree86/dixmods/extmod/modinit.h b/hw/xfree86/dixmods/extmod/modinit.h
index 3c2e202..bfbf443 100644
--- a/hw/xfree86/dixmods/extmod/modinit.h
+++ b/hw/xfree86/dixmods/extmod/modinit.h
@@ -95,12 +95,6 @@ extern void XcupExtensionInit(INITARGS);
 #include <X11/extensions/Xcupstr.h>
 #endif
 
-#ifdef EVI
-extern void EVIExtensionInit(INITARGS);
-#define _XEVI_SERVER_
-#include <X11/extensions/XEVIstr.h>
-#endif
-
 #ifdef XV
 extern void XvExtensionInit(INITARGS);
 extern void XvMCExtensionInit(INITARGS);
diff --git a/hw/xfree86/loader/dixsym.c b/hw/xfree86/loader/dixsym.c
index d6d22c4..a95dbe9 100644
--- a/hw/xfree86/loader/dixsym.c
+++ b/hw/xfree86/loader/dixsym.c
@@ -358,9 +358,6 @@ _X_HIDDEN void *dixLookupTab[] = {
 #ifdef DPMSExtension
     SYMVAR(noDPMSExtension)
 #endif
-#ifdef EVI
-    SYMVAR(noEVIExtension)
-#endif
 #ifdef FONTCACHE
     SYMVAR(noFontCacheExtension)
 #endif
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index a7c0c6a..4556223 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -422,9 +422,6 @@
 /* Build TOG-CUP extension */
 #undef TOGCUP
 
-/* Build Extended-Visual-Information extension */
-#undef EVI
-
 /* Build Multibuffer extension */
 #undef MULTIBUFFER
 
diff --git a/include/globals.h b/include/globals.h
index 2ca9531..1cedc0d 100644
--- a/include/globals.h
+++ b/include/globals.h
@@ -66,10 +66,6 @@ extern Bool noDbeExtension;
 extern Bool noDPMSExtension;
 #endif
 
-#ifdef EVI
-extern Bool noEVIExtension;
-#endif
-
 #ifdef FONTCACHE
 extern Bool noFontCacheExtension;
 #endif
diff --git a/mi/miinitext.c b/mi/miinitext.c
index cc4c15c..568bc9e 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -130,9 +130,6 @@ extern Bool noDbeExtension;
 #ifdef DPMSExtension
 extern Bool noDPMSExtension;
 #endif
-#ifdef EVI
-extern Bool noEVIExtension;
-#endif
 #ifdef FONTCACHE
 extern Bool noFontCacheExtension;
 #endif
@@ -265,9 +262,6 @@ typedef void (*InitExtension)(INITARGS);
 #endif
 
 /* FIXME: this whole block of externs should be from the appropriate headers */
-#ifdef EVI
-extern void EVIExtensionInit(INITARGS);
-#endif
 #ifdef MITSHM
 extern void ShmExtensionInit(INITARGS);
 #endif
@@ -413,9 +407,6 @@ static ExtensionToggle ExtensionToggleList[] =
 #ifdef DPMSExtension
     { "DPMS", &noDPMSExtension },
 #endif
-#ifdef EVI
-    { "Extended-Visual-Information", &noEVIExtension },
-#endif
 #ifdef FONTCACHE
     { "FontCache", &noFontCacheExtension },
 #endif
@@ -548,9 +539,6 @@ InitExtensions(argc, argv)
 #ifdef MITSHM
     if (!noMITShmExtension) ShmExtensionInit();
 #endif
-#ifdef EVI
-    if (!noEVIExtension) EVIExtensionInit();
-#endif
 #ifdef MULTIBUFFER
     if (!noMultibufferExtension) MultibufferExtensionInit();
 #endif
diff --git a/os/utils.c b/os/utils.c
index d785d46..5486010 100644
--- a/os/utils.c
+++ b/os/utils.c
@@ -149,9 +149,6 @@ _X_EXPORT Bool noDbeExtension = FALSE;
 #ifdef DPMSExtension
 _X_EXPORT Bool noDPMSExtension = FALSE;
 #endif
-#ifdef EVI
-_X_EXPORT Bool noEVIExtension = FALSE;
-#endif
 #ifdef FONTCACHE
 _X_EXPORT Bool noFontCacheExtension = FALSE;
 #endif
commit c14f5dc237a31b13d98ae2d0d6143bd91083cf13
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 17 20:21:45 2008 -0700

    XQuartz: Forgot to commit xprEvent.[hc] ...
    (cherry picked from commit 70e543baf2508d636f01b2b7e8cb05172195b68c)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 589ca79..d69e6b7 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -538,5 +538,6 @@ void DarwinSendDDXEvent(int type, int argc, ...) {
 
     mieqEnqueue_lock();
     mieqEnqueue(darwinPointer, &xe);
+    DarwinPokeEQ();
     mieqEnqueue_unlock();
 }
diff --git a/hw/xquartz/xpr/xpr.h b/hw/xquartz/xpr/xpr.h
index 7b7923c..ab79a42 100644
--- a/hw/xquartz/xpr/xpr.h
+++ b/hw/xquartz/xpr/xpr.h
@@ -29,6 +29,7 @@
 #ifndef XPR_H
 #define XPR_H
 
+#include "windowstr.h"
 #include "screenint.h"
 #include <Xplugin.h>
 
diff --git a/hw/xquartz/xpr/xprEvent.c b/hw/xquartz/xpr/xprEvent.c
new file mode 100644
index 0000000..617d6e1
--- /dev/null
+++ b/hw/xquartz/xpr/xprEvent.c
@@ -0,0 +1,91 @@
+/* Copyright (c) 2008 Apple Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE ABOVE LISTED COPYRIGHT
+ * HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above
+ * copyright holders shall not be used in advertising or otherwise to
+ * promote the sale, use or other dealings in this Software without
+ * prior written authorization.
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include "xpr.h"
+
+#define NEED_EVENTS
+#include   <X11/X.h>
+#include   <X11/Xmd.h>
+#include   <X11/Xproto.h>
+#include   "misc.h"
+#include   "windowstr.h"
+#include   "pixmapstr.h"
+#include   "inputstr.h"
+#include   "mi.h"
+#include   "scrnintstr.h"
+#include   "mipointer.h"
+
+#include "darwin.h"
+#include "quartz.h"
+#include "quartzKeyboard.h"
+#include "darwinEvents.h"
+
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <unistd.h>
+
+#include "rootlessWindow.h"
+#include "xprEvent.h"
+
+static void xprEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents) {
+    int i;
+    
+    TA_SERVER();
+    
+    DEBUG_LOG("DarwinEventHandler(%d, %p, %p, %d)\n", screenNum, xe, dev, nevents);
+    for (i=0; i<nevents; i++) {
+        switch(xe[i].u.u.type) {
+                
+            case kXquartzWindowState:
+                DEBUG_LOG("kXquartzWindowState\n");
+                RootlessNativeWindowStateChanged(xprGetXWindow(xe[i].u.clientMessage.u.l.longs0),
+                                                 xe[i].u.clientMessage.u.l.longs1);
+                break;
+                
+            case kXquartzWindowMoved:
+                DEBUG_LOG("kXquartzWindowMoved\n");
+                RootlessNativeWindowMoved ((WindowPtr)xe[i].u.clientMessage.u.l.longs0);
+                break;
+                
+            case kXquartzBringAllToFront:
+                DEBUG_LOG("kXquartzBringAllToFront\n");
+                RootlessOrderAllWindows();
+                break;
+        }
+    }
+}
+
+void QuartzModeEQInit(void) {
+    mieqSetHandler(kXquartzWindowState, xprEventHandler);
+    mieqSetHandler(kXquartzWindowMoved, xprEventHandler);
+    mieqSetHandler(kXquartzBringAllToFront, xprEventHandler);
+}
diff --git a/hw/xquartz/xpr/xprEvent.h b/hw/xquartz/xpr/xprEvent.h
new file mode 100644
index 0000000..5af9dfd
--- /dev/null
+++ b/hw/xquartz/xpr/xprEvent.h
@@ -0,0 +1,34 @@
+/* Copyright (c) 2008 Apple Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE ABOVE LISTED COPYRIGHT
+ * HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above
+ * copyright holders shall not be used in advertising or otherwise to
+ * promote the sale, use or other dealings in this Software without
+ * prior written authorization.
+ */
+
+#ifndef __XPR_EVENT_H__
+#define __XPR_EVENT_H__
+
+void QuartzModeEQInit(void);
+
+#endif
commit 22bb7608a025a4ec0f442637810b20e2cb0b0820
Author: Ben Byer <bbyer at apple.com>
Date:   Thu Apr 17 17:04:08 2008 -0700

    Added XKB support for Xquartz
    (cherry picked from commit 56dc1215202746590dbe8758411f47e8876e1317)

diff --git a/hw/xquartz/quartzKeyboard.c b/hw/xquartz/quartzKeyboard.c
index 30eec1d..e8d9968 100644
--- a/hw/xquartz/quartzKeyboard.c
+++ b/hw/xquartz/quartzKeyboard.c
@@ -41,7 +41,7 @@
 // Define this to get a diagnostic output to stderr which is helpful
 // in determining how the X server is interpreting the Darwin keymap.
 #define DUMP_DARWIN_KEYMAP
-
+#define XQUARTZ_USE_XKB
 #define HACK_MISSING 1
 #define HACK_KEYPAD 1
 
@@ -70,12 +70,12 @@
 #include <assert.h>
 #endif
 
-
-
-
+#include "xkbsrv.h"
+#include "exevents.h"
 #include "X11/keysym.h"
 #include "keysym2ucs.h"
 
+void QuartzXkbUpdate(DeviceIntPtr pDev);
 
 enum {
     MOD_COMMAND = 256,
@@ -863,6 +863,15 @@ static void DarwinLoadKeyboardMapping(KeySymsRec *keySyms) {
     keySyms->maxKeyCode = MAX_KEYCODE;
 }
 
+void QuartzXkbUpdate(DeviceIntPtr pDev) {
+#ifdef XQUARTZ_USE_XKB
+	SendDeviceMappingNotify(serverClient, MappingKeyboard, 
+		pDev->key->curKeySyms.minKeyCode, 
+		pDev->key->curKeySyms.maxKeyCode - pDev->key->curKeySyms.minKeyCode, pDev);
+	SendDeviceMappingNotify(serverClient, MappingModifier, 0, 0, pDev);
+	SwitchCoreKeyboard(pDev);   
+#endif
+}
 
 /*
  * DarwinKeyboardInit
@@ -879,38 +888,56 @@ void DarwinKeyboardInit(DeviceIntPtr pDev) {
     assert( darwinParamConnect = NXOpenEventStatus() );
 
     DarwinLoadKeyboardMapping(&keySyms);
-    //    DarwinKeyboardReload(pDev);
     /* Initialize the seed, so we don't reload the keymap unnecessarily
        (and possibly overwrite xinitrc changes) */
     QuartzSystemKeymapSeed();
 
+#ifdef XQUARTZ_USE_XKB
+	XkbComponentNamesRec names;
+	bzero(&names, sizeof(names));
+    XkbSetRulesDflts("base", "pc105", "us", NULL, NULL);
+    assert(XkbInitKeyboardDeviceStruct(pDev, &names, &keySyms, keyInfo.modMap,
+                                        QuartzBell, DarwinChangeKeyboardControl));
+	assert(SetKeySymsMap(&pDev->key->curKeySyms, &keySyms));
+	assert(keyInfo.modMap!=NULL);
+	assert(pDev->key->modifierMap!=NULL);
+	memcpy(pDev->key->modifierMap, keyInfo.modMap, sizeof(keyInfo.modMap));
+	
+	QuartzXkbUpdate(pDev);
+#else
+#error FAIL
     assert( InitKeyboardDeviceStruct( (DevicePtr)pDev, &keySyms,
                                       keyInfo.modMap, QuartzBell,
                                       DarwinChangeKeyboardControl ));
     SwitchCoreKeyboard(pDev);
+#endif
 }
 
 
-void DarwinKeyboardReloadHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents) {
-    KeySymsRec keySyms;
-	if (dev == NULL) dev = darwinKeyboard;
+void DarwinKeyboardReloadHandler(int screenNum, xEventPtr xe, DeviceIntPtr pDev, int nevents) {
+	if (pDev == NULL) pDev = darwinKeyboard;
 	
-	DEBUG_LOG("DarwinKeyboardReloadHandler(%p)\n", dev);
-    DarwinLoadKeyboardMapping(&keySyms);
+	DEBUG_LOG("DarwinKeyboardReloadHandler(%p)\n", pDev);
 
-	if (dev->key) {
-		if (dev->key->curKeySyms.map) xfree(dev->key->curKeySyms.map);
-		if (dev->key->modifierKeyMap) xfree(dev->key->modifierKeyMap);
-		xfree(dev->key);
+#ifdef XQUARTZ_USE_XKB
+	QuartzXkbUpdate(pDev);
+#else
+#error FAIL
+	if (pDev->key) {
+		if (pDev->key->curKeySyms.map) xfree(pDev->key->curKeySyms.map);
+		if (pDev->key->modifierKeyMap) xfree(pDev->key->modifierKeyMap);
+		xfree(pDev->key);
 	}
 	
-	if (!InitKeyClassDeviceStruct(dev, &keySyms, keyInfo.modMap)) {
+    KeySymsRec keySyms;
+	if (!InitKeyClassDeviceStruct(pDev, &keySyms, keyInfo.modMap)) {
 		DEBUG_LOG("InitKeyClassDeviceStruct failed\n");
 		return;
 	}
 
     SendMappingNotify(MappingKeyboard, MIN_KEYCODE, NUM_KEYCODES, 0);
     SendMappingNotify(MappingModifier, 0, 0, 0);
+#endif
 }
 
 
commit 652479dba38470273313dc46f17e3bcb1bc5e383
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 17 15:49:13 2008 -0700

    XQuartz: Moved some rootless-specific cruft into xpr
    (cherry picked from commit 31625cc03b58317120c2ac7877e227e2322e1de8)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index c593596..589ca79 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -69,10 +69,8 @@ in this Software without prior written authorization from The Open Group.
 #include "applewmExt.h"
 #include <X11/extensions/applewm.h>
 
-/* FIXME: Abstract this away into xpr */
-#include <Xplugin.h>
-#include "rootlessWindow.h"
-WindowPtr xprGetXWindow(xp_window_id wid);
+/* FIXME: Abstract this better */
+void QuartzModeEQInit(void);
 
 int input_check_zero, input_check_flag;
 
@@ -218,7 +216,7 @@ static void DarwinSimulateMouseClick(
    be moved into their own individual functions and set as handlers using
    mieqSetHandler. */
 
-void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents) {
+static void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents) {
     int i;
     
     TA_SERVER();
@@ -259,18 +257,7 @@ void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int neven
                                  AppleWMIsInactive, 0);
                 QuartzHide();
                 break;
-                
-            case kXquartzWindowState:
-                DEBUG_LOG("kXquartzWindowState\n");
-                RootlessNativeWindowStateChanged(xprGetXWindow(xe[i].u.clientMessage.u.l.longs0),
-                                                 xe[i].u.clientMessage.u.l.longs1);
-                break;
-                
-            case kXquartzWindowMoved:
-                DEBUG_LOG("kXquartzWindowMoved\n");
-                RootlessNativeWindowMoved ((WindowPtr)xe[i].u.clientMessage.u.l.longs0);
-                break;
-                
+
             case kXquartzToggleFullscreen:
                 DEBUG_LOG("kXquartzToggleFullscreen\n");
 #ifdef DARWIN_DDX_MISSING
@@ -304,11 +291,6 @@ void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int neven
                 GiveUp(0);
                 break;
                 
-            case kXquartzBringAllToFront:
-                DEBUG_LOG("kXquartzBringAllToFront\n");
-                RootlessOrderAllWindows();
-                break;
-                
             case kXquartzSpaceChanged:
                 DEBUG_LOG("kXquartzSpaceChanged\n");
                 QuartzSpaceChanged(xe[i].u.clientMessage.u.l.longs0);
@@ -329,7 +311,7 @@ Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) {
         FatalError("Couldn't allocate event buffer\n");
 
     if((err = pthread_mutex_init(&mieqEnqueue_mutex, NULL))) {
-        FatalError("Couldn't allocate miEnqueue mutex: %d.\n", err);
+        FatalError("Couldn't allocate mieqEnqueue mutex: %d.\n", err);
     }
     
     mieqInit();
@@ -346,9 +328,9 @@ Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) {
     mieqSetHandler(kXquartzControllerNotify, DarwinEventHandler);
     mieqSetHandler(kXquartzPasteboardNotify, DarwinEventHandler);
     mieqSetHandler(kXquartzDisplayChanged, QuartzDisplayChangedHandler);
-    mieqSetHandler(kXquartzWindowState, DarwinEventHandler);
-    mieqSetHandler(kXquartzWindowMoved, DarwinEventHandler);
 
+    QuartzModeEQInit();
+    
     return TRUE;
 }
 
diff --git a/hw/xquartz/darwinEvents.h b/hw/xquartz/darwinEvents.h
index c87d667..dd3f81c 100644
--- a/hw/xquartz/darwinEvents.h
+++ b/hw/xquartz/darwinEvents.h
@@ -41,7 +41,4 @@ void DarwinSendScrollEvents(float count_x, float count_y, int pointer_x, int poi
 			    float pressure, float tilt_x, float tilt_y);
 void DarwinUpdateModKeys(int flags);
 
-void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, 
-			int nevents);
-
 #endif  /* _DARWIN_EVENTS_H */
diff --git a/hw/xquartz/xpr/Makefile.am b/hw/xquartz/xpr/Makefile.am
index f6ede8b..3e2e605 100644
--- a/hw/xquartz/xpr/Makefile.am
+++ b/hw/xquartz/xpr/Makefile.am
@@ -11,6 +11,7 @@ Xquartz_SOURCES = \
 	dri.c \
 	xprAppleWM.c \
 	xprCursor.c \
+	xprEvent.c \
 	xprFrame.c \
 	xprScreen.c \
 	x-hash.c \
@@ -71,4 +72,5 @@ EXTRA_DIST = \
 	x-hash.h \
 	x-hook.h \
 	x-list.h \
-	xpr.h
+	xpr.h \
+	xprEvent.h
diff --git a/hw/xquartz/xpr/xpr.h b/hw/xquartz/xpr/xpr.h
index b8c69df..7b7923c 100644
--- a/hw/xquartz/xpr/xpr.h
+++ b/hw/xquartz/xpr/xpr.h
@@ -30,6 +30,7 @@
 #define XPR_H
 
 #include "screenint.h"
+#include <Xplugin.h>
 
 Bool QuartzModeBundleInit(void);
 
@@ -37,6 +38,7 @@ void AppleDRIExtensionInit(void);
 void xprAppleWMInit(void);
 Bool xprInit(ScreenPtr pScreen);
 Bool xprIsX11Window(void *nsWindow, int windowNumber);
+WindowPtr xprGetXWindow(xp_window_id wid);
 
 void xprHideWindows(Bool hide);
 
diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index fccaff0..8219046 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -35,6 +35,7 @@
 #include "inputstr.h"
 #include "quartz.h"
 #include "xpr.h"
+#include "xprEvent.h"
 #include "pseudoramiX.h"
 #include "darwin.h"
 #include "rootless.h"
@@ -44,9 +45,6 @@
 #include "applewmExt.h"
 #include "micmap.h"
 
-// From xprFrame.c
-WindowPtr xprGetXWindow(xp_window_id wid);
-
 #ifdef DAMAGE
 # include "damage.h"
 #endif
commit 2a1ba20af98c0e9a6a7f1a50d32058dcc9759c21
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 17 15:23:00 2008 -0700

    XQuartz: Use a mutex to ensure we only have one thread calling mieqEnqueue at a time.
    (cherry picked from commit 7b087c965bce9f440ab5233d6383aa4a7de969b8)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 260690c..c593596 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -54,6 +54,9 @@ in this Software without prior written authorization from The Open Group.
 #include <sys/types.h>
 #include <sys/uio.h>
 #include <unistd.h>
+#include <pthread.h>
+#include <errno.h>
+
 #include <IOKit/hidsystem/IOLLEvent.h>
 
 /* Fake button press/release for scroll wheel move. */
@@ -77,6 +80,25 @@ static int old_flags = 0;  // last known modifier state
 
 xEvent *darwinEvents = NULL;
 
+pthread_mutex_t mieqEnqueue_mutex;
+static inline void mieqEnqueue_lock(void) {
+    int err;
+    if((err = pthread_mutex_lock(&mieqEnqueue_mutex))) {
+        ErrorF("%s:%s:%d: Failed to lock mieqEnqueue_mutex: %d\n",
+               __FILE__, __FUNCTION__, __LINE__, err);
+        spewCallStack();
+    }
+}
+
+static inline void mieqEnqueue_unlock(void) {
+    int err;
+    if((err = pthread_mutex_unlock(&mieqEnqueue_mutex))) {
+        ErrorF("%s:%s:%d: Failed to unlock mieqEnqueue_mutex: %d\n",
+               __FILE__, __FUNCTION__, __LINE__, err);
+        spewCallStack();
+    }
+}
+
 /*
  * DarwinPressModifierMask
  *  Press or release the given modifier key, specified by its mask.
@@ -197,107 +219,119 @@ static void DarwinSimulateMouseClick(
    mieqSetHandler. */
 
 void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents) {
-  int i;
-
-  DEBUG_LOG("DarwinEventHandler(%d, %p, %p, %d)\n", screenNum, xe, dev, nevents);
-  for (i=0; i<nevents; i++) {
-	switch(xe[i].u.u.type) {
-		case kXquartzControllerNotify:
-            DEBUG_LOG("kXquartzControllerNotify\n");
-            AppleWMSendEvent(AppleWMControllerNotify,
-                             AppleWMControllerNotifyMask,
-                             xe[i].u.clientMessage.u.l.longs0,
-                             xe[i].u.clientMessage.u.l.longs1);
-            break;
-
-        case kXquartzPasteboardNotify:
-            DEBUG_LOG("kXquartzPasteboardNotify\n");
-            AppleWMSendEvent(AppleWMPasteboardNotify,
-                             AppleWMPasteboardNotifyMask,
-                             xe[i].u.clientMessage.u.l.longs0,
-                             xe[i].u.clientMessage.u.l.longs1);
-            break;
-
-        case kXquartzActivate:
-            DEBUG_LOG("kXquartzActivate\n");
-            QuartzShow(xe[i].u.keyButtonPointer.rootX,
-                       xe[i].u.keyButtonPointer.rootY);
-            AppleWMSendEvent(AppleWMActivationNotify,
-                             AppleWMActivationNotifyMask,
-                             AppleWMIsActive, 0);
-            break;
-
-        case kXquartzDeactivate:
-            DEBUG_LOG("kXquartzDeactivate\n");
-      		DarwinReleaseModifiers();
-            AppleWMSendEvent(AppleWMActivationNotify,
-                             AppleWMActivationNotifyMask,
-                             AppleWMIsInactive, 0);
-            QuartzHide();
-            break;
-
-        case kXquartzWindowState:
-            DEBUG_LOG("kXquartzWindowState\n");
-            RootlessNativeWindowStateChanged(xprGetXWindow(xe[i].u.clientMessage.u.l.longs0),
-                                             xe[i].u.clientMessage.u.l.longs1);
-            break;
-
-        case kXquartzWindowMoved:
-            DEBUG_LOG("kXquartzWindowMoved\n");
-            RootlessNativeWindowMoved ((WindowPtr)xe[i].u.clientMessage.u.l.longs0);
-            break;
-
-        case kXquartzToggleFullscreen:
-            DEBUG_LOG("kXquartzToggleFullscreen\n");
+    int i;
+    
+    TA_SERVER();
+    
+    DEBUG_LOG("DarwinEventHandler(%d, %p, %p, %d)\n", screenNum, xe, dev, nevents);
+    for (i=0; i<nevents; i++) {
+        switch(xe[i].u.u.type) {
+            case kXquartzControllerNotify:
+                DEBUG_LOG("kXquartzControllerNotify\n");
+                AppleWMSendEvent(AppleWMControllerNotify,
+                                 AppleWMControllerNotifyMask,
+                                 xe[i].u.clientMessage.u.l.longs0,
+                                 xe[i].u.clientMessage.u.l.longs1);
+                break;
+                
+            case kXquartzPasteboardNotify:
+                DEBUG_LOG("kXquartzPasteboardNotify\n");
+                AppleWMSendEvent(AppleWMPasteboardNotify,
+                                 AppleWMPasteboardNotifyMask,
+                                 xe[i].u.clientMessage.u.l.longs0,
+                                 xe[i].u.clientMessage.u.l.longs1);
+                break;
+                
+            case kXquartzActivate:
+                DEBUG_LOG("kXquartzActivate\n");
+                QuartzShow(xe[i].u.keyButtonPointer.rootX,
+                           xe[i].u.keyButtonPointer.rootY);
+                AppleWMSendEvent(AppleWMActivationNotify,
+                                 AppleWMActivationNotifyMask,
+                                 AppleWMIsActive, 0);
+                break;
+                
+            case kXquartzDeactivate:
+                DEBUG_LOG("kXquartzDeactivate\n");
+                DarwinReleaseModifiers();
+                AppleWMSendEvent(AppleWMActivationNotify,
+                                 AppleWMActivationNotifyMask,
+                                 AppleWMIsInactive, 0);
+                QuartzHide();
+                break;
+                
+            case kXquartzWindowState:
+                DEBUG_LOG("kXquartzWindowState\n");
+                RootlessNativeWindowStateChanged(xprGetXWindow(xe[i].u.clientMessage.u.l.longs0),
+                                                 xe[i].u.clientMessage.u.l.longs1);
+                break;
+                
+            case kXquartzWindowMoved:
+                DEBUG_LOG("kXquartzWindowMoved\n");
+                RootlessNativeWindowMoved ((WindowPtr)xe[i].u.clientMessage.u.l.longs0);
+                break;
+                
+            case kXquartzToggleFullscreen:
+                DEBUG_LOG("kXquartzToggleFullscreen\n");
 #ifdef DARWIN_DDX_MISSING
-            if (quartzEnableRootless) QuartzSetFullscreen(!quartzHasRoot);
-            else if (quartzHasRoot) QuartzHide();
-            else QuartzShow();
+                if (quartzEnableRootless) 
+                    QuartzSetFullscreen(!quartzHasRoot);
+                else if (quartzHasRoot)
+                    QuartzHide();
+                else
+                    QuartzShow();
 #else
-    //      ErrorF("kXquartzToggleFullscreen not implemented\n");               
+                //      ErrorF("kXquartzToggleFullscreen not implemented\n");               
 #endif
-            break;
-
-        case kXquartzSetRootless:
-            DEBUG_LOG("kXquartzSetRootless\n");
+                break;
+                
+            case kXquartzSetRootless:
+                DEBUG_LOG("kXquartzSetRootless\n");
 #ifdef DARWIN_DDX_MISSING
-            QuartzSetRootless(xe[i].u.clientMessage.u.l.longs0);
-            if (!quartzEnableRootless && !quartzHasRoot) QuartzHide();
+                QuartzSetRootless(xe[i].u.clientMessage.u.l.longs0);
+                if (!quartzEnableRootless && !quartzHasRoot)
+                    QuartzHide();
 #else
-    //      ErrorF("kXquartzSetRootless not implemented\n");                    
+                //      ErrorF("kXquartzSetRootless not implemented\n");                    
 #endif
-            break;
-
-        case kXquartzSetRootClip:
-            QuartzSetRootClip((BOOL)xe[i].u.clientMessage.u.l.longs0);
-		     break;
-
-        case kXquartzQuit:
-            GiveUp(0);
-            break;
-
-        case kXquartzBringAllToFront:
-     	    DEBUG_LOG("kXquartzBringAllToFront\n");
-            RootlessOrderAllWindows();
-            break;
-
-		case kXquartzSpaceChanged:
-            DEBUG_LOG("kXquartzSpaceChanged\n");
-            QuartzSpaceChanged(xe[i].u.clientMessage.u.l.longs0);
-
-            break;
-        default:
-            ErrorF("Unknown application defined event type %d.\n", xe[i].u.u.type);
+                break;
+                
+            case kXquartzSetRootClip:
+                QuartzSetRootClip((BOOL)xe[i].u.clientMessage.u.l.longs0);
+                break;
+                
+            case kXquartzQuit:
+                GiveUp(0);
+                break;
+                
+            case kXquartzBringAllToFront:
+                DEBUG_LOG("kXquartzBringAllToFront\n");
+                RootlessOrderAllWindows();
+                break;
+                
+            case kXquartzSpaceChanged:
+                DEBUG_LOG("kXquartzSpaceChanged\n");
+                QuartzSpaceChanged(xe[i].u.clientMessage.u.l.longs0);
+                break;
+
+            default:
+                ErrorF("Unknown application defined event type %d.\n", xe[i].u.u.type);
 		}	
-  }
+    }
 }
 
 Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) { 
+    int err;
+
     if (!darwinEvents)
         darwinEvents = (xEvent *)xcalloc(sizeof(xEvent), GetMaximumEventsNum());
     if (!darwinEvents)
         FatalError("Couldn't allocate event buffer\n");
 
+    if((err = pthread_mutex_init(&mieqEnqueue_mutex, NULL))) {
+        FatalError("Couldn't allocate miEnqueue mutex: %d.\n", err);
+    }
+    
     mieqInit();
     mieqSetHandler(kXquartzReloadKeymap, DarwinKeyboardReloadHandler);
     mieqSetHandler(kXquartzActivate, DarwinEventHandler);
@@ -305,7 +339,7 @@ Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) {
     mieqSetHandler(kXquartzSetRootClip, DarwinEventHandler);
     mieqSetHandler(kXquartzQuit, DarwinEventHandler);
     mieqSetHandler(kXquartzReadPasteboard, QuartzReadPasteboard);
-	mieqSetHandler(kXquartzWritePasteboard, QuartzWritePasteboard);
+    mieqSetHandler(kXquartzWritePasteboard, QuartzWritePasteboard);
     mieqSetHandler(kXquartzToggleFullscreen, DarwinEventHandler);
     mieqSetHandler(kXquartzSetRootless, DarwinEventHandler);
     mieqSetHandler(kXquartzSpaceChanged, DarwinEventHandler);
@@ -325,6 +359,8 @@ Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) {
 void ProcessInputEvents(void) {
     xEvent  xe;
 	int x = sizeof(xe);
+    
+    TA_SERVER();
 
     mieqProcessInputEvents();
 
@@ -336,7 +372,7 @@ void ProcessInputEvents(void) {
 
 /* Sends a null byte down darwinEventWriteFD, which will cause the
    Dispatch() event loop to check out event queue */
-void DarwinPokeEQ(void) {
+static void DarwinPokeEQ(void) {
 	char nullbyte=0;
 	input_check_flag++;
 	//  <daniels> oh, i ... er ... christ.
@@ -398,15 +434,18 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 		return;
 	} 
 
-	num_events = GetPointerEvents(darwinEvents, darwinPointer, ev_type, ev_button, 
-				POINTER_ABSOLUTE, 0, 5, valuators);
-      
-	for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
-	DarwinPokeEQ();
+    mieqEnqueue_lock(); {
+        num_events = GetPointerEvents(darwinEvents, darwinPointer, ev_type, ev_button, 
+                                      POINTER_ABSOLUTE, 0, 5, valuators);
+        for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
+        DarwinPokeEQ();
+
+    } mieqEnqueue_unlock();
 }
 
 void DarwinSendKeyboardEvents(int ev_type, int keycode) {
 	int i, num_events;
+
 	if(!darwinEvents) {
 		ErrorF("DarwinSendKeyboardEvents called before darwinEvents was initialized\n");
 		return;
@@ -425,9 +464,11 @@ void DarwinSendKeyboardEvents(int ev_type, int keycode) {
 		}
 	}
 
-	num_events = GetKeyboardEvents(darwinEvents, darwinKeyboard, ev_type, keycode + MIN_KEYCODE);
-	for(i=0; i<num_events; i++) mieqEnqueue(darwinKeyboard,&darwinEvents[i]);
-	DarwinPokeEQ();
+    mieqEnqueue_lock(); {
+        num_events = GetKeyboardEvents(darwinEvents, darwinKeyboard, ev_type, keycode + MIN_KEYCODE);
+        for(i=0; i<num_events; i++) mieqEnqueue(darwinKeyboard,&darwinEvents[i]);
+        DarwinPokeEQ();
+    } mieqEnqueue_unlock();
 }
 
 void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y, 
@@ -443,11 +484,12 @@ void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y,
 		return;
 	}
 
-	num_events = GetProximityEvents(darwinEvents, darwinPointer, ev_type,
-				0, 5, valuators);
-      
-	for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
-	DarwinPokeEQ();
+    mieqEnqueue_lock(); {
+        num_events = GetProximityEvents(darwinEvents, darwinPointer, ev_type,
+                                        0, 5, valuators);
+        for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
+        DarwinPokeEQ();
+    } mieqEnqueue_unlock();
 }
 
 
@@ -512,5 +554,7 @@ void DarwinSendDDXEvent(int type, int argc, ...) {
         va_end (args);
     }
 
+    mieqEnqueue_lock();
     mieqEnqueue(darwinPointer, &xe);
+    mieqEnqueue_unlock();
 }
diff --git a/hw/xquartz/darwinEvents.h b/hw/xquartz/darwinEvents.h
index 98426d6..c87d667 100644
--- a/hw/xquartz/darwinEvents.h
+++ b/hw/xquartz/darwinEvents.h
@@ -32,7 +32,6 @@ Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr);
 void DarwinEQEnqueue(const xEventPtr e);
 void DarwinEQPointerPost(DeviceIntPtr pDev, xEventPtr e);
 void DarwinEQSwitchScreen(ScreenPtr pScreen, Bool fromDIX);
-void DarwinPokeEQ(void);
 void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int pointer_y,
 			     float pressure, float tilt_x, float tilt_y);
 void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y, 
diff --git a/hw/xquartz/threadSafety.c b/hw/xquartz/threadSafety.c
index c0ec1e4..7835de6 100644
--- a/hw/xquartz/threadSafety.c
+++ b/hw/xquartz/threadSafety.c
@@ -36,7 +36,7 @@
 pthread_t SERVER_THREAD;
 pthread_t APPKIT_THREAD;
 
-static inline void spewCallStack(void) {
+void spewCallStack(void) {
     void* callstack[128];
     int i, frames = backtrace(callstack, 128);
     char** strs = backtrace_symbols(callstack, frames);
diff --git a/hw/xquartz/threadSafety.h b/hw/xquartz/threadSafety.h
index da3b599..ed2ad9f 100644
--- a/hw/xquartz/threadSafety.h
+++ b/hw/xquartz/threadSafety.h
@@ -36,6 +36,9 @@ extern pthread_t APPKIT_THREAD;
 
 #define threadSafetyID(tid) (pthread_equal((tid), SERVER_THREAD) ? "X Server Thread" : "Appkit Thread")
 
+/* Dump the call stack */
+void spewCallStack(void);
+
 /* Print message to ErrorF if we're in the wrong thread */
 void _threadAssert(pthread_t tid, const char *file, const char *fun, int line);
 
commit 55f80d754525398378de1ef28aa562bd29ee750f
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 17 14:21:31 2008 -0700

    XQuartz: A little more debugging output from threadSafety
    (cherry picked from commit f6fbdbf838ab77c3a4635f0b2356b1bbb060ff5b)

diff --git a/hw/xquartz/threadSafety.c b/hw/xquartz/threadSafety.c
index ff19863..c0ec1e4 100644
--- a/hw/xquartz/threadSafety.c
+++ b/hw/xquartz/threadSafety.c
@@ -36,7 +36,7 @@
 pthread_t SERVER_THREAD;
 pthread_t APPKIT_THREAD;
 
-static void spewCallStack(void) {
+static inline void spewCallStack(void) {
     void* callstack[128];
     int i, frames = backtrace(callstack, 128);
     char** strs = backtrace_symbols(callstack, frames);
@@ -48,12 +48,13 @@ static void spewCallStack(void) {
     free(strs);
 }
 
-void threadAssert(pthread_t tid) {
+void _threadAssert(pthread_t tid, const char *file, const char *fun, int line) {
     if(pthread_equal(pthread_self(), tid))
         return;
     
     /* NOOOO! */
-    ErrorF("Thread Assertion Failed: self=%s, expected=%s\n",
-            threadSafetyID(pthread_self()), threadSafetyID(tid));
+    ErrorF("Thread Assertion Failed: self=%s, expected=%s\n%s:%s:%d\n",
+           threadSafetyID(pthread_self()), threadSafetyID(tid),
+           file, fun, line);
     spewCallStack();
 }
diff --git a/hw/xquartz/threadSafety.h b/hw/xquartz/threadSafety.h
index 050469e..da3b599 100644
--- a/hw/xquartz/threadSafety.h
+++ b/hw/xquartz/threadSafety.h
@@ -27,6 +27,8 @@
 #ifndef _XQ_THREAD_SAFETY_H_
 #define _XQ_THREAD_SAFETY_H_
 
+#define DEBUG_THREADS 1
+
 #include <pthread.h>
 
 extern pthread_t SERVER_THREAD;
@@ -35,9 +37,16 @@ extern pthread_t APPKIT_THREAD;
 #define threadSafetyID(tid) (pthread_equal((tid), SERVER_THREAD) ? "X Server Thread" : "Appkit Thread")
 
 /* Print message to ErrorF if we're in the wrong thread */
-void threadAssert(pthread_t tid);
+void _threadAssert(pthread_t tid, const char *file, const char *fun, int line);
+
+#define threadAssert(tid) _threadAssert(tid, __FILE__, __FUNCTION__, __LINE__)
 
+#ifdef DEBUG_THREADS
 #define TA_SERVER() threadAssert(SERVER_THREAD)
 #define TA_APPKIT() threadAssert(APPKIT_THREAD)
+#else
+#define TA_SERVER() 
+#define TA_APPKIT() 
+#endif
 
 #endif _XQ_THREAD_SAFETY_H_
commit 0d61f6fca1efeb4f68488e323d1c0508b9b7a711
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 17 13:17:58 2008 -0700

    XQuartz: Fixed some missing prototypes
    (cherry picked from commit 95056afc562cfe58b116f5c36e4624018e79ff4a)

diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index 6a8cf7c..fb9f13c 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -52,6 +52,7 @@
 #include "windowstr.h"
 #include "colormapst.h"
 #include "globals.h"
+#include "mi.h"
 
 // System headers
 #include <sys/types.h>
diff --git a/hw/xquartz/quartz.h b/hw/xquartz/quartz.h
index ffe06f9..e116023 100644
--- a/hw/xquartz/quartz.h
+++ b/hw/xquartz/quartz.h
@@ -131,4 +131,9 @@ void QuartzInitInput(int argc, char **argv);
 void QuartzGiveUp(void);
 void QuartzProcessEvent(xEvent *xe);
 void QuartzDisplayChangedHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents);
+
+void QuartzShow(int x, int y); // (x, y) = cursor loc
+void QuartzHide(void);
+void QuartzSetRootClip(BOOL enable);
+void QuartzSpaceChanged(uint32_t space_id);
 #endif
commit dbd4c031565d269fef90af23386ff045ec78688c
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 17 13:12:56 2008 -0700

    XQuartz: Added framework for asserting which thread we're in.
    (cherry picked from commit 00beb982510e7a82d77e1f1d43e77c84d7bf74c2)

diff --git a/hw/xquartz/Makefile.am b/hw/xquartz/Makefile.am
index 6854557..1c97ac8 100644
--- a/hw/xquartz/Makefile.am
+++ b/hw/xquartz/Makefile.am
@@ -34,7 +34,8 @@ libXquartz_la_SOURCES = \
 	quartzForeground.c \
 	quartzKeyboard.c \
 	quartzPasteboard.c \
-	quartzStartup.c
+	quartzStartup.c \
+	threadSafety.c
 
 EXTRA_DIST = \
 	X11Application.h \
@@ -50,4 +51,5 @@ EXTRA_DIST = \
 	quartzCommon.h \
 	quartzForeground.h \
 	quartzKeyboard.h \
-	quartzPasteboard.h
+	quartzPasteboard.h \
+	threadSafety.h
diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 28bb6fb..31ac563 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -738,7 +738,7 @@ void X11ApplicationShowHideMenubar (int state) {
     [n release];
 }
 
-static void * create_thread (void *func, void *arg) {
+static pthread_t create_thread (void *func, void *arg) {
     pthread_attr_t attr;
     pthread_t tid;
 	
@@ -748,7 +748,7 @@ static void * create_thread (void *func, void *arg) {
     pthread_create (&tid, &attr, func, arg);
     pthread_attr_destroy (&attr);
 	
-    return (void *) tid;
+    return tid;
 }
 
 static void check_xinitrc (void) {
@@ -819,7 +819,10 @@ void X11ApplicationMain (int argc, const char **argv, void (*server_thread) (voi
     aquaMenuBarHeight = NSHeight([[NSScreen mainScreen] frame]) -
     NSMaxY([[NSScreen mainScreen] visibleFrame]);
   
-    if (!create_thread (server_thread, server_arg)) {
+    APPKIT_THREAD = pthread_self();
+    SERVER_THREAD = create_thread (server_thread, server_arg);
+
+    if (!SERVER_THREAD) {
         ErrorF("can't create secondary thread\n");
         exit (1);
     }
diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index df92d8b..3231077 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -34,6 +34,8 @@
 #include <X11/extensions/XKB.h>
 #include <assert.h>
 
+#include "threadSafety.h"
+
 typedef struct {
     void                *framebuffer;
     int                 x;
@@ -123,7 +125,7 @@ void DarwinSendDDXEvent(int type, int argc, ...);
 #ifdef ENABLE_DEBUG_LOG
 extern FILE *debug_log_fp;
 #define DEBUG_LOG_NAME "x11-debug.txt"
-#define DEBUG_LOG(msg, args...) if (debug_log_fp) fprintf(debug_log_fp, "%x:%s:%s:%d " msg, pthread_self(), __FILE__, __FUNCTION__, __LINE__, ##args ); fflush(debug_log_fp);
+#define DEBUG_LOG(msg, args...) if (debug_log_fp) fprintf(debug_log_fp, "%s:%s:%s:%d " msg, threadSafetyID(pthread_self()), __FILE__, __FUNCTION__, __LINE__, ##args ); fflush(debug_log_fp);
 #else
 #define DEBUG_LOG(msg, args...) 
 #endif
diff --git a/hw/xquartz/threadSafety.c b/hw/xquartz/threadSafety.c
new file mode 100644
index 0000000..ff19863
--- /dev/null
+++ b/hw/xquartz/threadSafety.c
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2008 Apple, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include "threadSafety.h"
+#include "os.h"
+
+#include <execinfo.h>
+
+pthread_t SERVER_THREAD;
+pthread_t APPKIT_THREAD;
+
+static void spewCallStack(void) {
+    void* callstack[128];
+    int i, frames = backtrace(callstack, 128);
+    char** strs = backtrace_symbols(callstack, frames);
+    
+    for (i = 0; i < frames; ++i) {
+        ErrorF("%s\n", strs[i]);
+    }
+    
+    free(strs);
+}
+
+void threadAssert(pthread_t tid) {
+    if(pthread_equal(pthread_self(), tid))
+        return;
+    
+    /* NOOOO! */
+    ErrorF("Thread Assertion Failed: self=%s, expected=%s\n",
+            threadSafetyID(pthread_self()), threadSafetyID(tid));
+    spewCallStack();
+}
diff --git a/hw/xquartz/threadSafety.h b/hw/xquartz/threadSafety.h
new file mode 100644
index 0000000..050469e
--- /dev/null
+++ b/hw/xquartz/threadSafety.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2008 Apple, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name(s) of the above copyright
+ * holders shall not be used in advertising or otherwise to promote the sale,
+ * use or other dealings in this Software without prior written authorization.
+ */
+
+#ifndef _XQ_THREAD_SAFETY_H_
+#define _XQ_THREAD_SAFETY_H_
+
+#include <pthread.h>
+
+extern pthread_t SERVER_THREAD;
+extern pthread_t APPKIT_THREAD;
+
+#define threadSafetyID(tid) (pthread_equal((tid), SERVER_THREAD) ? "X Server Thread" : "Appkit Thread")
+
+/* Print message to ErrorF if we're in the wrong thread */
+void threadAssert(pthread_t tid);
+
+#define TA_SERVER() threadAssert(SERVER_THREAD)
+#define TA_APPKIT() threadAssert(APPKIT_THREAD)
+
+#endif _XQ_THREAD_SAFETY_H_
commit fa0645b452cbebd1800a63f1c95cb77fef4ab211
Author: Ben Byer <bbyer at apple.com>
Date:   Thu Apr 17 12:27:12 2008 -0700

    removed Xquartz debugging code that leaked into master.  Our Bad.

diff --git a/dix/main.c b/dix/main.c
index 8f6507f..db43473 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -113,9 +113,6 @@ Equipment Corporation.
 #include "dispatch.h"		/* InitProcVectors() */
 #endif
 
-#include <pthread.h>
-pthread_key_t threadname_key=0;
-
 #ifdef DPMSExtension
 #define DPMS_SERVER
 #include <X11/extensions/dpms.h>
@@ -251,17 +248,6 @@ main(int argc, char *argv[], char *envp[])
     char	*xauthfile;
     HWEventQueueType	alwaysCheckForInput[2];
 
-    if(threadname_key == 0) ErrorF("pthread_key_create returned %d\n", pthread_key_create(&threadname_key, NULL));
-    ErrorF("threadname_key = %d\n", threadname_key);
-    if(pthread_getspecific(threadname_key) == NULL) {
-      char *nameptr = malloc(32);
-      sprintf(nameptr, "main thread %d", random());
-      //      strcpy(nameptr, "main thread");
-      ErrorF("calling: pthread_setspecific(%d, %s)=%d\n", threadname_key, nameptr, pthread_setspecific(threadname_key, nameptr));
-      if (pthread_getspecific(threadname_key) != NULL) ErrorF("current thread: %s\n", (char *)pthread_getspecific(threadname_key));
-    } else {
-      if (pthread_getspecific(threadname_key) != NULL) ErrorF("thread was already: %s\n", (char *)pthread_getspecific(threadname_key));
-    }
     display = "0";
 
     InitGlobals();
commit a3d40f0549f6c6f49fffc286bcdaad758fa92367
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 17 11:56:48 2008 -0700

    XQuartz: Include version info for CrashReporter
    (cherry picked from commit b4992755c3e29086c5939683c38fa8fd7d2e6754)

diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index 3704653..990b08e 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -142,6 +142,8 @@ const int NUMFORMATS = sizeof(formats)/sizeof(formats[0]);
 #define XORG_RELEASE "?"
 #endif
 
+const char *__crashreporter_info__ = "X.Org X Server " XSERVER_VERSION "Build Date: " BUILD_DATE;
+
 void DDXRingBell(int volume, int pitch, int duration) {
   // FIXME -- make some noise, yo
 }
commit 6d11712c2a35b243c19eea3b26622d18c2446dbe
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 17 11:06:54 2008 -0700

    XQuartz: Use strerror(errno)... cause I like text more than grepping header files
    (cherry picked from commit 1b4c37d8f9b517fbec5b94ed4e4a5e86a31472a5)

diff --git a/hw/xquartz/quartzKeyboard.c b/hw/xquartz/quartzKeyboard.c
index 56061fe..30eec1d 100644
--- a/hw/xquartz/quartzKeyboard.c
+++ b/hw/xquartz/quartzKeyboard.c
@@ -438,13 +438,13 @@ static Bool DarwinReadKeymapFile(NXKeyMapping *keyMap) {
 
     fref = fopen( darwinKeymapFile, "rb" );
     if (fref == NULL) {
-        ErrorF("Unable to open keymapping file '%s' (errno %d).\n",
-               darwinKeymapFile, errno);
+        ErrorF("Unable to open keymapping file '%s': %s.\n",
+               darwinKeymapFile, strerror(errno));
         return FALSE;
     }
     if (fstat(fileno(fref), &st) == -1) {
-        ErrorF("Could not stat keymapping file '%s' (errno %d).\n",
-               darwinKeymapFile, errno);
+        ErrorF("Could not stat keymapping file '%s': %s.\n",
+               darwinKeymapFile, strerror(errno));
         return FALSE;
     }
 
@@ -458,8 +458,8 @@ static Bool DarwinReadKeymapFile(NXKeyMapping *keyMap) {
     inBuffer = (char*) xalloc( st.st_size );
     bufferEnd = (int *) (inBuffer + st.st_size);
     if (fread(inBuffer, st.st_size, 1, fref) != 1) {
-        ErrorF("Could not read %qd bytes from keymapping file '%s' (errno %d).\n",
-               st.st_size, darwinKeymapFile, errno);
+        ErrorF("Could not read %qd bytes from keymapping file '%s': %s.\n",
+               st.st_size, darwinKeymapFile, strerror(errno));
         return FALSE;
     }
 
commit dcf4f917cc9488de72711255bbb030d9aa8f8bfb
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 17 11:03:31 2008 -0700

    merged darwinKeyboard.[ch] into quartzKeyboard
    (cherry picked from commit 57bb07320908b74facea0a97822bb19ed6f960a9)

diff --git a/hw/xquartz/Makefile.am b/hw/xquartz/Makefile.am
index 0753824..6854557 100644
--- a/hw/xquartz/Makefile.am
+++ b/hw/xquartz/Makefile.am
@@ -25,7 +25,6 @@ libXquartz_la_SOURCES = \
 	applewm.c \
 	darwin.c \
 	darwinEvents.c \
-	darwinKeyboard.c \
 	darwinXinput.c \
 	keysym2ucs.c \
 	pseudoramiX.c \
@@ -44,7 +43,6 @@ EXTRA_DIST = \
 	darwinClut8.h \
 	darwin.h \
 	darwinEvents.h \
-	darwinKeyboard.h \
 	keysym2ucs.h \
 	pseudoramiX.h \
 	quartz.h \
diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index 7d81a02..3704653 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -76,7 +76,7 @@
 
 #include "darwin.h"
 #include "darwinEvents.h"
-#include "darwinKeyboard.h"
+#include "quartzKeyboard.h"
 #include "quartz.h"
 //#include "darwinClut8.h"
 
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 37a66f7..260690c 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -48,7 +48,7 @@ in this Software without prior written authorization from The Open Group.
 
 #include "darwin.h"
 #include "quartz.h"
-#include "darwinKeyboard.h"
+#include "quartzKeyboard.h"
 #include "darwinEvents.h"
 
 #include <sys/types.h>
diff --git a/hw/xquartz/darwinKeyboard.c b/hw/xquartz/darwinKeyboard.c
deleted file mode 100644
index e72c894..0000000
--- a/hw/xquartz/darwinKeyboard.c
+++ /dev/null
@@ -1,965 +0,0 @@
-//=============================================================================
-//
-// Keyboard support for Xquartz
-//
-// Copyright (c) 2003, 2008 Apple, Inc.
-// Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
-// Copyright 2004 Kaleb S. KEITHLEY. All Rights Reserved.
-//
-// The code to parse the Darwin keymap is derived from dumpkeymap.c
-// by Eric Sunshine, which includes the following copyright:
-//
-// Copyright (C) 1999,2000 by Eric Sunshine <sunshine at sunshineco.com>
-// All rights reserved.
-//
-//-----------------------------------------------------------------------------
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-//   1. Redistributions of source code must retain the above copyright
-//      notice, this list of conditions and the following disclaimer.
-//   2. Redistributions in binary form must reproduce the above copyright
-//      notice, this list of conditions and the following disclaimer in the
-//      documentation and/or other materials provided with the distribution.
-//   3. The name of the author may not be used to endorse or promote products
-//      derived from this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
-// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
-// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
-// NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
-// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-//=============================================================================
-
-
-/*
-===========================================================================
-
- An X keyCode must be in the range XkbMinLegalKeyCode (8) to
- XkbMaxLegalKeyCode(255).
-
- The keyCodes we get from the kernel range from 0 to 127, so we need to
- offset the range before passing the keyCode to X.
-
- An X KeySym is an extended ascii code that is device independent.
-
- The modifier map is accessed by the keyCode, but the normal map is
- accessed by keyCode - MIN_KEYCODE.  Sigh.
-
-===========================================================================
-*/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-// Define this to get a diagnostic output to stderr which is helpful
-// in determining how the X server is interpreting the Darwin keymap.
-#define DUMP_DARWIN_KEYMAP
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <sys/stat.h>
-#include <IOKit/hidsystem/event_status_driver.h>
-#include <IOKit/hidsystem/ev_keymap.h>
-#include <architecture/byte_order.h>  // For the NXSwap*
-#include "darwin.h"
-#include "darwinKeyboard.h"
-#include "quartzKeyboard.h"
-#include "quartzAudio.h"
-
-#include <assert.h>
-
-#define AltMask         Mod1Mask
-#define MetaMask        Mod2Mask
-#define FunctionMask    Mod3Mask
-
-#define UK(a)           NoSymbol    // unknown symbol
-
-static KeySym const next_to_x[256] = {
-	NoSymbol,	NoSymbol,	NoSymbol,	XK_KP_Enter,
-	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-	XK_BackSpace,	XK_Tab,		XK_Linefeed,	NoSymbol,
-	NoSymbol,	XK_Return,	NoSymbol,	NoSymbol,
-	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-	NoSymbol,	NoSymbol,	NoSymbol,	XK_Escape,
-	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
-	XK_space,	XK_exclam,	XK_quotedbl,	XK_numbersign,
-	XK_dollar,	XK_percent,	XK_ampersand,	XK_apostrophe,
-	XK_parenleft,	XK_parenright,	XK_asterisk,	XK_plus,
-	XK_comma,	XK_minus,	XK_period,	XK_slash,
-	XK_0,		XK_1,		XK_2,		XK_3,
-	XK_4,		XK_5,		XK_6,		XK_7,
-	XK_8,		XK_9,		XK_colon,	XK_semicolon,
-	XK_less,	XK_equal,	XK_greater,	XK_question,
-	XK_at,		XK_A,		XK_B,		XK_C,
-	XK_D,		XK_E,		XK_F,		XK_G,
-	XK_H,		XK_I,		XK_J,		XK_K,
-	XK_L,		XK_M,		XK_N,		XK_O,
-	XK_P,		XK_Q,		XK_R,		XK_S,
-	XK_T,		XK_U,		XK_V,		XK_W,
-	XK_X,		XK_Y,		XK_Z,		XK_bracketleft,
-	XK_backslash,	XK_bracketright,XK_asciicircum,	XK_underscore,
-	XK_grave,	XK_a,		XK_b,		XK_c,
-	XK_d,		XK_e,		XK_f,		XK_g,
-	XK_h,		XK_i,		XK_j,		XK_k,
-	XK_l,		XK_m,		XK_n,		XK_o,
-	XK_p,		XK_q,		XK_r,		XK_s,
-	XK_t,		XK_u,		XK_v,		XK_w,
-	XK_x,		XK_y,		XK_z,		XK_braceleft,
-	XK_bar,		XK_braceright,	XK_asciitilde,	XK_BackSpace,
-// 128
-	NoSymbol,	XK_Agrave,	XK_Aacute,	XK_Acircumflex,
-	XK_Atilde,	XK_Adiaeresis,	XK_Aring,	XK_Ccedilla,
-	XK_Egrave,	XK_Eacute,	XK_Ecircumflex,	XK_Ediaeresis,
-	XK_Igrave,	XK_Iacute,	XK_Icircumflex,	XK_Idiaeresis,
-// 144
-	XK_ETH,		XK_Ntilde,	XK_Ograve,	XK_Oacute,
-	XK_Ocircumflex,	XK_Otilde,	XK_Odiaeresis,	XK_Ugrave,
-	XK_Uacute,	XK_Ucircumflex,	XK_Udiaeresis,	XK_Yacute,
-	XK_THORN,	XK_mu,		XK_multiply,	XK_division,
-// 160
-	XK_copyright,	XK_exclamdown,	XK_cent,	XK_sterling,
-	UK(fraction),	XK_yen,		UK(fhook),	XK_section,
-	XK_currency,	XK_rightsinglequotemark,
-					XK_leftdoublequotemark,
-							XK_guillemotleft,
-	XK_leftanglebracket,
-			XK_rightanglebracket,
-					UK(filigature),	UK(flligature),
-// 176
-	XK_registered,	XK_endash,	XK_dagger,	XK_doubledagger,
-	XK_periodcentered,XK_brokenbar,	XK_paragraph,	UK(bullet),
-	XK_singlelowquotemark,
-			XK_doublelowquotemark,
-					XK_rightdoublequotemark,
-							XK_guillemotright,
-	XK_ellipsis,	UK(permille),	XK_notsign,	XK_questiondown,
-// 192
-	XK_onesuperior,	XK_dead_grave,	XK_dead_acute,	XK_dead_circumflex,
-	XK_dead_tilde,	XK_dead_macron,	XK_dead_breve,	XK_dead_abovedot,
-	XK_dead_diaeresis,
-			XK_twosuperior,	XK_dead_abovering,
-							XK_dead_cedilla,
-	XK_threesuperior,
-			XK_dead_doubleacute,
-					XK_dead_ogonek,	XK_dead_caron,
-// 208
-	XK_emdash,	XK_plusminus,	XK_onequarter,	XK_onehalf,
-	XK_threequarters,
-			XK_agrave,	XK_aacute,	XK_acircumflex,
-	XK_atilde,	XK_adiaeresis,	XK_aring,	XK_ccedilla,
-	XK_egrave,	XK_eacute,	XK_ecircumflex,	XK_ediaeresis,
-// 224
-	XK_igrave,	XK_AE,		XK_iacute,	XK_ordfeminine,
-	XK_icircumflex,	XK_idiaeresis,	XK_eth,		XK_ntilde,
-	XK_Lstroke,	XK_Ooblique,	XK_OE,		XK_masculine,
-	XK_ograve,	XK_oacute,	XK_ocircumflex, XK_otilde,
-// 240
-	XK_odiaeresis,	XK_ae,		XK_ugrave,	XK_uacute,
-	XK_ucircumflex,	XK_idotless,	XK_udiaeresis,	XK_ygrave,
-	XK_lstroke,	XK_ooblique,	XK_oe,		XK_ssharp,
-	XK_thorn,	XK_ydiaeresis,	NoSymbol,	NoSymbol,
-  };
-
-#define MIN_SYMBOL      0xAC
-static KeySym const symbol_to_x[] = {
-    XK_Left,        XK_Up,          XK_Right,      XK_Down
-  };
-static int const NUM_SYMBOL = sizeof(symbol_to_x) / sizeof(symbol_to_x[0]);
-
-#define MIN_FUNCKEY     0x20
-static KeySym const funckey_to_x[] = {
-    XK_F1,          XK_F2,          XK_F3,          XK_F4,
-    XK_F5,          XK_F6,          XK_F7,          XK_F8,
-    XK_F9,          XK_F10,         XK_F11,         XK_F12,
-    XK_Insert,      XK_Delete,      XK_Home,        XK_End,
-    XK_Page_Up,     XK_Page_Down,   XK_F13,         XK_F14,
-    XK_F15
-  };
-static int const NUM_FUNCKEY = sizeof(funckey_to_x) / sizeof(funckey_to_x[0]);
-
-typedef struct {
-    KeySym      normalSym;
-    KeySym      keypadSym;
-} darwinKeyPad_t;
-
-static darwinKeyPad_t const normal_to_keypad[] = {
-    { XK_0,         XK_KP_0 },
-    { XK_1,         XK_KP_1 },
-    { XK_2,         XK_KP_2 },
-    { XK_3,         XK_KP_3 },
-    { XK_4,         XK_KP_4 },
-    { XK_5,         XK_KP_5 },
-    { XK_6,         XK_KP_6 },
-    { XK_7,         XK_KP_7 },
-    { XK_8,         XK_KP_8 },
-    { XK_9,         XK_KP_9 },
-    { XK_equal,     XK_KP_Equal },
-    { XK_asterisk,  XK_KP_Multiply },
-    { XK_plus,      XK_KP_Add },
-    { XK_comma,     XK_KP_Separator },
-    { XK_minus,     XK_KP_Subtract },
-    { XK_period,    XK_KP_Decimal },
-    { XK_slash,     XK_KP_Divide }
-};
-static int const NUM_KEYPAD = sizeof(normal_to_keypad) / sizeof(normal_to_keypad[0]);
-
-static void DarwinChangeKeyboardControl( DeviceIntPtr device, KeybdCtrl *ctrl )
-{
-	// FIXME: to be implemented
-    // keyclick, bell volume / pitch, autorepead, LED's
-}
-
-darwinKeyboardInfo keyInfo;
-static FILE *fref = NULL;
-static char *inBuffer = NULL;
-
-//-----------------------------------------------------------------------------
-// Data Stream Object
-//      Can be configured to treat embedded "numbers" as being composed of
-//      either 1, 2, or 4 bytes, apiece.
-//-----------------------------------------------------------------------------
-typedef struct _DataStream {
-    unsigned char const *data;
-    unsigned char const *data_end;
-    short number_size;  // Size in bytes of a "number" in the stream.
-} DataStream;
-
-static DataStream* new_data_stream(unsigned char const* data, int size) {
-    DataStream* s = (DataStream*)xalloc( sizeof(DataStream) );
-    if(s) {
-        s->data = data;
-        s->data_end = data + size;
-        s->number_size = 1; // Default to byte-sized numbers.
-    }
-    return s;
-}
-
-static void destroy_data_stream(DataStream* s) {
-    xfree(s);
-}
-
-static unsigned char get_byte(DataStream* s) {
-    assert(s->data + 1 <= s->data_end);
-    return *s->data++;
-}
-
-static short get_word(DataStream* s) {
-    short hi, lo;
-    assert(s->data + 2 <= s->data_end);
-    hi = *s->data++;
-    lo = *s->data++;
-    return ((hi << 8) | lo);
-}
-
-static int get_dword(DataStream* s) {
-    int b1, b2, b3, b4;
-    assert(s->data + 4 <= s->data_end);
-    b4 = *s->data++;
-    b3 = *s->data++;
-    b2 = *s->data++;
-    b1 = *s->data++;
-    return ((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
-}
-
-static int get_number(DataStream* s) {
-    switch (s->number_size) {
-        case 4:  return get_dword(s);
-        case 2:  return get_word(s);
-        default: return get_byte(s);
-    }
-}
-
-//-----------------------------------------------------------------------------
-// Utility functions to help parse Darwin keymap
-//-----------------------------------------------------------------------------
-
-/*
- * bits_set
- *      Calculate number of bits set in the modifier mask.
- */
-static short bits_set(short mask) {
-    short n = 0;
-
-    for ( ; mask != 0; mask >>= 1)
-        if ((mask & 0x01) != 0)
-            n++;
-    return n;
-}
-
-/*
- * parse_next_char_code
- *      Read the next character code from the Darwin keymapping
- *      and write it to the X keymap.
- */
-static void parse_next_char_code(DataStream *s, KeySym *k) {
-    const short charSet = get_number(s);
-    const short charCode = get_number(s);
-
-    if (charSet == 0) {                 // ascii character
-        if (charCode >= 0 && charCode < 256)
-            *k = next_to_x[charCode];
-    } else if (charSet == 0x01) {       // symbol character
-        if (charCode >= MIN_SYMBOL &&
-            charCode <= MIN_SYMBOL + NUM_SYMBOL)
-            *k = symbol_to_x[charCode - MIN_SYMBOL];
-    } else if (charSet == 0xFE) {       // function key
-        if (charCode >= MIN_FUNCKEY &&
-            charCode <= MIN_FUNCKEY + NUM_FUNCKEY)
-            *k = funckey_to_x[charCode - MIN_FUNCKEY];
-    }
-}
-
-
-/*
- * DarwinReadKeymapFile
- *      Read the appropriate keymapping from a keymapping file.
- */
-static Bool DarwinReadKeymapFile(NXKeyMapping *keyMap) {
-    struct stat         st;
-    NXEventSystemDevice info[20];
-    int                 interface = 0, handler_id = 0;
-    int                 map_interface, map_handler_id, map_size = 0;
-    unsigned int        i, size;
-    int                 *bufferEnd;
-    union km_tag {
-        int             *intP;
-        char            *charP;
-    } km;
-
-    fref = fopen( darwinKeymapFile, "rb" );
-    if (fref == NULL) {
-        ErrorF("Unable to open keymapping file '%s' (%s).\n",
-               darwinKeymapFile, strerror(errno));
-        return FALSE;
-    }
-    if (fstat(fileno(fref), &st) == -1) {
-        ErrorF("Could not stat keymapping file '%s' (%s).\n",
-               darwinKeymapFile, strerror(errno));
-        return FALSE;
-    }
-
-    // check to make sure we don't crash later
-    if (st.st_size <= 16*sizeof(int)) {
-        ErrorF("Keymapping file '%s' is invalid (too small).\n",
-               darwinKeymapFile);
-        return FALSE;
-    }
-
-    inBuffer = (char*) xalloc( st.st_size );
-    bufferEnd = (int *) (inBuffer + st.st_size);
-    if (fread(inBuffer, st.st_size, 1, fref) != 1) {
-        ErrorF("Could not read %qd bytes from keymapping file '%s' (%s).\n",
-               st.st_size, darwinKeymapFile, strerror(errno));
-        return FALSE;
-    }
-
-    if (strncmp( inBuffer, "KYM1", 4 ) == 0) {
-        // Magic number OK.
-    } else if (strncmp( inBuffer, "KYMP", 4 ) == 0) {
-        ErrorF("Keymapping file '%s' is intended for use with the original NeXT keyboards and cannot be used by XDarwin.\n", darwinKeymapFile);
-        return FALSE;
-    } else {
-        ErrorF("Keymapping file '%s' has a bad magic number and cannot be used by XDarwin.\n", darwinKeymapFile);
-        return FALSE;
-    }
-
-    // find the keyboard interface and handler id
-    size = sizeof( info ) / sizeof( int );
-    if (!NXEventSystemInfo( darwinParamConnect, NX_EVS_DEVICE_INFO,
-                            (NXEventSystemInfoType) info, &size )) {
-        ErrorF("Error reading event status driver info.\n");
-        return FALSE;
-    }
-
-    size = size * sizeof( int ) / sizeof( info[0] );
-    for( i = 0; i < size; i++) {
-        if (info[i].dev_type == NX_EVS_DEVICE_TYPE_KEYBOARD) {
-            Bool hasInterface = FALSE;
-            Bool hasMatch = FALSE;
-
-            interface = info[i].interface;
-            handler_id = info[i].id;
-
-            // Find an appropriate keymapping:
-            // The first time we try to match both interface and handler_id.
-            // If we can't match both, we take the first match for interface.
-
-            do {
-                km.charP = inBuffer;
-                km.intP++;
-                while (km.intP+3 < bufferEnd) {
-                    map_interface = NXSwapBigIntToHost(*(km.intP++));
-                    map_handler_id = NXSwapBigIntToHost(*(km.intP++));
-                    map_size = NXSwapBigIntToHost(*(km.intP++));
-                    if (map_interface == interface) {
-                        if (map_handler_id == handler_id || hasInterface) {
-                            hasMatch = TRUE;
-                            break;
-                        } else {
-                            hasInterface = TRUE;
-                        }
-                    }
-                    km.charP += map_size;
-                }
-            } while (hasInterface && !hasMatch);
-
-            if (hasMatch) {
-                // fill in NXKeyMapping structure
-                keyMap->size = map_size;
-                keyMap->mapping = (char*) xalloc(map_size);
-                memcpy(keyMap->mapping, km.charP, map_size);
-                return TRUE;
-            }
-        } // if dev_id == keyboard device
-    } // foreach info struct
-
-    // The keymapping file didn't match any of the info structs
-    // returned by NXEventSystemInfo.
-    ErrorF("Keymapping file '%s' did not contain appropriate keyboard interface.\n", darwinKeymapFile);
-    return FALSE;
-}
-
-
-/*
- * DarwinParseNXKeyMapping
- */
-static Bool DarwinParseNXKeyMapping(darwinKeyboardInfo  *info) {
-    KeySym              *k;
-    int                 i;
-    short               numMods, numKeys, numPadKeys = 0;
-    Bool                haveKeymap = FALSE;
-    NXKeyMapping        keyMap;
-    DataStream          *keyMapStream;
-    unsigned char const *numPadStart = 0;
-
-    if (darwinKeymapFile) {
-        haveKeymap = DarwinReadKeymapFile(&keyMap);
-        if (fref)
-            fclose(fref);
-        if (inBuffer)
-            xfree(inBuffer);
-        if (!haveKeymap) {
-            ErrorF("Reverting to kernel keymapping.\n");
-        }
-    }
-
-    if (!haveKeymap) {
-        // get the Darwin keyboard map
-        keyMap.size = NXKeyMappingLength( darwinParamConnect );
-        keyMap.mapping = (char*) xalloc( keyMap.size );
-        if (!NXGetKeyMapping( darwinParamConnect, &keyMap )) {
-            return FALSE;
-        }
-    }
-
-    keyMapStream = new_data_stream( (unsigned char const*)keyMap.mapping,
-                                    keyMap.size );
-
-    // check the type of map
-    if (get_word(keyMapStream)) {
-        keyMapStream->number_size = 2;
-        ErrorF("Current 16-bit keymapping may not be interpreted correctly.\n");
-    }
-
-    // Insert X modifier KeySyms into the keyboard map.
-    numMods = get_number(keyMapStream);
-    while (numMods-- > 0) {
-        int             left = 1;               // first keycode is left
-        short const     charCode = get_number(keyMapStream);
-        short           numKeyCodes = get_number(keyMapStream);
-
-        // This is just a marker, not a real modifier.
-        // Store numeric keypad keys for later.
-        if (charCode == NX_MODIFIERKEY_NUMERICPAD) {
-            numPadStart = keyMapStream->data;
-            numPadKeys = numKeyCodes;
-        }
-
-        while (numKeyCodes-- > 0) {
-            const short keyCode = get_number(keyMapStream);
-            if (charCode != NX_MODIFIERKEY_NUMERICPAD) {
-                switch (charCode) {
-                    case NX_MODIFIERKEY_ALPHALOCK:
-                        info->keyMap[keyCode * GLYPHS_PER_KEY] = XK_Caps_Lock;
-                        break;
-                    case NX_MODIFIERKEY_SHIFT:
-                        info->keyMap[keyCode * GLYPHS_PER_KEY] =
-                                (left ? XK_Shift_L : XK_Shift_R);
-                        break;
-                    case NX_MODIFIERKEY_CONTROL:
-                        info->keyMap[keyCode * GLYPHS_PER_KEY] =
-                                (left ? XK_Control_L : XK_Control_R);
-                        break;
-                    case NX_MODIFIERKEY_ALTERNATE:
-                        // info->keyMap[keyCode * GLYPHS_PER_KEY] = XK_Mode_switch;
-                        info->keyMap[keyCode * GLYPHS_PER_KEY] =
-                                (left ? XK_Alt_L : XK_Alt_R);
-                        break;
-                    case NX_MODIFIERKEY_COMMAND:
-                        info->keyMap[keyCode * GLYPHS_PER_KEY] =
-                                (left ? XK_Meta_L : XK_Meta_R);
-                        break;
-                    case NX_MODIFIERKEY_SECONDARYFN:
-                        info->keyMap[keyCode * GLYPHS_PER_KEY] =
-                                (left ? XK_Control_L : XK_Control_R);
-                        break;
-                    case NX_MODIFIERKEY_HELP:
-                        // Help is not an X11 modifier; treat as normal key
-                        info->keyMap[keyCode * GLYPHS_PER_KEY] = XK_Help;
-                        break;
-                }
-            }
-            left = 0;
-        }
-    }
-
-    // Convert the Darwin keyboard mapping to an X keyboard map.
-    // A key can have a different character code for each combination of
-    // modifiers. We currently ignore all modifier combinations except
-    // those with Shift, AlphaLock, and Alt.
-    numKeys = get_number(keyMapStream);
-    for (i = 0, k = info->keyMap; i < numKeys; i++, k += GLYPHS_PER_KEY) {
-        short const     charGenMask = get_number(keyMapStream);
-        if (charGenMask != 0xFF) {              // is key bound?
-            short       numKeyCodes = 1 << bits_set(charGenMask);
-
-            // Record unmodified case
-            parse_next_char_code( keyMapStream, k );
-            numKeyCodes--;
-
-            // If AlphaLock and Shift modifiers produce different codes,
-            // we record the Shift case since X handles AlphaLock.
-            if (charGenMask & 0x01) {       // AlphaLock
-                parse_next_char_code( keyMapStream, k+1 );
-                numKeyCodes--;
-            }
-
-            if (charGenMask & 0x02) {       // Shift
-                parse_next_char_code( keyMapStream, k+1 );
-                numKeyCodes--;
-
-                if (charGenMask & 0x01) {   // Shift-AlphaLock
-                    get_number(keyMapStream); get_number(keyMapStream);
-                    numKeyCodes--;
-                }
-            }
-
-            // Skip the Control cases
-            if (charGenMask & 0x04) {       // Control
-                get_number(keyMapStream); get_number(keyMapStream);
-                numKeyCodes--;
-
-                if (charGenMask & 0x01) {   // Control-AlphaLock
-                    get_number(keyMapStream); get_number(keyMapStream);
-                    numKeyCodes--;
-                }
-
-                if (charGenMask & 0x02) {   // Control-Shift
-                    get_number(keyMapStream); get_number(keyMapStream);
-                    numKeyCodes--;
-
-                    if (charGenMask & 0x01) {   // Shift-Control-AlphaLock
-                        get_number(keyMapStream); get_number(keyMapStream);
-                        numKeyCodes--;
-                    }
-                }
-            }
-
-            // Process Alt cases
-            if (charGenMask & 0x08) {       // Alt
-                parse_next_char_code( keyMapStream, k+2 );
-                numKeyCodes--;
-
-                if (charGenMask & 0x01) {   // Alt-AlphaLock
-                    parse_next_char_code( keyMapStream, k+3 );
-                    numKeyCodes--;
-                }
-
-                if (charGenMask & 0x02) {   // Alt-Shift
-                    parse_next_char_code( keyMapStream, k+3 );
-                    numKeyCodes--;
-
-                    if (charGenMask & 0x01) {   // Alt-Shift-AlphaLock
-                        get_number(keyMapStream); get_number(keyMapStream);
-                        numKeyCodes--;
-                    }
-                }
-            }
-
-            while (numKeyCodes-- > 0) {
-                get_number(keyMapStream); get_number(keyMapStream);
-            }
-
-            if (k[3] == k[2]) k[3] = NoSymbol;
-            if (k[2] == k[1]) k[2] = NoSymbol;
-            if (k[1] == k[0]) k[1] = NoSymbol;
-            if (k[0] == k[2] && k[1] == k[3]) k[2] = k[3] = NoSymbol;
-        }
-    }
-
-    // Now we have to go back through the list of keycodes that are on the
-    // numeric keypad and update the X keymap.
-    keyMapStream->data = numPadStart;
-    while(numPadKeys-- > 0) {
-        const short keyCode = get_number(keyMapStream);
-        k = &info->keyMap[keyCode * GLYPHS_PER_KEY];
-        for (i = 0; i < NUM_KEYPAD; i++) {
-            if (*k == normal_to_keypad[i].normalSym) {
-                k[0] = normal_to_keypad[i].keypadSym;
-                break;
-            }
-        }
-    }
-
-    // free Darwin keyboard map
-    destroy_data_stream( keyMapStream );
-    xfree( keyMap.mapping );
-
-    return TRUE;
-}
-
-/*
- * DarwinBuildModifierMaps
- *      Use the keyMap field of keyboard info structure to populate
- *      the modMap and modifierKeycodes fields.
- */
-static void DarwinBuildModifierMaps(darwinKeyboardInfo *info) {
-    int i;
-    KeySym *k;
-
-    memset(info->modMap, NoSymbol, sizeof(info->modMap));
-    memset(info->modifierKeycodes, 0, sizeof(info->modifierKeycodes));
-
-    for (i = 0; i < NUM_KEYCODES; i++) {
-        k = info->keyMap + i * GLYPHS_PER_KEY;
-
-        switch (*k) {
-            case XK_Shift_L:
-                info->modifierKeycodes[NX_MODIFIERKEY_SHIFT][0] = i;
-                info->modMap[MIN_KEYCODE + i] = ShiftMask;
-                break;
-
-            case XK_Shift_R:
-#ifdef NX_MODIFIERKEY_RSHIFT
-                info->modifierKeycodes[NX_MODIFIERKEY_RSHIFT][0] = i;
-#else
-                info->modifierKeycodes[NX_MODIFIERKEY_SHIFT][0] = i;
-#endif
-                info->modMap[MIN_KEYCODE + i] = ShiftMask;
-                break;
-
-            case XK_Control_L:
-                info->modifierKeycodes[NX_MODIFIERKEY_CONTROL][0] = i;
-                info->modMap[MIN_KEYCODE + i] = ControlMask;
-                break;
-
-            case XK_Control_R:
-#ifdef NX_MODIFIERKEY_RCONTROL
-                info->modifierKeycodes[NX_MODIFIERKEY_RCONTROL][0] = i;
-#else
-                info->modifierKeycodes[NX_MODIFIERKEY_CONTROL][0] = i;
-#endif
-                info->modMap[MIN_KEYCODE + i] = ControlMask;
-                break;
-
-            case XK_Caps_Lock:
-                info->modifierKeycodes[NX_MODIFIERKEY_ALPHALOCK][0] = i;
-                info->modMap[MIN_KEYCODE + i] = LockMask;
-                break;
-
-            case XK_Alt_L:
-                info->modifierKeycodes[NX_MODIFIERKEY_ALTERNATE][0] = i;
-                info->modMap[MIN_KEYCODE + i] = Mod1Mask;
-                *k = XK_Mode_switch; // Yes, this is ugly.  This needs to be cleaned up when we integrate quartzKeyboard with this code and refactor.
-                break;
-
-            case XK_Alt_R:
-#ifdef NX_MODIFIERKEY_RALTERNATE
-                info->modifierKeycodes[NX_MODIFIERKEY_RALTERNATE][0] = i;
-#else
-                info->modifierKeycodes[NX_MODIFIERKEY_ALTERNATE][0] = i;
-#endif
-                *k = XK_Mode_switch; // Yes, this is ugly.  This needs to be cleaned up when we integrate quartzKeyboard with this code and refactor.
-                info->modMap[MIN_KEYCODE + i] = Mod1Mask;
-                break;
-
-            case XK_Mode_switch:
-                info->modMap[MIN_KEYCODE + i] = Mod1Mask;
-                break;
-
-            case XK_Meta_L:
-                info->modifierKeycodes[NX_MODIFIERKEY_COMMAND][0] = i;
-                info->modMap[MIN_KEYCODE + i] = Mod2Mask;
-                break;
-
-            case XK_Meta_R:
-#ifdef NX_MODIFIERKEY_RCOMMAND
-                info->modifierKeycodes[NX_MODIFIERKEY_RCOMMAND][0] = i;
-#else
-                info->modifierKeycodes[NX_MODIFIERKEY_COMMAND][0] = i;
-#endif
-                info->modMap[MIN_KEYCODE + i] = Mod2Mask;
-                break;
-
-            case XK_Num_Lock:
-                info->modMap[MIN_KEYCODE + i] = Mod3Mask;
-                break;
-        }
-    }
-}
-
-/*
- * DarwinLoadKeyboardMapping
- *  Load the keyboard map from a file or system and convert
- *  it to an equivalent X keyboard map and modifier map.
- */
-static void DarwinLoadKeyboardMapping(KeySymsRec *keySyms) {
-    memset(keyInfo.keyMap, 0, sizeof(keyInfo.keyMap));
-
-    /* TODO: Clean this up
-     * QuartzReadSystemKeymap is in quartz/quartzKeyboard.c
-     * DarwinParseNXKeyMapping is here
-     */
-    if (!DarwinParseNXKeyMapping(&keyInfo)) {
-        DEBUG_LOG("DarwinParseNXKeyMapping returned 0... running QuartzReadSystemKeymap().\n");
-        if (!QuartzReadSystemKeymap(&keyInfo)) {
-            FatalError("Could not build a valid keymap.");
-        }
-    }
-
-    DarwinBuildModifierMaps(&keyInfo);
-
-#ifdef DUMP_DARWIN_KEYMAP
-    int i;
-    KeySym *k;
-    DEBUG_LOG("Darwin -> X converted keyboard map\n");
-    for (i = 0, k = keyInfo.keyMap; i < NX_NUMKEYCODES;
-         i++, k += GLYPHS_PER_KEY)
-    {
-        int j;
-        for (j = 0; j < GLYPHS_PER_KEY; j++) {
-            if (k[j] == NoSymbol) {
-                DEBUG_LOG("0x%02x:\tNoSym\n", i);
-            } else {
-                DEBUG_LOG("0x%02x:\t0x%lx\n", i, k[j]);
-            }
-        }
-    }
-#endif
-
-    keySyms->map        = keyInfo.keyMap;
-    keySyms->mapWidth   = GLYPHS_PER_KEY;
-    keySyms->minKeyCode = MIN_KEYCODE;
-    keySyms->maxKeyCode = MAX_KEYCODE;
-}
-
-
-/*
- * DarwinKeyboardInit
- *      Get the Darwin keyboard map and compute an equivalent
- *      X keyboard map and modifier map. Set the new keyboard
- *      device structure.
- */
-void DarwinKeyboardInit(DeviceIntPtr pDev) {
-    KeySymsRec          keySyms;
-
-    // Open a shared connection to the HID System.
-    // Note that the Event Status Driver is really just a wrapper
-    // for a kIOHIDParamConnectType connection.
-    assert( darwinParamConnect = NXOpenEventStatus() );
-
-    DarwinLoadKeyboardMapping(&keySyms);
-    //    DarwinKeyboardReload(pDev);
-    /* Initialize the seed, so we don't reload the keymap unnecessarily
-       (and possibly overwrite xinitrc changes) */
-    QuartzSystemKeymapSeed();
-
-    assert( InitKeyboardDeviceStruct( (DevicePtr)pDev, &keySyms,
-                                      keyInfo.modMap, QuartzBell,
-                                      DarwinChangeKeyboardControl ));
-    SwitchCoreKeyboard(pDev);
-}
-
-
-void DarwinKeyboardReloadHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents) {
-    KeySymsRec keySyms;
-	if (dev == NULL) dev = darwinKeyboard;
-	
-	DEBUG_LOG("DarwinKeyboardReloadHandler(%p)\n", dev);
-    DarwinLoadKeyboardMapping(&keySyms);
-
-	if (dev->key) {
-		if (dev->key->curKeySyms.map) xfree(dev->key->curKeySyms.map);
-		if (dev->key->modifierKeyMap) xfree(dev->key->modifierKeyMap);
-		xfree(dev->key);
-	}
-	
-	if (!InitKeyClassDeviceStruct(dev, &keySyms, keyInfo.modMap)) {
-		DEBUG_LOG("InitKeyClassDeviceStruct failed\n");
-		return;
-	}
-
-    SendMappingNotify(MappingKeyboard, MIN_KEYCODE, NUM_KEYCODES, 0);
-    SendMappingNotify(MappingModifier, 0, 0, 0);
-}
-
-
-//-----------------------------------------------------------------------------
-// Modifier translation functions
-//
-// There are three different ways to specify a Mac modifier key:
-// keycode - specifies hardware key, read from keymapping
-// key     - NX_MODIFIERKEY_*, really an index
-// mask    - NX_*MASK, mask for modifier flags in event record
-// Left and right side have different keycodes but the same key and mask.
-//-----------------------------------------------------------------------------
-
-/*
- * DarwinModifierNXKeyToNXKeycode
- *      Return the keycode for an NX_MODIFIERKEY_* modifier.
- *      side = 0 for left or 1 for right.
- *      Returns 0 if key+side is not a known modifier.
- */
-int DarwinModifierNXKeyToNXKeycode(int key, int side) {
-    return keyInfo.modifierKeycodes[key][side];
-}
-
-/*
- * DarwinModifierNXKeycodeToNXKey
- *      Returns -1 if keycode+side is not a modifier key
- *      outSide may be NULL, else it gets 0 for left and 1 for right.
- */
-int DarwinModifierNXKeycodeToNXKey(unsigned char keycode, int *outSide) {
-    int key, side;
-
-    keycode += MIN_KEYCODE;
-    // search modifierKeycodes for this keycode+side
-    for (key = 0; key < NX_NUMMODIFIERS; key++) {
-        for (side = 0; side <= 1; side++) {
-            if (keyInfo.modifierKeycodes[key][side] == keycode) break;
-        }
-    }
-    if (key == NX_NUMMODIFIERS) return -1;
-    if (outSide) *outSide = side;
-    return key;
-}
-
-/*
- * DarwinModifierNXMaskToNXKey
- *      Returns -1 if mask is not a known modifier mask.
- */
-int DarwinModifierNXMaskToNXKey(int mask) {
-    switch (mask) {
-        case NX_ALPHASHIFTMASK:       return NX_MODIFIERKEY_ALPHALOCK;
-        case NX_SHIFTMASK:            return NX_MODIFIERKEY_SHIFT;
-#ifdef NX_DEVICELSHIFTKEYMASK
-        case NX_DEVICELSHIFTKEYMASK:  return NX_MODIFIERKEY_SHIFT;
-        case NX_DEVICERSHIFTKEYMASK:  return NX_MODIFIERKEY_RSHIFT;
-#endif
-        case NX_CONTROLMASK:          return NX_MODIFIERKEY_CONTROL;
-#ifdef NX_DEVICELCTLKEYMASK
-        case NX_DEVICELCTLKEYMASK:    return NX_MODIFIERKEY_CONTROL;
-        case NX_DEVICERCTLKEYMASK:    return NX_MODIFIERKEY_RCONTROL;
-#endif
-        case NX_ALTERNATEMASK:        return NX_MODIFIERKEY_ALTERNATE;
-#ifdef NX_DEVICELALTKEYMASK
-        case NX_DEVICELALTKEYMASK:    return NX_MODIFIERKEY_ALTERNATE;
-        case NX_DEVICERALTKEYMASK:    return NX_MODIFIERKEY_RALTERNATE;
-#endif
-        case NX_COMMANDMASK:          return NX_MODIFIERKEY_COMMAND;
-#ifdef NX_DEVICELCMDKEYMASK
-        case NX_DEVICELCMDKEYMASK:    return NX_MODIFIERKEY_COMMAND;
-        case NX_DEVICERCMDKEYMASK:    return NX_MODIFIERKEY_RCOMMAND;
-#endif
-        case NX_NUMERICPADMASK:       return NX_MODIFIERKEY_NUMERICPAD;
-        case NX_HELPMASK:             return NX_MODIFIERKEY_HELP;
-        case NX_SECONDARYFNMASK:      return NX_MODIFIERKEY_SECONDARYFN;
-    }
-    return -1;
-}
-
-static const char *DarwinModifierNXMaskTostring(int mask) {
-    switch (mask) {
-        case NX_ALPHASHIFTMASK:      return "NX_ALPHASHIFTMASK";
-        case NX_SHIFTMASK:           return "NX_SHIFTMASK";
-        case NX_DEVICELSHIFTKEYMASK: return "NX_DEVICELSHIFTKEYMASK";
-        case NX_DEVICERSHIFTKEYMASK: return "NX_DEVICERSHIFTKEYMASK";
-        case NX_CONTROLMASK:         return "NX_CONTROLMASK";
-        case NX_DEVICELCTLKEYMASK:   return "NX_DEVICELCTLKEYMASK";
-        case NX_DEVICERCTLKEYMASK:   return "NX_DEVICERCTLKEYMASK";
-        case NX_ALTERNATEMASK:       return "NX_ALTERNATEMASK";
-        case NX_DEVICELALTKEYMASK:   return "NX_DEVICELALTKEYMASK";
-        case NX_DEVICERALTKEYMASK:   return "NX_DEVICERALTKEYMASK";
-        case NX_COMMANDMASK:         return "NX_COMMANDMASK";
-        case NX_DEVICELCMDKEYMASK:   return "NX_DEVICELCMDKEYMASK";
-        case NX_DEVICERCMDKEYMASK:   return "NX_DEVICERCMDKEYMASK";
-        case NX_NUMERICPADMASK:      return "NX_NUMERICPADMASK";
-        case NX_HELPMASK:            return "NX_HELPMASK";
-        case NX_SECONDARYFNMASK:     return "NX_SECONDARYFNMASK";
-    }
-    return "unknown mask";
-}
-
-/*
- * DarwinModifierNXKeyToNXMask
- *      Returns 0 if key is not a known modifier key.
- */
-int DarwinModifierNXKeyToNXMask(int key) {
-    switch (key) {
-        case NX_MODIFIERKEY_ALPHALOCK:   return NX_ALPHASHIFTMASK;
-        case NX_MODIFIERKEY_SHIFT:       return NX_SHIFTMASK;
-#ifdef NX_MODIFIERKEY_RSHIFT
-        case NX_MODIFIERKEY_RSHIFT:      return NX_SHIFTMASK;
-#endif
-        case NX_MODIFIERKEY_CONTROL:     return NX_CONTROLMASK;
-#ifdef NX_MODIFIERKEY_RCONTROL
-        case NX_MODIFIERKEY_RCONTROL:    return NX_CONTROLMASK;
-#endif
-        case NX_MODIFIERKEY_ALTERNATE:   return NX_ALTERNATEMASK;
-#ifdef NX_MODIFIERKEY_RALTERNATE
-        case NX_MODIFIERKEY_RALTERNATE:  return NX_ALTERNATEMASK;
-#endif
-        case NX_MODIFIERKEY_COMMAND:     return NX_COMMANDMASK;
-#ifdef NX_MODIFIERKEY_RCOMMAND
-        case NX_MODIFIERKEY_RCOMMAND:    return NX_COMMANDMASK;
-#endif
-        case NX_MODIFIERKEY_NUMERICPAD:  return NX_NUMERICPADMASK;
-        case NX_MODIFIERKEY_HELP:        return NX_HELPMASK;
-        case NX_MODIFIERKEY_SECONDARYFN: return NX_SECONDARYFNMASK;
-    }
-    return 0;
-}
-
-/*
- * DarwinModifierStringToNXKey
- *      Returns -1 if string is not a known modifier.
- */
-int DarwinModifierStringToNXKey(const char *str) {
-    if      (!strcasecmp(str, "shift"))   return NX_MODIFIERKEY_SHIFT;
-    else if (!strcasecmp(str, "control")) return NX_MODIFIERKEY_CONTROL;
-    else if (!strcasecmp(str, "option"))  return NX_MODIFIERKEY_ALTERNATE;
-    else if (!strcasecmp(str, "command")) return NX_MODIFIERKEY_COMMAND;
-    else if (!strcasecmp(str, "fn"))      return NX_MODIFIERKEY_SECONDARYFN;
-    else return -1;
-}
-
-/*
- * LegalModifier
- *      This allows the ddx layer to prevent some keys from being remapped
- *      as modifier keys.
- */
-Bool LegalModifier(unsigned int key, DeviceIntPtr pDev)
-{
-    return 1;
-}
diff --git a/hw/xquartz/darwinKeyboard.h b/hw/xquartz/darwinKeyboard.h
deleted file mode 100644
index 762f659..0000000
--- a/hw/xquartz/darwinKeyboard.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2003-2004 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-
-#ifndef DARWIN_KEYBOARD_H
-#define DARWIN_KEYBOARD_H 1
-
-#include "quartzKeyboard.h"
-
-/* Provided for darwinEvents.c */
-extern darwinKeyboardInfo keyInfo;
-void DarwinKeyboardReloadHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents);
-void DarwinKeyboardInit(DeviceIntPtr pDev);
-int DarwinModifierNXKeycodeToNXKey(unsigned char keycode, int *outSide);
-int DarwinModifierNXKeyToNXKeycode(int key, int side);
-int DarwinModifierNXKeyToNXMask(int key);
-int DarwinModifierNXMaskToNXKey(int mask);
-int DarwinModifierStringToNXKey(const char *string);
-
-/* Provided for darwin.c */
-void DarwinKeyboardInit(DeviceIntPtr pDev);
-
-#endif /* DARWIN_KEYBOARD_H */
diff --git a/hw/xquartz/quartzKeyboard.c b/hw/xquartz/quartzKeyboard.c
index 9b899ca..56061fe 100644
--- a/hw/xquartz/quartzKeyboard.c
+++ b/hw/xquartz/quartzKeyboard.c
@@ -1,51 +1,81 @@
 /*
-   quartzKeyboard.c
-
-   Code to build a keymap using the Carbon Keyboard Layout API.
-
-   Copyright (c) 2003-2007 Apple Inc.
-
-   Permission is hereby granted, free of charge, to any person
-   obtaining a copy of this software and associated documentation files
-   (the "Software"), to deal in the Software without restriction,
-   including without limitation the rights to use, copy, modify, merge,
-   publish, distribute, sublicense, and/or sell copies of the Software,
-   and to permit persons to whom the Software is furnished to do so,
-   subject to the following conditions:
-
-   The above copyright notice and this permission notice shall be
-   included in all copies or substantial portions of the Software.
-
-   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-   NONINFRINGEMENT.  IN NO EVENT SHALL THE ABOVE LISTED COPYRIGHT
-   HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-   DEALINGS IN THE SOFTWARE.
-
-   Except as contained in this notice, the name(s) of the above
-   copyright holders shall not be used in advertising or otherwise to
-   promote the sale, use or other dealings in this Software without
-   prior written authorization.
+   quartzKeyboard.c: Keyboard support for Xquartz
+
+   Copyright (c) 2003-2008 Apple Inc.
+   Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
+   Copyright 2004 Kaleb S. KEITHLEY. All Rights Reserved.
+
+   The code to parse the Darwin keymap is derived from dumpkeymap.c
+   by Eric Sunshine, which includes the following copyright:
+
+   Copyright (C) 1999,2000 by Eric Sunshine <sunshine at sunshineco.com>
+   All rights reserved.
+
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are met:
+
+     1. Redistributions of source code must retain the above copyright
+        notice, this list of conditions and the following disclaimer.
+     2. Redistributions in binary form must reproduce the above copyright
+        notice, this list of conditions and the following disclaimer in the
+        documentation and/or other materials provided with the distribution.
+     3. The name of the author may not be used to endorse or promote products
+        derived from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
+   NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
 
+// Define this to get a diagnostic output to stderr which is helpful
+// in determining how the X server is interpreting the Darwin keymap.
+#define DUMP_DARWIN_KEYMAP
+
+#define HACK_MISSING 1
+#define HACK_KEYPAD 1
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <sys/stat.h>
+
 #include "quartzCommon.h"
 
 #include <CoreServices/CoreServices.h>
 #include <Carbon/Carbon.h>
+#include <IOKit/hidsystem/event_status_driver.h>
+#include <IOKit/hidsystem/ev_keymap.h>
+#include <architecture/byte_order.h>  // For the NXSwap*
+#include "darwin.h"
 
 #include "quartzKeyboard.h"
+#include "quartzAudio.h"
+
+#ifdef NDEBUG
+#undef NDEBUG
+#include <assert.h>
+#define NDEBUG 1
+#else
+#include <assert.h>
+#endif
+
+
+
+
 #include "X11/keysym.h"
 #include "keysym2ucs.h"
 
-#define HACK_MISSING 1
-#define HACK_KEYPAD 1
 
 enum {
     MOD_COMMAND = 256,
@@ -56,6 +86,143 @@ enum {
 
 #define UKEYSYM(u) ((u) | 0x01000000)
 
+#define AltMask         Mod1Mask
+#define MetaMask        Mod2Mask
+#define FunctionMask    Mod3Mask
+
+#define UK(a)           NoSymbol    // unknown symbol
+
+static KeySym const next_to_x[256] = {
+	NoSymbol,	NoSymbol,	NoSymbol,	XK_KP_Enter,
+	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+	XK_BackSpace,	XK_Tab,		XK_Linefeed,	NoSymbol,
+	NoSymbol,	XK_Return,	NoSymbol,	NoSymbol,
+	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+	NoSymbol,	NoSymbol,	NoSymbol,	XK_Escape,
+	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
+	XK_space,	XK_exclam,	XK_quotedbl,	XK_numbersign,
+	XK_dollar,	XK_percent,	XK_ampersand,	XK_apostrophe,
+	XK_parenleft,	XK_parenright,	XK_asterisk,	XK_plus,
+	XK_comma,	XK_minus,	XK_period,	XK_slash,
+	XK_0,		XK_1,		XK_2,		XK_3,
+	XK_4,		XK_5,		XK_6,		XK_7,
+	XK_8,		XK_9,		XK_colon,	XK_semicolon,
+	XK_less,	XK_equal,	XK_greater,	XK_question,
+	XK_at,		XK_A,		XK_B,		XK_C,
+	XK_D,		XK_E,		XK_F,		XK_G,
+	XK_H,		XK_I,		XK_J,		XK_K,
+	XK_L,		XK_M,		XK_N,		XK_O,
+	XK_P,		XK_Q,		XK_R,		XK_S,
+	XK_T,		XK_U,		XK_V,		XK_W,
+	XK_X,		XK_Y,		XK_Z,		XK_bracketleft,
+	XK_backslash,	XK_bracketright,XK_asciicircum,	XK_underscore,
+	XK_grave,	XK_a,		XK_b,		XK_c,
+	XK_d,		XK_e,		XK_f,		XK_g,
+	XK_h,		XK_i,		XK_j,		XK_k,
+	XK_l,		XK_m,		XK_n,		XK_o,
+	XK_p,		XK_q,		XK_r,		XK_s,
+	XK_t,		XK_u,		XK_v,		XK_w,
+	XK_x,		XK_y,		XK_z,		XK_braceleft,
+	XK_bar,		XK_braceright,	XK_asciitilde,	XK_BackSpace,
+// 128
+	NoSymbol,	XK_Agrave,	XK_Aacute,	XK_Acircumflex,
+	XK_Atilde,	XK_Adiaeresis,	XK_Aring,	XK_Ccedilla,
+	XK_Egrave,	XK_Eacute,	XK_Ecircumflex,	XK_Ediaeresis,
+	XK_Igrave,	XK_Iacute,	XK_Icircumflex,	XK_Idiaeresis,
+// 144
+	XK_ETH,		XK_Ntilde,	XK_Ograve,	XK_Oacute,
+	XK_Ocircumflex,	XK_Otilde,	XK_Odiaeresis,	XK_Ugrave,
+	XK_Uacute,	XK_Ucircumflex,	XK_Udiaeresis,	XK_Yacute,
+	XK_THORN,	XK_mu,		XK_multiply,	XK_division,
+// 160
+	XK_copyright,	XK_exclamdown,	XK_cent,	XK_sterling,
+	UK(fraction),	XK_yen,		UK(fhook),	XK_section,
+	XK_currency,	XK_rightsinglequotemark,
+					XK_leftdoublequotemark,
+							XK_guillemotleft,
+	XK_leftanglebracket,
+			XK_rightanglebracket,
+					UK(filigature),	UK(flligature),
+// 176
+	XK_registered,	XK_endash,	XK_dagger,	XK_doubledagger,
+	XK_periodcentered,XK_brokenbar,	XK_paragraph,	UK(bullet),
+	XK_singlelowquotemark,
+			XK_doublelowquotemark,
+					XK_rightdoublequotemark,
+							XK_guillemotright,
+	XK_ellipsis,	UK(permille),	XK_notsign,	XK_questiondown,
+// 192
+	XK_onesuperior,	XK_dead_grave,	XK_dead_acute,	XK_dead_circumflex,
+	XK_dead_tilde,	XK_dead_macron,	XK_dead_breve,	XK_dead_abovedot,
+	XK_dead_diaeresis,
+			XK_twosuperior,	XK_dead_abovering,
+							XK_dead_cedilla,
+	XK_threesuperior,
+			XK_dead_doubleacute,
+					XK_dead_ogonek,	XK_dead_caron,
+// 208
+	XK_emdash,	XK_plusminus,	XK_onequarter,	XK_onehalf,
+	XK_threequarters,
+			XK_agrave,	XK_aacute,	XK_acircumflex,
+	XK_atilde,	XK_adiaeresis,	XK_aring,	XK_ccedilla,
+	XK_egrave,	XK_eacute,	XK_ecircumflex,	XK_ediaeresis,
+// 224
+	XK_igrave,	XK_AE,		XK_iacute,	XK_ordfeminine,
+	XK_icircumflex,	XK_idiaeresis,	XK_eth,		XK_ntilde,
+	XK_Lstroke,	XK_Ooblique,	XK_OE,		XK_masculine,
+	XK_ograve,	XK_oacute,	XK_ocircumflex, XK_otilde,
+// 240
+	XK_odiaeresis,	XK_ae,		XK_ugrave,	XK_uacute,
+	XK_ucircumflex,	XK_idotless,	XK_udiaeresis,	XK_ygrave,
+	XK_lstroke,	XK_ooblique,	XK_oe,		XK_ssharp,
+	XK_thorn,	XK_ydiaeresis,	NoSymbol,	NoSymbol,
+  };
+
+#define MIN_SYMBOL      0xAC
+static KeySym const symbol_to_x[] = {
+    XK_Left,        XK_Up,          XK_Right,      XK_Down
+  };
+static int const NUM_SYMBOL = sizeof(symbol_to_x) / sizeof(symbol_to_x[0]);
+
+#define MIN_FUNCKEY     0x20
+static KeySym const funckey_to_x[] = {
+    XK_F1,          XK_F2,          XK_F3,          XK_F4,
+    XK_F5,          XK_F6,          XK_F7,          XK_F8,
+    XK_F9,          XK_F10,         XK_F11,         XK_F12,
+    XK_Insert,      XK_Delete,      XK_Home,        XK_End,
+    XK_Page_Up,     XK_Page_Down,   XK_F13,         XK_F14,
+    XK_F15
+  };
+static int const NUM_FUNCKEY = sizeof(funckey_to_x) / sizeof(funckey_to_x[0]);
+
+typedef struct {
+    KeySym      normalSym;
+    KeySym      keypadSym;
+} darwinKeyPad_t;
+
+static darwinKeyPad_t const normal_to_keypad[] = {
+    { XK_0,         XK_KP_0 },
+    { XK_1,         XK_KP_1 },
+    { XK_2,         XK_KP_2 },
+    { XK_3,         XK_KP_3 },
+    { XK_4,         XK_KP_4 },
+    { XK_5,         XK_KP_5 },
+    { XK_6,         XK_KP_6 },
+    { XK_7,         XK_KP_7 },
+    { XK_8,         XK_KP_8 },
+    { XK_9,         XK_KP_9 },
+    { XK_equal,     XK_KP_Equal },
+    { XK_asterisk,  XK_KP_Multiply },
+    { XK_plus,      XK_KP_Add },
+    { XK_comma,     XK_KP_Separator },
+    { XK_minus,     XK_KP_Subtract },
+    { XK_period,    XK_KP_Decimal },
+    { XK_slash,     XK_KP_Divide }
+};
+
+static int const NUM_KEYPAD = sizeof(normal_to_keypad) / sizeof(normal_to_keypad[0]);
+
 /* Table of keycode->keysym mappings we use to fallback on for important
    keys that are often not in the Unicode mapping. */
 
@@ -146,6 +313,756 @@ const static struct {
     {UKEYSYM (0x31b), XK_dead_horn},		/* COMBINING HORN */
 };
 
+darwinKeyboardInfo keyInfo;
+static FILE *fref = NULL;
+static char *inBuffer = NULL;
+
+static void DarwinChangeKeyboardControl( DeviceIntPtr device, KeybdCtrl *ctrl )
+{
+	// FIXME: to be implemented
+    // keyclick, bell volume / pitch, autorepead, LED's
+}
+
+//-----------------------------------------------------------------------------
+// Data Stream Object
+//      Can be configured to treat embedded "numbers" as being composed of
+//      either 1, 2, or 4 bytes, apiece.
+//-----------------------------------------------------------------------------
+typedef struct _DataStream {
+    unsigned char const *data;
+    unsigned char const *data_end;
+    short number_size;  // Size in bytes of a "number" in the stream.
+} DataStream;
+
+static DataStream* new_data_stream(unsigned char const* data, int size) {
+    DataStream* s = (DataStream*)xalloc( sizeof(DataStream) );
+    if(s) {
+        s->data = data;
+        s->data_end = data + size;
+        s->number_size = 1; // Default to byte-sized numbers.
+    }
+    return s;
+}
+
+static void destroy_data_stream(DataStream* s) {
+    xfree(s);
+}
+
+static unsigned char get_byte(DataStream* s) {
+    assert(s->data + 1 <= s->data_end);
+    return *s->data++;
+}
+
+static short get_word(DataStream* s) {
+    short hi, lo;
+    assert(s->data + 2 <= s->data_end);
+    hi = *s->data++;
+    lo = *s->data++;
+    return ((hi << 8) | lo);
+}
+
+static int get_dword(DataStream* s) {
+    int b1, b2, b3, b4;
+    assert(s->data + 4 <= s->data_end);
+    b4 = *s->data++;
+    b3 = *s->data++;
+    b2 = *s->data++;
+    b1 = *s->data++;
+    return ((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
+}
+
+static int get_number(DataStream* s) {
+    switch (s->number_size) {
+        case 4:  return get_dword(s);
+        case 2:  return get_word(s);
+        default: return get_byte(s);
+    }
+}
+
+//-----------------------------------------------------------------------------
+// Utility functions to help parse Darwin keymap
+//-----------------------------------------------------------------------------
+
+/*
+ * bits_set
+ *      Calculate number of bits set in the modifier mask.
+ */
+static short bits_set(short mask) {
+    short n = 0;
+
+    for ( ; mask != 0; mask >>= 1)
+        if ((mask & 0x01) != 0)
+            n++;
+    return n;
+}
+
+/*
+ * parse_next_char_code
+ *      Read the next character code from the Darwin keymapping
+ *      and write it to the X keymap.
+ */
+static void parse_next_char_code(DataStream *s, KeySym *k) {
+    const short charSet = get_number(s);
+    const short charCode = get_number(s);
+
+    if (charSet == 0) {                 // ascii character
+        if (charCode >= 0 && charCode < 256)
+            *k = next_to_x[charCode];
+    } else if (charSet == 0x01) {       // symbol character
+        if (charCode >= MIN_SYMBOL &&
+            charCode <= MIN_SYMBOL + NUM_SYMBOL)
+            *k = symbol_to_x[charCode - MIN_SYMBOL];
+    } else if (charSet == 0xFE) {       // function key
+        if (charCode >= MIN_FUNCKEY &&
+            charCode <= MIN_FUNCKEY + NUM_FUNCKEY)
+            *k = funckey_to_x[charCode - MIN_FUNCKEY];
+    }
+}
+
+
+/*
+ * DarwinReadKeymapFile
+ *      Read the appropriate keymapping from a keymapping file.
+ */
+static Bool DarwinReadKeymapFile(NXKeyMapping *keyMap) {
+    struct stat         st;
+    NXEventSystemDevice info[20];
+    int                 interface = 0, handler_id = 0;
+    int                 map_interface, map_handler_id, map_size = 0;
+    unsigned int        i, size;
+    int                 *bufferEnd;
+    union km_tag {
+        int             *intP;
+        char            *charP;
+    } km;
+
+    fref = fopen( darwinKeymapFile, "rb" );
+    if (fref == NULL) {
+        ErrorF("Unable to open keymapping file '%s' (errno %d).\n",
+               darwinKeymapFile, errno);
+        return FALSE;
+    }
+    if (fstat(fileno(fref), &st) == -1) {
+        ErrorF("Could not stat keymapping file '%s' (errno %d).\n",
+               darwinKeymapFile, errno);
+        return FALSE;
+    }
+
+    // check to make sure we don't crash later
+    if (st.st_size <= 16*sizeof(int)) {
+        ErrorF("Keymapping file '%s' is invalid (too small).\n",
+               darwinKeymapFile);
+        return FALSE;
+    }
+
+    inBuffer = (char*) xalloc( st.st_size );
+    bufferEnd = (int *) (inBuffer + st.st_size);
+    if (fread(inBuffer, st.st_size, 1, fref) != 1) {
+        ErrorF("Could not read %qd bytes from keymapping file '%s' (errno %d).\n",
+               st.st_size, darwinKeymapFile, errno);
+        return FALSE;
+    }
+
+    if (strncmp( inBuffer, "KYM1", 4 ) == 0) {
+        // Magic number OK.
+    } else if (strncmp( inBuffer, "KYMP", 4 ) == 0) {
+        ErrorF("Keymapping file '%s' is intended for use with the original NeXT keyboards and cannot be used by XDarwin.\n", darwinKeymapFile);
+        return FALSE;
+    } else {
+        ErrorF("Keymapping file '%s' has a bad magic number and cannot be used by XDarwin.\n", darwinKeymapFile);
+        return FALSE;
+    }
+
+    // find the keyboard interface and handler id
+    size = sizeof( info ) / sizeof( int );
+    if (!NXEventSystemInfo( darwinParamConnect, NX_EVS_DEVICE_INFO,
+                            (NXEventSystemInfoType) info, &size )) {
+        ErrorF("Error reading event status driver info.\n");
+        return FALSE;
+    }
+
+    size = size * sizeof( int ) / sizeof( info[0] );
+    for( i = 0; i < size; i++) {
+        if (info[i].dev_type == NX_EVS_DEVICE_TYPE_KEYBOARD) {
+            Bool hasInterface = FALSE;
+            Bool hasMatch = FALSE;
+
+            interface = info[i].interface;
+            handler_id = info[i].id;
+
+            // Find an appropriate keymapping:
+            // The first time we try to match both interface and handler_id.
+            // If we can't match both, we take the first match for interface.
+
+            do {
+                km.charP = inBuffer;
+                km.intP++;
+                while (km.intP+3 < bufferEnd) {
+                    map_interface = NXSwapBigIntToHost(*(km.intP++));
+                    map_handler_id = NXSwapBigIntToHost(*(km.intP++));
+                    map_size = NXSwapBigIntToHost(*(km.intP++));
+                    if (map_interface == interface) {
+                        if (map_handler_id == handler_id || hasInterface) {
+                            hasMatch = TRUE;
+                            break;
+                        } else {
+                            hasInterface = TRUE;
+                        }
+                    }
+                    km.charP += map_size;
+                }
+            } while (hasInterface && !hasMatch);
+
+            if (hasMatch) {
+                // fill in NXKeyMapping structure
+                keyMap->size = map_size;
+                keyMap->mapping = (char*) xalloc(map_size);
+                memcpy(keyMap->mapping, km.charP, map_size);
+                return TRUE;
+            }
+        } // if dev_id == keyboard device
+    } // foreach info struct
+
+    // The keymapping file didn't match any of the info structs
+    // returned by NXEventSystemInfo.
+    ErrorF("Keymapping file '%s' did not contain appropriate keyboard interface.\n", darwinKeymapFile);
+    return FALSE;
+}
+
+
+/*
+ * DarwinParseNXKeyMapping
+ */
+static Bool DarwinParseNXKeyMapping(darwinKeyboardInfo  *info) {
+    KeySym              *k;
+    int                 i;
+    short               numMods, numKeys, numPadKeys = 0;
+    Bool                haveKeymap = FALSE;
+    NXKeyMapping        keyMap;
+    DataStream          *keyMapStream;
+    unsigned char const *numPadStart = 0;
+
+    if (darwinKeymapFile) {
+        haveKeymap = DarwinReadKeymapFile(&keyMap);
+        if (fref)
+            fclose(fref);
+        if (inBuffer)
+            xfree(inBuffer);
+        if (!haveKeymap) {
+            ErrorF("Reverting to kernel keymapping.\n");
+        }
+    }
+
+    if (!haveKeymap) {
+        // get the Darwin keyboard map
+        keyMap.size = NXKeyMappingLength( darwinParamConnect );
+        keyMap.mapping = (char*) xalloc( keyMap.size );
+        if (!NXGetKeyMapping( darwinParamConnect, &keyMap )) {
+            return FALSE;
+        }
+    }
+
+    keyMapStream = new_data_stream( (unsigned char const*)keyMap.mapping,
+                                    keyMap.size );
+
+    // check the type of map
+    if (get_word(keyMapStream)) {
+        keyMapStream->number_size = 2;
+        ErrorF("Current 16-bit keymapping may not be interpreted correctly.\n");
+    }
+
+    // Insert X modifier KeySyms into the keyboard map.
+    numMods = get_number(keyMapStream);
+    while (numMods-- > 0) {
+        int             left = 1;               // first keycode is left
+        short const     charCode = get_number(keyMapStream);
+        short           numKeyCodes = get_number(keyMapStream);
+
+        // This is just a marker, not a real modifier.
+        // Store numeric keypad keys for later.
+        if (charCode == NX_MODIFIERKEY_NUMERICPAD) {
+            numPadStart = keyMapStream->data;
+            numPadKeys = numKeyCodes;
+        }
+
+        while (numKeyCodes-- > 0) {
+            const short keyCode = get_number(keyMapStream);
+            if (charCode != NX_MODIFIERKEY_NUMERICPAD) {
+                switch (charCode) {
+                    case NX_MODIFIERKEY_ALPHALOCK:
+                        info->keyMap[keyCode * GLYPHS_PER_KEY] = XK_Caps_Lock;
+                        break;
+                    case NX_MODIFIERKEY_SHIFT:
+                        info->keyMap[keyCode * GLYPHS_PER_KEY] =
+                                (left ? XK_Shift_L : XK_Shift_R);
+                        break;
+                    case NX_MODIFIERKEY_CONTROL:
+                        info->keyMap[keyCode * GLYPHS_PER_KEY] =
+                                (left ? XK_Control_L : XK_Control_R);
+                        break;
+                    case NX_MODIFIERKEY_ALTERNATE:
+                        // info->keyMap[keyCode * GLYPHS_PER_KEY] = XK_Mode_switch;
+                        info->keyMap[keyCode * GLYPHS_PER_KEY] =
+                                (left ? XK_Alt_L : XK_Alt_R);
+                        break;
+                    case NX_MODIFIERKEY_COMMAND:
+                        info->keyMap[keyCode * GLYPHS_PER_KEY] =
+                                (left ? XK_Meta_L : XK_Meta_R);
+                        break;
+                    case NX_MODIFIERKEY_SECONDARYFN:
+                        info->keyMap[keyCode * GLYPHS_PER_KEY] =
+                                (left ? XK_Control_L : XK_Control_R);
+                        break;
+                    case NX_MODIFIERKEY_HELP:
+                        // Help is not an X11 modifier; treat as normal key
+                        info->keyMap[keyCode * GLYPHS_PER_KEY] = XK_Help;
+                        break;
+                }
+            }
+            left = 0;
+        }
+    }
+
+    // Convert the Darwin keyboard mapping to an X keyboard map.
+    // A key can have a different character code for each combination of
+    // modifiers. We currently ignore all modifier combinations except
+    // those with Shift, AlphaLock, and Alt.
+    numKeys = get_number(keyMapStream);
+    for (i = 0, k = info->keyMap; i < numKeys; i++, k += GLYPHS_PER_KEY) {
+        short const     charGenMask = get_number(keyMapStream);
+        if (charGenMask != 0xFF) {              // is key bound?
+            short       numKeyCodes = 1 << bits_set(charGenMask);
+
+            // Record unmodified case
+            parse_next_char_code( keyMapStream, k );
+            numKeyCodes--;
+
+            // If AlphaLock and Shift modifiers produce different codes,
+            // we record the Shift case since X handles AlphaLock.
+            if (charGenMask & 0x01) {       // AlphaLock
+                parse_next_char_code( keyMapStream, k+1 );
+                numKeyCodes--;
+            }
+
+            if (charGenMask & 0x02) {       // Shift
+                parse_next_char_code( keyMapStream, k+1 );
+                numKeyCodes--;
+
+                if (charGenMask & 0x01) {   // Shift-AlphaLock
+                    get_number(keyMapStream); get_number(keyMapStream);
+                    numKeyCodes--;
+                }
+            }
+
+            // Skip the Control cases
+            if (charGenMask & 0x04) {       // Control
+                get_number(keyMapStream); get_number(keyMapStream);
+                numKeyCodes--;
+
+                if (charGenMask & 0x01) {   // Control-AlphaLock
+                    get_number(keyMapStream); get_number(keyMapStream);
+                    numKeyCodes--;
+                }
+
+                if (charGenMask & 0x02) {   // Control-Shift
+                    get_number(keyMapStream); get_number(keyMapStream);
+                    numKeyCodes--;
+
+                    if (charGenMask & 0x01) {   // Shift-Control-AlphaLock
+                        get_number(keyMapStream); get_number(keyMapStream);
+                        numKeyCodes--;
+                    }
+                }
+            }
+
+            // Process Alt cases
+            if (charGenMask & 0x08) {       // Alt
+                parse_next_char_code( keyMapStream, k+2 );
+                numKeyCodes--;
+
+                if (charGenMask & 0x01) {   // Alt-AlphaLock
+                    parse_next_char_code( keyMapStream, k+3 );
+                    numKeyCodes--;
+                }
+
+                if (charGenMask & 0x02) {   // Alt-Shift
+                    parse_next_char_code( keyMapStream, k+3 );
+                    numKeyCodes--;
+
+                    if (charGenMask & 0x01) {   // Alt-Shift-AlphaLock
+                        get_number(keyMapStream); get_number(keyMapStream);
+                        numKeyCodes--;
+                    }
+                }
+            }
+
+            while (numKeyCodes-- > 0) {
+                get_number(keyMapStream); get_number(keyMapStream);
+            }
+
+            if (k[3] == k[2]) k[3] = NoSymbol;
+            if (k[2] == k[1]) k[2] = NoSymbol;
+            if (k[1] == k[0]) k[1] = NoSymbol;
+            if (k[0] == k[2] && k[1] == k[3]) k[2] = k[3] = NoSymbol;
+        }
+    }
+
+    // Now we have to go back through the list of keycodes that are on the
+    // numeric keypad and update the X keymap.
+    keyMapStream->data = numPadStart;
+    while(numPadKeys-- > 0) {
+        const short keyCode = get_number(keyMapStream);
+        k = &info->keyMap[keyCode * GLYPHS_PER_KEY];
+        for (i = 0; i < NUM_KEYPAD; i++) {
+            if (*k == normal_to_keypad[i].normalSym) {
+                k[0] = normal_to_keypad[i].keypadSym;
+                break;
+            }
+        }
+    }
+
+    // free Darwin keyboard map
+    destroy_data_stream( keyMapStream );
+    xfree( keyMap.mapping );
+
+    return TRUE;
+}
+
+/*
+ * DarwinBuildModifierMaps
+ *      Use the keyMap field of keyboard info structure to populate
+ *      the modMap and modifierKeycodes fields.
+ */
+static void DarwinBuildModifierMaps(darwinKeyboardInfo *info) {
+    int i;
+    KeySym *k;
+
+    memset(info->modMap, NoSymbol, sizeof(info->modMap));
+    memset(info->modifierKeycodes, 0, sizeof(info->modifierKeycodes));
+
+    for (i = 0; i < NUM_KEYCODES; i++) {
+        k = info->keyMap + i * GLYPHS_PER_KEY;
+
+        switch (*k) {
+            case XK_Shift_L:
+                info->modifierKeycodes[NX_MODIFIERKEY_SHIFT][0] = i;
+                info->modMap[MIN_KEYCODE + i] = ShiftMask;
+                break;
+
+            case XK_Shift_R:
+#ifdef NX_MODIFIERKEY_RSHIFT
+                info->modifierKeycodes[NX_MODIFIERKEY_RSHIFT][0] = i;
+#else
+                info->modifierKeycodes[NX_MODIFIERKEY_SHIFT][0] = i;
+#endif
+                info->modMap[MIN_KEYCODE + i] = ShiftMask;
+                break;
+
+            case XK_Control_L:
+                info->modifierKeycodes[NX_MODIFIERKEY_CONTROL][0] = i;
+                info->modMap[MIN_KEYCODE + i] = ControlMask;
+                break;
+
+            case XK_Control_R:
+#ifdef NX_MODIFIERKEY_RCONTROL
+                info->modifierKeycodes[NX_MODIFIERKEY_RCONTROL][0] = i;
+#else
+                info->modifierKeycodes[NX_MODIFIERKEY_CONTROL][0] = i;
+#endif
+                info->modMap[MIN_KEYCODE + i] = ControlMask;
+                break;
+
+            case XK_Caps_Lock:
+                info->modifierKeycodes[NX_MODIFIERKEY_ALPHALOCK][0] = i;
+                info->modMap[MIN_KEYCODE + i] = LockMask;
+                break;
+
+            case XK_Alt_L:
+                info->modifierKeycodes[NX_MODIFIERKEY_ALTERNATE][0] = i;
+                info->modMap[MIN_KEYCODE + i] = Mod1Mask;
+                *k = XK_Mode_switch; // Yes, this is ugly.  This needs to be cleaned up when we integrate quartzKeyboard with this code and refactor.
+                break;
+
+            case XK_Alt_R:
+#ifdef NX_MODIFIERKEY_RALTERNATE
+                info->modifierKeycodes[NX_MODIFIERKEY_RALTERNATE][0] = i;
+#else
+                info->modifierKeycodes[NX_MODIFIERKEY_ALTERNATE][0] = i;
+#endif
+                *k = XK_Mode_switch; // Yes, this is ugly.  This needs to be cleaned up when we integrate quartzKeyboard with this code and refactor.
+                info->modMap[MIN_KEYCODE + i] = Mod1Mask;
+                break;
+
+            case XK_Mode_switch:
+                info->modMap[MIN_KEYCODE + i] = Mod1Mask;
+                break;
+
+            case XK_Meta_L:
+                info->modifierKeycodes[NX_MODIFIERKEY_COMMAND][0] = i;
+                info->modMap[MIN_KEYCODE + i] = Mod2Mask;
+                break;
+
+            case XK_Meta_R:
+#ifdef NX_MODIFIERKEY_RCOMMAND
+                info->modifierKeycodes[NX_MODIFIERKEY_RCOMMAND][0] = i;
+#else
+                info->modifierKeycodes[NX_MODIFIERKEY_COMMAND][0] = i;
+#endif
+                info->modMap[MIN_KEYCODE + i] = Mod2Mask;
+                break;
+
+            case XK_Num_Lock:
+                info->modMap[MIN_KEYCODE + i] = Mod3Mask;
+                break;
+        }
+    }
+}
+
+/*
+ * DarwinLoadKeyboardMapping
+ *  Load the keyboard map from a file or system and convert
+ *  it to an equivalent X keyboard map and modifier map.
+ */
+static void DarwinLoadKeyboardMapping(KeySymsRec *keySyms) {
+    memset(keyInfo.keyMap, 0, sizeof(keyInfo.keyMap));
+
+    /* TODO: Clean this up
+     * QuartzReadSystemKeymap is in quartz/quartzKeyboard.c
+     * DarwinParseNXKeyMapping is here
+     */
+    if (!DarwinParseNXKeyMapping(&keyInfo)) {
+        DEBUG_LOG("DarwinParseNXKeyMapping returned 0... running QuartzReadSystemKeymap().\n");
+        if (!QuartzReadSystemKeymap(&keyInfo)) {
+            FatalError("Could not build a valid keymap.");
+        }
+    }
+
+    DarwinBuildModifierMaps(&keyInfo);
+
+#ifdef DUMP_DARWIN_KEYMAP
+    int i;
+    KeySym *k;
+    DEBUG_LOG("Darwin -> X converted keyboard map\n");
+    for (i = 0, k = keyInfo.keyMap; i < NX_NUMKEYCODES;
+         i++, k += GLYPHS_PER_KEY)
+    {
+        int j;
+        for (j = 0; j < GLYPHS_PER_KEY; j++) {
+            if (k[j] == NoSymbol) {
+                DEBUG_LOG("0x%02x:\tNoSym\n", i);
+            } else {
+                DEBUG_LOG("0x%02x:\t0x%lx\n", i, k[j]);
+            }
+        }
+    }
+#endif
+
+    keySyms->map        = keyInfo.keyMap;
+    keySyms->mapWidth   = GLYPHS_PER_KEY;
+    keySyms->minKeyCode = MIN_KEYCODE;
+    keySyms->maxKeyCode = MAX_KEYCODE;
+}
+
+
+/*
+ * DarwinKeyboardInit
+ *      Get the Darwin keyboard map and compute an equivalent
+ *      X keyboard map and modifier map. Set the new keyboard
+ *      device structure.
+ */
+void DarwinKeyboardInit(DeviceIntPtr pDev) {
+    KeySymsRec          keySyms;
+
+    // Open a shared connection to the HID System.
+    // Note that the Event Status Driver is really just a wrapper
+    // for a kIOHIDParamConnectType connection.
+    assert( darwinParamConnect = NXOpenEventStatus() );
+
+    DarwinLoadKeyboardMapping(&keySyms);
+    //    DarwinKeyboardReload(pDev);
+    /* Initialize the seed, so we don't reload the keymap unnecessarily
+       (and possibly overwrite xinitrc changes) */
+    QuartzSystemKeymapSeed();
+
+    assert( InitKeyboardDeviceStruct( (DevicePtr)pDev, &keySyms,
+                                      keyInfo.modMap, QuartzBell,
+                                      DarwinChangeKeyboardControl ));
+    SwitchCoreKeyboard(pDev);
+}
+
+
+void DarwinKeyboardReloadHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents) {
+    KeySymsRec keySyms;
+	if (dev == NULL) dev = darwinKeyboard;
+	
+	DEBUG_LOG("DarwinKeyboardReloadHandler(%p)\n", dev);
+    DarwinLoadKeyboardMapping(&keySyms);
+
+	if (dev->key) {
+		if (dev->key->curKeySyms.map) xfree(dev->key->curKeySyms.map);
+		if (dev->key->modifierKeyMap) xfree(dev->key->modifierKeyMap);
+		xfree(dev->key);
+	}
+	
+	if (!InitKeyClassDeviceStruct(dev, &keySyms, keyInfo.modMap)) {
+		DEBUG_LOG("InitKeyClassDeviceStruct failed\n");
+		return;
+	}
+
+    SendMappingNotify(MappingKeyboard, MIN_KEYCODE, NUM_KEYCODES, 0);
+    SendMappingNotify(MappingModifier, 0, 0, 0);
+}
+
+
+//-----------------------------------------------------------------------------
+// Modifier translation functions
+//
+// There are three different ways to specify a Mac modifier key:
+// keycode - specifies hardware key, read from keymapping
+// key     - NX_MODIFIERKEY_*, really an index
+// mask    - NX_*MASK, mask for modifier flags in event record
+// Left and right side have different keycodes but the same key and mask.
+//-----------------------------------------------------------------------------
+
+/*
+ * DarwinModifierNXKeyToNXKeycode
+ *      Return the keycode for an NX_MODIFIERKEY_* modifier.
+ *      side = 0 for left or 1 for right.
+ *      Returns 0 if key+side is not a known modifier.
+ */
+int DarwinModifierNXKeyToNXKeycode(int key, int side) {
+    return keyInfo.modifierKeycodes[key][side];
+}
+
+/*
+ * DarwinModifierNXKeycodeToNXKey
+ *      Returns -1 if keycode+side is not a modifier key
+ *      outSide may be NULL, else it gets 0 for left and 1 for right.
+ */
+int DarwinModifierNXKeycodeToNXKey(unsigned char keycode, int *outSide) {
+    int key, side;
+
+    keycode += MIN_KEYCODE;
+    // search modifierKeycodes for this keycode+side
+    for (key = 0; key < NX_NUMMODIFIERS; key++) {
+        for (side = 0; side <= 1; side++) {
+            if (keyInfo.modifierKeycodes[key][side] == keycode) break;
+        }
+    }
+    if (key == NX_NUMMODIFIERS) return -1;
+    if (outSide) *outSide = side;
+    return key;
+}
+
+/*
+ * DarwinModifierNXMaskToNXKey
+ *      Returns -1 if mask is not a known modifier mask.
+ */
+int DarwinModifierNXMaskToNXKey(int mask) {
+    switch (mask) {
+        case NX_ALPHASHIFTMASK:       return NX_MODIFIERKEY_ALPHALOCK;
+        case NX_SHIFTMASK:            return NX_MODIFIERKEY_SHIFT;
+#ifdef NX_DEVICELSHIFTKEYMASK
+        case NX_DEVICELSHIFTKEYMASK:  return NX_MODIFIERKEY_SHIFT;
+        case NX_DEVICERSHIFTKEYMASK:  return NX_MODIFIERKEY_RSHIFT;
+#endif
+        case NX_CONTROLMASK:          return NX_MODIFIERKEY_CONTROL;
+#ifdef NX_DEVICELCTLKEYMASK
+        case NX_DEVICELCTLKEYMASK:    return NX_MODIFIERKEY_CONTROL;
+        case NX_DEVICERCTLKEYMASK:    return NX_MODIFIERKEY_RCONTROL;
+#endif
+        case NX_ALTERNATEMASK:        return NX_MODIFIERKEY_ALTERNATE;
+#ifdef NX_DEVICELALTKEYMASK
+        case NX_DEVICELALTKEYMASK:    return NX_MODIFIERKEY_ALTERNATE;
+        case NX_DEVICERALTKEYMASK:    return NX_MODIFIERKEY_RALTERNATE;
+#endif
+        case NX_COMMANDMASK:          return NX_MODIFIERKEY_COMMAND;
+#ifdef NX_DEVICELCMDKEYMASK
+        case NX_DEVICELCMDKEYMASK:    return NX_MODIFIERKEY_COMMAND;
+        case NX_DEVICERCMDKEYMASK:    return NX_MODIFIERKEY_RCOMMAND;
+#endif
+        case NX_NUMERICPADMASK:       return NX_MODIFIERKEY_NUMERICPAD;
+        case NX_HELPMASK:             return NX_MODIFIERKEY_HELP;
+        case NX_SECONDARYFNMASK:      return NX_MODIFIERKEY_SECONDARYFN;
+    }
+    return -1;
+}
+
+static const char *DarwinModifierNXMaskTostring(int mask) {
+    switch (mask) {
+        case NX_ALPHASHIFTMASK:      return "NX_ALPHASHIFTMASK";
+        case NX_SHIFTMASK:           return "NX_SHIFTMASK";
+        case NX_DEVICELSHIFTKEYMASK: return "NX_DEVICELSHIFTKEYMASK";
+        case NX_DEVICERSHIFTKEYMASK: return "NX_DEVICERSHIFTKEYMASK";
+        case NX_CONTROLMASK:         return "NX_CONTROLMASK";
+        case NX_DEVICELCTLKEYMASK:   return "NX_DEVICELCTLKEYMASK";
+        case NX_DEVICERCTLKEYMASK:   return "NX_DEVICERCTLKEYMASK";
+        case NX_ALTERNATEMASK:       return "NX_ALTERNATEMASK";
+        case NX_DEVICELALTKEYMASK:   return "NX_DEVICELALTKEYMASK";
+        case NX_DEVICERALTKEYMASK:   return "NX_DEVICERALTKEYMASK";
+        case NX_COMMANDMASK:         return "NX_COMMANDMASK";
+        case NX_DEVICELCMDKEYMASK:   return "NX_DEVICELCMDKEYMASK";
+        case NX_DEVICERCMDKEYMASK:   return "NX_DEVICERCMDKEYMASK";
+        case NX_NUMERICPADMASK:      return "NX_NUMERICPADMASK";
+        case NX_HELPMASK:            return "NX_HELPMASK";
+        case NX_SECONDARYFNMASK:     return "NX_SECONDARYFNMASK";
+    }
+    return "unknown mask";
+}
+
+/*
+ * DarwinModifierNXKeyToNXMask
+ *      Returns 0 if key is not a known modifier key.
+ */
+int DarwinModifierNXKeyToNXMask(int key) {
+    switch (key) {
+        case NX_MODIFIERKEY_ALPHALOCK:   return NX_ALPHASHIFTMASK;
+        case NX_MODIFIERKEY_SHIFT:       return NX_SHIFTMASK;
+#ifdef NX_MODIFIERKEY_RSHIFT
+        case NX_MODIFIERKEY_RSHIFT:      return NX_SHIFTMASK;
+#endif
+        case NX_MODIFIERKEY_CONTROL:     return NX_CONTROLMASK;
+#ifdef NX_MODIFIERKEY_RCONTROL
+        case NX_MODIFIERKEY_RCONTROL:    return NX_CONTROLMASK;
+#endif
+        case NX_MODIFIERKEY_ALTERNATE:   return NX_ALTERNATEMASK;
+#ifdef NX_MODIFIERKEY_RALTERNATE
+        case NX_MODIFIERKEY_RALTERNATE:  return NX_ALTERNATEMASK;
+#endif
+        case NX_MODIFIERKEY_COMMAND:     return NX_COMMANDMASK;
+#ifdef NX_MODIFIERKEY_RCOMMAND
+        case NX_MODIFIERKEY_RCOMMAND:    return NX_COMMANDMASK;
+#endif
+        case NX_MODIFIERKEY_NUMERICPAD:  return NX_NUMERICPADMASK;
+        case NX_MODIFIERKEY_HELP:        return NX_HELPMASK;
+        case NX_MODIFIERKEY_SECONDARYFN: return NX_SECONDARYFNMASK;
+    }
+    return 0;
+}
+
+/*
+ * DarwinModifierStringToNXKey
+ *      Returns -1 if string is not a known modifier.
+ */
+int DarwinModifierStringToNXKey(const char *str) {
+    if      (!strcasecmp(str, "shift"))   return NX_MODIFIERKEY_SHIFT;
+    else if (!strcasecmp(str, "control")) return NX_MODIFIERKEY_CONTROL;
+    else if (!strcasecmp(str, "option"))  return NX_MODIFIERKEY_ALTERNATE;
+    else if (!strcasecmp(str, "command")) return NX_MODIFIERKEY_COMMAND;
+    else if (!strcasecmp(str, "fn"))      return NX_MODIFIERKEY_SECONDARYFN;
+    else return -1;
+}
+
+/*
+ * LegalModifier
+ *      This allows the ddx layer to prevent some keys from being remapped
+ *      as modifier keys.
+ */
+Bool LegalModifier(unsigned int key, DeviceIntPtr pDev)
+{
+    return 1;
+}
+
 unsigned int QuartzSystemKeymapSeed(void) {
     static unsigned int seed;
     static KeyboardLayoutRef last_key_layout;
diff --git a/hw/xquartz/quartzKeyboard.h b/hw/xquartz/quartzKeyboard.h
index 4f495bb..964ea01 100644
--- a/hw/xquartz/quartzKeyboard.h
+++ b/hw/xquartz/quartzKeyboard.h
@@ -49,4 +49,17 @@ typedef struct darwinKeyboardInfo_struct {
 Bool QuartzReadSystemKeymap(darwinKeyboardInfo *info);
 unsigned int QuartzSystemKeymapSeed(void);
 
+/* Provided for darwinEvents.c */
+extern darwinKeyboardInfo keyInfo;
+void DarwinKeyboardReloadHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents);
+void DarwinKeyboardInit(DeviceIntPtr pDev);
+int DarwinModifierNXKeycodeToNXKey(unsigned char keycode, int *outSide);
+int DarwinModifierNXKeyToNXKeycode(int key, int side);
+int DarwinModifierNXKeyToNXMask(int key);
+int DarwinModifierNXMaskToNXKey(int mask);
+int DarwinModifierStringToNXKey(const char *string);
+
+/* Provided for darwin.c */
+void DarwinKeyboardInit(DeviceIntPtr pDev);
+
 #endif /* QUARTZ_KEYBOARD_H */
commit 582397cd024c68df65ab9dececd6d2c40a5a261b
Author: Ben Byer <bbyer at apple.com>
Date:   Thu Apr 17 02:31:53 2008 -0700

    oops, missed a spot
    (cherry picked from commit 19872a6aeb8ee9cb0e33e4b4ffd794c9dbefe0cf)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index bb2a97d..37a66f7 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -459,7 +459,7 @@ void DarwinSendScrollEvents(float count_x, float count_y,
 		ErrorF("DarwinSendScrollEvents called before darwinEvents was initialized\n");
 		return;
 	}
-	ErrorF("scroll(%f, %f)\n", count_x, count_y);
+
 	int sign_x = count_x > 0.0f ? SCROLLWHEELLEFTFAKE : SCROLLWHEELRIGHTFAKE;
 	int sign_y = count_y > 0.0f ? SCROLLWHEELUPFAKE : SCROLLWHEELDOWNFAKE;
 	count_x = fabs(count_x);
commit 0bd1c369cce05d5a4da5e3fd7033aea8c68460ec
Author: Ben Byer <bbyer at apple.com>
Date:   Thu Apr 17 02:30:36 2008 -0700

    formatting cleanup
    (cherry picked from commit 769acd29348abf9e5b0bebfca6ae695d345f3077)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index c4ba146..bb2a97d 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -324,16 +324,12 @@ Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) {
  */
 void ProcessInputEvents(void) {
     xEvent  xe;
-    // button number and modifier mask of currently pressed fake button
-    input_check_flag=0;
+	int x = sizeof(xe);
 
-    //    ErrorF("calling mieqProcessInputEvents\n");
     mieqProcessInputEvents();
 
     // Empty the signaling pipe
-    int x = sizeof(xe);
     while (x == sizeof(xe)) {
-//      DEBUG_LOG("draining pipe\n");
       x = read(darwinEventReadFD, &xe, sizeof(xe));
     }
 }
@@ -341,23 +337,23 @@ void ProcessInputEvents(void) {
 /* Sends a null byte down darwinEventWriteFD, which will cause the
    Dispatch() event loop to check out event queue */
 void DarwinPokeEQ(void) {
-  char nullbyte=0;
-  input_check_flag++;
-  //  <daniels> bushing: oh, i ... er ... christ.
-  write(darwinEventWriteFD, &nullbyte, 1);
+	char nullbyte=0;
+	input_check_flag++;
+	//  <daniels> oh, i ... er ... christ.
+	write(darwinEventWriteFD, &nullbyte, 1);
 }
 
 void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int pointer_y, 
 			     float pressure, float tilt_x, float tilt_y) {
-  static int darwinFakeMouseButtonDown = 0;
-  static int darwinFakeMouseButtonMask = 0;
-  int i, num_events;
+	static int darwinFakeMouseButtonDown = 0;
+	static int darwinFakeMouseButtonMask = 0;
+	int i, num_events;
 
 	if(!darwinEvents) {
 		ErrorF("DarwinSendPointerEvents called before darwinEvents was initialized\n");
 		return;
 	}
-  /* I can't find a spec for this, but at least GTK expects that tablets are
+	/* I can't find a spec for this, but at least GTK expects that tablets are
      just like mice, except they have either one or three extra valuators, in this
      order:
      
@@ -366,91 +362,92 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
      we can't do that.  Again, GTK seems to record the min/max of each valuator,
      and then perform scaling back to float itself using that info. Soo.... */
 
-  int valuators[5] = {pointer_x, pointer_y, 
+	int valuators[5] = {pointer_x, pointer_y, 
 		      pressure * INT32_MAX * 1.0f, 
 		      tilt_x * INT32_MAX * 1.0f, 
 		      tilt_y * INT32_MAX * 1.0f};
 
-  if (ev_type == ButtonPress && darwinFakeButtons && ev_button == 1) {
-    // Mimic multi-button mouse with modifier-clicks
-    // If both sets of modifiers are pressed,
-    // button 2 is clicked.
-    if ((old_flags & darwinFakeMouse2Mask) == darwinFakeMouse2Mask) {
-      DarwinSimulateMouseClick(pointer_x, pointer_y, pressure, 
+	if (ev_type == ButtonPress && darwinFakeButtons && ev_button == 1) {
+		// Mimic multi-button mouse with modifier-clicks
+		// If both sets of modifiers are pressed,
+		// button 2 is clicked.
+		if ((old_flags & darwinFakeMouse2Mask) == darwinFakeMouse2Mask) {
+			DarwinSimulateMouseClick(pointer_x, pointer_y, pressure, 
 			       tilt_x, tilt_y, 2, darwinFakeMouse2Mask);
-      darwinFakeMouseButtonDown = 2;
-      darwinFakeMouseButtonMask = darwinFakeMouse2Mask;
-      return;
-    } else if ((old_flags & darwinFakeMouse3Mask) == darwinFakeMouse3Mask) {
-      DarwinSimulateMouseClick(pointer_x, pointer_y, pressure, 
+			darwinFakeMouseButtonDown = 2;
+			darwinFakeMouseButtonMask = darwinFakeMouse2Mask;
+			return;
+		} else if ((old_flags & darwinFakeMouse3Mask) == darwinFakeMouse3Mask) {
+			DarwinSimulateMouseClick(pointer_x, pointer_y, pressure, 
 			       tilt_x, tilt_y, 3, darwinFakeMouse3Mask);
-      darwinFakeMouseButtonDown = 3;
-      darwinFakeMouseButtonMask = darwinFakeMouse3Mask;
-      return;
-    }
-  }
-  if (ev_type == ButtonRelease && darwinFakeButtons && darwinFakeMouseButtonDown) {
-    // If last mousedown was a fake click, don't check for
-    // mouse modifiers here. The user may have released the
-    // modifiers before the mouse button.
-    ev_button = darwinFakeMouseButtonDown;
-    darwinFakeMouseButtonDown = 0;
-    // Bring modifiers back up to date
-    DarwinUpdateModifiers(KeyPress, darwinFakeMouseButtonMask & old_flags);
-    darwinFakeMouseButtonMask = 0;
-    return;
-  } 
-
-  num_events = GetPointerEvents(darwinEvents, darwinPointer, ev_type, ev_button, 
+			darwinFakeMouseButtonDown = 3;
+			darwinFakeMouseButtonMask = darwinFakeMouse3Mask;
+			return;
+		}
+	}
+
+	if (ev_type == ButtonRelease && darwinFakeButtons && darwinFakeMouseButtonDown) {
+		// If last mousedown was a fake click, don't check for
+		// mouse modifiers here. The user may have released the
+		// modifiers before the mouse button.
+		ev_button = darwinFakeMouseButtonDown;
+		darwinFakeMouseButtonDown = 0;
+		// Bring modifiers back up to date
+		DarwinUpdateModifiers(KeyPress, darwinFakeMouseButtonMask & old_flags);
+		darwinFakeMouseButtonMask = 0;
+		return;
+	} 
+
+	num_events = GetPointerEvents(darwinEvents, darwinPointer, ev_type, ev_button, 
 				POINTER_ABSOLUTE, 0, 5, valuators);
       
-  for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
-  DarwinPokeEQ();
+	for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
+	DarwinPokeEQ();
 }
 
 void DarwinSendKeyboardEvents(int ev_type, int keycode) {
-  int i, num_events;
+	int i, num_events;
 	if(!darwinEvents) {
 		ErrorF("DarwinSendKeyboardEvents called before darwinEvents was initialized\n");
 		return;
 	}
 
-  if (old_flags == 0 && darwinSyncKeymap && darwinKeymapFile == NULL) {
-    /* See if keymap has changed. */
+	if (old_flags == 0 && darwinSyncKeymap && darwinKeymapFile == NULL) {
+		/* See if keymap has changed. */
 
-    static unsigned int last_seed;
-    unsigned int this_seed;
+		static unsigned int last_seed;
+		unsigned int this_seed;
 
-    this_seed = QuartzSystemKeymapSeed();
-    if (this_seed != last_seed) {
-		last_seed = this_seed;
-		DarwinSendDDXEvent(kXquartzReloadKeymap, 0);
-    }
-  }
+		this_seed = QuartzSystemKeymapSeed();
+		if (this_seed != last_seed) {
+			last_seed = this_seed;
+			DarwinSendDDXEvent(kXquartzReloadKeymap, 0);
+		}
+	}
 
-  num_events = GetKeyboardEvents(darwinEvents, darwinKeyboard, ev_type, keycode + MIN_KEYCODE);
-  for(i=0; i<num_events; i++) mieqEnqueue(darwinKeyboard,&darwinEvents[i]);
-  DarwinPokeEQ();
+	num_events = GetKeyboardEvents(darwinEvents, darwinKeyboard, ev_type, keycode + MIN_KEYCODE);
+	for(i=0; i<num_events; i++) mieqEnqueue(darwinKeyboard,&darwinEvents[i]);
+	DarwinPokeEQ();
 }
 
 void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y, 
 			       float pressure, float tilt_x, float tilt_y) {
-  int i, num_events;
-  int valuators[5] = {pointer_x, pointer_y, 
+	int i, num_events;
+	int valuators[5] = {pointer_x, pointer_y, 
 		      pressure * INT32_MAX * 1.0f, 
 		      tilt_x * INT32_MAX * 1.0f, 
 		      tilt_y * INT32_MAX * 1.0f};
 
-  if(!darwinEvents) {
+	if(!darwinEvents) {
 		ErrorF("DarwinSendProximityvents called before darwinEvents was initialized\n");
 		return;
-}
+	}
 
-  num_events = GetProximityEvents(darwinEvents, darwinPointer, ev_type,
+	num_events = GetProximityEvents(darwinEvents, darwinPointer, ev_type,
 				0, 5, valuators);
       
-  for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
-  DarwinPokeEQ();
+	for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
+	DarwinPokeEQ();
 }
 
 
@@ -485,9 +482,9 @@ void DarwinSendScrollEvents(float count_x, float count_y,
 /* Send the appropriate KeyPress/KeyRelease events to GetKeyboardEvents to
    reflect changing modifier flags (alt, control, meta, etc) */
 void DarwinUpdateModKeys(int flags) {
-  DarwinUpdateModifiers(KeyRelease, old_flags & ~flags);
-  DarwinUpdateModifiers(KeyPress, ~old_flags & flags);
-  old_flags = flags;
+	DarwinUpdateModifiers(KeyRelease, old_flags & ~flags);
+	DarwinUpdateModifiers(KeyPress, ~old_flags & flags);
+	old_flags = flags;
 }
 
 
commit 700e14c22616b209867e4ea4d1811e53ca996164
Author: Ben Byer <bbyer at apple.com>
Date:   Thu Apr 17 02:21:33 2008 -0700

    delete debugging spew
    (cherry picked from commit f04f3af86a91d0cafbc86a0d71aeb0599d685f07)

diff --git a/hw/xquartz/darwinKeyboard.c b/hw/xquartz/darwinKeyboard.c
index 94699a5..e72c894 100644
--- a/hw/xquartz/darwinKeyboard.c
+++ b/hw/xquartz/darwinKeyboard.c
@@ -725,14 +725,6 @@ static void DarwinBuildModifierMaps(darwinKeyboardInfo *info) {
  *  it to an equivalent X keyboard map and modifier map.
  */
 static void DarwinLoadKeyboardMapping(KeySymsRec *keySyms) {
-  void* callstack[128];
-  int i, frames = backtrace(callstack, 128);
-  char** strs = backtrace_symbols(callstack, frames);
-  for (i = 0; i < frames; ++i) {
-    ErrorF("%s\n", strs[i]);
-  }
-  free(strs);
-
     memset(keyInfo.keyMap, 0, sizeof(keyInfo.keyMap));
 
     /* TODO: Clean this up
commit a440eebf2541ae0bb06bf65281b5facff2f04e00
Author: Ben Byer <bbyer at apple.com>
Date:   Thu Apr 17 02:21:11 2008 -0700

    add support for horizontal scrolling (buttons 6 and 7)
    (cherry picked from commit f525a4a432ebd0545ad1dd0a7ad84ad3e47e8b61)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 4a678f8..28bb6fb 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -899,7 +899,7 @@ static void send_nsevent (NSEventType type, NSEvent *e) {
 		break;
 
 		case NSScrollWheel:
-			DarwinSendScrollEvents([e deltaY], pointer_x, pointer_y,
+			DarwinSendScrollEvents([e deltaX], [e deltaY], pointer_x, pointer_y,
 				pressure, tilt_x, tilt_y);
 		break;
 
diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index 002ea41..7d81a02 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -337,7 +337,7 @@ static int DarwinMouseProc(
     DeviceIntPtr    pPointer,
     int             what )
 {
-    CARD8 map[6];
+  CARD8 map[8] = {0, 1, 2, 3, 4, 5, 6, 7};
 
     switch (what) {
 
@@ -345,15 +345,10 @@ static int DarwinMouseProc(
             pPointer->public.on = FALSE;
 
             // Set button map.
-            map[1] = 1;
-            map[2] = 2;
-            map[3] = 3;
-            map[4] = 4;
-            map[5] = 5;
-            InitPointerDeviceStruct( (DevicePtr)pPointer, map, 5,
+              InitPointerDeviceStruct( (DevicePtr)pPointer, map, 7,
 				     GetMotionHistory,
 				     (PtrCtrlProcPtr)NoopDDA,
-				     GetMotionHistorySize(), 5);
+				     GetMotionHistorySize(), 7);
 	    InitProximityClassDeviceStruct( (DevicePtr)pPointer);
             break;
 
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 70dfdaf..c4ba146 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -1,7 +1,7 @@
 /*
 Darwin event queue and event handling
 
-Copyright 2007 Apple Inc.
+Copyright 2007-2008 Apple Inc.
 Copyright 2004 Kaleb S. KEITHLEY. All Rights Reserved.
 Copyright (c) 2002-2004 Torrey T. Lyons. All Rights Reserved.
 
@@ -56,6 +56,12 @@ in this Software without prior written authorization from The Open Group.
 #include <unistd.h>
 #include <IOKit/hidsystem/IOLLEvent.h>
 
+/* Fake button press/release for scroll wheel move. */
+#define SCROLLWHEELUPFAKE    4
+#define SCROLLWHEELDOWNFAKE  5
+#define SCROLLWHEELLEFTFAKE  6
+#define SCROLLWHEELRIGHTFAKE 7
+
 #define _APPLEWM_SERVER_
 #include "applewmExt.h"
 #include <X11/extensions/applewm.h>
@@ -65,10 +71,6 @@ in this Software without prior written authorization from The Open Group.
 #include "rootlessWindow.h"
 WindowPtr xprGetXWindow(xp_window_id wid);
 
-/* Fake button press/release for scroll wheel move. */
-#define SCROLLWHEELUPFAKE   4
-#define SCROLLWHEELDOWNFAKE 5
-
 int input_check_zero, input_check_flag;
 
 static int old_flags = 0;  // last known modifier state
@@ -452,30 +454,32 @@ void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y,
 }
 
 
-/* Send the appropriate number of button 4 / 5 clicks to emulate scroll wheel */
-void DarwinSendScrollEvents(float count, int pointer_x, int pointer_y, 
-			    float pressure, float tilt_x, float tilt_y) {
-  int i;
-  int ev_button = count > 0.0f ? 4 : 5;
-  int valuators[5] = {pointer_x, pointer_y, 
-		      pressure * INT32_MAX * 1.0f, 
-		      tilt_x * INT32_MAX * 1.0f, 
-		      tilt_y * INT32_MAX * 1.0f};
-
+/* Send the appropriate number of button clicks to emulate scroll wheel */
+void DarwinSendScrollEvents(float count_x, float count_y, 
+							int pointer_x, int pointer_y, 
+			    			float pressure, float tilt_x, float tilt_y) {
 	if(!darwinEvents) {
 		ErrorF("DarwinSendScrollEvents called before darwinEvents was initialized\n");
 		return;
 	}
-
-  for (count = fabs(count); count > 0.0; count = count - 1.0f) {
-    int num_events = GetPointerEvents(darwinEvents, darwinPointer, ButtonPress, ev_button, 
-				      POINTER_ABSOLUTE, 0, 5, valuators);
-    for(i=0; i<num_events; i++) mieqEnqueue(darwinPointer,&darwinEvents[i]);
-    num_events = GetPointerEvents(darwinEvents, darwinPointer, ButtonRelease, ev_button, 
-				      POINTER_ABSOLUTE, 0, 5, valuators);
-    for(i=0; i<num_events; i++) mieqEnqueue(darwinPointer,&darwinEvents[i]);
-  }
-  DarwinPokeEQ();
+	ErrorF("scroll(%f, %f)\n", count_x, count_y);
+	int sign_x = count_x > 0.0f ? SCROLLWHEELLEFTFAKE : SCROLLWHEELRIGHTFAKE;
+	int sign_y = count_y > 0.0f ? SCROLLWHEELUPFAKE : SCROLLWHEELDOWNFAKE;
+	count_x = fabs(count_x);
+	count_y = fabs(count_y);
+	
+	while ((count_x > 0.0f) || (count_y > 0.0f)) {
+		if (count_x > 0.0f) {
+			DarwinSendPointerEvents(ButtonPress, sign_x, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
+			DarwinSendPointerEvents(ButtonRelease, sign_x, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
+			count_x = count_x - 1.0f;
+		}
+		if (count_y > 0.0f) {
+			DarwinSendPointerEvents(ButtonPress, sign_y, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
+			DarwinSendPointerEvents(ButtonRelease, sign_y, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
+			count_y = count_y - 1.0f;
+		}
+	}
 }
 
 /* Send the appropriate KeyPress/KeyRelease events to GetKeyboardEvents to
diff --git a/hw/xquartz/darwinEvents.h b/hw/xquartz/darwinEvents.h
index 7c56be9..98426d6 100644
--- a/hw/xquartz/darwinEvents.h
+++ b/hw/xquartz/darwinEvents.h
@@ -38,7 +38,7 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y, 
 			       float pressure, float tilt_x, float tilt_y);
 void DarwinSendKeyboardEvents(int ev_type, int keycode);
-void DarwinSendScrollEvents(float count, int pointer_x, int pointer_y,
+void DarwinSendScrollEvents(float count_x, float count_y, int pointer_x, int pointer_y,
 			    float pressure, float tilt_x, float tilt_y);
 void DarwinUpdateModKeys(int flags);
 
commit 612e901ef6aa3edc54b39e55e8040cda0e5ab7b6
Author: Ben Byer <bbyer at apple.com>
Date:   Thu Apr 17 01:32:56 2008 -0700

    enable keyboard map debugging -- it's going to x11-debug.txt, anyway ... so no harm
    (cherry picked from commit ab662c736e0654e2b4347091f0d9e87f26034216)

diff --git a/hw/xquartz/darwinKeyboard.c b/hw/xquartz/darwinKeyboard.c
index 3299556..94699a5 100644
--- a/hw/xquartz/darwinKeyboard.c
+++ b/hw/xquartz/darwinKeyboard.c
@@ -62,7 +62,7 @@
 
 // Define this to get a diagnostic output to stderr which is helpful
 // in determining how the X server is interpreting the Darwin keymap.
-// #define DUMP_DARWIN_KEYMAP
+#define DUMP_DARWIN_KEYMAP
 
 #include <stdio.h>
 #include <stdlib.h>
@@ -216,6 +216,7 @@ static int const NUM_KEYPAD = sizeof(normal_to_keypad) / sizeof(normal_to_keypad
 
 static void DarwinChangeKeyboardControl( DeviceIntPtr device, KeybdCtrl *ctrl )
 {
+	// FIXME: to be implemented
     // keyclick, bell volume / pitch, autorepead, LED's
 }
 
commit 5bdfbfbedcbd9ff61cbb0b678cbf7ce7889a5826
Author: Ben Byer <bbyer at apple.com>
Date:   Thu Apr 17 01:29:46 2008 -0700

    darwinKeyboard: refactor slightly so that we're not cutting and pasting code from dix, kthx
    (cherry picked from commit a8a090b853e811b9843a5732572cbbe542224f32)

diff --git a/hw/xquartz/darwinKeyboard.c b/hw/xquartz/darwinKeyboard.c
index 91b56d3..3299556 100644
--- a/hw/xquartz/darwinKeyboard.c
+++ b/hw/xquartz/darwinKeyboard.c
@@ -1,9 +1,9 @@
 //=============================================================================
 //
-// Keyboard support for the Darwin X Server
+// Keyboard support for Xquartz
 //
+// Copyright (c) 2003, 2008 Apple, Inc.
 // Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
-// Copyright (c) 2003 Apple Computer, Inc. All Rights Reserved.
 // Copyright 2004 Kaleb S. KEITHLEY. All Rights Reserved.
 //
 // The code to parse the Darwin keymap is derived from dumpkeymap.c
@@ -799,52 +799,6 @@ void DarwinKeyboardInit(DeviceIntPtr pDev) {
 }
 
 
-/* Borrowed from dix/devices.c */
-static Bool InitModMap(register KeyClassPtr keyc) {
-    int i, j;
-    CARD8 keysPerModifier[8];
-    CARD8 mask;
-
-    //    darwinKeyc = keyc;
-    if (keyc->modifierKeyMap != NULL)
-        xfree (keyc->modifierKeyMap);
-
-    keyc->maxKeysPerModifier = 0;
-    for (i = 0; i < 8; i++)
-        keysPerModifier[i] = 0;
-    for (i = 8; i < MAP_LENGTH; i++)
-    {
-        for (j = 0, mask = 1; j < 8; j++, mask <<= 1)
-        {
-            if (mask & keyc->modifierMap[i])
-            {
-                if (++keysPerModifier[j] > keyc->maxKeysPerModifier)
-                    keyc->maxKeysPerModifier = keysPerModifier[j];
-            }
-        }
-    }
-    keyc->modifierKeyMap = (KeyCode *)xalloc(8*keyc->maxKeysPerModifier);
-    if (!keyc->modifierKeyMap && keyc->maxKeysPerModifier)
-        return (FALSE);
-    bzero((char *)keyc->modifierKeyMap, 8*(int)keyc->maxKeysPerModifier);
-    for (i = 0; i < 8; i++)
-        keysPerModifier[i] = 0;
-    for (i = 8; i < MAP_LENGTH; i++)
-    {
-        for (j = 0, mask = 1; j < 8; j++, mask <<= 1)
-        {
-            if (mask & keyc->modifierMap[i])
-            {
-                keyc->modifierKeyMap[(j*keyc->maxKeysPerModifier) +
-                         keysPerModifier[j]] = i;
-                keysPerModifier[j]++;
-            }
-        }
-    }
-    return TRUE;
-}
-
-
 void DarwinKeyboardReloadHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents) {
     KeySymsRec keySyms;
 	if (dev == NULL) dev = darwinKeyboard;
@@ -852,12 +806,16 @@ void DarwinKeyboardReloadHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev,
 	DEBUG_LOG("DarwinKeyboardReloadHandler(%p)\n", dev);
     DarwinLoadKeyboardMapping(&keySyms);
 
-    if (SetKeySymsMap(&dev->key->curKeySyms, &keySyms)) {
-        /* now try to update modifiers. */
-
-        memmove(dev->key->modifierMap, keyInfo.modMap, MAP_LENGTH);
-        InitModMap(dev->key);
-    } else DEBUG_LOG("SetKeySymsMap=0\n");
+	if (dev->key) {
+		if (dev->key->curKeySyms.map) xfree(dev->key->curKeySyms.map);
+		if (dev->key->modifierKeyMap) xfree(dev->key->modifierKeyMap);
+		xfree(dev->key);
+	}
+	
+	if (!InitKeyClassDeviceStruct(dev, &keySyms, keyInfo.modMap)) {
+		DEBUG_LOG("InitKeyClassDeviceStruct failed\n");
+		return;
+	}
 
     SendMappingNotify(MappingKeyboard, MIN_KEYCODE, NUM_KEYCODES, 0);
     SendMappingNotify(MappingModifier, 0, 0, 0);
commit 58e42683c9e998f6b8a55d5653b9caec7b6acf96
Author: Ben Byer <bbyer at apple.com>
Date:   Thu Apr 17 00:19:56 2008 -0700

    hack to Xquartz to prevent xmodmap from wiping out our valid modmap, per daniels
    (cherry picked from commit cab54466a61281cfafc12825017c23d720cd75f4)

diff --git a/hw/xquartz/darwinKeyboard.c b/hw/xquartz/darwinKeyboard.c
index 0a8c5c0..91b56d3 100644
--- a/hw/xquartz/darwinKeyboard.c
+++ b/hw/xquartz/darwinKeyboard.c
@@ -795,6 +795,7 @@ void DarwinKeyboardInit(DeviceIntPtr pDev) {
     assert( InitKeyboardDeviceStruct( (DevicePtr)pDev, &keySyms,
                                       keyInfo.modMap, QuartzBell,
                                       DarwinChangeKeyboardControl ));
+    SwitchCoreKeyboard(pDev);
 }
 
 
commit cd3470a0cffbd6b8cec7c44227b33307c9e227ae
Author: Ben Byer <bbyer at apple.com>
Date:   Wed Apr 16 22:48:54 2008 -0700

    kludge: miEqEnqueue wants a device, even if we're passing custom messages,
    so give it one
    (cherry picked from commit a494ff04b2a14470eaf5a23c7cf6dbdea182c6d1)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 78708d2..70dfdaf 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -511,5 +511,5 @@ void DarwinSendDDXEvent(int type, int argc, ...) {
         va_end (args);
     }
 
-    mieqEnqueue(NULL, &xe);
+    mieqEnqueue(darwinPointer, &xe);
 }
commit 966ae1781f3ca563e15a9a1b8cab6fab94e07fe9
Author: Drew Parsons <dparsons at debian.org>
Date:   Mon Mar 10 22:54:49 2008 +1100

    Create dix/libXpdix.la for Xprint-specific build of libdix.la
    
    (cherry picked from commit 4e2c6dbabdbbaaca213fd08edd422de15d0900cc)
    
    required because of commit 7c0709a736c0f3aa011de67dd2c2962585ab146e,
    which made requestingClient in dix specific to Xprint only.
    Add to XPRINT_LIBS in hw/xprint/Makefile.am in front of
    $(XSERVER_LIBS) to override definitions in libdix.la for standard xservers.
    
    Follows 571206832d454771e3c638c7515767958365c19c (providing -DXPRINT
    to xprint subdirs).
    
    Note it may be possible to restructure the code so that
    requestingClient is stored elsewhere than in dix. See discussions
    following http://lists.freedesktop.org/archives/xorg/2008-March/033844.html
    If this is done it may be possible to revert this commit (if not 571206...).

diff --git a/dix/Makefile.am b/dix/Makefile.am
index b7b1ec0..e44b510 100644
--- a/dix/Makefile.am
+++ b/dix/Makefile.am
@@ -1,4 +1,10 @@
-noinst_LTLIBRARIES = libdix.la libxpstubs.la
+standard_dix_libs = libdix.la libxpstubs.la
+
+if XPRINT
+noinst_LTLIBRARIES = $(standard_dix_libs) libXpdix.la
+else
+noinst_LTLIBRARIES = $(standard_dix_libs)
+endif
 
 AM_CFLAGS = $(DIX_CFLAGS) \
 	-DVENDOR_NAME=\""@VENDOR_NAME@"\" \
@@ -39,7 +45,11 @@ libdix_la_SOURCES = 	\
 libxpstubs_la_SOURCES =	\
 	xpstubs.c
 
-INCLUDES = -I$(top_srcdir)/Xprint
+if XPRINT
+libXpdix_la_SOURCES = $(libdix_la_SOURCES)
+libXpdix_la_CPPFLAGS = -I$(top_srcdir)/hw/xprint
+libXpdix_la_CFLAGS = $(AM_CFLAGS) $(XPRINT_CFLAGS)
+endif
 
 EXTRA_DIST = buildatoms BuiltInAtoms CHANGES Xserver.d Xserver-dtrace.h.in
 
diff --git a/hw/xprint/Makefile.am b/hw/xprint/Makefile.am
index 5ca04ff..2ed7aaf 100644
--- a/hw/xprint/Makefile.am
+++ b/hw/xprint/Makefile.am
@@ -17,6 +17,7 @@ XPRINT_LIBS = \
 	pcl-mono/libpcl.la \
 	$(top_builddir)/fb/libfb.la \
 	$(top_builddir)/render/librender.la \
+	$(top_builddir)/dix/libXpdix.la \
 	$(XSERVER_LIBS) \
 	$(top_builddir)/Xext/libXext.la \
 	$(top_builddir)/xkb/libxkb.la \
commit 571206832d454771e3c638c7515767958365c19c
Author: Drew Parsons <dparsons at debian.org>
Date:   Mon Mar 10 13:48:05 2008 +1100

    Define XPRINT in XPRINT_CFLAGS (configure.ac)
    
    -DXPRINT had only been set for Xprt in hw/xprint/Makefile.am
    After commit 7c0709a736c0f3aa011de67dd2c2962585ab146e it is also
    required for ps/PsArea.c and PsFonts.c to ensure ‘requestingClient’ is
    defined, so make it a global Xprint definition in configure.ac.
    (cherry picked from commit 28a6719fd486d9a9cecad0b057d9ea7c59c66055)

diff --git a/configure.ac b/configure.ac
index 56303e4..9669f47 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1608,7 +1608,7 @@ AC_MSG_RESULT([$XPRINT])
 
 if test "x$XPRINT" = xyes; then
 	PKG_CHECK_MODULES([XPRINTMODULES], [printproto x11 xfont $XDMCP_MODULES xau])
-	XPRINT_CFLAGS="$XPRINTMODULES_CFLAGS"
+	XPRINT_CFLAGS="$XPRINTMODULES_CFLAGS -DXPRINT"
 	XPRINT_LIBS="$XEXT_LIB $CONFIG_LIB $DBE_LIB $XTRAP_LIB $RECORD_LIB $RENDER_LIB $COMPOSITE_LIB $RANDR_LIB $XI_LIB $FIXES_LIB $DAMAGE_LIB $XI_LIB $GLX_LIBS $MIEXT_DAMAGE_LIB $XKB_LIB $XKB_STUB_LIB"
 	XPRINT_SYS_LIBS="$XPRINTMODULES_LIBS"
 
diff --git a/hw/xprint/Makefile.am b/hw/xprint/Makefile.am
index 1b80048..5ca04ff 100644
--- a/hw/xprint/Makefile.am
+++ b/hw/xprint/Makefile.am
@@ -3,7 +3,7 @@ SUBDIRS = doc pcl pcl-mono raster ps etc config
 bin_PROGRAMS = Xprt
 
 Xprt_CFLAGS = @DIX_CFLAGS@ @XPRINT_CFLAGS@ \
-	-DXPRINT -DPRINT_ONLY_SERVER -D_XP_PRINT_SERVER_  \
+	-DPRINT_ONLY_SERVER -D_XP_PRINT_SERVER_  \
 	-DXPRINTDIR=\"$(libdir)/X11/xserver\"    \
 	-DXPRASTERDDX -DXPPCLDDX -DXPMONOPCLDDX -DXPPSDDX \
 	-DXFree86Server
commit 9b30cc524867a0ad3d0d2227e167f4284830ab4e
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Thu Apr 17 16:10:10 2008 +0200

    Optimize dixLookupPrivate for repeated lookups of the same private.
    
    This gives me a 20% speedup for EXA text rendering, though I still seem to burn
    quite a lot of cycles in here...

diff --git a/include/privates.h b/include/privates.h
index 8d59b72..093d177 100644
--- a/include/privates.h
+++ b/include/privates.h
@@ -46,13 +46,20 @@ dixAllocatePrivate(PrivateRec **privates, const DevPrivateKey key);
 static _X_INLINE pointer
 dixLookupPrivate(PrivateRec **privates, const DevPrivateKey key)
 {
-    PrivateRec *rec = *privates;
+    PrivateRec *rec, *prev;
     pointer *ptr;
 
-    while (rec) {
-	if (rec->key == key)
-	    return rec->value;
-	rec = rec->next;
+    for (rec = *privates, prev = NULL; rec; prev = rec, rec = rec->next) {
+	if (rec->key != key)
+	    continue;
+
+	if (prev) {
+	    prev->next = rec->next;
+	    rec->next = *privates;
+	    *privates = rec;
+	}
+
+	return rec->value;
     }
 
     ptr = dixAllocatePrivate(privates, key);
commit 886af8f3849a0fcfc6b63a9695107ce26d7a6955
Author: Tilman Sauerbeck <tilman at code-monkey.de>
Date:   Wed Apr 16 16:20:19 2008 +0200

    EXA: Avoid some fallbacks in exaCopyNtoN.
    
    In some cases we can still do the copying in hardware even if the
    dimensions of the pixmaps are out of range. This is true when the boxes
    that we're to copy are all in the card's range.

diff --git a/exa/exa_accel.c b/exa/exa_accel.c
index c2bfdee..844683c 100644
--- a/exa/exa_accel.c
+++ b/exa/exa_accel.c
@@ -527,16 +527,36 @@ exaCopyNtoN (DrawablePtr    pSrcDrawable,
     pDstExaPixmap = ExaGetPixmapPriv (pDstPixmap);
 
     /* Check whether the accelerator can use this pixmap.
-     * FIXME: If it cannot, use temporary pixmaps so that the drawing
-     * happens within limits.
+     * If the pitch of the pixmaps is out of range, there's nothing
+     * we can do but fall back to software rendering.
      */
-    if (pSrcExaPixmap->accel_blocked || pDstExaPixmap->accel_blocked)
-    {
+    if (pSrcExaPixmap->accel_blocked & EXA_RANGE_PITCH ||
+        pDstExaPixmap->accel_blocked & EXA_RANGE_PITCH)
 	goto fallback;
-    } else {
-	exaDoMigration (pixmaps, 2, TRUE);
+
+    /* If the width or the height of either of the pixmaps
+     * is out of range, check whether the boxes are actually out of the
+     * addressable range as well. If they aren't, we can still do
+     * the copying in hardware.
+     */
+    if (pSrcExaPixmap->accel_blocked || pDstExaPixmap->accel_blocked) {
+        int i;
+
+        for (i = 0; i < nbox; i++) {
+            /* src */
+            if ((pbox[i].x2 + dx + src_off_x) >= pExaScr->info->maxX ||
+                (pbox[i].y2 + dy + src_off_y) >= pExaScr->info->maxY)
+                goto fallback;
+
+            /* dst */
+            if ((pbox[i].x2 + dst_off_x) >= pExaScr->info->maxX ||
+                (pbox[i].y2 + dst_off_y) >= pExaScr->info->maxY)
+                goto fallback;
+        }
     }
 
+    exaDoMigration (pixmaps, 2, TRUE);
+
     /* Mixed directions must be handled specially if the card is lame */
     if ((pExaScr->info->flags & EXA_TWO_BITBLT_DIRECTIONS) &&
 	reverse != upsidedown) {
commit dc10f0a0e243b7ba38d02a4e2c43027563aead7c
Author: Julien Cristau <jcristau at debian.org>
Date:   Thu Apr 17 11:13:47 2008 +0200

    Fix composite on !darwin
    
    2ffdb0eb641ab6949783b4eb574f77e7486ac929 changes the default value of
    COMPOSITE to 'auto', but doesn't set it back to 'yes' as appropriate.

diff --git a/configure.ac b/configure.ac
index 1670c69..56303e4 100644
--- a/configure.ac
+++ b/configure.ac
@@ -789,6 +789,9 @@ if test "x$COMPOSITE" = xauto; then
 		darwin*)
 			[ "x$XQUARTZ" = xyes -o "x$XQUARTZ" = xauto ] && COMPOSITE=no
 			;;
+		*)
+			COMPOSITE=yes
+			;;
 	esac
 fi
 
commit 8716d081fdf61ddf956c30aff7697c70507911fd
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Thu Apr 3 16:29:43 2008 -0700

    XQuartz: Don't enable rootless accelerated functionality... crashy...
    (cherry picked from commit cdb4c291d8c10c3a9ea59d8e79275a30d2ea82b4)

diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index 35fa118..fccaff0 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -352,7 +352,9 @@ xprSetupScreen(int index, ScreenPtr pScreen)
 {
     // Initialize accelerated rootless drawing
     // Note that this must be done before DamageSetup().
-    RootlessAccelInit(pScreen);
+
+    // These are crashing ugly... better to be stable and not crash for now.
+    //RootlessAccelInit(pScreen);
 
 #ifdef DAMAGE
     // The Damage extension needs to wrap underneath the
diff --git a/miext/rootless/README.txt b/miext/rootless/README.txt
index ffd1790..2c3fbb0 100644
--- a/miext/rootless/README.txt
+++ b/miext/rootless/README.txt
@@ -76,10 +76,6 @@ rootlessConfig.h to specify compile time options for its platform.
         The following compile-time options are defined in 
 rootlessConfig.h:
 
-      o ROOTLESS_ACCEL: If true, use the optional rootless acceleration
-        functions where possible to a accelerate X11 drawing primitives.
-        If false, all drawing will be done with fb.
-
       o ROOTLESS_GLOBAL_COORDS: This option controls the way that frame
         coordinates are passed to the rootless implementation. If false,
         the coordinates are passed per screen relative to the origin of 
diff --git a/miext/rootless/rootlessConfig.h b/miext/rootless/rootlessConfig.h
index ab0187e..50bac3f 100644
--- a/miext/rootless/rootlessConfig.h
+++ b/miext/rootless/rootlessConfig.h
@@ -36,12 +36,12 @@
 
 #ifdef __APPLE__
 
-# define ROOTLESS_ACCEL TRUE
 # define ROOTLESS_GLOBAL_COORDS TRUE
 # define ROOTLESS_PROTECT_ALPHA TRUE
 # define ROOTLESS_REDISPLAY_DELAY 10
 # define ROOTLESS_RESIZE_GRAVITY TRUE
 # undef  ROOTLESS_TRACK_DAMAGE
+/*# define ROOTLESSDEBUG*/
 
 /* Bit mask for alpha channel with a particular number of bits per
    pixel. Note that we only care for 32bpp data. Mac OS X uses planar
@@ -52,7 +52,6 @@
 
 #if defined(__CYGWIN__) || defined(WIN32)
 
-# define ROOTLESS_ACCEL YES
 # define ROOTLESS_GLOBAL_COORDS TRUE
 # define ROOTLESS_PROTECT_ALPHA NO
 # define ROOTLESS_REDISPLAY_DELAY 10
diff --git a/miext/rootless/rootlessGC.c b/miext/rootless/rootlessGC.c
index c80b11f..1c787b6 100644
--- a/miext/rootless/rootlessGC.c
+++ b/miext/rootless/rootlessGC.c
@@ -118,7 +118,7 @@ static GCOps rootlessGCOps = {
 
 /*
    There are two issues we must contend with when drawing. These are
-   controlled with ROOTLESS_PROTECT_ALPHA and ROOTLESS_ACCEL.
+   controlled with ROOTLESS_PROTECT_ALPHA and RootlessAccelInit().
 
    If ROOTLESS_PROTECT_ALPHA is set, we have to make sure that the alpha
    channel of the on screen windows is always opaque. fb makes this harder
@@ -141,9 +141,9 @@ static GCOps rootlessGCOps = {
    from another window since its alpha channel must also be opaque.
 
    The other issue to consider is that the rootless implementation may
-   provide accelerated drawing functions if ROOTLESS_ACCEL is set. For some
-   drawing primitives we swap in rootless acceleration functions, which use
-   the accelerated drawing functions where possible.
+   provide accelerated drawing functions if RootlessAccelInit() is called.For 
+   some drawing primitives we swap in rootless acceleration functions, which
+   use the accelerated drawing functions where possible.
 
    Where both alpha protection and acceleration is used, it is even a bigger
    win to relax the planemask to all ones because most accelerated drawing
commit 2ffdb0eb641ab6949783b4eb574f77e7486ac929
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 16 21:54:00 2008 -0700

    XQuartz: Don't use composite.
    (cherry picked from commit 6d3d344b5b95b6dc4166556d03cfd8c9576dc3f0)

diff --git a/configure.ac b/configure.ac
index f0cfb1b..1670c69 100644
--- a/configure.ac
+++ b/configure.ac
@@ -524,7 +524,7 @@ AC_ARG_ENABLE(glx-tls,        AS_HELP_STRING([--enable-glx-tls], [Build GLX with
 
 dnl Extensions.
 AC_ARG_ENABLE(registry,       AS_HELP_STRING([--disable-registry], [Build string registry module (default: enabled)]), [XREGISTRY=$enableval], [XREGISTRY=yes])
-AC_ARG_ENABLE(composite,      AS_HELP_STRING([--disable-composite], [Build Composite extension (default: enabled)]), [COMPOSITE=$enableval], [COMPOSITE=yes])
+AC_ARG_ENABLE(composite,      AS_HELP_STRING([--disable-composite], [Build Composite extension (default: enabled)]), [COMPOSITE=$enableval], [COMPOSITE=auto])
 AC_ARG_ENABLE(mitshm,         AS_HELP_STRING([--disable-shm], [Build SHM extension (default: enabled)]), [MITSHM=$enableval], [MITSHM=yes])
 AC_ARG_ENABLE(xres,           AS_HELP_STRING([--disable-xres], [Build XRes extension (default: enabled)]), [RES=$enableval], [RES=yes])
 AC_ARG_ENABLE(xtrap,          AS_HELP_STRING([--disable-xtrap], [Build XTrap extension (default: enabled)]), [XTRAP=$enableval], [XTRAP=yes])
@@ -783,6 +783,15 @@ if test "x$XREGISTRY" = xyes; then
 	AC_DEFINE(XREGISTRY, 1, [Build registry module])
 fi
 
+dnl XQuartz DDX Detection... Yes, it's ugly to have it here... but we need to disable COMPOSITE for 
+if test "x$COMPOSITE" = xauto; then
+	case $host_os in
+		darwin*)
+			[ "x$XQUARTZ" = xyes -o "x$XQUARTZ" = xauto ] && COMPOSITE=no
+			;;
+	esac
+fi
+
 AM_CONDITIONAL(COMPOSITE, [test "x$COMPOSITE" = xyes])
 if test "x$COMPOSITE" = xyes; then
 	AC_DEFINE(COMPOSITE, 1, [Support Composite Extension])
diff --git a/hw/xquartz/xpr/Makefile.am b/hw/xquartz/xpr/Makefile.am
index 6523561..f6ede8b 100644
--- a/hw/xquartz/xpr/Makefile.am
+++ b/hw/xquartz/xpr/Makefile.am
@@ -27,7 +27,6 @@ Xquartz_LDADD = \
 	$(top_builddir)/miext/shadow/libshadow.la \
 	$(top_builddir)/fb/libfb.la \
 	$(top_builddir)/mi/libmi.la \
-	$(top_builddir)/composite/libcomposite.la \
 	$(top_builddir)/damageext/libdamageext.la \
 	$(top_builddir)/miext/damage/libdamage.la \
 	$(top_builddir)/xfixes/libxfixes.la \
commit 757a1bf3a3d72e17eeb362f825124c4ba40cc080
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 16 21:48:52 2008 -0700

    Xquartz: Don't need to link against rlAccel since we don't use it
    (cherry picked from commit 180ec128adef11a9a90cea1189dc31ac5de8359f)

diff --git a/hw/xquartz/xpr/Makefile.am b/hw/xquartz/xpr/Makefile.am
index b4d67c7..6523561 100644
--- a/hw/xquartz/xpr/Makefile.am
+++ b/hw/xquartz/xpr/Makefile.am
@@ -40,7 +40,6 @@ Xquartz_LDADD = \
 	$(top_builddir)/record/librecord.la \
 	$(top_builddir)/XTrap/libxtrap.la \
 	$(top_builddir)/miext/rootless/librootless.la \
-	$(top_builddir)/miext/rootless/accel/librlAccel.la \
 	$(DARWIN_LIBS) $(XSERVER_LIBS) $(XSERVER_SYS_LIBS) -lXplugin
 
 Xquartz_LDFLAGS =  \
commit ab8c6a3c5acb2a3bf288f1d6339b09a125bbb930
Author: Alan Coopersmith <alan.coopersmith at sun.com>
Date:   Mon Apr 14 19:12:00 2008 -0700

    Update ac_define_dir macro in acinclude.m4 to 2008-04-12 version

diff --git a/acinclude.m4 b/acinclude.m4
index e61244f..833b557 100644
--- a/acinclude.m4
+++ b/acinclude.m4
@@ -142,7 +142,9 @@ AC_SUBST(LTCXXCOMPILE)
 
 
 
-##### http://autoconf-archive.cryp.to/ac_define_dir.html
+# ===========================================================================
+#             http://autoconf-archive.cryp.to/ac_define_dir.html
+# ===========================================================================
 #
 # SYNOPSIS
 #
@@ -150,11 +152,11 @@ AC_SUBST(LTCXXCOMPILE)
 #
 # DESCRIPTION
 #
-#   This macro sets VARNAME to the expansion of the DIR variable,
-#   taking care of fixing up ${prefix} and such.
+#   This macro sets VARNAME to the expansion of the DIR variable, taking
+#   care of fixing up ${prefix} and such.
 #
-#   VARNAME is then offered as both an output variable and a C
-#   preprocessor symbol.
+#   VARNAME is then offered as both an output variable and a C preprocessor
+#   symbol.
 #
 #   Example:
 #
@@ -162,18 +164,18 @@ AC_SUBST(LTCXXCOMPILE)
 #
 # LAST MODIFICATION
 #
-#   2006-10-13
+#   2008-04-12
 #
 # COPYLEFT
 #
-#   Copyright (c) 2006 Stepan Kasal <kasal at ucw.cz>
-#   Copyright (c) 2006 Andreas Schwab <schwab at suse.de>
-#   Copyright (c) 2006 Guido U. Draheim <guidod at gmx.de>
-#   Copyright (c) 2006 Alexandre Oliva
+#   Copyright (c) 2008 Stepan Kasal <kasal at ucw.cz>
+#   Copyright (c) 2008 Andreas Schwab <schwab at suse.de>
+#   Copyright (c) 2008 Guido U. Draheim <guidod at gmx.de>
+#   Copyright (c) 2008 Alexandre Oliva
 #
-#   Copying and distribution of this file, with or without
-#   modification, are permitted in any medium without royalty provided
-#   the copyright notice and this notice are preserved.
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved.
 
 AC_DEFUN([AC_DEFINE_DIR], [
   prefix_NONE=
commit b907258ebe62642af088f6e2970a45a68cf4be19
Author: Eric Anholt <eric at anholt.net>
Date:   Wed Apr 16 12:07:51 2008 -0700

    Update dolt from upstream, fixing fallback to libtool.

diff --git a/acinclude.m4 b/acinclude.m4
index cbb68e1..e61244f 100644
--- a/acinclude.m4
+++ b/acinclude.m4
@@ -8,8 +8,7 @@ dnl To use dolt, invoke the DOLT macro immediately after the libtool macros.
 dnl Optionally, copy this file into acinclude.m4, to avoid the need to have it
 dnl installed when running autoconf on your project.
 dnl
-dnl git snapshot: 198a3026b347b9220a2f2e2ae23a3049c35af262
-
+dnl git snapshot: d91f2b4e9041538400e2703a2a6fbeecdb8ee27d
 AC_DEFUN([DOLT], [
 AC_REQUIRE([AC_CANONICAL_HOST])
 # dolt, a replacement for libtool
@@ -27,11 +26,13 @@ if test x$GCC != xyes; then
 fi
 case $host in
 i?86-*-linux*|x86_64-*-linux*|powerpc-*-linux*) ;;
-amd64-*-freebsd*|i386-*-freebsd*|ia64-*-freebsd*) ;;
+amd64-*-freebsd*|i?86-*-freebsd*|ia64-*-freebsd*) ;;
 *) dolt_supported=no ;;
 esac
 if test x$dolt_supported = xno ; then
     AC_MSG_RESULT([no, falling back to libtool])
+    LTCOMPILE='$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(COMPILE)'
+    LTCXXCOMPILE='$(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXXCOMPILE)'
 else
     AC_MSG_RESULT([yes, replacing libtool])
 
@@ -65,9 +66,10 @@ dnl Write out shared compilation code.
         cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
 libobjdir="${obj%$objbase}.libs"
 if test ! -d "$libobjdir" ; then
-    mkdir -p "$libobjdir"
+    mkdir_out="$(mkdir "$libobjdir" 2>&1)"
     mkdir_ret=$?
     if test "$mkdir_ret" -ne 0 && test ! -d "$libobjdir" ; then
+	echo "$mkdir_out" 1>&2
         exit $mkdir_ret
     fi
 fi
@@ -130,10 +132,10 @@ __DOLTCOMPILE__EOF__
 dnl Done writing out doltcompile; substitute it for libtool compilation.
     chmod +x doltcompile
     LTCOMPILE='$(top_builddir)/doltcompile $(COMPILE)'
-    AC_SUBST(LTCOMPILE)
     LTCXXCOMPILE='$(top_builddir)/doltcompile $(CXXCOMPILE)'
-    AC_SUBST(LTCXXCOMPILE)
 fi
+AC_SUBST(LTCOMPILE)
+AC_SUBST(LTCXXCOMPILE)
 # end dolt
 ])
 
commit e1e189f8538f2b77ae0cf0d846d3899061e4c4b7
Author: Aaron Plattner <aplattner at nvidia.com>
Date:   Tue Apr 15 14:49:51 2008 -0700

    Include pciaccess in the xorg-server.pc Requires line.
    
    This pulls in the include path for pciaccess.h, which is needed by, among other
    things, xf86.h.

diff --git a/xorg-server.pc.in b/xorg-server.pc.in
index 53b4ed2..139adf4 100644
--- a/xorg-server.pc.in
+++ b/xorg-server.pc.in
@@ -14,6 +14,6 @@ abi_font=@abi_font@
 Name: xorg-server
 Description: Modular X.Org X Server
 Version: @PACKAGE_VERSION@
-Requires: pixman-1
+Requires: pixman-1 pciaccess
 Cflags: -I${sdkdir}
 Libs: -L${libdir}
commit 9e7ced94a5e3a14762fe934aa69d91f0831cf5ca
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Tue Apr 15 12:06:07 2008 -0700

    XQuartz: Removed a call to RootlessReorderWindow from the Carbon thread
    (cherry picked from commit cb27d5ca8230707b276763c0ec20e586203144c9)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 2844fca..4a678f8 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -51,10 +51,6 @@
 #include <unistd.h>
 #include <pthread.h>
 
-#include "rootlessCommon.h"
-
-WindowPtr xprGetXWindowFromAppKit(int windowNumber); // xpr/xprFrame.c
-
 #define DEFAULTS_FILE "/usr/X11/lib/X11/xserver/Xquartz.plist"
 
 int X11EnableKeyEquivalents = TRUE;
@@ -192,6 +188,10 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 }
 
 - (void) sendEvent:(NSEvent *)e {
+  NSEventType type;
+  BOOL for_appkit, for_x;
+  
+  type = [e type];
  	NSEventType type;
 	BOOL for_appkit, for_x;
 
@@ -210,8 +210,6 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 			if (_x_active) [self activateX:NO];
 		} else if ([self modalWindow] == nil) {
 			/* Must be an X window. Tell appkit it doesn't have focus. */
-			WindowPtr pWin = xprGetXWindowFromAppKit([e windowNumber]);
-			if (pWin) RootlessReorderWindow(pWin);
 			for_appkit = NO;
 
 			if ([self isActive]) {
@@ -244,10 +242,6 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 							|| [e keyCode] == 53 /*Esc*/)) {
 						swallow_up = 0;
 						for_x = NO;
-#ifdef DARWIN_DDX_MISSING
-						DarwinSendDDXEvent(kXquartzToggleFullscreen, 0);
-#endif
-					}
 			} else {
 			/* If we saw a key equivalent on the down, don't pass
 	   			the up through to X. */
diff --git a/hw/xquartz/xpr/dri.h b/hw/xquartz/xpr/dri.h
index cf2638a..8bb2e9e 100644
--- a/hw/xquartz/xpr/dri.h
+++ b/hw/xquartz/xpr/dri.h
@@ -41,7 +41,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #include "scrnintstr.h"
 #define _APPLEDRI_SERVER_
 #include "appledri.h"
-#include "Xplugin.h"
+#include <Xplugin.h>
 
 typedef void (*ClipNotifyPtr)( WindowPtr, int, int );
 
diff --git a/hw/xquartz/xpr/xprAppleWM.c b/hw/xquartz/xpr/xprAppleWM.c
index bd82df0..aa5f291 100644
--- a/hw/xquartz/xpr/xprAppleWM.c
+++ b/hw/xquartz/xpr/xprAppleWM.c
@@ -34,7 +34,7 @@
 #include "xpr.h"
 #include "applewmExt.h"
 #include "rootless.h"
-#include "Xplugin.h"
+#include <Xplugin.h>
 #include <X11/X.h>
 
 static int xprSetWindowLevel(
diff --git a/hw/xquartz/xpr/xprCursor.c b/hw/xquartz/xpr/xprCursor.c
index 2ad8d6f..a42c30c 100644
--- a/hw/xquartz/xpr/xprCursor.c
+++ b/hw/xquartz/xpr/xprCursor.c
@@ -37,7 +37,7 @@
 #include "xpr.h"
 #include "darwin.h"
 #include "darwinEvents.h"
-#include "Xplugin.h"
+#include <Xplugin.h>
 
 #include "mi.h"
 #include "scrnintstr.h"
diff --git a/hw/xquartz/xpr/xprFrame.c b/hw/xquartz/xpr/xprFrame.c
index 864ef0d..901efca 100644
--- a/hw/xquartz/xpr/xprFrame.c
+++ b/hw/xquartz/xpr/xprFrame.c
@@ -33,7 +33,7 @@
 
 #include "xpr.h"
 #include "rootlessCommon.h"
-#include "Xplugin.h"
+#include <Xplugin.h>
 #include "x-hash.h"
 #include "x-list.h"
 #include "applewmExt.h"
diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index d685fca..35fa118 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -40,7 +40,7 @@
 #include "rootless.h"
 #include "dri.h"
 #include "globals.h"
-#include "Xplugin.h"
+#include <Xplugin.h>
 #include "applewmExt.h"
 #include "micmap.h"
 
commit 35982bc109d424c464551ab22ec90af69908c884
Author: Kristian Høgsberg <krh at redhat.com>
Date:   Fri Apr 11 11:09:13 2008 -0400

    Make DRI2 a serverlayout/serverflags option.
    
    Add xf86DRI2Enabled() to export the value of the setting.

diff --git a/hw/xfree86/common/xf86.h b/hw/xfree86/common/xf86.h
index 4b3e104..065102f 100644
--- a/hw/xfree86/common/xf86.h
+++ b/hw/xfree86/common/xf86.h
@@ -71,6 +71,7 @@ extern Bool sbusSlotClaimed;
 #endif
 extern confDRIRec xf86ConfigDRI;
 extern Bool xf86inSuspend;
+extern Bool xf86DRI2Enabled(void);
 
 #define XF86SCRNINFO(p) ((ScrnInfoPtr)dixLookupPrivate(&(p)->devPrivates, \
 						       xf86ScreenKey))
diff --git a/hw/xfree86/common/xf86Config.c b/hw/xfree86/common/xf86Config.c
index 3cc04f0..8e412b5 100644
--- a/hw/xfree86/common/xf86Config.c
+++ b/hw/xfree86/common/xf86Config.c
@@ -766,6 +766,7 @@ typedef enum {
     FLAG_AUTO_ADD_DEVICES,
     FLAG_AUTO_ENABLE_DEVICES,
     FLAG_GLX_VISUALS,
+    FLAG_DRI2,
 } FlagValues;
    
 static OptionInfoRec FlagOptions[] = {
@@ -837,16 +838,18 @@ static OptionInfoRec FlagOptions[] = {
 	{0}, FALSE },
   { FLAG_ALLOW_EMPTY_INPUT,     "AllowEmptyInput",              OPTV_BOOLEAN,
         {0}, FALSE },
-  { FLAG_IGNORE_ABI,			"IgnoreABI",			OPTV_BOOLEAN,
+  { FLAG_IGNORE_ABI,		"IgnoreABI",			OPTV_BOOLEAN,
 	{0}, FALSE },
-  { FLAG_USE_DEFAULT_FONT_PATH,  "UseDefaultFontPath",			OPTV_BOOLEAN,
+  { FLAG_USE_DEFAULT_FONT_PATH,  "UseDefaultFontPath",		OPTV_BOOLEAN,
 	{0}, FALSE },
-  { FLAG_AUTO_ADD_DEVICES,       "AutoAddDevices",                      OPTV_BOOLEAN,
+  { FLAG_AUTO_ADD_DEVICES,       "AutoAddDevices",		OPTV_BOOLEAN,
         {0}, TRUE },
-  { FLAG_AUTO_ENABLE_DEVICES,    "AutoEnableDevices",                   OPTV_BOOLEAN,
+  { FLAG_AUTO_ENABLE_DEVICES,    "AutoEnableDevices",		OPTV_BOOLEAN,
         {0}, TRUE },
   { FLAG_GLX_VISUALS,		"GlxVisuals",			OPTV_STRING,
         {0}, FALSE },
+  { FLAG_DRI2,			"DRI2",				OPTV_BOOLEAN,
+	{0}, FALSE },
   { -1,				NULL,				OPTV_NONE,
 	{0}, FALSE },
 };
@@ -1179,9 +1182,23 @@ configServerFlags(XF86ConfFlagsPtr flagsconf, XF86OptionPtr layoutopts)
       xf86Msg(from, "Xinerama: enabled\n");
 #endif
 
+#ifdef DRI2
+    xf86Info.dri2 = FALSE;
+    xf86Info.dri2From = X_DEFAULT;
+    if (xf86GetOptValBool(FlagOptions, FLAG_DRI2, &value)) {
+	xf86Info.dri2 = value;
+	xf86Info.dri2From = X_CONFIG;
+    }
+#endif
+
     return TRUE;
 }
 
+Bool xf86DRI2Enabled(void)
+{
+    return xf86Info.dri2;
+}
+
 /*
  * Locate the core input devices.  These can be specified/located in
  * the following ways, in order of priority:
diff --git a/hw/xfree86/common/xf86Privstr.h b/hw/xfree86/common/xf86Privstr.h
index d97ca44..8cab56e 100644
--- a/hw/xfree86/common/xf86Privstr.h
+++ b/hw/xfree86/common/xf86Privstr.h
@@ -149,6 +149,9 @@ typedef struct {
     Bool        autoAddDevices; /* Whether to succeed NIDR, or ignore. */
     Bool        autoEnableDevices; /* Whether to enable, or let the client
                                     * control. */
+
+    Bool		dri2;
+    MessageType		dri2From;
 } xf86InfoRec, *xf86InfoPtr;
 
 #ifdef DPMSExtension
commit f133d85778462134f366389bde7673bff7845fa8
Author: Tilman Sauerbeck <tilman at code-monkey.de>
Date:   Mon Apr 14 11:43:51 2008 +0200

    EXA: Update pixmaps' accel_blocked field in ModifyPixmapHeader.

diff --git a/exa/exa.c b/exa/exa.c
index cbe66e8..81dc3e2 100644
--- a/exa/exa.c
+++ b/exa/exa.c
@@ -224,6 +224,30 @@ exaLog2(int val)
     return bits - 1;
 }
 
+static void
+exaSetAccelBlock(ExaScreenPrivPtr pExaScr, ExaPixmapPrivPtr pExaPixmap,
+                 int w, int h, int bpp)
+{
+    pExaPixmap->accel_blocked = 0;
+
+    if (pExaScr->info->maxPitchPixels) {
+        int max_pitch = pExaScr->info->maxPitchPixels * (bpp + 7) / 8;
+
+        if (pExaPixmap->fb_pitch > max_pitch)
+            pExaPixmap->accel_blocked |= EXA_RANGE_PITCH;
+    }
+
+    if (pExaScr->info->maxPitchBytes &&
+        pExaPixmap->fb_pitch > pExaScr->info->maxPitchBytes)
+        pExaPixmap->accel_blocked |= EXA_RANGE_PITCH;
+
+    if (w > pExaScr->info->maxX)
+        pExaPixmap->accel_blocked |= EXA_RANGE_WIDTH;
+
+    if (h > pExaScr->info->maxY)
+        pExaPixmap->accel_blocked |= EXA_RANGE_HEIGHT;
+}
+
 /**
  * exaCreatePixmap() creates a new pixmap.
  *
@@ -339,25 +363,8 @@ exaCreatePixmap(ScreenPtr pScreen, int w, int h, int depth,
     REGION_NULL(pScreen, &pExaPixmap->validSys);
     REGION_NULL(pScreen, &pExaPixmap->validFB);
 
-    /* Check whether this pixmap can be used for acceleration. */
-    pExaPixmap->accel_blocked = 0;
-
-    if (pExaScr->info->maxPitchPixels) {
-        int max_pitch = pExaScr->info->maxPitchPixels * (bpp + 7) / 8;
-
-        if (pExaPixmap->fb_pitch > max_pitch)
-            pExaPixmap->accel_blocked |= EXA_RANGE_PITCH;
-    }
-
-    if (pExaScr->info->maxPitchBytes &&
-        pExaPixmap->fb_pitch > pExaScr->info->maxPitchBytes)
-        pExaPixmap->accel_blocked |= EXA_RANGE_PITCH;
-
-    if (w > pExaScr->info->maxX)
-        pExaPixmap->accel_blocked |= EXA_RANGE_WIDTH;
-
-    if (h > pExaScr->info->maxY)
-        pExaPixmap->accel_blocked |= EXA_RANGE_HEIGHT;
+    exaSetAccelBlock(pExaScr, pExaPixmap,
+                     w, h, bpp);
 
     return pPixmap;
 }
@@ -373,12 +380,16 @@ exaModifyPixmapHeader(PixmapPtr pPixmap, int width, int height, int depth,
     if (!pPixmap)
         return FALSE;
 
+    pExaScr = ExaGetScreenPriv(pPixmap->drawable.pScreen);
     pExaPixmap = ExaGetPixmapPriv(pPixmap);
 
-    if (pExaPixmap)
+    if (pExaPixmap) {
 	pExaPixmap->sys_ptr = pPixData;
 
-    pExaScr = ExaGetScreenPriv(pPixmap->drawable.pScreen);
+        exaSetAccelBlock(pExaScr, pExaPixmap,
+                         width, height, bitsPerPixel);
+    }
+
 
     if (pExaScr->info->ModifyPixmapHeader) {
 	ret = pExaScr->info->ModifyPixmapHeader(pPixmap, width, height, depth,
commit bb8868540f017b121d698da45e552ffb55a57cea
Author: Tilman Sauerbeck <tilman at code-monkey.de>
Date:   Mon Apr 14 09:58:49 2008 +0200

    EXA: Teach exaCompositeFallbackPictDesc() about x8r8g8b8.

diff --git a/exa/exa_render.c b/exa/exa_render.c
index da81401..1d7b897 100644
--- a/exa/exa_render.c
+++ b/exa/exa_render.c
@@ -51,6 +51,9 @@ static void exaCompositeFallbackPictDesc(PicturePtr pict, char *string, int n)
     case PICT_a8r8g8b8:
 	snprintf(format, 20, "ARGB8888");
 	break;
+    case PICT_x8r8g8b8:
+	snprintf(format, 20, "XRGB8888");
+	break;
     case PICT_r5g6b5:
 	snprintf(format, 20, "RGB565  ");
 	break;
commit 3e12c5bb67f3049156475d5cbf4e899aaded76bb
Author: Dave Airlie <airlied at redhat.com>
Date:   Mon Apr 14 11:45:12 2008 +1000

    glx: silly nitpick...
    
    even though i and j are the same, we use i to derefence visuals everywhere else

diff --git a/GL/glx/glxscreens.c b/GL/glx/glxscreens.c
index b49a775..41ee029 100644
--- a/GL/glx/glxscreens.c
+++ b/GL/glx/glxscreens.c
@@ -488,7 +488,7 @@ addMinimalSet(__GLXscreen *pGlxScreen)
 	    continue;
 
 	pGlxScreen->visuals[j] = config;
-	config->visualID = visuals[j].vid;
+	config->visualID = visuals[i].vid;
 	j++;
     }
 
commit 97565c0f394f16d042c614695c8b7b4ac354f2a3
Author: Dave Airlie <airlied at redhat.com>
Date:   Mon Apr 14 11:40:38 2008 +1000

    glcore: make visualRating GLX_NONE - note GLX_NONE is not == 0
    
    Finally glxinfo returns the set of 3 visuals and glxgears works again for me on
    sw rendering

diff --git a/GL/glx/glxglcore.c b/GL/glx/glxglcore.c
index 16064a9..1eac0eb 100644
--- a/GL/glx/glxglcore.c
+++ b/GL/glx/glxglcore.c
@@ -320,6 +320,7 @@ createFBConfigsForVisual(__GLXscreen *screen, ScreenPtr pScreen,
 		config->next = xcalloc(sizeof(*config), 1);
 		config = config->next;
 
+		config->visualRating = GLX_NONE;
 		config->visualType = glx_visual_types[visual->class];
 		config->xRenderable = GL_TRUE;
 		config->drawableType = GLX_WINDOW_BIT | GLX_PIXMAP_BIT;
commit c61087c82784633e522bd9392172b43656bdf45e
Author: Dave Airlie <airlied at redhat.com>
Date:   Mon Apr 14 10:47:28 2008 +1000

    glcore: zero fbconfigs before filling them in.
    
    I'm not sure this the complete proper solution, perhaps it should explicitly fill
    in ever field.
    
    This at least makes glxinfo on glcore return sensible information, it doesn't make
    gears work yet though.

diff --git a/GL/glx/glxglcore.c b/GL/glx/glxglcore.c
index 972ab88..16064a9 100644
--- a/GL/glx/glxglcore.c
+++ b/GL/glx/glxglcore.c
@@ -317,7 +317,7 @@ createFBConfigsForVisual(__GLXscreen *screen, ScreenPtr pScreen,
     for (back = numBack - 1; back >= 0; back--)
 	for (depth = 0; depth < numDepth; depth++)
 	    for (stencil = 0; stencil < numStencil; stencil++) {
-		config->next = xalloc(sizeof *config);
+		config->next = xcalloc(sizeof(*config), 1);
 		config = config->next;
 
 		config->visualType = glx_visual_types[visual->class];
commit 1fa4de80fcfc697b5e5879cc351fb3e9dbf6acbe
Author: Matt Turner <mattst88 at gmail.com>
Date:   Sat Apr 12 20:39:18 2008 +0200

    Check for __x86_64__ when we check for __amd64__
    
    It seems Intel C Compiler neglects to define __amd64__, __amd64, or
    amd64, but *does* define __x86_64__.

diff --git a/fb/fb.h b/fb/fb.h
index 01000d7..1cd9473 100644
--- a/fb/fb.h
+++ b/fb/fb.h
@@ -141,7 +141,7 @@ typedef unsigned __int64    FbBits;
       defined(ia64) || defined(__ia64__) || \
       defined(__sparc64__) || defined(_LP64) || \
       defined(__s390x__) || \
-      defined(amd64) || defined (__amd64__) || \
+      defined(amd64) || defined (__amd64__) || defined(__x86_64__) || \
       defined (__powerpc64__) || \
       (defined(sgi) && (_MIPS_SZLONG == 64))
 typedef unsigned long	    FbBits;
diff --git a/hw/xfree86/common/compiler.h b/hw/xfree86/common/compiler.h
index 73ca3d0..7b65da8 100644
--- a/hw/xfree86/common/compiler.h
+++ b/hw/xfree86/common/compiler.h
@@ -498,7 +498,7 @@ extern unsigned int inb(unsigned long port);
 extern unsigned int inw(unsigned long port);
 extern unsigned int inl(unsigned long port);
  
-#   elif defined(linux) && defined(__amd64__) 
+#   elif defined(linux) && (defined(__amd64__) || defined(__x86_64__))
  
 #    include <inttypes.h>
 
diff --git a/hw/xfree86/common/xf86AutoConfig.c b/hw/xfree86/common/xf86AutoConfig.c
index 3210e44..92b204b 100644
--- a/hw/xfree86/common/xf86AutoConfig.c
+++ b/hw/xfree86/common/xf86AutoConfig.c
@@ -449,7 +449,7 @@ chooseVideoDriver(void)
 	if (info != NULL)
 	    chosen_driver = videoPtrToDriverName(info);
 	if (chosen_driver == NULL) {
-#if defined  __i386__ || defined __amd64__ || defined __hurd__
+#if defined  __i386__ || defined __amd64__ || defined __x86_64__ || defined __hurd__
 	    chosen_driver = "vesa";
 #elif defined __sparc__
 	    chosen_driver = "sunffb";
diff --git a/hw/xfree86/loader/loader.c b/hw/xfree86/loader/loader.c
index 774a4c4..a00269b 100644
--- a/hw/xfree86/loader/loader.c
+++ b/hw/xfree86/loader/loader.c
@@ -63,7 +63,7 @@
 #include <string.h>
 #if defined(linux) && \
     (defined(__alpha__) || defined(__powerpc__) || defined(__ia64__) \
-    || defined(__amd64__))
+    || defined(__amd64__) || defined(__x86_64__))
 #include <malloc.h>
 #endif
 #include <stdarg.h>
diff --git a/hw/xfree86/os-support/bsd/bsdResource.c b/hw/xfree86/os-support/bsd/bsdResource.c
index fe166c8..d1ee787 100644
--- a/hw/xfree86/os-support/bsd/bsdResource.c
+++ b/hw/xfree86/os-support/bsd/bsdResource.c
@@ -19,7 +19,7 @@
 
 #ifdef INCLUDE_XF86_NO_DOMAIN
 
-#if defined(__alpha__) || defined(__sparc64__) || defined(__amd64__)
+#if defined(__alpha__) || defined(__sparc64__) || defined(__amd64__) || defined(__x86_64__)
 
 resPtr
 xf86AccResFromOS(resPtr ret)
diff --git a/hw/xfree86/os-support/bsd/i386_video.c b/hw/xfree86/os-support/bsd/i386_video.c
index 1ebac67..e2f6420 100644
--- a/hw/xfree86/os-support/bsd/i386_video.c
+++ b/hw/xfree86/os-support/bsd/i386_video.c
@@ -55,7 +55,7 @@
 #endif
 #endif
 
-#if defined(__OpenBSD__) && defined(__amd64__)
+#if defined(__OpenBSD__) && (defined(__amd64__) || defined(__x86_64__))
 #include <machine/mtrr.h>
 #include <machine/sysarch.h>
 #endif
@@ -108,7 +108,7 @@ static pointer NetBSDsetWC(int, unsigned long, unsigned long, Bool,
 			   MessageType);
 static void NetBSDundoWC(int, pointer);
 #endif
-#if defined(__amd64__) && defined(__OpenBSD__)
+#if (defined(__amd64__) || defined(__x86_64__)) && defined(__OpenBSD__)
 static pointer amd64setWC(int, unsigned long, unsigned long, Bool, 
     MessageType);
 static void amd64undoWC(int, pointer);
@@ -229,7 +229,7 @@ xf86OSInitVidMem(VidMemInfoPtr pVidMem)
 	pVidMem->setWC = NetBSDsetWC;
 	pVidMem->undoWC = NetBSDundoWC;
 #endif
-#if defined(__amd64__) && defined(__OpenBSD__)
+#if (defined(__amd64__) || defined(__x86_64__))  && defined(__OpenBSD__)
 	pVidMem->setWC = amd64setWC;
 	pVidMem->undoWC = amd64undoWC;
 #endif
@@ -953,7 +953,7 @@ NetBSDundoWC(int screenNum, pointer list)
 }
 #endif
 
-#if defined(__OpenBSD__) && defined(__amd64__)
+#if defined(__OpenBSD__) && (defined(__amd64__) || defined(__x86_64__))
 static pointer
 amd64setWC(int screenNum, unsigned long base, unsigned long size, Bool enable,
 	    MessageType from)
diff --git a/hw/xfree86/os-support/bus/Pci.h b/hw/xfree86/os-support/bus/Pci.h
index ebac090..b78d307 100644
--- a/hw/xfree86/os-support/bus/Pci.h
+++ b/hw/xfree86/os-support/bus/Pci.h
@@ -246,7 +246,7 @@
 # if !defined(__FreeBSD__) && !defined(linux)
 #  define ARCH_PCI_PCI_BRIDGE sparcPciPciBridge
 # endif
-#elif defined(__amd64__) || defined(__amd64)
+#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__)
 # if defined(linux)
 #  define ARCH_PCI_INIT linuxPciInit
 # else
diff --git a/hw/xfree86/utils/xorgcfg/loadmod.c b/hw/xfree86/utils/xorgcfg/loadmod.c
index 1207820..629dfe1 100644
--- a/hw/xfree86/utils/xorgcfg/loadmod.c
+++ b/hw/xfree86/utils/xorgcfg/loadmod.c
@@ -179,7 +179,9 @@ LOOKUP xfree86LookupTab[] = {
    SYMFUNC(xf86memchr)
    SYMFUNC(xf86memcmp)
    SYMFUNC(xf86memcpy)
-#if (defined(__powerpc__) && (defined(Lynx) || defined(linux))) || defined(__sparc__) || defined(__sparc) || defined(__ia64__) || defined (__amd64__)
+#if (defined(__powerpc__) && (defined(Lynx) || defined(linux))) || \
+    defined(__sparc__) || defined(__sparc) || defined(__ia64__) || \
+    defined (__amd64__) || defined(__x86_64__)
    /*
     * Some PPC, SPARC, and IA64 compilers generate calls to memcpy to handle
     * structure copies.  This causes a problem both here and in shared
diff --git a/hw/xfree86/x86emu/prim_ops.c b/hw/xfree86/x86emu/prim_ops.c
index b42cdc0..41968e1 100644
--- a/hw/xfree86/x86emu/prim_ops.c
+++ b/hw/xfree86/x86emu/prim_ops.c
@@ -103,7 +103,7 @@
 #include "x86emu/x86emui.h"
 
 #if defined(__GNUC__)
-# if defined (__i386__) || defined(__i386) || defined(__AMD64__) || defined(__x86_64__) || defined(__amd64__)
+# if defined (__i386__) || defined(__i386) || defined(__AMD64__) || defined(__x86_64__) || defined(__amd64__) || defined(__x86_64__)
 #  include "x86emu/prim_x86_gcc.h"
 # endif
 #endif
diff --git a/hw/xfree86/x86emu/x86emu/prim_x86_gcc.h b/hw/xfree86/x86emu/x86emu/prim_x86_gcc.h
index af61e20..5a443cd 100644
--- a/hw/xfree86/x86emu/x86emu/prim_x86_gcc.h
+++ b/hw/xfree86/x86emu/x86emu/prim_x86_gcc.h
@@ -42,7 +42,7 @@
 
 #include "x86emu/types.h"
 
-#if !defined(__GNUC__) || !(defined (__i386__) || defined(__i386) || defined(__AMD64__) || defined(__x86_64__) || defined(__amd64__))
+#if !defined(__GNUC__) || !(defined (__i386__) || defined(__i386) || defined(__AMD64__) || defined(__x86_64__) || defined(__amd64__) || defined(__x86_64__))
 #error This file is intended to be used by gcc on i386 or x86-64 system
 #endif
 
diff --git a/hw/xfree86/x86emu/x86emu/types.h b/hw/xfree86/x86emu/x86emu/types.h
index c0c09c1..2d41b0f 100644
--- a/hw/xfree86/x86emu/x86emu/types.h
+++ b/hw/xfree86/x86emu/x86emu/types.h
@@ -75,7 +75,7 @@
     defined(__sparc64__) || \
     defined(__s390x__) || \
     (defined(__hppa__) && defined(__LP64)) || \
-    defined(__amd64__) || defined(amd64) || \
+    defined(__amd64__) || defined(amd64) || defined(__x86_64__) || \
     (defined(__sgi) && (_MIPS_SZLONG == 64))
 #define NUM32 int
 #else
diff --git a/hw/xprint/ps/psout.h b/hw/xprint/ps/psout.h
index 3e19d5a..1138e4a 100644
--- a/hw/xprint/ps/psout.h
+++ b/hw/xprint/ps/psout.h
@@ -169,7 +169,7 @@ typedef signed __int64    PsOutColor;
      defined(ia64) || defined(__ia64__) || \
      defined(__sparc64__) || defined(_LP64) || \
      defined(__s390x__) || \
-     defined(amd64) || defined (__amd64__) || \
+     defined(amd64) || defined (__amd64__) || defined(__x86_64__) || \
      defined (__powerpc64__) || \
      (defined(sgi) && (_MIPS_SZLONG == 64))
 typedef signed long       PsOutColor;
diff --git a/include/servermd.h b/include/servermd.h
index 2f511da..6168410 100644
--- a/include/servermd.h
+++ b/include/servermd.h
@@ -393,7 +393,7 @@ SOFTWARE.
 
 #endif /* ia64 */
 
-#if defined(__amd64__) || defined(amd64) || defined(__amd64)
+#if defined(__amd64__) || defined(amd64) || defined(__amd64) || defined(__x86_64__)
 # define IMAGE_BYTE_ORDER	LSBFirst
 
 # if defined(XF86MONOVGA) || defined(XF86VGA16) || defined(XF86MONO)
diff --git a/mi/micoord.h b/mi/micoord.h
index 16d0861..876e88c 100644
--- a/mi/micoord.h
+++ b/mi/micoord.h
@@ -48,7 +48,7 @@
     defined(__alpha) || defined(__alpha__) || \
     defined(__i386__) || defined(__i386) || defined(__ia64__) || \
     defined(__s390x__) || defined(__s390__) || \
-    defined(__amd64__) || defined(amd64) || defined(__amd64)
+    defined(__amd64__) || defined(amd64) || defined(__amd64) || defined(__x86_64__)
 #define GetHighWord(x) (((int) (x)) >> 16)
 #else
 #define GetHighWord(x) (((int) (x)) / 65536)
commit 862558c70889e78aa06585af816ca7219f2789af
Merge: 06e7e1d... b1f3f42...
Author: Keith Packard <keithp at keithp.com>
Date:   Fri Apr 11 20:07:39 2008 -0700

    Merge commit 'origin/master' into transform-proposal

commit b1f3f42840ec01db417345a0740b59ad5e4471cb
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri Apr 11 17:49:51 2008 -0700

    Xquartz: Added applicationShouldHandleReopen:hasVisibleWindows to handle dock icon clicking
    (cherry picked from commit 55d9973b053f25bb95b26e00351dc5531caf5b04)

diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index 5bf4f4d..2fd9886 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -743,15 +743,21 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 
 - (BOOL) application:(NSApplication *)app openFile:(NSString *)filename
 {
-  const char *name = [filename UTF8String];
-	
-  if (finished_launching)
-    [self launch_client:filename];
-  else if (name[0] != ':')		/* ignore display names */
-    pending_apps = x_list_prepend (pending_apps, [filename retain]);
-	
-  /* FIXME: report failures. */
-  return YES;
+    const char *name = [filename UTF8String];
+    
+    if (finished_launching)
+        [self launch_client:filename];
+    else if (name[0] != ':')		/* ignore display names */
+        pending_apps = x_list_prepend (pending_apps, [filename retain]);
+    
+    /* FIXME: report failures. */
+    return YES;
+}
+
+- (BOOL) applicationShouldHandleReopen:(NSApplication *)app
+                     hasVisibleWindows:(BOOL)hasVis {
+    DarwinSendDDXEvent(kXquartzBringAllToFront, 0);
+    return YES;
 }
 
 @end
commit eabcfce0a68d504d11be9479f09e66f574dd2f21
Author: Adam Jackson <ajax at redhat.com>
Date:   Fri Apr 11 09:51:26 2008 -0400

    Stop building mfb/afb/xf1bpp by default.

diff --git a/configure.ac b/configure.ac
index 4e83a42..f0cfb1b 100644
--- a/configure.ac
+++ b/configure.ac
@@ -574,8 +574,8 @@ AC_ARG_ENABLE(xgl,            AS_HELP_STRING([--enable-xgl], [Build Xgl server (
 AC_ARG_ENABLE(xglx,           AS_HELP_STRING([--enable-xglx], [Build Xglx xgl module (default: no)]), [XGLX=$enableval], [XGLX=no])
 AC_ARG_ENABLE(xegl,           AS_HELP_STRING([--enable-xegl], [Build Xegl xgl module (default: no)]), [XEGL=$enableval], [XEGL=no])
 dnl legacy fb support
-AC_ARG_ENABLE(mfb,            AS_HELP_STRING([--enable-mfb], [Build legacy mono framebuffer support (default: enabled)]), [MFB=$enableval], [MFB=$XORG])
-AC_ARG_ENABLE(afb,            AS_HELP_STRING([--enable-afb], [Build legacy advanced framebuffer support (default: enabled)]), [AFB=$enableval], [AFB=$XORG])
+AC_ARG_ENABLE(mfb,            AS_HELP_STRING([--enable-mfb], [Build legacy mono framebuffer support (default: disable)]), [MFB=$enableval], [MFB=no])
+AC_ARG_ENABLE(afb,            AS_HELP_STRING([--enable-afb], [Build legacy advanced framebuffer support (default: disable)]), [AFB=$enableval], [AFB=no])
 dnl kdrive and its subsystems
 AC_ARG_ENABLE(kdrive,         AS_HELP_STRING([--enable-kdrive], [Build kdrive servers (default: no)]), [KDRIVE=$enableval], [KDRIVE=no])
 AC_ARG_ENABLE(xephyr,         AS_HELP_STRING([--enable-xephyr], [Build the kdrive Xephyr server (default: auto)]), [XEPHYR=$enableval], [XEPHYR=auto])
commit 0dab6fa3582b70ccd0f01459902415c28dbc81ff
Author: Adam Jackson <ajax at redhat.com>
Date:   Fri Apr 11 09:47:51 2008 -0400

    So long, and thanks for all the cfb.

diff --git a/Makefile.am b/Makefile.am
index 71ba2c4..d2e10ac 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -9,11 +9,6 @@ if XTRAP
 XTRAP_DIR=XTrap
 endif
 
-if CFB
-CFB_DIR=cfb
-CFB32_DIR=cfb32
-endif
-
 if AFB
 AFB_DIR=afb
 endif
@@ -50,8 +45,6 @@ SUBDIRS = \
 	$(DBE_DIR) \
 	$(MFB_DIR) \
 	$(AFB_DIR) \
-	$(CFB_DIR) \
-	$(CFB32_DIR) \
 	$(RECORD_DIR) \
 	xfixes \
 	damageext \
@@ -96,8 +89,6 @@ DIST_SUBDIRS = \
 	dbe \
 	mfb \
 	afb \
-	cfb \
-	cfb32 \
 	record \
 	xfixes \
 	damageext \
diff --git a/cfb/Makefile.am b/cfb/Makefile.am
deleted file mode 100644
index 901fc95..0000000
--- a/cfb/Makefile.am
+++ /dev/null
@@ -1,21 +0,0 @@
-noinst_LTLIBRARIES = libcfb.la
-
-include Makefile.am.inc
-
-DISTCLEANFILES += cfbglrop8.c
-
-libcfb_la_SOURCES = cfb8bit.c cfbteblt8.c cfbglrop8.c cfbpush8.c cfbrctstp8.c \
-                    $(libcfb_gen_sources) $(libcfb_common_sources)
-
-libcfb_la_LIBADD = ../mfb/libmfb.la
-
-AM_CFLAGS = -DPSZ=8 $(DIX_CFLAGS) $(PLATFORMDEFS)
-
-INCLUDES = $(CFB_INCLUDES) -I$(top_srcdir)/hw/xfree86/os-support  -I$(top_srcdir)/hw/xfree86/common
-
-EXTRA_DIST = cfbline.c cfbfillarc.c cfbzerarc.c cfbblt.c cfbsolid.c \
-             cfbtileodd.c cfbtile32.c cfb8line.c cfbply1rct.c cfbglblt8.c \
-	     cfb16.h cfb24.h cfb32.h cfb8bit.h cfbrrop.h \
-	     stip68kgnu.h stipmips.s stipsparc.s stipsprc32.s
-
-sdk_HEADERS = cfb.h cfb32.h cfb16.h cfbmap.h cfbunmap.h cfbmskbits.h
diff --git a/cfb/Makefile.am.inc b/cfb/Makefile.am.inc
deleted file mode 100644
index a2ee143..0000000
--- a/cfb/Makefile.am.inc
+++ /dev/null
@@ -1,153 +0,0 @@
-libcfb_gen_sources = cfbseg.c cfbfillarcC.c cfbfillarcG.c cfbzerarcC.c cfbzerarcX.c cfbzerarcG.c \
-	cfbbltC.c cfbbltX.c cfbbltO.c cfbbltG.c cfbsolidC.c cfbsolidX.c cfbsolidG.c cfbtileoddC.c \
-	cfbtileoddG.c cfbtile32C.c cfbtile32G.c cfb8lineCO.c cfb8lineCP.c cfb8lineX.c cfb8lineG.c \
-	cfb8segCS.c cfb8segC.c cfb8segX.c cfb8setG.c cfbply1rctC.c cfbply1rctG.c
-
-DISTCLEANFILES = $(libcfb_gen_sources)
-
-CFB_INCLUDES = -I$(top_srcdir)/mfb -I$(top_srcdir)/cfb
-
-libcfb_common_sources =  $(top_srcdir)/cfb/cfbgc.c $(top_srcdir)/cfb/cfbrrop.c \
-	$(top_srcdir)/cfb/cfbwindow.c \
-	$(top_srcdir)/cfb/cfbmskbits.c $(top_srcdir)/cfb/cfbpixmap.c \
-	$(top_srcdir)/cfb/cfbbitblt.c $(top_srcdir)/cfb/cfbfillsp.c \
-	$(top_srcdir)/cfb/cfbsetsp.c $(top_srcdir)/cfb/cfbscrinit.c \
-	$(top_srcdir)/cfb/cfballpriv.c $(top_srcdir)/cfb/cfbgetsp.c \
-	$(top_srcdir)/cfb/cfbfillrct.c $(top_srcdir)/cfb/cfbigblt8.c \
-	$(top_srcdir)/cfb/cfbglblt8.c $(top_srcdir)/cfb/cfbtegblt.c \
-	$(top_srcdir)/cfb/cfbpolypnt.c \
-	$(top_srcdir)/cfb/cfbbres.c $(top_srcdir)/cfb/cfbline.c \
-	$(top_srcdir)/cfb/cfbhrzvert.c $(top_srcdir)/cfb/cfbbresd.c \
-	$(top_srcdir)/cfb/cfbimage.c $(top_srcdir)/cfb/cfbcppl.c \
-	$(top_srcdir)/cfb/cfbcmap.c
-
-cfbseg.c:
-	echo "#define POLYSEGMENT" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbline.c\"" >> $@
-
-cfbfillarcC.c:
-	echo "#define RROP GXcopy" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbfillarc.c\"" >> $@
-
-cfbfillarcG.c:
-	echo "#define RROP GXset" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbfillarc.c\"" >> $@
-
-cfbzerarcC.c:
-	echo "#define RROP GXcopy" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbzerarc.c\"" >> $@
-
-cfbzerarcX.c:
-	echo "#define RROP GXxor" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbzerarc.c\"" >> $@
-
-cfbzerarcG.c:
-	echo "#define RROP GXset" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbzerarc.c\"" >> $@
-
-cfbbltC.c:
-	echo "#define MROP Mcopy" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbblt.c\"" >> $@
-
-cfbbltX.c:
-	echo "#define MROP Mxor" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbblt.c\"" >> $@
-
-cfbbltO.c:
-	echo "#define MROP Mor" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbblt.c\"" >> $@
-
-cfbbltG.c:
-	echo "#define MROP 0" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbblt.c\"" >> $@
-
-cfbsolidC.c:
-	echo "#define RROP GXcopy" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbsolid.c\"" >> $@
-
-cfbsolidX.c:
-	echo "#define RROP GXxor" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbsolid.c\"" >> $@
-
-cfbsolidG.c:
-	echo "#define RROP GXset" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbsolid.c\"" >> $@
-
-cfbtileoddC.c:
-	echo "#define MROP Mcopy" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbtileodd.c\"" >> $@
-
-cfbtileoddG.c:
-	echo "#define MROP 0" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbtileodd.c\"" >> $@
-
-cfbtile32C.c:
-	echo "#define MROP Mcopy" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbtile32.c\"" >> $@
-
-cfbtile32G.c:
-	echo "#define MROP 0" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbtile32.c\"" >> $@
-
-cfb8lineCO.c:
-	echo "#define RROP GXcopy" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfb8line.c\"" >> $@
-
-cfb8lineCP.c:
-	echo "#define RROP GXcopy" > $@
-	echo "#define PREVIOUS" >> $@
-	echo "#include \"$(top_srcdir)/cfb/cfb8line.c\"" >> $@
-
-cfb8lineX.c:
-	echo "#define RROP GXxor" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfb8line.c\"" >> $@
-
-cfb8lineG.c:
-	echo "#define RROP GXset" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfb8line.c\"" >> $@
-
-cfb8segCS.c:
-	echo "#define RROP GXcopy" > $@
-	echo "#define POLYSEGMENT" >> $@
-	echo "#define WIDTH_SHIFT" >> $@
-	echo "#include \"$(top_srcdir)/cfb/cfb8line.c\"" >> $@
-
-cfb8segC.c:
-	echo "#define RROP GXcopy" > $@
-	echo "#define POLYSEGMENT" >> $@
-	echo "#include \"$(top_srcdir)/cfb/cfb8line.c\"" >> $@
-
-cfb8segX.c:
-	echo "#define RROP GXxor" > $@
-	echo "#define POLYSEGMENT" >> $@
-	echo "#include \"$(top_srcdir)/cfb/cfb8line.c\"" >> $@
-
-cfb8setG.c:
-	echo "#define RROP GXset" > $@
-	echo "#define POLYSEGMENT" >> $@
-	echo "#include \"$(top_srcdir)/cfb/cfb8line.c\"" >> $@
-
-cfbply1rctC.c:
-	echo "#define RROP GXcopy" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbply1rct.c\"" >> $@
-
-cfbply1rctG.c:
-	echo "#define RROP GXset" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbply1rct.c\"" >> $@
-
-cfbglrop8.c:
-	echo "#define GLYPHROP" > $@
-	echo "#include \"$(top_srcdir)/cfb/cfbglblt8.c\"" >> $@
-
-
-if XPRINT
-
-PLATFORMDEFS = -DXFREE86
-
-cfb8bit.o:   compiler.h
-
-compiler.h:
-	echo "#include \"$(top_srcdir)/hw/xfree86/common/compiler.h\"" >> $@
-
-endif
-
diff --git a/cfb/cfb.h b/cfb/cfb.h
deleted file mode 100644
index aece133..0000000
--- a/cfb/cfb.h
+++ /dev/null
@@ -1,1268 +0,0 @@
-/************************************************************
-Copyright 1987 by Sun Microsystems, Inc. Mountain View, CA.
-
-                    All Rights Reserved
-
-Permission  to  use,  copy,  modify,  and  distribute   this
-software  and  its documentation for any purpose and without
-fee is hereby granted, provided that the above copyright no-
-tice  appear  in all copies and that both that copyright no-
-tice and this permission notice appear in  supporting  docu-
-mentation,  and  that the names of Sun or The Open Group
-not be used in advertising or publicity pertaining to 
-distribution  of  the software  without specific prior 
-written permission. Sun and The Open Group make no 
-representations about the suitability of this software for 
-any purpose. It is provided "as is" without any express or 
-implied warranty.
-
-SUN DISCLAIMS ALL WARRANTIES WITH REGARD TO  THIS  SOFTWARE,
-INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
-NESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SUN BE  LI-
-ABLE  FOR  ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,  DATA  OR
-PROFITS,  WHETHER  IN  AN  ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
-THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-********************************************************/
-
-#if !defined(__CFB_H__) || defined(CFB_PROTOTYPES_ONLY)
-
-#include <X11/X.h>
-#include "globals.h"
-#include "pixmap.h"
-#include "region.h"
-#include "gc.h"
-#include "colormap.h"
-#include "miscstruct.h"
-#include "servermd.h"
-#include "privates.h"
-#include "windowstr.h"
-#include "mfb.h"
-#undef PixelType
-
-#include "cfbmap.h"
-
-#ifndef CfbBits
-#define CfbBits CARD32
-#endif
-
-#ifndef CFB_PROTOTYPES_ONLY
-#define __CFB_H__
-/*
-   private filed of pixmap
-   pixmap.devPrivate = (unsigned int *)pointer_to_bits
-   pixmap.devKind = width_of_pixmap_in_bytes
-*/
-
-extern DevPrivateKey cfbGCPrivateKey;
-
-/* private field of GC */
-typedef struct {
-    unsigned char       rop;            /* special case rop values */
-    /* next two values unused in cfb, included for compatibility with mfb */
-    unsigned char       ropOpStip;      /* rop for opaque stipple */
-    /* this value is ropFillArea in mfb, usurped for cfb */
-    unsigned char       oneRect;	/*  drawable has one clip rect */
-    CfbBits	xor, and;	/* reduced rop values */
-    } cfbPrivGC;
-
-typedef cfbPrivGC	*cfbPrivGCPtr;
-
-#define cfbGetGCPrivate(pGC)	((cfbPrivGCPtr)\
-    dixLookupPrivate(&(pGC)->devPrivates, cfbGCPrivateKey))
-
-#define cfbGetCompositeClip(pGC) ((pGC)->pCompositeClip)
-
-/* way to carry RROP info around */
-typedef struct {
-    unsigned char	rop;
-    CfbBits	xor, and;
-} cfbRRopRec, *cfbRRopPtr;
-
-/* cfb8bit.c */
-
-extern int cfbSetStipple(
-    int /*alu*/,
-    CfbBits /*fg*/,
-    CfbBits /*planemask*/
-);
-
-extern int cfbSetOpaqueStipple(
-    int /*alu*/,
-    CfbBits /*fg*/,
-    CfbBits /*bg*/,
-    CfbBits /*planemask*/
-);
-
-extern int cfbComputeClipMasks32(
-    BoxPtr /*pBox*/,
-    int /*numRects*/,
-    int /*x*/,
-    int /*y*/,
-    int /*w*/,
-    int /*h*/,
-    CARD32 * /*clips*/
-);
-#endif /* !CFB_PROTOTYPES_ONLY */
-/* cfb8cppl.c */
-
-extern void cfbCopyImagePlane(
-    DrawablePtr /*pSrcDrawable*/,
-    DrawablePtr /*pDstDrawable*/,
-    int /*rop*/,
-    RegionPtr /*prgnDst*/,
-    DDXPointPtr /*pptSrc*/,
-    unsigned long /*planemask*/
-);
-
-#ifndef CFB_PROTOTYPES_ONLY
-extern void cfbCopyPlane8to1(
-    DrawablePtr /*pSrcDrawable*/,
-    DrawablePtr /*pDstDrawable*/,
-    int /*rop*/,
-    RegionPtr /*prgnDst*/,
-    DDXPointPtr /*pptSrc*/,
-    unsigned long /*planemask*/,
-    unsigned long /*bitPlane*/
-);
-
-extern void cfbCopyPlane16to1(
-    DrawablePtr /*pSrcDrawable*/,
-    DrawablePtr /*pDstDrawable*/,
-    int /*rop*/,
-    RegionPtr /*prgnDst*/,
-    DDXPointPtr /*pptSrc*/,
-    unsigned long /*planemask*/,
-    unsigned long /*bitPlane*/
-);
-
-extern void cfbCopyPlane24to1(
-    DrawablePtr /*pSrcDrawable*/,
-    DrawablePtr /*pDstDrawable*/,
-    int /*rop*/,
-    RegionPtr /*prgnDst*/,
-    DDXPointPtr /*pptSrc*/,
-    unsigned long /*planemask*/,
-    unsigned long /*bitPlane*/
-);
-
-extern void cfbCopyPlane32to1(
-    DrawablePtr /*pSrcDrawable*/,
-    DrawablePtr /*pDstDrawable*/,
-    int /*rop*/,
-    RegionPtr /*prgnDst*/,
-    DDXPointPtr /*pptSrc*/,
-    unsigned long /*planemask*/,
-    unsigned long /*bitPlane*/
-);
-#endif
-
-/* cfb8lineCO.c */
-
-extern int cfb8LineSS1RectCopy(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*mode*/,
-    int /*npt*/,
-    DDXPointPtr /*pptInit*/,
-    DDXPointPtr /*pptInitOrig*/,
-    int * /*x1p*/,
-    int * /*y1p*/,
-    int * /*x2p*/,
-    int * /*y2p*/
-);
-
-extern void cfb8LineSS1Rect(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*mode*/,
-    int /*npt*/,
-    DDXPointPtr /*pptInit*/
-);
-
-extern void cfb8ClippedLineCopy(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*x1*/,
-    int /*y1*/,
-    int /*x2*/,
-    int /*y2*/,
-    BoxPtr /*boxp*/,
-    Bool /*shorten*/
-);
-/* cfb8lineCP.c */
-
-extern int cfb8LineSS1RectPreviousCopy(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*mode*/,
-    int /*npt*/,
-    DDXPointPtr /*pptInit*/,
-    DDXPointPtr /*pptInitOrig*/,
-    int * /*x1p*/,
-    int * /*y1p*/,
-    int * /*x2p*/,
-    int * /*y2p*/
-);
-/* cfb8lineG.c */
-
-extern int cfb8LineSS1RectGeneral(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*mode*/,
-    int /*npt*/,
-    DDXPointPtr /*pptInit*/,
-    DDXPointPtr /*pptInitOrig*/,
-    int * /*x1p*/,
-    int * /*y1p*/,
-    int * /*x2p*/,
-    int * /*y2p*/
-);
-
-extern void cfb8ClippedLineGeneral(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*x1*/,
-    int /*y1*/,
-    int /*x2*/,
-    int /*y2*/,
-    BoxPtr /*boxp*/,
-    Bool /*shorten*/
-);
-/* cfb8lineX.c */
-
-extern int cfb8LineSS1RectXor(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*mode*/,
-    int /*npt*/,
-    DDXPointPtr /*pptInit*/,
-    DDXPointPtr /*pptInitOrig*/,
-    int * /*x1p*/,
-    int * /*y1p*/,
-    int * /*x2p*/,
-    int * /*y2p*/
-);
-
-extern void cfb8ClippedLineXor(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*x1*/,
-    int /*y1*/,
-    int /*x2*/,
-    int /*y2*/,
-    BoxPtr /*boxp*/,
-    Bool /*shorten*/
-);
-/* cfb8segC.c */
-
-extern int cfb8SegmentSS1RectCopy(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nseg*/,
-    xSegment * /*pSegInit*/
-);
-/* cfb8segCS.c */
-
-extern int cfb8SegmentSS1RectShiftCopy(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nseg*/,
-    xSegment * /*pSegInit*/
-);
-
-extern void cfb8SegmentSS1Rect(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nseg*/,
-    xSegment * /*pSegInit*/
-);
-/* cfb8segG.c */
-
-extern int cfb8SegmentSS1RectGeneral(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nseg*/,
-    xSegment * /*pSegInit*/
-);
-/* cfbsegX.c */
-
-extern int cfb8SegmentSS1RectXor(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nseg*/,
-    xSegment * /*pSegInit*/
-);
-/* cfballpriv.c */
-
-extern Bool cfbAllocatePrivates(
-    ScreenPtr /*pScreen*/,
-    DevPrivateKey * /*gc_key*/
-);
-/* cfbbitblt.c */
-
-extern RegionPtr cfbBitBlt(
-    DrawablePtr /*pSrcDrawable*/,
-    DrawablePtr /*pDstDrawable*/,
-    GCPtr/*pGC*/,
-    int /*srcx*/,
-    int /*srcy*/,
-    int /*width*/,
-    int /*height*/,
-    int /*dstx*/,
-    int /*dsty*/,
-    void (* /*doBitBlt*/)(
-	DrawablePtr /*pSrc*/,
-	DrawablePtr /*pDst*/,
-	int /*alu*/,
-	RegionPtr /*prgnDst*/,
-	DDXPointPtr /*pptSrc*/,
-	unsigned long /*planemask*/
-	),
-    unsigned long /*bitPlane*/
-);
-
-#define cfbCopyPlaneExpand cfbBitBlt
-
-extern RegionPtr cfbCopyPlaneReduce(
-    DrawablePtr /*pSrcDrawable*/,
-    DrawablePtr /*pDstDrawable*/,
-    GCPtr /*pGC*/,
-    int /*srcx*/,
-    int /*srcy*/,
-    int /*width*/,
-    int /*height*/,
-    int /*dstx*/,
-    int /*dsty*/,
-    void (* /*doCopyPlane*/)(
-	DrawablePtr /*pSrc*/,
-	DrawablePtr /*pDst*/,
-	int /*alu*/,
-	RegionPtr /*prgnDst*/,
-	DDXPointPtr /*pptSrc*/,
-	unsigned long /*planemask*/,
-	unsigned long /*bitPlane*/ /* We must know which plane to reduce! */
-	),
-    unsigned long /*bitPlane*/
-);
-
-extern void cfbDoBitblt(
-    DrawablePtr /*pSrc*/,
-    DrawablePtr /*pDst*/,
-    int /*alu*/,
-    RegionPtr /*prgnDst*/,
-    DDXPointPtr /*pptSrc*/,
-    unsigned long /*planemask*/
-);
-
-extern RegionPtr cfbCopyArea(
-    DrawablePtr /*pSrcDrawable*/,
-    DrawablePtr /*pDstDrawable*/,
-    GCPtr/*pGC*/,
-    int /*srcx*/,
-    int /*srcy*/,
-    int /*width*/,
-    int /*height*/,
-    int /*dstx*/,
-    int /*dsty*/
-);
-
-#ifndef CFB_PROTOTYPES_ONLY
-extern void cfbCopyPlane1to8(
-    DrawablePtr /*pSrcDrawable*/,
-    DrawablePtr /*pDstDrawable*/,
-    int /*rop*/,
-    RegionPtr /*prgnDst*/,
-    DDXPointPtr /*pptSrc*/,
-    unsigned long /*planemask*/
-);
-#endif
-
-extern RegionPtr cfbCopyPlane(
-    DrawablePtr /*pSrcDrawable*/,
-    DrawablePtr /*pDstDrawable*/,
-    GCPtr /*pGC*/,
-    int /*srcx*/,
-    int /*srcy*/,
-    int /*width*/,
-    int /*height*/,
-    int /*dstx*/,
-    int /*dsty*/,
-    unsigned long /*bitPlane*/
-);
-/* cfbbltC.c */
-
-extern void cfbDoBitbltCopy(
-    DrawablePtr /*pSrc*/,
-    DrawablePtr /*pDst*/,
-    int /*alu*/,
-    RegionPtr /*prgnDst*/,
-    DDXPointPtr /*pptSrc*/,
-    unsigned long /*planemask*/
-);
-/* cfbbltG.c */
-
-extern void cfbDoBitbltGeneral(
-    DrawablePtr /*pSrc*/,
-    DrawablePtr /*pDst*/,
-    int /*alu*/,
-    RegionPtr /*prgnDst*/,
-    DDXPointPtr /*pptSrc*/,
-    unsigned long /*planemask*/
-);
-/* cfbbltO.c */
-
-extern void cfbDoBitbltOr(
-    DrawablePtr /*pSrc*/,
-    DrawablePtr /*pDst*/,
-    int /*alu*/,
-    RegionPtr /*prgnDst*/,
-    DDXPointPtr /*pptSrc*/,
-    unsigned long /*planemask*/
-);
-/* cfbbltX.c */
-
-extern void cfbDoBitbltXor(
-    DrawablePtr /*pSrc*/,
-    DrawablePtr /*pDst*/,
-    int /*alu*/,
-    RegionPtr /*prgnDst*/,
-    DDXPointPtr /*pptSrc*/,
-    unsigned long /*planemask*/
-);
-/* cfbbres.c */
-
-extern void cfbBresS(
-    int /*rop*/,
-    CfbBits /*and*/,
-    CfbBits /*xor*/,
-    CfbBits * /*addrl*/,
-    int /*nlwidth*/,
-    int /*signdx*/,
-    int /*signdy*/,
-    int /*axis*/,
-    int /*x1*/,
-    int /*y1*/,
-    int /*e*/,
-    int /*e1*/,
-    int /*e2*/,
-    int /*len*/
-);
-/* cfbbresd.c */
-
-extern void cfbBresD(
-    cfbRRopPtr /*rrops*/,
-    int * /*pdashIndex*/,
-    unsigned char * /*pDash*/,
-    int /*numInDashList*/,
-    int * /*pdashOffset*/,
-    int /*isDoubleDash*/,
-    CfbBits * /*addrl*/,
-    int /*nlwidth*/,
-    int /*signdx*/,
-    int /*signdy*/,
-    int /*axis*/,
-    int /*x1*/,
-    int /*y1*/,
-    int /*e*/,
-    int /*e1*/,
-    int /*e2*/,
-    int /*len*/
-);
-
-/* cfbcmap.c */
-
-#ifndef CFB_PROTOTYPES_ONLY
-extern int cfbListInstalledColormaps(
-    ScreenPtr	/*pScreen*/,
-    Colormap	* /*pmaps*/
-);
-
-extern void cfbInstallColormap(
-    ColormapPtr	/*pmap*/
-);
-
-extern void cfbUninstallColormap(
-    ColormapPtr	/*pmap*/
-);
-
-extern void cfbResolveColor(
-    unsigned short * /*pred*/,
-    unsigned short * /*pgreen*/,
-    unsigned short * /*pblue*/,
-    VisualPtr /*pVisual*/
-);
-
-extern Bool cfbInitializeColormap(
-    ColormapPtr /*pmap*/
-);
-
-extern int cfbExpandDirectColors(
-    ColormapPtr /*pmap*/,
-    int /*ndef*/,
-    xColorItem * /*indefs*/,
-    xColorItem * /*outdefs*/
-);
-
-extern Bool cfbCreateDefColormap(
-    ScreenPtr /*pScreen*/
-);
-
-extern Bool cfbSetVisualTypes(
-    int /*depth*/,
-    int /*visuals*/,
-    int /*bitsPerRGB*/
-);
-
-extern void cfbClearVisualTypes(void);
-
-extern Bool cfbInitVisuals(
-    VisualPtr * /*visualp*/,
-    DepthPtr * /*depthp*/,
-    int * /*nvisualp*/,
-    int * /*ndepthp*/,
-    int * /*rootDepthp*/,
-    VisualID * /*defaultVisp*/,
-    unsigned long /*sizes*/,
-    int /*bitsPerRGB*/
-);
-#endif
-/* cfbfillarcC.c */
-
-extern void cfbPolyFillArcSolidCopy(
-    DrawablePtr /*pDraw*/,
-    GCPtr /*pGC*/,
-    int /*narcs*/,
-    xArc * /*parcs*/
-);
-/* cfbfillarcG.c */
-
-extern void cfbPolyFillArcSolidGeneral(
-    DrawablePtr /*pDraw*/,
-    GCPtr /*pGC*/,
-    int /*narcs*/,
-    xArc * /*parcs*/
-);
-/* cfbfillrct.c */
-
-extern void cfbFillBoxTileOdd(
-    DrawablePtr /*pDrawable*/,
-    int /*n*/,
-    BoxPtr /*rects*/,
-    PixmapPtr /*tile*/,
-    int /*xrot*/,
-    int /*yrot*/
-);
-
-extern void cfbFillRectTileOdd(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/
-);
-
-extern void cfbPolyFillRect(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nrectFill*/,
-    xRectangle * /*prectInit*/
-);
-/* cfbfillsp.c */
-
-extern void cfbUnnaturalTileFS(
-    DrawablePtr /*pDrawable*/,
-    GCPtr/*pGC*/,
-    int /*nInit*/,
-    DDXPointPtr /*pptInit*/,
-    int * /*pwidthInit*/,
-    int /*fSorted*/
-);
-
-extern void cfbUnnaturalStippleFS(
-    DrawablePtr /*pDrawable*/,
-    GCPtr/*pGC*/,
-    int /*nInit*/,
-    DDXPointPtr /*pptInit*/,
-    int * /*pwidthInit*/,
-    int /*fSorted*/
-);
-
-#ifndef CFB_PROTOTYPES_ONLY
-extern void cfb8Stipple32FS(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nInit*/,
-    DDXPointPtr /*pptInit*/,
-    int * /*pwidthInit*/,
-    int /*fSorted*/
-);
-
-extern void cfb8OpaqueStipple32FS(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nInit*/,
-    DDXPointPtr /*pptInit*/,
-    int * /*pwidthInit*/,
-    int /*fSorted*/
-);
-#endif
-/* cfbgc.c */
-
-extern GCOpsPtr cfbMatchCommon(
-    GCPtr /*pGC*/,
-    cfbPrivGCPtr /*devPriv*/
-);
-
-extern Bool cfbCreateGC(
-    GCPtr /*pGC*/
-);
-
-extern void cfbValidateGC(
-    GCPtr /*pGC*/,
-    unsigned long /*changes*/,
-    DrawablePtr /*pDrawable*/
-);
-
-/* cfbgetsp.c */
-
-extern void cfbGetSpans(
-    DrawablePtr /*pDrawable*/,
-    int /*wMax*/,
-    DDXPointPtr /*ppt*/,
-    int * /*pwidth*/,
-    int /*nspans*/,
-    char * /*pdstStart*/
-);
-/* cfbglblt8.c */
-
-extern void cfbPolyGlyphBlt8(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*x*/,
-    int /*y*/,
-    unsigned int /*nglyph*/,
-    CharInfoPtr * /*ppci*/,
-    pointer /*pglyphBase*/
-);
-/* cfbglrop8.c */
-
-extern void cfbPolyGlyphRop8(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*x*/,
-    int /*y*/,
-    unsigned int /*nglyph*/,
-    CharInfoPtr * /*ppci*/,
-    pointer /*pglyphBase*/
-);
-/* cfbhrzvert.c */
-
-extern void cfbHorzS(
-    int /*rop*/,
-    CfbBits /*and*/,
-    CfbBits /*xor*/,
-    CfbBits * /*addrl*/,
-    int /*nlwidth*/,
-    int /*x1*/,
-    int /*y1*/,
-    int /*len*/
-);
-
-extern void cfbVertS(
-    int /*rop*/,
-    CfbBits /*and*/,
-    CfbBits /*xor*/,
-    CfbBits * /*addrl*/,
-    int /*nlwidth*/,
-    int /*x1*/,
-    int /*y1*/,
-    int /*len*/
-);
-/* cfbigblt8.c */
-
-extern void cfbImageGlyphBlt8(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*x*/,
-    int /*y*/,
-    unsigned int /*nglyph*/,
-    CharInfoPtr * /*ppci*/,
-    pointer /*pglyphBase*/
-);
-/* cfbimage.c */
-
-extern void cfbPutImage(
-    DrawablePtr /*pDraw*/,
-    GCPtr /*pGC*/,
-    int /*depth*/,
-    int /*x*/,
-    int /*y*/,
-    int /*w*/,
-    int /*h*/,
-    int /*leftPad*/,
-    int /*format*/,
-    char * /*pImage*/
-);
-
-extern void cfbGetImage(
-    DrawablePtr /*pDrawable*/,
-    int /*sx*/,
-    int /*sy*/,
-    int /*w*/,
-    int /*h*/,
-    unsigned int /*format*/,
-    unsigned long /*planeMask*/,
-    char * /*pdstLine*/
-);
-/* cfbline.c */
-
-extern void cfbLineSS(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*mode*/,
-    int /*npt*/,
-    DDXPointPtr /*pptInit*/
-);
-
-extern void cfbLineSD(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*mode*/,
-    int /*npt*/,
-    DDXPointPtr /*pptInit*/
-);
-/* cfbmskbits.c */
-/* cfbpixmap.c */
-
-extern PixmapPtr cfbCreatePixmap(
-    ScreenPtr /*pScreen*/,
-    int /*width*/,
-    int /*height*/,
-    int /*depth*/,
-    unsigned /*usage_hint*/
-);
-
-extern Bool cfbDestroyPixmap(
-    PixmapPtr /*pPixmap*/
-);
-
-extern PixmapPtr cfbCopyPixmap(
-    PixmapPtr /*pSrc*/
-);
-
-extern void cfbPadPixmap(
-    PixmapPtr /*pPixmap*/
-);
-
-extern void cfbXRotatePixmap(
-    PixmapPtr /*pPix*/,
-    int /*rw*/
-);
-
-extern void cfbYRotatePixmap(
-    PixmapPtr /*pPix*/,
-    int /*rh*/
-);
-
-extern void cfbCopyRotatePixmap(
-    PixmapPtr /*psrcPix*/,
-    PixmapPtr * /*ppdstPix*/,
-    int /*xrot*/,
-    int /*yrot*/
-);
-/* cfbply1rctC.c */
-
-extern void cfbFillPoly1RectCopy(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*shape*/,
-    int /*mode*/,
-    int /*count*/,
-    DDXPointPtr /*ptsIn*/
-);
-/* cfbply1rctG.c */
-
-extern void cfbFillPoly1RectGeneral(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*shape*/,
-    int /*mode*/,
-    int /*count*/,
-    DDXPointPtr /*ptsIn*/
-);
-/* cfbpolypnt.c */
-
-extern void cfbPolyPoint(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*mode*/,
-    int /*npt*/,
-    xPoint * /*pptInit*/
-);
-/* cfbpush8.c */
-
-#ifndef CFB_PROTOTYPES_ONLY
-extern void cfbPushPixels8(
-    GCPtr /*pGC*/,
-    PixmapPtr /*pBitmap*/,
-    DrawablePtr /*pDrawable*/,
-    int /*dx*/,
-    int /*dy*/,
-    int /*xOrg*/,
-    int /*yOrg*/
-);
-/* cfbrctstp8.c */
-
-extern void cfb8FillRectOpaqueStippled32(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/
-);
-
-extern void cfb8FillRectTransparentStippled32(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/
-);
-
-extern void cfb8FillRectStippledUnnatural(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/
-);
-#endif
-/* cfbrrop.c */
-
-extern int cfbReduceRasterOp(
-    int /*rop*/,
-    CfbBits /*fg*/,
-    CfbBits /*pm*/,
-    CfbBits * /*andp*/,
-    CfbBits * /*xorp*/
-);
-/* cfbscrinit.c */
-
-extern Bool cfbCloseScreen(
-    int /*index*/,
-    ScreenPtr /*pScreen*/
-);
-
-extern Bool cfbSetupScreen(
-    ScreenPtr /*pScreen*/,
-    pointer /*pbits*/,
-    int /*xsize*/,
-    int /*ysize*/,
-    int /*dpix*/,
-    int /*dpiy*/,
-    int /*width*/
-);
-
-extern Bool cfbFinishScreenInit(
-    ScreenPtr /*pScreen*/,
-    pointer /*pbits*/,
-    int /*xsize*/,
-    int /*ysize*/,
-    int /*dpix*/,
-    int /*dpiy*/,
-    int /*width*/
-);
-
-extern Bool cfbScreenInit(
-    ScreenPtr /*pScreen*/,
-    pointer /*pbits*/,
-    int /*xsize*/,
-    int /*ysize*/,
-    int /*dpix*/,
-    int /*dpiy*/,
-    int /*width*/
-);
-
-extern PixmapPtr cfbGetScreenPixmap(
-    ScreenPtr /*pScreen*/
-);
-
-extern void cfbSetScreenPixmap(
-    PixmapPtr /*pPix*/
-);
-
-/* cfbseg.c */
-
-extern void cfbSegmentSS(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nseg*/,
-    xSegment * /*pSeg*/
-);
-
-extern void cfbSegmentSD(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nseg*/,
-    xSegment * /*pSeg*/
-);
-/* cfbsetsp.c */
-
-extern void cfbSetScanline(
-    int /*y*/,
-    int /*xOrigin*/,
-    int /*xStart*/,
-    int /*xEnd*/,
-    unsigned int * /*psrc*/,
-    int /*alu*/,
-    int * /*pdstBase*/,
-    int /*widthDst*/,
-    unsigned long /*planemask*/
-);
-
-extern void cfbSetSpans(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    char * /*psrc*/,
-    DDXPointPtr /*ppt*/,
-    int * /*pwidth*/,
-    int /*nspans*/,
-    int /*fSorted*/
-);
-/* cfbsolidC.c */
-
-extern void cfbFillRectSolidCopy(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/
-);
-
-extern void cfbSolidSpansCopy(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nInit*/,
-    DDXPointPtr /*pptInit*/,
-    int * /*pwidthInit*/,
-    int /*fSorted*/
-);
-/* cfbsolidG.c */
-
-extern void cfbFillRectSolidGeneral(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/
-);
-
-extern void cfbSolidSpansGeneral(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nInit*/,
-    DDXPointPtr /*pptInit*/,
-    int * /*pwidthInit*/,
-    int /*fSorted*/
-);
-/* cfbsolidX.c */
-
-extern void cfbFillRectSolidXor(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/
-);
-
-extern void cfbSolidSpansXor(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nInit*/,
-    DDXPointPtr /*pptInit*/,
-    int * /*pwidthInit*/,
-    int /*fSorted*/
-);
-/* cfbteblt8.c */
-
-#ifndef CFB_PROTOTYPES_ONLY
-extern void cfbTEGlyphBlt8(
-    DrawablePtr /*pDrawable*/,
-    GCPtr/*pGC*/,
-    int /*xInit*/,
-    int /*yInit*/,
-    unsigned int /*nglyph*/,
-    CharInfoPtr * /*ppci*/,
-    pointer /*pglyphBase*/
-);
-#endif
-/* cfbtegblt.c */
-
-extern void cfbTEGlyphBlt(
-    DrawablePtr /*pDrawable*/,
-    GCPtr/*pGC*/,
-    int /*x*/,
-    int /*y*/,
-    unsigned int /*nglyph*/,
-    CharInfoPtr * /*ppci*/,
-    pointer /*pglyphBase*/
-);
-/* cfbtile32C.c */
-
-extern void cfbFillRectTile32Copy(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/
-);
-
-extern void cfbTile32FSCopy(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nInit*/,
-    DDXPointPtr /*pptInit*/,
-    int * /*pwidthInit*/,
-    int /*fSorted*/
-);
-/* cfbtile32G.c */
-
-extern void cfbFillRectTile32General(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/
-);
-
-extern void cfbTile32FSGeneral(
-    DrawablePtr /*pDrawable*/,
-    GCPtr /*pGC*/,
-    int /*nInit*/,
-    DDXPointPtr /*pptInit*/,
-    int * /*pwidthInit*/,
-    int /*fSorted*/
-);
-/* cfbtileoddC.c */
-
-extern void cfbFillBoxTileOddCopy(
-    DrawablePtr /*pDrawable*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/,
-    PixmapPtr /*tile*/,
-    int /*xrot*/,
-    int /*yrot*/,
-    int /*alu*/,
-    unsigned long /*planemask*/
-);
-
-extern void cfbFillSpanTileOddCopy(
-    DrawablePtr /*pDrawable*/,
-    int /*n*/,
-    DDXPointPtr /*ppt*/,
-    int * /*pwidth*/,
-    PixmapPtr /*tile*/,
-    int /*xrot*/,
-    int /*yrot*/,
-    int /*alu*/,
-    unsigned long /*planemask*/
-);
-
-extern void cfbFillBoxTile32sCopy(
-    DrawablePtr /*pDrawable*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/,
-    PixmapPtr /*tile*/,
-    int /*xrot*/,
-    int /*yrot*/,
-    int /*alu*/,
-    unsigned long /*planemask*/
-);
-
-extern void cfbFillSpanTile32sCopy(
-    DrawablePtr /*pDrawable*/,
-    int /*n*/,
-    DDXPointPtr /*ppt*/,
-    int * /*pwidth*/,
-    PixmapPtr /*tile*/,
-    int /*xrot*/,
-    int /*yrot*/,
-    int /*alu*/,
-    unsigned long /*planemask*/
-);
-/* cfbtileoddG.c */
-
-extern void cfbFillBoxTileOddGeneral(
-    DrawablePtr /*pDrawable*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/,
-    PixmapPtr /*tile*/,
-    int /*xrot*/,
-    int /*yrot*/,
-    int /*alu*/,
-    unsigned long /*planemask*/
-);
-
-extern void cfbFillSpanTileOddGeneral(
-    DrawablePtr /*pDrawable*/,
-    int /*n*/,
-    DDXPointPtr /*ppt*/,
-    int * /*pwidth*/,
-    PixmapPtr /*tile*/,
-    int /*xrot*/,
-    int /*yrot*/,
-    int /*alu*/,
-    unsigned long /*planemask*/
-);
-
-extern void cfbFillBoxTile32sGeneral(
-    DrawablePtr /*pDrawable*/,
-    int /*nBox*/,
-    BoxPtr /*pBox*/,
-    PixmapPtr /*tile*/,
-    int /*xrot*/,
-    int /*yrot*/,
-    int /*alu*/,
-    unsigned long /*planemask*/
-);
-
-extern void cfbFillSpanTile32sGeneral(
-    DrawablePtr /*pDrawable*/,
-    int /*n*/,
-    DDXPointPtr /*ppt*/,
-    int * /*pwidth*/,
-    PixmapPtr /*tile*/,
-    int /*xrot*/,
-    int /*yrot*/,
-    int /*alu*/,
-    unsigned long /*planemask*/
-);
-/* cfbwindow.c */
-
-extern Bool cfbCreateWindow(
-    WindowPtr /*pWin*/
-);
-
-extern Bool cfbDestroyWindow(
-    WindowPtr /*pWin*/
-);
-
-extern Bool cfbMapWindow(
-    WindowPtr /*pWindow*/
-);
-
-extern Bool cfbPositionWindow(
-    WindowPtr /*pWin*/,
-    int /*x*/,
-    int /*y*/
-);
-
-extern Bool cfbUnmapWindow(
-    WindowPtr /*pWindow*/
-);
-
-extern void cfbCopyWindow(
-    WindowPtr /*pWin*/,
-    DDXPointRec /*ptOldOrg*/,
-    RegionPtr /*prgnSrc*/
-);
-
-extern Bool cfbChangeWindowAttributes(
-    WindowPtr /*pWin*/,
-    unsigned long /*mask*/
-);
-/* cfbzerarcC.c */
-
-extern void cfbZeroPolyArcSS8Copy(
-    DrawablePtr /*pDraw*/,
-    GCPtr /*pGC*/,
-    int /*narcs*/,
-    xArc * /*parcs*/
-);
-/* cfbzerarcG.c */
-
-extern void cfbZeroPolyArcSS8General(
-    DrawablePtr /*pDraw*/,
-    GCPtr /*pGC*/,
-    int /*narcs*/,
-    xArc * /*parcs*/
-);
-/* cfbzerarcX.c */
-
-extern void cfbZeroPolyArcSS8Xor(
-    DrawablePtr /*pDraw*/,
-    GCPtr /*pGC*/,
-    int /*narcs*/,
-    xArc * /*parcs*/
-);
-
-#if (!defined(SINGLEDEPTH) && PSZ != 8) || defined(FORCE_SEPARATE_PRIVATE)
-
-#define CFB_NEED_SCREEN_PRIVATE
-
-extern DevPrivateKey cfbScreenPrivateKey;
-#endif
-
-#ifndef CFB_PROTOTYPES_ONLY
-
-/* Common macros for extracting drawing information */
-
-#define cfbGetWindowPixmap(d) \
-    ((* ((DrawablePtr)(d))->pScreen->GetWindowPixmap)((WindowPtr)(d)))
-
-#define cfbGetTypedWidth(pDrawable,wtype) (\
-    (((pDrawable)->type != DRAWABLE_PIXMAP) ? \
-     (int) (cfbGetWindowPixmap(pDrawable)->devKind) : \
-     (int)(((PixmapPtr)pDrawable)->devKind)) / sizeof (wtype))
-
-#define cfbGetByteWidth(pDrawable) cfbGetTypedWidth(pDrawable, unsigned char)
-
-#define cfbGetPixelWidth(pDrawable) cfbGetTypedWidth(pDrawable, PixelType)
-
-#define cfbGetLongWidth(pDrawable) cfbGetTypedWidth(pDrawable, CfbBits)
-    
-#define cfbGetTypedWidthAndPointer(pDrawable, width, pointer, wtype, ptype) {\
-    PixmapPtr   _pPix; \
-    if ((pDrawable)->type != DRAWABLE_PIXMAP) \
-	_pPix = cfbGetWindowPixmap(pDrawable); \
-    else \
-	_pPix = (PixmapPtr) (pDrawable); \
-    (pointer) = (ptype *) _pPix->devPrivate.ptr; \
-    (width) = ((int) _pPix->devKind) / sizeof (wtype); \
-}
-
-#define cfbGetByteWidthAndPointer(pDrawable, width, pointer) \
-    cfbGetTypedWidthAndPointer(pDrawable, width, pointer, unsigned char, unsigned char)
-
-#define cfbGetLongWidthAndPointer(pDrawable, width, pointer) \
-    cfbGetTypedWidthAndPointer(pDrawable, width, pointer, CfbBits, CfbBits)
-
-#define cfbGetPixelWidthAndPointer(pDrawable, width, pointer) \
-    cfbGetTypedWidthAndPointer(pDrawable, width, pointer, PixelType, PixelType)
-
-#define cfbGetWindowTypedWidthAndPointer(pWin, width, pointer, wtype, ptype) {\
-    PixmapPtr	_pPix = cfbGetWindowPixmap((DrawablePtr) (pWin)); \
-    (pointer) = (ptype *) _pPix->devPrivate.ptr; \
-    (width) = ((int) _pPix->devKind) / sizeof (wtype); \
-}
-
-#define cfbGetWindowLongWidthAndPointer(pWin, width, pointer) \
-    cfbGetWindowTypedWidthAndPointer(pWin, width, pointer, CfbBits, CfbBits)
-
-#define cfbGetWindowByteWidthAndPointer(pWin, width, pointer) \
-    cfbGetWindowTypedWidthAndPointer(pWin, width, pointer, unsigned char, unsigned char)
-
-#define cfbGetWindowPixelWidthAndPointer(pDrawable, width, pointer) \
-    cfbGetWindowTypedWidthAndPointer(pDrawable, width, pointer, PixelType, PixelType)
-
-/*
- * XFree86 empties the root BorderClip when the VT is inactive,
- * here's a macro which uses that to disable GetImage and GetSpans
- */
-#define cfbWindowEnabled(pWin) \
-    REGION_NOTEMPTY((pWin)->drawable.pScreen, \
-		    &WindowTable[(pWin)->drawable.pScreen->myNum]->borderClip)
-
-#define cfbDrawableEnabled(pDrawable) \
-    ((pDrawable)->type == DRAWABLE_PIXMAP ? \
-     TRUE : cfbWindowEnabled((WindowPtr) pDrawable))
-
-#include "micoord.h"
-
-#endif /* !CFB_PROTOTYPES_ONLY */
-
-#endif
diff --git a/cfb/cfb16.h b/cfb/cfb16.h
deleted file mode 100644
index 6b5c302..0000000
--- a/cfb/cfb16.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 1994-1998 The XFree86 Project, Inc.  All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
- * XFREE86 PROJECT BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name of the XFree86 Project shall
- * not be used in advertising or otherwise to promote the sale, use or other
- * dealings in this Software without prior written authorization from the
- * XFree86 Project.
- */
-
-#ifndef _CFB16_H_
-#define _CFB16_H_
-
-/*
- * C's preprocessing language substitutes >text<, not values...
- */
-
-#ifdef OLDPSZ
-# undef OLDPSZ
-#endif
-
-#ifdef PSZ
-
-# if (PSZ == 8)
-#  define OLDPSZ 8
-# endif
-
-# if (PSZ == 16)
-#  define OLDPSZ 16 
-# endif
-
-# if (PSZ == 24)
-#  define OLDPSZ 24 
-# endif
-
-# if (PSZ == 32)
-#  define OLDPSZ 32 
-# endif
-
-# ifndef OLDPSZ
-   /* Maybe an #error here ? */
-# endif
-
-# undef PSZ
-
-#endif
-
-#define PSZ 16
-#define CFB_PROTOTYPES_ONLY
-#include "cfb.h"
-#undef CFB_PROTOTYPES_ONLY
-#include "cfbunmap.h"
-
-#undef PSZ
-#ifdef OLDPSZ
-
-# if (OLDPSZ == 8)
-#  define PSZ 8
-# endif
-
-# if (OLDPSZ == 16)
-#  define PSZ 16 
-# endif
-
-# if (OLDPSZ == 24)
-#  define PSZ 24 
-# endif
-
-# if (OLDPSZ == 32)
-#  define PSZ 32 
-# endif
-
-# undef OLDPSZ
-
-#endif
-
-#endif /* _CFB16_H_ */
diff --git a/cfb/cfb24.h b/cfb/cfb24.h
deleted file mode 100644
index ea5fc84..0000000
--- a/cfb/cfb24.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 1994-1998 The XFree86 Project, Inc.  All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
- * XFREE86 PROJECT BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name of the XFree86 Project shall
- * not be used in advertising or otherwise to promote the sale, use or other
- * dealings in this Software without prior written authorization from the
- * XFree86 Project.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifndef _CFB24_H_
-#define _CFB24_H_
-
-/*
- * C's preprocessing language substitutes >text<, not values...
- */
-
-#ifdef OLDPSZ
-# undef OLDPSZ
-#endif
-
-#ifdef PSZ
-
-# if (PSZ == 8)
-#  define OLDPSZ 8
-# endif
-
-# if (PSZ == 16)
-#  define OLDPSZ 16 
-# endif
-
-# if (PSZ == 24)
-#  define OLDPSZ 24 
-# endif
-
-# if (PSZ == 32)
-#  define OLDPSZ 32 
-# endif
-
-# ifndef OLDPSZ
-   /* Maybe an #error here ? */
-# endif
-
-# undef PSZ
-
-#endif
-
-#define PSZ 24
-#define CFB_PROTOTYPES_ONLY
-#include "cfb.h"
-#undef CFB_PROTOTYPES_ONLY
-#include "cfbunmap.h"
-
-#undef PSZ
-#ifdef OLDPSZ
-
-# if (OLDPSZ == 8)
-#  define PSZ 8
-# endif
-
-# if (OLDPSZ == 16)
-#  define PSZ 16 
-# endif
-
-# if (OLDPSZ == 24)
-#  define PSZ 24 
-# endif
-
-# if (OLDPSZ == 32)
-#  define PSZ 32 
-# endif
-
-# undef OLDPSZ
-
-#endif
-
-#endif /* _CFB24_H_ */
diff --git a/cfb/cfb32.h b/cfb/cfb32.h
deleted file mode 100644
index 18a5dc1..0000000
--- a/cfb/cfb32.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 1994-1998 The XFree86 Project, Inc.  All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
- * XFREE86 PROJECT BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name of the XFree86 Project shall
- * not be used in advertising or otherwise to promote the sale, use or other
- * dealings in this Software without prior written authorization from the
- * XFree86 Project.
- */
-
-#ifndef _CFB32_H_
-#define _CFB32_H_
-
-/*
- * C's preprocessing language substitutes >text<, not values...
- */
-
-#ifdef OLDPSZ
-# undef OLDPSZ
-#endif
-
-#ifdef PSZ
-
-# if (PSZ == 8)
-#  define OLDPSZ 8
-# endif
-
-# if (PSZ == 16)
-#  define OLDPSZ 16 
-# endif
-
-# if (PSZ == 24)
-#  define OLDPSZ 24 
-# endif
-
-# if (PSZ == 32)
-#  define OLDPSZ 32 
-# endif
-
-# ifndef OLDPSZ
-   /* Maybe an #error here ? */
-# endif
-
-# undef PSZ
-
-#endif
-
-#define PSZ 32
-#define CFB_PROTOTYPES_ONLY
-#include "cfb.h"
-#undef CFB_PROTOTYPES_ONLY
-#include "cfbunmap.h"
-
-#undef PSZ
-#ifdef OLDPSZ
-
-# if (OLDPSZ == 8)
-#  define PSZ 8
-# endif
-
-# if (OLDPSZ == 16)
-#  define PSZ 16 
-# endif
-
-# if (OLDPSZ == 24)
-#  define PSZ 24 
-# endif
-
-# if (OLDPSZ == 32)
-#  define PSZ 32 
-# endif
-
-# undef OLDPSZ
-
-#endif
-
-#endif /* _CFB32_H_ */
diff --git a/cfb/cfb8bit.c b/cfb/cfb8bit.c
deleted file mode 100644
index 54a08c5..0000000
--- a/cfb/cfb8bit.c
+++ /dev/null
@@ -1,469 +0,0 @@
-/*
-
-Copyright 1989, 1994, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
-OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall
-not be used in advertising or otherwise to promote the sale, use or
-other dealings in this Software without prior written authorization
-from The Open Group.
-
-*/
-
-/*
- * cfb8bit.c
- *
- * 8 bit color frame buffer utility routines
- */
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#if PSZ == 8
-
-#include	<X11/X.h>
-#include	<X11/Xmd.h>
-#include	<X11/Xproto.h>
-#include	"gcstruct.h"
-#include	"windowstr.h"
-#include	"scrnintstr.h"
-#include	"pixmapstr.h"
-#include	"regionstr.h"
-#include	"cfb.h"
-#include	"cfbmskbits.h"
-#include	"cfb8bit.h"
-
-PixelGroup cfb8StippleMasks[NUM_MASKS] = {
-#if NUM_MASKS == 16
-    0x00000000, 0x000000ff, 0x0000ff00, 0x0000ffff,
-    0x00ff0000, 0x00ff00ff, 0x00ffff00, 0x00ffffff,
-    0xff000000, 0xff0000ff, 0xff00ff00, 0xff00ffff,
-    0xffff0000, 0xffff00ff, 0xffffff00, 0xffffffff
-#else /* NUM_MASKS == 256 */
-    0x0000000000000000,	0x00000000000000ff,
-    0x000000000000ff00,	0x000000000000ffff,
-    0x0000000000ff0000,	0x0000000000ff00ff,
-    0x0000000000ffff00,	0x0000000000ffffff,
-    0x00000000ff000000,	0x00000000ff0000ff,
-    0x00000000ff00ff00,	0x00000000ff00ffff,
-    0x00000000ffff0000,	0x00000000ffff00ff,
-    0x00000000ffffff00,	0x00000000ffffffff,
-    0x000000ff00000000,	0x000000ff000000ff,
-    0x000000ff0000ff00,	0x000000ff0000ffff,
-    0x000000ff00ff0000,	0x000000ff00ff00ff,
-    0x000000ff00ffff00,	0x000000ff00ffffff,
-    0x000000ffff000000,	0x000000ffff0000ff,
-    0x000000ffff00ff00,	0x000000ffff00ffff,
-    0x000000ffffff0000,	0x000000ffffff00ff,
-    0x000000ffffffff00,	0x000000ffffffffff,
-    0x0000ff0000000000,	0x0000ff00000000ff,
-    0x0000ff000000ff00,	0x0000ff000000ffff,
-    0x0000ff0000ff0000,	0x0000ff0000ff00ff,
-    0x0000ff0000ffff00,	0x0000ff0000ffffff,
-    0x0000ff00ff000000,	0x0000ff00ff0000ff,
-    0x0000ff00ff00ff00,	0x0000ff00ff00ffff,
-    0x0000ff00ffff0000,	0x0000ff00ffff00ff,
-    0x0000ff00ffffff00,	0x0000ff00ffffffff,
-    0x0000ffff00000000,	0x0000ffff000000ff,
-    0x0000ffff0000ff00,	0x0000ffff0000ffff,
-    0x0000ffff00ff0000,	0x0000ffff00ff00ff,
-    0x0000ffff00ffff00,	0x0000ffff00ffffff,
-    0x0000ffffff000000,	0x0000ffffff0000ff,
-    0x0000ffffff00ff00,	0x0000ffffff00ffff,
-    0x0000ffffffff0000,	0x0000ffffffff00ff,
-    0x0000ffffffffff00,	0x0000ffffffffffff,
-    0x00ff000000000000,	0x00ff0000000000ff,
-    0x00ff00000000ff00,	0x00ff00000000ffff,
-    0x00ff000000ff0000,	0x00ff000000ff00ff,
-    0x00ff000000ffff00,	0x00ff000000ffffff,
-    0x00ff0000ff000000,	0x00ff0000ff0000ff,
-    0x00ff0000ff00ff00,	0x00ff0000ff00ffff,
-    0x00ff0000ffff0000,	0x00ff0000ffff00ff,
-    0x00ff0000ffffff00,	0x00ff0000ffffffff,
-    0x00ff00ff00000000,	0x00ff00ff000000ff,
-    0x00ff00ff0000ff00,	0x00ff00ff0000ffff,
-    0x00ff00ff00ff0000,	0x00ff00ff00ff00ff,
-    0x00ff00ff00ffff00,	0x00ff00ff00ffffff,
-    0x00ff00ffff000000,	0x00ff00ffff0000ff,
-    0x00ff00ffff00ff00,	0x00ff00ffff00ffff,
-    0x00ff00ffffff0000,	0x00ff00ffffff00ff,
-    0x00ff00ffffffff00,	0x00ff00ffffffffff,
-    0x00ffff0000000000,	0x00ffff00000000ff,
-    0x00ffff000000ff00,	0x00ffff000000ffff,
-    0x00ffff0000ff0000,	0x00ffff0000ff00ff,
-    0x00ffff0000ffff00,	0x00ffff0000ffffff,
-    0x00ffff00ff000000,	0x00ffff00ff0000ff,
-    0x00ffff00ff00ff00,	0x00ffff00ff00ffff,
-    0x00ffff00ffff0000,	0x00ffff00ffff00ff,
-    0x00ffff00ffffff00,	0x00ffff00ffffffff,
-    0x00ffffff00000000,	0x00ffffff000000ff,
-    0x00ffffff0000ff00,	0x00ffffff0000ffff,
-    0x00ffffff00ff0000,	0x00ffffff00ff00ff,
-    0x00ffffff00ffff00,	0x00ffffff00ffffff,
-    0x00ffffffff000000,	0x00ffffffff0000ff,
-    0x00ffffffff00ff00,	0x00ffffffff00ffff,
-    0x00ffffffffff0000,	0x00ffffffffff00ff,
-    0x00ffffffffffff00,	0x00ffffffffffffff,
-    0xff00000000000000,	0xff000000000000ff,
-    0xff0000000000ff00,	0xff0000000000ffff,
-    0xff00000000ff0000,	0xff00000000ff00ff,
-    0xff00000000ffff00,	0xff00000000ffffff,
-    0xff000000ff000000,	0xff000000ff0000ff,
-    0xff000000ff00ff00,	0xff000000ff00ffff,
-    0xff000000ffff0000,	0xff000000ffff00ff,
-    0xff000000ffffff00,	0xff000000ffffffff,
-    0xff0000ff00000000,	0xff0000ff000000ff,
-    0xff0000ff0000ff00,	0xff0000ff0000ffff,
-    0xff0000ff00ff0000,	0xff0000ff00ff00ff,
-    0xff0000ff00ffff00,	0xff0000ff00ffffff,
-    0xff0000ffff000000,	0xff0000ffff0000ff,
-    0xff0000ffff00ff00,	0xff0000ffff00ffff,
-    0xff0000ffffff0000,	0xff0000ffffff00ff,
-    0xff0000ffffffff00,	0xff0000ffffffffff,
-    0xff00ff0000000000,	0xff00ff00000000ff,
-    0xff00ff000000ff00,	0xff00ff000000ffff,
-    0xff00ff0000ff0000,	0xff00ff0000ff00ff,
-    0xff00ff0000ffff00,	0xff00ff0000ffffff,
-    0xff00ff00ff000000,	0xff00ff00ff0000ff,
-    0xff00ff00ff00ff00,	0xff00ff00ff00ffff,
-    0xff00ff00ffff0000,	0xff00ff00ffff00ff,
-    0xff00ff00ffffff00,	0xff00ff00ffffffff,
-    0xff00ffff00000000,	0xff00ffff000000ff,
-    0xff00ffff0000ff00,	0xff00ffff0000ffff,
-    0xff00ffff00ff0000,	0xff00ffff00ff00ff,
-    0xff00ffff00ffff00,	0xff00ffff00ffffff,
-    0xff00ffffff000000,	0xff00ffffff0000ff,
-    0xff00ffffff00ff00,	0xff00ffffff00ffff,
-    0xff00ffffffff0000,	0xff00ffffffff00ff,
-    0xff00ffffffffff00,	0xff00ffffffffffff,
-    0xffff000000000000,	0xffff0000000000ff,
-    0xffff00000000ff00,	0xffff00000000ffff,
-    0xffff000000ff0000,	0xffff000000ff00ff,
-    0xffff000000ffff00,	0xffff000000ffffff,
-    0xffff0000ff000000,	0xffff0000ff0000ff,
-    0xffff0000ff00ff00,	0xffff0000ff00ffff,
-    0xffff0000ffff0000,	0xffff0000ffff00ff,
-    0xffff0000ffffff00,	0xffff0000ffffffff,
-    0xffff00ff00000000,	0xffff00ff000000ff,
-    0xffff00ff0000ff00,	0xffff00ff0000ffff,
-    0xffff00ff00ff0000,	0xffff00ff00ff00ff,
-    0xffff00ff00ffff00,	0xffff00ff00ffffff,
-    0xffff00ffff000000,	0xffff00ffff0000ff,
-    0xffff00ffff00ff00,	0xffff00ffff00ffff,
-    0xffff00ffffff0000,	0xffff00ffffff00ff,
-    0xffff00ffffffff00,	0xffff00ffffffffff,
-    0xffffff0000000000,	0xffffff00000000ff,
-    0xffffff000000ff00,	0xffffff000000ffff,
-    0xffffff0000ff0000,	0xffffff0000ff00ff,
-    0xffffff0000ffff00,	0xffffff0000ffffff,
-    0xffffff00ff000000,	0xffffff00ff0000ff,
-    0xffffff00ff00ff00,	0xffffff00ff00ffff,
-    0xffffff00ffff0000,	0xffffff00ffff00ff,
-    0xffffff00ffffff00,	0xffffff00ffffffff,
-    0xffffffff00000000,	0xffffffff000000ff,
-    0xffffffff0000ff00,	0xffffffff0000ffff,
-    0xffffffff00ff0000,	0xffffffff00ff00ff,
-    0xffffffff00ffff00,	0xffffffff00ffffff,
-    0xffffffffff000000,	0xffffffffff0000ff,
-    0xffffffffff00ff00,	0xffffffffff00ffff,
-    0xffffffffffff0000,	0xffffffffffff00ff,
-    0xffffffffffffff00,	0xffffffffffffffff
-#endif
-};
-
-int	cfb8StippleMode, cfb8StippleAlu, cfb8StippleRRop;
-PixelGroup cfb8StippleFg, cfb8StippleBg, cfb8StipplePm;
-PixelGroup cfb8StippleAnd[NUM_MASKS], cfb8StippleXor[NUM_MASKS];
-
-int
-cfb8SetStipple (alu, fg, planemask)
-int		alu;
-CfbBits	fg, planemask;
-{
-    CfbBits   and, xor, rrop;
-    int	s;
-    CfbBits   c;
-
-    cfb8StippleMode = FillStippled;
-    cfb8StippleAlu = alu;
-    cfb8StippleFg = fg & PMSK;
-    cfb8StipplePm = planemask & PMSK;
-    rrop = cfbReduceRasterOp (alu, fg, planemask, &and, &xor);
-    cfb8StippleRRop = rrop;
-    /*
-     * create the appropriate pixel-fill bits for current
-     * foreground
-     */
-    for (s = 0; s < NUM_MASKS; s++)
-    {
-	c = cfb8StippleMasks[s];
-	cfb8StippleAnd[s] = and | ~c;
-	cfb8StippleXor[s] = xor & c;
-    }
-    return TRUE;
-}
-
-
-int
-cfb8SetOpaqueStipple (alu, fg, bg, planemask)
-int		alu;
-CfbBits	fg, bg, planemask;
-{
-    CfbBits   andfg, xorfg, andbg, xorbg, rropfg, rropbg;
-    int	s;
-    CfbBits   c;
-
-    cfb8StippleMode = FillOpaqueStippled;
-    cfb8StippleAlu = alu;
-    cfb8StippleFg = fg & PMSK;
-    cfb8StippleBg = bg & PMSK;
-    cfb8StipplePm = planemask & PMSK;
-    rropfg = cfbReduceRasterOp (alu, cfb8StippleFg, cfb8StipplePm, &andfg, &xorfg);
-    rropbg = cfbReduceRasterOp (alu, cfb8StippleBg, cfb8StipplePm, &andbg, &xorbg);
-    if (rropfg == rropbg)
-	cfb8StippleRRop = rropfg;
-    else
-	cfb8StippleRRop = GXset;
-    /*
-     * create the appropriate pixel-fill bits for current
-     * foreground
-     */
-    for (s = 0; s < NUM_MASKS; s++)
-    {
-	c = cfb8StippleMasks[s];
-	cfb8StippleAnd[s] = (andfg | ~c) & (andbg | c);
-	cfb8StippleXor[s] = (xorfg & c) | (xorbg & ~c);
-    }
-    return TRUE;
-}
-
-/*
- * a grungy little routine.  This computes clip masks
- * for partial character blts.  Returns rgnOUT if the
- * entire character is clipped; returns rgnIN if the entire
- * character is unclipped; returns rgnPART if a portion of
- * the character is visible.  Computes clip masks for each
- * longword of the character -- and those with the
- * contents of the glyph to compute the visible bits.
- */
-
-#if PGSZ == 32
-#if (BITMAP_BIT_ORDER == MSBFirst)
-PixelGroup cfb8BitLenMasks[PGSZ] = {
-    0xffffffff, 0x7fffffff, 0x3fffffff, 0x1fffffff,
-    0x0fffffff, 0x07ffffff, 0x03ffffff, 0x01ffffff,
-    0x00ffffff, 0x007fffff, 0x003fffff, 0x001fffff,
-    0x000fffff, 0x0007ffff, 0x0003ffff, 0x0001ffff,
-    0x0000ffff, 0x00007fff, 0x00003fff, 0x00001fff,
-    0x00000fff, 0x000007ff, 0x000003ff, 0x000001ff,
-    0x000000ff, 0x0000007f, 0x0000003f, 0x0000001f,
-    0x0000000f, 0x00000007, 0x00000003, 0x00000001,
-};
-#else
-PixelGroup cfb8BitLenMasks[PGSZ] = {
-    0xffffffff, 0xfffffffe, 0xfffffffc, 0xfffffff8,
-    0xfffffff0, 0xffffffe0, 0xffffffc0, 0xffffff80,
-    0xffffff00, 0xfffffe00, 0xfffffc00, 0xfffff800,
-    0xfffff000, 0xffffe000, 0xffffc000, 0xffff8000,
-    0xffff0000, 0xfffe0000, 0xfffc0000, 0xfff80000,
-    0xfff00000, 0xffe00000, 0xffc00000, 0xff800000,
-    0xff000000, 0xfe000000, 0xfc000000, 0xf8000000,
-    0xf0000000, 0xe0000000, 0xc0000000, 0x80000000,
-};
-#endif /* BITMAP_BIT_ORDER */
-#else /* PGSZ == 64 */
-#if (BITMAP_BIT_ORDER == MSBFirst)
-PixelGroup cfb8BitLenMasks[PGSZ] = {
-    0xffffffffffffffff,    0x7fffffffffffffff,
-    0x3fffffffffffffff,    0x1fffffffffffffff,
-    0x0fffffffffffffff,    0x07ffffffffffffff,
-    0x03ffffffffffffff,    0x01ffffffffffffff,
-    0x00ffffffffffffff,    0x007fffffffffffff,
-    0x003fffffffffffff,    0x001fffffffffffff,
-    0x000fffffffffffff,    0x0007ffffffffffff,
-    0x0003ffffffffffff,    0x0001ffffffffffff,
-    0x0000ffffffffffff,    0x00007fffffffffff,
-    0x00003fffffffffff,    0x00001fffffffffff,
-    0x00000fffffffffff,    0x000007ffffffffff,
-    0x000003ffffffffff,    0x000001ffffffffff,
-    0x000000ffffffffff,    0x0000007fffffffff,
-    0x0000003fffffffff,    0x0000001fffffffff,
-    0x0000000fffffffff,    0x00000007ffffffff,
-    0x00000003ffffffff,    0x00000001ffffffff,
-    0x00000000ffffffff,    0x000000007fffffff,
-    0x000000003fffffff,    0x000000001fffffff,
-    0x000000000fffffff,    0x0000000007ffffff,
-    0x0000000003ffffff,    0x0000000001ffffff,
-    0x0000000000ffffff,    0x00000000007fffff,
-    0x00000000003fffff,    0x00000000001fffff,
-    0x00000000000fffff,    0x000000000007ffff,
-    0x000000000003ffff,    0x000000000001ffff,
-    0x000000000000ffff,    0x0000000000007fff,
-    0x0000000000003fff,    0x0000000000001fff,
-    0x0000000000000fff,    0x00000000000007ff,
-    0x00000000000003ff,    0x00000000000001ff,
-    0x00000000000000ff,    0x000000000000007f,
-    0x000000000000003f,    0x000000000000001f,
-    0x000000000000000f,    0x0000000000000007,
-    0x0000000000000003,    0x0000000000000001
-};
-#else
-PixelGroup cfb8BitLenMasks[PGSZ] = {
-    0xffffffffffffffff,    0xfffffffffffffffe,
-    0xfffffffffffffffc,    0xfffffffffffffff8,
-    0xfffffffffffffff0,    0xffffffffffffffe0,
-    0xffffffffffffffc0,    0xffffffffffffff80,
-    0xffffffffffffff00,    0xfffffffffffffe00,
-    0xfffffffffffffc00,    0xfffffffffffff800,
-    0xfffffffffffff000,    0xffffffffffffe000,
-    0xffffffffffffc000,    0xffffffffffff8000,
-    0xffffffffffff0000,    0xfffffffffffe0000,
-    0xfffffffffffc0000,    0xfffffffffff80000,
-    0xfffffffffff00000,    0xffffffffffe00000,
-    0xffffffffffc00000,    0xffffffffff800000,
-    0xffffffffff000000,    0xfffffffffe000000,
-    0xfffffffffc000000,    0xfffffffff8000000,
-    0xfffffffff0000000,    0xffffffffe0000000,
-    0xffffffffc0000000,    0xffffffff80000000,
-    0xffffffff00000000,    0xfffffffe00000000,
-    0xfffffffc00000000,    0xfffffff800000000,
-    0xfffffff000000000,    0xffffffe000000000,
-    0xffffffc000000000,    0xffffff8000000000,
-    0xffffff0000000000,    0xfffffe0000000000,
-    0xfffffc0000000000,    0xfffff80000000000,
-    0xfffff00000000000,    0xffffe00000000000,
-    0xffffc00000000000,    0xffff800000000000,
-    0xffff000000000000,    0xfffe000000000000,
-    0xfffc000000000000,    0xfff8000000000000,
-    0xfff0000000000000,    0xffe0000000000000,
-    0xffc0000000000000,    0xff80000000000000,
-    0xff00000000000000,    0xfe00000000000000,
-    0xfc00000000000000,    0xf800000000000000,
-    0xf000000000000000,    0xe000000000000000,
-    0xc000000000000000,    0x8000000000000000
-};
-#endif /* BITMAP_BIT_ORDER */
-#endif /* PGSZ */
-
-
-
-int
-cfb8ComputeClipMasks32 (pBox, numRects, x, y, w, h, clips)
-    BoxPtr	pBox;
-    int		numRects;
-    int		x, y, w, h;
-    CARD32      *clips;
-{
-    int	    yBand, yBandBot;
-    int	    ch;
-    CfbBits	    clip;
-    int	    partIN = FALSE, partOUT = FALSE;
-    int	    result;
-
-    if (numRects == 0)
-	return rgnOUT;
-    while (numRects && pBox->y2 <= y)
-    {
-	--numRects;
-	++pBox;
-    }
-    if (!numRects || pBox->y1 >= y + h)
-	return rgnOUT;
-    yBand = pBox->y1;
-    while (numRects && pBox->y1 == yBand && pBox->x2 <= x)
-    {
-	--numRects;
-	++pBox;
-    }
-    if (!numRects || pBox->y1 >= y + h)
-	return rgnOUT;
-    if (numRects &&
-	x >= pBox->x1 &&
-	x + w <= pBox->x2 &&
-	y >= pBox->y1 &&
-	y + h <= pBox->y2)
-    {
-	return rgnIN;
-    }
-    ch = 0;
-    while (numRects && pBox->y1 < y + h)
-    {
-	yBand = pBox->y1;
-	yBandBot = pBox->y2;
- 	while (ch < h && y + ch < yBand)
- 	{
- 	    partOUT = TRUE;
- 	    clips[ch++] = 0;
- 	}
- 	if (ch >= h)
- 	    break;
-    	while (numRects && pBox->y1 == yBand && pBox->x2 <= x)
-    	{
-	    --numRects;
-	    ++pBox;
-    	}
-    	if (!numRects)
-	    break;
-	clip = 0;
-    	while (numRects && pBox->y1 == yBand && pBox->x1 < x + w)
-    	{
-	    if (x < pBox->x1)
-		if (pBox->x2 < x + w)
-		    clip |= cfb8BitLenMasks[pBox->x1 - x] & ~cfb8BitLenMasks[pBox->x2 - x];
-		else
-		    clip |= cfb8BitLenMasks[pBox->x1 - x];
- 	    else
-		if (pBox->x2 < x + w)
-		    clip |= ~cfb8BitLenMasks[pBox->x2 - x];
-		else
-		    clip = ~0;
-	    --numRects;
-	    ++pBox;
-    	}
-	if (clip != 0)
-		partIN = TRUE;
-	if (clip != ~0)
-		partOUT = TRUE;
-	while (ch < h && y + ch < yBandBot)
-	    clips[ch++] = clip;
-	while (numRects && pBox->y1 == yBand)
-	{
-	    --numRects;
-	    ++pBox;
-	}
-    }
-    while (ch < h)
-    {
-	partOUT = TRUE;
-	clips[ch++] = 0;
-    }
-    result = rgnOUT;
-    if (partIN)
-    {
-	if (partOUT)
-	    result = rgnPART;
-	else
-	    result = rgnIN;
-    }
-    return result;
-}
-
-#endif /* PSZ == 8 */
diff --git a/cfb/cfb8bit.h b/cfb/cfb8bit.h
deleted file mode 100644
index 5a17adf..0000000
--- a/cfb/cfb8bit.h
+++ /dev/null
@@ -1,1570 +0,0 @@
-/*
- * cfb8bit.h
- *
- * Defines which are only useful to 8 bit color frame buffers
- *
- * That doesn't seem to be true any more.  Some of the macros in here 
- * are used for depths other than 8.  Perhaps the file should be
- * renamed.  dpw
- */
-
-/*
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-*/
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "servermd.h"
-
-#if (BITMAP_BIT_ORDER == MSBFirst)
-#define GetBitGroup(x)		(((PixelGroup) (x)) >> (PGSZ - PGSZB))
-#define NextBitGroup(x)		((x) <<= PGSZB)
-#define NextSomeBits(x,n)	((x) <<= (n))
-#else
-#define GetBitGroup(x)		((x) & PGSZBMSK)
-#define NextBitGroup(x)		((x) >>= PGSZB)
-#define NextSomeBits(x,n)	((x) >>= (n))
-#endif
-
-#define RotBitsLeft(x,k)    ((x) = BitLeft (x,k) | \
-				   BitRight (x, PGSZ-(k)))
-
-#if defined(__GNUC__) && defined(mc68020)
-#undef RotBitsLeft
-#define RotBitsLeft(x,k)	asm("rol%.l %2,%0" \
-				: "=d" (x) \
- 				: "0" (x), "dI" (k))
-#endif
-
-#if PSZ == 8
-
-#define GetPixelGroup(x)		(cfb8StippleXor[GetBitGroup(x)])
-#define RRopPixels(dst,x)	(DoRRop(dst,cfb8StippleAnd[x], cfb8StippleXor[x]))
-#define RRopPixelGroup(dst,x)	(RRopPixels(dst,GetBitGroup(x)))
-#define MaskRRopPixels(dst,x,mask)  (DoMaskRRop(dst,cfb8StippleAnd[x], cfb8StippleXor[x], mask))
-
-#define NUM_MASKS	(1<<PPW) /* XXX goes in cfbmskbits.h? */
-extern int		cfb8StippleMode, cfb8StippleAlu;
-extern PixelGroup	cfb8StippleFg, cfb8StippleBg, cfb8StipplePm;
-extern PixelGroup	cfb8StippleMasks[NUM_MASKS];
-extern PixelGroup	cfb8StippleAnd[NUM_MASKS], cfb8StippleXor[NUM_MASKS];
-extern int		cfb8StippleRRop;
-
-#define cfb8PixelMasks	cfb8StippleMasks
-#define cfb8Pixels	cfb8StippleXor
-
-#define cfb8CheckPixels(fg, bg) \
-    (FillOpaqueStippled == cfb8StippleMode && \
-     GXcopy == cfb8StippleAlu && \
-     ((fg) & PMSK) == cfb8StippleFg && \
-     ((bg) & PMSK) == cfb8StippleBg && \
-     PMSK == cfb8StipplePm)
-
-#define cfb8CheckOpaqueStipple(alu,fg,bg,pm) \
-    ((FillOpaqueStippled == cfb8StippleMode && \
-      (alu) == cfb8StippleAlu && \
-      ((fg) & PMSK) == cfb8StippleFg && \
-      ((bg) & PMSK) == cfb8StippleBg && \
-      ((pm) & PMSK) == cfb8StipplePm) ? 0 : cfb8SetOpaqueStipple(alu,fg,bg,pm))
-
-#define cfb8CheckStipple(alu,fg,pm) \
-    ((FillStippled == cfb8StippleMode && \
-      (alu) == cfb8StippleAlu && \
-      ((fg) & PMSK) == cfb8StippleFg && \
-      ((pm) & PMSK) == cfb8StipplePm) ? 0 : cfb8SetStipple(alu,fg,pm))
-
-#define cfb8SetPixels(fg,bg) cfb8SetOpaqueStipple(GXcopy,fg,bg,PMSK)
-
-/*
- * These macros are shared between the unnatural spans code
- * and the unnatural rectangle code.  No reasonable person
- * would attempt to use them anyplace else.
- */
-
-#define NextUnnaturalStippleWord \
-	if (bitsLeft >= MFB_PPW) \
-	{ \
-	    inputBits = *srcTemp++; \
-	    bitsLeft -= MFB_PPW; \
-	    partBitsLeft = MFB_PPW; \
-	} \
-	else \
-	{ \
-	    inputBits = 0; \
-	    if (bitsLeft) \
-		inputBits = *srcTemp & ~cfb8BitLenMasks[bitsLeft]; \
-	    srcTemp = srcStart; \
-	    partBitsLeft = bitsLeft; \
-	    bitsLeft = bitsWhole; \
-	}
-
-#define NextUnnaturalStippleBits \
-    if (partBitsLeft >= PPW) { \
-	bits = GetBitGroup (inputBits); \
-	NextBitGroup (inputBits); \
-	partBitsLeft -= PPW; \
-    } else { \
-	bits = GetBitGroup (inputBits); \
-	nextPartBits = PPW - partBitsLeft; \
-	NextUnnaturalStippleWord \
-	if (partBitsLeft < nextPartBits) { \
-	    if (partBitsLeft) {\
-	    	bits |= BitRight (GetBitGroup (inputBits), \
-				  PPW - nextPartBits) & PPWMSK;\
-	    	nextPartBits -= partBitsLeft; \
-	    } \
-	    NextUnnaturalStippleWord \
-	} \
-	bits |= BitRight (GetBitGroup (inputBits), \
-			  PPW - nextPartBits) & PPWMSK; \
-	NextSomeBits (inputBits, nextPartBits); \
-	partBitsLeft -= nextPartBits; \
-    }
-
-#define NextUnnaturalStippleBitsFast \
-    if (partBitsLeft >= PPW) { \
-	bits = GetBitGroup(inputBits); \
-	NextBitGroup(inputBits); \
-	partBitsLeft -= PPW; \
-    } else { \
-	bits = GetBitGroup (inputBits); \
-	nextPartBits = PPW - partBitsLeft; \
-	inputBits = *srcTemp++; \
-	bits |= BitRight (GetBitGroup (inputBits), \
-		          partBitsLeft) & PPWMSK; \
-	NextSomeBits (inputBits, nextPartBits); \
-	partBitsLeft =  MFB_PPW - nextPartBits; \
-    }
-
-/*
- * WriteBitGroup takes the destination address, a pixel
- * value (which must be 8 bits duplicated 4 time with PFILL)
- * and the PPW bits to write, which must be in the low order
- * bits of the register (probably from GetBitGroup) and writes
- * the appropriate locations in memory with the pixel value.  This
- * is a copy-mode only operation.
- */
-
-#define RRopBitGroup(dst,bits)					\
-    {								\
-    *(dst) = RRopPixels(*(dst),bits);				\
-    }
-
-#define MaskRRopBitGroup(dst,bits,mask)				\
-    {								\
-    *(dst) = MaskRRopPixels(*(dst),bits,mask);			\
-    }
-#endif /* PSZ == 8 */
-
-#if !defined(AVOID_MEMORY_READ) && PSZ == 8
-
-#define WriteBitGroup(dst,pixel,bits)				\
-    {								\
-    register PixelGroup _maskTmp = cfb8PixelMasks[(bits)];   \
-    *(dst) = (*(dst) & ~_maskTmp) | ((pixel) & _maskTmp);	\
-    }
-
-#define SwitchBitGroup(dst,pixel,bits)				\
-    {								\
-    register PixelGroup _maskTmp = cfb8PixelMasks[(bits)];   \
-    register PixelGroup _pixTmp = ((pixel) & _maskTmp);	\
-    _maskTmp = ~_maskTmp;					\
-    SwitchBitsLoop (*(dst) = (*(dst) & _maskTmp) | _pixTmp;)	\
-    }
-    
-#else /* AVOID_MEMORY_READ */
-
-#if PGSZ == 32
-#if (BITMAP_BIT_ORDER == MSBFirst)
-#define SinglePixel0	3
-#define SinglePixel1	2
-#define SinglePixel2	1
-#define SinglePixel3	0
-#define SinglePixel4	7
-#define SinglePixel5	6
-#define SinglePixel6	5
-#define SinglePixel7	4
-#define SinglePixel8	0xB
-#define SinglePixel9	0xA
-#define DoublePixel0	1
-#define DoublePixel1	0
-#define DoublePixel2	3
-#define DoublePixel3	2
-#define DoublePixel4	5
-#define DoublePixel5	4
-#else
-#define SinglePixel0	0
-#define SinglePixel1	1
-#define SinglePixel2	2
-#define SinglePixel3	3
-#define SinglePixel4	4
-#define SinglePixel5	5
-#define SinglePixel6	6
-#define SinglePixel7	7
-#define SinglePixel8	8
-#define SinglePixel9	9
-#define DoublePixel0	0
-#define DoublePixel1	1
-#define DoublePixel2	2
-#define DoublePixel3	3
-#define DoublePixel4	4
-#define DoublePixel5	5
-#endif
-#define QuadPixel0	0
-#define QuadPixel1	1
-#define QuadPixel2	2
-#else /* PGSZ == 64 */
-#if (BITMAP_BIT_ORDER == MSBFirst)
-#define SinglePixel0	7
-#define SinglePixel1	6
-#define SinglePixel2	5
-#define SinglePixel3	4
-#define SinglePixel4	3
-#define SinglePixel5	2
-#define SinglePixel6	1
-#define SinglePixel7	0
-#define DoublePixel0	3
-#define DoublePixel1	2
-#define DoublePixel2	1
-#define DoublePixel3	0
-#define QuadPixel0	1
-#define QuadPixel1	0
-#else
-#define SinglePixel0	0
-#define SinglePixel1	1
-#define SinglePixel2	2
-#define SinglePixel3	3
-#define SinglePixel4	4
-#define SinglePixel5	5
-#define SinglePixel6	6
-#define SinglePixel7	7
-#define DoublePixel0	0
-#define DoublePixel1	1
-#define DoublePixel2	2
-#define DoublePixel3	3
-#define QuadPixel0	0
-#define QuadPixel1	1
-#endif
-#define OctaPixel0	0
-#endif /* PGSZ == 64 */
-
-#if PSZ == 8
-
-#if PGSZ == 32
-#define WriteBitGroup(dst,pixel,bits) \
-	switch (bits) {			\
-	case 0:				\
-	    break;			\
-	case 1:				\
-	    ((CARD8 *) (dst))[SinglePixel0] = (pixel);	\
-	    break;			\
-	case 2:				\
-	    ((CARD8 *) (dst))[SinglePixel1] = (pixel);	\
-	    break;			\
-	case 3:				\
-	    ((CARD16 *) (dst))[DoublePixel0] = (pixel);	\
-	    break;			\
-	case 4:				\
-	    ((CARD8 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 5:				\
-	    ((CARD8 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD8 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 6:				\
-	    ((CARD8 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD8 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 7:				\
-	    ((CARD16 *) (dst))[DoublePixel0] = (pixel);	\
-	    ((CARD8 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 8:				\
-	    ((CARD8 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 9:				\
-	    ((CARD8 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD8 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 10:			\
-	    ((CARD8 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD8 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 11:			\
-	    ((CARD16 *) (dst))[DoublePixel0] = (pixel);	\
-	    ((CARD8 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 12:			\
-	    ((CARD16 *) (dst))[DoublePixel1] = (pixel);	\
-	    break;			\
-	case 13:			\
-	    ((CARD8 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD16 *) (dst))[DoublePixel1] = (pixel);	\
-	    break;			\
-	case 14:			\
-	    ((CARD8 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD16 *) (dst))[DoublePixel1] = (pixel);	\
-	    break;			\
-	case 15:			\
-	    ((CARD32 *) (dst))[0] = (pixel);	\
-	    break;			\
-	}
-#else /* PGSZ == 64 */
-#define WriteBitGroup(dst,pixel,bits) 				\
-    if ( bits == 0xff )						\
-	((PixelGroup *) (dst))[OctaPixel0] = (pixel);		\
-    else {							\
-	switch (bits & 0x0f) {					\
-	    case 0:						\
-	        break;						\
-	    case 1:						\
-	        ((CARD8 *) (dst))[SinglePixel0] = (pixel);	\
-	        break;						\
-	    case 2:						\
-	        ((CARD8 *) (dst))[SinglePixel1] = (pixel);	\
-	        break;						\
-	    case 3:						\
-	        ((CARD16 *) (dst))[DoublePixel0] = (pixel);	\
-	        break;						\
-	    case 4:						\
-	        ((CARD8 *) (dst))[SinglePixel2] = (pixel);	\
-	        break;						\
-	    case 5:						\
-	        ((CARD8 *) (dst))[SinglePixel0] = (pixel);	\
-	        ((CARD8 *) (dst))[SinglePixel2] = (pixel);	\
-	        break;						\
-	    case 6:						\
-	        ((CARD8 *) (dst))[SinglePixel1] = (pixel);	\
-	        ((CARD8 *) (dst))[SinglePixel2] = (pixel);	\
-	        break;						\
-	    case 7:						\
-	        ((CARD16 *) (dst))[DoublePixel0] = (pixel);	\
-	        ((CARD8 *) (dst))[SinglePixel2] = (pixel);	\
-	        break;						\
-	    case 8:						\
-	        ((CARD8 *) (dst))[SinglePixel3] = (pixel);	\
-	        break;						\
-	    case 9:						\
-	        ((CARD8 *) (dst))[SinglePixel0] = (pixel);	\
-	        ((CARD8 *) (dst))[SinglePixel3] = (pixel);	\
-	        break;						\
-	    case 10:						\
-	        ((CARD8 *) (dst))[SinglePixel1] = (pixel);	\
-	        ((CARD8 *) (dst))[SinglePixel3] = (pixel);	\
-	        break;						\
-	    case 11:						\
-	        ((CARD16 *) (dst))[DoublePixel0] = (pixel);	\
-	        ((CARD8 *) (dst))[SinglePixel3] = (pixel);	\
-	        break;						\
-	    case 12:						\
-	        ((CARD16 *) (dst))[DoublePixel1] = (pixel);	\
-	        break;						\
-	    case 13:						\
-	        ((CARD8 *) (dst))[SinglePixel0] = (pixel);	\
-	        ((CARD16 *) (dst))[DoublePixel1] = (pixel);	\
-	        break;						\
-	    case 14:						\
-	        ((CARD8 *) (dst))[SinglePixel1] = (pixel);	\
-	        ((CARD16 *) (dst))[DoublePixel1] = (pixel);	\
-	        break;						\
-	    case 15:						\
-	        ((CARD32 *) (dst))[QuadPixel0] = (pixel);	\
-	        break;						\
-	}							\
-	switch ((bits & 0xf0) >> 4) {				\
-	    case 0:						\
-	        break;						\
-	    case 1:						\
-	        ((CARD8 *) (dst))[SinglePixel4] = (pixel);	\
-	        break;						\
-	    case 2:						\
-	        ((CARD8 *) (dst))[SinglePixel5] = (pixel);	\
-	        break;						\
-	    case 3:						\
-	        ((CARD16 *) (dst))[DoublePixel2] = (pixel);	\
-	        break;						\
-	    case 4:						\
-	        ((CARD8 *) (dst))[SinglePixel6] = (pixel);	\
-	        break;						\
-	    case 5:						\
-	        ((CARD8 *) (dst))[SinglePixel4] = (pixel);	\
-	        ((CARD8 *) (dst))[SinglePixel6] = (pixel);	\
-	        break;						\
-	    case 6:						\
-	        ((CARD8 *) (dst))[SinglePixel5] = (pixel);	\
-	        ((CARD8 *) (dst))[SinglePixel6] = (pixel);	\
-	        break;						\
-	    case 7:						\
-	        ((CARD16 *) (dst))[DoublePixel2] = (pixel);	\
-	        ((CARD8 *) (dst))[SinglePixel6] = (pixel);	\
-	        break;						\
-	    case 8:						\
-	        ((CARD8 *) (dst))[SinglePixel7] = (pixel);	\
-	        break;						\
-	    case 9:						\
-	        ((CARD8 *) (dst))[SinglePixel4] = (pixel);	\
-	        ((CARD8 *) (dst))[SinglePixel7] = (pixel);	\
-	        break;						\
-	    case 10:						\
-	        ((CARD8 *) (dst))[SinglePixel5] = (pixel);	\
-	        ((CARD8 *) (dst))[SinglePixel7] = (pixel);	\
-	        break;						\
-	    case 11:						\
-	        ((CARD16 *) (dst))[DoublePixel2] = (pixel);	\
-	        ((CARD8 *) (dst))[SinglePixel7] = (pixel);	\
-	        break;						\
-	    case 12:						\
-	        ((CARD16 *) (dst))[DoublePixel3] = (pixel);	\
-	        break;						\
-	    case 13:						\
-	        ((CARD8 *) (dst))[SinglePixel4] = (pixel);	\
-	        ((CARD16 *) (dst))[DoublePixel3] = (pixel);	\
-	        break;						\
-	    case 14:						\
-	        ((CARD8 *) (dst))[SinglePixel5] = (pixel);	\
-	        ((CARD16 *) (dst))[DoublePixel3] = (pixel);	\
-	        break;						\
-	    case 15:						\
-	        ((CARD32 *) (dst))[QuadPixel1] = (pixel);	\
-	        break;						\
-	}							\
-    }
-#endif /* PGSZ == 64 */
-
-#if PGSZ == 32
-#define SwitchBitGroup(dst,pixel,bits) { \
-	switch (bits) { \
-	case 0: \
-       	    break; \
-	case 1: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel0] = (pixel);) \
-	    break; \
-	case 2: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel1] = (pixel);) \
-	    break; \
-	case 3: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel0] = (pixel);) \
-	    break; \
-	case 4: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 5: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel0] = (pixel); \
-		     ((CARD8 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 6: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel1] = (pixel); \
-		     ((CARD8 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 7: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel0] = (pixel); \
-		     ((CARD8 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 8: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 9: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel0] = (pixel); \
-		     ((CARD8 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 10: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel1] = (pixel); \
-		     ((CARD8 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 11: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel0] = (pixel); \
-		     ((CARD8 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 12: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel1] = (pixel);) \
-	    break; \
-	case 13: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel0] = (pixel); \
-		     ((CARD16 *) (dst))[DoublePixel1] = (pixel);) \
-	    break; \
-	case 14: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel1] = (pixel); \
-		     ((CARD16 *) (dst))[DoublePixel1] = (pixel);) \
-	    break; \
-	case 15: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[0] = (pixel);) \
-	    break; \
-	} \
-}
-#else /* PGSZ == 64 */
-#define SwitchBitGroup(dst,pixel,bits) { 				   \
-    if ( bits == 0xff )							   \
-	SwitchBitsLoop (((PixelGroup *) (dst))[OctaPixel0] = (pixel);)	   \
-    else {								   \
-	switch (bits & 0x0f) {	 					   \
-	    case 0: 							   \
-       	        break; 							   \
-	    case 1: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel0] = (pixel);) \
-	        break; 							   \
-	    case 2: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel1] = (pixel);) \
-	        break; 							   \
-	    case 3: 							   \
-	        SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel0] = (pixel);)\
-	        break; 							   \
-	    case 4: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel2] = (pixel);) \
-	        break; 							   \
-	    case 5: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel0] = (pixel);  \
-		         	((CARD8 *) (dst))[SinglePixel2] = (pixel);) \
-	        break; 							   \
-	    case 6: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel1] = (pixel);  \
-		         	((CARD8 *) (dst))[SinglePixel2] = (pixel);) \
-	        break; 							   \
-	    case 7: 							   \
-	        SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel0] = (pixel); \
-		         	((CARD8 *) (dst))[SinglePixel2] = (pixel);) \
-	        break; 							   \
-	    case 8: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel3] = (pixel);) \
-	        break; 							   \
-	    case 9: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel0] = (pixel);  \
-		         	((CARD8 *) (dst))[SinglePixel3] = (pixel);) \
-	        break; 							   \
-	    case 10: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel1] = (pixel);  \
-		         	((CARD8 *) (dst))[SinglePixel3] = (pixel);) \
-	        break; 							   \
-	    case 11: 							   \
-	        SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel0] = (pixel); \
-		         	((CARD8 *) (dst))[SinglePixel3] = (pixel);) \
-	        break; 							   \
-	    case 12: 							   \
-	        SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel1] = (pixel);)\
-	        break; 							   \
-	    case 13: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel0] = (pixel);  \
-		         	((CARD16 *) (dst))[DoublePixel1] = (pixel);)\
-	        break; 							   \
-	    case 14: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel1] = (pixel);  \
-		         	((CARD16 *) (dst))[DoublePixel1] = (pixel);)\
-	        break; 							   \
-	    case 15: 							   \
-	        SwitchBitsLoop (((CARD32 *) (dst))[QuadPixel0] = (pixel);)    \
-	        break; 							   \
-	}								   \
-	switch ((bits & 0xf0) >> 4) {					   \
-	    case 0: 							   \
-       	        break; 							   \
-	    case 1: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel4] = (pixel);) \
-	        break; 							   \
-	    case 2: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel5] = (pixel);) \
-	        break; 							   \
-	    case 3: 							   \
-	        SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel2] = (pixel);)\
-	        break; 							   \
-	    case 4: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel6] = (pixel);) \
-	        break; 							   \
-	    case 5: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel4] = (pixel);  \
-		         	((CARD8 *) (dst))[SinglePixel6] = (pixel);) \
-	        break; 							   \
-	    case 6: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel5] = (pixel);  \
-		         	((CARD8 *) (dst))[SinglePixel6] = (pixel);) \
-	        break; 							   \
-	    case 7: 							   \
-	        SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel2] = (pixel); \
-		         	((CARD8 *) (dst))[SinglePixel6] = (pixel);) \
-	        break; 							   \
-	    case 8: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel7] = (pixel);) \
-	        break; 							   \
-	    case 9: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel4] = (pixel);  \
-		         	((CARD8 *) (dst))[SinglePixel7] = (pixel);) \
-	        break; 							   \
-	    case 10: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel5] = (pixel);  \
-		         	((CARD8 *) (dst))[SinglePixel7] = (pixel);) \
-	        break; 							   \
-	    case 11: 							   \
-	        SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel2] = (pixel); \
-		         	((CARD8 *) (dst))[SinglePixel7] = (pixel);) \
-	        break; 							   \
-	    case 12: 							   \
-	        SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel3] = (pixel);)\
-	        break; 							   \
-	    case 13: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel4] = (pixel);  \
-		         	((CARD16 *) (dst))[DoublePixel3] = (pixel);)\
-	        break; 							   \
-	    case 14: 							   \
-	        SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel5] = (pixel);  \
-		         	((CARD16 *) (dst))[DoublePixel3] = (pixel);)\
-	        break; 							   \
-	    case 15: 							   \
-	        SwitchBitsLoop (((CARD32 *) (dst))[QuadPixel1] = (pixel);) \
-	        break; 							   \
-	} 								   \
-    }									   \
-}
-#endif /* PGSZ == 64 */
-#endif /* PSZ == 8 */
-
-#if PSZ == 16
-
-#if PGSZ == 32
-#define WriteBitGroup(dst,pixel,bits) \
-	switch (bits) {			\
-	case 0:				\
-	    break;			\
-	case 1:				\
-	    ((CARD16 *) (dst))[SinglePixel0] = (pixel);	\
-	    break;			\
-	case 2:				\
-	    ((CARD16 *) (dst))[SinglePixel1] = (pixel);	\
-	    break;			\
-	case 3:				\
-	    ((CARD32 *) (dst))[DoublePixel0] = (pixel);	\
-	    break;			\
-	case 4:				\
-	    ((CARD16 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 5:				\
-	    ((CARD16 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 6:				\
-	    ((CARD16 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 7:				\
-	    ((CARD32 *) (dst))[DoublePixel0] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 8:				\
-	    ((CARD16 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 9:				\
-	    ((CARD16 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 10:			\
-	    ((CARD16 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 11:			\
-	    ((CARD32 *) (dst))[DoublePixel0] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 12:			\
-	    ((CARD32 *) (dst))[DoublePixel1] = (pixel);	\
-	    break;			\
-	case 13:			\
-	    ((CARD16 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[DoublePixel1] = (pixel);	\
-	    break;			\
-	case 14:			\
-	    ((CARD16 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[DoublePixel1] = (pixel);	\
-	    break;			\
-	case 15:			\
-	    ((CARD32 *) (dst))[DoublePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[DoublePixel1] = (pixel);	\
-	    break;			\
-	}
-#else /* PGSZ == 64 */
-#define WriteBitGroup(dst,pixel,bits) \
-    if ( bits == 0xff )	{						\
-	((PixelGroup *) (dst))[QuadPixel0] = (pixel);			\
-	((PixelGroup *) (dst))[QuadPixel1] = (pixel);			\
-    }									\
-    else {								\
-	switch (bits & 0x0f) {	 					\
-	case 0:				\
-	    break;			\
-	case 1:				\
-	    ((CARD16 *) (dst))[SinglePixel0] = (pixel);	\
-	    break;			\
-	case 2:				\
-	    ((CARD16 *) (dst))[SinglePixel1] = (pixel);	\
-	    break;			\
-	case 3:				\
-	    ((CARD32 *) (dst))[DoublePixel0] = (pixel);	\
-	    break;			\
-	case 4:				\
-	    ((CARD16 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 5:				\
-	    ((CARD16 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 6:				\
-	    ((CARD16 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 7:				\
-	    ((CARD32 *) (dst))[DoublePixel0] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 8:				\
-	    ((CARD16 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 9:				\
-	    ((CARD16 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 10:			\
-	    ((CARD16 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 11:			\
-	    ((CARD32 *) (dst))[DoublePixel0] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 12:			\
-	    ((CARD32 *) (dst))[DoublePixel1] = (pixel);	\
-	    break;			\
-	case 13:			\
-	    ((CARD16 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[DoublePixel1] = (pixel);	\
-	    break;			\
-	case 14:			\
-	    ((CARD16 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[DoublePixel1] = (pixel);	\
-	    break;			\
-	case 15:			\
-	    ((CARD32 *) (dst))[DoublePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[DoublePixel1] = (pixel);	\
-	    break;			\
-	}				\
-	switch ((bits & 0xf0) >> 4) {			\
-	case 0:				\
-	    break;			\
-	case 1:				\
-	    ((CARD16 *) (dst))[SinglePixel4] = (pixel);	\
-	    break;			\
-	case 2:				\
-	    ((CARD16 *) (dst))[SinglePixel5] = (pixel);	\
-	    break;			\
-	case 3:				\
-	    ((CARD32 *) (dst))[DoublePixel2] = (pixel);	\
-	    break;			\
-	case 4:				\
-	    ((CARD16 *) (dst))[SinglePixel6] = (pixel);	\
-	    break;			\
-	case 5:				\
-	    ((CARD16 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel6] = (pixel);	\
-	    break;			\
-	case 6:				\
-	    ((CARD16 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel6] = (pixel);	\
-	    break;			\
-	case 7:				\
-	    ((CARD32 *) (dst))[DoublePixel2] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel6] = (pixel);	\
-	    break;			\
-	case 8:				\
-	    ((CARD16 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 9:				\
-	    ((CARD16 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 10:			\
-	    ((CARD16 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 11:			\
-	    ((CARD32 *) (dst))[DoublePixel2] = (pixel);	\
-	    ((CARD16 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 12:			\
-	    ((CARD32 *) (dst))[DoublePixel3] = (pixel);	\
-	    break;			\
-	case 13:			\
-	    ((CARD16 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[DoublePixel3] = (pixel);	\
-	    break;			\
-	case 14:			\
-	    ((CARD16 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[DoublePixel3] = (pixel);	\
-	    break;			\
-	case 15:			\
-	    ((CARD32 *) (dst))[DoublePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[DoublePixel3] = (pixel);	\
-	    break;			\
-	}				\
-    }
-#endif /* PGSZ */
-
-#if PGSZ == 32
-#define SwitchBitGroup(dst,pixel,bits) { \
-	switch (bits) { \
-	case 0: \
-       	    break; \
-	case 1: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[SinglePixel0] = (pixel);) \
-	    break; \
-	case 2: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[SinglePixel1] = (pixel);) \
-	    break; \
-	case 3: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[DoublePixel0] = (pixel);) \
-	    break; \
-	case 4: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 5: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[SinglePixel0] = (pixel); \
-		     ((CARD16 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 6: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[SinglePixel1] = (pixel); \
-		     ((CARD16 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 7: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[DoublePixel0] = (pixel); \
-		     ((CARD16 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 8: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 9: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[SinglePixel0] = (pixel); \
-		     ((CARD16 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 10: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[SinglePixel1] = (pixel); \
-		     ((CARD16 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 11: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[DoublePixel0] = (pixel); \
-		     ((CARD16 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 12: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[DoublePixel1] = (pixel);) \
-	    break; \
-	case 13: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[SinglePixel0] = (pixel); \
-		     ((CARD32 *) (dst))[DoublePixel1] = (pixel);) \
-	    break; \
-	case 14: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[SinglePixel1] = (pixel); \
-		     ((CARD32 *) (dst))[DoublePixel1] = (pixel);) \
-	    break; \
-	case 15: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[DoublePixel0] = (pixel); \
-			    ((CARD32 *) (dst))[DoublePixel1] = (pixel);) \
-	    break; \
-	} \
-}
-#else /* PGSZ == 64 */
-#define SwitchBitGroup(dst,pixel,bits) { \
-	cfb cannot hack 64-bit SwitchBitGroup psz=PSZ
-#endif /* PGSZ */
-
-#endif /* PSZ == 16 */
-
-#if PSZ == 24
-/* 32 000011112222*/
-/* 24 000111222333*/
-/* 16 001122334455*/
-/*  8 0123456789AB*/
-#if PGSZ == 32
-#define WriteBitGroup(dst,pixel,bits) \
-	{ \
-	register CARD32 reg_pixel = (pixel); \
-	switch (bits) {			\
-	case 0:				\
-	    break;			\
-	case 1:				\
-	    ((CARD16 *) (dst))[DoublePixel0] = reg_pixel;	\
-	    ((CARD8 *) (dst))[SinglePixel2] = ((reg_pixel>>16)&0xFF);	\
-	    break;			\
-	case 2:				\
-	    ((CARD8 *) (dst))[SinglePixel3] = reg_pixel&0xFF;	\
-	    ((CARD16 *) (dst))[DoublePixel2] = (reg_pixel>>8)&0xFFFF;	\
-	    break;			\
-	case 3:				\
-	    ((CARD8 *) (dst))[SinglePixel3] = reg_pixel & 0xFF;	\
-	    ((CARD16 *) (dst))[DoublePixel0] = reg_pixel;	\
-	    ((CARD16 *) (dst))[DoublePixel2] = (reg_pixel>>8)&0xFFFF;	\
-	    ((CARD8 *) (dst))[SinglePixel2] = (reg_pixel>>16&0xFF);	\
-	    break;			\
-	case 4:				\
-	    ((CARD16 *) (dst))[DoublePixel3] = reg_pixel;	\
-	    ((CARD8 *) (dst))[SinglePixel8] = (reg_pixel>>16)&0xFF; \
-	    break;			\
-	case 5:				\
-	    ((CARD16 *) (dst))[DoublePixel0] = \
-	    ((CARD16 *) (dst))[DoublePixel3] = reg_pixel;	\
-	    reg_pixel >>= 16;	\
-	    ((CARD8 *) (dst))[SinglePixel2] = \
-	    ((CARD8 *) (dst))[SinglePixel8] = reg_pixel&0xFF; \
-	    break;			\
-	case 6:				\
-	    ((CARD8 *) (dst))[SinglePixel3] = reg_pixel;	\
-	    ((CARD16 *) (dst))[DoublePixel3] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD16 *) (dst))[DoublePixel2] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD8 *) (dst))[SinglePixel8] = reg_pixel&0xFF; \
-	    break;			\
-	case 7:				\
-	    ((CARD16 *) (dst))[DoublePixel0] = \
-	    ((CARD16 *) (dst))[DoublePixel3] = reg_pixel;	\
-	    ((CARD8 *) (dst))[SinglePixel3] = reg_pixel&0xFF;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD16 *) (dst))[DoublePixel2] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD8 *) (dst))[SinglePixel2] = \
-	    ((CARD8 *) (dst))[SinglePixel8] = reg_pixel&0xFF; \
-	    break;			\
-	case 8:				\
-	    ((CARD8 *) (dst))[SinglePixel9] = reg_pixel&0xFF;	\
-	    ((CARD16 *) (dst))[DoublePixel5] = (reg_pixel>>8);	\
-	    break;			\
-	case 9:				\
-	    ((CARD16 *) (dst))[DoublePixel0] = reg_pixel;	\
-	    ((CARD8 *) (dst))[SinglePixel9] = reg_pixel&0xFF;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD16 *) (dst))[DoublePixel5] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD8 *) (dst))[SinglePixel2] = reg_pixel&0xFF;	\
-	    break;			\
-	case 10:			\
-	    ((CARD8 *) (dst))[SinglePixel3] = \
-	    ((CARD8 *) (dst))[SinglePixel9] = reg_pixel&0xFF;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD16 *) (dst))[DoublePixel2] = \
-	    ((CARD16 *) (dst))[DoublePixel5] = reg_pixel;	\
-	    break;			\
-	case 11:			\
-	    ((CARD8 *) (dst))[SinglePixel3] = \
-	    ((CARD8 *) (dst))[SinglePixel9] = reg_pixel;	\
-	    ((CARD16 *) (dst))[DoublePixel0] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD16 *) (dst))[DoublePixel2] = \
-	    ((CARD16 *) (dst))[DoublePixel5] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD8 *) (dst))[SinglePixel2] = reg_pixel;	\
-	    break;			\
-	case 12:			\
-	    ((CARD16 *) (dst))[DoublePixel3] = reg_pixel;	\
-	    ((CARD8 *) (dst))[SinglePixel9] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD16 *) (dst))[DoublePixel5] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD8 *) (dst))[SinglePixel8] = reg_pixel; \
-	    break;			\
-	case 13:			\
-	    ((CARD16 *) (dst))[DoublePixel0] = \
-	    ((CARD16 *) (dst))[DoublePixel3] = reg_pixel;	\
-	    ((CARD8 *) (dst))[SinglePixel9] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD16 *) (dst))[DoublePixel5] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD8 *) (dst))[SinglePixel2] = \
-	    ((CARD8 *) (dst))[SinglePixel8] = reg_pixel; \
-	    break;			\
-	case 14:			\
-	    ((CARD8 *) (dst))[SinglePixel3] = \
-	    ((CARD8 *) (dst))[SinglePixel9] = reg_pixel;	\
-	    ((CARD16 *) (dst))[DoublePixel3] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD16 *) (dst))[DoublePixel2] = \
-	    ((CARD16 *) (dst))[DoublePixel5] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD8 *) (dst))[SinglePixel8] = reg_pixel; \
-	    break;			\
-	case 15:			\
-	    ((CARD16 *) (dst))[DoublePixel0] = \
-	    ((CARD16 *) (dst))[DoublePixel3] = reg_pixel;	\
-	    ((CARD8 *) (dst))[SinglePixel3] = \
-	    ((CARD8 *) (dst))[SinglePixel9] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD16 *) (dst))[DoublePixel2] = \
-	    ((CARD16 *) (dst))[DoublePixel5] = reg_pixel;	\
-	    reg_pixel >>= 8;	\
-	    ((CARD8 *) (dst))[SinglePixel8] = \
-	    ((CARD8 *) (dst))[SinglePixel2] = reg_pixel;	\
-	    break;			\
-	} \
-      }
-#else /* PGSZ == 64 */
-#define WriteBitGroup(dst,pixel,bits) \
-    if ( bits == 0xff )	 {				   \
-	((PixelGroup *) (dst))[DoublePixel0] = (pixel);	   \
-	((PixelGroup *) (dst))[DoublePixel1] = (pixel);	   \
-	((PixelGroup *) (dst))[DoublePixel2] = (pixel);	   \
-	((PixelGroup *) (dst))[DoublePixel3] = (pixel);	   \
-    }							   \
-    else {						   \
-	switch (bits & 0x0f) {	 			   \
-	case 0:				\
-	    break;			\
-	case 1:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    break;			\
-	case 2:				\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    break;			\
-	case 3:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    break;			\
-	case 4:				\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 5:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 6:				\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 7:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 8:				\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 9:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 10:			\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 11:			\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 12:			\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 13:			\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 14:			\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 15:			\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	}				\
-	switch ((bits & 0xf0) >> 4) {	\
-	case 0:				\
-	    break;			\
-	case 1:				\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    break;			\
-	case 2:				\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    break;			\
-	case 3:				\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    break;			\
-	case 4:				\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    break;			\
-	case 5:				\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    break;			\
-	case 6:				\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    break;			\
-	case 7:				\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    break;			\
-	case 8:				\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 9:				\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 10:			\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 11:			\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 12:			\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 13:			\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 14:			\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 15:			\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	}				\
-    }
-#endif /* PGSZ */
-
-#if PGSZ == 32
-#define SwitchBitGroup(dst,pixel,bits) { \
-	switch (bits) { \
-	case 0: \
-       	    break; \
-	case 1: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel0] = (pixel); \
-			    ((CARD8 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 2: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel3] = (pixel); \
-			    ((CARD16 *) (dst))[DoublePixel2] = (pixel);) \
-	    break; \
-	case 3: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[QuadPixel0] = (pixel); \
-			    ((CARD16 *) (dst))[DoublePixel2] = (pixel);) \
-	    break; \
-	case 4: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel3] = (pixel); \
-			    ((CARD8 *) (dst))[SinglePixel8] = (pixel);) \
-	    break; \
-	case 5: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel0] = (pixel); \
-			    ((CARD8 *) (dst))[SinglePixel2] = (pixel); \
-			    ((CARD16 *) (dst))[DoublePixel3] = (pixel); \
-			    ((CARD8 *) (dst))[SinglePixel8] = (pixel);) \
-	    break; \
-	case 6: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel3] = (pixel); \
-			    ((CARD32 *) (dst))[QuadPixel2] = (pixel); \
-			    ((CARD8 *) (dst))[SinglePixel8] = (pixel);) \
-	    break; \
-	case 7: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[QuadPixel0] = (pixel); \
-			    ((CARD32 *) (dst))[QuadPixel1] = (pixel); \
-			    ((CARD8 *) (dst))[SinglePixel8] = (pixel);) \
-	    break; \
-	case 8: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel9] = (pixel); \
-			    ((CARD16 *) (dst))[DoublePixel5] = (pixel);) \
-	    break; \
-	case 9: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel0] = (pixel); \
-			    ((CARD8 *) (dst))[SinglePixel2] = (pixel); \
-			    ((CARD8 *) (dst))[SinglePixel9] = (pixel); \
-			    ((CARD16 *) (dst))[DoublePixel5] = (pixel);) \
-	    break; \
-	case 10: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel3] = (pixel); \
-			    ((CARD16 *) (dst))[DoublePixel2] = (pixel); \
-			    ((CARD8 *) (dst))[SinglePixel9] = (pixel); \
-			    ((CARD16 *) (dst))[DoublePixel5] = (pixel);) \
-	    break; \
-	case 11: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[QuadPixel0] = (pixel); \
-			    ((CARD16 *) (dst))[DoublePixel3] = (pixel);) \
-			    ((CARD8 *) (dst))[SinglePixel9] = (pixel); \
-			    ((CARD16 *) (dst))[DoublePixel5] = (pixel);) \
-	    break; \
-	case 12: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[DoublePixel3] = (pixel); \
-			    ((CARD32 *) (dst))[QuadPixel2] = (pixel);) \
-	    break; \
-	case 13: \
-	    SwitchBitsLoop (((CARD16 *) (dst))[SinglePixel0] = (pixel); \
-			    ((CARD8 *) (dst))[SinglePixel2] = (pixel); \
-			    ((CARD16 *) (dst))[DoublePixel3] = (pixel); \
-			    ((CARD32 *) (dst))[QuadPixel2] = (pixel);) \
-	    break; \
-	case 14: \
-	    SwitchBitsLoop (((CARD8 *) (dst))[SinglePixel3] = (pixel); \
-			    ((CARD32 *) (dst))[QuadPixel1] = (pixel); \
-			    ((CARD32 *) (dst))[QuadPixel2] = (pixel);) \
-	    break; \
-	case 15: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[QuadPixel0] = (pixel); \
-			    ((CARD32 *) (dst))[QuadPixel1] = (pixel); \
-			    ((CARD32 *) (dst))[QuadPixel2] = (pixel);) \
-	    break; \
-	} \
-}
-#else /* PGSZ == 64 */
-#define SwitchBitGroup(dst,pixel,bits) { \
-	cfb cannot hack 64-bit SwitchBitGroup psz=PSZ
-#endif /* PGSZ */
-
-#endif /* PSZ == 24 */
-
-#if PSZ == 32
-
-#if PGSZ == 32
-#define WriteBitGroup(dst,pixel,bits) \
-	switch (bits) {			\
-	case 0:				\
-	    break;			\
-	case 1:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    break;			\
-	case 2:				\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    break;			\
-	case 3:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    break;			\
-	case 4:				\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 5:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 6:				\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 7:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 8:				\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 9:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 10:			\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 11:			\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 12:			\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 13:			\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 14:			\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 15:			\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	}
-#else /* PGSZ == 64 */
-#define WriteBitGroup(dst,pixel,bits) \
-    if ( bits == 0xff )	 {				   \
-	((PixelGroup *) (dst))[DoublePixel0] = (pixel);	   \
-	((PixelGroup *) (dst))[DoublePixel1] = (pixel);	   \
-	((PixelGroup *) (dst))[DoublePixel2] = (pixel);	   \
-	((PixelGroup *) (dst))[DoublePixel3] = (pixel);	   \
-    }							   \
-    else {						   \
-	switch (bits & 0x0f) {	 			   \
-	case 0:				\
-	    break;			\
-	case 1:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    break;			\
-	case 2:				\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    break;			\
-	case 3:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    break;			\
-	case 4:				\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 5:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 6:				\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 7:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    break;			\
-	case 8:				\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 9:				\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 10:			\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 11:			\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 12:			\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 13:			\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 14:			\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	case 15:			\
-	    ((CARD32 *) (dst))[SinglePixel0] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel1] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel2] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel3] = (pixel);	\
-	    break;			\
-	}				\
-	switch ((bits & 0xf0) >> 4) {	\
-	case 0:				\
-	    break;			\
-	case 1:				\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    break;			\
-	case 2:				\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    break;			\
-	case 3:				\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    break;			\
-	case 4:				\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    break;			\
-	case 5:				\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    break;			\
-	case 6:				\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    break;			\
-	case 7:				\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    break;			\
-	case 8:				\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 9:				\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 10:			\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 11:			\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 12:			\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 13:			\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 14:			\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	case 15:			\
-	    ((CARD32 *) (dst))[SinglePixel4] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel5] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel6] = (pixel);	\
-	    ((CARD32 *) (dst))[SinglePixel7] = (pixel);	\
-	    break;			\
-	}				\
-    }
-#endif /* PGSZ */
-
-#if PGSZ == 32
-#define SwitchBitGroup(dst,pixel,bits) { \
-	switch (bits) { \
-	case 0: \
-       	    break; \
-	case 1: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel0] = (pixel);) \
-	    break; \
-	case 2: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel1] = (pixel);) \
-	    break; \
-	case 3: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel0] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel1] = (pixel);) \
-	    break; \
-	case 4: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 5: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel0] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 6: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel1] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 7: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel0] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel1] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel2] = (pixel);) \
-	    break; \
-	case 8: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 9: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel0] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 10: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel1] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 11: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel0] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel1] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 12: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel2] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 13: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel0] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel2] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 14: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel1] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel2] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	case 15: \
-	    SwitchBitsLoop (((CARD32 *) (dst))[SinglePixel0] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel1] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel2] = (pixel); \
-			    ((CARD32 *) (dst))[SinglePixel3] = (pixel);) \
-	    break; \
-	} \
-}
-#else /* PGSZ == 64 */
-#define SwitchBitGroup(dst,pixel,bits) { \
-	cfb cannot hack 64-bit SwitchBitGroup psz=PSZ
-#endif /* PGSZ */
-
-#endif /* PSZ == 32 */
-#endif /* AVOID_MEMORY_READ */
-
-extern PixelGroup cfb8BitLenMasks[PGSZ];
-
-extern int cfb8SetStipple (
-    int	/*alu*/,
-    CfbBits /*fg*/,
-    CfbBits /*planemask*/
-);
-
-extern int cfb8SetOpaqueStipple (
-    int /*alu*/,
-    CfbBits /*fg*/,
-    CfbBits /*bg*/,
-    CfbBits /*planemask*/
-);
-
-extern int cfb8ComputeClipMasks32 (
-    BoxPtr	/*pBox*/,
-    int		/*numRects*/,
-    int		/*x*/,
-    int		/*y*/,
-    int		/*w*/,
-    int		/*h*/,
-    CARD32 * /*clips*/
-);
diff --git a/cfb/cfb8line.c b/cfb/cfb8line.c
deleted file mode 100644
index 8c00d9f..0000000
--- a/cfb/cfb8line.c
+++ /dev/null
@@ -1,1503 +0,0 @@
-/*
- *
-Copyright 1990, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- *
- * Jeff Anton'x fixes: cfb8line.c   97/02/07
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <stdlib.h>
-#include <X11/X.h>
-
-#include "gcstruct.h"
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "regionstr.h"
-#include "scrnintstr.h"
-#include "mistruct.h"
-
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "cfbrrop.h"
-#include "miline.h"
-
-#ifdef PIXEL_ADDR
-
-#if defined(__GNUC__) && defined(mc68020)
-#define STUPID volatile
-#define REARRANGE
-#else
-#define STUPID
-#endif
-
-#ifdef __GNUC__
-/* lame compiler doesn't even look at 'register' attributes */
-#define I_H do{
-#define I_T }while(0);
-#define IMPORTANT_START I_H I_H I_H I_H I_H I_H I_H I_H I_H I_H
-#define IMPORTANT_END	I_T I_T I_T I_T I_T I_T I_T I_T I_T I_T
-#else
-#define IMPORTANT_START
-#define IMPORTANT_END
-#endif
-
-#define isClipped(c,ul,lr)  ((((c) - (ul)) | ((lr) - (c))) & ClipMask)
-
-#ifdef POLYSEGMENT
-
-# if (defined(sun) || defined(__bsdi__)) && \
-     (defined(sparc) || defined(__sparc__))
-#  define WIDTH_FAST  1152
-# endif
-
-# ifdef ultrix
-#  define WIDTH_FAST  1024
-# endif
-
-# ifdef Mips
-#  define WIDTH_FAST 4096
-# endif
-# ifdef WIDTH_FAST
-#  if WIDTH_FAST == 1024
-#   define FAST_MUL(y)	((y) << 10)
-#  endif
-
-#  if WIDTH_FAST == 1152
-#   define FAST_MUL(y)	(((y) << 10) + ((y) << 7))
-#  endif
-
-#  if WIDTH_FAST == 1280
-#   define FAST_MUL(y)	(((y) << 10) + ((y) << 8))
-#  endif
-
-#  if WIDTH_FAST == 2048
-#   define FAST_MUL(y)	((y) << 11)
-#  endif
-
-#  if WIDTH_FAST == 4096
-#   define FAST_MUL(y)	((y) << 12)
-#  endif
-# endif
-
-# if defined(WIDTH_SHIFT)
-#  ifdef FAST_MUL
-#   define FUNC_NAME(e)	    RROP_NAME(RROP_NAME_CAT(e,Shift))
-#   if RROP == GXcopy
-#    define INCLUDE_OTHERS
-#    define SERIOUS_UNROLLING
-#   endif
-#   define INCLUDE_DRAW
-#   define NWIDTH(nwidth)   WIDTH_FAST
-#   define WIDTH_MUL(y,w)   FAST_MUL(y)
-#  endif
-# else
-#  define FUNC_NAME(e)	    RROP_NAME(e)
-#  define WIDTH_MUL(y,w)    ((y) * (w))
-#  define NWIDTH(nwidth)    (nwidth)
-#  define INCLUDE_DRAW
-#  if !defined (FAST_MUL) && RROP == GXcopy
-#   define INCLUDE_OTHERS
-#   define SERIOUS_UNROLLING
-#  endif
-# endif
-#else
-
-# define INCLUDE_DRAW
-# define WIDTH_MUL(y,w)	((y) * (w))
-# define NWIDTH(nwidth)	nwidth
-# ifdef PREVIOUS
-#  define FUNC_NAME(e)	RROP_NAME(RROP_NAME_CAT(e,Previous))
-# else
-#  define FUNC_NAME(e)	RROP_NAME(e)
-#  if RROP == GXcopy
-#   define INCLUDE_OTHERS
-#   ifdef PLENTIFUL_REGISTERS
-#    define SAVE_X2Y2
-#   endif
-#   define ORIGIN
-#   define SERIOUS_UNROLLING
-#  else
-#   define EITHER_MODE
-#  endif
-# endif
-#endif
-
-#if PSZ == 24
-#define PXL2ADR(x)  ((x)*3 >> 2)
-
-#if RROP == GXcopy
-#define body_rop \
-	    addrp = (PixelType *)((unsigned long)addrb & ~0x03); \
-	    switch((unsigned long)addrb & 3){ \
-	    case 0: \
-	      *addrp = (*addrp & 0xFF000000)|(piQxelXor[0] & 0xFFFFFF); \
-	      break; \
-	    case 1: \
-	      *addrp = (*addrp & 0xFF)|(piQxelXor[2] & 0xFFFFFF00); \
-	      break; \
-	    case 3: \
-	      *addrp = (*addrp & 0xFFFFFF)|(piQxelXor[0] & 0xFF000000); \
-	      *(addrp+1)=(*(addrp+1) & 0xFFFF0000)|(piQxelXor[1] & 0xFFFF); \
-	      break; \
-	    case 2: \
-	      *addrp = (*addrp & 0xFFFF)|(piQxelXor[1] & 0xFFFF0000); \
-	      *(addrp+1)=(*(addrp+1) & 0xFFFFFF00)|(piQxelXor[2] & 0xFF); \
-	      break; \
-	    }
-#endif
-#if RROP == GXxor
-#define body_rop \
-	    addrp = (PixelType *)((unsigned long)addrb & ~0x03); \
-	    switch((unsigned long)addrb & 3){ \
-	    case 0: \
-	      *addrp ^= piQxelXor[0] & 0xFFFFFF; \
-	      break; \
-	    case 1: \
-	      *addrp ^= piQxelXor[2] & 0xFFFFFF00; \
-	      break; \
-	    case 3: \
-	      *addrp ^= piQxelXor[0] & 0xFF000000; \
-	      *(addrp+1) ^= piQxelXor[1] & 0xFFFF; \
-	      break; \
-	    case 2: \
-	      *addrp ^= piQxelXor[1] & 0xFFFF0000; \
-	      *(addrp+1) ^= piQxelXor[2] & 0xFF; \
-	      break; \
-	    }
-#endif
-#if RROP == GXand
-#define body_rop \
-	    addrp = (PixelType *)((unsigned long)addrb & ~0x03); \
-	    switch((unsigned long)addrb & 3){ \
-	    case 0: \
-	      *addrp &= piQxelAnd[0] | 0xFF000000; \
-	      break; \
-	    case 1: \
-	      *addrp &= piQxelAnd[2] | 0xFF; \
-	      break; \
-	    case 3: \
-	      *addrp &= 0xFFFFFF | piQxelAnd[0]; \
-	      *(addrp+1) &= 0xFFFF0000 | piQxelAnd[1]; \
-	      break; \
-	    case 2: \
-	      *addrp &= 0xFFFF | piQxelAnd[1]; \
-	      *(addrp+1) &= 0xFFFFFF00 | piQxelAnd[2]; \
-	      break; \
-	    }
-#endif
-#if RROP == GXor
-#define body_rop \
-	    addrp = (PixelType *)((unsigned long)addrb & ~0x03); \
-	    switch((unsigned long)addrb & 3){ \
-	    case 0: \
-	      *addrp |= piQxelOr[0] & 0xFFFFFF; \
-	      break; \
-	    case 1: \
-	      *addrp |= piQxelOr[2] & 0xFFFFFF00; \
-	      break; \
-	    case 3: \
-	      *addrp |= piQxelOr[0] & 0xFF000000; \
-	      *(addrp+1) |= piQxelOr[1] & 0xFFFF; \
-	      break; \
-	    case 2: \
-	      *addrp |= piQxelOr[1] & 0xFFFF0000; \
-	      *(addrp+1) |= piQxelOr[2] & 0xFF; \
-	      break; \
-	    }
-#endif
-#if RROP == GXset
-#define body_rop \
-	    addrp = (PixelType *)((unsigned long)addrb & ~0x03); \
-	    switch((unsigned long)addrb & 3){ \
-	    case 0: \
-	      *addrp = (*addrp & (piQxelAnd[0]|0xFF000000)) \
-			^ (piQxelXor[0] & 0xFFFFFF); \
-	      break; \
-	    case 1: \
-	      *addrp = (*addrp & (piQxelAnd[2]|0xFF)) \
-			^ (piQxelXor[2] & 0xFFFFFF00); \
-	      break; \
-	    case 3: \
-	      *addrp = (*addrp & (piQxelAnd[0]|0xFFFFFF)) \
-			^ (piQxelXor[0] & 0xFF000000); \
-	      *(addrp+1) = (*(addrp+1) & (piQxelAnd[1]|0xFFFF0000)) \
-			^ (piQxelXor[1] & 0xFFFF); \
-	      break; \
-	    case 2: \
-	      *addrp = (*addrp & (piQxelAnd[1]|0xFFFF)) \
-			^ (piQxelXor[1] & 0xFFFF0000); \
-	      *(addrp+1) = (*(addrp+1) & (piQxelAnd[2]|0xFFFFFF00)) \
-			^ (piQxelXor[2] & 0xFF); \
-	      break; \
-	    }
-#endif
-#endif /* PSZ == 24 */
-
-#define BUGFIX_clip
-
-#ifdef INCLUDE_DRAW
-
-int
-#ifdef POLYSEGMENT
-FUNC_NAME(cfb8SegmentSS1Rect) (pDrawable, pGC, nseg, pSegInit)
-    DrawablePtr	pDrawable;
-    GCPtr	pGC;
-    int		nseg;
-    xSegment	*pSegInit;
-#else
-FUNC_NAME(cfb8LineSS1Rect) (pDrawable, pGC, mode, npt, pptInit, pptInitOrig,
-			    x1p,y1p,x2p,y2p)
-    DrawablePtr pDrawable;
-    GCPtr	pGC;
-    int	mode;		/* Origin or Previous */
-    int	npt;		/* number of points */
-    DDXPointPtr pptInit, pptInitOrig;
-    int	*x1p, *y1p, *x2p, *y2p;
-#endif /* POLYSEGMENT */
-{
-    register long   e;
-    register int    y1_or_e1;
-    register PixelType   *addrp;
-    register int    stepmajor;
-    register int    stepminor;
-#ifndef REARRANGE
-    register long   e3;
-#endif
-#ifdef mc68000
-    register short  x1_or_len;
-#else
-    register int    x1_or_len;
-#endif
-    RROP_DECLARE
-
-#ifdef SAVE_X2Y2
-# define c2 y2
-#else
-    register int    c2;
-#endif
-#if !defined(ORIGIN) && !defined(POLYSEGMENT)
-    register int _x1 = 0, _y1 = 0, _x2 = 0, _y2 = 0;
-    int extents_x1, extents_y1, extents_x2, extents_y2;
-#endif /* !ORIGIN */
-#ifndef PREVIOUS
-    register int upperleft, lowerright;
-    CARD32	 ClipMask = 0x80008000;
-#endif /* !PREVIOUS */
-#ifdef POLYSEGMENT
-    register int    capStyle;
-#endif /* POLYSEGMENT */
-#ifdef SAVE_X2Y2
-    register int    x2, y2;
-# define X1  x1_or_len
-# define Y1  y1_or_e1
-# define X2  x2
-# define Y2  y2
-#else
-# ifdef POLYSEGMENT
-#  define X1  x1_or_len
-#  define Y1  y1_or_e1
-# else
-#  define X1  intToX(y1_or_e1)
-#  define Y1  intToY(y1_or_e1)
-# endif /* POLYSEGMENT */
-# define X2  intToX(c2)
-# define Y2  intToY(c2)
-#endif /* SAVE_X2Y2 */
-    PixelType   *addr;
-    int		    nwidth;
-    cfbPrivGCPtr    devPriv;
-    BoxPtr	    extents;
-    int		    *ppt;
-#if PSZ == 24
-    int xBase;     /* x of addr */
-    int xOffset;   /* x of addrp */
-    PixelType   *addrLineEnd;
-    char *addrb;
-    int stepmajor3, stepminor3, majordx, minordx;
-#endif
-#ifndef POLYSEGMENT
-#ifndef ORIGIN
-#ifdef BUGFIX_clip
-    int ex_x1, ex_y1, ex_x2, ex_y2;
-#endif
-#endif
-#endif
-    int		    octant;
-    unsigned int    bias = miGetZeroLineBias(pDrawable->pScreen);
-
-    devPriv = cfbGetGCPrivate(pGC);
-    cfbGetPixelWidthAndPointer (pDrawable, nwidth, addr);
-#ifndef REARRANGE
-    RROP_FETCH_GCPRIV(devPriv);
-#endif
-    extents = &pGC->pCompositeClip->extents;
-#ifndef PREVIOUS
-    c2 = *((int *) &pDrawable->x);
-    c2 -= (c2 & 0x8000) << 1;
-    upperleft = *((int *) &extents->x1) - c2;
-    lowerright = *((int *) &extents->x2) - c2 - 0x00010001;
-#endif /* !PREVIOUS */
-#ifndef POLYSEGMENT
-#ifndef ORIGIN
-#ifdef BUGFIX_clip
-    ex_x1 = extents->x1 - pDrawable->x;
-    ex_y1 = extents->y1 - pDrawable->y;
-    ex_x2 = extents->x2 - pDrawable->x;
-    ex_y2 = extents->y2 - pDrawable->y;
-#endif
-#endif
-#endif
-#if PSZ == 24
-    xBase = pDrawable->x;
-    addr += WIDTH_MUL(pDrawable->y,nwidth);
-#else
-    addr = addr + WIDTH_MUL(pDrawable->y,nwidth) + pDrawable->x;
-#endif
-#ifdef POLYSEGMENT
-    capStyle = pGC->capStyle - CapNotLast;
-    ppt = (int *) pSegInit;
-    while (nseg--)
-#else /* POLYSEGMENT */
-#ifdef EITHER_MODE
-    mode -= CoordModePrevious;
-    if (!mode)
-#endif /* EITHER_MODE */	
-#ifndef ORIGIN
-    {	/* CoordModePrevious */
-	ppt = (int *)pptInit + 1;
-	_x1 = *x1p;
-	_y1 = *y1p;
-	extents_x1 = extents->x1 - pDrawable->x;
-	extents_x2 = extents->x2 - pDrawable->x;
-	extents_y1 = extents->y1 - pDrawable->y;
-	extents_y2 = extents->y2 - pDrawable->y;
-	if (_x1 < extents_x1 || _x1 >= extents_x2 ||
-	    _y1 < extents_y1 || _y1 >= extents_y2)
-	{
-	    c2 = *ppt++;
-	    intToCoord(c2, _x2, _y2);
-	    *x2p = _x1 + _x2;
-	    *y2p = _y1 + _y2;
-	    return 1;
-	}
-#if PSZ == 24
-	addrLineEnd = addr + WIDTH_MUL(_y1, nwidth);
-	xOffset = xBase + _x1;
-	addrb = (char *)addrLineEnd + xOffset * 3;
-	addrp = (PixelType *)((unsigned long)addrb & ~0x03);
-#else
-	addrp = addr + WIDTH_MUL(_y1, nwidth) + _x1;
-#endif
-	_x2 = _x1;
-	_y2 = _y1;	
-    }
-#endif /* !ORIGIN */
-#ifdef EITHER_MODE
-    else
-#endif /* EITHER_MODE */
-#ifndef PREVIOUS
-    {
-	ppt = (int *) pptInit;
-	c2 = *ppt++;
-	if (isClipped (c2, upperleft, lowerright))
-	{
-	    return 1;
-	}
-#ifdef SAVE_X2Y2
-	intToCoord(c2,x2,y2);
-#endif
-#if PSZ == 24
-	addrLineEnd = addr + WIDTH_MUL(Y2, nwidth);
-	xOffset = xBase + X2;
-	addrb = (char *)addrLineEnd + xOffset * 3;
-	addrp = (PixelType *)((unsigned long)addrb & ~0x03);
-#else
-	addrp = addr + WIDTH_MUL(Y2, nwidth) + X2;
-#endif
-    }
-#endif /* !PREVIOUS */    
-    while (--npt)
-#endif /* POLYSEGMENT */
-    {
-#ifdef POLYSEGMENT
-	y1_or_e1 = ppt[0];
-	c2 = ppt[1];
-	ppt += 2;
-	if (isClipped(y1_or_e1,upperleft,lowerright)|isClipped(c2,upperleft,lowerright))
-	    break;
-	intToCoord(y1_or_e1,x1_or_len,y1_or_e1);
-	/* compute now to avoid needing x1, y1 later */
-#if PSZ == 24
-	addrLineEnd = addr + WIDTH_MUL(y1_or_e1, nwidth);
-	xOffset = xBase + x1_or_len;
-	addrb = (char *)addrLineEnd + xOffset * 3;
-	addrp = (PixelType *)((unsigned long)addrb & ~0x03);
-#else
-	addrp = addr + WIDTH_MUL(y1_or_e1, nwidth) + x1_or_len;
-#endif
-#else /* !POLYSEGMENT */
-#ifdef EITHER_MODE
-	if (!mode)
-#endif /* EITHER_MODE */	
-#ifndef ORIGIN
-	{	
-	    /* CoordModePrevious */
-	    _x1 = _x2;
-	    _y1 = _y2;
-	    c2 = *ppt++;
-	    intToCoord(c2, _x2, _y2);
-	    _x2 = _x1 + _x2;
-	    _y2 = _y1 + _y2;
-
-#ifdef BUGFIX_clip
-	    if (_x2 < ex_x1 || _x2 >= ex_x2 ||
-		_y2 < ex_y1 || _y2 >= ex_y2)
-#else
-	    if (_x2 < extents_x1 || _x2 >= extents_x2 ||
-		_y2 < extents_y1 || _y2 >= extents_y2)
-#endif
-	    {
-		break;
-	    }
-	    CalcLineDeltas(_x1, _y1, _x2, _y2, x1_or_len, y1_or_e1,
-			   stepmajor, stepminor, 1, NWIDTH(nwidth), octant);
-	}
-#endif /* !ORIGIN */
-#ifdef EITHER_MODE
-	else
-#endif /* EITHER_MODE */
-#ifndef PREVIOUS
-        {
-#ifndef SAVE_X2Y2
-	    y1_or_e1 = c2;
-#else
-	    y1_or_e1 = y2;
-	    x1_or_len = x2;
-#endif /* SAVE_X2Y2 */
-	    c2 = *ppt++;
-
-	    if (isClipped (c2, upperleft, lowerright))
-		break;
-#ifdef SAVE_X2Y2
-	    intToCoord(c2,x2,y2);
-#endif
-	    CalcLineDeltas(X1, Y1, X2, Y2, x1_or_len, y1_or_e1,
-			   stepmajor, stepminor, 1, NWIDTH(nwidth), octant);
-	}
-#endif /* !PREVIOUS */
-#endif /* POLYSEGMENT */
-
-#ifdef POLYSEGMENT
-	CalcLineDeltas(X1, Y1, X2, Y2, x1_or_len, y1_or_e1,
-		       stepmajor, stepminor, 1, NWIDTH(nwidth), octant);
-	/*
-	 * although the horizontal code works for polyline, it
-	 * slows down 10 pixel lines by 15%.  Thus, this
-	 * code is optimized for horizontal segments and
-	 * random orientation lines, which seems like a reasonable
-	 * assumption
-	 */
-	if (y1_or_e1 != 0)
-	{
-#endif /* POLYSEGMENT */
-	if (x1_or_len < y1_or_e1)
-	{
-#ifdef REARRANGE
-	    register int	e3;
-#endif
-
-	    e3 = x1_or_len;
-	    x1_or_len = y1_or_e1;
-	    y1_or_e1 = e3;
-
-	    e3 = stepminor;
-	    stepminor = stepmajor;
-	    stepmajor = e3;
-	    SetYMajorOctant(octant);
-	}
-
-	e = -x1_or_len;
-#ifdef POLYSEGMENT
-	if (!capStyle)
-	    x1_or_len--;
-#endif
-
-	{
-#ifdef REARRANGE
-	register int e3;
-	RROP_DECLARE
-	RROP_FETCH_GCPRIV(devPriv);
-#endif
-
-	y1_or_e1 = y1_or_e1 << 1;
-	e3 = e << 1;
-
-	FIXUP_ERROR(e, octant, bias);
-
-#if PSZ == 24
- 	if (stepmajor == 1  ||  stepmajor == -1){
- 	    stepmajor3 = stepmajor * 3;
- 	    stepminor3 = stepminor * sizeof (CfbBits);
- 	    majordx = stepmajor; minordx = 0;
-         } else {
- 	    stepmajor3 = stepmajor * sizeof (CfbBits);
- 	    stepminor3 = stepminor * 3;
- 	    majordx = 0; minordx = stepminor;
-         }
-#endif
- 
-#if PSZ == 24
-#define body {\
- 	    body_rop \
- 	    addrb += stepmajor3; \
-             xOffset += majordx; \
- 	    e += y1_or_e1; \
- 	    if (e >= 0){ \
- 	        addrb += stepminor3; \
-                 xOffset += minordx; \
- 		e += e3; \
- 	    } \
- 	}
-#else /* PSZ == 24 */
-
-#define body {\
-	    RROP_SOLID(addrp); \
-	    addrp += stepmajor; \
-	    e += y1_or_e1; \
-	    if (e >= 0) \
-	    { \
-		addrp += stepminor; \
-		e += e3; \
-	     } \
-	}
-#endif /* PSZ == 24 */
-
-#ifdef LARGE_INSTRUCTION_CACHE
-
-# ifdef SERIOUS_UNROLLING
-#  define UNROLL	16
-# else
-#  define UNROLL	4
-# endif
-#define CASE(n)	case -n: body
-
-	while ((x1_or_len -= UNROLL) >= 0)
-	{
-	    body body body body
-# if UNROLL >= 8
-	    body body body body
-# endif
-# if UNROLL >= 12
-	    body body body body
-# endif
-# if UNROLL >= 16
-	    body body body body
-# endif
-	}
-	switch (x1_or_len)
-	{
-	CASE(1) CASE(2) CASE(3)
-# if UNROLL >= 8
-	CASE(4) CASE(5) CASE(6) CASE(7)
-# endif
-# if UNROLL >= 12
-	CASE(8) CASE(9) CASE(10) CASE(11)
-# endif
-# if UNROLL >= 16
-	CASE(12) CASE(13) CASE(14) CASE(15)
-# endif
-	}
-#else /* !LARGE_INSTRUCTION_CACHE */
-
-	IMPORTANT_START
-	IMPORTANT_START
-
-	if (x1_or_len & 1)
-	    body
-	x1_or_len >>= 1;
-	while (x1_or_len--) {
-	    body body
-	}
-
-	IMPORTANT_END
-	IMPORTANT_END
-#endif /* LARGE_INSTRUCTION_CACHE */
-
-#ifdef POLYSEGMENT
-#if PSZ == 24
-	body_rop
-#else
-	RROP_SOLID(addrp);
-#endif
-#endif
-#if PSZ == 24
-	addrp = (PixelType *)((unsigned long)addrb & ~0x03);
-#endif
-	}
-#undef body
-#ifdef POLYSEGMENT
-	}
-	else /* Polysegment horizontal line optimization */
-	{
-# ifdef REARRANGE
-	    register int    e3;
-	    RROP_DECLARE
-	    RROP_FETCH_GCPRIV(devPriv);
-# endif /* REARRANGE */
-	    if (stepmajor < 0)
-	    {
-#if PSZ == 24
-		xOffset -= x1_or_len;
-		addrp = addrLineEnd + PXL2ADR(xOffset);
-#else
-		addrp -= x1_or_len;
-#endif
-		if (capStyle)
-		    x1_or_len++;
-		else
-#if PSZ == 24
-		  xOffset++;
-		addrp = addrLineEnd + PXL2ADR(xOffset);
-#else
-		    addrp++;
-#endif
-	    }
-	    else
-	    {
-#if PSZ == 24
-		addrp = addrLineEnd + PXL2ADR(xOffset);
-#endif
-		if (capStyle)
-		    x1_or_len++;
-	    }
-# if PSZ == 24
-	    y1_or_e1 = xOffset & 3;
-# else
-#  if PGSZ == 64 /* PIM value from <cfbmskbits.h> is not it! (for 16/32 PSZ)*/
-	    y1_or_e1 = ((long) addrp) & 0x7;
-	    addrp = (PixelType *) (((unsigned char *) addrp) - y1_or_e1);
-#  else
-	    y1_or_e1 = ((long) addrp) & PIM;
-	    addrp = (PixelType *) (((unsigned char *) addrp) - y1_or_e1);
-#  endif
-#if PGSZ == 32
-#  if PWSH != 2
-	    y1_or_e1 >>= (2 - PWSH);
-#  endif
-#else /* PGSZ == 64 */
-#  if PWSH != 3
-	    y1_or_e1 >>= (3 - PWSH);
-#  endif
-#endif /* PGSZ */
-# endif /* PSZ == 24 */
-#if PSZ == 24
-	    {
-#if RROP == GXcopy
-	      register int nlmiddle;
-	      int leftIndex = xOffset & 3;
-	      int rightIndex = (xOffset + x1_or_len) & 3;
-#else
-	      register int pidx;
-#endif
-
-#if RROP == GXcopy
-	      nlmiddle = x1_or_len;
-	      if(leftIndex){
-		nlmiddle -= (4 - leftIndex);
-	      }
-	      if(rightIndex){
-		nlmiddle -= rightIndex;
-	      }
-	      
-	      nlmiddle >>= 2;
-	      switch(leftIndex+x1_or_len){
-	      case 4:
-		switch(leftIndex){
-		case 0:
-		  *addrp++ = piQxelXor[0];
-		  *addrp++ = piQxelXor[1];
-		  *addrp   = piQxelXor[2];
-		  break;
-		case 1:
-		  *addrp = ((*addrp) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-		  addrp++;
-		  *addrp = piQxelXor[1];
-		  addrp++;
-		  *addrp = piQxelXor[2];
-		  break;
-		case 2:
-		  *addrp = ((*addrp) & 0xFFFF) | (piQxelXor[1] & 0xFFFF0000);
-		  addrp++;
-		  *addrp = piQxelXor[2];
-		  break;
-		case 3:
-		  *addrp = ((*addrp) & 0xFF) | (piQxelXor[2] & 0xFFFFFF00);
-		  break;
-		}
-		break;
-	      case 3:
-		switch(leftIndex){
-		case 0:
-		  *addrp++ = piQxelXor[0];
-		  *addrp++ = piQxelXor[1];
-		  *addrp = ((*addrp) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		  break;
-		case 1:
-		  *addrp = ((*addrp) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-		  addrp++;
-		  *addrp = piQxelXor[1];
-		  addrp++;
-		  *addrp = ((*addrp) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		  break;
-		case 2:
-		  *addrp = ((*addrp) & 0xFFFF) | (piQxelXor[1] & 0xFFFF0000);
-		  addrp++;
-		  *addrp = ((*addrp) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		  break;
-		}
-		break;
-	      case 2:
-		switch(leftIndex){
-/*
-		case 2:
-		  *addrp = ((*addrp) & 0xFFFF) | (piQxelXor[1] & 0xFFFF0000);
-		  addrp++;
-		  *addrp = ((*addrp) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		  break;
-*/
-		case 1:
-		  *addrp = ((*addrp) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-		  addrp++;
-		  *addrp = ((*addrp) & 0xFFFF0000) | (piQxelXor[1] & 0xFFFF);
-		  break;
-		case 0:
-		  *addrp++ =  piQxelXor[0];
-		  *addrp = ((*addrp) & 0xFFFF0000) | (piQxelXor[1] & 0xFFFF);
-		  break;
-		}
-		break;
-	      case 1: /*only if leftIndex = 0 and w = 1*/
-		if(x1_or_len){
-		*addrp =  ((*addrp) & 0xFF000000) | (piQxelXor[0] & 0xFFFFFF);
-		}
-/*
-		else{
-		*addrp =  ((*addrp) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-		addrp++;
-		*addrp =  ((*addrp) & 0xFFFF0000) | (piQxelXor[1] & 0xFFFF);
-		}
-*/
-		break;
-	      case 0: /*never*/
-		break;
-	      default:
-		{
-/*
-		  maskbits(y1_or_e1, x1_or_len, e, e3, x1_or_len)
-*/
-		  switch(leftIndex){
-		  case 0:
-		    break;
-		  case 1:
-		    *addrp = ((*addrp) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-		    addrp++;
-		    *addrp = piQxelXor[1];
-		    addrp++;
-		    *addrp = piQxelXor[2];
-		    addrp++;
-		    break;
-		  case 2:
-		    *addrp = ((*addrp) & 0xFFFF) | (piQxelXor[1] & 0xFFFF0000);
-		    addrp++;
-		    *addrp = piQxelXor[2];
-		    addrp++;
-		    break;
-		  case 3:
-		    *addrp = ((*addrp) & 0xFF) | (piQxelXor[2] & 0xFFFFFF00);
-		    addrp++;
-		    break;
-		  }
-		  while(nlmiddle--){
-		    *addrp++ = piQxelXor[0];
-		    *addrp++ = piQxelXor[1];
-		    *addrp++ = piQxelXor[2];
-		  }
-		  switch(rightIndex++){
-		  case 0:
-		    break;
-		  case 1:
-		    *addrp = ((*addrp) & 0xFF000000) | (piQxelXor[0] & 0xFFFFFF);
-		    break;
-		  case 2:
-		    *addrp++ = piQxelXor[0];
-		    *addrp = ((*addrp) & 0xFFFF0000) | (piQxelXor[1] & 0xFFFF);
-		    break;
-		  case 3:
-		    *addrp++ = piQxelXor[0];
-		    *addrp++ = piQxelXor[1];
-		    *addrp = ((*addrp) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		    break;
-		  }
-/*
-		  if (e3){
-		    e3 &= 0xFFFFFF;
-		    switch(rightIndex&3){
-		    case 0:
-		      *addrp = ((*addrp) & (0xFF000000 | ~e3))
-			| (piQxelXor[0] & 0xFFFFFF & e3);
-		      break;
-		    case 1:
-		      *addrp = ((*addrp) & (0xFFFFFF | ~(e3<<24)))
-				  + (piQxelXor[0] & 0xFF000000 & (e3<<24));
-		      addrp++;
-		      *addrp = ((*addrp) & (0xFFFF0000|~(e3 >> 8)))
-				  | (piQxelXor[1] & 0xFFFF & (e3 >> 8));
-		      break;
-		    case 2:
-		      *addrp = ((*addrp) & (0xFFFF|~(e3 << 16)))
-				  | (piQxelXor[1] & 0xFFFF0000 & (e3 << 16));
-		      addrp++;
-		      *addrp = ((*addrp) & (0xFFFFFF00|~(e3>>16)))
-				  | (piQxelXor[2] & 0xFF & (e3 >> 16));
-		      break;
-		    case 3:
-		      *addrp = ((*addrp) & (0xFF|~(e3<<8)))
-				  | (piQxelXor[2] & 0xFFFFFF00 & (e3<<8));
-		      addrp++;
-		      break;
-		    }
-		  }
-*/
-		}
-	      }
-#else /* GXcopy */
-	      addrp = (PixelType *)((char *)addrLineEnd + ((xOffset * 3) & ~0x03));
-	      if (x1_or_len <= 1){
-		if (x1_or_len)
-		  RROP_SOLID24(addrp, xOffset);
-	      } else {
-		maskbits(xOffset, x1_or_len, e, e3, x1_or_len);
-		pidx = xOffset & 3;
-		if (e){
-		  RROP_SOLID_MASK(addrp, e, pidx-1);
-		  addrp++;
-		  if (pidx == 3)
-		    pidx = 0;
-		}
-		while (--x1_or_len >= 0){
-		  RROP_SOLID(addrp, pidx);
-		  addrp++;
-		  if (++pidx == 3)
-		    pidx = 0;
-		}
-		if (e3)
-		  RROP_SOLID_MASK(addrp, e3, pidx);
-	      }
-#endif /* GXcopy */
-	    }
-#else /* PSZ == 24 */
-	    if (y1_or_e1 + x1_or_len <= PPW)
-	    {
-		if (x1_or_len)
-		{
-		    maskpartialbits(y1_or_e1, x1_or_len, e)
-		    RROP_SOLID_MASK((CfbBits *) addrp, e);
-		}
-	    }
-	    else
-	    {
-	    	maskbits(y1_or_e1, x1_or_len, e, e3, x1_or_len)
-	    	if (e)
-	    	{
-		    RROP_SOLID_MASK((CfbBits *) addrp, e);
-		    addrp += PPW;
-	    	}
-		RROP_SPAN(addrp, x1_or_len)
-	    	if (e3)
-		    RROP_SOLID_MASK((CfbBits *) addrp, e3);
-	    }
-#endif /* PSZ == 24 */
-	}
-#endif /* POLYSEGMENT */
-    }
-#ifdef POLYSEGMENT
-    if (nseg >= 0)
-	return (xSegment *) ppt - pSegInit;
-#else
-    if (npt)
-    {
-#ifdef EITHER_MODE
-	if (!mode)
-#endif /* EITHER_MODE */
-#ifndef ORIGIN
-	{
-	    *x1p = _x1;
-	    *y1p = _y1;		
-	    *x2p = _x2;
-	    *y2p = _y2;
-	}
-#endif /* !ORIGIN */	    
-	return ((DDXPointPtr) ppt - pptInit) - 1;
-    }
-
-# ifndef ORIGIN
-#  define C2  c2
-# else
-#  define C2  ppt[-1]
-# endif
-#ifdef EITHER_MODE
-    if (pGC->capStyle != CapNotLast &&
-	((mode ? (C2 != *((int *) pptInitOrig))
-	       : ((_x2 != pptInitOrig->x) ||
-		  (_y2 != pptInitOrig->y)))
-	 || (ppt == ((int *)pptInitOrig) + 2)))
-#endif /* EITHER_MODE */
-#ifdef PREVIOUS
-    if (pGC->capStyle != CapNotLast &&
-	((_x2 != pptInitOrig->x) ||
-	 (_y2 != pptInitOrig->y) ||
-	 (ppt == ((int *)pptInitOrig) + 2)))
-#endif /* PREVIOUS */
-#ifdef ORIGIN
-    if (pGC->capStyle != CapNotLast &&
-	((C2 != *((int *) pptInitOrig)) ||
-	 (ppt == ((int *)pptInitOrig) + 2)))
-#endif /* !PREVIOUS */
-    {
-# ifdef REARRANGE
-	RROP_DECLARE
-
-	RROP_FETCH_GCPRIV(devPriv);
-# endif
-#if PSZ == 24
-#if RROP == GXcopy
-	    switch(xOffset & 3){
-	    case 0:
-	      *addrp = ((*addrp)&0xFF000000)|(piQxelXor[0] & 0xFFFFFF);
-	      break;
-	    case 3:
-	      *addrp = ((*addrp)&0xFF)|(piQxelXor[2] & 0xFFFFFF00);
-	      break;
-	    case 1:
-	      *addrp = ((*addrp)&0xFFFFFF)|(piQxelXor[0] & 0xFF000000);
-	      *(addrp+1) = ((*(addrp+1))&0xFFFF0000)|(piQxelXor[1] & 0xFFFF);
-	      break;
-	    case 2:
-	      *addrp = ((*addrp)&0xFFFF)|(piQxelXor[1] & 0xFFFF0000);
-	      *(addrp+1) = ((*(addrp+1))&0xFFFFFF00)|(piQxelXor[2] & 0xFF);
-	      break;
-	    }
-#endif
-#if RROP == GXxor
-	    switch(xOffset & 3){
-	    case 0:
-	      *addrp ^= (piQxelXor[0] & 0xFFFFFF);
-	      break;
-	    case 3:
-	      *addrp ^= (piQxelXor[2] & 0xFFFFFF00);
-	      break;
-	    case 1:
-	      *addrp ^= (piQxelXor[0] & 0xFF000000);
-	      *(addrp+1) ^= (piQxelXor[1] & 0xFFFF);
-	      break;
-	    case 2:
-	      *addrp ^= (piQxelXor[1] & 0xFFFF0000);
-	      *(addrp+1) ^= (piQxelXor[2] & 0xFF);
-	      break;
-	    }
-#endif
-#if RROP == GXand
-	    switch(xOffset & 3){
-	    case 0:
-	      *addrp &= (piQxelAnd[0] | 0xFF000000);
-	      break;
-	    case 3:
-	      *addrp &= (piQxelAnd[2] | 0xFF);
-	      break;
-	    case 1:
-	      *addrp &= (0xFFFFFF|piQxelAnd[0]);
-	      *(addrp+1) &= (0xFFFF0000|piQxelAnd[1]);
-	      break;
-	    case 2:
-	      *addrp &= (0xFFFF|piQxelAnd[1]);
-	      *(addrp+1) &= (0xFFFFFF00|piQxelAnd[2]);
-	      break;
-	    }
-#endif
-#if RROP == GXor
-	    switch(xOffset & 3){
-	    case 0:
-	      *addrp |= (piQxelOr[0] & 0xFFFFFF);
-	      break;
-	    case 3:
-	      *addrp |= (piQxelOr[2] & 0xFFFFFF00);
-	      break;
-	    case 1:
-	      *addrp |= (piQxelOr[0] & 0xFF000000);
-	      *(addrp+1) |= (piQxelOr[1] & 0xFFFF);
-	      break;
-	    case 2:
-	      *addrp |= (piQxelOr[1] & 0xFFFF0000);
-	      *(addrp+1) |= (piQxelOr[2] & 0xFF);
-	      break;
-	    }
-#endif
-#if RROP == GXset
-	    switch(xOffset & 3){
-	    case 0:
-	      *addrp = (((*addrp)&(piQxelAnd[0] |0xFF000000))^(piQxelXor[0] & 0xFFFFFF));
-	      break;
-	    case 3:
-	      *addrp = (((*addrp)&(piQxelAnd[2]|0xFF))^(piQxelXor[2] & 0xFFFFFF00));
-	      break;
-	    case 1:
-	      *addrp = (((*addrp)&(piQxelAnd[0]|0xFFFFFF))^(piQxelXor[0] & 0xFF000000));
-	      *(addrp+1) = (((*(addrp+1))&(piQxelAnd[1]|0xFFFF0000))^(piQxelXor[1] & 0xFFFF));
-	      break;
-	    case 2:
-	      *addrp = (((*addrp)&(piQxelAnd[1]|0xFFFF))^(piQxelXor[1] & 0xFFFF0000));
-	      *(addrp+1) = (((*(addrp+1))&(piQxelAnd[2]|0xFFFFFF00))^(piQxelXor[2] & 0xFF));
-	      break;
-	    } 
-#endif
-#else
-	RROP_SOLID (addrp);
-# endif
-    }
-#endif /* !POLYSEGMENT */
-    RROP_UNDECLARE;
-    return -1;
-}
-
-#endif /* INCLUDE_DRAW */
-
-
-#ifdef INCLUDE_OTHERS
-
-#ifdef POLYSEGMENT
-
-void
-cfb8SegmentSS1Rect (pDrawable, pGC, nseg, pSegInit)
-    DrawablePtr	    pDrawable;
-    GCPtr	    pGC;
-    int		    nseg;
-    xSegment	    *pSegInit;
-{
-    int	    (*func)(DrawablePtr, GCPtr, int, xSegment *);
-    void    (*clip)(DrawablePtr, GCPtr, int, int, int, int, BoxPtr, Bool);
-    int	    drawn;
-    cfbPrivGCPtr    devPriv;
-
-#if defined(__arm32__) && PSZ != 8
-    /* XXX -JJK */
-    /* There is a painting bug when PSZ != 8; I need to track it down! */
-    cfbSegmentSS(pDrawable, pGC, nseg, pSegInit);
-    return;
-#endif
-
-    devPriv = cfbGetGCPrivate(pGC);
-#ifdef NO_ONE_RECT
-    if (REGION_NUM_RECTS(pGC->pCompositeClip) != 1)
-    {
-       cfbSegmentSS(pDrawable, pGC, nseg, pSegInit);
-       return;
-    }
-#endif
-    switch (devPriv->rop)
-    {
-    case GXcopy:
-	func = cfb8SegmentSS1RectCopy;
-	clip = cfb8ClippedLineCopy;
-#ifdef FAST_MUL
-	if (cfbGetPixelWidth (pDrawable) == WIDTH_FAST)
-	    func = cfb8SegmentSS1RectShiftCopy;
-#endif
-	break;
-    case GXxor:
-	func = cfb8SegmentSS1RectXor;
-	clip = cfb8ClippedLineXor;
-	break;
-    default:
-	func = cfb8SegmentSS1RectGeneral;
-	clip = cfb8ClippedLineGeneral;
-	break;
-    }
-    while (nseg)
-    {
-	drawn = (*func) (pDrawable, pGC, nseg, pSegInit);
-	if (drawn == -1)
-	    break;
-	(*clip) (pDrawable, pGC,
-			 pSegInit[drawn-1].x1, pSegInit[drawn-1].y1,
-			 pSegInit[drawn-1].x2, pSegInit[drawn-1].y2,
-			 &pGC->pCompositeClip->extents,
-			 pGC->capStyle == CapNotLast);
-	pSegInit += drawn;
-	nseg -= drawn;
-    }
-}
-
-#else /* POLYSEGMENT */
-
-void
-cfb8LineSS1Rect (pDrawable, pGC, mode, npt, pptInit)
-    DrawablePtr	pDrawable;
-    GCPtr	pGC;
-    int		mode;
-    int		npt;
-    DDXPointPtr	pptInit;
-{
-    int	    (*func)(DrawablePtr, GCPtr, int, int, 
-		    DDXPointPtr, DDXPointPtr,
-		    int *, int *, int *, int *);
-    void    (*clip)(DrawablePtr, GCPtr, int, int, int, int, BoxPtr, Bool);
-    int	    drawn;
-    cfbPrivGCPtr    devPriv;
-    int x1, y1, x2, y2;
-    DDXPointPtr pptInitOrig = pptInit;
-
-#if defined(__arm32__) && PSZ != 8
-    /* XXX -JJK */
-    /* There is a painting bug when PSZ != 8; I need to track it down! */
-    cfbLineSS(pDrawable, pGC, mode, npt, pptInit);
-    return;
-#endif
-
-    devPriv = cfbGetGCPrivate(pGC);
-#ifdef NO_ONE_RECT
-    if (REGION_NUM_RECTS(pGC->pCompositeClip) != 1)
-    {
-       cfbLineSS(pDrawable, pGC, mode, npt, pptInit);
-       return;
-    }
-#endif
-    switch (devPriv->rop)
-    {
-    case GXcopy:
-	func = cfb8LineSS1RectCopy;
-	clip = cfb8ClippedLineCopy;
-	if (mode == CoordModePrevious)
-	    func = cfb8LineSS1RectPreviousCopy;
-	break;
-    case GXxor:
-	func = cfb8LineSS1RectXor;
-	clip = cfb8ClippedLineXor;
-	break;
-    default:
-	func = cfb8LineSS1RectGeneral;
-	clip = cfb8ClippedLineGeneral;
-	break;
-    }
-    if (mode == CoordModePrevious)
-    {
-	x1 = pptInit->x;
-	y1 = pptInit->y;
-	while (npt > 1)
-	{
-	    drawn = (*func) (pDrawable, pGC, mode, npt, pptInit, pptInitOrig,
-			     &x1, &y1, &x2, &y2);
-	    if (drawn == -1)
-		break;
-	    (*clip) (pDrawable, pGC, x1, y1, x2, y2,
-		     &pGC->pCompositeClip->extents,
-		     drawn != npt - 1 || pGC->capStyle == CapNotLast);
-	    pptInit += drawn;
-	    npt -= drawn;
-	    x1 = x2;
-	    y1 = y2;
-	}
-    }
-    else
-    {
-	while (npt > 1)
-	{
-	    drawn = (*func) (pDrawable, pGC, mode, npt, pptInit, pptInitOrig,
-			     &x1, &y1, &x2, &y2);
-	    if (drawn == -1)
-		break;
-	    (*clip) (pDrawable, pGC,
-		     pptInit[drawn-1].x, pptInit[drawn-1].y,
-		     pptInit[drawn].x, pptInit[drawn].y,
-		     &pGC->pCompositeClip->extents,
-		     drawn != npt - 1 || pGC->capStyle == CapNotLast);
-	    pptInit += drawn;
-	    npt -= drawn;
-	}
-    }
-}
-
-#endif /* else POLYSEGMENT */
-#endif /* INCLUDE_OTHERS */
-
-#if !defined(POLYSEGMENT) && !defined (PREVIOUS)
-
-void
-RROP_NAME (cfb8ClippedLine) (pDrawable, pGC, x1, y1, x2, y2, boxp, shorten)
-    DrawablePtr	pDrawable;
-    GCPtr	pGC;
-    int		x1, y1, x2, y2;
-    BoxPtr	boxp;
-    Bool	shorten;
-{
-    int		    oc1, oc2;
-    int		    e, e1, e3, len;
-    int		    adx, ady;
-
-    PixelType	    *addr;
-    int		    nwidth;
-    int		    stepx, stepy;
-    int		    xorg, yorg;
-    int             new_x1, new_y1, new_x2, new_y2;
-    Bool	    pt1_clipped, pt2_clipped;
-    int		    changex, changey, result;
-#if PSZ == 24
-    PixelType   *addrLineEnd;
-    char *addrb;
-    int stepx3, stepy3;
-#endif
-    int		    octant;
-    unsigned int    bias = miGetZeroLineBias(pDrawable->pScreen);
-
-    cfbGetPixelWidthAndPointer(pDrawable, nwidth, addr);
-
-    xorg = pDrawable->x;
-    yorg = pDrawable->y;
-    x1 += xorg;
-    y1 += yorg;
-    x2 += xorg;
-    y2 += yorg;
-    oc1 = 0;
-    oc2 = 0;
-    OUTCODES (oc1, x1, y1, boxp);
-    OUTCODES (oc2, x2, y2, boxp);
-
-    if (oc1 & oc2)
-	return;
-
-    CalcLineDeltas(x1, y1, x2, y2, adx, ady, stepx, stepy, 1, nwidth, octant);
-
-    if (adx <= ady)
-    {
-	int	t;
-
-	t = adx;
-	adx = ady;
-	ady = t;
-
-	t = stepx;
-	stepx = stepy;
-	stepy = t;
-	
-	SetYMajorOctant(octant);
-    }
-    e = - adx;
-    e1 = ady << 1;
-    e3 = - (adx << 1);
-
-    FIXUP_ERROR(e, octant, bias);
-
-    new_x1 = x1;
-    new_y1 = y1;
-    new_x2 = x2;
-    new_y2 = y2;
-    pt1_clipped = 0;
-    pt2_clipped = 0;
-
-    if (IsXMajorOctant(octant))
-    {
-	result = miZeroClipLine(boxp->x1, boxp->y1, boxp->x2 - 1, boxp->y2 - 1,
-				&new_x1, &new_y1, &new_x2, &new_y2,
-				adx, ady,
-				&pt1_clipped, &pt2_clipped,
-				octant, bias, oc1, oc2);
-	if (result == -1)
-	    return;
-	
-	len = abs(new_x2 - new_x1) - 1; /* this routine needs the "-1" */
-	
-	/* if we've clipped the endpoint, always draw the full length
-	 * of the segment, because then the capstyle doesn't matter 
-	 * if x2,y2 isn't clipped, use the capstyle
-	 * (shorten == TRUE <--> CapNotLast)
-	 */
-	if (pt2_clipped || !shorten)
-	    len++;
-	
-	if (pt1_clipped)
-	{
-	    /* must calculate new error terms */
-	    changex = abs(new_x1 - x1);
-	    changey = abs(new_y1 - y1);
-	    e = e + changey * e3 + changex * e1;	    
-	}
-    }
-    else /* Y_AXIS */
-    {
-	result = miZeroClipLine(boxp->x1, boxp->y1, boxp->x2 - 1, boxp->y2 - 1,
-				&new_x1, &new_y1, &new_x2, &new_y2,
-				ady, adx,
-				&pt1_clipped, &pt2_clipped,
-				octant, bias, oc1, oc2);
-	if (result == -1)
-	    return;
-	
-	len = abs(new_y2 - new_y1) - 1; /* this routine needs the "-1" */
-	
-	/* if we've clipped the endpoint, always draw the full length
-	 * of the segment, because then the capstyle doesn't matter 
-	 * if x2,y2 isn't clipped, use the capstyle
-	 * (shorten == TRUE <--> CapNotLast)
-	 */
-	if (pt2_clipped || !shorten)
-	    len++;
-	
-	if (pt1_clipped)
-	{
-	    /* must calculate new error terms */
-	    changex = abs(new_x1 - x1);
-	    changey = abs(new_y1 - y1);
-	    e = e + changex * e3 + changey * e1;
-	}
-    }
-    x1 = new_x1;
-    y1 = new_y1;
-    {
-    register PixelType	*addrp;
-    RROP_DECLARE
-
-    RROP_FETCH_GC(pGC);
-
-#if PSZ == 24
-    addrLineEnd = addr + (y1 * nwidth);
-    addrb = (char *)addrLineEnd + x1 * 3;
-    if (stepx == 1  ||  stepx == -1){
-      stepx3 = stepx * 3;
-      stepy3 = stepy * sizeof (CfbBits);
-    } else {
-      stepx3 = stepx * sizeof (CfbBits);
-      stepy3 = stepy * 3;
-    }
-#else
-    addrp = addr + (y1 * nwidth) + x1;
-#endif
-
-#ifndef REARRANGE
-    if (!ady)
-    {
-#if PSZ == 24
-#define body {\
-	    body_rop \
-	    addrb += stepx3; \
-	}
-#else
-#define body	{ RROP_SOLID(addrp); addrp += stepx; }
-#endif
-	while (len >= PGSZB)
-	{
-	    body body body body
-#if PGSZ == 64
-	    body body body body
-#endif
-	    len -= PGSZB;
-	}
-	switch (len)
-	{
-#if PGSZ == 64
-	case  7: body case 6: body case 5: body case 4: body
-#endif
-	case  3: body case 2: body case 1: body
-	}
-#undef body
-    }
-    else
-#endif /* !REARRANGE */
-    {
-#if PSZ == 24
-#define body {\
-	    body_rop \
-	    addrb += stepx3; \
-	    e += e1; \
-	    if (e >= 0) \
-	    { \
-		addrb += stepy3; \
-		e += e3; \
-	    } \
-	}
-#else
-#define body {\
-	    RROP_SOLID(addrp); \
-	    addrp += stepx; \
-	    e += e1; \
-	    if (e >= 0) \
-	    { \
-		addrp += stepy; \
-		e += e3; \
-	     } \
-	}
-#endif
-
-#ifdef LARGE_INSTRUCTION_CACHE
-	while ((len -= PGSZB) >= 0)
-	{
-	    body body body body
-#if PGSZ == 64
-	    body body body body
-#endif
-	}
-	switch (len)
-	{
-	case  -1: body case -2: body case -3: body
-#if PGSZ == 64
-	case  -4: body case -5: body case -6: body case -7: body
-#endif
-	}
-#else /* !LARGE_INSTRUCTION_CACHE */
-	IMPORTANT_START;
-
-	while ((len -= 2) >= 0)
-	{
-	    body body;
-	}
-	if (len & 1)
-	    body;
-
-	IMPORTANT_END;
-#endif /* LARGE_INSTRUCTION_CACHE */
-    }
-#if PSZ == 24
-    body_rop
-#else
-    RROP_SOLID(addrp);
-#endif
-#undef body
-    RROP_UNDECLARE
-    }
-}
-
-#endif /* !POLYSEGMENT && !PREVIOUS */
-#endif /* PIXEL_ADDR */
diff --git a/cfb/cfballpriv.c b/cfb/cfballpriv.c
deleted file mode 100644
index 3b58266..0000000
--- a/cfb/cfballpriv.c
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- *
-Copyright 1991, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "servermd.h"
-#include "scrnintstr.h"
-#include "pixmapstr.h"
-#include "resource.h"
-#include "colormap.h"
-#include "colormapst.h"
-#include "cfb.h"
-#include "mi.h"
-#include "mistruct.h"
-#include "dix.h"
-#include "cfbmskbits.h"
-#include "mibstore.h"
-
-#if 1 || PSZ==8
-DevPrivateKey cfbGCPrivateKey = &cfbGCPrivateKey;
-#endif
-#ifdef CFB_NEED_SCREEN_PRIVATE
-DevPrivateKey cfbScreenPrivateKey = &cfbScreenPrivateKey;
-#endif
-
-
-Bool
-cfbAllocatePrivates(ScreenPtr pScreen, DevPrivateKey *gc_key)
-{
-    if (!gc_key || !*gc_key)
-    {
-    	if (!mfbAllocatePrivates(pScreen, &cfbGCPrivateKey))
-	    return FALSE;
-    	if (gc_key)
-	    *gc_key = cfbGCPrivateKey;
-    }
-    else
-    {
-	cfbGCPrivateKey = *gc_key;
-    }
-    return dixRequestPrivate(cfbGCPrivateKey, sizeof(cfbPrivGC));
-}
diff --git a/cfb/cfbbitblt.c b/cfb/cfbbitblt.c
deleted file mode 100644
index 00bf413..0000000
--- a/cfb/cfbbitblt.c
+++ /dev/null
@@ -1,1455 +0,0 @@
-/*
- * cfb copy area
- */
-
-
-/*
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-Author: Keith Packard
-
-*/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <stdlib.h>
-
-#include	<X11/X.h>
-#include	<X11/Xmd.h>
-#include	<X11/Xproto.h>
-#include	"gcstruct.h"
-#include	"windowstr.h"
-#include	"scrnintstr.h"
-#include	"pixmapstr.h"
-#include	"regionstr.h"
-#include	"mi.h"
-#include	"cfb.h"
-#include	"cfbmskbits.h"
-#include	"cfb8bit.h"
-#include	"fastblt.h"
-#define MFB_CONSTS_ONLY
-#include	"maskbits.h"
-
-#if PSZ == 8
-#define cfbCopyPlane1toN cfbCopyPlane1to8
-#define cfbCopyPlaneNto1 cfbCopyPlane8to1
-#else
-static unsigned int FgPixel, BgPixel;
-# if PSZ == 16
-#define cfbCopyPlane1toN cfbCopyPlane1to16
-#define cfbCopyPlaneNto1 cfbCopyPlane16to1
-# endif
-# if PSZ == 24
-#define cfbCopyPlane1toN cfbCopyPlane1to24
-#define cfbCopyPlaneNto1 cfbCopyPlane24to1
-# endif
-# if PSZ == 32
-#define cfbCopyPlane1toN cfbCopyPlane1to32
-#define cfbCopyPlaneNto1 cfbCopyPlane32to1
-# endif
-#endif
-
-/* cfbBitBltcfb == cfbCopyPlaneExpand */
-RegionPtr
-cfbBitBlt (
-    register DrawablePtr pSrcDrawable,
-    register DrawablePtr pDstDrawable,
-    GC *pGC,
-    int srcx, int srcy,
-    int width, int height,
-    int dstx, int dsty,
-    void (*doBitBlt)(
-        DrawablePtr /*pSrc*/,
-        DrawablePtr /*pDst*/,
-        int /*alu*/,
-        RegionPtr /*prgnDst*/,
-        DDXPointPtr /*pptSrc*/,
-        unsigned long /*planemask*/),
-    unsigned long bitPlane)
-{
-    RegionPtr prgnSrcClip = NULL; /* may be a new region, or just a copy */
-    Bool freeSrcClip = FALSE;
-
-    RegionPtr prgnExposed;
-    RegionRec rgnDst;
-    DDXPointPtr pptSrc;
-    register DDXPointPtr ppt;
-    register BoxPtr pbox;
-    int i;
-    register int dx;
-    register int dy;
-    xRectangle origSource;
-    DDXPointRec origDest;
-    int numRects;
-    BoxRec fastBox;
-    int fastClip = 0;		/* for fast clipping with pixmap source */
-    int fastExpose = 0;		/* for fast exposures with pixmap source */
-
-    origSource.x = srcx;
-    origSource.y = srcy;
-    origSource.width = width;
-    origSource.height = height;
-    origDest.x = dstx;
-    origDest.y = dsty;
-
-    if ((pSrcDrawable != pDstDrawable) &&
-	pSrcDrawable->pScreen->SourceValidate)
-    {
-	(*pSrcDrawable->pScreen->SourceValidate) (pSrcDrawable, srcx, srcy, width, height);
-    }
-
-    srcx += pSrcDrawable->x;
-    srcy += pSrcDrawable->y;
-
-    /* clip the source */
-
-    if (pSrcDrawable->type == DRAWABLE_PIXMAP)
-    {
-	if ((pSrcDrawable == pDstDrawable) &&
-	    (pGC->clientClipType == CT_NONE))
-	{
-	    prgnSrcClip = cfbGetCompositeClip(pGC);
-	}
-	else
-	{
-	    fastClip = 1;
-	}
-    }
-    else
-    {
-	if (pGC->subWindowMode == IncludeInferiors)
-	{
-	    /*
-	     * XFree86 DDX empties the border clip when the
-	     * VT is inactive
-	     */
-	    if (!((WindowPtr) pSrcDrawable)->parent &&
-		REGION_NOTEMPTY (pSrcDrawable->pScreen,
-				 &((WindowPtr) pSrcDrawable)->borderClip))
-	    {
-		/*
-		 * special case bitblt from root window in
-		 * IncludeInferiors mode; just like from a pixmap
-		 */
-		fastClip = 1;
-	    }
-	    else if ((pSrcDrawable == pDstDrawable) &&
-		(pGC->clientClipType == CT_NONE))
-	    {
-		prgnSrcClip = cfbGetCompositeClip(pGC);
-	    }
-	    else
-	    {
-		prgnSrcClip = NotClippedByChildren((WindowPtr)pSrcDrawable);
-		freeSrcClip = TRUE;
-	    }
-	}
-	else
-	{
-	    prgnSrcClip = &((WindowPtr)pSrcDrawable)->clipList;
-	}
-    }
-
-    fastBox.x1 = srcx;
-    fastBox.y1 = srcy;
-    fastBox.x2 = srcx + width;
-    fastBox.y2 = srcy + height;
-
-    /* Don't create a source region if we are doing a fast clip */
-    if (fastClip)
-    {
-	fastExpose = 1;
-	/*
-	 * clip the source; if regions extend beyond the source size,
- 	 * make sure exposure events get sent
-	 */
-	if (fastBox.x1 < pSrcDrawable->x)
-	{
-	    fastBox.x1 = pSrcDrawable->x;
-	    fastExpose = 0;
-	}
-	if (fastBox.y1 < pSrcDrawable->y)
-	{
-	    fastBox.y1 = pSrcDrawable->y;
-	    fastExpose = 0;
-	}
-	if (fastBox.x2 > pSrcDrawable->x + (int) pSrcDrawable->width)
-	{
-	    fastBox.x2 = pSrcDrawable->x + (int) pSrcDrawable->width;
-	    fastExpose = 0;
-	}
-	if (fastBox.y2 > pSrcDrawable->y + (int) pSrcDrawable->height)
-	{
-	    fastBox.y2 = pSrcDrawable->y + (int) pSrcDrawable->height;
-	    fastExpose = 0;
-	}
-    }
-    else
-    {
-	REGION_INIT(pGC->pScreen, &rgnDst, &fastBox, 1);
-	REGION_INTERSECT(pGC->pScreen, &rgnDst, &rgnDst, prgnSrcClip);
-    }
-
-    dstx += pDstDrawable->x;
-    dsty += pDstDrawable->y;
-
-    if (pDstDrawable->type == DRAWABLE_WINDOW)
-    {
-	if (!((WindowPtr)pDstDrawable)->realized)
-	{
-	    if (!fastClip)
-		REGION_UNINIT(pGC->pScreen, &rgnDst);
-	    if (freeSrcClip)
-		REGION_DESTROY(pGC->pScreen, prgnSrcClip);
-	    return NULL;
-	}
-    }
-
-    dx = srcx - dstx;
-    dy = srcy - dsty;
-
-    /* Translate and clip the dst to the destination composite clip */
-    if (fastClip)
-    {
-	RegionPtr cclip;
-
-        /* Translate the region directly */
-        fastBox.x1 -= dx;
-        fastBox.x2 -= dx;
-        fastBox.y1 -= dy;
-        fastBox.y2 -= dy;
-
-	/* If the destination composite clip is one rectangle we can
-	   do the clip directly.  Otherwise we have to create a full
-	   blown region and call intersect */
-
-	/* XXX because CopyPlane uses this routine for 8-to-1 bit
-	 * copies, this next line *must* also correctly fetch the
-	 * composite clip from an mfb gc
-	 */
-
-	cclip = cfbGetCompositeClip(pGC);
-        if (REGION_NUM_RECTS(cclip) == 1)
-        {
-	    BoxPtr pBox = REGION_RECTS(cclip);
-
-	    if (fastBox.x1 < pBox->x1) fastBox.x1 = pBox->x1;
-	    if (fastBox.x2 > pBox->x2) fastBox.x2 = pBox->x2;
-	    if (fastBox.y1 < pBox->y1) fastBox.y1 = pBox->y1;
-	    if (fastBox.y2 > pBox->y2) fastBox.y2 = pBox->y2;
-
-	    /* Check to see if the region is empty */
-	    if (fastBox.x1 >= fastBox.x2 || fastBox.y1 >= fastBox.y2)
-	    {
-		REGION_NULL(pGC->pScreen, &rgnDst);
-	    }
-	    else
-	    {
-		REGION_INIT(pGC->pScreen, &rgnDst, &fastBox, 1);
-	    }
-	}
-        else
-	{
-	    /* We must turn off fastClip now, since we must create
-	       a full blown region.  It is intersected with the
-	       composite clip below. */
-	    fastClip = 0;
-	    REGION_INIT(pGC->pScreen, &rgnDst, &fastBox,1);
-	}
-    }
-    else
-    {
-        REGION_TRANSLATE(pGC->pScreen, &rgnDst, -dx, -dy);
-    }
-
-    if (!fastClip)
-    {
-	REGION_INTERSECT(pGC->pScreen, &rgnDst,
-				   &rgnDst,
-				   cfbGetCompositeClip(pGC));
-    }
-
-    /* Do bit blitting */
-    numRects = REGION_NUM_RECTS(&rgnDst);
-    if (numRects && width && height)
-    {
-	if(!(pptSrc = (DDXPointPtr)xalloc(numRects *
-						  sizeof(DDXPointRec))))
-	{
-	    REGION_UNINIT(pGC->pScreen, &rgnDst);
-	    if (freeSrcClip)
-		REGION_DESTROY(pGC->pScreen, prgnSrcClip);
-	    return NULL;
-	}
-	pbox = REGION_RECTS(&rgnDst);
-	ppt = pptSrc;
-	for (i = numRects; --i >= 0; pbox++, ppt++)
-	{
-	    ppt->x = pbox->x1 + dx;
-	    ppt->y = pbox->y1 + dy;
-	}
-
-	(*doBitBlt) (pSrcDrawable, pDstDrawable, pGC->alu, &rgnDst, pptSrc, pGC->planemask);
-	xfree(pptSrc);
-    }
-
-    prgnExposed = NULL;
-    if (pGC->fExpose)
-    {
-        /* Pixmap sources generate a NoExposed (we return NULL to do this) */
-        if (!fastExpose)
-	    prgnExposed =
-		miHandleExposures(pSrcDrawable, pDstDrawable, pGC,
-				  origSource.x, origSource.y,
-				  (int)origSource.width,
-				  (int)origSource.height,
-				  origDest.x, origDest.y, bitPlane);
-    }
-    REGION_UNINIT(pGC->pScreen, &rgnDst);
-    if (freeSrcClip)
-	REGION_DESTROY(pGC->pScreen, prgnSrcClip);
-    return prgnExposed;
-}
-
-
-RegionPtr
-cfbCopyPlaneReduce (
-    register DrawablePtr pSrcDrawable,
-    register DrawablePtr pDstDrawable,
-    GC *pGC,
-    int srcx, int srcy,
-    int width, int height,
-    int dstx, int dsty,
-    void (*doCopyPlane)(
-        DrawablePtr /*pSrc*/,
-        DrawablePtr /*pDst*/,
-        int /*alu*/,
-        RegionPtr /*prgnDst*/,
-        DDXPointPtr /*pptSrc*/,
-        unsigned long /*planemask*/,
-        unsigned long /*bitPlane*/),
-    unsigned long bitPlane)
-{
-    RegionPtr prgnSrcClip = NULL; /* may be a new region, or just a copy */
-    Bool freeSrcClip = FALSE;
-
-    RegionPtr prgnExposed;
-    RegionRec rgnDst;
-    DDXPointPtr pptSrc;
-    register DDXPointPtr ppt;
-    register BoxPtr pbox;
-    int i;
-    register int dx;
-    register int dy;
-    xRectangle origSource;
-    DDXPointRec origDest;
-    int numRects;
-    BoxRec fastBox;
-    int fastClip = 0;		/* for fast clipping with pixmap source */
-    int fastExpose = 0;		/* for fast exposures with pixmap source */
-
-    origSource.x = srcx;
-    origSource.y = srcy;
-    origSource.width = width;
-    origSource.height = height;
-    origDest.x = dstx;
-    origDest.y = dsty;
-
-    if ((pSrcDrawable != pDstDrawable) &&
-	pSrcDrawable->pScreen->SourceValidate)
-    {
-	(*pSrcDrawable->pScreen->SourceValidate) (pSrcDrawable, srcx, srcy, width, height);
-    }
-
-    srcx += pSrcDrawable->x;
-    srcy += pSrcDrawable->y;
-
-    /* clip the source */
-
-    if (pSrcDrawable->type == DRAWABLE_PIXMAP)
-    {
-	if ((pSrcDrawable == pDstDrawable) &&
-	    (pGC->clientClipType == CT_NONE))
-	{
-	    prgnSrcClip = cfbGetCompositeClip(pGC);
-	}
-	else
-	{
-	    fastClip = 1;
-	}
-    }
-    else
-    {
-	if (pGC->subWindowMode == IncludeInferiors)
-	{
-	    /*
-	     * XFree86 DDX empties the border clip when the
-	     * VT is inactive
-	     */
-	    if (!((WindowPtr) pSrcDrawable)->parent &&
-		REGION_NOTEMPTY (pSrcDrawable->pScreen,
-				 &((WindowPtr) pSrcDrawable)->borderClip))
-	    {
-		/*
-		 * special case bitblt from root window in
-		 * IncludeInferiors mode; just like from a pixmap
-		 */
-		fastClip = 1;
-	    }
-	    else if ((pSrcDrawable == pDstDrawable) &&
-		(pGC->clientClipType == CT_NONE))
-	    {
-		prgnSrcClip = cfbGetCompositeClip(pGC);
-	    }
-	    else
-	    {
-		prgnSrcClip = NotClippedByChildren((WindowPtr)pSrcDrawable);
-		freeSrcClip = TRUE;
-	    }
-	}
-	else
-	{
-	    prgnSrcClip = &((WindowPtr)pSrcDrawable)->clipList;
-	}
-    }
-
-    fastBox.x1 = srcx;
-    fastBox.y1 = srcy;
-    fastBox.x2 = srcx + width;
-    fastBox.y2 = srcy + height;
-
-    /* Don't create a source region if we are doing a fast clip */
-    if (fastClip)
-    {
-	fastExpose = 1;
-	/*
-	 * clip the source; if regions extend beyond the source size,
- 	 * make sure exposure events get sent
-	 */
-	if (fastBox.x1 < pSrcDrawable->x)
-	{
-	    fastBox.x1 = pSrcDrawable->x;
-	    fastExpose = 0;
-	}
-	if (fastBox.y1 < pSrcDrawable->y)
-	{
-	    fastBox.y1 = pSrcDrawable->y;
-	    fastExpose = 0;
-	}
-	if (fastBox.x2 > pSrcDrawable->x + (int) pSrcDrawable->width)
-	{
-	    fastBox.x2 = pSrcDrawable->x + (int) pSrcDrawable->width;
-	    fastExpose = 0;
-	}
-	if (fastBox.y2 > pSrcDrawable->y + (int) pSrcDrawable->height)
-	{
-	    fastBox.y2 = pSrcDrawable->y + (int) pSrcDrawable->height;
-	    fastExpose = 0;
-	}
-    }
-    else
-    {
-	REGION_INIT(pGC->pScreen, &rgnDst, &fastBox, 1);
-	REGION_INTERSECT(pGC->pScreen, &rgnDst, &rgnDst, prgnSrcClip);
-    }
-
-    dstx += pDstDrawable->x;
-    dsty += pDstDrawable->y;
-
-    if (pDstDrawable->type == DRAWABLE_WINDOW)
-    {
-	if (!((WindowPtr)pDstDrawable)->realized)
-	{
-	    if (!fastClip)
-		REGION_UNINIT(pGC->pScreen, &rgnDst);
-	    if (freeSrcClip)
-		REGION_DESTROY(pGC->pScreen, prgnSrcClip);
-	    return NULL;
-	}
-    }
-
-    dx = srcx - dstx;
-    dy = srcy - dsty;
-
-    /* Translate and clip the dst to the destination composite clip */
-    if (fastClip)
-    {
-	RegionPtr cclip;
-
-        /* Translate the region directly */
-        fastBox.x1 -= dx;
-        fastBox.x2 -= dx;
-        fastBox.y1 -= dy;
-        fastBox.y2 -= dy;
-
-	/* If the destination composite clip is one rectangle we can
-	   do the clip directly.  Otherwise we have to create a full
-	   blown region and call intersect */
-
-	/* XXX because CopyPlane uses this routine for 8-to-1 bit
-	 * copies, this next line *must* also correctly fetch the
-	 * composite clip from an mfb gc
-	 */
-
-	cclip = cfbGetCompositeClip(pGC);
-        if (REGION_NUM_RECTS(cclip) == 1)
-        {
-	    BoxPtr pBox = REGION_RECTS(cclip);
-
-	    if (fastBox.x1 < pBox->x1) fastBox.x1 = pBox->x1;
-	    if (fastBox.x2 > pBox->x2) fastBox.x2 = pBox->x2;
-	    if (fastBox.y1 < pBox->y1) fastBox.y1 = pBox->y1;
-	    if (fastBox.y2 > pBox->y2) fastBox.y2 = pBox->y2;
-
-	    /* Check to see if the region is empty */
-	    if (fastBox.x1 >= fastBox.x2 || fastBox.y1 >= fastBox.y2)
-	    {
-		REGION_NULL(pGC->pScreen, &rgnDst);
-	    }
-	    else
-	    {
-		REGION_INIT(pGC->pScreen, &rgnDst, &fastBox, 1);
-	    }
-	}
-        else
-	{
-	    /* We must turn off fastClip now, since we must create
-	       a full blown region.  It is intersected with the
-	       composite clip below. */
-	    fastClip = 0;
-	    REGION_INIT(pGC->pScreen, &rgnDst, &fastBox, 1);
-	}
-    }
-    else
-    {
-        REGION_TRANSLATE(pGC->pScreen, &rgnDst, -dx, -dy);
-    }
-
-    if (!fastClip)
-    {
-	REGION_INTERSECT(pGC->pScreen, &rgnDst,
-				   &rgnDst,
-				   cfbGetCompositeClip(pGC));
-    }
-
-    /* Do bit blitting */
-    numRects = REGION_NUM_RECTS(&rgnDst);
-    if (numRects && width && height)
-    {
-	if(!(pptSrc = (DDXPointPtr)xalloc(numRects *
-						  sizeof(DDXPointRec))))
-	{
-	    REGION_UNINIT(pGC->pScreen, &rgnDst);
-	    if (freeSrcClip)
-		REGION_DESTROY(pGC->pScreen, prgnSrcClip);
-	    return NULL;
-	}
-	pbox = REGION_RECTS(&rgnDst);
-	ppt = pptSrc;
-	for (i = numRects; --i >= 0; pbox++, ppt++)
-	{
-	    ppt->x = pbox->x1 + dx;
-	    ppt->y = pbox->y1 + dy;
-	}
-
-	(*doCopyPlane) (pSrcDrawable, pDstDrawable, pGC->alu, &rgnDst, pptSrc, pGC->planemask, bitPlane);
-	xfree(pptSrc);
-    }
-
-    prgnExposed = NULL;
-    if (pGC->fExpose)
-    {
-        /* Pixmap sources generate a NoExposed (we return NULL to do this) */
-        if (!fastExpose)
-	    prgnExposed =
-		miHandleExposures(pSrcDrawable, pDstDrawable, pGC,
-				  origSource.x, origSource.y,
-				  (int)origSource.width,
-				  (int)origSource.height,
-				  origDest.x, origDest.y, bitPlane);
-    }
-    REGION_UNINIT(pGC->pScreen, &rgnDst);
-    if (freeSrcClip)
-	REGION_DESTROY(pGC->pScreen, prgnSrcClip);
-    return prgnExposed;
-}
-
-
-void
-cfbDoBitblt (pSrc, pDst, alu, prgnDst, pptSrc, planemask)
-    DrawablePtr	    pSrc, pDst;
-    int		    alu;
-    RegionPtr	    prgnDst;
-    DDXPointPtr	    pptSrc;
-    unsigned long   planemask;
-{
-    void (*doBitBlt)(
-        DrawablePtr /*pSrc*/,
-        DrawablePtr /*pDst*/,
-        int /*alu*/,
-        RegionPtr /*prgnDst*/,
-        DDXPointPtr /*pptSrc*/,
-        unsigned long /*planemask*/)
-        = cfbDoBitbltGeneral;
-
-    if ((planemask & PMSK) == PMSK) {
-	switch (alu) {
-	case GXcopy:
-	    doBitBlt = cfbDoBitbltCopy;
-	    break;
-	case GXxor:
-	    doBitBlt = cfbDoBitbltXor;
-	    break;
-	case GXor:
-	    doBitBlt = cfbDoBitbltOr;
-	    break;
-	}
-    }
-    (*doBitBlt) (pSrc, pDst, alu, prgnDst, pptSrc, planemask);
-}
-
-RegionPtr
-cfbCopyArea(pSrcDrawable, pDstDrawable,
-            pGC, srcx, srcy, width, height, dstx, dsty)
-    register DrawablePtr pSrcDrawable;
-    register DrawablePtr pDstDrawable;
-    GC *pGC;
-    int srcx, srcy;
-    int width, height;
-    int dstx, dsty;
-{
-    void (*doBitBlt) (
-        DrawablePtr /*pSrc*/,
-        DrawablePtr /*pDst*/,
-        int /*alu*/,
-        RegionPtr /*prgnDst*/,
-        DDXPointPtr /*pptSrc*/,
-        unsigned long /*planemask*/);
-    
-    doBitBlt = cfbDoBitbltCopy;
-    if (pGC->alu != GXcopy || (pGC->planemask & PMSK) != PMSK)
-    {
-	doBitBlt = cfbDoBitbltGeneral;
-	if ((pGC->planemask & PMSK) == PMSK)
-	{
-	    switch (pGC->alu) {
-	    case GXxor:
-		doBitBlt = cfbDoBitbltXor;
-		break;
-	    case GXor:
-		doBitBlt = cfbDoBitbltOr;
-		break;
-	    }
-	}
-    }
-    return cfbBitBlt (pSrcDrawable, pDstDrawable,
-            pGC, srcx, srcy, width, height, dstx, dsty, doBitBlt, 0L);
-}
-
-#if PSZ == 8
-void
-cfbCopyPlane1to8 (pSrcDrawable, pDstDrawable, rop, prgnDst, pptSrc, planemask)
-    DrawablePtr pSrcDrawable;	/* must be a bitmap */
-    DrawablePtr pDstDrawable;	/* must be depth 8 drawable */
-    int	rop;		/* not used; caller must call cfb8CheckOpaqueStipple
-			 * beforehand to get cfb8StippleRRop set correctly */
-    RegionPtr prgnDst;		/* region in destination to draw to;
-				 * screen relative coords. if dest is a window;
-				 * drawable relative if dest is a pixmap */
-    DDXPointPtr pptSrc;		/* drawable relative src coords to copy from;
-				 * must be one point for each box in prgnDst */
-    unsigned long planemask;	/* to apply to destination writes */
-{
-    int	srcx, srcy;	/* upper left corner of box being copied in source */
-    int dstx, dsty;	/* upper left corner of box being copied in dest */
-    int width, height;	/* in pixels, unpadded, of box being copied */
-    int xoffSrc; /* bit # in leftmost word of row from which copying starts */
-    int xoffDst; /* byte # in leftmost word of row from which copying starts */
-    CfbBits *psrcBase, *pdstBase; /* start of drawable's pixel data */
-    int	widthSrc;    /* # of groups of 32 pixels (1 bit/pixel) in src bitmap*/
-    int widthDst;    /* # of groups of 4 pixels (8 bits/pixel) in dst */
-    CfbBits *psrcLine, *pdstLine; /* steps a row at a time thru src/dst; 
-					 * may point into middle of row */
-    register CfbBits *psrc, *pdst; /* steps within the row */
-    register CfbBits bits, tmp;	 /* bits from source */
-    register int leftShift;
-    register int rightShift;
-    CfbBits startmask;		/* left edge pixel mask */
-    CfbBits endmask;		/* right edge pixel mask */
-    register int nlMiddle;   /* number of words in middle of the row to draw */
-    register int nl;
-    int firstoff = 0;
-    int secondoff = 0;
-    CfbBits src;
-    int nbox;		/* number of boxes in region to copy */
-    BoxPtr  pbox;	/* steps thru boxes in region */
-    int pixelsRemainingOnRightEdge; /* # pixels to be drawn on a row after
-				     * the main "middle" loop */
-
-    cfbGetLongWidthAndPointer (pSrcDrawable, widthSrc, psrcBase)
-    cfbGetLongWidthAndPointer (pDstDrawable, widthDst, pdstBase)
-
-    nbox = REGION_NUM_RECTS(prgnDst);
-    pbox = REGION_RECTS(prgnDst);
-    while (nbox--)
-    {
-	dstx = pbox->x1;
-	dsty = pbox->y1;
-	srcx = pptSrc->x;
-	srcy = pptSrc->y;
-	width = pbox->x2 - pbox->x1;
-	height = pbox->y2 - pbox->y1;
-	pbox++;
-	pptSrc++;
-
-	psrcLine = psrcBase + srcy * widthSrc + (srcx >> MFB_PWSH);
-	pdstLine = pdstBase + dsty * widthDst + (dstx >> PWSH);
-	xoffSrc = srcx & MFB_PIM; /* finds starting bit in src */
-	xoffDst = dstx & PIM;  /* finds starting byte in dst */
-
-	/* compute startmask, endmask, nlMiddle */
-
-	if (xoffDst + width < PPW) /* XXX should this be '<= PPW' ? */
-	{ /* the copy only affects one word per row in destination */
-	    maskpartialbits(dstx, width, startmask);
-	    endmask = 0;  /* nothing on right edge */
-	    nlMiddle = 0; /* nothing in middle */
-	}
-	else
-	{ /* the copy will affect multiple words per row in destination */
-	    maskbits(dstx, width, startmask, endmask, nlMiddle);
-	}
-
-	/*
-	 * compute constants for the first four bits to be
-	 * copied.  This avoids troubles with partial first
-	 * writes, and difficult shift computation
-	 */
-	if (startmask)
-	{
-	    firstoff = xoffSrc - xoffDst;
-	    if (firstoff > (MFB_PPW-PPW))
-		secondoff = MFB_PPW - firstoff;
-	    if (xoffDst)
-	    {
-	    	srcx += (PPW-xoffDst);
-	    	xoffSrc = srcx & MFB_PIM;
-	    }
-	}
-	leftShift = xoffSrc;
-	rightShift = MFB_PPW - leftShift;
-
-	pixelsRemainingOnRightEdge = (nlMiddle & 7) * PPW +
-	    				((dstx + width) & PIM);
-
-	/* setup is done; now let's move some bits */
-
-	/* caller must call cfb8CheckOpaqueStipple before this function
-	 * to set cfb8StippleRRop!
-	 */
-
-	if (cfb8StippleRRop == GXcopy)
-	{
-	    while (height--)
-	    { /* one iteration of this loop copies one row */
-	    	psrc = psrcLine;
-	    	pdst = pdstLine;
-	    	psrcLine += widthSrc;
-	    	pdstLine += widthDst;
-	    	bits = *psrc++;
-	    	if (startmask)
-	    	{
-		    if (firstoff < 0)
-		    	tmp = BitRight (bits, -firstoff);
-		    else
-		    {
-		    	tmp = BitLeft (bits, firstoff);
-			/*
-			 * need a more cautious test for partialmask
-			 * case...
-			 */
-		    	if (firstoff >= (MFB_PPW-PPW))
-		    	{
-			    bits = *psrc++;
-			    if (firstoff != (MFB_PPW-PPW))
-				tmp |= BitRight (bits, secondoff);
-		    	}
-		    }
-		    *pdst = (*pdst & ~startmask) | (GetPixelGroup(tmp) & startmask);
-		    pdst++;
-	    	}
-	    	nl = nlMiddle;
-	    	while (nl >= 8)
-	    	{
-		    nl -= 8;
-		    tmp = BitLeft(bits, leftShift);
-		    bits = *psrc++;
-		    if (rightShift != MFB_PPW)
-		    	tmp |= BitRight(bits, rightShift);
-
-#ifdef FAST_CONSTANT_OFFSET_MODE
-# define StorePixels(pdst,o,pixels)	(pdst)[o] = (pixels)
-# define EndStep(pdst,o)		(pdst) += (o)
-# define StoreRopPixels(pdst,o,and,xor)	(pdst)[o] = DoRRop((pdst)[o],and,xor);
-#else
-# define StorePixels(pdst,o,pixels)	*(pdst)++ = (pixels)
-# define EndStep(pdst,o)
-# define StoreRopPixels(pdst,o,and,xor)	*(pdst) = DoRRop(*(pdst),and,xor); (pdst)++;
-#endif
-
-#define Step(c)			NextBitGroup(c);
-#define StoreBitsPlain(o,c)	StorePixels(pdst,o,GetPixelGroup(c))
-#define StoreRopBitsPlain(o,c)	StoreRopPixels(pdst,o,\
-					cfb8StippleAnd[GetBitGroup(c)], \
-					cfb8StippleXor[GetBitGroup(c)])
-#define StoreBits0(c)		StoreBitsPlain(0,c)
-#define StoreRopBits0(c)	StoreRopBitsPlain(0,c)
-
-#if (BITMAP_BIT_ORDER == MSBFirst)
-# define StoreBits(o,c)	StoreBitsPlain(o,c)
-# define StoreRopBits(o,c)  StoreRopBitsPlain(o,c)
-# define FirstStep(c)	Step(c)
-#else /* BITMAP_BIT_ORDER == LSBFirst */
-#if PGSZ == 64
-# define StoreBits(o,c)	StorePixels(pdst,o, (cfb8Pixels[c & 0xff]))
-# define StoreRopBits(o,c)  StoreRopPixels(pdst,o, \
-    (cfb8StippleAnd[c & 0xff]), \
-    (cfb8StippleXor[c & 0xff]))
-# define FirstStep(c)	c = BitLeft (c, 8);
-#else
-/* 0x3c is 0xf << 2 (4 bits, long word) */
-# define StoreBits(o,c)	StorePixels(pdst,o,*((CfbBits *)\
-			    (((char *) cfb8Pixels) + (c & 0x3c))))
-# define StoreRopBits(o,c)  StoreRopPixels(pdst,o, \
-    *((CfbBits *) (((char *) cfb8StippleAnd) + (c & 0x3c))), \
-    *((CfbBits *) (((char *) cfb8StippleXor) + (c & 0x3c))))
-# define FirstStep(c)	c = BitLeft (c, 2);
-#endif /* PGSZ */
-#endif /* BITMAP_BIT_ORDER */
-
-		    StoreBits0(tmp);	FirstStep(tmp);
-		    StoreBits(1,tmp);	Step(tmp);
-		    StoreBits(2,tmp);	Step(tmp);
-		    StoreBits(3,tmp);	Step(tmp);
-		    StoreBits(4,tmp);	Step(tmp);
-		    StoreBits(5,tmp);	Step(tmp);
-		    StoreBits(6,tmp);	Step(tmp);
-		    StoreBits(7,tmp);   EndStep (pdst,8);
-	    	}
-
-		/* do rest of middle and partial word on right edge */
-
-	    	if (pixelsRemainingOnRightEdge)
-	    	{
-		    tmp = BitLeft(bits, leftShift);
-
-		    if (pixelsRemainingOnRightEdge > rightShift)
-		    {
-		    	bits = *psrc++;
-		    	tmp |= BitRight (bits, rightShift);
-		    }
-		    EndStep (pdst, nl);
-		    switch (nl)
-		    {
-		    case 7:
-			StoreBitsPlain(-7,tmp);	Step(tmp);
-		    case 6:
-			StoreBitsPlain(-6,tmp);	Step(tmp);
-		    case 5:
-			StoreBitsPlain(-5,tmp);	Step(tmp);
-		    case 4:
-			StoreBitsPlain(-4,tmp);	Step(tmp);
-		    case 3:
-			StoreBitsPlain(-3,tmp);	Step(tmp);
-		    case 2:
-			StoreBitsPlain(-2,tmp);	Step(tmp);
-		    case 1:
-			StoreBitsPlain(-1,tmp);	Step(tmp);
-		    }
-		    if (endmask)
-		    	*pdst = (*pdst & ~endmask) | (GetPixelGroup(tmp) & endmask);
-	    	}
-	    }
-	}
-	else /* cfb8StippleRRop != GXcopy */
-	{
-	    while (height--)
-	    { /* one iteration of this loop copies one row */
-	    	psrc = psrcLine;
-	    	pdst = pdstLine;
-	    	psrcLine += widthSrc;
-	    	pdstLine += widthDst;
-	    	bits = *psrc++;
-
-		/* do partial word on left edge */
-
-	    	if (startmask)
-	    	{
-		    if (firstoff < 0)
-		    	tmp = BitRight (bits, -firstoff);
-		    else
-		    {
-		    	tmp = BitLeft (bits, firstoff);
-		    	if (firstoff >= (MFB_PPW-PPW))
-		    	{
-			    bits = *psrc++;
-			    if (firstoff != (MFB_PPW-PPW))
-				tmp |= BitRight (bits, secondoff);
-		    	}
-		    }
-		    src = GetBitGroup(tmp);
-		    *pdst = MaskRRopPixels (*pdst, src, startmask);
-		    pdst++;
-	    	}
-
-		/* do middle of row */
-
-	    	nl = nlMiddle;
-		while (nl >= 8)
-		{
-		    nl -= 8;
-		    tmp = BitLeft(bits, leftShift);
-		    bits = *psrc++;
-		    if (rightShift != MFB_PPW)
-			tmp |= BitRight(bits, rightShift);
-		    StoreRopBits0(tmp);		FirstStep(tmp);
-		    StoreRopBits(1,tmp);	Step(tmp);
-		    StoreRopBits(2,tmp);	Step(tmp);
-		    StoreRopBits(3,tmp);	Step(tmp);
-		    StoreRopBits(4,tmp);	Step(tmp);
-		    StoreRopBits(5,tmp);	Step(tmp);
-		    StoreRopBits(6,tmp);	Step(tmp);
-		    StoreRopBits(7,tmp);	EndStep(pdst,8);
-		}
-
-		/* do rest of middle and partial word on right edge */
-
-	    	if (pixelsRemainingOnRightEdge)
-	    	{
-		    tmp = BitLeft(bits, leftShift);
-
-		    if (pixelsRemainingOnRightEdge > rightShift)
-		    {
-		    	bits = *psrc++; /* XXX purify abr here */
-		    	tmp |= BitRight (bits, rightShift);
-		    }
-		    while (nl--)
-		    {
-			src = GetBitGroup (tmp);
-			*pdst = RRopPixels (*pdst, src);
-		    	pdst++;
-			NextBitGroup(tmp);
-		    }
-		    if (endmask)
-		    {
-			src = GetBitGroup (tmp);
-			*pdst = MaskRRopPixels (*pdst, src, endmask);
-		    }
-	    	}
-	    } /* end copy one row */
-	} /* end alu is non-copy-mode case */
-    } /* end iteration over region boxes */
-}
-
-#else /* PSZ == 8 */
-
-#define mfbmaskbits(x, w, startmask, endmask, nlw) \
-    startmask = mfbGetstarttab((x)&0x1f); \
-    endmask = mfbGetendtab(((x)+(w)) & 0x1f); \
-    if (startmask) \
-	nlw = (((w) - (32 - ((x)&0x1f))) >> 5); \
-    else \
-	nlw = (w) >> 5;
-
-#define mfbmaskpartialbits(x, w, mask) \
-    mask = mfbGetpartmasks((x)&0x1f,(w)&0x1f);
-
-#define LeftMost    0
-#define StepBit(bit, inc)  ((bit) += (inc))
-
-
-#define GetBits(psrc, nBits, curBit, bitPos, bits) {\
-    bits = 0; \
-    while (nBits--) \
-    { \
-	bits |= ((*psrc++ >> bitPos) & 1) << curBit; \
-	StepBit (curBit, 1); \
-    } \
-}
-
-/******************************************************************/
-
-static void
-#if PSZ == 16
-cfbCopyPlane1to16
-#endif
-#if PSZ == 24
-cfbCopyPlane1to24
-#endif
-#if PSZ == 32
-cfbCopyPlane1to32
-#endif
-(
-    DrawablePtr pSrcDrawable,
-    DrawablePtr pDstDrawable,
-    int	rop,
-    RegionPtr prgnDst,
-    DDXPointPtr pptSrc,
-    unsigned long planemask)
-{
-    int	srcx, srcy, dstx, dsty;
-    int width, height;
-    int xoffSrc;
-    CfbBits *psrcBase, *pdstBase;
-    int	widthSrc, widthDst;
-    unsigned int *psrcLine;
-    register unsigned int *psrc;
-#if PSZ == 16
-    unsigned short *pdstLine;
-    register unsigned short *pdst;
-#endif
-#if PSZ == 32
-    unsigned int *pdstLine;
-    register unsigned int *pdst;
-#endif
-#if PSZ == 24
-    unsigned char *pdstLine;
-    register unsigned char *pdst;
-#endif
-    register unsigned int  bits, tmp;
-    register unsigned int  fgpixel, bgpixel;
-    register unsigned int  src;
-#if PSZ == 24
-    register unsigned int  dst;
-#endif
-    register int  leftShift, rightShift;
-    register int  i, nl;
-    int nbox;
-    BoxPtr pbox;
-    int  result;
-
-#if PSZ == 16
-    unsigned int doublet[4];	/* Pixel values for 16bpp expansion. */
-#endif
-#if PSZ == 32
-    unsigned int doublet[8];	/* Pixel values for 32bpp expansion */
-#endif
-
-    fgpixel = FgPixel & planemask;
-    bgpixel = BgPixel & planemask;    
-
-#if PSZ == 16
-    if (rop == GXcopy && (planemask & PMSK) == PMSK) {
-        doublet[0] = bgpixel | (bgpixel << 16);
-        doublet[1] = fgpixel | (bgpixel << 16);
-        doublet[2] = bgpixel | (fgpixel << 16);
-        doublet[3] = fgpixel | (fgpixel << 16);
-    }
-#endif
-#if PSZ == 32
-    if (rop == GXcopy && (planemask & PMSK) == PMSK) {
-        doublet[0] = bgpixel; doublet[1] = bgpixel;
-        doublet[2] = fgpixel; doublet[3] = bgpixel;
-        doublet[4] = bgpixel; doublet[5] = fgpixel;
-        doublet[6] = fgpixel; doublet[7] = fgpixel;
-    }
-#endif
-
-    /* must explicitly ask for "int" widths, as code below expects it */
-    /* on some machines (Alpha), "long" and "int" are not the same size */
-    cfbGetTypedWidthAndPointer (pSrcDrawable, widthSrc, psrcBase, int, CfbBits)
-    cfbGetTypedWidthAndPointer (pDstDrawable, widthDst, pdstBase, int, CfbBits)
-
-#if PSZ == 16
-    widthDst <<= 1;
-#endif
-#if PSZ == 24
-    widthDst <<= 2;
-#endif
-
-    nbox = REGION_NUM_RECTS(prgnDst);
-    pbox = REGION_RECTS(prgnDst);
-
-    while (nbox--)
-    {
-	dstx = pbox->x1;
-	dsty = pbox->y1;
-	srcx = pptSrc->x;
-	srcy = pptSrc->y;
-	width = pbox->x2 - pbox->x1;
-	height = pbox->y2 - pbox->y1;
-	pbox++;
-	pptSrc++;
-	psrcLine = (unsigned int *)psrcBase + srcy * widthSrc + (srcx >> 5);
-#if PSZ == 16
-	pdstLine = (unsigned short *)pdstBase + dsty * widthDst + dstx;
-#endif
-#if PSZ == 24
-	pdstLine = (unsigned char *)pdstBase + dsty * widthDst + dstx * 3;
-#endif
-#if PSZ == 32
-	pdstLine = (unsigned int *)pdstBase + dsty * widthDst + dstx;
-#endif
-	xoffSrc = srcx & 0x1f;
-
-	/*
-	 * compute constants for the first four bits to be
-	 * copied.  This avoids troubles with partial first
-	 * writes, and difficult shift computation
-	 */
-	leftShift = xoffSrc;
-	rightShift = 32 - leftShift;
-
-	if (rop == GXcopy && (planemask & PMSK) == PMSK)
-	{
-	    while (height--)
-	    {
-	        psrc = psrcLine;
-	        pdst = pdstLine;
-	        psrcLine += widthSrc;
-	        pdstLine += widthDst;
-	        bits = *psrc++;
-	        nl = width;
-   	        while (nl >= 32)
-	        {
-		    tmp = BitLeft(bits, leftShift);
-		    bits = *psrc++;
-		    if (rightShift != 32)
-		        tmp |= BitRight(bits, rightShift);
-		    i = 0;
-#if PSZ == 16
-		    /*
-		     * I've thrown in some optimization to at least write
-		     * some aligned 32-bit words instead of 16-bit shorts.
-		     */
-		    if ((unsigned long)psrc & 2) {
-		        /* Write unaligned 16-bit word at left edge. */
-		        if (tmp & 0x01)
-		            *pdst = fgpixel;
-		        else
-		            *pdst = bgpixel;
-		        pdst++;
-		        i++;
-		    }
-		    while (i <= 24)
-		    {
-		        unsigned tmpbits = tmp >> i;
-		        *(unsigned int *)pdst = doublet[tmpbits & 0x03];
-	        	*(unsigned int *)(pdst + 2) =
-		            doublet[(tmpbits >> 2) & 0x03];
-	        	*(unsigned int *)(pdst + 4) =
-		            doublet[(tmpbits >> 4) & 0x03];
-	        	*(unsigned int *)(pdst + 6) =
-		            doublet[(tmpbits >> 6) & 0x03];
-		        pdst += 8;	/* Advance four 32-bit words. */
-		        i += 8;
-		    }
-		    while (i <= 30)
-		    {
-		        *(unsigned int *)pdst =
-		            doublet[(tmp >> i) & 0x03];
-		        pdst += 2;	/* Advance one 32-bit word. */
-		        i += 2;
-		    }
-		    if (i == 31) {
-		        if ((tmp >> 31) & 0x01)
-		            *pdst = fgpixel;
-		        else
-		            *pdst = bgpixel;
-		        pdst++;
-		    }
-#endif		    
-#if PSZ == 24
-		    while (i < 32) {
-		        if ((tmp >> i) & 0x01) {
-		            *pdst = fgpixel;
-		            *(pdst + 1) = fgpixel >> 8;
-		            *(pdst + 2) = fgpixel >> 16;
-		        }
-		        else {
-		            *pdst = bgpixel;
-		            *(pdst + 1) = bgpixel >> 8;
-		            *(pdst + 2) = bgpixel >> 16;
-		        }
-		        pdst += 3;
-		        i++;
-		    }
-#endif
-#if PSZ == 32
-		    while (i <= 28) {
-		        int pair;
-		        pair = (tmp >> i) & 0x03;
-		        *pdst = doublet[pair * 2];
-		        *(pdst + 1) = doublet[pair * 2 + 1];
-		        pair = (tmp >> (i + 2)) & 0x03;
-		        *(pdst + 2) = doublet[pair * 2];
-		        *(pdst + 3) = doublet[pair * 2 + 1];
-		        pdst += 4;
-		        i += 4;
-		    }
-		    while (i < 32) {
-		        *pdst = ((tmp >> i) & 0x01) ? fgpixel : bgpixel;
-		        pdst++;
-		        i++;
-		    }
-#endif
-		    nl -= 32;
-	        }
-
-	        if (nl)
-	        {
-		    tmp = BitLeft(bits, leftShift);
-		    /*
-		     * better condition needed -- mustn't run
-		     * off the end of the source...
-		     */
-		    if (rightShift != 32)
-		    {
-		        bits = *psrc++;
-		        tmp |= BitRight (bits, rightShift);
-		    }
-		    i = 32;
-		    while (nl--)
-		    {
-		        --i;
-#if PSZ == 24
-		        if ((tmp >> (31 - i)) & 0x01) {
-		            *pdst = fgpixel;
-		            *(pdst + 1) = fgpixel >> 8;
-		            *(pdst + 2) = fgpixel >> 16;
-		        }
-		        else {
-		            *pdst = bgpixel;
-		            *(pdst + 1) = bgpixel >> 8;
-		            *(pdst + 2) = bgpixel >> 16;
-		        }
-		        pdst += 3;
-#else
-		        *pdst = ((tmp >> (31 - i)) & 0x01) ? fgpixel : bgpixel;
-		        pdst++;
-#endif
-		    }
-	        }
-            }
-        }
-	else
-	{
-	    while (height--)
-	    {
-	        psrc = psrcLine;
-	        pdst = pdstLine;
-	        psrcLine += widthSrc;
-	        pdstLine += widthDst;
-	        bits = *psrc++;
-	        nl = width;
-   	        while (nl >= 32)
-	        {
-		    tmp = BitLeft(bits, leftShift);
-		    bits = *psrc++;
-		    if (rightShift != 32)
-		        tmp |= BitRight(bits, rightShift);
-		    i = 32;
-		    while (i--)
-		    {
-		        src = ((tmp >> (31 - i)) & 0x01) ? fgpixel : bgpixel;
-#if PSZ == 24
-		        dst = *pdst;
-			dst |= (*(pdst + 1)) << 8;
-			dst |= (*(pdst + 2)) << 16;
-                        DoRop (result, rop, src, dst);
-			*pdst = (dst & ~planemask) |
-		  	        (result & planemask);
-			*(pdst+1) = ((dst & ~planemask) >> 8) |
-		  	        ((result & planemask) >> 8);
-			*(pdst+2) = ((dst & ~planemask) >> 16) |
-		  	        ((result & planemask) >> 16);
-			pdst += 3;
-#else
-                        DoRop (result, rop, src, *pdst);
-
-		        *pdst = (*pdst & ~planemask) |
-		  	        (result & planemask);
-		        pdst++;
-#endif
-		    }
-		    nl -= 32;
-	        }
-
-	        if (nl)
-	        {
-		    tmp = BitLeft(bits, leftShift);
-		    /*
-		     * better condition needed -- mustn't run
-		     * off the end of the source...
-		     */
-		    if (rightShift != 32)
-		    {
-		        bits = *psrc++;
-		        tmp |= BitRight (bits, rightShift);
-		    }
-		    i = 32;
-		    while (nl--)
-		    {
-		        --i;
-		        src = ((tmp >> (31 - i)) & 0x01) ? fgpixel : bgpixel;
-#if PSZ == 24
-		        dst = *pdst;
-			dst |= (*(pdst + 1)) << 8;
-			dst |= (*(pdst + 2)) << 16;
-                        DoRop (result, rop, src, dst);
-			*pdst = (dst & ~planemask) |
-		  	        (result & planemask);
-			*(pdst+1) = ((dst & ~planemask) >> 8) |
-		  	        ((result & planemask) >> 8);
-			*(pdst+2) = ((dst & ~planemask) >> 16) |
-		  	        ((result & planemask) >> 16);
-			pdst += 3;
-#else
-                        DoRop (result, rop, src, *pdst);
-
-		        *pdst = (*pdst & ~planemask) |
-		  	        (result & planemask);
-		        pdst++;
-#endif
-		    }
-	        }
-            }
-        }
-    }
-}
-
-#endif  /* PSZ == 8 */
-
-/* shared among all different cfb depths through linker magic */
-
-RegionPtr cfbCopyPlane(pSrcDrawable, pDstDrawable,
-	    pGC, srcx, srcy, width, height, dstx, dsty, bitPlane)
-    DrawablePtr 	pSrcDrawable;
-    DrawablePtr		pDstDrawable;
-    GCPtr		pGC;
-    int 		srcx, srcy;
-    int 		width, height;
-    int 		dstx, dsty;
-    unsigned long	bitPlane;
-{
-    RegionPtr	ret;
-
-#if IMAGE_BYTE_ORDER == LSBFirst
-
-    void (*doCopyPlaneExpand)(
-        DrawablePtr /*pSrc*/,
-        DrawablePtr /*pDst*/,
-        int /*alu*/,
-        RegionPtr /*prgnDst*/,
-        DDXPointPtr /*pptSrc*/,
-        unsigned long /*planemask*/);
-
-    if (pSrcDrawable->bitsPerPixel == 1 && pDstDrawable->bitsPerPixel == PSZ)
-    {
-    	if (bitPlane == 1)
-	{
-       	    doCopyPlaneExpand = cfbCopyPlane1toN;
-#if PSZ == 8
-	    cfb8CheckOpaqueStipple (pGC->alu,
-				    pGC->fgPixel, pGC->bgPixel,
-				    pGC->planemask);
-#else
-	    FgPixel = pGC->fgPixel;
-	    BgPixel = pGC->bgPixel;
-#endif
-    	    ret = cfbCopyPlaneExpand (pSrcDrawable, pDstDrawable,
-	    	    pGC, srcx, srcy, width, height, dstx, dsty, doCopyPlaneExpand, bitPlane);
-	}
-	else
-	    ret = miHandleExposures (pSrcDrawable, pDstDrawable,
-	    	pGC, srcx, srcy, width, height, dstx, dsty, bitPlane);
-    }
-    else if (pSrcDrawable->bitsPerPixel == PSZ && pDstDrawable->bitsPerPixel == 1)
-    {
-	int oldalu;
-
-	oldalu = pGC->alu;
-    	if ((pGC->fgPixel & 1) == 0 && (pGC->bgPixel&1) == 1)
-	    pGC->alu = mfbGetInverseAlu(pGC->alu);
-    	else if ((pGC->fgPixel & 1) == (pGC->bgPixel & 1))
-	    pGC->alu = mfbReduceRop(pGC->alu, pGC->fgPixel);
-	ret = cfbCopyPlaneReduce(pSrcDrawable, pDstDrawable,
-			 pGC, srcx, srcy, width, height, dstx, dsty, 
-			 cfbCopyPlaneNto1, bitPlane);
-	pGC->alu = oldalu;
-    }
-    else if (pSrcDrawable->bitsPerPixel == PSZ && pDstDrawable->bitsPerPixel == PSZ)
-    {
-	PixmapPtr	pBitmap;
-	ScreenPtr	pScreen = pSrcDrawable->pScreen;
-	GCPtr		pGC1;
-
-	pBitmap = (*pScreen->CreatePixmap) (pScreen, width, height, 1,
-					    CREATE_PIXMAP_USAGE_SCRATCH);
-	if (!pBitmap)
-	    return NULL;
-	pGC1 = GetScratchGC (1, pScreen);
-	if (!pGC1)
-	{
-	    (*pScreen->DestroyPixmap) (pBitmap);
-	    return NULL;
-	}
-	/*
-	 * don't need to set pGC->fgPixel,bgPixel as copyPlaneNto1
-	 * ignores pixel values, expecting the rop to "do the
-	 * right thing", which GXcopy will.
-	 */
-	ValidateGC ((DrawablePtr) pBitmap, pGC1);
-	/* no exposures here, scratch GC's don't get graphics expose */
-	cfbCopyPlaneReduce(pSrcDrawable, (DrawablePtr) pBitmap,
-			  pGC1, srcx, srcy, width, height, 0, 0, 
-			  cfbCopyPlaneNto1, bitPlane);
-#if PSZ == 8
-	cfb8CheckOpaqueStipple (pGC->alu,
-				pGC->fgPixel, pGC->bgPixel,
-				pGC->planemask);
-#else
-	    FgPixel = pGC->fgPixel;
-	    BgPixel = pGC->bgPixel;
-#endif
-	/* no exposures here, copy bits from inside a pixmap */
-	cfbCopyPlaneExpand((DrawablePtr) pBitmap, pDstDrawable, pGC,
-			    0, 0, width, height, dstx, dsty, cfbCopyPlane1toN, 1);
-	FreeScratchGC (pGC1);
-	(*pScreen->DestroyPixmap) (pBitmap);
-	/* compute resultant exposures */
-	ret = miHandleExposures (pSrcDrawable, pDstDrawable, pGC,
-				 srcx, srcy, width, height,
-				 dstx, dsty, bitPlane);
-    }
-    else
-#endif
-	ret = miCopyPlane (pSrcDrawable, pDstDrawable,
-	    pGC, srcx, srcy, width, height, dstx, dsty, bitPlane);
-    return ret;
-}
-
-
diff --git a/cfb/cfbblt.c b/cfb/cfbblt.c
deleted file mode 100644
index ff34589..0000000
--- a/cfb/cfbblt.c
+++ /dev/null
@@ -1,933 +0,0 @@
-/*
- * cfb copy area
- */
-
-/*
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-Author: Keith Packard
-
-*/
-
-/* 24-bit bug fixes: Peter Wainwright, 1998/11/28 */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <stdlib.h>
-
-#include	<X11/X.h>
-#include	<X11/Xmd.h>
-#include	<X11/Xproto.h>
-#include	"gcstruct.h"
-#include	"windowstr.h"
-#include	"scrnintstr.h"
-#include	"pixmapstr.h"
-#include	"regionstr.h"
-#include	"cfb.h"
-#include	"cfbmskbits.h"
-#include	"cfb8bit.h"
-#include	"fastblt.h"
-#include	"mergerop.h"
-
-#ifdef notdef /* XXX fails right now, walks off end of pixmaps */
-#if defined (FAST_UNALIGNED_READS) && PSZ == 8
-#define DO_UNALIGNED_BITBLT
-#endif
-#endif
-
-#if defined(FAST_MEMCPY) && (MROP == Mcopy) && PSZ == 8
-#define DO_MEMCPY
-#endif
-
-/* ................................................. */
-/* SPECIAL CODE FOR 24 BITS      by Peter Wainwright */
-
-#if PSZ == 24 && (MROP) == 0
-
-/* The default macros are defined in mergerop.h, and none of them are
-   really appropriate for what we want to do.
-
-   There are two ways of fixing this: either define SLOW_24BIT_COPY
-   to copy pixel by pixel, or (by default) use the following macros
-   modified from mergerop.h
-
-   MROP_SOLID and MROP_MASK are defined for each of the operations,
-   i.e. each value of MROP.
-
-   There are special cases for Mcopy, McopyInverted, Mxor, and Mor.
-   There is a completely generic version for MROP=0, and a simplified
-   generic version which works for (Mcopy|Mxor|MandReverse|Mor).
-
-   However, the generic version does not work for the 24-bit case
-   because the pixels cannot be packed exactly into a machine word (32
-   bits).
-
-   Alternative macros MROP_SOLID24 and MROP_MASK24 are provided for
-   the 24-bit case. However, these each copy a single *pixel*, not a
-   single machine word. They take an rvalue source pixel, an lvalue
-   destination, and the pixel index. The latter is used to find the
-   position of the pixel data within the two words *dst and *(dst+1).
-
-   Further macros MROP_SOLID24P and MROP_MASK24P are used to copy from
-   an lvalue source to an lvalue destination. MROP_PIXEL24 is used to
-   assemble the source pixel from the adjacent words *src and
-   *(src+1), and this is then split between the destination words
-   using the non-P macros above.
-
-   But we want to copy entire words for the sake of efficiency.
-   Unfortunately if a plane mask is specified this must be shifted
-   from one word to the next.  Fortunately the pattern repeats after 3
-   words, so we unroll the planemask here and redefine MROP_SOLID
-   and MROP_MASK. */
-
-
-#endif /* MROP == 0 && PSZ == 24 */
-
-/* ................................................. */
-
-#if PSZ == 24
-#define BYPP 3
-#if PGSZ == 32
-#define P3W 4 /* pixels in 3 machine words */
-#define PAM 3 /* pixel align mask; PAM = P3W -1 */
-#define P2WSH 2
-#else
-#define P3W 8 /* pixels in 3 machine words */
-#define PAM 7 /* pixel align mask; PAM = P3W -1 */
-#define P2WSH 3
-#endif
-#endif
-
-void
-MROP_NAME(cfbDoBitblt)(
-    DrawablePtr	    pSrc, 
-    DrawablePtr	    pDst,
-    int		    alu,
-    RegionPtr	    prgnDst,
-    DDXPointPtr	    pptSrc,
-    unsigned long   planemask)
-{
-    CfbBits *psrcBase, *pdstBase;	
-				/* start of src and dst bitmaps */
-    int widthSrc, widthDst;	/* add to get to same position in next line */
-
-    BoxPtr pbox;
-    int nbox;
-
-    BoxPtr pboxTmp, pboxNext, pboxBase, pboxNew1, pboxNew2;
-				/* temporaries for shuffling rectangles */
-    DDXPointPtr pptTmp, pptNew1, pptNew2;
-				/* shuffling boxes entails shuffling the
-				   source points too */
-    int w, h;
-    int xdir;			/* 1 = left right, -1 = right left/ */
-    int ydir;			/* 1 = top down, -1 = bottom up */
-
-    CfbBits *psrcLine, *pdstLine;	
-				/* pointers to line with current src and dst */
-    register CfbBits *psrc;/* pointer to current src longword */
-    register CfbBits *pdst;/* pointer to current dst longword */
-
-    MROP_DECLARE_REG()
-
-				/* following used for looping through a line */
-    CfbBits startmask, endmask;	/* masks for writing ends of dst */
-    int nlMiddle;		/* whole longwords in dst */
-    int xoffSrc, xoffDst;
-    register int nl;		/* temp copy of nlMiddle */
-    int careful;
-
-#if (PSZ != 24) || (MROP != 0)
-    register int leftShift, rightShift;
-    register CfbBits bits;
-    register CfbBits bits1;
-#endif
-
-#if PSZ == 24
-#ifdef DO_MEMCPY
-    int w2;
-#endif
-
-#if MROP == 0
-    int widthSrcBytes = cfbGetByteWidth(pSrc);
-    int widthDstBytes = cfbGetByteWidth(pDst);
-#endif
-#endif
-
-    MROP_INITIALIZE(alu,planemask)
-
-    cfbGetLongWidthAndPointer (pSrc, widthSrc, psrcBase)
-
-    cfbGetLongWidthAndPointer (pDst, widthDst, pdstBase)
-
-    /* XXX we have to err on the side of safety when both are windows,
-     * because we don't know if IncludeInferiors is being used.
-     */
-    careful = ((pSrc == pDst) ||
-	       ((pSrc->type == DRAWABLE_WINDOW) &&
-		(pDst->type == DRAWABLE_WINDOW)));
-
-    pbox = REGION_RECTS(prgnDst);
-    nbox = REGION_NUM_RECTS(prgnDst);
-
-    pboxNew1 = NULL;
-    pptNew1 = NULL;
-    pboxNew2 = NULL;
-    pptNew2 = NULL;
-    if (careful && (pptSrc->y < pbox->y1))
-    {
-        /* walk source botttom to top */
-	ydir = -1;
-	widthSrc = -widthSrc;
-	widthDst = -widthDst;
-
-	if (nbox > 1)
-	{
-	    /* keep ordering in each band, reverse order of bands */
-	    pboxNew1 = (BoxPtr)xalloc(sizeof(BoxRec) * nbox);
-	    if(!pboxNew1)
-		return;
-	    pptNew1 = (DDXPointPtr)xalloc(sizeof(DDXPointRec) * nbox);
-	    if(!pptNew1)
-	    {
-	        xfree(pboxNew1);
-	        return;
-	    }
-	    pboxBase = pboxNext = pbox+nbox-1;
-	    while (pboxBase >= pbox)
-	    {
-	        while ((pboxNext >= pbox) &&
-		       (pboxBase->y1 == pboxNext->y1))
-		    pboxNext--;
-	        pboxTmp = pboxNext+1;
-	        pptTmp = pptSrc + (pboxTmp - pbox);
-	        while (pboxTmp <= pboxBase)
-	        {
-		    *pboxNew1++ = *pboxTmp++;
-		    *pptNew1++ = *pptTmp++;
-	        }
-	        pboxBase = pboxNext;
-	    }
-	    pboxNew1 -= nbox;
-	    pbox = pboxNew1;
-	    pptNew1 -= nbox;
-	    pptSrc = pptNew1;
-        }
-    }
-    else
-    {
-	/* walk source top to bottom */
-	ydir = 1;
-    }
-
-    if (careful && (pptSrc->x < pbox->x1))
-    {
-	/* walk source right to left */
-        xdir = -1;
-
-	if (nbox > 1)
-	{
-	    /* reverse order of rects in each band */
-	    pboxNew2 = (BoxPtr)xalloc(sizeof(BoxRec) * nbox);
-	    pptNew2 = (DDXPointPtr)xalloc(sizeof(DDXPointRec) * nbox);
-	    if(!pboxNew2 || !pptNew2)
-	    {
-		if (pptNew2) xfree(pptNew2);
-		if (pboxNew2) xfree(pboxNew2);
-		if (pboxNew1)
-		{
-		    xfree(pptNew1);
-		    xfree(pboxNew1);
-		}
-	        return;
-	    }
-	    pboxBase = pboxNext = pbox;
-	    while (pboxBase < pbox+nbox)
-	    {
-	        while ((pboxNext < pbox+nbox) &&
-		       (pboxNext->y1 == pboxBase->y1))
-		    pboxNext++;
-	        pboxTmp = pboxNext;
-	        pptTmp = pptSrc + (pboxTmp - pbox);
-	        while (pboxTmp != pboxBase)
-	        {
-		    *pboxNew2++ = *--pboxTmp;
-		    *pptNew2++ = *--pptTmp;
-	        }
-	        pboxBase = pboxNext;
-	    }
-	    pboxNew2 -= nbox;
-	    pbox = pboxNew2;
-	    pptNew2 -= nbox;
-	    pptSrc = pptNew2;
-	}
-    }
-    else
-    {
-	/* walk source left to right */
-        xdir = 1;
-    }
-
-    while(nbox--)
-    {
-	w = pbox->x2 - pbox->x1;
-	h = pbox->y2 - pbox->y1;
-
-#if PSZ == 24
-#ifdef DO_MEMCPY
-	w2 = w * BYPP;
-#endif
-#endif
-	if (ydir == -1) /* start at last scanline of rectangle */
-	{
-	    psrcLine = psrcBase + ((pptSrc->y+h-1) * -widthSrc);
-	    pdstLine = pdstBase + ((pbox->y2-1) * -widthDst);
-	}
-	else /* start at first scanline */
-	{
-	    psrcLine = psrcBase + (pptSrc->y * widthSrc);
-	    pdstLine = pdstBase + (pbox->y1 * widthDst);
-	}
-#if PSZ == 24
-	if (w == 1 && ((pbox->x1 & PAM) == 0  ||  (pbox->x1 & PAM) == PAM))
-#else
-	if ((pbox->x1 & PIM) + w <= PPW)
-#endif
-	{
-	    maskpartialbits (pbox->x1, w, endmask);
-	    startmask = 0;
-	    nlMiddle = 0;
-	}
-	else
-	{
-	    maskbits(pbox->x1, w, startmask, endmask, nlMiddle);
-	}
-
-#if PSZ == 24
-#if 0
-	nlMiddle = w - (pbox->x2 &PAM);;
-	if(pbox->x1 & PAM){
-	  nlMiddle -= (PAM+1 - (pbox->x1 &PAM));
-	}
-	nlMiddle >>= P2WSH;
-	if(nlMiddle < 0)
-	  nlMiddle = 0;
-#endif
-#endif
-
-#ifdef DO_MEMCPY
-	/* If the src and dst scanline don't overlap, do forward case.  */
-
-	if ((xdir == 1) || (pptSrc->y != pbox->y1)
-		|| (pptSrc->x + w <= pbox->x1))
-	{
-#if PSZ == 24
-	    char *psrc = (char *) psrcLine + (pptSrc->x * BYPP);
-	    char *pdst = (char *) pdstLine + (pbox->x1 * BYPP);
-#else
-	    char *psrc = (char *) psrcLine + pptSrc->x;
-	    char *pdst = (char *) pdstLine + pbox->x1;
-#endif
-	    while (h--)
-	    {
-#if PSZ == 24
-	    	memcpy(pdst, psrc, w2);
-#else
-	    	memcpy(pdst, psrc, w);
-#endif
-		pdst += widthDst << PWSH;
-		psrc += widthSrc << PWSH;
-	    }
-	}
-#else /* ! DO_MEMCPY */
-	if (xdir == 1)
-	{
-#if PSZ == 24 && MROP == 0
-	    /* Note: x is a pixel number; the byte offset is 3*x;
-	       therefore the offset within a word is (3*x) & 3 ==
-	       (4*x-x) & 3 == (-x) & 3.  The offsets therefore
-	       DECREASE by 1 for each pixel.
-	    */
-	  xoffSrc = ( - pptSrc->x) & PAM;
-	  xoffDst = ( - pbox->x1) & PAM;
-#if 1
-	  if((int)xoffSrc != (int)xoffDst /* Alignments must be same. */
-	     || ((widthDstBytes & PAM) != (widthSrcBytes & PAM) && h > 1))
-#else
-	    if(1)
-#endif
-	    /* Width also must be same, if hight > 1 */
-	    {
-	      /* ...otherwise, pixel by pixel operation */
-	  while (h--)
-	    {
-	      register int i, si, sii, di;
-
-	      for (i = 0, si = pptSrc->x, di = pbox->x1;
-		   i < w;
-		   i++, si++, di++) {
-		    psrc = psrcLine + ((si * BYPP) >> P2WSH);
-		    pdst = pdstLine + ((di * BYPP) >> P2WSH);
-		sii = (si & 3);
-		MROP_SOLID24P(psrc, pdst, sii, di);
-	      }
-	      pdstLine += widthDst;
-	      psrcLine += widthSrc;
-	    }
-	  }
-	  else
-#endif
-	  {
-
-#if PSZ == 24
-
-#if MROP != 0
-	    xoffSrc = ( - pptSrc->x) & PAM;
-	    xoffDst = ( - pbox->x1) & PAM;
-#endif
-	    pdstLine += (pbox->x1 * BYPP) >> P2WSH;
-	    psrcLine += (pptSrc->x * BYPP) >> P2WSH;
-#else
-	    xoffSrc = pptSrc->x & PIM;
-	    xoffDst = pbox->x1 & PIM;
-	    pdstLine += (pbox->x1 >> PWSH);
-	    psrcLine += (pptSrc->x >> PWSH);
-#endif
-#ifdef DO_UNALIGNED_BITBLT
-	    nl = xoffSrc - xoffDst;
-	    psrcLine = (CfbBits *)
-			(((unsigned char *) psrcLine) + nl);
-#else
-#if PSZ == 24 && MROP == 0
-	    /* alredy satisfied */
-#else
-	    if (xoffSrc == xoffDst)
-#endif
-#endif
-	    {
-		while (h--)
-		{
-#if PSZ == 24 && MROP == 0
-		    register int index;
-		    register int im3;
-#endif /*  PSZ == 24 && MROP == 0 */
-		    psrc = psrcLine;
-		    pdst = pdstLine;
-		    pdstLine += widthDst;
-		    psrcLine += widthSrc;
-#if PSZ == 24 && MROP == 0
-		    index = (int)(pdst - pdstBase);
-		    im3 = index % 3;
-#endif /*  PSZ == 24 && MROP == 0 */
-		    if (startmask)
-		    {
-#if PSZ == 24 && MROP == 0
-		      	*pdst = DoMaskMergeRop24u(*psrc, *pdst, startmask, im3);
-			index++;
-			im3 = index % 3;
-#else /* PSZ != 24 || MROP != 0 */
-			*pdst = MROP_MASK(*psrc, *pdst, startmask);
-#endif /*  PSZ == 24 && MROP == 0 */
-			psrc++;
-			pdst++;
-		    }
-
-		    nl = nlMiddle;
-#ifdef LARGE_INSTRUCTION_CACHE
-#ifdef FAST_CONSTANT_OFFSET_MODE
-
-		    psrc += nl & (UNROLL-1);
-		    pdst += nl & (UNROLL-1);
-
-#if PSZ == 24 && MROP == 0
-#define BodyOdd(n) pdst[-n] = DoMergeRop24u(psrc[-n], pdst[-n], ((int)(pdst - n - pdstBase))%3);
-#define BodyEven(n) pdst[-n] = DoMergeRop24u(psrc[-n], pdst[-n], ((int)(pdst - n - pdstBase))%3);
-#else /* PSZ != 24 || MROP != 0 */
-#define BodyOdd(n) pdst[-n] = MROP_SOLID (psrc[-n], pdst[-n]);
-#define BodyEven(n) pdst[-n] = MROP_SOLID (psrc[-n], pdst[-n]);
-#endif /*  PSZ == 24 && MROP == 0 */
-
-#define LoopReset \
-pdst += UNROLL; \
-psrc += UNROLL;
-
-#else
-
-#if PSZ == 24 && MROP == 0
-#define BodyOdd(n)  *pdst = DoMergeRop24u(*psrc, *pdst, im3); pdst++; psrc++; index++; im3 = index % 3;
-#define BodyEven(n) BodyOdd(n)
-#else /* PSZ != 24 || MROP != 0 */
-#define BodyOdd(n)  *pdst = MROP_SOLID (*psrc, *pdst); pdst++; psrc++;
-#define BodyEven(n) BodyOdd(n)
-#endif /*  PSZ == 24 && MROP == 0 */
-
-#define LoopReset   ;
-
-#endif
-		    PackedLoop
-
-#undef BodyOdd
-#undef BodyEven
-#undef LoopReset
-
-#else
-#ifdef NOTDEF
-		    /* you'd think this would be faster --
-		     * a single instruction instead of 6
-		     * but measurements show it to be ~15% slower
-		     */
-		    while ((nl -= 6) >= 0)
-		    {
-			asm ("moveml %1+,#0x0c0f;moveml#0x0c0f,%0"
-			     : "=m" (*(char *)pdst)
-			     : "m" (*(char *)psrc)
-			     : "d0", "d1", "d2", "d3",
-			       "a2", "a3");
-			pdst += 6;
-		    }
-		    nl += 6;
-		    while (nl--)
-			*pdst++ = *psrc++;
-#endif
-#if 0 /*PSZ == 24 && MROP == 0*/
-		    DuffL(nl, label1,
-			    *pdst = DoMergeRop24u(*psrc, *pdst, im3);
-			    pdst++; psrc++; index++;im3 = index % 3;)
-#else /* !(PSZ == 24 && MROP == 0) */
-		    DuffL(nl, label1,
-			    *pdst = MROP_SOLID (*psrc, *pdst);
-			    pdst++; psrc++;)
-#endif /* PSZ == 24 && MROP == 0 */
-#endif
-
-		    if (endmask)
-#if PSZ == 24 && MROP == 0
-			*pdst = DoMaskMergeRop24u(*psrc, *pdst, endmask, (int)(pdst - pdstBase) % 3);
-#else /* !(PSZ == 24 && MROP == 0) */
-			*pdst = MROP_MASK(*psrc, *pdst, endmask);
-#endif /* PSZ == 24 && MROP == 0 */
-		}
-	    }
-#ifndef DO_UNALIGNED_BITBLT
-#if PSZ == 24 && MROP == 0
-		/* can not happen */ 
-#else /* !(PSZ == 24 && MROP == 0) */
-	    else /* xoffSrc != xoffDst */
-	    {
-		if (xoffSrc > xoffDst)
-		{
-#if PSZ == 24
-		    leftShift = (xoffSrc - xoffDst) << 3;
-#else
-#if PGSZ == 32
-		    leftShift = (xoffSrc - xoffDst) << (5 - PWSH);
-#else /* PGSZ == 64 */
-		    leftShift = (xoffSrc - xoffDst) << (6 - PWSH);
-#endif /* PGSZ */
-#endif
-		    rightShift = PGSZ - leftShift;
-		}
-		else
-		{
-#if PSZ == 24
-		    rightShift = (xoffDst - xoffSrc) << 3;
-#else
-#if PGSZ == 32
-		    rightShift = (xoffDst - xoffSrc) << (5 - PWSH);
-#else /* PGSZ == 64 */
-		    rightShift = (xoffDst - xoffSrc) << (6 - PWSH);
-#endif /* PGSZ */
-#endif
-		    leftShift = PGSZ - rightShift;
-		}
-		while (h--)
-		{
-		    psrc = psrcLine;
-		    pdst = pdstLine;
-		    pdstLine += widthDst;
-		    psrcLine += widthSrc;
-		    bits = 0;
-		    if (xoffSrc > xoffDst)
-			bits = *psrc++;
-		    if (startmask)
-		    {
-			bits1 = BitLeft(bits,leftShift);
-			bits = *psrc++;
-			bits1 |= BitRight(bits,rightShift);
-			*pdst = MROP_MASK(bits1, *pdst, startmask);
-			pdst++;
-		    }
-		    nl = nlMiddle;
-#ifdef LARGE_INSTRUCTION_CACHE
-		    bits1 = bits;
-
-#ifdef FAST_CONSTANT_OFFSET_MODE
-
-		    psrc += nl & (UNROLL-1);
-		    pdst += nl & (UNROLL-1);
-
-#define BodyOdd(n) \
-bits = psrc[-n]; \
-pdst[-n] = MROP_SOLID(BitLeft(bits1, leftShift) | BitRight(bits, rightShift), pdst[-n]);
-
-#define BodyEven(n) \
-bits1 = psrc[-n]; \
-pdst[-n] = MROP_SOLID(BitLeft(bits, leftShift) | BitRight(bits1, rightShift), pdst[-n]);
-
-#define LoopReset \
-pdst += UNROLL; \
-psrc += UNROLL;
-
-#else
-
-#define BodyOdd(n) \
-bits = *psrc++; \
-*pdst = MROP_SOLID(BitLeft(bits1, leftShift) | BitRight(bits, rightShift), *pdst); \
-pdst++;
-		   
-#define BodyEven(n) \
-bits1 = *psrc++; \
-*pdst = MROP_SOLID(BitLeft(bits, leftShift) | BitRight(bits1, rightShift), *pdst); \
-pdst++;
-
-#define LoopReset   ;
-
-#endif	/* !FAST_CONSTANT_OFFSET_MODE */
-
-		    PackedLoop
-
-#undef BodyOdd
-#undef BodyEven
-#undef LoopReset
-
-#else
-		    DuffL (nl,label2,
-			bits1 = BitLeft(bits, leftShift);
-			bits = *psrc++;
-			*pdst = MROP_SOLID (bits1 | BitRight(bits, rightShift), *pdst);
-			pdst++;
-		    )
-#endif
-
-		    if (endmask)
-		    {
-			bits1 = BitLeft(bits, leftShift);
-			if (BitLeft(endmask, rightShift))
-			{
-			    bits = *psrc;
-			    bits1 |= BitRight(bits, rightShift);
-			}
-			*pdst = MROP_MASK (bits1, *pdst, endmask);
-		    }
-		}
-	    }
-#endif /* (PSZ == 24 && MROP == 0) */
-#endif /* DO_UNALIGNED_BITBLT */
-
-	  }
-	}
-#endif /* ! DO_MEMCPY */
-	else	/* xdir == -1 */
-	{
-#if PSZ == 24 && MROP == 0
-	  xoffSrc = (-(pptSrc->x + w)) & PAM;
-	  xoffDst = (-pbox->x2) & PAM;
-#if 1
-	  if(xoffSrc != xoffDst /* Alignments must be same. */
-	     || ((widthDstBytes & PAM) != (widthSrcBytes & PAM) && h > 1))
-#else
-	    if(1)
-#endif
-	    /* Width also must be same, if hight > 1 */
-	    {
-	      /* ...otherwise, pixel by pixel operation */
-	  while (h--)
-	    {
-	      register int i, si, sii, di;
-
-		    for (i = 0, si = pptSrc->x + w - 1, di = pbox->x2 - 1;
-		   i < w;
-			 i++, si--, di--) {
-		      psrc = psrcLine + ((si * BYPP) >> P2WSH);
-		      pdst = pdstLine + ((di * BYPP) >> P2WSH);
-		      sii = (si & PAM);
-		MROP_SOLID24P(psrc, pdst, sii, di);
-	      }
-	      psrcLine += widthSrc;
-	      pdstLine += widthDst;
-	    }
-	  }else
-#endif /* MROP == 0 && PSZ == 24 */
-	    {
-
-#if PSZ == 24
-#if MROP == 0
-	      /* already calculated */
-#else
-	    xoffSrc = (pptSrc->x + w) & PAM;
-	    xoffDst = pbox->x2 & PAM;
-#endif
-	    pdstLine += ((pbox->x2 * BYPP - 1) >> P2WSH) + 1;
-	    psrcLine += (((pptSrc->x+w) * BYPP - 1) >> P2WSH) + 1;
-#else
-	    xoffSrc = (pptSrc->x + w - 1) & PIM;
-	    xoffDst = (pbox->x2 - 1) & PIM;
-	    pdstLine += ((pbox->x2-1) >> PWSH) + 1;
-	    psrcLine += ((pptSrc->x+w - 1) >> PWSH) + 1;
-#endif
-#ifdef DO_UNALIGNED_BITBLT
-#if PSZ == 24
-	    nl = xoffDst - xoffSrc;
-#else
-	    nl = xoffSrc - xoffDst;
-#endif
-	    psrcLine = (CfbBits *)
-			(((unsigned char *) psrcLine) + nl);
-#else
-#if PSZ == 24 && MROP == 0
-	    /* already satisfied */
-#else
-	    if (xoffSrc == xoffDst)
-#endif
-#endif
-	    {
-		while (h--)
-		{
-#if PSZ == 24 && MROP == 0
-		    register int index;
-		    register int im3;
-#endif /*  PSZ == 24 && MROP == 0 */
-		    psrc = psrcLine;
-		    pdst = pdstLine;
-		    pdstLine += widthDst;
-		    psrcLine += widthSrc;
-#if PSZ == 24 && MROP == 0
-		    index = (int)(pdst - pdstBase);
-#endif /*  PSZ == 24 && MROP == 0 */
-
-		    if (endmask)
-		    {
-			pdst--;
-			psrc--;
-#if PSZ == 24 && MROP == 0
-			index--;
-			im3 = index % 3;
-			*pdst = DoMaskMergeRop24u(*psrc, *pdst, endmask, im3);
-#else /* !(PSZ == 24 && MROP == 0) */
-			*pdst = MROP_MASK (*psrc, *pdst, endmask);
-#endif /* PSZ == 24 && MROP == 0 */
-		    }
-		    nl = nlMiddle;
-#ifdef LARGE_INSTRUCTION_CACHE
-#ifdef FAST_CONSTANT_OFFSET_MODE
-		    psrc -= nl & (UNROLL - 1);
-		    pdst -= nl & (UNROLL - 1);
-
-#if PSZ == 24 && MROP == 0
-#define BodyOdd(n) pdst[n-1] = DoMergeRop24u(psrc[n-1], pdst[n-1], ((int)(pdst - (n - 1) -pdstBase)) % 3);
-#else /* !(PSZ == 24 && MROP == 0) */
-#define BodyOdd(n) pdst[n-1] = MROP_SOLID (psrc[n-1], pdst[n-1]);
-#endif /* PSZ == 24 && MROP == 0 */
-
-#define BodyEven(n) BodyOdd(n)
-
-#define LoopReset \
-pdst -= UNROLL;\
-psrc -= UNROLL;
-
-#else
-
-#if PSZ == 24 && MROP == 0
-#define BodyOdd(n)  --pdst; --psrc; --index; im3 = index % 3;*pdst = DoMergeRop24u(*psrc, *pdst, im3);
-#else /* !(PSZ == 24 && MROP == 0) */
-#define BodyOdd(n)  --pdst; --psrc; *pdst = MROP_SOLID(*psrc, *pdst);
-#endif /* PSZ == 24 && MROP == 0 */
-#define BodyEven(n) BodyOdd(n)
-#define LoopReset   ;
-
-#endif
-		    PackedLoop
-
-#undef BodyOdd
-#undef BodyEven
-#undef LoopReset
-
-#else
-#if PSZ == 24 && MROP == 0
-		    DuffL(nl,label3,
-			  --pdst; --psrc; --index; im3= index%3;*pdst = DoMergeRop24u(*psrc, *pdst, im3);)
-#else /* !(PSZ == 24 && MROP == 0) */
-		    DuffL(nl,label3,
-			 --pdst; --psrc; *pdst = MROP_SOLID (*psrc, *pdst);)
-#endif /* PSZ == 24 && MROP == 0 */
-#endif
-
-		    if (startmask)
-		    {
-			--pdst;
-			--psrc;
-#if PSZ == 24 && MROP == 0
-			*pdst = DoMaskMergeRop24u(*psrc, *pdst, startmask, (int)(pdst - pdstBase) % 3);
-#else /* !(PSZ == 24 && MROP == 0) */
-			*pdst = MROP_MASK(*psrc, *pdst, startmask);
-#endif /* PSZ == 24 && MROP == 0 */
-		    }
-		}
-	    }
-#ifndef DO_UNALIGNED_BITBLT
-#if PSZ == 24 && MROP == 0
-	    /* can not happen */
-#else /* !( PSZ == 24 && MROP == 0) */
-	    else
-	    {
-		if (xoffDst > xoffSrc)
-		{
-#if PSZ == 24
-		    leftShift = (xoffDst - xoffSrc) << 3;
-		    rightShift = PGSZ - leftShift;
-#else
-#if PGSZ == 32
-		    rightShift = (xoffDst - xoffSrc) << (5 - PWSH);
-#else /* PGSZ == 64 */
-		    rightShift = (xoffDst - xoffSrc) << (6 - PWSH);
-#endif /* PGSZ */
-		    leftShift = PGSZ - rightShift;
-#endif
-		}
-		else
-		{
-#if PSZ == 24
-		    rightShift = (xoffSrc - xoffDst) << 3;
-		    leftShift = PGSZ - rightShift;
-#else
-#if PGSZ == 32
-		    leftShift = (xoffSrc - xoffDst) << (5 - PWSH);
-#else /* PGSZ == 64 */
-		    leftShift = (xoffSrc - xoffDst) << (6 - PWSH);
-#endif /* PGSZ */
-		    rightShift = PGSZ - leftShift;
-#endif
-		}
-		while (h--)
-		{
-		    psrc = psrcLine;
-		    pdst = pdstLine;
-		    pdstLine += widthDst;
-		    psrcLine += widthSrc;
-		    bits = 0;
-#if PSZ == 24
-		    if (xoffSrc > xoffDst)
-#else
-		    if (xoffDst > xoffSrc)
-#endif
-			bits = *--psrc;
-		    if (endmask)
-		    {
-			bits1 = BitRight(bits, rightShift);
-			bits = *--psrc;
-			bits1 |= BitLeft(bits, leftShift);
-			pdst--;
-			*pdst = MROP_MASK(bits1, *pdst, endmask);
-		    }
-		    nl = nlMiddle;
-#ifdef LARGE_INSTRUCTION_CACHE
-		    bits1 = bits;
-#ifdef FAST_CONSTANT_OFFSET_MODE
-		    psrc -= nl & (UNROLL - 1);
-		    pdst -= nl & (UNROLL - 1);
-
-#define BodyOdd(n) \
-bits = psrc[n-1]; \
-pdst[n-1] = MROP_SOLID(BitRight(bits1, rightShift) | BitLeft(bits, leftShift),pdst[n-1]);
-
-#define BodyEven(n) \
-bits1 = psrc[n-1]; \
-pdst[n-1] = MROP_SOLID(BitRight(bits, rightShift) | BitLeft(bits1, leftShift),pdst[n-1]);
-
-#define LoopReset \
-pdst -= UNROLL; \
-psrc -= UNROLL;
-
-#else
-
-#define BodyOdd(n) \
-bits = *--psrc; --pdst; \
-*pdst = MROP_SOLID(BitRight(bits1, rightShift) | BitLeft(bits, leftShift),*pdst);
-
-#define BodyEven(n) \
-bits1 = *--psrc; --pdst; \
-*pdst = MROP_SOLID(BitRight(bits, rightShift) | BitLeft(bits1, leftShift),*pdst);
-
-#define LoopReset   ;
-
-#endif
-
-		    PackedLoop
-
-#undef BodyOdd
-#undef BodyEven
-#undef LoopReset
-
-#else
-		    DuffL (nl, label4,
-			bits1 = BitRight(bits, rightShift);
-			bits = *--psrc;
-			--pdst;
-			*pdst = MROP_SOLID(bits1 | BitLeft(bits, leftShift),*pdst);
-		    )
-#endif
-
-		    if (startmask)
-		    {
-			bits1 = BitRight(bits, rightShift);
-			if (BitRight (startmask, leftShift))
-			{
-			    bits = *--psrc;
-			    bits1 |= BitLeft(bits, leftShift);
-			}
-			--pdst;
-			*pdst = MROP_MASK(bits1, *pdst, startmask);
-		    }
-		}
-	    }
-#endif  /* PSZ == 24 && MROP == 0 */
-#endif
-	    }
-	}
-	pbox++;
-	pptSrc++;
-    }
-    if (pboxNew2)
-    {
-	xfree(pptNew2);
-	xfree(pboxNew2);
-    }
-    if (pboxNew1)
-    {
-	xfree(pptNew1);
-	xfree(pboxNew1);
-    }
-}
diff --git a/cfb/cfbbres.c b/cfb/cfbbres.c
deleted file mode 100644
index fa1ee13..0000000
--- a/cfb/cfbbres.c
+++ /dev/null
@@ -1,340 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include "misc.h"
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "servermd.h"
-#include "miline.h"
-
-/* Solid bresenham line */
-/* NOTES
-   e2 is used less often than e1, so it's not in a register
-*/
-
-void
-cfbBresS(rop, and, xor, addrl, nlwidth, signdx, signdy, axis, x1, y1, e, e1,
-	 e2, len)
-    int		    rop;
-    CfbBits   and, xor;
-    CfbBits   *addrl;		/* pointer to base of bitmap */
-    int		    nlwidth;		/* width in longwords of bitmap */
-    register int    signdx;
-    int		    signdy;		/* signs of directions */
-    int		    axis;		/* major axis (Y_AXIS or X_AXIS) */
-    int		    x1, y1;		/* initial point */
-    register int    e;			/* error accumulator */
-    register int    e1;			/* bresenham increments */
-    int		    e2;
-    int		    len;		/* length of line */
-{
-    register int	e3 = e2-e1;
-#if PSZ == 24
-    CfbBits piQxelXor[3],piQxelAnd[3];
-    char *addrb;
-    int nlwidth3, signdx3;
-#endif
-#ifdef PIXEL_ADDR
-    register PixelType	*addrp;		/* Pixel pointer */
-
-    if (len == 0)
-    	return;
-    /* point to first point */
-    nlwidth <<= PWSH;
-#if PSZ == 24
-    addrp = (PixelType *)(addrl) + (y1 * nlwidth);
-    addrb = (char *)addrp + x1 * 3;
-
-    piQxelXor[0] = (xor << 24) | xor;
-    piQxelXor[1] = (xor << 16)| (xor >> 8);
-    piQxelXor[2] = (xor << 8) | (xor >> 16);
-    piQxelAnd[0] = (and << 24) | and;
-    piQxelAnd[1] = (and << 16)| (and >> 8);
-    piQxelAnd[2] = (and << 8) | (and >> 16);
-#else
-    addrp = (PixelType *)(addrl) + (y1 * nlwidth) + x1;
-#endif
-    if (signdy < 0)
-    	nlwidth = -nlwidth;
-    e = e-e1;			/* to make looping easier */
-#if PSZ == 24
-    nlwidth3 = nlwidth * sizeof (CfbBits);
-    signdx3 = signdx * 3;
-#endif
-    
-    if (axis == Y_AXIS)
-    {
-	int	t;
-
-	t = nlwidth;
-	nlwidth = signdx;
-	signdx = t;
-#if PSZ == 24
-	t = nlwidth3;
-	nlwidth3 = signdx3;
-	signdx3 = t;
-#endif
-    }
-    if (rop == GXcopy)
-    {
-	--len;
-#if PSZ == 24
-#define body_copy \
-	    addrp = (PixelType *)((unsigned long)addrb & ~0x03); \
-	    switch((unsigned long)addrb & 3){ \
-	    case 0: \
-	      *addrp = ((*addrp)&0xFF000000)|(piQxelXor[0] & 0xFFFFFF); \
-	      break; \
-	    case 1: \
-	      *addrp = ((*addrp)&0xFF)|(piQxelXor[2] & 0xFFFFFF00); \
-	      break; \
-	    case 3: \
-	      *addrp = ((*addrp)&0xFFFFFF)|(piQxelXor[0] & 0xFF000000); \
-	      *(addrp+1) = ((*(addrp+1))&0xFFFF0000)|(piQxelXor[1] & 0xFFFF); \
-	      break; \
-	    case 2: \
-	      *addrp = ((*addrp)&0xFFFF)|(piQxelXor[1] & 0xFFFF0000); \
-	      *(addrp+1) = ((*(addrp+1))&0xFFFFFF00)|(piQxelXor[2] & 0xFF); \
-	      break; \
-	    }
-#define body {\
-	    body_copy \
-	    addrb += signdx3; \
-	    e += e1; \
-	    if (e >= 0) \
-	    { \
-		addrb += nlwidth3; \
-		e += e3; \
-	     } \
-	    }
-#else /* PSZ == 24 */
-#define body {\
-	    *addrp = xor; \
-	    addrp += signdx; \
-	    e += e1; \
-	    if (e >= 0) \
-	    { \
-		addrp += nlwidth; \
-		e += e3; \
-	    } \
-	}
-#endif /* PSZ == 24 */
-	while (len >= 4)
-	{
-	    body body body body
-	    len -= 4;
-	}
-	switch (len)
-	{
-	case  3: body case  2: body case  1: body
-	}
-#undef body
-#if PSZ == 24
-	body_copy
-# undef body_copy
-#else
-	*addrp = xor;
-#endif
-    }
-    else /* not GXcopy */
-    {
-	while(len--)
-	{ 
-#if PSZ == 24
-	    addrp = (PixelType *)((unsigned long)addrb & ~0x03);
-	    switch((unsigned long)addrb & 3){
-	    case 0:
-	      *addrp = (*addrp & (piQxelAnd[0]|0xFF000000))
-			^ (piQxelXor[0] & 0xFFFFFF);
-	      break;
-	    case 1:
-	      *addrp = (*addrp & (piQxelAnd[2]|0xFF))
-			^ (piQxelXor[2] & 0xFFFFFF00);
-	      break;
-	    case 3:
-	      *addrp = (*addrp & (piQxelAnd[0]|0xFFFFFF))
-			^ (piQxelXor[0] & 0xFF000000);
-	      *(addrp+1) = (*(addrp+1) & (piQxelAnd[1]|0xFFFF0000))
-			^ (piQxelXor[1] & 0xFFFF);
-	      break;
-	    case 2:
-	      *addrp = (*addrp & (piQxelAnd[1]|0xFFFF))
-			^ (piQxelXor[1] & 0xFFFF0000);
-	      *(addrp+1) = (*(addrp+1) & (piQxelAnd[2]|0xFFFFFF00))
-			^ (piQxelXor[2] & 0xFF);
-	      break;
-	    }
-	    e += e1;
-	    if (e >= 0)
-	    {
-		addrb += nlwidth3;
-		e += e3;
-	    }
-	    addrb += signdx3;
-#else /* PSZ == 24 */
-	    *addrp = DoRRop (*addrp, and, xor);
-	    e += e1;
-	    if (e >= 0)
-	    {
-		addrp += nlwidth;
-		e += e3;
-	    }
-	    addrp += signdx;
-#endif /* PSZ == 24 */
-	}
-    }
-#else /* !PIXEL_ADDR */
-    register CfbBits   tmp, bit;
-    CfbBits leftbit, rightbit;
-
-    /* point to longword containing first point */
-#if PSZ == 24
-    addrl = (addrl + (y1 * nlwidth) + ((x1 * 3) >>2);
-#else
-    addrl = (addrl + (y1 * nlwidth) + (x1 >> PWSH));
-#endif
-    if (signdy < 0)
-	    nlwidth = -nlwidth;
-    e = e-e1;			/* to make looping easier */
-
-    leftbit = cfbmask[0];
-#if PSZ == 24
-    rightbit = cfbmask[(PPW-1)<<1];
-    bit = cfbmask[(x1 & 3)<<1];
-#else
-    rightbit = cfbmask[PPW-1];
-    bit = cfbmask[x1 & PIM];
-#endif
-
-    if (axis == X_AXIS)
-    {
-	if (signdx > 0)
-	{
-	    while (len--)
-	    { 
-		*addrl = DoMaskRRop (*addrl, and, xor, bit);
-		bit = SCRRIGHT(bit,1);
-		e += e1;
-		if (e >= 0)
-		{
-		    addrl += nlwidth;
-		    e += e3;
-		}
-		if (!bit)
-		{
-		    bit = leftbit;
-		    addrl++;
-		}
-	    }
-	}
-	else
-	{
-	    while (len--)
-	    { 
-		*addrl = DoMaskRRop (*addrl, and, xor, bit);
-		e += e1;
-		bit = SCRLEFT(bit,1);
-		if (e >= 0)
-		{
-		    addrl += nlwidth;
-		    e += e3;
-		}
-		if (!bit)
-		{
-		    bit = rightbit;
-		    addrl--;
-		}
-	    }
-	}
-    } /* if X_AXIS */
-    else
-    {
-	if (signdx > 0)
-	{
-	    while(len--)
-	    {
-		*addrl = DoMaskRRop (*addrl, and, xor, bit);
-		e += e1;
-		if (e >= 0)
-		{
-		    bit = SCRRIGHT(bit,1);
-		    if (!bit)
-		    {
-			bit = leftbit;
-			addrl++;
-		    }
-		    e += e3;
-		}
-		addrl += nlwidth;
-	    }
-	}
-	else
-	{
-	    while(len--)
-	    {
-		*addrl = DoMaskRRop (*addrl, and, xor, bit);
-		e += e1;
-		if (e >= 0)
-		{
-		    bit = SCRLEFT(bit,1);
-		    if (!bit)
-		    {
-			bit = rightbit;
-			addrl--;
-		    }
-		    e += e3;
-		}
-		addrl += nlwidth;
-	    }
-	}
-    } /* else Y_AXIS */
-#endif
-}
diff --git a/cfb/cfbbresd.c b/cfb/cfbbresd.c
deleted file mode 100644
index ee48a74..0000000
--- a/cfb/cfbbresd.c
+++ /dev/null
@@ -1,404 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include "misc.h"
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "miline.h"
-
-/* Dashed bresenham line */
-
-void
-cfbBresD(rrops,
-	 pdashIndex, pDash, numInDashList, pdashOffset, isDoubleDash,
-	 addrl, nlwidth,
-	 signdx, signdy, axis, x1, y1, e, e1, e2, len)
-    cfbRRopPtr	    rrops;
-    int		    *pdashIndex;	/* current dash */
-    unsigned char   *pDash;		/* dash list */
-    int		    numInDashList;	/* total length of dash list */
-    int		    *pdashOffset;	/* offset into current dash */
-    int		    isDoubleDash;
-    CfbBits   *addrl;		/* pointer to base of bitmap */
-    int		    nlwidth;		/* width in longwords of bitmap */
-    int		    signdx, signdy;	/* signs of directions */
-    int		    axis;		/* major axis (Y_AXIS or X_AXIS) */
-    int		    x1, y1;		/* initial point */
-    register int    e;			/* error accumulator */
-    register int    e1;			/* bresenham increments */
-    int		    e2;
-    int		    len;		/* length of line */
-{
-#ifdef PIXEL_ADDR
-    register PixelType	*addrp;
-#endif
-    register		int e3 = e2-e1;
-    int			dashIndex;
-    int			dashOffset;
-    int			dashRemaining;
-    CfbBits	xorFg, andFg, xorBg, andBg;
-    Bool		isCopy;
-    int			thisDash;
-#if PSZ == 24
-    CfbBits xorPiQxlFg[3], andPiQxlFg[3], xorPiQxlBg[3], andPiQxlBg[3]; 
-    char *addrb;
-    int signdx3, signdy3;
-#endif
-
-    dashOffset = *pdashOffset;
-    dashIndex = *pdashIndex;
-    isCopy = (rrops[0].rop == GXcopy && rrops[1].rop == GXcopy);
-#if PSZ == 24
-    xorFg = rrops[0].xor & 0xffffff;
-    andFg = rrops[0].and & 0xffffff;
-    xorBg = rrops[1].xor & 0xffffff;
-    andBg = rrops[1].and & 0xffffff;
-    xorPiQxlFg[0] = xorFg | (xorFg << 24);
-    xorPiQxlFg[1] = (xorFg >> 8) | (xorFg << 16);
-    xorPiQxlFg[2] = (xorFg >> 16) | (xorFg << 8);
-    andPiQxlFg[0] = andFg | (andFg << 24);
-    andPiQxlFg[1] = (andFg >> 8) | (andFg << 16);
-    andPiQxlFg[2] = (andFg >> 16) | (andFg << 8);
-    xorPiQxlBg[0] = xorBg | (xorBg << 24);
-    xorPiQxlBg[1] = (xorBg >> 8) | (xorBg << 16);
-    xorPiQxlBg[2] = (xorBg >> 16) | (xorBg << 8);
-    andPiQxlBg[0] = andBg | (andBg << 24);
-    andPiQxlBg[1] = (andBg >> 8) | (andBg << 16);
-    andPiQxlBg[2] = (andFg >> 16) | (andBg << 8);
-#else
-    xorFg = rrops[0].xor;
-    andFg = rrops[0].and;
-    xorBg = rrops[1].xor;
-    andBg = rrops[1].and;
-#endif
-    dashRemaining = pDash[dashIndex] - dashOffset;
-    if ((thisDash = dashRemaining) >= len)
-    {
-	thisDash = len;
-	dashRemaining -= len;
-    }
-    e = e-e1;			/* to make looping easier */
-
-#define BresStep(minor,major) {if ((e += e1) >= 0) { e += e3; minor; } major;}
-
-#define NextDash {\
-    dashIndex++; \
-    if (dashIndex == numInDashList) \
-	dashIndex = 0; \
-    dashRemaining = pDash[dashIndex]; \
-    if ((thisDash = dashRemaining) >= len) \
-    { \
-	dashRemaining -= len; \
-	thisDash = len; \
-    } \
-}
-
-#ifdef PIXEL_ADDR
-
-#if PSZ == 24
-#define Loop(store) while (thisDash--) {\
-			store; \
- 			BresStep(addrb+=signdy3,addrb+=signdx3) \
-		    }
-    /* point to first point */
-    nlwidth <<= PWSH;
-    addrp = (PixelType *)(addrl) + (y1 * nlwidth);
-    addrb = (char *)addrp + x1 * 3;
-
-#else
-#define Loop(store) while (thisDash--) {\
-			store; \
- 			BresStep(addrp+=signdy,addrp+=signdx) \
-		    }
-    /* point to first point */
-    nlwidth <<= PWSH;
-    addrp = (PixelType *)(addrl) + (y1 * nlwidth) + x1;
-#endif
-    signdy *= nlwidth;
-#if PSZ == 24
-    signdx3 = signdx * 3;
-    signdy3 = signdy * sizeof (CfbBits);
-#endif
-    if (axis == Y_AXIS)
-    {
-	int t;
-
-	t = signdx;
-	signdx = signdy;
-	signdy = t;
-#if PSZ == 24
-	t = signdx3;
-	signdx3 = signdy3;
-	signdy3 = t;
-#endif
-    }
-
-    if (isCopy)
-    {
-#if PSZ == 24
-#define body_copy(pix) { \
-	addrp = (PixelType *)((unsigned long)addrb & ~0x03); \
-	switch((unsigned long)addrb & 3){ \
-	case 0: \
-	  *addrp = (*addrp & 0xFF000000)|((pix)[0] & 0xFFFFFF); \
-	  break; \
-	case 1: \
-	  *addrp = (*addrp & 0xFF)|((pix)[2] & 0xFFFFFF00); \
-	  break; \
-	case 3: \
-	  *addrp = (*addrp & 0xFFFFFF)|((pix)[0] & 0xFF000000); \
-	  *(addrp+1) = (*(addrp+1) & 0xFFFF0000)|((pix)[1] & 0xFFFF); \
-	  break; \
-	case 2: \
-	  *addrp = (*addrp & 0xFFFF)|((pix)[1] & 0xFFFF0000); \
-	  *(addrp+1) = (*(addrp+1) & 0xFFFFFF00)|((pix)[2] & 0xFF); \
-	  break; \
-	} \
-}
-#endif /* PSZ == 24 */
-		    
-	for (;;)
-	{ 
-	    len -= thisDash;
-	    if (dashIndex & 1) {
-		if (isDoubleDash) {
-#if PSZ == 24
-		    Loop(body_copy(xorPiQxlBg))
-#else
-		    Loop(*addrp = xorBg)
-#endif
-		} else {
-		    Loop(;)
-		}
-	    } else {
-#if PSZ == 24
-		Loop(body_copy(xorPiQxlFg))
-#else
-		Loop(*addrp = xorFg)
-#endif
-	    }
-	    if (!len)
-		break;
-	    NextDash
-	}
-#undef body_copy
-    }
-    else
-    {
-#define body_set(and, xor) { \
-	addrp = (PixelType *)((unsigned long)addrb & ~0x03); \
-	switch((unsigned long)addrb & 3){ \
-	case 0: \
-	  *addrp = (*addrp & ((and)[0]|0xFF000000)) ^ ((xor)[0] & 0xFFFFFF); \
-	  break; \
-	case 1: \
-	  *addrp = (*addrp & ((and)[2]|0xFF)) ^ ((xor)[2] & 0xFFFFFF00); \
-	  break; \
-	case 3: \
-	  *addrp = (*addrp & ((and)[0]|0xFFFFFF)) ^ ((xor)[0] & 0xFF000000); \
-	  *(addrp+1)=(*(addrp+1)&((and)[1]|0xFFFF0000)) ^ ((xor)[1]&0xFFFF); \
-	  break; \
-	case 2: \
-	  *addrp = (*addrp & ((and)[1]|0xFFFF)) ^ ((xor)[1] & 0xFFFF0000); \
-	  *(addrp+1)=(*(addrp+1)&((and)[2]|0xFFFFFF00)) ^ ((xor)[2] & 0xFF); \
-	  break; \
-	} \
-}
-
-	for (;;)
-	{ 
-	    len -= thisDash;
-	    if (dashIndex & 1) {
-		if (isDoubleDash) {
-#if PSZ == 24
-		    Loop(body_set(andPiQxlBg, xorPiQxlBg))
-#else
-		    Loop(*addrp = DoRRop(*addrp,andBg, xorBg))
-#endif
-		} else {
-		    Loop(;)
-		}
-	    } else {
-#if PSZ == 24
-		Loop(body_set(andPiQxlFg, xorPiQxlFg))
-#else
-		Loop(*addrp = DoRRop(*addrp,andFg, xorFg))
-#endif
-	    }
-	    if (!len)
-		break;
-	    NextDash
-	}
-#undef body_set
-    }
-#else /* !PIXEL_ADDR */
-    {
-    	register CfbBits	tmp;
-	CfbBits		startbit, bit;
-
-    	/* point to longword containing first point */
-#if PSZ == 24
-    	addrl = (addrl + (y1 * nlwidth) + ((x1*3) >> 2);
-#else
-    	addrl = (addrl + (y1 * nlwidth) + (x1 >> PWSH));
-#endif
-    	signdy = signdy * nlwidth;
-
-	if (signdx > 0)
-	    startbit = cfbmask[0];
-	else
-#if PSZ == 24
-	    startbit = cfbmask[(PPW-1)<<1];
-    	bit = cfbmask[(x1 & 3)<<1];
-#else
-	    startbit = cfbmask[PPW-1];
-    	bit = cfbmask[x1 & PIM];
-#endif
-
-#if PSZ == 24
-#define X_Loop(store)	while(thisDash--) {\
-			    store; \
-		    	    BresStep(addrl += signdy, \
-		    	     	     if (signdx > 0) \
-		    	     	     	 bit = SCRRIGHT(bit,1); \
-		    	     	     else \
-		    	     	     	 bit = SCRLEFT(bit,1); \
-		    	     	     if (!bit) \
-		    	     	     { \
-		    	     	     	 bit = startbit; \
-		    	     	     	 addrl += signdx; \
-		    	     	     }) \
-			}
-#define Y_Loop(store)	while(thisDash--) {\
-			    store; \
-		    	    BresStep(if (signdx > 0) \
-		    	     	     	 bit = SCRRIGHT(bit,1); \
-		    	     	     else \
-		    	     	     	 bit = SCRLEFT(bit,1); \
-		    	     	     if (!bit) \
-		    	     	     { \
-		    	     	     	 bit = startbit; \
-		    	     	     	 addrl += signdx; \
-		    	     	     }, \
-				     addrl += signdy) \
-			}
-#else
-#define X_Loop(store)	while(thisDash--) {\
-			    store; \
-		    	    BresStep(addrl += signdy, \
-		    	     	     if (signdx > 0) \
-		    	     	     	 bit = SCRRIGHT(bit,1); \
-		    	     	     else \
-		    	     	     	 bit = SCRLEFT(bit,1); \
-		    	     	     if (!bit) \
-		    	     	     { \
-		    	     	     	 bit = startbit; \
-		    	     	     	 addrl += signdx; \
-		    	     	     }) \
-			}
-#define Y_Loop(store)	while(thisDash--) {\
-			    store; \
-		    	    BresStep(if (signdx > 0) \
-		    	     	     	 bit = SCRRIGHT(bit,1); \
-		    	     	     else \
-		    	     	     	 bit = SCRLEFT(bit,1); \
-		    	     	     if (!bit) \
-		    	     	     { \
-		    	     	     	 bit = startbit; \
-		    	     	     	 addrl += signdx; \
-		    	     	     }, \
-				     addrl += signdy) \
-			}
-#endif
-
-    	if (axis == X_AXIS)
-    	{
-	    for (;;)
-	    {
-	    	len -= thisDash;
-	    	if (dashIndex & 1) {
-		    if (isDoubleDash) {
-		    	X_Loop(*addrl = DoMaskRRop(*addrl, andBg, xorBg, bit));
-		    } else {
-		    	X_Loop(;)
-		    }
-	    	} else {
-		    X_Loop(*addrl = DoMaskRRop(*addrl, andFg, xorFg, bit));
-	    	}
-	    	if (!len)
-		    break;
-	    	NextDash
-	    }
-    	} /* if X_AXIS */
-    	else
-    	{
-	    for (;;)
-	    {
-	    	len -= thisDash;
-	    	if (dashIndex & 1) {
-		    if (isDoubleDash) {
-		    	Y_Loop(*addrl = DoMaskRRop(*addrl, andBg, xorBg, bit));
-		    } else {
-		    	Y_Loop(;)
-		    }
-	    	} else {
-		    Y_Loop(*addrl = DoMaskRRop(*addrl, andFg, xorFg, bit));
-	    	}
-	    	if (!len)
-		    break;
-	    	NextDash
-	    }
-    	} /* else Y_AXIS */
-    }
-#endif
-    *pdashIndex = dashIndex;
-    *pdashOffset = pDash[dashIndex] - dashRemaining;
-}
diff --git a/cfb/cfbcmap.c b/cfb/cfbcmap.c
deleted file mode 100644
index b96f671..0000000
--- a/cfb/cfbcmap.c
+++ /dev/null
@@ -1,119 +0,0 @@
-/************************************************************
-Copyright 1987 by Sun Microsystems, Inc. Mountain View, CA.
-
-                    All Rights Reserved
-
-Permission  to  use,  copy,  modify,  and  distribute   this
-software  and  its documentation for any purpose and without
-fee is hereby granted, provided that the above copyright no-
-tice  appear  in all copies and that both that copyright no-
-tice and this permission notice appear in  supporting  docu-
-mentation,  and  that the names of Sun or The Open Group
-not be used in advertising or publicity pertaining to 
-distribution  of  the software  without specific prior 
-written permission. Sun and The Open Group make no 
-representations about the suitability of this software for 
-any purpose. It is provided "as is" without any express or 
-implied warranty.
-
-SUN DISCLAIMS ALL WARRANTIES WITH REGARD TO  THIS  SOFTWARE,
-INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
-NESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SUN BE  LI-
-ABLE  FOR  ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,  DATA  OR
-PROFITS,  WHETHER  IN  AN  ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
-THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-********************************************************/
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include "scrnintstr.h"
-#include "colormapst.h"
-#include "resource.h"
-#include "micmap.h"
-#include "cfb.h"
-
-int
-cfbListInstalledColormaps(ScreenPtr pScreen, Colormap *pmaps)
-{
-    return miListInstalledColormaps(pScreen, pmaps);
-}
-
-void
-cfbInstallColormap(ColormapPtr pmap)
-{
-    miInstallColormap(pmap);
-}
-
-void
-cfbUninstallColormap(ColormapPtr pmap)
-{
-    miUninstallColormap(pmap);
-}
-
-void
-cfbResolveColor(unsigned short *pred, 
-		unsigned short *pgreen,
-		unsigned short *pblue,
-		VisualPtr	pVisual)
-{
-    miResolveColor(pred, pgreen, pblue, pVisual);
-}
-
-Bool
-cfbInitializeColormap(ColormapPtr pmap)
-{
-    return miInitializeColormap(pmap);
-}
-
-int
-cfbExpandDirectColors (ColormapPtr pmap, int ndef, 
-		       xColorItem *indefs, xColorItem *outdefs)
-{
-    return miExpandDirectColors(pmap, ndef, indefs, outdefs);
-}
-
-Bool
-cfbCreateDefColormap(ScreenPtr pScreen)
-{
-    return miCreateDefColormap(pScreen);
-}
-
-void
-cfbClearVisualTypes(void)
-{
-    miClearVisualTypes();
-}
-
-Bool
-cfbSetVisualTypes (int depth, int visuals, int bitsPerRGB)
-{
-    return miSetVisualTypes(depth, visuals, bitsPerRGB, -1);
-}
-
-/*
- * Given a list of formats for a screen, create a list
- * of visuals and depths for the screen which coorespond to
- * the set which can be used with this version of cfb.
- */
-
-Bool
-cfbInitVisuals (VisualPtr   *visualp,
-		DepthPtr    *depthp,
-		int	    *nvisualp,
-		int	    *ndepthp,
-		int	    *rootDepthp,
-		VisualID    *defaultVisp,
-		unsigned long	sizes,
-		int	    bitsPerRGB)
-{
-    return miInitVisuals(visualp, depthp, nvisualp, ndepthp, rootDepthp,
-			 defaultVisp, sizes, bitsPerRGB, -1);
-}
diff --git a/cfb/cfbcppl.c b/cfb/cfbcppl.c
deleted file mode 100644
index 00714cb..0000000
--- a/cfb/cfbcppl.c
+++ /dev/null
@@ -1,486 +0,0 @@
-/*
-Copyright 1990, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <string.h>
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "gcstruct.h"
-#include "window.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "windowstr.h"
-#include "cfb.h"
-#if PSZ == 8
-#undef   PSZ /* for maskbits.h */
-#include "maskbits.h"
-#define PSZ 8
-#include "mergerop.h"
-#endif
-
-
-void
-cfbCopyImagePlane(
-    DrawablePtr pSrcDrawable,
-    DrawablePtr pDstDrawable,
-    int	rop,
-    RegionPtr prgnDst,
-    DDXPointPtr pptSrc,
-    unsigned long planemask)
-{
-    /* note: there must be some sort of trick behind,
-       passing a planemask value with all bits set
-       whilst using the current planemask for the bitPlane value. */
-#if PSZ == 8
-    cfbCopyPlane8to1 (pSrcDrawable, pDstDrawable, rop, prgnDst, pptSrc,
-		      (unsigned long) ~0L, planemask);
-#endif
-#if PSZ == 16
-    cfbCopyPlane16to1 (pSrcDrawable, pDstDrawable, rop, prgnDst, pptSrc,
-		      (unsigned long) ~0L, planemask);
-#endif
-#if PSZ == 24
-    cfbCopyPlane24to1 (pSrcDrawable, pDstDrawable, rop, prgnDst, pptSrc,
-		      (unsigned long) ~0L, planemask);
-#endif
-#if PSZ == 32
-    cfbCopyPlane32to1 (pSrcDrawable, pDstDrawable, rop, prgnDst, pptSrc,
-		      (unsigned long) ~0L, planemask);
-#endif
-}
-
-#if PSZ == 8
-
-#if BITMAP_BIT_ORDER == MSBFirst
-#define LeftMost    (MFB_PPW-1)
-#define StepBit(bit, inc)  ((bit) -= (inc))
-#else
-#define LeftMost    0
-#define StepBit(bit, inc)  ((bit) += (inc))
-#endif
-
-#define GetBits(psrc, nBits, curBit, bitPos, bits) {\
-    bits = 0; \
-    while (nBits--) \
-    { \
-	bits |= (PixelType)(((*psrc++ >> bitPos) & 1)) << curBit; \
-	StepBit (curBit, 1); \
-    } \
-}
-
-void
-cfbCopyPlane8to1(
-    DrawablePtr pSrcDrawable,
-    DrawablePtr pDstDrawable,
-    int	rop,
-    RegionPtr prgnDst,
-    DDXPointPtr pptSrc,
-    unsigned long planemask,
-    unsigned long bitPlane)
-{
-    int			    srcx, srcy, dstx, dsty, width, height;
-    unsigned char	    *psrcBase;
-    PixelType		    *pdstBase;
-    int			    widthSrc, widthDst;
-    unsigned char	    *psrcLine;
-    PixelType		    *pdstLine;
-    register unsigned char  *psrc;
-    register int	    i;
-    register int	    curBit;
-    register int	    bitPos;
-    register CfbBits  bits;
-    register PixelType	    *pdst;
-    PixelType		    startmask, endmask;
-    int			    niStart = 0, niEnd = 0;
-    int			    bitStart = 0, bitEnd = 0;
-    int			    nl, nlMiddle;
-    int			    nbox;
-    BoxPtr		    pbox;
-    MROP_DECLARE()
-
-    if (!(planemask & 1))
-	return;
-
-    if (rop != GXcopy)
-	MROP_INITIALIZE (rop, planemask);
-
-    cfbGetByteWidthAndPointer (pSrcDrawable, widthSrc, psrcBase)
-
-    mfbGetPixelWidthAndPointer (pDstDrawable, widthDst, pdstBase)
-
-    bitPos = ffs (bitPlane) - 1;
-
-    nbox = REGION_NUM_RECTS(prgnDst);
-    pbox = REGION_RECTS(prgnDst);
-    while (nbox--)
-    {
-	dstx = pbox->x1;
-	dsty = pbox->y1;
-	srcx = pptSrc->x;
-	srcy = pptSrc->y;
-	width = pbox->x2 - pbox->x1;
-	height = pbox->y2 - pbox->y1;
-	pbox++;
-	pptSrc++;
-	psrcLine = psrcBase + srcy * widthSrc + srcx;
-	pdstLine = mfbScanline(pdstBase, dstx, dsty, widthDst);
-	dstx &= MFB_PIM;
-	if (dstx + width <= MFB_PPW)
-	{
-	    maskpartialbits(dstx, width, startmask);
-	    nlMiddle = 0;
-	    endmask = 0;
-	}
-	else
-	{
-	    maskbits (dstx, width, startmask, endmask, nlMiddle);
-	}
-	if (startmask)
-	{
-	    niStart = min(MFB_PPW - dstx, width);
-	    bitStart = LeftMost;
-	    StepBit (bitStart, dstx);
-	}
-	if (endmask)
-	{
-	    niEnd = (dstx + width) & MFB_PIM;
-	    bitEnd = LeftMost;
-	}
-	if (rop == GXcopy)
-	{
-	    while (height--)
-	    {
-	    	psrc = psrcLine;
-	    	pdst = pdstLine;
-	    	psrcLine += widthSrc;
-	    	mfbScanlineInc(pdstLine, widthDst);
-	    	if (startmask)
-	    	{
-		    i = niStart;
-		    curBit = bitStart;
-		    GetBits (psrc, i, curBit, bitPos, bits);
-		    *pdst = (*pdst & ~startmask) | bits;
-		    pdst++;
-	    	}
-	    	nl = nlMiddle;
-	    	while (nl--)
-	    	{
-		    i = MFB_PPW;
-		    curBit = LeftMost;
-		    GetBits (psrc, i, curBit, bitPos, bits);
-		    *pdst++ = bits;
-	    	}
-	    	if (endmask)
-	    	{
-		    i = niEnd;
-		    curBit = bitEnd;
-		    GetBits (psrc, i, curBit, bitPos, bits);
-		    *pdst = (*pdst & ~endmask) | bits;
-	    	}
-	    }
-	}
-	else
-	{
-	    while (height--)
-	    {
-	    	psrc = psrcLine;
-	    	pdst = pdstLine;
-	    	psrcLine += widthSrc;
-	    	mfbScanlineInc(pdstLine, widthDst);
-	    	if (startmask)
-	    	{
-		    i = niStart;
-		    curBit = bitStart;
-		    GetBits (psrc, i, curBit, bitPos, bits);
-		    *pdst = MROP_MASK(bits, *pdst, startmask);
-		    pdst++;
-	    	}
-	    	nl = nlMiddle;
-	    	while (nl--)
-	    	{
-		    i = MFB_PPW;
-		    curBit = LeftMost;
-		    GetBits (psrc, i, curBit, bitPos, bits);
-		    *pdst = MROP_SOLID(bits, *pdst);
-		    pdst++;
-	    	}
-	    	if (endmask)
-	    	{
-		    i = niEnd;
-		    curBit = bitEnd;
-		    GetBits (psrc, i, curBit, bitPos, bits);
-		    *pdst = MROP_MASK (bits, *pdst, endmask);
-	    	}
-	    }
-	}
-    }
-}
-
-#else /*  PSZ == 8 */
-
-#define mfbmaskbits(x, w, startmask, endmask, nlw) \
-    startmask = mfbGetstarttab((x)&0x1f); \
-    endmask = mfbGetendtab(((x)+(w)) & 0x1f); \
-    if (startmask) \
-	nlw = (((w) - (32 - ((x)&0x1f))) >> 5); \
-    else \
-	nlw = (w) >> 5;
-
-#define mfbmaskpartialbits(x, w, mask) \
-    mask = mfbGetpartmasks((x)&0x1f,(w)&0x1f);
-
-#define LeftMost    0
-#define StepBit(bit, inc)  ((bit) += (inc))
-
-
-#if PSZ == 24
-#define GetBits(psrc, nBits, curBit, bitPos, bits) {\
-    bits = 0; \
-    while (nBits--) \
-    { \
-	if (bitPos < 8) \
-        { \
-	    bits |= ((*psrc++ >> bitPos) & 1) << curBit; \
-	    psrc += 2; \
-        } \
-	else if (bitPos < 16) \
-        { \
-	    psrc++; \
-	    bits |= ((*psrc++ >> (bitPos - 8)) & 1) << curBit; \
-	    psrc++; \
-        } \
-	else \
-        { \
-	    psrc += 2; \
-	    bits |= ((*psrc++ >> (bitPos - 16)) & 1) << curBit; \
-        } \
-	StepBit (curBit, 1); \
-    } \
-}
-#else
-#define GetBits(psrc, nBits, curBit, bitPos, bits) {\
-    bits = 0; \
-    while (nBits--) \
-    { \
-	bits |= ((*psrc++ >> bitPos) & 1) << curBit; \
-	StepBit (curBit, 1); \
-    } \
-}
-#endif
-
-void
-#if PSZ == 16
-cfbCopyPlane16to1
-#endif
-#if PSZ == 24
-cfbCopyPlane24to1
-#endif
-#if PSZ == 32
-cfbCopyPlane32to1
-#endif
-(
-    DrawablePtr pSrcDrawable,
-    DrawablePtr pDstDrawable,
-    int	rop,
-    RegionPtr prgnDst,
-    DDXPointPtr pptSrc,
-    unsigned long planemask,
-    unsigned long bitPlane)
-{
-    int			    srcx, srcy, dstx, dsty, width, height;
-    CfbBits	    *psrcBase;
-    CfbBits	    *pdstBase;
-    int			    widthSrc, widthDst;
-#if PSZ == 16
-    unsigned short	    *psrcLine;
-    register unsigned short *psrc;
-#endif
-#if PSZ == 24
-    unsigned char	    *psrcLine;
-    register unsigned char  *psrc;
-#endif
-#if PSZ == 32
-    unsigned int	    *psrcLine;
-    register unsigned int   *psrc;
-#endif
-    unsigned int	    *pdstLine;
-    register unsigned int   *pdst;
-    register int	    i;
-    register int	    curBit;
-    register int	    bitPos;
-    register unsigned int   bits;
-    unsigned int	    startmask = 0, endmask = 0;
-    int			    niStart = 0, niEnd = 0;
-    int			    bitStart = 0, bitEnd = 0;
-    int			    nl, nlMiddle;
-    int			    nbox;
-    BoxPtr		    pbox;
-    int result;
-
-
-    if (!(planemask & 1))
-	return;
-
-    /* must explicitly ask for "int" widths, as code below expects it */
-    /* on some machines (Alpha), "long" and "int" are not the same size */
-    cfbGetTypedWidthAndPointer (pSrcDrawable, widthSrc, psrcBase, int, CfbBits)
-    cfbGetTypedWidthAndPointer (pDstDrawable, widthDst, pdstBase, int, CfbBits)
-
-#if PSZ == 16
-    widthSrc <<= 1;
-#endif
-#if PSZ == 24
-    widthSrc <<= 2;
-#endif
-
-    bitPos = ffs (bitPlane) - 1;
-
-    nbox = REGION_NUM_RECTS(prgnDst);
-    pbox = REGION_RECTS(prgnDst);
-    while (nbox--)
-    {
-	dstx = pbox->x1;
-	dsty = pbox->y1;
-	srcx = pptSrc->x;
-	srcy = pptSrc->y;
-	width = pbox->x2 - pbox->x1;
-	height = pbox->y2 - pbox->y1;
-	pbox++;
-	pptSrc++;
-#if PSZ == 16
-	psrcLine = (unsigned short *)psrcBase + srcy * widthSrc + srcx;
-#endif
-#if PSZ == 24
-	psrcLine = (unsigned char *)psrcBase + srcy * widthSrc + srcx * 3;
-#endif
-#if PSZ == 32
-	psrcLine = (unsigned int *)psrcBase + srcy * widthSrc + srcx;
-#endif
-	pdstLine = (unsigned int *)pdstBase + dsty * widthDst + (dstx >> 5);
-	if (dstx + width <= 32)
-	{
-	    mfbmaskpartialbits(dstx, width, startmask);
-	    nlMiddle = 0;
-	    endmask = 0;
-	}
-	else
-	{
-	    mfbmaskbits (dstx, width, startmask, endmask, nlMiddle);
-	}
-	if (startmask)
-	{
-	    niStart = 32 - (dstx & 0x1f);
-	    bitStart = LeftMost;
-	    StepBit (bitStart, (dstx & 0x1f));
-	}
-	if (endmask)
-	{
-	    niEnd = (dstx + width) & 0x1f;
-	    bitEnd = LeftMost;
-	}
-	if (rop == GXcopy)
-	{
-	    while (height--)
-	    {
-	    	psrc = psrcLine;
-	    	pdst = pdstLine;
-	    	psrcLine += widthSrc;
-	    	pdstLine += widthDst;
-	    	if (startmask)
-	    	{
-		    i = niStart;
-		    curBit = bitStart;
-		    GetBits (psrc, i, curBit, bitPos, bits);
-
-		    *pdst = (*pdst & ~startmask) | bits;
-		    pdst++;
-	    	}
-	    	nl = nlMiddle;
-	    	while (nl--)
-	    	{
-		    i = 32;
-		    curBit = LeftMost;
-		    GetBits (psrc, i, curBit, bitPos, bits);
-		    *pdst++ = bits;
-	    	}
-	    	if (endmask)
-	    	{
-		    i = niEnd;
-		    curBit = bitEnd;
-		    GetBits (psrc, i, curBit, bitPos, bits);
-
-		    *pdst = (*pdst & ~endmask) | bits;
-	    	}
-	    }
-	}
-	else
-	{
-	    while (height--)
-	    {
-	    	psrc = psrcLine;
-	    	pdst = pdstLine;
-	    	psrcLine += widthSrc;
-	    	pdstLine += widthDst;
-	    	if (startmask)
-	    	{
-		    i = niStart;
-		    curBit = bitStart;
-		    GetBits (psrc, i, curBit, bitPos, bits);
-                    DoRop (result, rop, bits, *pdst);
-
-		    *pdst = (*pdst & ~startmask) | 
-			    (result & startmask);
-		    pdst++;
-	    	}
-	    	nl = nlMiddle;
- 	    	while (nl--)
-	    	{
-		    i = 32;
-		    curBit = LeftMost;
-		    GetBits (psrc, i, curBit, bitPos, bits);
-                    DoRop (result, rop, bits, *pdst);
-		    *pdst = result;
-		    ++pdst;
-	    	}
-	    	if (endmask)
-	    	{
-		    i = niEnd;
-		    curBit = bitEnd;
-		    GetBits (psrc, i, curBit, bitPos, bits);
-                    DoRop (result, rop, bits, *pdst);
-
-		    *pdst = (*pdst & ~endmask) |
-			    (result & endmask);
-	    	}
-	    }
-	}
-    }
-}
-
-#endif  /* PSZ == 8 */
diff --git a/cfb/cfbfillarc.c b/cfb/cfbfillarc.c
deleted file mode 100644
index 0eb5ff4..0000000
--- a/cfb/cfbfillarc.c
+++ /dev/null
@@ -1,374 +0,0 @@
-/************************************************************
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-********************************************************/
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <limits.h>
-
-#include <X11/X.h>
-#include <X11/Xprotostr.h>
-#include "regionstr.h"
-#include "gcstruct.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "mifillarc.h"
-#include "cfbrrop.h"
-#include "mi.h"
-
-/* gcc 1.35 is stupid */
-#if defined(__GNUC__) && __GNUC__ < 2 && defined(mc68020)
-#define STUPID volatile
-#else
-#define STUPID
-#endif
-
-static void
-RROP_NAME(cfbFillEllipseSolid)(
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    xArc *arc)
-{
-    STUPID int x, y, e;
-    STUPID int yk, xk, ym, xm, dx, dy, xorg, yorg;
-    miFillArcRec info;
-#if PSZ == 24
-    unsigned char *addrlt, *addrlb;
-#else
-    CfbBits *addrlt, *addrlb;
-#endif
-    register CfbBits *addrl;
-    register int n;
-    int nlwidth;
-    RROP_DECLARE
-    register int xpos;
-    register int slw;
-    CfbBits startmask, endmask;
-    int	nlmiddle;
-#if PSZ == 24
-    register int pidx;
-    int xpos3;
-#endif
-
-#if PSZ == 24
-    cfbGetByteWidthAndPointer (pDraw, nlwidth, addrlt)
-#else
-    cfbGetLongWidthAndPointer (pDraw, nlwidth, addrlt)
-#endif
-
-    RROP_FETCH_GC(pGC);
-    miFillArcSetup(arc, &info);
-    MIFILLARCSETUP();
-    xorg += pDraw->x;
-    yorg += pDraw->y;
-    addrlb = addrlt;
-    addrlt += nlwidth * (yorg - y);
-    addrlb += nlwidth * (yorg + y + dy);
-    while (y)
-    {
-	addrlt += nlwidth;
-	addrlb -= nlwidth;
-	MIFILLARCSTEP(slw);
-	if (!slw)
-	    continue;
-	xpos = xorg - x;
-#if PSZ == 24
-	xpos3 = (xpos * 3) & ~0x03;
-	addrl = (CfbBits *)((char *)addrlt + xpos3);
-	if (slw == 1){
-	  RROP_SOLID24(addrl, xpos);
-	  if (miFillArcLower(slw)){
-	    addrl = (CfbBits *)((char *)addrlb + xpos3);
-	    RROP_SOLID24(addrl, xpos);
-          }
-	  continue;
-	}
-	maskbits(xpos, slw, startmask, endmask, nlmiddle);
-	xpos &= 3;
-	pidx = xpos;
-	if (startmask){
-	  RROP_SOLID_MASK(addrl, startmask, pidx-1);
-	  addrl++;
-	  if (pidx == 3)
-	    pidx = 0;
-	}
-	n = nlmiddle;
-	while (--n >= 0){
-	  RROP_SOLID(addrl, pidx);
-	  addrl++;
-	  if (++pidx == 3)
-	    pidx = 0;
-	}
-	if (endmask)
-	  RROP_SOLID_MASK(addrl, endmask, pidx);
-	if (!miFillArcLower(slw))
-	  continue;
-	addrl = (CfbBits *)((char *)addrlb + xpos3);
-	pidx = xpos;
-	if (startmask){
-	  RROP_SOLID_MASK(addrl, startmask, pidx-1);
-	  addrl++;
-	  if (pidx == 3)
-	    pidx = 0;
-	}
-	n = nlmiddle;
-	while (--n >= 0){
-	  RROP_SOLID(addrl, pidx);
-	  addrl++;
-	  if (++pidx == 3)
-	    pidx = 0;
-	}
-	if (endmask)
-	  RROP_SOLID_MASK(addrl, endmask, pidx);
-#else /* PSZ == 24 */
-	addrl = addrlt + (xpos >> PWSH);
-	if (((xpos & PIM) + slw) <= PPW)
-	{
-	    maskpartialbits(xpos, slw, startmask);
-	    RROP_SOLID_MASK(addrl,startmask);
-	    if (miFillArcLower(slw))
-	    {
-		addrl = addrlb + (xpos >> PWSH);
-		RROP_SOLID_MASK(addrl, startmask);
-	    }
-	    continue;
-	}
-	maskbits(xpos, slw, startmask, endmask, nlmiddle);
-	if (startmask)
-	{
-	    RROP_SOLID_MASK(addrl, startmask);
-	    addrl++;
-	}
-	n = nlmiddle;
-	RROP_SPAN(addrl,n)
-
-	if (endmask)
-	    RROP_SOLID_MASK(addrl, endmask);
-	if (!miFillArcLower(slw))
-	    continue;
-	addrl = addrlb + (xpos >> PWSH);
-	if (startmask)
-	{
-	    RROP_SOLID_MASK(addrl, startmask);
-	    addrl++;
-	}
-	n = nlmiddle;
-	RROP_SPAN(addrl, n);
-	if (endmask)
-	    RROP_SOLID_MASK(addrl, endmask);
-#endif /* PSZ == 24 */
-    }
-    RROP_UNDECLARE
-}
-
-#if PSZ == 24
-#define FILLSPAN(xl,xr,addr) \
-    if (xr >= xl){ \
-	n = xr - xl + 1; \
-	addrl = (CfbBits *)((char *)addr + ((xl * 3) & ~0x03)); \
-	if (n <= 1){ \
-          if (n) \
-            RROP_SOLID24(addrl, xl); \
-	} else { \
-	  maskbits(xl, n, startmask, endmask, n); \
-          pidx = xl & 3; \
-	  if (startmask){ \
-	    RROP_SOLID_MASK(addrl, startmask, pidx-1); \
-	    addrl++; \
-	    if (pidx == 3) \
-	      pidx = 0; \
-	  } \
-	  while (--n >= 0){ \
-	    RROP_SOLID(addrl, pidx); \
-	    addrl++; \
-	    if (++pidx == 3) \
-	      pidx = 0; \
-	  } \
-	  if (endmask) \
-	    RROP_SOLID_MASK(addrl, endmask, pidx); \
-	} \
-    }
-#else /* PSZ == 24 */
-#define FILLSPAN(xl,xr,addr) \
-    if (xr >= xl) \
-    { \
-	n = xr - xl + 1; \
-	addrl = addr + (xl >> PWSH); \
-	if (((xl & PIM) + n) <= PPW) \
-	{ \
-	    maskpartialbits(xl, n, startmask); \
-	    RROP_SOLID_MASK(addrl, startmask); \
-	} \
-	else \
-	{ \
-	    maskbits(xl, n, startmask, endmask, n); \
-	    if (startmask) \
-	    { \
-		RROP_SOLID_MASK(addrl, startmask); \
-		addrl++; \
-	    } \
-	    while (n--) \
-	    { \
-		RROP_SOLID(addrl); \
-		++addrl; \
-	    } \
-	    if (endmask) \
-		RROP_SOLID_MASK(addrl, endmask); \
-	} \
-    }
-#endif /* PSZ == 24 */
-
-#define FILLSLICESPANS(flip,addr) \
-    if (!flip) \
-    { \
-	FILLSPAN(xl, xr, addr); \
-    } \
-    else \
-    { \
-	xc = xorg - x; \
-	FILLSPAN(xc, xr, addr); \
-	xc += slw - 1; \
-	FILLSPAN(xl, xc, addr); \
-    }
-
-static void
-RROP_NAME(cfbFillArcSliceSolid)(
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    xArc *arc)
-{
-    int yk, xk, ym, xm, dx, dy, xorg, yorg, slw;
-    register int x, y, e;
-    miFillArcRec info;
-    miArcSliceRec slice;
-    int xl, xr, xc;
-#if PSZ == 24
-    unsigned char *addrlt, *addrlb;
-#else
-    CfbBits *addrlt, *addrlb;
-#endif
-    register CfbBits *addrl;
-    register int n;
-    int nlwidth;
-    RROP_DECLARE
-    CfbBits startmask, endmask;
-#if PSZ == 24
-    register int pidx;
-#endif /* PSZ == 24 */
-
-#if PSZ == 24
-    cfbGetByteWidthAndPointer (pDraw, nlwidth, addrlt)
-#else
-    cfbGetLongWidthAndPointer (pDraw, nlwidth, addrlt)
-#endif
-
-    RROP_FETCH_GC(pGC);
-    miFillArcSetup(arc, &info);
-    miFillArcSliceSetup(arc, &slice, pGC);
-    MIFILLARCSETUP();
-    xorg += pDraw->x;
-    yorg += pDraw->y;
-    addrlb = addrlt;
-    addrlt += nlwidth * (yorg - y);
-    addrlb += nlwidth * (yorg + y + dy);
-    slice.edge1.x += pDraw->x;
-    slice.edge2.x += pDraw->x;
-    while (y > 0)
-    {
-	addrlt += nlwidth;
-	addrlb -= nlwidth;
-	MIFILLARCSTEP(slw);
-	MIARCSLICESTEP(slice.edge1);
-	MIARCSLICESTEP(slice.edge2);
-	if (miFillSliceUpper(slice))
-	{
-	    MIARCSLICEUPPER(xl, xr, slice, slw);
-	    FILLSLICESPANS(slice.flip_top, addrlt);
-	}
-	if (miFillSliceLower(slice))
-	{
-	    MIARCSLICELOWER(xl, xr, slice, slw);
-	    FILLSLICESPANS(slice.flip_bot, addrlb);
-	}
-    }
-    RROP_UNDECLARE
-}
-
-void
-RROP_NAME(cfbPolyFillArcSolid) (pDraw, pGC, narcs, parcs)
-    DrawablePtr	pDraw;
-    GCPtr	pGC;
-    int		narcs;
-    xArc	*parcs;
-{
-    register xArc *arc;
-    register int i;
-    int x2, y2;
-    BoxRec box;
-    RegionPtr cclip;
-
-    cclip = cfbGetCompositeClip(pGC);
-    for (arc = parcs, i = narcs; --i >= 0; arc++)
-    {
-	if (miFillArcEmpty(arc))
-	    continue;
-	if (miCanFillArc(arc))
-	{
-	    box.x1 = arc->x + pDraw->x;
-	    box.y1 = arc->y + pDraw->y;
- 	    /*
- 	     * Because box.x2 and box.y2 get truncated to 16 bits, and the
- 	     * RECT_IN_REGION test treats the resulting number as a signed
- 	     * integer, the RECT_IN_REGION test alone can go the wrong way.
- 	     * This can result in a server crash because the rendering
- 	     * routines in this file deal directly with cpu addresses
- 	     * of pixels to be stored, and do not clip or otherwise check
- 	     * that all such addresses are within their respective pixmaps.
- 	     * So we only allow the RECT_IN_REGION test to be used for
- 	     * values that can be expressed correctly in a signed short.
- 	     */
- 	    x2 = box.x1 + (int)arc->width + 1;
- 	    box.x2 = x2;
- 	    y2 = box.y1 + (int)arc->height + 1;
- 	    box.y2 = y2;
- 	    if ( (x2 <= SHRT_MAX) && (y2 <= SHRT_MAX) &&
- 		    (RECT_IN_REGION(pDraw->pScreen, cclip, &box) == rgnIN) )
-	    {
-		if ((arc->angle2 >= FULLCIRCLE) ||
-		    (arc->angle2 <= -FULLCIRCLE))
-		    RROP_NAME(cfbFillEllipseSolid)(pDraw, pGC, arc);
-		else
-		    RROP_NAME(cfbFillArcSliceSolid)(pDraw, pGC, arc);
-		continue;
-	    }
-	}
-	miPolyFillArc(pDraw, pGC, 1, arc);
-    }
-}
diff --git a/cfb/cfbfillrct.c b/cfb/cfbfillrct.c
deleted file mode 100644
index fc2d31b..0000000
--- a/cfb/cfbfillrct.c
+++ /dev/null
@@ -1,305 +0,0 @@
-/*
- * Fill rectangles.
- */
-
-/*
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-*/
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "servermd.h"
-#include "gcstruct.h"
-#include "window.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "windowstr.h"
-#include "mi.h"
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "mergerop.h"
-
-
-void
-cfbFillBoxTileOdd (pDrawable, n, rects, tile, xrot, yrot)
-    DrawablePtr	pDrawable;
-    int		n;
-    BoxPtr	rects;
-    PixmapPtr	tile;
-    int		xrot, yrot;
-{
-#if PSZ == 24
-    if (tile->drawable.width & 3)
-#else
-    if (tile->drawable.width & PIM)
-#endif
-	cfbFillBoxTileOddCopy (pDrawable, n, rects, tile, xrot, yrot, GXcopy, ~0L);
-    else
-	cfbFillBoxTile32sCopy (pDrawable, n, rects, tile, xrot, yrot, GXcopy, ~0L);
-}
-
-void
-cfbFillRectTileOdd (pDrawable, pGC, nBox, pBox)
-    DrawablePtr	pDrawable;
-    GCPtr	pGC;
-    int		nBox;
-    BoxPtr	pBox;
-{
-    int	xrot, yrot;
-    void    (*fill)(DrawablePtr, int, BoxPtr, PixmapPtr, int, int, int, unsigned long);
-
-    xrot = pDrawable->x + pGC->patOrg.x;
-    yrot = pDrawable->y + pGC->patOrg.y;
-#if PSZ == 24
-    if (pGC->tile.pixmap->drawable.width & 3)
-#else
-    if (pGC->tile.pixmap->drawable.width & PIM)
-#endif
-    {
-    	fill = cfbFillBoxTileOddGeneral;
-    	if ((pGC->planemask & PMSK) == PMSK)
-    	{
-	    if (pGC->alu == GXcopy)
-	    	fill = cfbFillBoxTileOddCopy;
-    	}
-    }
-    else
-    {
-    	fill = cfbFillBoxTile32sGeneral;
-    	if ((pGC->planemask & PMSK) == PMSK)
-    	{
-	    if (pGC->alu == GXcopy)
-	    	fill = cfbFillBoxTile32sCopy;
-    	}
-    }
-    (*fill) (pDrawable, nBox, pBox, pGC->tile.pixmap, xrot, yrot, pGC->alu, pGC->planemask);
-}
-
-#define NUM_STACK_RECTS	1024
-
-void
-cfbPolyFillRect(pDrawable, pGC, nrectFill, prectInit)
-    DrawablePtr pDrawable;
-    register GCPtr pGC;
-    int		nrectFill; 	/* number of rectangles to fill */
-    xRectangle	*prectInit;  	/* Pointer to first rectangle to fill */
-{
-    xRectangle	    *prect;
-    RegionPtr	    prgnClip;
-    register BoxPtr pbox;
-    register BoxPtr pboxClipped;
-    BoxPtr	    pboxClippedBase;
-    BoxPtr	    pextent;
-    BoxRec	    stackRects[NUM_STACK_RECTS];
-    cfbPrivGC	    *priv;
-    int		    numRects;
-    void	    (*BoxFill)(DrawablePtr, GCPtr, int, BoxPtr);
-    int		    n;
-    int		    xorg, yorg;
-
-#if PSZ != 8
-    if ((pGC->fillStyle == FillStippled) ||
-	(pGC->fillStyle == FillOpaqueStippled)) {
-       miPolyFillRect(pDrawable, pGC, nrectFill, prectInit);
-       return;
-    }
-#endif
-
-    priv = cfbGetGCPrivate(pGC);
-    prgnClip = pGC->pCompositeClip;
-
-    BoxFill = 0;
-    switch (pGC->fillStyle)
-    {
-    case FillSolid:
-	switch (priv->rop) {
-	case GXcopy:
-	    BoxFill = cfbFillRectSolidCopy;
-	    break;
-	case GXxor:
-	    BoxFill = cfbFillRectSolidXor;
-	    break;
-	default:
-	    BoxFill = cfbFillRectSolidGeneral;
-	    break;
-	}
-	break;
-    case FillTiled:
-	if (!pGC->pRotatedPixmap)
-	    BoxFill = cfbFillRectTileOdd;
-	else
-	{
-	    if (pGC->alu == GXcopy && (pGC->planemask & PMSK) == PMSK)
-		BoxFill = cfbFillRectTile32Copy;
-	    else
-		BoxFill = cfbFillRectTile32General;
-	}
-	break;
-#if PSZ == 8
-    case FillStippled:
-	if (!pGC->pRotatedPixmap)
-	    BoxFill = cfb8FillRectStippledUnnatural;
-	else
-	    BoxFill = cfb8FillRectTransparentStippled32;
-	break;
-    case FillOpaqueStippled:
-	if (!pGC->pRotatedPixmap)
-	    BoxFill = cfb8FillRectStippledUnnatural;
-	else
-	    BoxFill = cfb8FillRectOpaqueStippled32;
-	break;
-#endif
-    }
-    prect = prectInit;
-    xorg = pDrawable->x;
-    yorg = pDrawable->y;
-    if (xorg || yorg)
-    {
-	prect = prectInit;
-	n = nrectFill;
-	while(n--)
-	{
-	    prect->x += xorg;
-	    prect->y += yorg;
-	    prect++;
-	}
-    }
-
-    prect = prectInit;
-
-    numRects = REGION_NUM_RECTS(prgnClip) * nrectFill;
-    if (numRects > NUM_STACK_RECTS)
-    {
-	pboxClippedBase = (BoxPtr)xalloc(numRects * sizeof(BoxRec));
-	if (!pboxClippedBase)
-	    return;
-    }
-    else
-	pboxClippedBase = stackRects;
-
-    pboxClipped = pboxClippedBase;
-	
-    if (REGION_NUM_RECTS(prgnClip) == 1)
-    {
-	int x1, y1, x2, y2, bx2, by2;
-
-	pextent = REGION_RECTS(prgnClip);
-	x1 = pextent->x1;
-	y1 = pextent->y1;
-	x2 = pextent->x2;
-	y2 = pextent->y2;
-    	while (nrectFill--)
-    	{
-	    if ((pboxClipped->x1 = prect->x) < x1)
-		pboxClipped->x1 = x1;
-    
-	    if ((pboxClipped->y1 = prect->y) < y1)
-		pboxClipped->y1 = y1;
-    
-	    bx2 = (int) prect->x + (int) prect->width;
-	    if (bx2 > x2)
-		bx2 = x2;
-	    pboxClipped->x2 = bx2;
-    
-	    by2 = (int) prect->y + (int) prect->height;
-	    if (by2 > y2)
-		by2 = y2;
-	    pboxClipped->y2 = by2;
-
-	    prect++;
-	    if ((pboxClipped->x1 < pboxClipped->x2) &&
-		(pboxClipped->y1 < pboxClipped->y2))
-	    {
-		pboxClipped++;
-	    }
-    	}
-    }
-    else
-    {
-	int x1, y1, x2, y2, bx2, by2;
-
-	pextent = REGION_EXTENTS(pGC->pScreen, prgnClip);
-	x1 = pextent->x1;
-	y1 = pextent->y1;
-	x2 = pextent->x2;
-	y2 = pextent->y2;
-    	while (nrectFill--)
-    	{
-	    BoxRec box;
-    
-	    if ((box.x1 = prect->x) < x1)
-		box.x1 = x1;
-    
-	    if ((box.y1 = prect->y) < y1)
-		box.y1 = y1;
-    
-	    bx2 = (int) prect->x + (int) prect->width;
-	    if (bx2 > x2)
-		bx2 = x2;
-	    box.x2 = bx2;
-    
-	    by2 = (int) prect->y + (int) prect->height;
-	    if (by2 > y2)
-		by2 = y2;
-	    box.y2 = by2;
-    
-	    prect++;
-    
-	    if ((box.x1 >= box.x2) || (box.y1 >= box.y2))
-	    	continue;
-    
-	    n = REGION_NUM_RECTS (prgnClip);
-	    pbox = REGION_RECTS(prgnClip);
-    
-	    /* clip the rectangle to each box in the clip region
-	       this is logically equivalent to calling Intersect()
-	    */
-	    while(n--)
-	    {
-		pboxClipped->x1 = max(box.x1, pbox->x1);
-		pboxClipped->y1 = max(box.y1, pbox->y1);
-		pboxClipped->x2 = min(box.x2, pbox->x2);
-		pboxClipped->y2 = min(box.y2, pbox->y2);
-		pbox++;
-
-		/* see if clipping left anything */
-		if(pboxClipped->x1 < pboxClipped->x2 && 
-		   pboxClipped->y1 < pboxClipped->y2)
-		{
-		    pboxClipped++;
-		}
-	    }
-    	}
-    }
-    if (pboxClipped != pboxClippedBase)
-	(*BoxFill) (pDrawable, pGC,
-		    pboxClipped-pboxClippedBase, pboxClippedBase);
-    if (pboxClippedBase != stackRects)
-    	xfree(pboxClippedBase);
-}
diff --git a/cfb/cfbfillsp.c b/cfb/cfbfillsp.c
deleted file mode 100644
index 36710b6..0000000
--- a/cfb/cfbfillsp.c
+++ /dev/null
@@ -1,1004 +0,0 @@
-/************************************************************
-Copyright 1987 by Sun Microsystems, Inc. Mountain View, CA.
-
-                    All Rights Reserved
-
-Permission  to  use,  copy,  modify,  and  distribute   this
-software  and  its documentation for any purpose and without
-fee is hereby granted, provided that the above copyright no-
-tice  appear  in all copies and that both that copyright no-
-tice and this permission notice appear in  supporting  docu-
-mentation,  and  that the names of Sun or The Open Group
-not be used in advertising or publicity pertaining to 
-distribution  of  the software  without specific prior 
-written permission. Sun and The Open Group make no 
-representations about the suitability of this software for 
-any purpose. It is provided "as is" without any express or 
-implied warranty.
-
-SUN DISCLAIMS ALL WARRANTIES WITH REGARD TO  THIS  SOFTWARE,
-INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
-NESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SUN BE  LI-
-ABLE  FOR  ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,  DATA  OR
-PROFITS,  WHETHER  IN  AN  ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
-THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-********************************************************/
-
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "servermd.h"
-#include "gcstruct.h"
-#include "window.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "windowstr.h"
-
-#include "cfb.h"
-#include "cfbmskbits.h"
-
-#include "mergerop.h"
-
-#if PSZ == 8
-#include "cfb8bit.h"
-#endif
-
-#define MFB_CONSTS_ONLY
-#include "maskbits.h"
-
-#include "mi.h"
-#include "mispans.h"
-
-/* scanline filling for color frame buffer
-   written by drewry, oct 1986 modified by smarks
-   changes for compatibility with Little-endian systems Jul 1987; MIT:yba.
-
-   these routines all clip.  they assume that anything that has called
-them has already translated the points (i.e. pGC->miTranslate is
-non-zero, which is howit gets set in cfbCreateGC().)
-
-   the number of new scnalines created by clipping ==
-MaxRectsPerBand * nSpans.
-
-    FillSolid is overloaded to be used for OpaqueStipple as well,
-if fgPixel == bgPixel.  
-Note that for solids, PrivGC.rop == PrivGC.ropOpStip
-
-
-    FillTiled is overloaded to be used for OpaqueStipple, if
-fgPixel != bgPixel.  based on the fill style, it uses
-{RotatedTile, gc.alu} or {RotatedStipple, PrivGC.ropOpStip}
-*/
-
-#ifdef	notdef
-#include	<stdio.h>
-static
-dumpspans(n, ppt, pwidth)
-    int	n;
-    DDXPointPtr ppt;
-    int *pwidth;
-{
-    fprintf(stderr,"%d spans\n", n);
-    while (n--) {
-	fprintf(stderr, "[%d,%d] %d\n", ppt->x, ppt->y, *pwidth);
-	ppt++;
-	pwidth++;
-    }
-    fprintf(stderr, "\n");
-}
-#endif
-
-/* Fill spans with tiles that aren't 32 bits wide */
-void
-cfbUnnaturalTileFS(pDrawable, pGC, nInit, pptInit, pwidthInit, fSorted)
-DrawablePtr pDrawable;
-GC		*pGC;
-int		nInit;		/* number of spans to fill */
-DDXPointPtr pptInit;		/* pointer to list of start points */
-int *pwidthInit;		/* pointer to list of n widths */
-int fSorted;
-{
-    int n;			/* number of spans to fill */
-    register DDXPointPtr ppt;	/* pointer to list of start points */
-    register int *pwidth;	/* pointer to list of n widths */
-    void    (*fill)(DrawablePtr, int, DDXPointPtr, int *, PixmapPtr, int, int, int, unsigned long);
-    int	xrot, yrot;
-
-    if (!(pGC->planemask))
-	return;
-
-#if PSZ == 24
-    if (pGC->tile.pixmap->drawable.width & 3)
-#else
-    if (pGC->tile.pixmap->drawable.width & PIM)
-#endif
-    {
-    	fill = cfbFillSpanTileOddGeneral;
-    	if ((pGC->planemask & PMSK) == PMSK)
-    	{
-	    if (pGC->alu == GXcopy)
-	    	fill = cfbFillSpanTileOddCopy;
-    	}
-    }
-    else
-    {
-	fill = cfbFillSpanTile32sGeneral;
-    	if ((pGC->planemask & PMSK) == PMSK)
-    	{
-	    if (pGC->alu == GXcopy)
-		fill = cfbFillSpanTile32sCopy;
-	}
-    }
-    n = nInit * miFindMaxBand( cfbGetCompositeClip(pGC) );
-    if ( n == 0 )
-	return;
-    pwidth = (int *)xalloc(n * sizeof(int));
-    ppt = (DDXPointRec *)xalloc(n * sizeof(DDXPointRec));
-    if(!ppt || !pwidth)
-    {
-	if (ppt) xfree(ppt);
-	if (pwidth) xfree(pwidth);
-	return;
-    }
-    n = miClipSpans( cfbGetCompositeClip(pGC),
-		     pptInit, pwidthInit, nInit, 
-		     ppt, pwidth, fSorted);
-
-    xrot = pDrawable->x + pGC->patOrg.x;
-    yrot = pDrawable->y + pGC->patOrg.y;
-
-    (*fill) (pDrawable, n, ppt, pwidth, pGC->tile.pixmap, xrot, yrot, pGC->alu, pGC->planemask);
-
-    xfree(ppt);
-    xfree(pwidth);
-}
-
-#if PSZ == 8
-
-void
-cfbUnnaturalStippleFS(pDrawable, pGC, nInit, pptInit, pwidthInit, fSorted)
-DrawablePtr pDrawable;
-GC		*pGC;
-int		nInit;		/* number of spans to fill */
-DDXPointPtr pptInit;		/* pointer to list of start points */
-int *pwidthInit;		/* pointer to list of n widths */
-int fSorted;
-{
-				/* next three parameters are post-clip */
-    int		    n;		/* number of spans to fill */
-    DDXPointPtr	    ppt;	/* pointer to list of start points */
-    int		    *pwidth;	/* pointer to list of n widths */
-    int		    *pwidthFree;/* copies of the pointers to free */
-    DDXPointPtr	    pptFree;
-    CfbBits   *pdstBase;	/* pointer to start of bitmap */
-    int		    nlwDst;	/* width in longwords of bitmap */
-    register CfbBits    *pdst;	/* pointer to current word in bitmap */
-    PixmapPtr	    pStipple;	/* pointer to stipple we want to fill with */
-    int		    nlw;
-    int		    x, y, w, xrem, xSrc, ySrc;
-    int		    stwidth, stippleWidth;
-    int		    stippleHeight;
-    register CfbBits  bits, inputBits;
-    register int    partBitsLeft;
-    int		    nextPartBits;
-    int		    bitsLeft, bitsWhole;
-    CfbBits   *srcTemp, *srcStart;
-    CfbBits   *psrcBase;
-    CfbBits   startmask, endmask;
-
-    if (pGC->fillStyle == FillStippled)
-	cfb8CheckStipple (pGC->alu, pGC->fgPixel, pGC->planemask);
-    else
-	cfb8CheckOpaqueStipple (pGC->alu, pGC->fgPixel, pGC->bgPixel, pGC->planemask);
-
-    if (cfb8StippleRRop == GXnoop)
-	return;
-
-    n = nInit * miFindMaxBand( cfbGetCompositeClip(pGC) );
-    if ( n == 0 )
-	return;
-    pwidthFree = (int *)xalloc(n * sizeof(int));
-    pptFree = (DDXPointRec *)xalloc(n * sizeof(DDXPointRec));
-    if(!pptFree || !pwidthFree)
-    {
-	if (pptFree) xfree(pptFree);
-	if (pwidthFree) xfree(pwidthFree);
-	return;
-    }
-
-    pwidth = pwidthFree;
-    ppt = pptFree;
-    n = miClipSpans( cfbGetCompositeClip(pGC),
-		     pptInit, pwidthInit, nInit, 
-		     ppt, pwidth, fSorted);
-
-    /*
-     *  OK,  so what's going on here?  We have two Drawables:
-     *
-     *  The Stipple:
-     *		Depth = 1
-     *		Width = stippleWidth
-     *		Words per scanline = stwidth
-     *		Pointer to pixels = pStipple->devPrivate.ptr
-     */
-
-    pStipple = pGC->stipple;
-
-    stwidth = pStipple->devKind >> PWSH;
-    stippleWidth = pStipple->drawable.width;
-    stippleHeight = pStipple->drawable.height;
-    psrcBase = (CfbBits *) pStipple->devPrivate.ptr;
-
-    /*
-     *	The Target:
-     *		Depth = PSZ
-     *		Width = determined from *pwidth
-     *		Words per scanline = nlwDst
-     *		Pointer to pixels = addrlBase
-     */
-
-    cfbGetLongWidthAndPointer (pDrawable, nlwDst, pdstBase)
-
-    /* this replaces rotating the stipple. Instead we just adjust the offset
-     * at which we start grabbing bits from the stipple.
-     * Ensure that ppt->x - xSrc >= 0 and ppt->y - ySrc >= 0,
-     * so that iline and xrem always stay within the stipple bounds.
-     */
-
-    modulus (pGC->patOrg.x, stippleWidth, xSrc);
-    xSrc += pDrawable->x - stippleWidth;
-    modulus (pGC->patOrg.y, stippleHeight, ySrc);
-    ySrc += pDrawable->y - stippleHeight;
-
-    bitsWhole = stippleWidth;
-
-    while (n--)
-    {
-	x = ppt->x;
-	y = ppt->y;
-	ppt++;
-	w = *pwidth++;
-	pdst = pdstBase + y * nlwDst + (x >> PWSH);
-	y = (y - ySrc) % stippleHeight;
-	srcStart = psrcBase + y * stwidth;
-	xrem = ((x & ~(PGSZB-1)) - xSrc) % stippleWidth;
-	srcTemp = srcStart + (xrem >> MFB_PWSH);
-	bitsLeft = stippleWidth - (xrem & ~MFB_PIM);
-	xrem &= MFB_PIM;
-	NextUnnaturalStippleWord
-	if (partBitsLeft < xrem)
-	    FatalError ("cfbUnnaturalStippleFS bad partBitsLeft %d xrem %d",
-			partBitsLeft, xrem);
-	NextSomeBits (inputBits, xrem);
-	partBitsLeft -= xrem;
-	if (((x & PIM) + w) <= PPW)
-	{
-	    maskpartialbits (x, w, startmask)
-	    NextUnnaturalStippleBits
-	    *pdst = MaskRRopPixels(*pdst,bits,startmask);
-	}
-	else
-	{
-	    maskbits (x, w, startmask, endmask, nlw);
-	    nextPartBits = (x & (PGSZB-1)) + w;
-	    if (nextPartBits < partBitsLeft)
-	    {
-		if (startmask)
-		{
-		    MaskRRopBitGroup(pdst,GetBitGroup(inputBits),startmask)
-		    pdst++;
-		    NextBitGroup (inputBits);
-		}
-		while (nlw--)
-		{
-		    RRopBitGroup (pdst, GetBitGroup (inputBits));
-		    pdst++;
-		    NextBitGroup (inputBits);
-		}
-		if (endmask)
-		{
-		    MaskRRopBitGroup(pdst,GetBitGroup(inputBits),endmask)
-		}
-	    }
-	    else if (bitsLeft != bitsWhole && nextPartBits < partBitsLeft + bitsLeft)
-	    {
-	    	NextUnnaturalStippleBitsFast
-	    	if (startmask)
-	    	{
-		    *pdst = MaskRRopPixels(*pdst,bits,startmask);
-		    pdst++;
-	    	    NextUnnaturalStippleBitsFast
-	    	}
-	    	while (nlw--)
-	    	{
-		    *pdst = RRopPixels(*pdst,bits);
-		    pdst++;
-	    	    NextUnnaturalStippleBitsFast
-	    	}
-	    	if (endmask)
-		    *pdst = MaskRRopPixels (*pdst,bits,endmask);
-	    }
-	    else
-	    {
-	    	NextUnnaturalStippleBits
-	    	if (startmask)
-	    	{
-		    *pdst = MaskRRopPixels(*pdst,bits,startmask);
-		    pdst++;
-	    	    NextUnnaturalStippleBits
-	    	}
-	    	while (nlw--)
-	    	{
-		    *pdst = RRopPixels(*pdst,bits);
-		    pdst++;
-	    	    NextUnnaturalStippleBits
-	    	}
-	    	if (endmask)
-		    *pdst = MaskRRopPixels(*pdst,bits,endmask);
-	    }
-	}
-    }
-    xfree(pptFree);
-    xfree(pwidthFree);
-}
-
-#else /* PSZ != 8 */
-
-/* Fill spans with stipples that aren't 32 bits wide */
-void
-cfbUnnaturalStippleFS(pDrawable, pGC, nInit, pptInit, pwidthInit, fSorted)
-DrawablePtr pDrawable;
-GC		*pGC;
-int		nInit;		/* number of spans to fill */
-DDXPointPtr pptInit;		/* pointer to list of start points */
-int *pwidthInit;		/* pointer to list of n widths */
-int fSorted;
-{
-				/* next three parameters are post-clip */
-    int			    n;		/* number of spans to fill */
-    register DDXPointPtr    ppt;	/* pointer to list of start points */
-    register int	    *pwidth;	/* pointer to list of n widths */
-    int			    iline;	/* first line of tile to use */
-    CfbBits	    *addrlBase;	/* pointer to start of bitmap */
-    int			    nlwidth;	/* width in longwords of bitmap */
-    register CfbBits  *pdst;	/* pointer to current word in bitmap */
-    PixmapPtr		    pStipple;	/* pointer to stipple we want to fill with */
-    register int	    w;
-    int			    width,  x, xrem, xSrc, ySrc;
-    CfbBits	    tmpSrc, tmpDst1, tmpDst2;
-    int			    stwidth, stippleWidth;
-    CfbBits	    *psrcS;
-    int			    rop, stiprop = 0;
-    int			    stippleHeight;
-    int			    *pwidthFree;    /* copies of the pointers to free */
-    DDXPointPtr		    pptFree;
-    CfbBits	    fgfill, bgfill;
-
-    if (!(pGC->planemask))
-	return;
-
-    n = nInit * miFindMaxBand( cfbGetCompositeClip(pGC) );
-    if ( n == 0 )
-	return;
-    pwidthFree = (int *)xalloc(n * sizeof(int));
-    pptFree = (DDXPointRec *)xalloc(n * sizeof(DDXPointRec));
-    if(!pptFree || !pwidthFree)
-    {
-	if (pptFree) xfree(pptFree);
-	if (pwidthFree) xfree(pwidthFree);
-	return;
-    }
-    pwidth = pwidthFree;
-    ppt = pptFree;
-    n = miClipSpans( cfbGetCompositeClip(pGC),
-		     pptInit, pwidthInit, nInit, 
-		     ppt, pwidth, fSorted);
-    rop = pGC->alu;
-    if (pGC->fillStyle == FillStippled) {
-	switch (rop) {
-	    case GXand:
-	    case GXcopy:
-	    case GXnoop:
-	    case GXor:
-		stiprop = rop;
-		break;
-	    default:
-		stiprop = rop;
-		rop = GXcopy;
-	}
-    }
-    fgfill = PFILL(pGC->fgPixel);
-    bgfill = PFILL(pGC->bgPixel);
-
-    /*
-     *  OK,  so what's going on here?  We have two Drawables:
-     *
-     *  The Stipple:
-     *		Depth = 1
-     *		Width = stippleWidth
-     *		Words per scanline = stwidth
-     *		Pointer to pixels = pStipple->devPrivate.ptr
-     */
-    pStipple = pGC->stipple;
-
-    stwidth = pStipple->devKind / PGSZB;
-    stippleWidth = pStipple->drawable.width;
-    stippleHeight = pStipple->drawable.height;
-
-    /*
-     *	The Target:
-     *		Depth = PSZ
-     *		Width = determined from *pwidth
-     *		Words per scanline = nlwidth
-     *		Pointer to pixels = addrlBase
-     */
-
-    cfbGetLongWidthAndPointer (pDrawable, nlwidth, addrlBase)
-
-    /* this replaces rotating the stipple. Instead we just adjust the offset
-     * at which we start grabbing bits from the stipple.
-     * Ensure that ppt->x - xSrc >= 0 and ppt->y - ySrc >= 0,
-     * so that iline and xrem always stay within the stipple bounds.
-     */
-    modulus (pGC->patOrg.x, stippleWidth, xSrc);
-    xSrc += pDrawable->x - stippleWidth;
-    modulus (pGC->patOrg.y, stippleHeight, ySrc);
-    ySrc += pDrawable->y - stippleHeight;
-
-    while (n--)
-    {
-	iline = (ppt->y - ySrc) % stippleHeight;
-	x = ppt->x;
-	pdst = addrlBase + (ppt->y * nlwidth);
-        psrcS = (CfbBits *) pStipple->devPrivate.ptr + (iline * stwidth);
-
-	if (*pwidth)
-	{
-	    width = *pwidth;
-	    while(width > 0)
-	    {
-		int xtemp;
-#if PSZ != 32 || PPW != 1
-		int tmpx;
-#endif
-		register CfbBits *ptemp;
-		register CfbBits *pdsttmp;
-		/*
-		 *  Do a stripe through the stipple & destination w pixels
-		 *  wide.  w is not more than:
-		 *	-	the width of the destination
-		 *	-	the width of the stipple
-		 *	-	the distance between x and the next word 
-		 *		boundary in the destination
-		 *	-	the distance between x and the next word
-		 *		boundary in the stipple
-		 */
-
-		/* width of dest/stipple */
-                xrem = (x - xSrc) % stippleWidth;
-#if PSZ == 24
-		w = 1;
-#else
-	        w = min((stippleWidth - xrem), width);
-		/* dist to word bound in dest */
-		w = min(w, PPW - (x & PIM));
-		/* dist to word bound in stip */
-		w = min(w, MFB_PPW - (x & MFB_PIM));
-#endif
-
-	        xtemp = (xrem & MFB_PIM);
-	        ptemp = (CfbBits *)(psrcS + (xrem >> MFB_PWSH));
-#if PSZ == 24
-		tmpx = x & 3;
-		pdsttmp = pdst + ((x * 3)>>2);
-#else
-#if PSZ != 32 || PPW != 1
-		tmpx = x & PIM;
-#endif
-		pdsttmp = pdst + (x>>PWSH);
-#endif
-		switch ( pGC->fillStyle ) {
-		    case FillOpaqueStippled:
-#if PSZ == 24
-			getstipplepixels24(ptemp, xtemp, 0, &bgfill, &tmpDst1, xrem);
-			getstipplepixels24(ptemp, xtemp, 1, &fgfill, &tmpDst2, xrem);
-#else
-			getstipplepixels(ptemp, xtemp, w, 0, &bgfill, &tmpDst1);
-			getstipplepixels(ptemp, xtemp, w, 1, &fgfill, &tmpDst2);
-#endif
-			break;
-		    case FillStippled:
-			/* Fill tmpSrc with the source pixels */
-#if PSZ == 24
-			getbits24(pdsttmp, tmpSrc, x);
-			getstipplepixels24(ptemp, xtemp, 0, &tmpSrc, &tmpDst1, xrem);
-#else
-			getbits(pdsttmp, tmpx, w, tmpSrc);
-			getstipplepixels(ptemp, xtemp, w, 0, &tmpSrc, &tmpDst1);
-#endif
-			if (rop != stiprop) {
-#if PSZ == 24
-			    putbitsrop24(fgfill, 0, &tmpSrc, pGC->planemask, stiprop);
-#else
-			    putbitsrop(fgfill, 0, w, &tmpSrc, pGC->planemask, stiprop);
-#endif
-			} else {
-			    tmpSrc = fgfill;
-			}
-#if PSZ == 24
-			getstipplepixels24(ptemp, xtemp, 1, &tmpSrc, &tmpDst2, xrem);
-#else
-			getstipplepixels(ptemp, xtemp, w, 1, &tmpSrc, &tmpDst2);
-#endif
-			break;
-		}
-		tmpDst2 |= tmpDst1;
-#if PSZ == 24
-		putbitsrop24(tmpDst2, tmpx, pdsttmp, pGC->planemask, rop);
-#else
-		putbitsrop(tmpDst2, tmpx, w, pdsttmp, pGC->planemask, rop);
-#endif
-		x += w;
-		width -= w;
-	    }
-	}
-	ppt++;
-	pwidth++;
-    }
-    xfree(pptFree);
-    xfree(pwidthFree);
-}
-
-#endif /* PSZ == 8 */
-
-#if PSZ == 8
-
-void
-cfb8Stipple32FS (pDrawable, pGC, nInit, pptInit, pwidthInit, fSorted)
-    DrawablePtr pDrawable;
-    GCPtr	pGC;
-    int		nInit;			/* number of spans to fill */
-    DDXPointPtr pptInit;		/* pointer to list of start points */
-    int		*pwidthInit;		/* pointer to list of n widths */
-    int 	fSorted;
-{
-				/* next three parameters are post-clip */
-    int		    n;			/* number of spans to fill */
-    DDXPointPtr	    ppt;		/* pointer to list of start points */
-    int		    *pwidth;		/* pointer to list of n widths */
-    CfbBits   *src;		/* pointer to bits in stipple, if needed */
-    int		    stippleHeight;	/* height of the stipple */
-    PixmapPtr	    stipple;
-
-    int		    nlwDst;		/* width in longwords of the dest pixmap */
-    int		    x,y,w;		/* current span */
-    CfbBits   startmask;
-    CfbBits   endmask;
-    register CfbBits *dst;	/* pointer to bits we're writing */
-    register int    nlw;
-    CfbBits   *dstTmp;
-    int		    nlwTmp;
-
-    CfbBits   *pbits;		/* pointer to start of pixmap */
-    register CfbBits  xor;
-    register CfbBits  mask;
-    register CfbBits  bits;	/* bits from stipple */
-    int		    wEnd;
-
-    int		    *pwidthFree;	/* copies of the pointers to free */
-    DDXPointPtr	    pptFree;
-    cfbPrivGCPtr    devPriv;
-
-    devPriv = cfbGetGCPrivate(pGC);
-    cfb8CheckStipple (pGC->alu, pGC->fgPixel, pGC->planemask);
-    n = nInit * miFindMaxBand(pGC->pCompositeClip);
-    if ( n == 0 )
-	return;
-    pwidthFree = (int *)xalloc(n * sizeof(int));
-    pptFree = (DDXPointRec *)xalloc(n * sizeof(DDXPointRec));
-    if(!pptFree || !pwidthFree)
-    {
-	if (pptFree) xfree(pptFree);
-	if (pwidthFree) xfree(pwidthFree);
-	return;
-    }
-    pwidth = pwidthFree;
-    ppt = pptFree;
-    n = miClipSpans(pGC->pCompositeClip, pptInit, pwidthInit, nInit,
-		     ppt, pwidth, fSorted);
-
-    stipple = pGC->pRotatedPixmap;
-    src = (CfbBits *)stipple->devPrivate.ptr;
-    stippleHeight = stipple->drawable.height;
-
-    cfbGetLongWidthAndPointer (pDrawable, nlwDst, pbits)
-
-    while (n--)
-    {
-    	w = *pwidth++;
-	x = ppt->x;
-    	y = ppt->y;
-	ppt++;
-    	dst = pbits + (y * nlwDst) + (x >> PWSH);
-	if (((x & PIM) + w) <= PPW)
-	{
-	    maskpartialbits(x, w, startmask);
-	    endmask = 0;
-	    nlw = 0;
-	}
-	else
-	{
-	    maskbits (x, w, startmask, endmask, nlw);
-	}
-	bits = src[y % stippleHeight];
-	RotBitsLeft (bits, (x & ((PGSZ-1) & ~PIM)));
-#if PPW == 4
-	if (cfb8StippleRRop == GXcopy)
-	{
-	    xor = devPriv->xor;
-	    if (w < (PGSZ*2))
-	    {
-		if (startmask)
-		{
-		    mask = cfb8PixelMasks[GetBitGroup(bits)];
-		    *dst = (*dst & ~(mask & startmask)) |
-			   (xor & (mask & startmask));
-		    dst++;
-		    RotBitsLeft (bits, PGSZB);
-		}
-		while (nlw--)
-		{
-		    WriteBitGroup (dst,xor,GetBitGroup(bits))
-		    dst++;
-		    RotBitsLeft (bits, PGSZB);
-		}
-		if (endmask)
-		{
-		    mask = cfb8PixelMasks[GetBitGroup(bits)];
-		    *dst = (*dst & ~(mask & endmask)) |
-			   (xor & (mask & endmask));
-		}
-	    }
-	    else
-	    { /* XXX constants probably not OK here */
-		wEnd = 7 - (nlw & 7);
-		nlw = (nlw >> 3) + 1;
-		dstTmp = dst;
-		nlwTmp = nlw;
-		if (startmask)
-		{
-		    mask = cfb8PixelMasks[GetBitGroup(bits)];
-		    *dstTmp = (*dstTmp & ~(mask & startmask)) |
-			   (xor & (mask & startmask));
-		    dstTmp++;
-		    RotBitsLeft (bits, PGSZB);
-		}
-		w = 7 - wEnd;
-		while (w--)
-		{
-		    dst = dstTmp;
-		    dstTmp++;
-		    nlw = nlwTmp;
-#if defined(__GNUC__) && defined(mc68020)
-		    mask = cfb8PixelMasks[GetBitGroup(bits)];
-		    xor = xor & mask;
-		    mask = ~mask;
-		    while (nlw--)
-		    {
-			*dst = (*dst & mask) | xor;
-			dst += 8;
-		    }
-		    xor = devPriv->xor;
-#else
-#define SwitchBitsLoop(body) \
-    while (nlw--)	\
-    {		\
-	body	\
-	dst += 8;	\
-    }
-		    SwitchBitGroup(dst, xor, GetBitGroup(bits));
-#undef SwitchBitsLoop
-#endif
-		    NextBitGroup (bits);
-		}
-		nlwTmp--;
-		w = wEnd + 1;
-		if (endmask)
-		{
-		    mask = cfb8PixelMasks[GetBitGroup(bits)];
-		    dst = dstTmp + (nlwTmp << 3);
-		    *dst = (*dst & ~(mask & endmask)) |
-			   (xor &  (mask & endmask));
-		}
-		while (w--)
-		{
-		    nlw = nlwTmp;
-		    dst = dstTmp;
-		    dstTmp++;
-#if defined(__GNUC__) && defined(mc68020)
-		    mask = cfb8PixelMasks[GetBitGroup(bits)];
-		    xor = xor & mask;
-		    mask = ~mask;
-		    while (nlw--)
-		    {
-			*dst = (*dst & mask) | xor;
-			dst += 8;
-		    }
-		    xor = devPriv->xor;
-#else
-#define SwitchBitsLoop(body) \
-	while (nlw--)	\
-	{		\
-	    body	\
-	    dst += 8;	\
-	}
-		    SwitchBitGroup(dst, xor, GetBitGroup(bits));
-#undef SwitchBitsLoop
-#endif
-		    NextBitGroup (bits);
-		}
-	    }
-	}
-	else
-#endif /* PPW == 4 */
-	{
-	    if (startmask)
-	    {
-		xor = GetBitGroup(bits);
-		*dst = MaskRRopPixels(*dst, xor, startmask);
-		dst++;
-		RotBitsLeft (bits, PGSZB);
-	    }
-	    while (nlw--)
-	    {
-		RRopBitGroup(dst, GetBitGroup(bits));
-		dst++;
-		RotBitsLeft (bits, PGSZB);
-	    }
-	    if (endmask)
-	    {
-		xor = GetBitGroup(bits);
-		*dst = MaskRRopPixels(*dst, xor, endmask);
-	    }
-	}
-    }
-    xfree(pptFree);
-    xfree(pwidthFree);
-}
-
-void
-cfb8OpaqueStipple32FS (pDrawable, pGC, nInit, pptInit, pwidthInit, fSorted)
-    DrawablePtr pDrawable;
-    GCPtr	pGC;
-    int		nInit;			/* number of spans to fill */
-    DDXPointPtr pptInit;		/* pointer to list of start points */
-    int		*pwidthInit;		/* pointer to list of n widths */
-    int 	fSorted;
-{
-				/* next three parameters are post-clip */
-    int		    n;			/* number of spans to fill */
-    DDXPointPtr	    ppt;		/* pointer to list of start points */
-    int		    *pwidth;		/* pointer to list of n widths */
-    CfbBits   *src;		/* pointer to bits in stipple, if needed */
-    int		    stippleHeight;	/* height of the stipple */
-    PixmapPtr	    stipple;
-
-    int		    nlwDst;		/* width in longwords of the dest pixmap */
-    int		    x,y,w;		/* current span */
-    CfbBits   startmask;
-    CfbBits   endmask;
-    register CfbBits *dst;	/* pointer to bits we're writing */
-    register int    nlw;
-    CfbBits   *dstTmp;
-    int		    nlwTmp;
-
-    CfbBits   *pbits;		/* pointer to start of pixmap */
-    register CfbBits  xor;
-    register CfbBits  bits;	/* bits from stipple */
-    int		    wEnd;
-
-    int		    *pwidthFree;	/* copies of the pointers to free */
-    DDXPointPtr	    pptFree;
-    cfbPrivGCPtr    devPriv;
-
-    devPriv = cfbGetGCPrivate(pGC);
-
-    cfb8CheckOpaqueStipple(pGC->alu, pGC->fgPixel, pGC->bgPixel, pGC->planemask);
-
-    n = nInit * miFindMaxBand(pGC->pCompositeClip);
-    if ( n == 0 )
-	return;
-    pwidthFree = (int *)xalloc(n * sizeof(int));
-    pptFree = (DDXPointRec *)xalloc(n * sizeof(DDXPointRec));
-    if(!pptFree || !pwidthFree)
-    {
-	if (pptFree) xfree(pptFree);
-	if (pwidthFree) xfree(pwidthFree);
-	return;
-    }
-    pwidth = pwidthFree;
-    ppt = pptFree;
-    n = miClipSpans(pGC->pCompositeClip, pptInit, pwidthInit, nInit,
-		     ppt, pwidth, fSorted);
-
-    stipple = pGC->pRotatedPixmap;
-    src = (CfbBits *)stipple->devPrivate.ptr;
-    stippleHeight = stipple->drawable.height;
-
-    cfbGetLongWidthAndPointer (pDrawable, nlwDst, pbits)
-
-    while (n--)
-    {
-    	w = *pwidth++;
-	x = ppt->x;
-    	y = ppt->y;
-	ppt++;
-    	dst = pbits + (y * nlwDst) + (x >> PWSH);
-	if (((x & PIM) + w) <= PPW)
-	{
-	    maskpartialbits(x, w, startmask);
-	    endmask = 0;
-	    nlw = 0;
-	}
-	else
-	{
-	    maskbits (x, w, startmask, endmask, nlw);
-	}
-	bits = src[y % stippleHeight];
-	RotBitsLeft (bits, (x & ((PGSZ-1) & ~PIM)));
-#if PPW == 4
-	if (cfb8StippleRRop == GXcopy)
-	{
-	    xor = devPriv->xor;
-	    if (w < PGSZ*2)
-	    {
-		if (startmask)
-		{
-		    *dst = (*dst & ~startmask) |
-			   (GetPixelGroup (bits) & startmask);
-		    dst++;
-		    RotBitsLeft (bits, PGSZB);
-		}
-		while (nlw--)
-		{
-		    *dst++ = GetPixelGroup(bits);
-		    RotBitsLeft (bits, PGSZB);
-		}
-		if (endmask)
-		{
-		    *dst = (*dst & ~endmask) |
-			   (GetPixelGroup (bits) & endmask);
-		}
-	    }
-	    else
-	    { /* XXX consts probably not OK here */
-		wEnd = 7 - (nlw & 7);
-		nlw = (nlw >> 3) + 1;
-		dstTmp = dst;
-		nlwTmp = nlw;
-		if (startmask)
-		{
-		    *dstTmp = (*dstTmp & ~startmask) |
-			      (GetPixelGroup (bits) & startmask);
-		    dstTmp++;
-		    RotBitsLeft (bits, PGSZB);
-		}
-		w = 7 - wEnd;
-		while (w--)
-		{
-		    nlw = nlwTmp;
-		    dst = dstTmp;
-		    dstTmp++;
-		    xor = GetPixelGroup (bits);
-		    while (nlw--)
-		    {
-			*dst = xor;
-			dst += 8;
-		    }
-		    NextBitGroup (bits);
-		}
-		nlwTmp--;
-		w = wEnd + 1;
-		if (endmask)
-		{
-		    dst = dstTmp + (nlwTmp << 3);
-		    *dst = (*dst & ~endmask) |
-			   (GetPixelGroup (bits) & endmask);
-		}
-		while (w--)
-		{
-		    nlw = nlwTmp;
-		    dst = dstTmp;
-		    dstTmp++;
-		    xor = GetPixelGroup (bits);
-		    while (nlw--)
-		    {
-			*dst = xor;
-			dst += 8;
-		    }
-		    NextBitGroup (bits);
-		}
-	    }
-	}
-	else
-#endif /* PPW == 4 */
-	{
-	    if (startmask)
-	    {
-		xor = GetBitGroup(bits);
-		*dst = MaskRRopPixels(*dst, xor, startmask);
-		dst++;
-		RotBitsLeft (bits, PGSZB);
-	    }
-	    while (nlw--)
-	    {
-		RRopBitGroup(dst, GetBitGroup(bits));
-		dst++;
-		RotBitsLeft (bits, PGSZB);
-	    }
-	    if (endmask)
-	    {
-		xor = GetBitGroup(bits);
-		*dst = MaskRRopPixels(*dst, xor, endmask);
-	    }
-	}
-    }
-    xfree(pptFree);
-    xfree(pwidthFree);
-}
-
-#endif /* PSZ == 8 */
diff --git a/cfb/cfbgc.c b/cfb/cfbgc.c
deleted file mode 100644
index a74c28c..0000000
--- a/cfb/cfbgc.c
+++ /dev/null
@@ -1,799 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <stdlib.h>
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include <X11/Xproto.h>
-#include "cfb.h"
-#include <X11/fonts/fontstruct.h>
-#include "dixfontstr.h"
-#include "gcstruct.h"
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "region.h"
-
-#include "mistruct.h"
-#include "mibstore.h"
-#include "migc.h"
-
-#include "cfbmskbits.h"
-#include "cfb8bit.h"
-
-#if PSZ == 8
-# define useTEGlyphBlt  cfbTEGlyphBlt8
-#else
-# ifdef WriteBitGroup
-#  define useTEGlyphBlt	cfbImageGlyphBlt8
-# else
-#  define useTEGlyphBlt	cfbTEGlyphBlt
-# endif
-#endif
-
-#ifdef WriteBitGroup
-# define useImageGlyphBlt	cfbImageGlyphBlt8
-# define usePolyGlyphBlt	cfbPolyGlyphBlt8
-#else
-# define useImageGlyphBlt	miImageGlyphBlt
-# define usePolyGlyphBlt	miPolyGlyphBlt
-#endif
-
-static void cfbUnPushPixels (GCPtr, PixmapPtr, DrawablePtr, int, int, int, int);
-
-#ifdef FOUR_BIT_CODE
-# define usePushPixels	cfbPushPixels8
-#else
-# define usePushPixels	cfbUnPushPixels
-#endif
-
-#ifdef PIXEL_ADDR
-# define ZeroPolyArc	cfbZeroPolyArcSS8Copy
-#else
-# define ZeroPolyArc	miZeroPolyArc
-#endif
-
-GCFuncs cfbGCFuncs = {
-    cfbValidateGC,
-    miChangeGC,
-    miCopyGC,
-    miDestroyGC,
-    miChangeClip,
-    miDestroyClip,
-    miCopyClip,
-};
-
-GCOps	cfbTEOps1Rect = {
-    cfbSolidSpansCopy,
-    cfbSetSpans,
-    cfbPutImage,
-    cfbCopyArea,
-    cfbCopyPlane,
-    cfbPolyPoint,
-#ifdef PIXEL_ADDR
-    cfb8LineSS1Rect,
-    cfb8SegmentSS1Rect,
-#else
-    cfbLineSS,
-    cfbSegmentSS,
-#endif
-    miPolyRectangle,
-    ZeroPolyArc,
-    cfbFillPoly1RectCopy,
-    cfbPolyFillRect,
-    cfbPolyFillArcSolidCopy,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    useTEGlyphBlt,
-    usePolyGlyphBlt,
-    usePushPixels
-};
-
-GCOps	cfbNonTEOps1Rect = {
-    cfbSolidSpansCopy,
-    cfbSetSpans,
-    cfbPutImage,
-    cfbCopyArea,
-    cfbCopyPlane,
-    cfbPolyPoint,
-#ifdef PIXEL_ADDR
-    cfb8LineSS1Rect,
-    cfb8SegmentSS1Rect,
-#else
-    cfbLineSS,
-    cfbSegmentSS,
-#endif
-    miPolyRectangle,
-    ZeroPolyArc,
-    cfbFillPoly1RectCopy,
-    cfbPolyFillRect,
-    cfbPolyFillArcSolidCopy,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    useImageGlyphBlt,
-    usePolyGlyphBlt,
-    usePushPixels
-};
-
-GCOps	cfbTEOps = {
-    cfbSolidSpansCopy,
-    cfbSetSpans,
-    cfbPutImage,
-    cfbCopyArea,
-    cfbCopyPlane,
-    cfbPolyPoint,
-    cfbLineSS,
-    cfbSegmentSS,
-    miPolyRectangle,
-    ZeroPolyArc,
-    miFillPolygon,
-    cfbPolyFillRect,
-    cfbPolyFillArcSolidCopy,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    useTEGlyphBlt,
-    usePolyGlyphBlt,
-    usePushPixels
-};
-
-GCOps	cfbNonTEOps = {
-    cfbSolidSpansCopy,
-    cfbSetSpans,
-    cfbPutImage,
-    cfbCopyArea,
-    cfbCopyPlane,
-    cfbPolyPoint,
-    cfbLineSS,
-    cfbSegmentSS,
-    miPolyRectangle,
-#ifdef PIXEL_ADDR
-    cfbZeroPolyArcSS8Copy,
-#else
-    miZeroPolyArc,
-#endif
-    miFillPolygon,
-    cfbPolyFillRect,
-    cfbPolyFillArcSolidCopy,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    useImageGlyphBlt,
-    usePolyGlyphBlt,
-    usePushPixels
-};
-
-GCOps *
-cfbMatchCommon (pGC, devPriv)
-    GCPtr	    pGC;
-    cfbPrivGCPtr    devPriv;
-{
-    if (pGC->lineWidth != 0)
-	return 0;
-    if (pGC->lineStyle != LineSolid)
-	return 0;
-    if (pGC->fillStyle != FillSolid)
-	return 0;
-    if (devPriv->rop != GXcopy)
-	return 0;
-    if (pGC->font &&
-	FONTMAXBOUNDS(pGC->font,rightSideBearing) -
-        FONTMINBOUNDS(pGC->font,leftSideBearing) <= 32 &&
-	FONTMINBOUNDS(pGC->font,characterWidth) >= 0)
-    {
-	if (TERMINALFONT(pGC->font)
-#ifdef FOUR_BIT_CODE
-	    && FONTMAXBOUNDS(pGC->font,characterWidth) >= PGSZB
-#endif
-	)
-#ifdef NO_ONE_RECT
-            return &cfbTEOps1Rect;
-#else
-	    if (devPriv->oneRect)
-		return &cfbTEOps1Rect;
-	    else
-		return &cfbTEOps;
-#endif
-	else
-#ifdef NO_ONE_RECT
-	    return &cfbNonTEOps1Rect;
-#else
-	    if (devPriv->oneRect)
-		return &cfbNonTEOps1Rect;
-	    else
-		return &cfbNonTEOps;
-#endif
-    }
-    return 0;
-}
-
-Bool
-cfbCreateGC(pGC)
-    register GCPtr pGC;
-{
-    cfbPrivGC  *pPriv;
-
-    if (PixmapWidthPaddingInfo[pGC->depth].padPixelsLog2 == LOG2_BITMAP_PAD)
-	return (mfbCreateGC(pGC));
-    pGC->clientClip = NULL;
-    pGC->clientClipType = CT_NONE;
-
-    if (cfbNonTEOps.PushPixels == cfbUnPushPixels)
-    {
-        cfbTEOps1Rect.PushPixels    = mfbPushPixelsWeak();
-        cfbNonTEOps1Rect.PushPixels = mfbPushPixelsWeak();
-        cfbTEOps.PushPixels         = mfbPushPixelsWeak();
-        cfbNonTEOps.PushPixels      = mfbPushPixelsWeak();		    
-    }
-
-    /*
-     * some of the output primitives aren't really necessary, since they
-     * will be filled in ValidateGC because of dix/CreateGC() setting all
-     * the change bits.  Others are necessary because although they depend
-     * on being a color frame buffer, they don't change 
-     */
-
-    pGC->ops = &cfbNonTEOps;
-    pGC->funcs = &cfbGCFuncs;
-
-    /* cfb wants to translate before scan conversion */
-    pGC->miTranslate = 1;
-
-    pPriv = cfbGetGCPrivate(pGC);
-    pPriv->rop = pGC->alu;
-    pPriv->oneRect = FALSE;
-    pGC->fExpose = TRUE;
-    pGC->freeCompClip = FALSE;
-    pGC->pRotatedPixmap = (PixmapPtr) NULL;
-    return TRUE;
-}
-
-/* Clipping conventions
-	if the drawable is a window
-	    CT_REGION ==> pCompositeClip really is the composite
-	    CT_other ==> pCompositeClip is the window clip region
-	if the drawable is a pixmap
-	    CT_REGION ==> pCompositeClip is the translated client region
-		clipped to the pixmap boundary
-	    CT_other ==> pCompositeClip is the pixmap bounding box
-*/
-
-void
-cfbValidateGC(pGC, changes, pDrawable)
-    register GCPtr  pGC;
-    unsigned long   changes;
-    DrawablePtr	    pDrawable;
-{
-    int         mask;		/* stateChanges */
-    int         index;		/* used for stepping through bitfields */
-    int		new_rrop;
-    int         new_line, new_text, new_fillspans, new_fillarea;
-    int		new_rotate;
-    int		xrot, yrot;
-    /* flags for changing the proc vector */
-    cfbPrivGCPtr devPriv;
-    int		oneRect;
-
-    new_rotate = pGC->lastWinOrg.x != pDrawable->x ||
-		 pGC->lastWinOrg.y != pDrawable->y;
-
-    pGC->lastWinOrg.x = pDrawable->x;
-    pGC->lastWinOrg.y = pDrawable->y;
-    devPriv = cfbGetGCPrivate(pGC);
-
-    new_rrop = FALSE;
-    new_line = FALSE;
-    new_text = FALSE;
-    new_fillspans = FALSE;
-    new_fillarea = FALSE;
-
-    /*
-     * if the client clip is different or moved OR the subwindowMode has
-     * changed OR the window's clip has changed since the last validation
-     * we need to recompute the composite clip 
-     */
-
-    if ((changes & (GCClipXOrigin|GCClipYOrigin|GCClipMask|GCSubwindowMode)) ||
-	(pDrawable->serialNumber != (pGC->serialNumber & DRAWABLE_SERIAL_BITS))
-	)
-    {
-	miComputeCompositeClip (pGC, pDrawable);
-#ifdef NO_ONE_RECT
-	devPriv->oneRect = FALSE;
-#else
-	oneRect = REGION_NUM_RECTS(pGC->pCompositeClip) == 1;
-	if (oneRect != devPriv->oneRect)
-	    new_line = TRUE;
-	devPriv->oneRect = oneRect;
-#endif
-    }
-
-    mask = changes;
-    while (mask) {
-	index = lowbit (mask);
-	mask &= ~index;
-
-	/*
-	 * this switch acculmulates a list of which procedures might have
-	 * to change due to changes in the GC.  in some cases (e.g.
-	 * changing one 16 bit tile for another) we might not really need
-	 * a change, but the code is being paranoid. this sort of batching
-	 * wins if, for example, the alu and the font have been changed,
-	 * or any other pair of items that both change the same thing. 
-	 */
-	switch (index) {
-	case GCFunction:
-	case GCForeground:
-	    new_rrop = TRUE;
-	    break;
-	case GCPlaneMask:
-	    new_rrop = TRUE;
-	    new_text = TRUE;
-	    break;
-	case GCBackground:
-	    break;
-	case GCLineStyle:
-	case GCLineWidth:
-	    new_line = TRUE;
-	    break;
-	case GCJoinStyle:
-	case GCCapStyle:
-	    break;
-	case GCFillStyle:
-	    new_text = TRUE;
-	    new_fillspans = TRUE;
-	    new_line = TRUE;
-	    new_fillarea = TRUE;
-	    break;
-	case GCFillRule:
-	    break;
-	case GCTile:
-	    new_fillspans = TRUE;
-	    new_fillarea = TRUE;
-	    break;
-
-	case GCStipple:
-	    if (pGC->stipple)
-	    {
-		int width = pGC->stipple->drawable.width;
-		PixmapPtr nstipple;
-
-		if ((width <= PGSZ) && !(width & (width - 1)) &&
-		    (nstipple = cfbCopyPixmap(pGC->stipple)))
-		{
-		    cfbPadPixmap(nstipple);
-		    (*pGC->pScreen->DestroyPixmap)(pGC->stipple);
-		    pGC->stipple = nstipple;
-		}
-	    }
-	    new_fillspans = TRUE;
-	    new_fillarea = TRUE;
-	    break;
-
-	case GCTileStipXOrigin:
-	    new_rotate = TRUE;
-	    break;
-
-	case GCTileStipYOrigin:
-	    new_rotate = TRUE;
-	    break;
-
-	case GCFont:
-	    new_text = TRUE;
-	    break;
-	case GCSubwindowMode:
-	    break;
-	case GCGraphicsExposures:
-	    break;
-	case GCClipXOrigin:
-	    break;
-	case GCClipYOrigin:
-	    break;
-	case GCClipMask:
-	    break;
-	case GCDashOffset:
-	    break;
-	case GCDashList:
-	    break;
-	case GCArcMode:
-	    break;
-	default:
-	    break;
-	}
-    }
-
-    /*
-     * If the drawable has changed,  ensure suitable
-     * entries are in the proc vector. 
-     */
-    if (pDrawable->serialNumber != (pGC->serialNumber & (DRAWABLE_SERIAL_BITS))) {
-	new_fillspans = TRUE;	/* deal with FillSpans later */
-    }
-
-    if (new_rotate || new_fillspans)
-    {
-	Bool new_pix = FALSE;
-
-	xrot = pGC->patOrg.x + pDrawable->x;
-	yrot = pGC->patOrg.y + pDrawable->y;
-
-	switch (pGC->fillStyle)
-	{
-	case FillTiled:
-	    if (!pGC->tileIsPixel)
-	    {
-		int width = pGC->tile.pixmap->drawable.width * PSZ;
-
-		if ((width <= PGSZ) && !(width & (width - 1)))
-		{
-		    cfbCopyRotatePixmap(pGC->tile.pixmap, &pGC->pRotatedPixmap,
-					xrot, yrot);
-		    new_pix = TRUE;
-		}
-	    }
-	    break;
-#ifdef FOUR_BIT_CODE
-	case FillStippled:
-	case FillOpaqueStippled:
-	    {
-		int width = pGC->stipple->drawable.width;
-
-		if ((width <= PGSZ) && !(width & (width - 1)))
-		{
-		    mfbCopyRotatePixmap(pGC->stipple, &pGC->pRotatedPixmap,
-					xrot, yrot);
-		    new_pix = TRUE;
-		}
-	    }
-	    break;
-#endif
-	}
-	if (!new_pix && pGC->pRotatedPixmap)
-	{
-	    (*pGC->pScreen->DestroyPixmap)(pGC->pRotatedPixmap);
-	    pGC->pRotatedPixmap = (PixmapPtr) NULL;
-	}
-    }
-
-    if (new_rrop)
-    {
-	int old_rrop;
-
-	old_rrop = devPriv->rop;
-	devPriv->rop = cfbReduceRasterOp (pGC->alu, pGC->fgPixel,
-					   pGC->planemask,
-					   &devPriv->and, &devPriv->xor);
-	if (old_rrop == devPriv->rop)
-	    new_rrop = FALSE;
-	else
-	{
-#ifdef PIXEL_ADDR
-	    new_line = TRUE;
-#endif
-#ifdef WriteBitGroup
-	    new_text = TRUE;
-#endif
-	    new_fillspans = TRUE;
-	    new_fillarea = TRUE;
-	}
-    }
-
-    if (new_rrop || new_fillspans || new_text || new_fillarea || new_line)
-    {
-	GCOps	*newops;
-
-	if ((newops = cfbMatchCommon (pGC, devPriv)))
- 	{
-	    if (pGC->ops->devPrivate.val)
-		miDestroyGCOps (pGC->ops);
-	    pGC->ops = newops;
-	    new_rrop = new_line = new_fillspans = new_text = new_fillarea = 0;
-	}
- 	else
- 	{
-	    if (!pGC->ops->devPrivate.val)
-	    {
-		pGC->ops = miCreateGCOps (pGC->ops);
-		pGC->ops->devPrivate.val = 1;
-	    }
-	}
-    }
-
-    /* deal with the changes we've collected */
-    if (new_line)
-    {
-	pGC->ops->FillPolygon = miFillPolygon;
-#ifdef NO_ONE_RECT
-	if (pGC->fillStyle == FillSolid)
-	{
-	    switch (devPriv->rop) {
-	    case GXcopy:
-		pGC->ops->FillPolygon = cfbFillPoly1RectCopy;
-		break;
-	    default:
-		pGC->ops->FillPolygon = cfbFillPoly1RectGeneral;
-		break;
-	    }
-	}
-#else
-	if (devPriv->oneRect && pGC->fillStyle == FillSolid)
-	{
-	    switch (devPriv->rop) {
-	    case GXcopy:
-		pGC->ops->FillPolygon = cfbFillPoly1RectCopy;
-		break;
-	    default:
-		pGC->ops->FillPolygon = cfbFillPoly1RectGeneral;
-		break;
-	    }
-	}
-#endif
-	if (pGC->lineWidth == 0)
-	{
-#ifdef PIXEL_ADDR
-	    if ((pGC->lineStyle == LineSolid) && (pGC->fillStyle == FillSolid))
-	    {
-		switch (devPriv->rop)
-		{
-		case GXxor:
-		    pGC->ops->PolyArc = cfbZeroPolyArcSS8Xor;
-		    break;
-		case GXcopy:
-		    pGC->ops->PolyArc = cfbZeroPolyArcSS8Copy;
-		    break;
-		default:
-		    pGC->ops->PolyArc = cfbZeroPolyArcSS8General;
-		    break;
-		}
-	    }
-	    else
-#endif
-		pGC->ops->PolyArc = miZeroPolyArc;
-	}
-	else
-	    pGC->ops->PolyArc = miPolyArc;
-	pGC->ops->PolySegment = miPolySegment;
-	switch (pGC->lineStyle)
-	{
-	case LineSolid:
-	    if(pGC->lineWidth == 0)
-	    {
-		if (pGC->fillStyle == FillSolid)
-		{
-#if defined(PIXEL_ADDR) && !defined(NO_ONE_RECT)
-		    if (devPriv->oneRect &&
-			((pDrawable->x >= pGC->pScreen->width - 32768) &&
-			 (pDrawable->y >= pGC->pScreen->height - 32768)))
-		    {
-			pGC->ops->Polylines = cfb8LineSS1Rect;
-			pGC->ops->PolySegment = cfb8SegmentSS1Rect;
-		    } else
-#endif
-#ifdef NO_ONE_RECT
-		    {
-			pGC->ops->Polylines = cfb8LineSS1Rect;
-			pGC->ops->PolySegment = cfb8SegmentSS1Rect;
-		    }
-#else
-		    {
-		    	pGC->ops->Polylines = cfbLineSS;
-		    	pGC->ops->PolySegment = cfbSegmentSS;
-		    }
-#endif
-		}
- 		else
-		    pGC->ops->Polylines = miZeroLine;
-	    }
-	    else
-		pGC->ops->Polylines = miWideLine;
-	    break;
-	case LineOnOffDash:
-	case LineDoubleDash:
-	    if (pGC->lineWidth == 0 && pGC->fillStyle == FillSolid)
-	    {
-		pGC->ops->Polylines = cfbLineSD;
-		pGC->ops->PolySegment = cfbSegmentSD;
-	    } else
-		pGC->ops->Polylines = miWideDash;
-	    break;
-	}
-    }
-
-    if (new_text && (pGC->font))
-    {
-        if (FONTMAXBOUNDS(pGC->font,rightSideBearing) -
-            FONTMINBOUNDS(pGC->font,leftSideBearing) > 32 ||
-	    FONTMINBOUNDS(pGC->font,characterWidth) < 0)
-        {
-            pGC->ops->PolyGlyphBlt = miPolyGlyphBlt;
-            pGC->ops->ImageGlyphBlt = miImageGlyphBlt;
-        }
-        else
-        {
-#ifdef WriteBitGroup
-	    if (pGC->fillStyle == FillSolid)
-	    {
-		if (devPriv->rop == GXcopy)
-		    pGC->ops->PolyGlyphBlt = cfbPolyGlyphBlt8;
-		else
-#ifdef FOUR_BIT_CODE
-		    pGC->ops->PolyGlyphBlt = cfbPolyGlyphRop8;
-#else
-		    pGC->ops->PolyGlyphBlt = miPolyGlyphBlt;
-#endif
-	    }
-	    else
-#endif
-		pGC->ops->PolyGlyphBlt = miPolyGlyphBlt;
-            /* special case ImageGlyphBlt for terminal emulator fonts */
-#if !defined(WriteBitGroup) || PSZ == 8
-	    if (TERMINALFONT(pGC->font) &&
-		(pGC->planemask & PMSK) == PMSK
-#ifdef FOUR_BIT_CODE
-		&& FONTMAXBOUNDS(pGC->font,characterWidth) >= PGSZB
-#endif
-		)
-	    {
-		pGC->ops->ImageGlyphBlt = useTEGlyphBlt;
-	    }
-            else
-#endif
-	    {
-#ifdef WriteBitGroup
-		if (devPriv->rop == GXcopy &&
-		    pGC->fillStyle == FillSolid &&
-		    (pGC->planemask & PMSK) == PMSK)
-		    pGC->ops->ImageGlyphBlt = cfbImageGlyphBlt8;
-		else
-#endif
-		    pGC->ops->ImageGlyphBlt = miImageGlyphBlt;
-	    }
-        }
-    }    
-
-
-    if (new_fillspans) {
-	switch (pGC->fillStyle) {
-	case FillSolid:
-	    switch (devPriv->rop) {
-	    case GXcopy:
-		pGC->ops->FillSpans = cfbSolidSpansCopy;
-		break;
-	    case GXxor:
-		pGC->ops->FillSpans = cfbSolidSpansXor;
-		break;
-	    default:
-		pGC->ops->FillSpans = cfbSolidSpansGeneral;
-		break;
-	    }
-	    break;
-	case FillTiled:
-	    if (pGC->pRotatedPixmap)
-	    {
-		if (pGC->alu == GXcopy && (pGC->planemask & PMSK) == PMSK)
-		    pGC->ops->FillSpans = cfbTile32FSCopy;
-		else
-		    pGC->ops->FillSpans = cfbTile32FSGeneral;
-	    }
-	    else
-		pGC->ops->FillSpans = cfbUnnaturalTileFS;
-	    break;
-	case FillStippled:
-#ifdef FOUR_BIT_CODE
-	    if (pGC->pRotatedPixmap)
-		pGC->ops->FillSpans = cfb8Stipple32FS;
-	    else
-#endif
-		pGC->ops->FillSpans = cfbUnnaturalStippleFS;
-	    break;
-	case FillOpaqueStippled:
-#ifdef FOUR_BIT_CODE
-	    if (pGC->pRotatedPixmap)
-		pGC->ops->FillSpans = cfb8OpaqueStipple32FS;
-	    else
-#endif
-		pGC->ops->FillSpans = cfbUnnaturalStippleFS;
-	    break;
-	default:
-	    FatalError("cfbValidateGC: illegal fillStyle\n");
-	}
-    } /* end of new_fillspans */
-
-    if (new_fillarea) {
-#ifndef FOUR_BIT_CODE
-	pGC->ops->PolyFillRect = miPolyFillRect;
-	if (pGC->fillStyle == FillSolid || pGC->fillStyle == FillTiled)
-	{
-	    pGC->ops->PolyFillRect = cfbPolyFillRect;
-	}
-#endif
-#ifdef FOUR_BIT_CODE
-	pGC->ops->PushPixels = mfbPushPixelsWeak();
-	if (pGC->fillStyle == FillSolid && devPriv->rop == GXcopy)
-	    pGC->ops->PushPixels = cfbPushPixels8;
-#endif
-	pGC->ops->PolyFillArc = miPolyFillArc;
-	if (pGC->fillStyle == FillSolid)
-	{
-	    switch (devPriv->rop)
-	    {
-	    case GXcopy:
-		pGC->ops->PolyFillArc = cfbPolyFillArcSolidCopy;
-		break;
-	    default:
-		pGC->ops->PolyFillArc = cfbPolyFillArcSolidGeneral;
-		break;
-	    }
-	}
-    }
-}
-
-/*
- * this is never called, it just exists to have its address
- * taken in mfbCreateGC.
- */
-static void
-cfbUnPushPixels (pGC, pBitmap, pDrawable, dx, dy, xOrg, yOrg)
-    GCPtr       pGC;
-    PixmapPtr   pBitmap;
-    DrawablePtr pDrawable;
-    int         dx, dy, xOrg, yOrg;
-{
-    return;
-}
diff --git a/cfb/cfbgetsp.c b/cfb/cfbgetsp.c
deleted file mode 100644
index 672196a..0000000
--- a/cfb/cfbgetsp.c
+++ /dev/null
@@ -1,213 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "servermd.h"
-
-#include "misc.h"
-#include "region.h"
-#include "gc.h"
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-
-#include "cfb.h"
-#include "cfbmskbits.h"
-
-/* GetSpans -- for each span, gets bits from drawable starting at ppt[i]
- * and continuing for pwidth[i] bits
- * Each scanline returned will be server scanline padded, i.e., it will come
- * out to an integral number of words.
- */
-void
-cfbGetSpans(pDrawable, wMax, ppt, pwidth, nspans, pchardstStart)
-    DrawablePtr		pDrawable;	/* drawable from which to get bits */
-    int			wMax;		/* largest value of all *pwidths */
-    register DDXPointPtr ppt;		/* points to start copying from */
-    int			*pwidth;	/* list of number of bits to copy */
-    int			nspans;		/* number of scanlines to copy */
-    char		*pchardstStart; /* where to put the bits */
-{
-    PixelGroup	*pdstStart = (PixelGroup *)pchardstStart;
-    register PixelGroup	*pdst;		/* where to put the bits */
-    register PixelGroup	*psrc;		/* where to get the bits */
-    register PixelGroup	tmpSrc;		/* scratch buffer for bits */
-    PixelGroup		*psrcBase;	/* start of src bitmap */
-    int			widthSrc;	/* width of pixmap in bytes */
-    register DDXPointPtr pptLast;	/* one past last point to get */
-    int         	xEnd;		/* last pixel to copy from */
-    int			nl, srcBit;
-    int			w;
-    PixelGroup		*pdstNext;
-#if PSZ == 24
-    register char *psrcb, *pdstb;
-    register int xIndex = 0;
-#else
-    register int	nstart; 
-#if PSZ != 32 || PPW != 1
-    int	 		nend; 
-#endif
-    PixelGroup		startmask, endmask;
-    int			nlMiddle;
-#endif
-
-    switch (pDrawable->bitsPerPixel) {
-	case 1:
-	    mfbGetSpans(pDrawable, wMax, ppt, pwidth, nspans, pchardstStart);
-	    return;
-	case PSZ:
-	    break;
-	default:
-	    FatalError("cfbGetSpans: invalid depth\n");
-    }
-
-    /*
-     * XFree86 DDX empties the root borderClip when the VT is
-     * switched away; this checks for that case
-     */
-    if (!cfbDrawableEnabled(pDrawable))
-	return;
-    
-    cfbGetLongWidthAndPointer (pDrawable, widthSrc, psrcBase)
-
-#ifdef PIXEL_ADDR
-# if PSZ != 24
-    if ((nspans == 1) && (*pwidth == 1))
-    {
-	tmpSrc = *((PixelType *)(psrcBase + (ppt->y * widthSrc))
-		   + ppt->x);
-#if BITMAP_BIT_ORDER == MSBFirst
-	tmpSrc <<= (sizeof (CfbBits) - sizeof (PixelType)) * 8;
-#endif
-	*pdstStart = tmpSrc;
-	return;
-    }
-# endif /* PSZ != 24 */
-#endif
-    pdst = pdstStart;
-    pptLast = ppt + nspans;
-    while(ppt < pptLast)
-    {
-#if PSZ == 24
-	xEnd = min(ppt->x + *pwidth, widthSrc * sizeof(CfbBits) / 3);
-	w = xEnd - ppt->x;
-	psrc = psrcBase + ppt->y * widthSrc;
-	srcBit = ppt->x;
-	psrcb = (char *)psrc + (ppt->x * 3);
-	xIndex = 0;
-	pdstb = (char *)pdst;
-    	pdstNext = pdst + ((w * 3 + 3) >> 2);
-#else
-	xEnd = min(ppt->x + *pwidth, widthSrc << PWSH);
-	w = xEnd - ppt->x;
-	psrc = psrcBase + ppt->y * widthSrc + (ppt->x >> PWSH); 
-	srcBit = ppt->x & PIM;
-    	pdstNext = pdst + ((w + PPW - 1) >> PWSH);
-#endif
-
-#if PSZ == 24
-	if (w < 0)
-	  FatalError("cfb24GetSpans: Internal error (w < 0)\n");
-	nl = w;
-	while (nl--){ 
-	  psrc = (PixelGroup *)((unsigned long)psrcb & ~0x03);
-	  getbits24(psrc, tmpSrc, srcBit);
-	  pdst = (PixelGroup *)((unsigned long)pdstb & ~0x03);
-	  putbits24(tmpSrc, PPW, pdst, ~((CfbBits)0), xIndex);
-	  srcBit++;
-	  psrcb += 3;
-	  xIndex++;
-	  pdstb += 3;
-	} 
-	pdst = pdstNext;
-#else /* PSZ == 24 */
-	if (srcBit + w <= PPW) 
-	{ 
-	    getbits(psrc, srcBit, w, tmpSrc);
-	    putbits(tmpSrc, 0, w, pdst, ~((CfbBits)0)); 
-	    pdst++;
-	} 
-	else 
-	{ 
-	    maskbits(ppt->x, w, startmask, endmask, nlMiddle);
-	    nstart = 0; 
-	    if (startmask) 
-	    { 
-		nstart = PPW - srcBit; 
-		getbits(psrc, srcBit, nstart, tmpSrc);
-		putbits(tmpSrc, 0, nstart, pdst, ~((CfbBits)0));
-		if(srcBit + nstart >= PPW)
-		    psrc++;
-	    } 
-	    nl = nlMiddle; 
-	    while (nl--) 
-	    { 
-		tmpSrc = *psrc;
-		putbits(tmpSrc, nstart, PPW, pdst, ~((CfbBits)0));
-		psrc++;
-		pdst++;
-	    } 
-	    if (endmask) 
-	    { 
-#if PSZ != 32 || PPW != 1
-		nend = xEnd & PIM; 
-#endif
-		getbits(psrc, 0, nend, tmpSrc);
-		putbits(tmpSrc, nstart, nend, pdst, ~((CfbBits)0));
-	    } 
-	    pdst = pdstNext;
-	} 
-#endif /* PSZ == 24 */
-        ppt++;
-	pwidth++;
-    }
-}
diff --git a/cfb/cfbglblt8.c b/cfb/cfbglblt8.c
deleted file mode 100644
index 4d964b3..0000000
--- a/cfb/cfbglblt8.c
+++ /dev/null
@@ -1,477 +0,0 @@
-/*
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-*/
-
-/*
- * Poly glyph blt.  Accepts an arbitrary font <= 32 bits wide, in Copy mode
- * only.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include	<X11/X.h>
-#include	<X11/Xmd.h>
-#include	<X11/Xproto.h>
-#include	"cfb.h"
-#include	<X11/fonts/fontstruct.h>
-#include	"dixfontstr.h"
-#include	"gcstruct.h"
-#include	"windowstr.h"
-#include	"scrnintstr.h"
-#include	"pixmapstr.h"
-#include	"regionstr.h"
-#include	"cfbmskbits.h"
-#include	"cfb8bit.h"
-
-#define BOX_OVERLAP(box1, box2, xoffset, yoffset) \
- 	((box1)->x1 <= ((int) (box2)->x2 + (xoffset)) && \
- 	 ((int) (box2)->x1 + (xoffset)) <= (box1)->x2 && \
-	 (box1)->y1 <= ((int) (box2)->y2 + (yoffset)) && \
- 	 ((int) (box2)->y1 + (yoffset)) <= (box1)->y2)
-
-#define BOX_CONTAINS(box1, box2, xoffset, yoffset) \
- 	((box1)->x1 <= ((int) (box2)->x1 + (xoffset)) && \
- 	 ((int) (box2)->x2 + (xoffset)) <= (box1)->x2 && \
-	 (box1)->y1 <= ((int) (box2)->y1 + (yoffset)) && \
- 	 ((int) (box2)->y2 + (yoffset)) <= (box1)->y2)
-
-#if defined(FOUR_BIT_CODE) || defined(WriteBitGroup) && !defined(GLYPHROP)
-
-#if GLYPHPADBYTES != 4
-#define USE_LEFTBITS
-#endif
-
-#ifdef USE_LEFTBITS
-typedef	unsigned char	*glyphPointer;
-
-#define GlyphBits(bits,width,dst)	getleftbits(bits,width,dst); \
-					(dst) &= widthMask; \
-					(bits) += widthGlyph;
-#define GlyphBitsS(bits,width,dst,off)	GlyphBits(bits,width,dst); \
-					dst = BitRight (dst, off);
-#else
-typedef CARD32	*glyphPointer;
-
-#define GlyphBits(bits,width,dst)	dst = *bits++;
-#define GlyphBitsS(bits,width,dst,off)	dst = BitRight(*bits++, off);
-#endif
-
-#ifdef GLYPHROP
-#define cfbPolyGlyphBlt8	cfbPolyGlyphRop8
-#define cfbPolyGlyphBlt8Clipped	cfbPolyGlyphRop8Clipped
-
-#undef WriteBitGroup
-#define WriteBitGroup(dst,pixel,bits)	RRopBitGroup(dst,bits)
-
-#endif
-
-static void cfbPolyGlyphBlt8Clipped(
-    DrawablePtr pDrawable,
-    GCPtr	pGC,
-    int 	x,
-    int         y,
-    unsigned int nglyph,
-    CharInfoPtr *ppci,		/* array of character info */
-    unsigned char *pglyphBase); /* start of array of glyphs */
-
-#if defined(HAS_STIPPLE_CODE) && !defined(GLYPHROP) && !defined(USE_LEFTBITS)
-#define USE_STIPPLE_CODE
-#endif
-
-#if defined(__GNUC__) && !defined(GLYPHROP) && (defined(mc68020) || defined(mc68000) || defined(__mc68000__)) && PSZ == 8 && !defined(USE_LEFTBITS)
-#ifdef USE_STIPPLE_CODE
-#undef USE_STIPPLE_CODE
-#endif
-#include "stip68kgnu.h"
-#endif
-
-#if PSZ == 24
-#define DST_INC	    3
-#else
-#define DST_INC	    (PGSZB >> PWSH)
-#endif
-
-/*  cfbStippleStack/cfbStippleStackTE are coded in assembly language.
- *  They are only provided on some architecures.
- */
-#ifdef USE_STIPPLE_CODE
-extern void		cfbStippleStack (), cfbStippleStackTE ();
-#endif
-
-void
-cfbPolyGlyphBlt8 (pDrawable, pGC, x, y, nglyph, ppci, pglyphBase)
-    DrawablePtr pDrawable;
-    GCPtr	pGC;
-    int 	x, y;
-    unsigned int nglyph;
-    CharInfoPtr *ppci;		/* array of character info */
-    pointer	pglyphBase;	/* start of array of glyphs */
-{
-#ifndef GLYPHROP
-    register CfbBits  pixel;
-#endif
-#if !defined(STIPPLE) && !defined(USE_STIPPLE_CODE)
-    register CfbBits  c;
-    register CfbBits  *dst;
-#endif
-    register glyphPointer   glyphBits;
-    register int	    xoff;
-
-    FontPtr		pfont = pGC->font;
-    CharInfoPtr		pci;
-    CfbBits	*dstLine;
-    CfbBits	*pdstBase;
-    int			hTmp;
-    int			bwidthDst;
-    int			widthDst;
-    int			h;
-    BoxRec		bbox;		/* for clipping */
-    int			w;
-    RegionPtr		clip;
-    BoxPtr		extents;
-#ifdef USE_LEFTBITS
-    int			widthGlyph;
-    CfbBits	widthMask;
-#endif
-#ifndef STIPPLE
-#ifdef USE_STIPPLE_CODE
-    void		(*stipple)();
-
-    stipple = cfbStippleStack;
-    if (FONTCONSTMETRICS(pfont))
-	stipple = cfbStippleStackTE;
-#endif
-#endif
-    
-    x += pDrawable->x;
-    y += pDrawable->y;
-
-    /* compute an approximate (but covering) bounding box */
-    bbox.x1 = 0;
-    if ((ppci[0]->metrics.leftSideBearing < 0))
-	bbox.x1 = ppci[0]->metrics.leftSideBearing;
-    h = nglyph - 1;
-    w = ppci[h]->metrics.rightSideBearing;
-    while (--h >= 0)
-	w += ppci[h]->metrics.characterWidth;
-    bbox.x2 = w;
-    bbox.y1 = -FONTMAXBOUNDS(pfont,ascent);
-    bbox.y2 = FONTMAXBOUNDS(pfont,descent);
-
-    clip = cfbGetCompositeClip(pGC);
-    extents = &clip->extents;
-
-    if (!clip->data) 
-    {
-	if (!BOX_CONTAINS(extents, &bbox, x, y))
-	{
-	    if (BOX_OVERLAP (extents, &bbox, x, y))
-		cfbPolyGlyphBlt8Clipped(pDrawable, pGC, x, y,
-					nglyph, ppci, pglyphBase);
-	    return;
-	}
-    }
-    else
-    {
-    	/* check to make sure some of the text appears on the screen */
-    	if (!BOX_OVERLAP (extents, &bbox, x, y))
-	    return;
-    
-    	bbox.x1 += x;
-    	bbox.x2 += x;
-    	bbox.y1 += y;
-    	bbox.y2 += y;
-    
-    	switch (RECT_IN_REGION(pGC->pScreen, clip, &bbox))
-    	{
-      	  case rgnPART:
-	    cfbPolyGlyphBlt8Clipped(pDrawable, pGC, x, y,
-				    nglyph, ppci, pglyphBase);
-      	  case rgnOUT:
-	    return;
-    	}
-    }
-
-#ifdef GLYPHROP
-    cfb8CheckStipple (pGC->alu, pGC->fgPixel, pGC->planemask);
-#else
-    pixel = cfbGetGCPrivate(pGC)->xor;
-#endif
-
-    cfbGetTypedWidthAndPointer (pDrawable, bwidthDst, pdstBase, char, CfbBits)
-
-    widthDst = bwidthDst / PGSZB;
-    while (nglyph--)
-    {
-	pci = *ppci++;
-	glyphBits = (glyphPointer) FONTGLYPHBITS(pglyphBase,pci);
-	xoff = x + pci->metrics.leftSideBearing;
-#if PSZ == 24
-	dstLine = pdstBase + (y - pci->metrics.ascent) * widthDst +((xoff>> 2)*3);
-#else
-	dstLine = pdstBase +
-	          (y - pci->metrics.ascent) * widthDst + (xoff >> PWSH);
-#endif
-	x += pci->metrics.characterWidth;
-	if ((hTmp = pci->metrics.descent + pci->metrics.ascent))
-	{
-#if PSZ == 24
-	    xoff &= 0x03;
-#else
-	    xoff &= PIM;
-#endif /* PSZ == 24 */
-#ifdef STIPPLE
-	    STIPPLE(dstLine,glyphBits,pixel,bwidthDst,hTmp,xoff);
-#else
-#ifdef USE_STIPPLE_CODE
-	    (*stipple)(dstLine,glyphBits,pixel,bwidthDst,hTmp,xoff);
-#else
-#ifdef USE_LEFTBITS
-	    w = pci->metrics.rightSideBearing - pci->metrics.leftSideBearing;
-	    widthGlyph = PADGLYPHWIDTHBYTES(w);
-	    widthMask = mfbGetendtab(w);
-#endif
-	    do {
-	    	dst = dstLine;
-	    	dstLine = (CfbBits *) (((char *) dstLine) + bwidthDst);
-	    	GlyphBits(glyphBits, w, c)
-	    	WriteBitGroup(dst, pixel, GetBitGroup(BitRight(c,xoff)));
-	    	dst += DST_INC;
-	    	c = BitLeft(c,PGSZB - xoff);
-	    	while (c)
-	    	{
-		    WriteBitGroup(dst, pixel, GetBitGroup(c));
-		    NextBitGroup(c);
-		    dst += DST_INC;
-	    	}
-	    } while (--hTmp);
-#endif /* USE_STIPPLE_CODE else */
-#endif /* STIPPLE else */
-	}
-    }
-}
-
-static void
-cfbPolyGlyphBlt8Clipped(
-    DrawablePtr pDrawable,
-    GCPtr	pGC,
-    int 	x,
-    int         y,
-    unsigned int nglyph,
-    CharInfoPtr *ppci,		/* array of character info */
-    unsigned char *pglyphBase)	/* start of array of glyphs */
-{
-#ifndef GLYPHROP
-    register CfbBits	pixel;
-#endif
-#if !defined(STIPPLE) && !defined(USE_STIPPLE_CODE)
-    register CfbBits	c;
-#endif
-    register glyphPointer   glyphBits;
-    register int	xoff;
-#if defined(USE_LEFTBITS) || (!defined(STIPPLE) && !defined(USE_STIPPLE_CODE))
-    register CfbBits	*dst;
-#endif
-
-    CharInfoPtr		pci;
-    FontPtr		pfont = pGC->font;
-    CfbBits		*dstLine;
-    CfbBits		*pdstBase;
-#ifdef USE_LEFTBITS
-    CARD32		*cTmp;
-#endif
-    CARD32		*clips;
-    int			maxAscent, maxDescent;
-    int			minLeftBearing;
-    int			hTmp;
-    int			widthDst;
-    int			bwidthDst;
-    int			xG, yG;
-    BoxPtr		pBox;
-    int			numRects;
-    int			w;
-    RegionPtr		pRegion;
-    int			yBand;
-#ifdef GLYPHROP
-    CfbBits		bits;
-#endif
-#ifdef USE_LEFTBITS
-    int			widthGlyph;
-    CfbBits		widthMask;
-#endif
-
-#ifdef GLYPHROP
-    cfb8CheckStipple (pGC->alu, pGC->fgPixel, pGC->planemask);
-#else
-    pixel = cfbGetGCPrivate(pGC)->xor;
-#endif
-    
-    cfbGetTypedWidthAndPointer (pDrawable, bwidthDst, pdstBase, char, CfbBits)
-
-    widthDst = bwidthDst / PGSZB;
-    maxAscent = FONTMAXBOUNDS(pfont,ascent);
-    maxDescent = FONTMAXBOUNDS(pfont,descent);
-    minLeftBearing = FONTMINBOUNDS(pfont,leftSideBearing);
-
-    pRegion = cfbGetCompositeClip(pGC);
-
-    pBox = REGION_RECTS(pRegion);
-    numRects = REGION_NUM_RECTS (pRegion);
-    while (numRects && pBox->y2 <= y - maxAscent)
-    {
-	++pBox;
-	--numRects;
-    }
-    if (!numRects || pBox->y1 >= y + maxDescent)
-	return;
-    yBand = pBox->y1;
-    while (numRects && pBox->y1 == yBand && pBox->x2 <= x + minLeftBearing)
-    {
-	++pBox;
-	--numRects;
-    }
-    if (!numRects)
-	return;
-    clips = (CARD32 *)xalloc ((maxAscent + maxDescent) *
-						sizeof (CARD32));
-    while (nglyph--)
-    {
-	pci = *ppci++;
-	glyphBits = (glyphPointer) FONTGLYPHBITS(pglyphBase,pci);
-	w = pci->metrics.rightSideBearing - pci->metrics.leftSideBearing;
-	xG = x + pci->metrics.leftSideBearing;
-	yG = y - pci->metrics.ascent;
-	x += pci->metrics.characterWidth;
-	if ((hTmp = pci->metrics.descent + pci->metrics.ascent))
-	{
-#if PSZ == 24
-	    dstLine = pdstBase + yG * widthDst + ((xG>> 2)*3);
-	    /* never use (xG*3)>>2 */
-#else
-	    dstLine = pdstBase + yG * widthDst + (xG >> PWSH);
-#endif
-#if PSZ == 24
-	    xoff = xG & 3;
-#else
-	    xoff = xG & PIM;
-#endif
-#ifdef USE_LEFTBITS
-	    w = pci->metrics.rightSideBearing - pci->metrics.leftSideBearing;
-	    widthGlyph = PADGLYPHWIDTHBYTES(w);
-	    widthMask = mfbGetendtab(w);
-#endif
-	    switch (cfb8ComputeClipMasks32 (pBox, numRects, xG, yG, w, hTmp, clips))
- 	    {
-	    case rgnPART:
-#ifdef USE_LEFTBITS
-	    	cTmp = clips;
-	    	do {
-	    	    dst = dstLine;
-	    	    dstLine = (CfbBits *) (((char *) dstLine) + bwidthDst);
-	    	    GlyphBits(glyphBits, w, c)
-		    c &= *cTmp++;
-		    if (c)
-		    {
-	    	    	WriteBitGroup(dst, pixel, GetBitGroup(BitRight(c,xoff)));
-	    	    	c = BitLeft(c,PGSZB - xoff); 
-	    	    	dst += DST_INC;
-	    	    	while (c)
-	    	    	{
-		    	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-		    	    NextBitGroup(c);
-		    	    dst += DST_INC;
-	    	    	}
-		    }
-	    	} while (--hTmp);
-	    	break;
-#else /* !USE_LEFTBITS */
-	    	{
-		    int h;
-    
-		    h = hTmp;
-		    do
-		    {
-			--h;
-		    	clips[h] = clips[h] & glyphBits[h];
-		    } while (h);
-	    	}
-	    	glyphBits = clips;
-	    	/* fall through */
-#endif /* USE_LEFTBITS */
-	    case rgnIN:
-#ifdef STIPPLE
-	    	STIPPLE(dstLine,glyphBits,pixel,bwidthDst,hTmp,xoff);
-#else
-#ifdef USE_STIPPLE_CODE
-	    	cfbStippleStackTE(dstLine,glyphBits,pixel,bwidthDst,hTmp,xoff);
-#else
-	    	do {
-	    	    dst = dstLine;
-	    	    dstLine = (CfbBits *) (((char *) dstLine) + bwidthDst);
-	    	    GlyphBits(glyphBits, w, c)
-		    if (c)
-		    {
-		        /* This code originally could read memory locations
-			 * that were not mapped. Hence we have to check the
-			 * trailing bits to see whether they are zero and if
-			 * then skip them correctly. This is no problem for
-			 * the GXcopy case, since there only the pixels that
-			 * are non-zero are written ...
-			 */
-#ifndef GLYPHROP
-	    	    	WriteBitGroup(dst, pixel, GetBitGroup(BitRight(c,xoff)));
-	    	    	c = BitLeft(c,PGSZB - xoff);
-	    	    	dst += DST_INC;
-#else /* GLYPHROP */
-                        if ((bits = GetBitGroup(BitRight(c,xoff))))
-	    	    	  WriteBitGroup(dst, pixel, bits);
-	    	    	c = BitLeft(c,PGSZB - xoff);
-	    	    	dst += DST_INC;
-
-			while (c && ((bits = GetBitGroup(c)) == 0))
-		        {
-		    	    NextBitGroup(c);
-		    	    dst += DST_INC;
-                        } 
-#endif /* GLYPHROP */
-	    	    	while (c)
-	    	    	{
-		    	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-		    	    NextBitGroup(c);
-		    	    dst += DST_INC;
-	    	    	}
-		    }
-	    	} while (--hTmp);
-#endif /* USE_STIPPLE_CODE else */
-#endif /* STIPPLE else */
-	    	break;
-	    }
-	}
-    }
-    xfree (clips);
-}
-
-#endif /* FOUR_BIT_CODE */
diff --git a/cfb/cfbhrzvert.c b/cfb/cfbhrzvert.c
deleted file mode 100644
index a6a7930..0000000
--- a/cfb/cfbhrzvert.c
+++ /dev/null
@@ -1,554 +0,0 @@
-/***********************************************************
-
-Copyright 1987,1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-
-#include "gc.h"
-#include "window.h"
-#include "pixmap.h"
-#include "region.h"
-
-#include "cfb.h"
-#include "cfbmskbits.h"
-
-/* horizontal solid line
-   abs(len) > 1
-*/
-void
-cfbHorzS(rop, and, xor, addrl, nlwidth, x1, y1, len)
-register int rop;
-register CfbBits and;
-register CfbBits xor;
-register CfbBits *addrl;	/* pointer to base of bitmap */
-int nlwidth;		/* width in longwords of bitmap */
-int x1;			/* initial point */ 
-int y1;
-int len;		/* length of line */
-{
-    register int nlmiddle;
-
-#if PSZ == 24
-
-    int leftIndex, rightIndex;
-    CfbBits piQxelAnd[3], piQxelXor[3];
-    piQxelAnd[0] = (and & 0xFFFFFF) | ((and<<24)  & 0xFF000000);
-    piQxelAnd[1] = ((and>>8)  & 0xFFFF)| ((and<<16) & 0xFFFF0000);
-    piQxelAnd[2] = ((and<<8) & 0xFFFFFF00) | ((and>>16) & 0xFF);
-
-    piQxelXor[0] = (xor & 0xFFFFFF) | ((xor<<24) & 0xFF000000);
-    piQxelXor[1] = ((xor>>8)  & 0xFFFF)| ((xor<<16) & 0xFFFF0000);
-    piQxelXor[2] = ((xor<<8) & 0xFFFFFF00) | ((xor>>16) & 0xFF);
-
-    leftIndex = x1 & 3;
-    rightIndex = ((x1 + len) < 5)?0:(x1 + len)&3;
-    nlmiddle = len;
-    if(leftIndex){
-      nlmiddle -= (4 - leftIndex);
-    }
-    if(rightIndex){
-      nlmiddle -= rightIndex;
-    }
-    if (nlmiddle < 0)
-      nlmiddle = 0;
-
-    nlmiddle >>= 2;
-
-    addrl += (y1 * nlwidth) + (x1 >> 2)*3 + (leftIndex?leftIndex-1:0);
-
-    switch(leftIndex+len){
-    case 4:
-      switch(leftIndex){
-      case 0:
-	*addrl = DoRRop (*addrl, piQxelAnd[0], piQxelXor[0]);
-	addrl++;
-	*addrl = DoRRop (*addrl, piQxelAnd[1], piQxelXor[1]);
-	addrl++;
-	*addrl = DoRRop (*addrl, piQxelAnd[2], piQxelXor[2]);
-	break;
-      case 1:
-	*addrl = DoMaskRRop (*addrl, piQxelAnd[0], piQxelXor[0], 0xFF000000);
-	addrl++;
-	*addrl = DoRRop (*addrl, piQxelAnd[1], piQxelXor[1]);
-	addrl++;
-	*addrl = DoRRop (*addrl, piQxelAnd[2], piQxelXor[2]);
-	break;
-      case 2:
-	*addrl = DoMaskRRop (*addrl, piQxelAnd[1], piQxelXor[1], 0xFFFF0000);
-	addrl++;
-	*addrl = DoRRop (*addrl, piQxelAnd[2], piQxelXor[2]);
-	break;
-      case 3:
-	*addrl = DoMaskRRop (*addrl, piQxelAnd[2], piQxelXor[2], 0xFFFFFF00);
-	break;
-      }
-      break;
-    case 3:
-      switch(leftIndex){
-      case 0:
-	*addrl = DoRRop (*addrl, piQxelAnd[0], piQxelXor[0]);
-	addrl++;
-	*addrl = DoRRop (*addrl, piQxelAnd[1], piQxelXor[1]);
-	addrl++;
-	*addrl = DoMaskRRop (*addrl, piQxelAnd[2], piQxelXor[2], 0xFF);
-	break;
-      case 1:
-	*addrl = DoMaskRRop (*addrl, piQxelAnd[0], piQxelXor[0], 0xFF000000);
-	addrl++;
-	*addrl = DoRRop (*addrl, piQxelAnd[1], piQxelXor[1]);
-	addrl++;
-	*addrl = DoMaskRRop (*addrl, piQxelAnd[2], piQxelXor[2], 0xFF);
-	break;
-      case 2:
-	*addrl = DoMaskRRop (*addrl, piQxelAnd[1], piQxelXor[1], 0xFFFF0000);
-	addrl++;
-	*addrl = DoMaskRRop (*addrl, piQxelAnd[2], piQxelXor[2], 0xFF);
-	break;
-      }
-      break;
-    case 2:
-      if(leftIndex){
-	*addrl = DoMaskRRop (*addrl, piQxelAnd[0], piQxelXor[0], 0xFF000000);
-	addrl++;
-      }
-      else{
-	*addrl = DoRRop (*addrl, piQxelAnd[0], piQxelXor[0]);
-	addrl++;
-      }
-      *addrl =  DoMaskRRop (*addrl, piQxelAnd[1], piQxelXor[1], 0xFFFF);
-      break;
-    case 1: /*only if leftIndex = 0 and w = 1*/
-      *addrl = DoMaskRRop (*addrl, piQxelAnd[0], piQxelXor[0], 0xFFFFFF);
-      break;
-    case 0: /*never*/
-      break;
-    default:
-      {
-	if (rop == GXcopy){
-	  switch(leftIndex){
-	  case 0:
-	    break;
-	  case 1:
-	    *addrl = ((*addrl) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-	    addrl++;
-	    *addrl++ = piQxelXor[1];
-	    *addrl++ = piQxelXor[2];
-	    break;
-	  case 2:
-	    *addrl = ((*addrl) & 0xFFFF) | (piQxelXor[1] & 0xFFFF0000);
-	    addrl++;
-	    *addrl++ = piQxelXor[2];
-	    break;
-	  case 3:
-	    *addrl = ((*addrl) & 0xFF) | (piQxelXor[2] & 0xFFFFFF00);
-	    addrl++;
-	    break;
-	  }
-	  while(nlmiddle--){
-	    *addrl++ = piQxelXor[0];
-	    *addrl++ = piQxelXor[1];
-	    *addrl++ = piQxelXor[2];
-	  }
-	  switch(rightIndex){
-	  case 0:
-	    break;
-	  case 1:
-	    *addrl = ((*addrl) & 0xFF000000) | (piQxelXor[0] & 0xFFFFFF);
-	    break;
-	  case 2:
-	    *addrl++ = piQxelXor[0];
-	    *addrl = ((*addrl) & 0xFFFF0000) | (piQxelXor[1] & 0xFFFF);
-	    break;
-	  case 3:
-	    *addrl++ = piQxelXor[0];
-	    *addrl++ = piQxelXor[1];
-	    *addrl = ((*addrl) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-	    break;
-	  }
-	}
-	else{
-	  if(rop == GXxor){
-	  switch(leftIndex){
-	  case 0:
-	    break;
-	  case 1:
-	    *addrl++ ^= (piQxelXor[0]&0xFF000000);
-	    *addrl++ ^= piQxelXor[1];
-	    *addrl++ ^= piQxelXor[2];
-	    break;
-	  case 2:
-	    *addrl++ ^= (piQxelXor[1]& 0xFFFF0000);
-	    *addrl++ ^= piQxelXor[2];
-	    break;
-	  case 3:
-	    *addrl++ ^= (piQxelXor[2]& 0xFFFFFF00);
-	    break;
-	  }
-	  while(nlmiddle--){
-	    *addrl++ ^= piQxelXor[0];
-	    *addrl++ ^= piQxelXor[1];
-	    *addrl++ ^= piQxelXor[2];
-	  }
-	  switch(rightIndex){
-	  case 0:
-	    break;
-	  case 1:
-	    *addrl ^= (piQxelXor[0]& 0xFFFFFF);
-	    break;
-	  case 2:
-	    *addrl++ ^= piQxelXor[0];
-	    *addrl ^= (piQxelXor[1]&0xFFFF);
-	    break;
-	  case 3:
-	    *addrl++ ^= piQxelXor[0];
-	    *addrl++ ^= piQxelXor[1];
-	    *addrl ^= (piQxelXor[2]&0xFF);
-	    break;
-	  }
-	}
-	  else{
-	    switch(leftIndex){
-	    case 0:
-	      break;
-	    case 1:
-	      *addrl = DoMaskRRop (*addrl, piQxelAnd[0], piQxelXor[0], 0xFF000000);
-	      addrl++;
-	      *addrl = DoRRop (*addrl, piQxelAnd[1], piQxelXor[1]);
-	      addrl++;
-	      *addrl = DoRRop (*addrl, piQxelAnd[2], piQxelXor[2]);
-	      addrl++;
-	      break;
-	    case 2:
-	      *addrl = DoMaskRRop (*addrl, piQxelAnd[1], piQxelXor[1], 0xFFFF0000);
-	      addrl++;
-	      *addrl = DoRRop (*addrl, piQxelAnd[2], piQxelXor[2]);
-	      addrl++;
-	      break;
-	    case 3:
-	      *addrl = DoMaskRRop (*addrl, piQxelAnd[2], piQxelXor[2], 0xFFFFFF00);
-	      addrl++;
-	      break;
-	  }
-	  while(nlmiddle--){
-	    *addrl = DoRRop (*addrl, piQxelAnd[0], piQxelXor[0]);
-	    addrl++;
-	    *addrl = DoRRop (*addrl, piQxelAnd[1], piQxelXor[1]);
-	    addrl++;
-	    *addrl = DoRRop (*addrl, piQxelAnd[2], piQxelXor[2]);
-	    addrl++;
-	  }
-	  switch(rightIndex){
-	  case 0:
-	    break;
-	  case 1:
-	    *addrl = DoMaskRRop (*addrl, piQxelAnd[0], piQxelXor[0], 0xFFFFFF);
-	    addrl++;
-	    break;
-	  case 2:
-	    *addrl = DoRRop (*addrl, piQxelAnd[0], piQxelXor[0]);
-	    addrl++;
-	    *addrl = DoMaskRRop (*addrl, piQxelAnd[1], piQxelXor[1], 0xFFFF);
-	    break;
-	  case 3:
-	    *addrl = DoRRop (*addrl, piQxelAnd[0], piQxelXor[0]);
-	    addrl++;
-	    *addrl = DoRRop (*addrl, piQxelAnd[1], piQxelXor[1]);
-	    addrl++;
-	    *addrl = DoMaskRRop (*addrl, piQxelAnd[2], piQxelXor[2], 0xFF);
-	    break;
-	  }
-
-	  }
-	}
-      }
-    }
-#else
-    register CfbBits startmask;
-    register CfbBits endmask;
-
-    addrl = addrl + (y1 * nlwidth) + (x1 >> PWSH);
-
-    /* all bits inside same longword */
-    if ( ((x1 & PIM) + len) < PPW)
-    {
-	maskpartialbits(x1, len, startmask);
-	*addrl = DoMaskRRop (*addrl, and, xor, startmask);
-    }
-    else
-    {
-	maskbits(x1, len, startmask, endmask, nlmiddle);
-	if (rop == GXcopy)
-	{
-	    if (startmask)
-	    {
-		*addrl = (*addrl & ~startmask) | (xor & startmask);
-		addrl++;
-	    }
-	    while (nlmiddle--)
-	    	*addrl++ = xor;
-	    if (endmask)
-		*addrl = (*addrl & ~endmask) | (xor & endmask);
-	}
-	else
-	{
-	    if (startmask)
-	    {
-		*addrl = DoMaskRRop (*addrl, and, xor, startmask);
-		addrl++;
-	    }
-	    if (rop == GXxor)
-	    {
-		while (nlmiddle--)
-		    *addrl++ ^= xor;
-	    }
-	    else
-	    {
-		while (nlmiddle--)
-		{
-		    *addrl = DoRRop (*addrl, and, xor);
-		    addrl++;
-		}
-	    }
-	    if (endmask)
-		*addrl = DoMaskRRop (*addrl, and, xor, endmask);
-	}
-    }
-#endif
-}
-
-/* vertical solid line */
-
-void
-cfbVertS(rop, and, xor, addrl, nlwidth, x1, y1, len)
-int rop;
-register CfbBits and, xor;
-register CfbBits *addrl;	/* pointer to base of bitmap */
-register int nlwidth;	/* width in longwords of bitmap */
-int x1, y1;		/* initial point */
-register int len;	/* length of line */
-{
-#if PSZ == 24
-    int xIdx;
-    CfbBits and2 = 0, xor2 = 0, mask = 0, mask2;
-#endif
-#ifdef PIXEL_ADDR
-    register PixelType    *bits = (PixelType *) addrl;
-
-#if PSZ == 24
-    nlwidth <<= PWSH;
-    xIdx = x1 & 3;
-    bits = (PixelType *)(addrl + (y1 * nlwidth) + ((x1*3) >> 2));
-#else
-    nlwidth <<= PWSH;
-    bits = bits + (y1 * nlwidth) + x1;
-#endif
-#if PSZ == 24
-    mask2 = 0;
-    switch(xIdx){
-      case 0:
-        mask = 0xFF000000;
-	xor &= 0xFFFFFF;
-	and |= 0xFF000000;
-	break;
-      case 3:
-	mask = 0xFF;
-	xor &= 0xFFFFFF;
-	xor <<= 8;
-	and <<= 8;
-	and |= 0xFF;
-	break;
-      case 1:
-	mask = 0xFFFFFF;
-	mask2 = 0xFFFF0000;
-	xor2 = (xor>>8) & 0xFFFF;
-	xor &= 0xFF;
-	xor <<= 24;
-	and2 = (and >> 8 ) | 0xFFFF0000;
-	and <<= 24;
-	and |= 0xFFFFFF;
-	break;
-      case 2:
-	mask = 0x0000FFFF;
-	mask2 = 0xFFFFFF00;
-	xor2 = (xor >> 16) & 0xFF;
-	xor <<= 16;
-	xor &= 0xFFFF0000;
-	and2 = (and >> 16) | 0xFFFFFF00;
-	and <<= 16;
-	and |= 0xFFFF;
-	break;
-      }
-#endif
-
-    /*
-     * special case copy and xor to avoid a test per pixel
-     */
-    if (rop == GXcopy)
-    {
-#if PSZ == 24
-      switch(xIdx){
-      case 0:
-      case 3:
-	while (len--){
-	  *bits = (*bits & mask)| xor;
-	  bits += nlwidth;
-	}
-	break;
-      case 1:
-      case 2:
-	while (len--){
-	  *bits = (*bits & mask)| xor;
-	  bits++;
-	  *bits = (*bits & mask2)| xor2;
-	  bits--;
-	  bits += nlwidth;
-	}
-	break;
-      }
-#else
-	while (len--)
-	{
-	    *bits = xor;
-	    bits += nlwidth;
-	}
-#endif
-    }
-    else if (rop == GXxor)
-    {
-#if PSZ == 24
-      switch(xIdx){
-      case 0:
-      case 3:
-	while (len--){
-	  *bits ^=  xor;
-	  bits += nlwidth;
-	}
-	break;
-      case 1:
-      case 2:
-	while (len--){
-	  *bits ^= xor;
-	  bits++;
-	  *bits ^= xor2;
-	  bits--;
-	  bits += nlwidth;
-	}
-	break;
-      }
-#else
-	while (len--)
-	{
-	    *bits ^= xor;
-	    bits += nlwidth;
-	}
-#endif
-    }
-    else
-    {
-#if PSZ == 24
-      switch(xIdx){
-      case 0:
-	while (len--){
-	  *bits = DoMaskRRop(*bits, and, xor, 0x00FFFFFF);
-	  bits += nlwidth;
-	}
-	break;
-      case 3:
-	while (len--){
-	  *bits = DoMaskRRop(*bits, and, xor, 0xFFFFFF00);
-	  bits += nlwidth;
-	}
-	break;
-      case 1:
-	while (len--){
-	  *bits = DoMaskRRop(*bits, and, xor, 0xFF000000);
-	  bits++;
-	  *bits = DoMaskRRop(*bits, and2, xor2, 0x0000FFFF);
-	  bits--;
-	  bits += nlwidth;
-	}
-	break;
-      case 2:
-	while (len--){
-	  *bits = DoMaskRRop(*bits, and, xor, 0xFFFF0000);
-	  bits++;
-	  *bits = DoMaskRRop(*bits, and2, xor2, 0x000000FF);
-	  bits--;
-	  bits += nlwidth;
-	}
-	break;
-      }
-#else
-	while (len--)
-	{
-	    *bits = DoRRop(*bits, and, xor);
-	    bits += nlwidth;
-	}
-#endif
-    }
-#else /* !PIXEL_ADDR */
-#if PSZ == 24
-    addrl = addrl + (y1 * nlwidth) + ((x1*3) >>2);
-
-    and |= ~cfbmask[(x1 & 3)<<1];
-    xor &= cfbmask[(x1 & 3)<<1];
-#else
-    addrl = addrl + (y1 * nlwidth) + (x1 >> PWSH);
-
-    and |= ~cfbmask[x1 & PIM];
-    xor &= cfbmask[x1 & PIM];
-#endif
-
-    while (len--)
-    {
-	*addrl = DoRRop (*addrl, and, xor);
-	addrl += nlwidth;
-    }
-#endif
-}
diff --git a/cfb/cfbigblt8.c b/cfb/cfbigblt8.c
deleted file mode 100644
index 1f1ce6f..0000000
--- a/cfb/cfbigblt8.c
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- *
-Copyright 1990, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- */
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include	<X11/X.h>
-#include	<X11/Xmd.h>
-#include	<X11/Xproto.h>
-#include	"mi.h"
-#include	"cfb.h"
-#include	<X11/fonts/fontstruct.h>
-#include	"dixfontstr.h"
-#include	"gcstruct.h"
-#include	"windowstr.h"
-#include	"scrnintstr.h"
-#include	"pixmapstr.h"
-#include	"regionstr.h"
-#include	"cfbmskbits.h"
-#include	"cfb8bit.h"
-
-void
-cfbImageGlyphBlt8 (pDrawable, pGC, x, y, nglyph, ppci, pglyphBase)
-    DrawablePtr	    pDrawable;
-    GCPtr	    pGC;
-    int		    x, y;
-    unsigned int    nglyph;
-    CharInfoPtr	    *ppci;
-    pointer	    pglyphBase;
-{
-    ExtentInfoRec info;		/* used by QueryGlyphExtents() */
-    xRectangle backrect;
-    int		fgPixel;
-    cfbPrivGC	*priv;
-
-    /*
-     * We can't avoid GC validations if calling mi functions.
-     */
-    if ((pGC->ops->PolyFillRect == miPolyFillRect) ||
-        (pGC->ops->PolyGlyphBlt == miPolyGlyphBlt))
-    {
-        miImageGlyphBlt(pDrawable, pGC, x, y, nglyph, ppci, pglyphBase);
-        return;
-    }
-
-    QueryGlyphExtents(pGC->font, ppci, (unsigned long)nglyph, &info);
-
-    if (info.overallWidth >= 0)
-    {
-    	backrect.x = x;
-    	backrect.width = info.overallWidth;
-    }
-    else
-    {
-	backrect.x = x + info.overallWidth;
-	backrect.width = -info.overallWidth;
-    }
-    backrect.y = y - FONTASCENT(pGC->font);
-    backrect.height = FONTASCENT(pGC->font) + FONTDESCENT(pGC->font);
-
-    priv = cfbGetGCPrivate(pGC);
-
-    /* this code cheats by knowing that ValidateGC isn't
-     * necessary for PolyFillRect
-     */
-
-    fgPixel = pGC->fgPixel;
-
-    pGC->fgPixel = pGC->bgPixel;
-    priv->xor = PFILL(pGC->bgPixel);
-
-    (*pGC->ops->PolyFillRect) (pDrawable, pGC, 1, &backrect);
-
-    pGC->fgPixel = fgPixel;
-
-    priv->xor = PFILL(pGC->fgPixel);
-
-    (*pGC->ops->PolyGlyphBlt) (pDrawable, pGC, x, y, nglyph, ppci, pglyphBase);
-    
-}
diff --git a/cfb/cfbimage.c b/cfb/cfbimage.c
deleted file mode 100644
index 396e1fc..0000000
--- a/cfb/cfbimage.c
+++ /dev/null
@@ -1,206 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <string.h>
-
-#include <X11/X.h>
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "gcstruct.h"
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "servermd.h"
-#include "mi.h"
-
-void
-cfbPutImage(pDraw, pGC, depth, x, y, w, h, leftPad, format, pImage)
-    DrawablePtr pDraw;
-    GCPtr	pGC;
-    int		depth, x, y, w, h;
-    int		leftPad;
-    int		format;
-    char 	*pImage;
-{
-    PixmapPtr   pPixmap;
-
-    if ((w == 0) || (h == 0))
-	return;
-
-    if (format != XYPixmap)
-    {
-	pPixmap = GetScratchPixmapHeader(pDraw->pScreen, w+leftPad, h, depth,
-		      BitsPerPixel(depth), PixmapBytePad(w+leftPad, depth),
-		      (pointer)pImage);
-	if (!pPixmap)
-	    return;
-	
-    	pGC->fExpose = FALSE;
-	if (format == ZPixmap)
-	    (void)(*pGC->ops->CopyArea)((DrawablePtr)pPixmap, pDraw, pGC,
-					leftPad, 0, w, h, x, y);
-	else
-	    (void)(*pGC->ops->CopyPlane)((DrawablePtr)pPixmap, pDraw, pGC,
-					 leftPad, 0, w, h, x, y, 1);
-	pGC->fExpose = TRUE;
-        FreeScratchPixmapHeader(pPixmap);
-    }
-    else
-    {
-	CfbBits	oldFg, oldBg;
-	XID		gcv[3];
-	CfbBits	oldPlanemask;
-	unsigned long	i;
-	long		bytesPer;
-
-	depth = pGC->depth;
-	oldPlanemask = pGC->planemask;
-	oldFg = pGC->fgPixel;
-	oldBg = pGC->bgPixel;
-	gcv[0] = ~0L;
-	gcv[1] = 0;
-	DoChangeGC(pGC, GCForeground | GCBackground, gcv, 0);
-	bytesPer = (long)h * BitmapBytePad(w + leftPad);
-
-	for (i = 1 << (depth-1); i != 0; i >>= 1, pImage += bytesPer)
-	{
-	    if (i & oldPlanemask)
-	    {
-	        gcv[0] = i;
-	        DoChangeGC(pGC, GCPlaneMask, gcv, 0);
-	        ValidateGC(pDraw, pGC);
-	        (*pGC->ops->PutImage)(pDraw, pGC, 1, x, y, w, h, leftPad,
-			         XYBitmap, pImage);
-	    }
-	}
-	gcv[0] = oldPlanemask;
-	gcv[1] = oldFg;
-	gcv[2] = oldBg;
-	DoChangeGC(pGC, GCPlaneMask | GCForeground | GCBackground, gcv, 0);
-	ValidateGC(pDraw, pGC);
-    }
-}
-
-void
-cfbGetImage(pDrawable, sx, sy, w, h, format, planeMask, pdstLine)
-    DrawablePtr pDrawable;
-    int		sx, sy, w, h;
-    unsigned int format;
-    unsigned long planeMask;
-    char	*pdstLine;
-{
-    BoxRec box;
-    DDXPointRec ptSrc;
-    RegionRec rgnDst;
-    ScreenPtr pScreen;
-    PixmapPtr pPixmap;
-
-    if ((w == 0) || (h == 0))
-	return;
-    if (pDrawable->bitsPerPixel == 1)
-    {
-	mfbGetImage(pDrawable, sx, sy, w, h, format, planeMask, pdstLine);
-	return;
-    }
-    pScreen = pDrawable->pScreen;
-    /*
-     * XFree86 DDX empties the root borderClip when the VT is
-     * switched away; this checks for that case
-     */
-    if (!cfbDrawableEnabled (pDrawable))
-	return;
-    if (format == ZPixmap)
-    {
-	pPixmap = GetScratchPixmapHeader(pScreen, w, h, 
-			pDrawable->depth, pDrawable->bitsPerPixel,
-			PixmapBytePad(w,pDrawable->depth), (pointer)pdstLine);
-	if (!pPixmap)
-	    return;
-	if ((planeMask & PMSK) != PMSK)
-	    bzero((char *)pdstLine, pPixmap->devKind * h);
-        ptSrc.x = sx + pDrawable->x;
-        ptSrc.y = sy + pDrawable->y;
-        box.x1 = 0;
-        box.y1 = 0;
-        box.x2 = w;
-        box.y2 = h;
-        REGION_INIT(pScreen, &rgnDst, &box, 1);
-	cfbDoBitblt(pDrawable, (DrawablePtr)pPixmap, GXcopy, &rgnDst,
-		    &ptSrc, planeMask);
-        REGION_UNINIT(pScreen, &rgnDst);
-	FreeScratchPixmapHeader(pPixmap);
-    }
-    else
-    {
-
-#if IMAGE_BYTE_ORDER == LSBFirst
-
-	pPixmap = GetScratchPixmapHeader(pScreen, w, h,  /*depth*/ 1,
-			/*bpp*/ 1, BitmapBytePad(w), (pointer)pdstLine);
-	if (!pPixmap)
-	    return;
-
-        ptSrc.x = sx + pDrawable->x;
-        ptSrc.y = sy + pDrawable->y;
-        box.x1 = 0;
-        box.y1 = 0;
-        box.x2 = w;
-        box.y2 = h;
-        REGION_INIT(pScreen, &rgnDst, &box, 1);
-	cfbCopyImagePlane (pDrawable, (DrawablePtr)pPixmap, GXcopy, &rgnDst,
-		    &ptSrc, planeMask);
-        REGION_UNINIT(pScreen, &rgnDst);
-	FreeScratchPixmapHeader(pPixmap);
-#else
-	miGetImage (pDrawable, sx, sy, w, h, format, planeMask, pdstLine);
-#endif
-    }
-}
diff --git a/cfb/cfbline.c b/cfb/cfbline.c
deleted file mode 100644
index 84c089a..0000000
--- a/cfb/cfbline.c
+++ /dev/null
@@ -1,756 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <stdlib.h>
-#include <X11/X.h>
-
-#include "gcstruct.h"
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "regionstr.h"
-#include "scrnintstr.h"
-#include "mistruct.h"
-
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "miline.h"
-
-/* single-pixel lines on a color frame buffer
-
-   NON-SLOPED LINES
-   horizontal lines are always drawn left to right; we have to
-move the endpoints right by one after they're swapped.
-   horizontal lines will be confined to a single band of a
-region.  the code finds that band (giving up if the lower
-bound of the band is above the line we're drawing); then it
-finds the first box in that band that contains part of the
-line.  we clip the line to subsequent boxes in that band.
-   vertical lines are always drawn top to bottom (y-increasing.)
-this requires adding one to the y-coordinate of each endpoint
-after swapping.
-
-   SLOPED LINES
-   when clipping a sloped line, we bring the second point inside
-the clipping box, rather than one beyond it, and then add 1 to
-the length of the line before drawing it.  this lets us use
-the same box for finding the outcodes for both endpoints.  since
-the equation for clipping the second endpoint to an edge gives us
-1 beyond the edge, we then have to move the point towards the
-first point by one step on the major axis.
-   eventually, there will be a diagram here to explain what's going
-on.  the method uses Cohen-Sutherland outcodes to determine
-outsideness, and a method similar to Pike's layers for doing the
-actual clipping.
-
-*/
-
-void
-#ifdef POLYSEGMENT
-cfbSegmentSS (pDrawable, pGC, nseg, pSeg)
-    DrawablePtr	pDrawable;
-    GCPtr	pGC;
-    int		nseg;
-    register xSegment	*pSeg;
-#else
-cfbLineSS (pDrawable, pGC, mode, npt, pptInit)
-    DrawablePtr pDrawable;
-    GCPtr	pGC;
-    int		mode;		/* Origin or Previous */
-    int		npt;		/* number of points */
-    DDXPointPtr pptInit;
-#endif
-{
-    int nboxInit;
-    register int nbox;
-    BoxPtr pboxInit;
-    register BoxPtr pbox;
-#ifndef POLYSEGMENT
-    register DDXPointPtr ppt;	/* pointer to list of translated points */
-#endif
-
-    unsigned int oc1;		/* outcode of point 1 */
-    unsigned int oc2;		/* outcode of point 2 */
-
-    CfbBits *addrl;	/* address of destination pixmap */
-    int nlwidth;		/* width in longwords of destination pixmap */
-    int xorg, yorg;		/* origin of window */
-
-    int adx;		/* abs values of dx and dy */
-    int ady;
-    int signdx;		/* sign of dx and dy */
-    int signdy;
-    int e, e1, e2;		/* bresenham error and increments */
-    int len;			/* length of segment */
-    int axis;			/* major axis */
-    int octant;
-    unsigned int bias = miGetZeroLineBias(pDrawable->pScreen);
-
-				/* a bunch of temporaries */
-    int tmp;
-    register int y1, y2;
-    register int x1, x2;
-    RegionPtr cclip;
-    cfbPrivGCPtr    devPriv;
-    CfbBits   xor, and;
-    int		    alu;
-
-    devPriv = cfbGetGCPrivate(pGC);
-    cclip = pGC->pCompositeClip;
-    pboxInit = REGION_RECTS(cclip);
-    nboxInit = REGION_NUM_RECTS(cclip);
-
-    cfbGetLongWidthAndPointer (pDrawable, nlwidth, addrl)
-
-    alu = devPriv->rop;
-    xor = devPriv->xor;
-    and = devPriv->and;
-    xorg = pDrawable->x;
-    yorg = pDrawable->y;
-#ifdef POLYSEGMENT
-    while (nseg--)
-#else
-    ppt = pptInit;
-    x2 = ppt->x + xorg;
-    y2 = ppt->y + yorg;
-    while(--npt)
-#endif
-    {
-	nbox = nboxInit;
-	pbox = pboxInit;
-
-#ifdef POLYSEGMENT
-	x1 = pSeg->x1 + xorg;
-	y1 = pSeg->y1 + yorg;
-	x2 = pSeg->x2 + xorg;
-	y2 = pSeg->y2 + yorg;
-	pSeg++;
-#else
-	x1 = x2;
-	y1 = y2;
-	++ppt;
-	if (mode == CoordModePrevious)
-	{
-	    xorg = x1;
-	    yorg = y1;
-	}
-	x2 = ppt->x + xorg;
-	y2 = ppt->y + yorg;
-#endif
-
-	if (x1 == x2)  /* vertical line */
-	{
-	    /* make the line go top to bottom of screen, keeping
-	       endpoint semantics
-	    */
-	    if (y1 > y2)
-	    {
-		register int tmp;
-
-		tmp = y2;
-		y2 = y1 + 1;
-		y1 = tmp + 1;
-#ifdef POLYSEGMENT
-		if (pGC->capStyle != CapNotLast)
-		    y1--;
-#endif
-	    }
-#ifdef POLYSEGMENT
-	    else if (pGC->capStyle != CapNotLast)
-		y2++;
-#endif
-	    /* get to first band that might contain part of line */
-	    while ((nbox) && (pbox->y2 <= y1))
-	    {
-		pbox++;
-		nbox--;
-	    }
-
-	    if (nbox)
-	    {
-		/* stop when lower edge of box is beyond end of line */
-		while((nbox) && (y2 >= pbox->y1))
-		{
-		    if ((x1 >= pbox->x1) && (x1 < pbox->x2))
-		    {
-			int y1t, y2t;
-			/* this box has part of the line in it */
-			y1t = max(y1, pbox->y1);
-			y2t = min(y2, pbox->y2);
-			if (y1t != y2t)
-			{
-			    cfbVertS (alu, and, xor,
-				      addrl, nlwidth, 
-				      x1, y1t, y2t-y1t);
-			}
-		    }
-		    nbox--;
-		    pbox++;
-		}
-	    }
-#ifndef POLYSEGMENT
-	    y2 = ppt->y + yorg;
-#endif
-	}
-	else if (y1 == y2)  /* horizontal line */
-	{
-	    /* force line from left to right, keeping
-	       endpoint semantics
-	    */
-	    if (x1 > x2)
-	    {
-		register int tmp;
-
-		tmp = x2;
-		x2 = x1 + 1;
-		x1 = tmp + 1;
-#ifdef POLYSEGMENT
-		if (pGC->capStyle != CapNotLast)
-		    x1--;
-#endif
-	    }
-#ifdef POLYSEGMENT
-	    else if (pGC->capStyle != CapNotLast)
-		x2++;
-#endif
-
-	    /* find the correct band */
-	    while( (nbox) && (pbox->y2 <= y1))
-	    {
-		pbox++;
-		nbox--;
-	    }
-
-	    /* try to draw the line, if we haven't gone beyond it */
-	    if ((nbox) && (pbox->y1 <= y1))
-	    {
-		/* when we leave this band, we're done */
-		tmp = pbox->y1;
-		while((nbox) && (pbox->y1 == tmp))
-		{
-		    int	x1t, x2t;
-
-		    if (pbox->x2 <= x1)
-		    {
-			/* skip boxes until one might contain start point */
-			nbox--;
-			pbox++;
-			continue;
-		    }
-
-		    /* stop if left of box is beyond right of line */
-		    if (pbox->x1 >= x2)
-		    {
-			nbox = 0;
-			break;
-		    }
-
-		    x1t = max(x1, pbox->x1);
-		    x2t = min(x2, pbox->x2);
-		    if (x1t != x2t)
-		    {
-			cfbHorzS (alu, and, xor,
-				  addrl, nlwidth, 
-				  x1t, y1, x2t-x1t);
-		    }
-		    nbox--;
-		    pbox++;
-		}
-	    }
-#ifndef POLYSEGMENT
-	    x2 = ppt->x + xorg;
-#endif
-	}
-	else	/* sloped line */
-	{
-	    CalcLineDeltas(x1, y1, x2, y2, adx, ady, signdx, signdy,
-			   1, 1, octant);
-
-	    if (adx > ady)
-	    {
-		axis = X_AXIS;
-		e1 = ady << 1;
-		e2 = e1 - (adx << 1);
-		e = e1 - adx;
- 	    }
-	    else
-	    {
-		axis = Y_AXIS;
-		e1 = adx << 1;
-		e2 = e1 - (ady << 1);
-		e = e1 - ady;
-		SetYMajorOctant(octant);
-	    }
-
-	    FIXUP_ERROR(e, octant, bias);
-
-	    /* we have bresenham parameters and two points.
-	       all we have to do now is clip and draw.
-	    */
-
-	    while(nbox--)
-	    {
-		oc1 = 0;
-		oc2 = 0;
-		OUTCODES(oc1, x1, y1, pbox);
-		OUTCODES(oc2, x2, y2, pbox);
-		if ((oc1 | oc2) == 0)
-		{
-		    if (axis == X_AXIS)
-			len = adx;
-		    else
-			len = ady;
-#ifdef POLYSEGMENT
-		    if (pGC->capStyle != CapNotLast)
-			len++;
-#endif
-		    cfbBresS (alu, and, xor,
-			  addrl, nlwidth,
-			  signdx, signdy, axis, x1, y1,
-			  e, e1, e2, len);
-		    break;
-		}
-		else if (oc1 & oc2)
-		{
-		    pbox++;
-		}
-		else
-		{
-		    int new_x1 = x1, new_y1 = y1, new_x2 = x2, new_y2 = y2;
-		    int clip1 = 0, clip2 = 0;
-		    int clipdx, clipdy;
-		    int err;
-		    
-		    if (miZeroClipLine(pbox->x1, pbox->y1, pbox->x2-1,
-				       pbox->y2-1,
-				       &new_x1, &new_y1, &new_x2, &new_y2,
-				       adx, ady, &clip1, &clip2,
-				       octant, bias, oc1, oc2) == -1)
-		    {
-			pbox++;
-			continue;
-		    }
-
-		    if (axis == X_AXIS)
-			len = abs(new_x2 - new_x1);
-		    else
-			len = abs(new_y2 - new_y1);
-#ifdef POLYSEGMENT
-		    if (clip2 != 0 || pGC->capStyle != CapNotLast)
-			len++;
-#else
-		    len += (clip2 != 0);
-#endif
-		    if (len)
-		    {
-			/* unwind bresenham error term to first point */
-			if (clip1)
-			{
-			    clipdx = abs(new_x1 - x1);
-			    clipdy = abs(new_y1 - y1);
-			    if (axis == X_AXIS)
-				err = e+((clipdy*e2) + ((clipdx-clipdy)*e1));
-			    else
-				err = e+((clipdx*e2) + ((clipdy-clipdx)*e1));
-			}
-			else
-			    err = e;
-			    cfbBresS(alu, and, xor,
-				     addrl, nlwidth,
-				     signdx, signdy, axis, new_x1, new_y1,
-				     err, e1, e2, len);
-		    }
-		    pbox++;
-		}
-	    } /* while (nbox--) */
-	} /* sloped line */
-    } /* while (nline--) */
-
-#ifndef POLYSEGMENT
-    /* paint the last point if the end style isn't CapNotLast.
-       (Assume that a projecting, butt, or round cap that is one
-        pixel wide is the same as the single pixel of the endpoint.)
-    */
-
-    if ((pGC->capStyle != CapNotLast) &&
-	((ppt->x + xorg != pptInit->x + pDrawable->x) ||
-	 (ppt->y + yorg != pptInit->y + pDrawable->y) ||
-	 (ppt == pptInit + 1)))
-    {
-	nbox = nboxInit;
-	pbox = pboxInit;
-	while (nbox--)
-	{
-	    if ((x2 >= pbox->x1) &&
-		(y2 >= pbox->y1) &&
-		(x2 <  pbox->x2) &&
-		(y2 <  pbox->y2))
-	    {
-		CfbBits mask;
-		CfbBits scrbits;
-
-#if PSZ == 24
-		mask = cfbmask[(x2 & 3)<<1];
-		addrl += (y2 * nlwidth) + ((x2*3) >> 2);
-#else
-		mask = cfbmask[x2 & PIM];
-		addrl += (y2 * nlwidth) + (x2 >> PWSH);
-#endif
-		scrbits = *addrl;
-		*addrl = (scrbits & ~mask) |
-			 (DoRRop (scrbits, and, xor) & mask);
-		break;
-	    }
-	    else
-		pbox++;
-	}
-    }
-#endif
-}
-
-/*
- * Draw dashed 1-pixel lines.
- */
-
-void
-#ifdef POLYSEGMENT
-cfbSegmentSD (pDrawable, pGC, nseg, pSeg)
-    DrawablePtr	pDrawable;
-    register GCPtr	pGC;
-    int		nseg;
-    register xSegment	*pSeg;
-#else
-cfbLineSD( pDrawable, pGC, mode, npt, pptInit)
-    DrawablePtr pDrawable;
-    register GCPtr pGC;
-    int mode;		/* Origin or Previous */
-    int npt;		/* number of points */
-    DDXPointPtr pptInit;
-#endif
-{
-    int nboxInit;
-    register int nbox;
-    BoxPtr pboxInit;
-    register BoxPtr pbox;
-#ifndef POLYSEGMENT
-    register DDXPointPtr ppt;	/* pointer to list of translated points */
-#endif
-
-    register unsigned int oc1;		/* outcode of point 1 */
-    register unsigned int oc2;		/* outcode of point 2 */
-
-    CfbBits *addrl;		/* address of destination pixmap */
-    int nlwidth;		/* width in longwords of destination pixmap */
-    int xorg, yorg;		/* origin of window */
-
-    int adx;		/* abs values of dx and dy */
-    int ady;
-    int signdx;		/* sign of dx and dy */
-    int signdy;
-    int e, e1, e2;		/* bresenham error and increments */
-    int len;			/* length of segment */
-    int axis;			/* major axis */
-    int octant;
-    unsigned int bias = miGetZeroLineBias(pDrawable->pScreen);
-    int x1, x2, y1, y2;
-    RegionPtr cclip;
-    cfbRRopRec	    rrops[2];
-    unsigned char   *pDash;
-    int		    dashOffset;
-    int		    numInDashList;
-    int		    dashIndex;
-    int		    isDoubleDash;
-    int		    dashIndexTmp, dashOffsetTmp;
-    int		    unclippedlen;
-    cfbPrivGCPtr    devPriv;
-
-    devPriv = cfbGetGCPrivate(pGC);
-    cclip = pGC->pCompositeClip;
-    rrops[0].rop = devPriv->rop;
-    rrops[0].and = devPriv->and;
-    rrops[0].xor = devPriv->xor;
-    if (pGC->alu == GXcopy)
-    {
-	rrops[1].rop = GXcopy;
-	rrops[1].and = 0;
-	rrops[1].xor = PFILL (pGC->bgPixel);
-    }
-    else
-    {
-    	rrops[1].rop = cfbReduceRasterOp (pGC->alu,
-					  pGC->bgPixel, pGC->planemask,
-					  &rrops[1].and, &rrops[1].xor);
-    }
-    pboxInit = REGION_RECTS(cclip);
-    nboxInit = REGION_NUM_RECTS(cclip);
-
-    cfbGetLongWidthAndPointer (pDrawable, nlwidth, addrl)
-
-    /* compute initial dash values */
-     
-    pDash = (unsigned char *) pGC->dash;
-    numInDashList = pGC->numInDashList;
-    isDoubleDash = (pGC->lineStyle == LineDoubleDash);
-    dashIndex = 0;
-    dashOffset = 0;
-    miStepDash ((int)pGC->dashOffset, &dashIndex, pDash,
-		numInDashList, &dashOffset);
-
-    xorg = pDrawable->x;
-    yorg = pDrawable->y;
-#ifdef POLYSEGMENT
-    while (nseg--)
-#else
-    ppt = pptInit;
-    x2 = ppt->x + xorg;
-    y2 = ppt->y + yorg;
-    while(--npt)
-#endif
-    {
-	nbox = nboxInit;
-	pbox = pboxInit;
-
-#ifdef POLYSEGMENT
-	x1 = pSeg->x1 + xorg;
-	y1 = pSeg->y1 + yorg;
-	x2 = pSeg->x2 + xorg;
-	y2 = pSeg->y2 + yorg;
-	pSeg++;
-#else
-	x1 = x2;
-	y1 = y2;
-	++ppt;
-	if (mode == CoordModePrevious)
-	{
-	    xorg = x1;
-	    yorg = y1;
-	}
-	x2 = ppt->x + xorg;
-	y2 = ppt->y + yorg;
-#endif
-
-	CalcLineDeltas(x1, y1, x2, y2, adx, ady, signdx, signdy, 1, 1, octant);
-
-	if (adx > ady)
-	{
-	    axis = X_AXIS;
-	    e1 = ady << 1;
-	    e2 = e1 - (adx << 1);
-	    e = e1 - adx;
-	    unclippedlen = adx;
-	}
-	else
-	{
-	    axis = Y_AXIS;
-	    e1 = adx << 1;
-	    e2 = e1 - (ady << 1);
-	    e = e1 - ady;
-	    unclippedlen = ady;
-	    SetYMajorOctant(octant);
-	}
-
-	FIXUP_ERROR(e, octant, bias);
-
-	/* we have bresenham parameters and two points.
-	   all we have to do now is clip and draw.
-	*/
-
-	while(nbox--)
-	{
-	    oc1 = 0;
-	    oc2 = 0;
-	    OUTCODES(oc1, x1, y1, pbox);
-	    OUTCODES(oc2, x2, y2, pbox);
-	    if ((oc1 | oc2) == 0)
-	    {
-#ifdef POLYSEGMENT
-		if (pGC->capStyle != CapNotLast)
-		    unclippedlen++;
-		dashIndexTmp = dashIndex;
-		dashOffsetTmp = dashOffset;
-		cfbBresD (rrops,
-		      &dashIndexTmp, pDash, numInDashList,
-		      &dashOffsetTmp, isDoubleDash,
-		      addrl, nlwidth,
-		      signdx, signdy, axis, x1, y1,
-		      e, e1, e2, unclippedlen);
-		break;
-#else
-		cfbBresD (rrops,
-		      &dashIndex, pDash, numInDashList,
-		      &dashOffset, isDoubleDash,
-		      addrl, nlwidth,
-		      signdx, signdy, axis, x1, y1,
-		      e, e1, e2, unclippedlen);
-		goto dontStep;
-#endif
-	    }
-	    else if (oc1 & oc2)
-	    {
-		pbox++;
-	    }
-	    else /* have to clip */
-	    {
-		int new_x1 = x1, new_y1 = y1, new_x2 = x2, new_y2 = y2;
-		int clip1 = 0, clip2 = 0;
-		int clipdx, clipdy;
-		int err;
-		
-		if (miZeroClipLine(pbox->x1, pbox->y1, pbox->x2-1,
-				   pbox->y2-1,
-				   &new_x1, &new_y1, &new_x2, &new_y2,
-				   adx, ady, &clip1, &clip2,
-				   octant, bias, oc1, oc2) == -1)
-		{
-		    pbox++;
-		    continue;
-		}
-
-		dashIndexTmp = dashIndex;
-		dashOffsetTmp = dashOffset;
-
-		if (clip1)
-		{
-		    int dlen;
-    
-		    if (axis == X_AXIS)
-			dlen = abs(new_x1 - x1);
-		    else
-			dlen = abs(new_y1 - y1);
-		    miStepDash (dlen, &dashIndexTmp, pDash,
-				numInDashList, &dashOffsetTmp);
-		}
-		
-		if (axis == X_AXIS)
-		    len = abs(new_x2 - new_x1);
-		else
-		    len = abs(new_y2 - new_y1);
-#ifdef POLYSEGMENT
-		if (clip2 != 0 || pGC->capStyle != CapNotLast)
-		    len++;
-#else
-		len += (clip2 != 0);
-#endif
-		if (len)
-		{
-		    /* unwind bresenham error term to first point */
-		    if (clip1)
-		    {
-			clipdx = abs(new_x1 - x1);
-			clipdy = abs(new_y1 - y1);
-			if (axis == X_AXIS)
-			    err = e+((clipdy*e2) + ((clipdx-clipdy)*e1));
-			else
-			    err = e+((clipdx*e2) + ((clipdy-clipdx)*e1));
-		    }
-		    else
-			err = e;
-		    cfbBresD (rrops,
-			      &dashIndexTmp, pDash, numInDashList,
-			      &dashOffsetTmp, isDoubleDash,
-			      addrl, nlwidth,
-			      signdx, signdy, axis, new_x1, new_y1,
-			      err, e1, e2, len);
-		}
-		pbox++;
-	    }
-	} /* while (nbox--) */
-#ifndef POLYSEGMENT
-	/*
-	 * walk the dash list around to the next line
-	 */
-	miStepDash (unclippedlen, &dashIndex, pDash,
-		    numInDashList, &dashOffset);
-dontStep:	;
-#endif
-    } /* while (nline--) */
-
-#ifndef POLYSEGMENT
-    /* paint the last point if the end style isn't CapNotLast.
-       (Assume that a projecting, butt, or round cap that is one
-        pixel wide is the same as the single pixel of the endpoint.)
-    */
-
-    if ((pGC->capStyle != CapNotLast) &&
-        ((dashIndex & 1) == 0 || isDoubleDash) &&
-	((ppt->x + xorg != pptInit->x + pDrawable->x) ||
-	 (ppt->y + yorg != pptInit->y + pDrawable->y) ||
-	 (ppt == pptInit + 1)))
-    {
-	nbox = nboxInit;
-	pbox = pboxInit;
-	while (nbox--)
-	{
-	    if ((x2 >= pbox->x1) &&
-		(y2 >= pbox->y1) &&
-		(x2 <  pbox->x2) &&
-		(y2 <  pbox->y2))
-	    {
-		CfbBits	mask;
-		int		pix;
-
-		pix = 0;
-		if (dashIndex & 1)
-		    pix = 1;
-#if PSZ == 24
-		mask = cfbmask[(x2 & 3)<<1];
-		addrl += (y2 * nlwidth) + ((x2 *3)>> 2);
-#else
-		mask = cfbmask[x2 & PIM];
-		addrl += (y2 * nlwidth) + (x2 >> PWSH);
-#endif
-		*addrl = DoMaskRRop (*addrl, rrops[pix].and, rrops[pix].xor, mask);
-		break;
-	    }
-	    else
-		pbox++;
-	}
-    }
-#endif
-}
diff --git a/cfb/cfbmap.h b/cfb/cfbmap.h
deleted file mode 100644
index 16e4afc..0000000
--- a/cfb/cfbmap.h
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- *
-Copyright 1991, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- */
-
-
-/*
- * Map names around so that multiple depths can be supported simultaneously
- */
-
-/* a losing vendor cpp dumps core if we define CFBNAME in terms of CATNAME */
-
-#if PSZ != 8
-
-#if PSZ == 32
-#if !defined(UNIXCPP) || defined(ANSICPP)
-#define CFBNAME(subname) cfb32##subname
-#else
-#define CFBNAME(subname) cfb32/**/subname
-#endif
-#endif
-
-#if PSZ == 24
-#if !defined(UNIXCPP) || defined(ANSICPP)
-#define CFBNAME(subname) cfb24##subname
-#else
-#define CFBNAME(subname) cfb24/**/subname
-#endif
-#endif
-
-#if PSZ == 16
-#if !defined(UNIXCPP) || defined(ANSICPP)
-#define CFBNAME(subname) cfb16##subname
-#else
-#define CFBNAME(subname) cfb16/**/subname
-#endif
-#endif
-
-#if PSZ == 4
-#if !defined(UNIXCPP) || defined(ANSICPP)
-#define CFBNAME(subname) cfb4##subname
-#else
-#define CFBNAME(subname) cfb4/**/subname
-#endif
-#endif
-
-#ifndef CFBNAME
-cfb can not hack PSZ yet
-#endif
-
-#undef CATNAME
-
-#if !defined(UNIXCPP) || defined(ANSICPP)
-#define CATNAME(prefix,subname) prefix##subname
-#else
-#define CATNAME(prefix,subname) prefix/**/subname
-#endif
-
-#define QuartetBitsTable CFBNAME(QuartetBitsTable)
-#define QuartetPixelMaskTable CFBNAME(QuartetPixelMaskTable)
-#define cfb8ClippedLineCopy CFBNAME(ClippedLineCopy)
-#define cfb8ClippedLineGeneral  CFBNAME(ClippedLineGeneral )
-#define cfb8ClippedLineXor CFBNAME(ClippedLineXor)
-#define cfb8LineSS1Rect CFBNAME(LineSS1Rect)
-#define cfb8LineSS1RectCopy CFBNAME(LineSS1RectCopy)
-#define cfb8LineSS1RectGeneral  CFBNAME(LineSS1RectGeneral )
-#define cfb8LineSS1RectPreviousCopy CFBNAME(LineSS1RectPreviousCopy)
-#define cfb8LineSS1RectXor CFBNAME(LineSS1RectXor)
-#define cfb8SegmentSS1Rect CFBNAME(SegmentSS1Rect)
-#define cfb8SegmentSS1RectCopy CFBNAME(SegmentSS1RectCopy)
-#define cfb8SegmentSS1RectGeneral  CFBNAME(SegmentSS1RectGeneral )
-#define cfb8SegmentSS1RectShiftCopy CFBNAME(SegmentSS1RectShiftCopy)
-#define cfb8SegmentSS1RectXor CFBNAME(SegmentSS1RectXor)
-#define cfbAllocatePrivates CFBNAME(AllocatePrivates)
-#define cfbBSFuncRec CFBNAME(BSFuncRec)
-#define cfbBitBlt CFBNAME(BitBlt)
-#define cfbBresD CFBNAME(BresD)
-#define cfbBresS CFBNAME(BresS)
-#define cfbChangeWindowAttributes CFBNAME(ChangeWindowAttributes)
-#define cfbClearVisualTypes CFBNAME(cfbClearVisualTypes)
-#define cfbCloseScreen CFBNAME(CloseScreen)
-#define cfbCreateDefColormap CFBNAME (cfbCreateDefColormap)
-#define cfbCopyArea CFBNAME(CopyArea)
-#define cfbCopyImagePlane CFBNAME(CopyImagePlane)
-#define cfbCopyPixmap CFBNAME(CopyPixmap)
-#define cfbCopyPlane CFBNAME(CopyPlane)
-#define cfbCopyPlaneReduce CFBNAME(CopyPlaneReduce)
-#define cfbCopyRotatePixmap CFBNAME(CopyRotatePixmap)
-#define cfbCopyWindow CFBNAME(CopyWindow)
-#define cfbCreateGC CFBNAME(CreateGC)
-#define cfbCreatePixmap CFBNAME(CreatePixmap)
-#define cfbCreateScreenResources CFBNAME(CreateScreenResources)
-#define cfbCreateWindow CFBNAME(CreateWindow)
-#define cfbDestroyPixmap CFBNAME(DestroyPixmap)
-#define cfbDestroyWindow CFBNAME(DestroyWindow)
-#define cfbDoBitblt CFBNAME(DoBitblt)
-#define cfbDoBitbltCopy CFBNAME(DoBitbltCopy)
-#define cfbDoBitbltGeneral CFBNAME(DoBitbltGeneral)
-#define cfbDoBitbltOr CFBNAME(DoBitbltOr)
-#define cfbDoBitbltXor CFBNAME(DoBitbltXor)
-#define cfbExpandDirectColors CFBNAME(cfbExpandDirectColors)
-#define cfbFillBoxTile32sCopy CFBNAME(FillBoxTile32sCopy)
-#define cfbFillBoxTile32sGeneral CFBNAME(FillBoxTile32sGeneral)
-#define cfbFillBoxTileOdd CFBNAME(FillBoxTileOdd)
-#define cfbFillBoxTileOddCopy CFBNAME(FillBoxTileOddCopy)
-#define cfbFillBoxTileOddGeneral CFBNAME(FillBoxTileOddGeneral)
-#define cfbFillPoly1RectCopy CFBNAME(FillPoly1RectCopy)
-#define cfbFillPoly1RectGeneral CFBNAME(FillPoly1RectGeneral)
-#define cfbFillRectSolidCopy CFBNAME(FillRectSolidCopy)
-#define cfbFillRectSolidGeneral CFBNAME(FillRectSolidGeneral)
-#define cfbFillRectSolidXor CFBNAME(FillRectSolidXor)
-#define cfbFillRectTile32Copy CFBNAME(FillRectTile32Copy)
-#define cfbFillRectTile32General CFBNAME(FillRectTile32General)
-#define cfbFillRectTileOdd CFBNAME(FillRectTileOdd)
-#define cfbFillSpanTile32sCopy CFBNAME(FillSpanTile32sCopy)
-#define cfbFillSpanTile32sGeneral CFBNAME(FillSpanTile32sGeneral)
-#define cfbFillSpanTileOddCopy CFBNAME(FillSpanTileOddCopy)
-#define cfbFillSpanTileOddGeneral CFBNAME(FillSpanTileOddGeneral)
-#define cfbFinishScreenInit CFBNAME(FinishScreenInit)
-#define cfbGCFuncs CFBNAME(GCFuncs)
-#define cfbGCPrivateKey CFBNAME(GCPrivateKey)
-#define cfbGetImage CFBNAME(GetImage)
-#define cfbGetScreenPixmap CFBNAME(GetScreenPixmap)
-#define cfbGetSpans CFBNAME(GetSpans)
-#define cfbHorzS CFBNAME(HorzS)
-#define cfbImageGlyphBlt8 CFBNAME(ImageGlyphBlt8)
-#define cfbInitializeColormap CFBNAME(InitializeColormap)
-#define cfbInitVisuals CFBNAME(cfbInitVisuals)
-#define cfbInstallColormap CFBNAME(InstallColormap)
-#define cfbLineSD CFBNAME(LineSD)
-#define cfbLineSS CFBNAME(LineSS)
-#define cfbListInstalledColormaps CFBNAME(ListInstalledColormaps)
-#define cfbMapWindow CFBNAME(MapWindow)
-#define cfbMatchCommon CFBNAME(MatchCommon)
-#define cfbNonTEOps CFBNAME(NonTEOps)
-#define cfbNonTEOps1Rect CFBNAME(NonTEOps1Rect)
-#define cfbPadPixmap CFBNAME(PadPixmap)
-#define cfbPolyFillArcSolidCopy CFBNAME(PolyFillArcSolidCopy)
-#define cfbPolyFillArcSolidGeneral CFBNAME(PolyFillArcSolidGeneral)
-#define cfbPolyFillRect CFBNAME(PolyFillRect)
-#define cfbPolyGlyphBlt8 CFBNAME(PolyGlyphBlt8)
-#define cfbPolyGlyphRop8 CFBNAME(PolyGlyphRop8)
-#define cfbPolyPoint CFBNAME(PolyPoint)
-#define cfbPositionWindow CFBNAME(PositionWindow)
-#define cfbPutImage CFBNAME(PutImage)
-#define cfbReduceRasterOp CFBNAME(ReduceRasterOp)
-#define cfbResolveColor CFBNAME(ResolveColor)
-#define cfbRestoreAreas CFBNAME(RestoreAreas)
-#define cfbSaveAreas CFBNAME(SaveAreas)
-#define cfbScreenInit CFBNAME(ScreenInit)
-#define cfbScreenPrivateKey CFBNAME(ScreenPrivateKey)
-#define cfbSegmentSD CFBNAME(SegmentSD)
-#define cfbSegmentSS CFBNAME(SegmentSS)
-#define cfbSetScanline CFBNAME(SetScanline)
-#define cfbSetScreenPixmap CFBNAME(SetScreenPixmap)
-#define cfbSetSpans CFBNAME(SetSpans)
-#define cfbSetVisualTypes CFBNAME(cfbSetVisualTypes)
-#define cfbSetupScreen CFBNAME(SetupScreen)
-#define cfbSolidSpansCopy CFBNAME(SolidSpansCopy)
-#define cfbSolidSpansGeneral CFBNAME(SolidSpansGeneral)
-#define cfbSolidSpansXor CFBNAME(SolidSpansXor)
-#define cfbStippleStack CFBNAME(StippleStack)
-#define cfbStippleStackTE CFBNAME(StippleStackTE)
-#define cfbTEGlyphBlt CFBNAME(TEGlyphBlt)
-#define cfbTEOps CFBNAME(TEOps)
-#define cfbTEOps1Rect CFBNAME(TEOps1Rect)
-#define cfbTile32FSCopy CFBNAME(Tile32FSCopy)
-#define cfbTile32FSGeneral CFBNAME(Tile32FSGeneral)
-#define cfbUninstallColormap CFBNAME(UninstallColormap)
-#define cfbUnmapWindow CFBNAME(UnmapWindow)
-#define cfbUnnaturalStippleFS CFBNAME(UnnaturalStippleFS)
-#define cfbUnnaturalTileFS CFBNAME(UnnaturalTileFS)
-#define cfbValidateGC CFBNAME(ValidateGC)
-#define cfbVertS CFBNAME(VertS)
-#define cfbWindowPrivateKey CFBNAME(WindowPrivateKey)
-#define cfbXRotatePixmap CFBNAME(XRotatePixmap)
-#define cfbYRotatePixmap CFBNAME(YRotatePixmap)
-#define cfbZeroPolyArcSS8Copy CFBNAME(ZeroPolyArcSSCopy)
-#define cfbZeroPolyArcSS8General CFBNAME(ZeroPolyArcSSGeneral)
-#define cfbZeroPolyArcSS8Xor CFBNAME(ZeroPolyArcSSXor)
-#define cfbendpartial CFBNAME(endpartial)
-#define cfbendtab CFBNAME(endtab)
-#define cfbmask CFBNAME(mask)
-#define cfbrmask CFBNAME(rmask)
-#define cfbstartpartial CFBNAME(startpartial)
-#define cfbstarttab CFBNAME(starttab)
-
-#endif /* PSZ != 8 */
diff --git a/cfb/cfbmskbits.c b/cfb/cfbmskbits.c
deleted file mode 100644
index 915ea35..0000000
--- a/cfb/cfbmskbits.c
+++ /dev/null
@@ -1,1400 +0,0 @@
-/************************************************************
-Copyright 1987 by Sun Microsystems, Inc. Mountain View, CA.
-
-                    All Rights Reserved
-
-Permission  to  use,  copy,  modify,  and  distribute   this
-software  and  its documentation for any purpose and without
-fee is hereby granted, provided that the above copyright no-
-tice  appear  in all copies and that both that copyright no-
-tice and this permission notice appear in  supporting  docu-
-mentation,  and  that the names of Sun or The Open Group
-not be used in advertising or publicity pertaining to 
-distribution  of  the software  without specific prior 
-written permission. Sun and The Open Group make no 
-representations about the suitability of this software for 
-any purpose. It is provided "as is" without any express or 
-implied warranty.
-
-SUN DISCLAIMS ALL WARRANTIES WITH REGARD TO  THIS  SOFTWARE,
-INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
-NESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SUN BE  LI-
-ABLE  FOR  ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,  DATA  OR
-PROFITS,  WHETHER  IN  AN  ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
-THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-********************************************************/
-
-
-/*
- * ==========================================================================
- * Converted to Color Frame Buffer by smarks at sun, April-May 1987.  The "bit 
- * numbering" in the doc below really means "byte numbering" now.
- * ==========================================================================
- */
-
-/*
-   these tables are used by several macros in the cfb code.
-
-   the vax numbers everything left to right, so bit indices on the
-screen match bit indices in longwords.  the pc-rt and Sun number
-bits on the screen the way they would be written on paper,
-(i.e. msb to the left), and so a bit index n on the screen is
-bit index 32-n in a longword
-
-   see also cfbmskbits.h
-*/
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include	<X11/X.h>
-#include	<X11/Xmd.h>
-#include	<servermd.h>
-#include	"cfb.h"
-#include	"cfbmskbits.h"
-
-#define _cfbBits(a) (PixelGroup)(a)
-
-#if	(BITMAP_BIT_ORDER == MSBFirst)
-#define cfbBits(v)	_cfbBits(v)
-#else /* BITMAP_BIT_ORDER == LSBFirst */
-#define cfbFlip2(a)	((((a) & 0x1) << 1) | (((a) & 0x2) >> 1))
-#define cfbFlip4(a)	((cfbFlip2(a) << 2) | cfbFlip2(a >> 2))
-#define cfbFlip8(a)	((cfbFlip4(a) << 4) | cfbFlip4(a >> 4))
-#define cfbFlip16(a)	((cfbFlip8(a) << 8) | cfbFlip8(a >> 8))
-#define cfbFlip32(a)	((cfbFlip16(a) << 16) | cfbFlip16(a >> 16))
-#if PGSZ == 32
-#define cfbBits(a)	cfbFlip32(_cfbBits(a))
-#else /* PGSZ == 64 */
-#define cfbFlip64(a)	((cfbFlip32(a) << 32) | cfbFlip32(a >> 32))
-#define cfbBits(a)	cfbFlip64(_cfbBits(a))
-#endif /* PGSZ */
-#endif /* BITMAP_BIT_ORDER */
-
-/* NOTE:
-the first element in starttab could be 0xffffffff.  making it 0
-lets us deal with a full first word in the middle loop, rather
-than having to do the multiple reads and masks that we'd
-have to do if we thought it was partial.
-*/
-#if PSZ == 4
-#if PGSZ == 32
-PixelGroup cfbstarttab[] =
-    {
-	cfbBits(0x00000000),
-	cfbBits(0x0FFFFFFF),
-	cfbBits(0x00FFFFFF),
-	cfbBits(0x000FFFFF),
-	cfbBits(0x0000FFFF),
-	cfbBits(0x00000FFF),
-	cfbBits(0x000000FF),
-	cfbBits(0x0000000F)
-    };
-PixelGroup cfbendtab[] =
-    {
-	cfbBits(0x00000000),
-	cfbBits(0xF0000000),
-	cfbBits(0xFF000000),
-	cfbBits(0xFFF00000),
-	cfbBits(0xFFFF0000),
-	cfbBits(0xFFFFF000),
-	cfbBits(0xFFFFFF00),
-	cfbBits(0xFFFFFFF0)
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbstarttab[] =
-    {
-	cfbBits(0x0000000000000000),
-	cfbBits(0x0FFFFFFFFFFFFFFF),
-	cfbBits(0x00FFFFFFFFFFFFFF),
-	cfbBits(0x000FFFFFFFFFFFFF),
-	cfbBits(0x0000FFFFFFFFFFFF),
-	cfbBits(0x00000FFFFFFFFFFF),
-	cfbBits(0x000000FFFFFFFFFF),
-	cfbBits(0x0000000FFFFFFFFF),
-	cfbBits(0x00000000FFFFFFFF),
-	cfbBits(0x000000000FFFFFFF),
-	cfbBits(0x0000000000FFFFFF),
-	cfbBits(0x00000000000FFFFF),
-	cfbBits(0x000000000000FFFF),
-	cfbBits(0x0000000000000FFF),
-	cfbBits(0x00000000000000FF),
-	cfbBits(0x000000000000000F),
-    };
-PixelGroup cfbendtab[] =
-    {
-	cfbBits(0x0000000000000000),
-	cfbBits(0xF000000000000000),
-	cfbBits(0xFF00000000000000),
-	cfbBits(0xFFF0000000000000),
-	cfbBits(0xFFFF000000000000),
-	cfbBits(0xFFFFF00000000000),
-	cfbBits(0xFFFFFF0000000000),
-	cfbBits(0xFFFFFFF000000000),
-	cfbBits(0xFFFFFFFF00000000),
-	cfbBits(0xFFFFFFFFF0000000),
-	cfbBits(0xFFFFFFFFFF000000),
-	cfbBits(0xFFFFFFFFFFF00000),
-	cfbBits(0xFFFFFFFFFFFF0000),
-	cfbBits(0xFFFFFFFFFFFFF000),
-	cfbBits(0xFFFFFFFFFFFFFF00),
-	cfbBits(0xFFFFFFFFFFFFFFF0),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 4 */
-
-#if PSZ == 8
-#if PGSZ == 32
-PixelGroup cfbstarttab[] =
-    {
-	cfbBits(0x00000000),
-	cfbBits(0x00FFFFFF),
-	cfbBits(0x0000FFFF),
-	cfbBits(0x000000FF)
-    };
-PixelGroup cfbendtab[] =
-    {
-	cfbBits(0x00000000),
-	cfbBits(0xFF000000),
-	cfbBits(0xFFFF0000),
-	cfbBits(0xFFFFFF00)
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbstarttab[] =
-    {
-	cfbBits(0x0000000000000000),
-	cfbBits(0x00FFFFFFFFFFFFFF),
-	cfbBits(0x0000FFFFFFFFFFFF),
-	cfbBits(0x000000FFFFFFFFFF),
-	cfbBits(0x00000000FFFFFFFF),
-	cfbBits(0x0000000000FFFFFF),
-	cfbBits(0x000000000000FFFF),
-	cfbBits(0x00000000000000FF)
-    };
-PixelGroup cfbendtab[] =
-    {
-	cfbBits(0x0000000000000000),
-	cfbBits(0xFF00000000000000),
-	cfbBits(0xFFFF000000000000),
-	cfbBits(0xFFFFFF0000000000),
-	cfbBits(0xFFFFFFFF00000000),
-	cfbBits(0xFFFFFFFFFF000000),
-	cfbBits(0xFFFFFFFFFFFF0000),
-	cfbBits(0xFFFFFFFFFFFFFF00)
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 8 */
-
-#if PSZ == 16
-#if PGSZ == 32
-PixelGroup cfbstarttab[] =
-    {
-	cfbBits(0x00000000),
-	cfbBits(0x0000FFFF),
-    };
-PixelGroup cfbendtab[] =
-    {
-	cfbBits(0x00000000),
-	cfbBits(0xFFFF0000),
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbstarttab[] =
-    {
-	cfbBits(0x0000000000000000),
-	cfbBits(0x0000FFFFFFFFFFFF),
-	cfbBits(0x00000000FFFFFFFF),
-	cfbBits(0x000000000000FFFF),
-    };
-PixelGroup cfbendtab[] =
-    {
-	cfbBits(0x0000000000000000),
-	cfbBits(0xFFFF000000000000),
-	cfbBits(0xFFFFFFFF00000000),
-	cfbBits(0xFFFFFFFFFFFF0000),
-    };
-#endif /* PGSZ */
-#endif
-
-#if PSZ == 24
-#if PGSZ == 32
-PixelGroup cfbstarttab[] =
-    {
-	cfbBits(0x00000000),
-	cfbBits(0x000000FF),
-	cfbBits(0x0000FFFF),
-	cfbBits(0x00FFFFFF),
-    };
-PixelGroup cfbendtab[] = 
-    {
-	cfbBits(0x00000000),
-	cfbBits(0xFFFFFF00),
-	cfbBits(0xFFFF0000),
-	cfbBits(0xFF000000),
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbstarttab[] =
-    {
-	cfbBits(0x0000000000000000),
-	cfbBits(0x000000FFFFFFFFFF),
-	cfbBits(0x000000000000FFFF),
-    };
-PixelGroup cfbendtab[] = 
-    {
-	cfbBits(0x0000000000000000),
-	cfbBits(0xFFFFFFFFFF000000),
-	cfbBits(0xFFFF000000000000),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 24 */
-
-#if PSZ == 32
-#if PGSZ == 32
-PixelGroup cfbstarttab[] =
-    {
-	cfbBits(0x00000000),
-    };
-PixelGroup cfbendtab[] = 
-    {
-	cfbBits(0x00000000),
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbstarttab[] =
-    {
-	cfbBits(0x0000000000000000),
-	cfbBits(0x00000000FFFFFFFF),
-    };
-PixelGroup cfbendtab[] = 
-    {
-	cfbBits(0x0000000000000000),
-	cfbBits(0xFFFFFFFF00000000),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 32 */
-
-/* a hack, for now, since the entries for 0 need to be all
-   1 bits, not all zeros.
-   this means the code DOES NOT WORK for segments of length
-   0 (which is only a problem in the horizontal line code.)
-*/
-#if PSZ == 4
-#if PGSZ == 32
-PixelGroup cfbstartpartial[] =
-    {
-	cfbBits(0xFFFFFFFF),
-	cfbBits(0x0FFFFFFF),
-	cfbBits(0x00FFFFFF),
-	cfbBits(0x000FFFFF),
-	cfbBits(0x0000FFFF),
-	cfbBits(0x00000FFF),
-	cfbBits(0x000000FF),
-	cfbBits(0x0000000F)
-    };
-
-PixelGroup cfbendpartial[] =
-    {
-	cfbBits(0xFFFFFFFF),
-	cfbBits(0xF0000000),
-	cfbBits(0xFF000000),
-	cfbBits(0xFFF00000),
-	cfbBits(0xFFFF0000),
-	cfbBits(0xFFFFF000),
-	cfbBits(0xFFFFFF00),
-	cfbBits(0xFFFFFFF0)
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbstartpartial[] =
-    {
-	cfbBits(0xFFFFFFFFFFFFFFFF),
-	cfbBits(0x0FFFFFFFFFFFFFFF),
-	cfbBits(0x00FFFFFFFFFFFFFF),
-	cfbBits(0x000FFFFFFFFFFFFF),
-	cfbBits(0x0000FFFFFFFFFFFF),
-	cfbBits(0x00000FFFFFFFFFFF),
-	cfbBits(0x000000FFFFFFFFFF),
-	cfbBits(0x0000000FFFFFFFFF),
-	cfbBits(0x00000000FFFFFFFF),
-	cfbBits(0x000000000FFFFFFF),
-	cfbBits(0x0000000000FFFFFF),
-	cfbBits(0x00000000000FFFFF),
-	cfbBits(0x000000000000FFFF),
-	cfbBits(0x0000000000000FFF),
-	cfbBits(0x00000000000000FF),
-	cfbBits(0x000000000000000F),
-    };
-
-PixelGroup cfbendpartial[] =
-    {
-	cfbBits(0xFFFFFFFFFFFFFFFF),
-	cfbBits(0xF000000000000000),
-	cfbBits(0xFF00000000000000),
-	cfbBits(0xFFF0000000000000),
-	cfbBits(0xFFFF000000000000),
-	cfbBits(0xFFFFF00000000000),
-	cfbBits(0xFFFFFF0000000000),
-	cfbBits(0xFFFFFFF000000000),
-	cfbBits(0xFFFFFFFF00000000),
-	cfbBits(0xFFFFFFFFF0000000),
-	cfbBits(0xFFFFFFFFFF000000),
-	cfbBits(0xFFFFFFFFFFF00000),
-	cfbBits(0xFFFFFFFFFFFF0000),
-	cfbBits(0xFFFFFFFFFFFFF000),
-	cfbBits(0xFFFFFFFFFFFFFF00),
-	cfbBits(0xFFFFFFFFFFFFFFF0),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 4 */
-
-#if PSZ == 8
-#if PGSZ == 32
-PixelGroup cfbstartpartial[] =
-    {
-	cfbBits(0xFFFFFFFF),
-	cfbBits(0x00FFFFFF),
-	cfbBits(0x0000FFFF),
-	cfbBits(0x000000FF)
-    };
-
-PixelGroup cfbendpartial[] =
-    {
-	cfbBits(0xFFFFFFFF),
-	cfbBits(0xFF000000),
-	cfbBits(0xFFFF0000),
-	cfbBits(0xFFFFFF00)
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbstartpartial[] =
-    {
-	cfbBits(0xFFFFFFFFFFFFFFFF),
-	cfbBits(0x00FFFFFFFFFFFFFF),
-	cfbBits(0x0000FFFFFFFFFFFF),
-	cfbBits(0x000000FFFFFFFFFF),
-	cfbBits(0x00000000FFFFFFFF),
-	cfbBits(0x0000000000FFFFFF),
-	cfbBits(0x000000000000FFFF),
-	cfbBits(0x00000000000000FF),
-    };
-
-PixelGroup cfbendpartial[] =
-    {
-	cfbBits(0xFFFFFFFFFFFFFFFF),
-	cfbBits(0xFF00000000000000),
-	cfbBits(0xFFFF000000000000),
-	cfbBits(0xFFFFFF0000000000),
-	cfbBits(0xFFFFFFFF00000000),
-	cfbBits(0xFFFFFFFFFF000000),
-	cfbBits(0xFFFFFFFFFFFF0000),
-	cfbBits(0xFFFFFFFFFFFFFF00),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 8 */
-
-#if PSZ == 16
-#if PGSZ == 32
-PixelGroup cfbstartpartial[] =
-    {
-	cfbBits(0xFFFFFFFF),
-	cfbBits(0x0000FFFF),
-    };
-
-PixelGroup cfbendpartial[] =
-    {
-	cfbBits(0xFFFFFFFF),
-	cfbBits(0xFFFF0000),
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbstartpartial[] =
-    {
-	cfbBits(0xFFFFFFFFFFFFFFFF),
-	cfbBits(0x0000FFFFFFFFFFFF),
-	cfbBits(0x00000000FFFFFFFF),
-	cfbBits(0x000000000000FFFF),
-    };
-
-PixelGroup cfbendpartial[] =
-    {
-	cfbBits(0xFFFFFFFFFFFFFFFF),
-	cfbBits(0xFFFF000000000000),
-	cfbBits(0xFFFFFFFF00000000),
-	cfbBits(0xFFFFFFFFFFFF0000),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 16 */
-
-#if PSZ == 24
-#if PGSZ == 32
-PixelGroup cfbstartpartial[] =
-    {
-	cfbBits(0xFFFFFFFF),
-	cfbBits(0x000000FF),
-	cfbBits(0x0000FFFF),
-	cfbBits(0x00FFFFFF),
-    };
-
-PixelGroup cfbendpartial[] =
-    {
-	cfbBits(0xFFFFFFFF),
-	cfbBits(0xFFFFFF00),
-	cfbBits(0xFFFF0000),
-	cfbBits(0xFF000000),
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbstartpartial[] =
-    {
-	cfbBits(0xFFFFFFFFFFFFFFFF),
-	cfbBits(0x0000FFFFFFFFFFFF),
-	cfbBits(0x000000FFFFFFFFFF),
-	cfbBits(0x00000000FFFFFFFF),
-	cfbBits(0x0000000000FFFFFF),
-	cfbBits(0x000000000000FFFF),
-	cfbBits(0x00000000000000FF),
-    };
-
-PixelGroup cfbendpartial[] =
-    {
-	cfbBits(0xFFFFFFFFFFFFFFFF),
-	cfbBits(0xFFFFFFFFFFFF0000),
-	cfbBits(0xFFFFFFFFFF000000),
-	cfbBits(0xFFFFFFFF00000000),
-	cfbBits(0xFFFFFF0000000000),
-	cfbBits(0xFFFF000000000000),
-	cfbBits(0xFF00000000000000),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 24 */
-
-#if PSZ == 32
-#if PGSZ == 32
-PixelGroup cfbstartpartial[] =
-    {
-	cfbBits(0xFFFFFFFF),
-    };
-
-PixelGroup cfbendpartial[] =
-    {
-	cfbBits(0xFFFFFFFF),
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbstartpartial[] =
-    {
-	cfbBits(0xFFFFFFFFFFFFFFFF),
-	cfbBits(0x00000000FFFFFFFF),
-    };
-
-PixelGroup cfbendpartial[] =
-    {
-	cfbBits(0xFFFFFFFFFFFFFFFF),
-	cfbBits(0xFFFFFFFF00000000),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 32 */
-
-/* used for masking bits in bresenham lines
-   mask[n] is used to mask out all but bit n in a longword (n is a
-screen position).
-   rmask[n] is used to mask out the single bit at position n (n
-is a screen posiotion.)
-*/
-
-#if PSZ == 4
-#if PGSZ == 32
-PixelGroup cfbmask[] =
-    {
-	cfbBits(0xF0000000),
-	cfbBits(0x0F000000),
- 	cfbBits(0x00F00000),
- 	cfbBits(0x000F0000),
- 	cfbBits(0x0000F000),
- 	cfbBits(0x00000F00),
- 	cfbBits(0x000000F0),
- 	cfbBits(0x0000000F)
-    }; 
-PixelGroup cfbrmask[] = 
-    {
-	cfbBits(0x0FFFFFFF),
-	cfbBits(0xF0FFFFFF),
- 	cfbBits(0xFF0FFFFF),
- 	cfbBits(0xFFF0FFFF),
- 	cfbBits(0xFFFF0FFF),
- 	cfbBits(0xFFFFF0FF),
- 	cfbBits(0xFFFFFF0F),
- 	cfbBits(0xFFFFFFF0)
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbmask[] =
-    {
-	cfbBits(0xF000000000000000),
-	cfbBits(0x0F00000000000000),
- 	cfbBits(0x00F0000000000000),
- 	cfbBits(0x000F000000000000),
- 	cfbBits(0x0000F00000000000),
- 	cfbBits(0x00000F0000000000),
- 	cfbBits(0x000000F000000000),
- 	cfbBits(0x0000000F00000000),
-	cfbBits(0x00000000F0000000),
-	cfbBits(0x000000000F000000),
- 	cfbBits(0x0000000000F00000),
- 	cfbBits(0x00000000000F0000),
- 	cfbBits(0x000000000000F000),
- 	cfbBits(0x0000000000000F00),
- 	cfbBits(0x00000000000000F0),
- 	cfbBits(0x000000000000000F),
-    }; 
-PixelGroup cfbrmask[] = 
-    {
-	cfbBits(0x0FFFFFFFFFFFFFFF),
-	cfbBits(0xF0FFFFFFFFFFFFFF),
- 	cfbBits(0xFF0FFFFFFFFFFFFF),
- 	cfbBits(0xFFF0FFFFFFFFFFFF),
- 	cfbBits(0xFFFF0FFFFFFFFFFF),
- 	cfbBits(0xFFFFF0FFFFFFFFFF),
- 	cfbBits(0xFFFFFF0FFFFFFFFF),
- 	cfbBits(0xFFFFFFF0FFFFFFFF),
-	cfbBits(0xFFFFFFFF0FFFFFFF),
-	cfbBits(0xFFFFFFFFF0FFFFFF),
- 	cfbBits(0xFFFFFFFFFF0FFFFF),
- 	cfbBits(0xFFFFFFFFFFF0FFFF),
- 	cfbBits(0xFFFFFFFFFFFF0FFF),
- 	cfbBits(0xFFFFFFFFFFFFF0FF),
- 	cfbBits(0xFFFFFFFFFFFFFF0F),
- 	cfbBits(0xFFFFFFFFFFFFFFF0),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 4 */
-
-#if PSZ == 8
-#if PGSZ == 32
-PixelGroup cfbmask[] =
-    {
-	cfbBits(0xFF000000),
- 	cfbBits(0x00FF0000),
- 	cfbBits(0x0000FF00),
- 	cfbBits(0x000000FF)
-    }; 
-PixelGroup cfbrmask[] = 
-    {
-	cfbBits(0x00FFFFFF),
- 	cfbBits(0xFF00FFFF),
- 	cfbBits(0xFFFF00FF),
- 	cfbBits(0xFFFFFF00)
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbmask[] =
-    {
-	cfbBits(0xFF00000000000000),
- 	cfbBits(0x00FF000000000000),
- 	cfbBits(0x0000FF0000000000),
- 	cfbBits(0x000000FF00000000),
-	cfbBits(0x00000000FF000000),
- 	cfbBits(0x0000000000FF0000),
- 	cfbBits(0x000000000000FF00),
- 	cfbBits(0x00000000000000FF),
-    }; 
-PixelGroup cfbrmask[] = 
-    {
-	cfbBits(0x00FFFFFFFFFFFFFF),
- 	cfbBits(0xFF00FFFFFFFFFFFF),
- 	cfbBits(0xFFFF00FFFFFFFFFF),
- 	cfbBits(0xFFFFFF00FFFFFFFF),
-	cfbBits(0xFFFFFFFF00FFFFFF),
- 	cfbBits(0xFFFFFFFFFF00FFFF),
- 	cfbBits(0xFFFFFFFFFFFF00FF),
- 	cfbBits(0xFFFFFFFFFFFFFF00),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 8 */
-
-#if PSZ == 16
-#if PGSZ == 32
-PixelGroup cfbmask[] =
-    {
-	cfbBits(0xFFFF0000),
- 	cfbBits(0x0000FFFF),
-    }; 
-PixelGroup cfbrmask[] = 
-    {
-	cfbBits(0x0000FFFF),
- 	cfbBits(0xFFFF0000),
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbmask[] =
-    {
-	cfbBits(0xFFFF000000000000),
- 	cfbBits(0x0000FFFF00000000),
-	cfbBits(0x00000000FFFF0000),
- 	cfbBits(0x000000000000FFFF),
-    }; 
-PixelGroup cfbrmask[] = 
-    {
-	cfbBits(0x0000FFFFFFFFFFFF),
- 	cfbBits(0xFFFF0000FFFFFFFF),
-	cfbBits(0xFFFFFFFF0000FFFF),
- 	cfbBits(0xFFFFFFFFFFFF0000),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 16 */
-
-#if PSZ == 24
-#if PGSZ == 32
-PixelGroup cfbmask[] =
-    {
- 	cfbBits(0xFFFFFF00),
-	cfbBits(0x00000000),
-	cfbBits(0x000000FF),
- 	cfbBits(0xFFFF0000),
-	cfbBits(0x0000FFFF),
-	cfbBits(0xFF000000),
-	cfbBits(0x00FFFFFF),
-	cfbBits(0x00000000),
-    }; 
-PixelGroup cfbrmask[] = 
-    {
-	cfbBits(0x000000FF),
- 	cfbBits(0xFFFFFFFF),
- 	cfbBits(0xFFFFFF00),
-	cfbBits(0x0000FFFF),
-	cfbBits(0xFFFF0000),
-	cfbBits(0x00FFFFFF),
-	cfbBits(0xFF000000),
- 	cfbBits(0xFFFFFFFF),
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbmask[] =
-    {
-	cfbBits(0xFFFFFF0000000000),
- 	cfbBits(0x000000FFFFFF0000),
- 	cfbBits(0x000000000000FFFF),
-    }; 
-PixelGroup cfbmask2[] =
-    {
- 	cfbBits(0x0000000000000000),
- 	cfbBits(0x0000000000000000),
-	cfbBits(0xFF00000000000000),
-    }; 
-PixelGroup cfbrmask[] = 
-    {
- 	cfbBits(0x000000FFFFFFFFFF),
- 	cfbBits(0xFFFFFF000000FFFF),
- 	cfbBits(0xFFFFFFFFFFFF0000),
-    };
-PixelGroup cfbrmask2[] = 
-    {
- 	cfbBits(0x0000000000000000),
- 	cfbBits(0x0000000000000000),
- 	cfbBits(0x00FFFFFFFFFFFFFF),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 24 */
-
-#if PSZ == 32
-#if PGSZ == 32
-PixelGroup cfbmask[] =
-    {
-	cfbBits(0xFFFFFFFF),
-    }; 
-PixelGroup cfbrmask[] = 
-    {
-	cfbBits(0xFFFFFFFF),
-    };
-#else /* PGSZ == 64 */
-PixelGroup cfbmask[] =
-    {
-	cfbBits(0xFFFFFFFF00000000),
-	cfbBits(0x00000000FFFFFFFF),
-    }; 
-PixelGroup cfbrmask[] = 
-    {
-	cfbBits(0x00000000FFFFFFFF),
-	cfbBits(0xFFFFFFFF00000000),
-    };
-#endif /* PGSZ */
-#endif /* PSZ == 32 */
-
-/*
- * QuartetBitsTable contains PPW+1 masks whose binary values are masks in the
- * low order quartet that contain the number of bits specified in the
- * index.  This table is used by getstipplepixels.
- */
-#if PSZ == 4
-PixelGroup QuartetBitsTable[] = {
-#if PGSZ == 32
-#if (BITMAP_BIT_ORDER == MSBFirst)
-    0x00000000,                         /* 0 - 00000000 */
-    0x00000080,				/* 1 - 10000000 */
-    0x000000C0,                         /* 2 - 11000000 */
-    0x000000E0,                         /* 3 - 11100000 */
-    0x000000F0,                         /* 4 - 11110000 */
-    0x000000F8,                         /* 5 - 11111000 */
-    0x000000FC,                         /* 6 - 11111100 */
-    0x000000FE,                         /* 7 - 11111110 */
-    0x000000FF                          /* 8 - 11111111 */
-#else /* (BITMAP_BIT_ORDER == LSBFirst */
-    0x00000000,                         /* 0 - 00000000 */
-    0x00000001,                         /* 1 - 00000001 */
-    0x00000003,                         /* 2 - 00000011 */
-    0x00000007,                         /* 3 - 00000111 */
-    0x0000000F,                         /* 4 - 00001111 */
-    0x0000001F,                         /* 5 - 00011111 */
-    0x0000003F,                         /* 6 - 00111111 */
-    0x0000007F,                         /* 7 - 01111111 */
-    0x000000FF                          /* 8 - 11111111 */
-#endif /* (BITMAP_BIT_ORDER == MSBFirst) */
-#else /* PGSZ == 64 */
-#if (BITMAP_BIT_ORDER == MSBFirst)
-    0x00000000,                         /* 0 - 0000000000000000 */
-    0x00008000,				/* 1 - 1000000000000000 */
-    0x0000C000,                         /* 2 - 1100000000000000 */
-    0x0000E000,                         /* 3 - 1110000000000000 */
-    0x0000F000,                         /* 4 - 1111000000000000 */
-    0x0000F800,                         /* 5 - 1111100000000000 */
-    0x0000FC00,                         /* 6 - 1111110000000000 */
-    0x0000FE00,                         /* 7 - 1111111000000000 */
-    0x0000FF00,                         /* 8 - 1111111100000000 */
-    0x0000FF80,				/* 9 - 1111111110000000 */
-    0x0000FFC0,                         /* 10- 1111111111000000 */
-    0x0000FFE0,                         /* 11- 1111111111100000 */
-    0x0000FFF0,                         /* 12- 1111111111110000 */
-    0x0000FFF8,                         /* 13- 1111111111111000 */
-    0x0000FFFC,                         /* 14- 1111111111111100 */
-    0x0000FFFE,                         /* 15- 1111111111111110 */
-    0x0000FFFF,                         /* 16- 1111111111111111 */
-#else /* (BITMAP_BIT_ORDER == LSBFirst */
-    0x00000000,                         /* 0 - 0000000000000000 */
-    0x00000001,                         /* 1 - 0000000000000001 */
-    0x00000003,                         /* 2 - 0000000000000011 */
-    0x00000007,                         /* 3 - 0000000000000111 */
-    0x0000000F,                         /* 4 - 0000000000001111 */
-    0x0000001F,                         /* 5 - 0000000000011111 */
-    0x0000003F,                         /* 6 - 0000000000111111 */
-    0x0000007F,                         /* 7 - 0000000001111111 */
-    0x000000FF,                         /* 8 - 0000000011111111 */
-    0x000001FF,                         /* 9 - 0000000111111111 */
-    0x000003FF,                         /* 10- 0000001111111111 */
-    0x000007FF,                         /* 11- 0000011111111111 */
-    0x00000FFF,                         /* 12- 0000111111111111 */
-    0x00001FFF,                         /* 13- 0001111111111111 */
-    0x00003FFF,                         /* 14- 0011111111111111 */
-    0x00007FFF,                         /* 15- 0111111111111111 */
-    0x0000FFFF,                         /* 16- 1111111111111111 */
-#endif /* (BITMAP_BIT_ORDER == MSBFirst) */
-#endif /* PGSZ */
-};
-#endif /* PSZ == 4 */
-
-#if PSZ == 8
-PixelGroup QuartetBitsTable[] = {
-#if PGSZ == 32
-#if (BITMAP_BIT_ORDER == MSBFirst)
-    0x00000000,                         /* 0 - 0000 */
-    0x00000008,                         /* 1 - 1000 */
-    0x0000000C,                         /* 2 - 1100 */
-    0x0000000E,                         /* 3 - 1110 */
-    0x0000000F                          /* 4 - 1111 */
-#else /* (BITMAP_BIT_ORDER == LSBFirst */
-    0x00000000,                         /* 0 - 0000 */
-    0x00000001,                         /* 1 - 0001 */
-    0x00000003,                         /* 2 - 0011 */
-    0x00000007,                         /* 3 - 0111 */
-    0x0000000F                          /* 4 - 1111 */
-#endif /* (BITMAP_BIT_ORDER == MSBFirst) */
-#else /* PGSZ == 64 */
-#if (BITMAP_BIT_ORDER == MSBFirst)
-    0x00000000,                         /* 0 - 00000000 */
-    0x00000080,                         /* 1 - 10000000 */
-    0x000000C0,                         /* 2 - 11000000 */
-    0x000000E0,                         /* 3 - 11100000 */
-    0x000000F0,                         /* 4 - 11110000 */
-    0x000000F8,                         /* 5 - 11111000 */
-    0x000000FC,                         /* 6 - 11111100 */
-    0x000000FE,                         /* 7 - 11111110 */
-    0x000000FF                          /* 8 - 11111111 */
-#else /* (BITMAP_BIT_ORDER == LSBFirst */
-    0x00000000,                         /* 0 - 00000000 */
-    0x00000001,                         /* 1 - 00000001 */
-    0x00000003,                         /* 2 - 00000011 */
-    0x00000007,                         /* 3 - 00000111 */
-    0x0000000F,                         /* 4 - 10000111 */
-    0x0000001F,                         /* 5 - 00011111 */
-    0x0000003F,                         /* 6 - 00111111 */
-    0x0000007F,                         /* 7 - 01111111 */
-    0x000000FF                          /* 8 - 11111111 */
-#endif /* (BITMAP_BIT_ORDER == MSBFirst) */
-#endif /* PGSZ */
-};
-#endif /* PSZ == 8 */
-
-#if PSZ == 16
-PixelGroup QuartetBitsTable[] = {
-#if PGSZ == 32
-#if (BITMAP_BIT_ORDER == MSBFirst)
-    0x00000000,                         /* 0 - 00 */
-    0x00000002,                         /* 1 - 10 */
-    0x00000003,                         /* 2 - 11 */
-#else /* (BITMAP_BIT_ORDER == LSBFirst */
-    0x00000000,                         /* 0 - 00 */
-    0x00000001,                         /* 1 - 01 */
-    0x00000003,                         /* 2 - 11 */
-#endif /* (BITMAP_BIT_ORDER == MSBFirst) */
-#else /* PGSZ == 64 */
-#if (BITMAP_BIT_ORDER == MSBFirst)
-    0x00000000,                         /* 0 - 0000 */
-    0x00000008,                         /* 1 - 1000 */
-    0x0000000C,                         /* 2 - 1100 */
-    0x0000000E,                         /* 3 - 1110 */
-    0x0000000F,                         /* 4 - 1111 */
-#else /* (BITMAP_BIT_ORDER == LSBFirst */
-    0x00000000,                         /* 0 - 0000 */
-    0x00000001,                         /* 1 - 0001 */
-    0x00000003,                         /* 2 - 0011 */
-    0x00000007,                         /* 3 - 0111 */
-    0x0000000F,                         /* 4 - 1111 */
-#endif /* (BITMAP_BIT_ORDER == MSBFirst) */
-#endif /* PGSZ */
-};
-#endif /* PSZ == 16 */
-
-#if PSZ == 24
-PixelGroup QuartetBitsTable[] = {
-#if PGSZ == 32
-#if (BITMAP_BIT_ORDER == MSBFirst)
-    0x00000000,                         /* 0 - 0 */
-    0x00000001,                         /* 1 - 1 */
-#else /* (BITMAP_BIT_ORDER == LSBFirst */
-    0x00000000,                         /* 0 - 0 */
-    0x00000001,                         /* 1 - 1 */
-#endif /* (BITMAP_BIT_ORDER == MSBFirst) */
-#else /* PGSZ == 64 */
-#if (BITMAP_BIT_ORDER == MSBFirst)
-    0x00000000,                         /* 0 - 00 */
-    0x00000002,                         /* 1 - 10 */
-    0x00000003,                         /* 2 - 11*/
-#else /* (BITMAP_BIT_ORDER == LSBFirst */
-    0x00000000,                         /* 0 - 00 */
-    0x00000001,                         /* 1 - 01 */
-    0x00000003,                         /* 2 - 11 */
-#endif /* (BITMAP_BIT_ORDER == MSBFirst) */
-#endif /* PGSZ */
-};
-#endif /* PSZ == 24 */
-
-#if PSZ == 32
-PixelGroup QuartetBitsTable[] = {
-#if PGSZ == 32
-#if (BITMAP_BIT_ORDER == MSBFirst)
-    0x00000000,                         /* 0 - 0 */
-    0x00000001,                         /* 1 - 1 */
-#else /* (BITMAP_BIT_ORDER == LSBFirst */
-    0x00000000,                         /* 0 - 0 */
-    0x00000001,                         /* 1 - 1 */
-#endif /* (BITMAP_BIT_ORDER == MSBFirst) */
-#else /* PGSZ == 64 */
-#if (BITMAP_BIT_ORDER == MSBFirst)
-    0x00000000,                         /* 0 - 00 */
-    0x00000002,                         /* 1 - 10 */
-    0x00000003,                         /* 2 - 11*/
-#else /* (BITMAP_BIT_ORDER == LSBFirst */
-    0x00000000,                         /* 0 - 00 */
-    0x00000001,                         /* 1 - 01 */
-    0x00000003,                         /* 2 - 11 */
-#endif /* (BITMAP_BIT_ORDER == MSBFirst) */
-#endif /* PGSZ */
-};
-#endif /* PSZ == 32 */
-
-/*
- * QuartetPixelMaskTable is used by getstipplepixels to get a pixel mask
- * corresponding to a quartet of bits.  Note: the bit/byte order dependency
- * is handled by QuartetBitsTable above.
- */
-#if PSZ == 4
-#if PGSZ == 32
-PixelGroup QuartetPixelMaskTable[] = {
-    0x00000000,
-    0x0000000F,
-    0x000000F0,
-    0x000000FF,
-    0x00000F00,
-    0x00000F0F,
-    0x00000FF0,
-    0x00000FFF,
-    0x0000F000,
-    0x0000F00F,
-    0x0000F0F0,
-    0x0000F0FF,
-    0x0000FF00,
-    0x0000FF0F,
-    0x0000FFF0,
-    0x0000FFFF,
-    0x000F0000,
-    0x000F000F,
-    0x000F00F0,
-    0x000F00FF,
-    0x000F0F00,
-    0x000F0F0F,
-    0x000F0FF0,
-    0x000F0FFF,
-    0x000FF000,
-    0x000FF00F,
-    0x000FF0F0,
-    0x000FF0FF,
-    0x000FFF00,
-    0x000FFF0F,
-    0x000FFFF0,
-    0x000FFFFF,
-    0x00F00000,
-    0x00F0000F,
-    0x00F000F0,
-    0x00F000FF,
-    0x00F00F00,
-    0x00F00F0F,
-    0x00F00FF0,
-    0x00F00FFF,
-    0x00F0F000,
-    0x00F0F00F,
-    0x00F0F0F0,
-    0x00F0F0FF,
-    0x00F0FF00,
-    0x00F0FF0F,
-    0x00F0FFF0,
-    0x00F0FFFF,
-    0x00FF0000,
-    0x00FF000F,
-    0x00FF00F0,
-    0x00FF00FF,
-    0x00FF0F00,
-    0x00FF0F0F,
-    0x00FF0FF0,
-    0x00FF0FFF,
-    0x00FFF000,
-    0x00FFF00F,
-    0x00FFF0F0,
-    0x00FFF0FF,
-    0x00FFFF00,
-    0x00FFFF0F,
-    0x00FFFFF0,
-    0x00FFFFFF,
-    0x0F000000,
-    0x0F00000F,
-    0x0F0000F0,
-    0x0F0000FF,
-    0x0F000F00,
-    0x0F000F0F,
-    0x0F000FF0,
-    0x0F000FFF,
-    0x0F00F000,
-    0x0F00F00F,
-    0x0F00F0F0,
-    0x0F00F0FF,
-    0x0F00FF00,
-    0x0F00FF0F,
-    0x0F00FFF0,
-    0x0F00FFFF,
-    0x0F0F0000,
-    0x0F0F000F,
-    0x0F0F00F0,
-    0x0F0F00FF,
-    0x0F0F0F00,
-    0x0F0F0F0F,
-    0x0F0F0FF0,
-    0x0F0F0FFF,
-    0x0F0FF000,
-    0x0F0FF00F,
-    0x0F0FF0F0,
-    0x0F0FF0FF,
-    0x0F0FFF00,
-    0x0F0FFF0F,
-    0x0F0FFFF0,
-    0x0F0FFFFF,
-    0x0FF00000,
-    0x0FF0000F,
-    0x0FF000F0,
-    0x0FF000FF,
-    0x0FF00F00,
-    0x0FF00F0F,
-    0x0FF00FF0,
-    0x0FF00FFF,
-    0x0FF0F000,
-    0x0FF0F00F,
-    0x0FF0F0F0,
-    0x0FF0F0FF,
-    0x0FF0FF00,
-    0x0FF0FF0F,
-    0x0FF0FFF0,
-    0x0FF0FFFF,
-    0x0FFF0000,
-    0x0FFF000F,
-    0x0FFF00F0,
-    0x0FFF00FF,
-    0x0FFF0F00,
-    0x0FFF0F0F,
-    0x0FFF0FF0,
-    0x0FFF0FFF,
-    0x0FFFF000,
-    0x0FFFF00F,
-    0x0FFFF0F0,
-    0x0FFFF0FF,
-    0x0FFFFF00,
-    0x0FFFFF0F,
-    0x0FFFFFF0,
-    0x0FFFFFFF,
-    0xF0000000,
-    0xF000000F,
-    0xF00000F0,
-    0xF00000FF,
-    0xF0000F00,
-    0xF0000F0F,
-    0xF0000FF0,
-    0xF0000FFF,
-    0xF000F000,
-    0xF000F00F,
-    0xF000F0F0,
-    0xF000F0FF,
-    0xF000FF00,
-    0xF000FF0F,
-    0xF000FFF0,
-    0xF000FFFF,
-    0xF00F0000,
-    0xF00F000F,
-    0xF00F00F0,
-    0xF00F00FF,
-    0xF00F0F00,
-    0xF00F0F0F,
-    0xF00F0FF0,
-    0xF00F0FFF,
-    0xF00FF000,
-    0xF00FF00F,
-    0xF00FF0F0,
-    0xF00FF0FF,
-    0xF00FFF00,
-    0xF00FFF0F,
-    0xF00FFFF0,
-    0xF00FFFFF,
-    0xF0F00000,
-    0xF0F0000F,
-    0xF0F000F0,
-    0xF0F000FF,
-    0xF0F00F00,
-    0xF0F00F0F,
-    0xF0F00FF0,
-    0xF0F00FFF,
-    0xF0F0F000,
-    0xF0F0F00F,
-    0xF0F0F0F0,
-    0xF0F0F0FF,
-    0xF0F0FF00,
-    0xF0F0FF0F,
-    0xF0F0FFF0,
-    0xF0F0FFFF,
-    0xF0FF0000,
-    0xF0FF000F,
-    0xF0FF00F0,
-    0xF0FF00FF,
-    0xF0FF0F00,
-    0xF0FF0F0F,
-    0xF0FF0FF0,
-    0xF0FF0FFF,
-    0xF0FFF000,
-    0xF0FFF00F,
-    0xF0FFF0F0,
-    0xF0FFF0FF,
-    0xF0FFFF00,
-    0xF0FFFF0F,
-    0xF0FFFFF0,
-    0xF0FFFFFF,
-    0xFF000000,
-    0xFF00000F,
-    0xFF0000F0,
-    0xFF0000FF,
-    0xFF000F00,
-    0xFF000F0F,
-    0xFF000FF0,
-    0xFF000FFF,
-    0xFF00F000,
-    0xFF00F00F,
-    0xFF00F0F0,
-    0xFF00F0FF,
-    0xFF00FF00,
-    0xFF00FF0F,
-    0xFF00FFF0,
-    0xFF00FFFF,
-    0xFF0F0000,
-    0xFF0F000F,
-    0xFF0F00F0,
-    0xFF0F00FF,
-    0xFF0F0F00,
-    0xFF0F0F0F,
-    0xFF0F0FF0,
-    0xFF0F0FFF,
-    0xFF0FF000,
-    0xFF0FF00F,
-    0xFF0FF0F0,
-    0xFF0FF0FF,
-    0xFF0FFF00,
-    0xFF0FFF0F,
-    0xFF0FFFF0,
-    0xFF0FFFFF,
-    0xFFF00000,
-    0xFFF0000F,
-    0xFFF000F0,
-    0xFFF000FF,
-    0xFFF00F00,
-    0xFFF00F0F,
-    0xFFF00FF0,
-    0xFFF00FFF,
-    0xFFF0F000,
-    0xFFF0F00F,
-    0xFFF0F0F0,
-    0xFFF0F0FF,
-    0xFFF0FF00,
-    0xFFF0FF0F,
-    0xFFF0FFF0,
-    0xFFF0FFFF,
-    0xFFFF0000,
-    0xFFFF000F,
-    0xFFFF00F0,
-    0xFFFF00FF,
-    0xFFFF0F00,
-    0xFFFF0F0F,
-    0xFFFF0FF0,
-    0xFFFF0FFF,
-    0xFFFFF000,
-    0xFFFFF00F,
-    0xFFFFF0F0,
-    0xFFFFF0FF,
-    0xFFFFFF00,
-    0xFFFFFF0F,
-    0xFFFFFFF0,
-    0xFFFFFFFF,
-};
-#else /* PGSZ == 64 */
-No QuartetPixelMaskTable for psz=PSZ
-this would be a 64K entry table, a bit much I think.
-Try breaking things in two:
-mask = table[index&0xff00]<<32 | table[index&0xff]
-#endif /* PGSZ */
-#endif /* PSZ == 4 */
-
-#if PSZ == 8
-PixelGroup QuartetPixelMaskTable[] = {
-#if PGSZ == 32
-    0x00000000,
-    0x000000FF,
-    0x0000FF00,
-    0x0000FFFF,
-    0x00FF0000,
-    0x00FF00FF,
-    0x00FFFF00,
-    0x00FFFFFF,
-    0xFF000000,
-    0xFF0000FF,
-    0xFF00FF00,
-    0xFF00FFFF,
-    0xFFFF0000,
-    0xFFFF00FF,
-    0xFFFFFF00,
-    0xFFFFFFFF
-#else /* PGSZ == 64 */
-    0x0000000000000000,    0x00000000000000FF,
-    0x000000000000FF00,    0x000000000000FFFF,
-    0x0000000000FF0000,    0x0000000000FF00FF,
-    0x0000000000FFFF00,    0x0000000000FFFFFF,
-    0x00000000FF000000,    0x00000000FF0000FF,
-    0x00000000FF00FF00,    0x00000000FF00FFFF,
-    0x00000000FFFF0000,    0x00000000FFFF00FF,
-    0x00000000FFFFFF00,    0x00000000FFFFFFFF,
-    0x000000FF00000000,    0x000000FF000000FF,
-    0x000000FF0000FF00,    0x000000FF0000FFFF,
-    0x000000FF00FF0000,    0x000000FF00FF00FF,
-    0x000000FF00FFFF00,    0x000000FF00FFFFFF,
-    0x000000FFFF000000,    0x000000FFFF0000FF,
-    0x000000FFFF00FF00,    0x000000FFFF00FFFF,
-    0x000000FFFFFF0000,    0x000000FFFFFF00FF,
-    0x000000FFFFFFFF00,    0x000000FFFFFFFFFF,
-    0x0000FF0000000000,    0x0000FF00000000FF,
-    0x0000FF000000FF00,    0x0000FF000000FFFF,
-    0x0000FF0000FF0000,    0x0000FF0000FF00FF,
-    0x0000FF0000FFFF00,    0x0000FF0000FFFFFF,
-    0x0000FF00FF000000,    0x0000FF00FF0000FF,
-    0x0000FF00FF00FF00,    0x0000FF00FF00FFFF,
-    0x0000FF00FFFF0000,    0x0000FF00FFFF00FF,
-    0x0000FF00FFFFFF00,    0x0000FF00FFFFFFFF,
-    0x0000FFFF00000000,    0x0000FFFF000000FF,
-    0x0000FFFF0000FF00,    0x0000FFFF0000FFFF,
-    0x0000FFFF00FF0000,    0x0000FFFF00FF00FF,
-    0x0000FFFF00FFFF00,    0x0000FFFF00FFFFFF,
-    0x0000FFFFFF000000,    0x0000FFFFFF0000FF,
-    0x0000FFFFFF00FF00,    0x0000FFFFFF00FFFF,
-    0x0000FFFFFFFF0000,    0x0000FFFFFFFF00FF,
-    0x0000FFFFFFFFFF00,    0x0000FFFFFFFFFFFF,
-    0x00FF000000000000,    0x00FF0000000000FF,
-    0x00FF00000000FF00,    0x00FF00000000FFFF,
-    0x00FF000000FF0000,    0x00FF000000FF00FF,
-    0x00FF000000FFFF00,    0x00FF000000FFFFFF,
-    0x00FF0000FF000000,    0x00FF0000FF0000FF,
-    0x00FF0000FF00FF00,    0x00FF0000FF00FFFF,
-    0x00FF0000FFFF0000,    0x00FF0000FFFF00FF,
-    0x00FF0000FFFFFF00,    0x00FF0000FFFFFFFF,
-    0x00FF00FF00000000,    0x00FF00FF000000FF,
-    0x00FF00FF0000FF00,    0x00FF00FF0000FFFF,
-    0x00FF00FF00FF0000,    0x00FF00FF00FF00FF,
-    0x00FF00FF00FFFF00,    0x00FF00FF00FFFFFF,
-    0x00FF00FFFF000000,    0x00FF00FFFF0000FF,
-    0x00FF00FFFF00FF00,    0x00FF00FFFF00FFFF,
-    0x00FF00FFFFFF0000,    0x00FF00FFFFFF00FF,
-    0x00FF00FFFFFFFF00,    0x00FF00FFFFFFFFFF,
-    0x00FFFF0000000000,    0x00FFFF00000000FF,
-    0x00FFFF000000FF00,    0x00FFFF000000FFFF,
-    0x00FFFF0000FF0000,    0x00FFFF0000FF00FF,
-    0x00FFFF0000FFFF00,    0x00FFFF0000FFFFFF,
-    0x00FFFF00FF000000,    0x00FFFF00FF0000FF,
-    0x00FFFF00FF00FF00,    0x00FFFF00FF00FFFF,
-    0x00FFFF00FFFF0000,    0x00FFFF00FFFF00FF,
-    0x00FFFF00FFFFFF00,    0x00FFFF00FFFFFFFF,
-    0x00FFFFFF00000000,    0x00FFFFFF000000FF,
-    0x00FFFFFF0000FF00,    0x00FFFFFF0000FFFF,
-    0x00FFFFFF00FF0000,    0x00FFFFFF00FF00FF,
-    0x00FFFFFF00FFFF00,    0x00FFFFFF00FFFFFF,
-    0x00FFFFFFFF000000,    0x00FFFFFFFF0000FF,
-    0x00FFFFFFFF00FF00,    0x00FFFFFFFF00FFFF,
-    0x00FFFFFFFFFF0000,    0x00FFFFFFFFFF00FF,
-    0x00FFFFFFFFFFFF00,    0x00FFFFFFFFFFFFFF,
-    0xFF00000000000000,    0xFF000000000000FF,
-    0xFF0000000000FF00,    0xFF0000000000FFFF,
-    0xFF00000000FF0000,    0xFF00000000FF00FF,
-    0xFF00000000FFFF00,    0xFF00000000FFFFFF,
-    0xFF000000FF000000,    0xFF000000FF0000FF,
-    0xFF000000FF00FF00,    0xFF000000FF00FFFF,
-    0xFF000000FFFF0000,    0xFF000000FFFF00FF,
-    0xFF000000FFFFFF00,    0xFF000000FFFFFFFF,
-    0xFF0000FF00000000,    0xFF0000FF000000FF,
-    0xFF0000FF0000FF00,    0xFF0000FF0000FFFF,
-    0xFF0000FF00FF0000,    0xFF0000FF00FF00FF,
-    0xFF0000FF00FFFF00,    0xFF0000FF00FFFFFF,
-    0xFF0000FFFF000000,    0xFF0000FFFF0000FF,
-    0xFF0000FFFF00FF00,    0xFF0000FFFF00FFFF,
-    0xFF0000FFFFFF0000,    0xFF0000FFFFFF00FF,
-    0xFF0000FFFFFFFF00,    0xFF0000FFFFFFFFFF,
-    0xFF00FF0000000000,    0xFF00FF00000000FF,
-    0xFF00FF000000FF00,    0xFF00FF000000FFFF,
-    0xFF00FF0000FF0000,    0xFF00FF0000FF00FF,
-    0xFF00FF0000FFFF00,    0xFF00FF0000FFFFFF,
-    0xFF00FF00FF000000,    0xFF00FF00FF0000FF,
-    0xFF00FF00FF00FF00,    0xFF00FF00FF00FFFF,
-    0xFF00FF00FFFF0000,    0xFF00FF00FFFF00FF,
-    0xFF00FF00FFFFFF00,    0xFF00FF00FFFFFFFF,
-    0xFF00FFFF00000000,    0xFF00FFFF000000FF,
-    0xFF00FFFF0000FF00,    0xFF00FFFF0000FFFF,
-    0xFF00FFFF00FF0000,    0xFF00FFFF00FF00FF,
-    0xFF00FFFF00FFFF00,    0xFF00FFFF00FFFFFF,
-    0xFF00FFFFFF000000,    0xFF00FFFFFF0000FF,
-    0xFF00FFFFFF00FF00,    0xFF00FFFFFF00FFFF,
-    0xFF00FFFFFFFF0000,    0xFF00FFFFFFFF00FF,
-    0xFF00FFFFFFFFFF00,    0xFF00FFFFFFFFFFFF,
-    0xFFFF000000000000,    0xFFFF0000000000FF,
-    0xFFFF00000000FF00,    0xFFFF00000000FFFF,
-    0xFFFF000000FF0000,    0xFFFF000000FF00FF,
-    0xFFFF000000FFFF00,    0xFFFF000000FFFFFF,
-    0xFFFF0000FF000000,    0xFFFF0000FF0000FF,
-    0xFFFF0000FF00FF00,    0xFFFF0000FF00FFFF,
-    0xFFFF0000FFFF0000,    0xFFFF0000FFFF00FF,
-    0xFFFF0000FFFFFF00,    0xFFFF0000FFFFFFFF,
-    0xFFFF00FF00000000,    0xFFFF00FF000000FF,
-    0xFFFF00FF0000FF00,    0xFFFF00FF0000FFFF,
-    0xFFFF00FF00FF0000,    0xFFFF00FF00FF00FF,
-    0xFFFF00FF00FFFF00,    0xFFFF00FF00FFFFFF,
-    0xFFFF00FFFF000000,    0xFFFF00FFFF0000FF,
-    0xFFFF00FFFF00FF00,    0xFFFF00FFFF00FFFF,
-    0xFFFF00FFFFFF0000,    0xFFFF00FFFFFF00FF,
-    0xFFFF00FFFFFFFF00,    0xFFFF00FFFFFFFFFF,
-    0xFFFFFF0000000000,    0xFFFFFF00000000FF,
-    0xFFFFFF000000FF00,    0xFFFFFF000000FFFF,
-    0xFFFFFF0000FF0000,    0xFFFFFF0000FF00FF,
-    0xFFFFFF0000FFFF00,    0xFFFFFF0000FFFFFF,
-    0xFFFFFF00FF000000,    0xFFFFFF00FF0000FF,
-    0xFFFFFF00FF00FF00,    0xFFFFFF00FF00FFFF,
-    0xFFFFFF00FFFF0000,    0xFFFFFF00FFFF00FF,
-    0xFFFFFF00FFFFFF00,    0xFFFFFF00FFFFFFFF,
-    0xFFFFFFFF00000000,    0xFFFFFFFF000000FF,
-    0xFFFFFFFF0000FF00,    0xFFFFFFFF0000FFFF,
-    0xFFFFFFFF00FF0000,    0xFFFFFFFF00FF00FF,
-    0xFFFFFFFF00FFFF00,    0xFFFFFFFF00FFFFFF,
-    0xFFFFFFFFFF000000,    0xFFFFFFFFFF0000FF,
-    0xFFFFFFFFFF00FF00,    0xFFFFFFFFFF00FFFF,
-    0xFFFFFFFFFFFF0000,    0xFFFFFFFFFFFF00FF,
-    0xFFFFFFFFFFFFFF00,    0xFFFFFFFFFFFFFFFF,
-#endif /* PGSZ */
-};
-#endif /* PSZ == 8 */
-
-#if PSZ == 16
-PixelGroup QuartetPixelMaskTable[] = {
-#if PGSZ == 32
-    0x00000000,
-    0x0000FFFF,
-    0xFFFF0000,
-    0xFFFFFFFF,
-#else /* PGSZ == 64 */
-    0x0000000000000000,    0x000000000000FFFF,
-    0x00000000FFFF0000,    0x00000000FFFFFFFF,
-    0x0000FFFF00000000,    0x0000FFFF0000FFFF,
-    0x0000FFFFFFFF0000,    0x0000FFFFFFFFFFFF,
-    0xFFFF000000000000,    0xFFFF00000000FFFF,
-    0xFFFF0000FFFF0000,    0xFFFF0000FFFFFFFF,
-    0xFFFFFFFF00000000,    0xFFFFFFFF0000FFFF,
-    0xFFFFFFFFFFFF0000,    0xFFFFFFFFFFFFFFFF,
-#endif /* PGSZ */
-};
-#endif /* PSZ == 16 */
-
-#if PSZ == 24
-PixelGroup QuartetPixelMaskTable[] = {
-#if PGSZ == 32
-/* Four pixels consist three pixel groups....*/
-    0x00000000, 0x00FFFFFF, /*0x00000000, *//*0*/
-/*    0x00000000, 0x00000000, 0x00000000,*/ /*0*/
-/*    0x00FFFFFF, 0x00000000, 0x00000000,*/ /*1*/
-/*    0xFF000000, 0x0000FFFF, 0x00000000,*/ /*2*/
-/*    0xFFFFFFFF, 0x0000FFFF, 0x00000000,*/ /*3*/
-/*    0x00000000, 0xFFFF0000, 0x000000FF,*/ /*4*/
-/*    0x00FFFFFF, 0xFFFF0000, 0x000000FF,*/ /*5*/
-/*    0xFF000000, 0xFFFFFFFF, 0x000000FF,*/ /*6*/
-/*    0xFFFFFFFF, 0xFFFFFFFF, 0x000000FF,*/ /*7*/
-/*    0x00000000, 0x00000000, 0xFFFFFF00,*/ /*8*/
-/*    0x00FFFFFF, 0x00000000, 0xFFFFFF00,*/ /*9*/
-/*    0xFF000000, 0x0000FFFF, 0xFFFFFF00,*/ /*10*/
-/*    0xFFFFFFFF, 0x0000FFFF, 0xFFFFFF00,*/ /*11*/
-/*    0x00000000, 0xFFFF0000, 0xFFFFFFFF,*/ /*12*/
-/*    0x00FFFFFF, 0xFFFF0000, 0xFFFFFFFF,*/ /*13*/
-/*    0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF,*/ /*14*/
-/*    0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,*/ /*15*/
-#else /* PGSZ == 64 */
-    0x0000000000000000,    0x0000000000FFFFFF,
-    0x0000FFFFFF000000,    0xFFFFFFFFFFFFFFFF
-#endif /* PGSZ */
-};
-#endif /* PSZ == 24 */
-
-#if PSZ == 32
-PixelGroup QuartetPixelMaskTable[] = {
-#if PGSZ == 32
-    0x00000000,
-    0xFFFFFFFF,
-#else /* PGSZ == 64 */
-    0x0000000000000000,
-    0x00000000FFFFFFFF,
-    0xFFFFFFFF00000000,
-    0xFFFFFFFFFFFFFFFF
-#endif /* PGSZ */
-};
-#endif /* PSZ == 32 */
-
-#if PSZ == 24
-int cfb24Shift[] = 
-#if	(BITMAP_BIT_ORDER == MSBFirst)
-{8,0,16,16,8,24,0,0};
-#else	/* (BITMAP_BIT_ORDER == LSBFirst) */
-{0,0,24,8,16,16,8,0};
-#endif	/* (BITMAP_BIT_ORDER == MSBFirst) */
-#endif
diff --git a/cfb/cfbmskbits.h b/cfb/cfbmskbits.h
deleted file mode 100644
index 5ee9125..0000000
--- a/cfb/cfbmskbits.h
+++ /dev/null
@@ -1,854 +0,0 @@
-/************************************************************
-Copyright 1987 by Sun Microsystems, Inc. Mountain View, CA.
-
-                    All Rights Reserved
-
-Permission  to  use,  copy,  modify,  and  distribute   this
-software  and  its documentation for any purpose and without
-fee is hereby granted, provided that the above copyright no-
-tice  appear  in all copies and that both that copyright no-
-tice and this permission notice appear in  supporting  docu-
-mentation,  and  that the names of Sun or The Open Group
-not be used in advertising or publicity pertaining to 
-distribution  of  the software  without specific prior 
-written permission. Sun and The Open Group make no 
-representations about the suitability of this software for 
-any purpose. It is provided "as is" without any express or 
-implied warranty.
-
-SUN DISCLAIMS ALL WARRANTIES WITH REGARD TO  THIS  SOFTWARE,
-INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
-NESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SUN BE  LI-
-ABLE  FOR  ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,  DATA  OR
-PROFITS,  WHETHER  IN  AN  ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
-THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-********************************************************/
-
-/* Optimizations for PSZ == 32 added by Kyle Marvin (marvin at vitec.com) */
-
-#include	<X11/X.h>
-#include	<X11/Xmd.h>
-#include	"servermd.h"
-#include	"compiler.h"
-
-/*
- * ==========================================================================
- * Converted from mfb to support memory-mapped color framebuffer by smarks at sun, 
- * April-May 1987.
- *
- * The way I did the conversion was to consider each longword as an
- * array of four bytes instead of an array of 32 one-bit pixels.  So
- * getbits() and putbits() retain much the same calling sequence, but
- * they move bytes around instead of bits.  Of course, this entails the
- * removal of all of the one-bit-pixel dependencies from the other
- * files, but the major bit-hacking stuff should be covered here.
- *
- * I've created some new macros that make it easier to understand what's 
- * going on in the pixel calculations, and that make it easier to change the 
- * pixel size.
- *
- * name	    explanation
- * ----	    -----------
- * PSZ	    pixel size (in bits)
- * PGSZ     pixel group size (in bits)
- * PGSZB    pixel group size (in bytes)
- * PGSZBMSK mask with lowest PGSZB bits set to 1
- * PPW	    pixels per word (pixels per pixel group)
- * PPWMSK   mask with lowest PPW bits set to 1
- * PLST	    index of last pixel in a word (should be PPW-1)
- * PIM	    pixel index mask (index within a pixel group)
- * PWSH	    pixel-to-word shift (should be log2(PPW))
- * PMSK	    mask with lowest PSZ bits set to 1
- *
- *
- * Here are some sample values.  In the notation cfbA,B: A is PSZ, and
- * B is PGSZB.  All the other values are derived from these
- * two.  This table does not show all combinations!
- *
- * name	    cfb8,4    cfb24,4      cfb32,4    cfb8,8    cfb24,8    cfb32,8
- * ----	    ------    -------      ------     ------    ------     -------
- * PSZ	      8	        24	     32          8        24         32
- * PGSZ	     32         32           32         64        64         64
- * PGSZB      4          4            4          8         8          8
- * PGSZBMSK 0xF        0xF?         0xF        0xFF      0xFF       0xFF
- * PPW	      4	         1            1          8         2          2
- * PPWMSK   0xF        0x1          0x1        0xFF       0x3?       0x3    
- * PLST	      3	         0            0	         7         1          1
- * PIM	    0x3        0x0          0x0	       0x7       0x1?        0x1
- * PWSH	      2	         0            0	         3         1          1
- * PMSK	    0xFF      0xFFFFFF     0xFFFFFFFF 0xFF      0xFFFFFF   0xFFFFFFFF
- *
- *
- * I have also added a new macro, PFILL, that takes one pixel and
- * replicates it throughout a word.  This macro definition is dependent
- * upon pixel and word size; it doesn't use macros like PPW and so
- * forth.  Examples: for monochrome, PFILL(1) => 0xffffffff, PFILL(0) =>
- * 0x00000000.  For 8-bit color, PFILL(0x5d) => 0x5d5d5d5d.  This macro
- * is used primarily for replicating a plane mask into a word.
- *
- * Color framebuffers operations also support the notion of a plane
- * mask.  This mask determines which planes of the framebuffer can be
- * altered; the others are left unchanged.  I have added another
- * parameter to the putbits and putbitsrop macros that is the plane
- * mask.
- * ==========================================================================
- *
- * Keith Packard (keithp at suse.com)
- * 64bit code is no longer supported; it requires DIX support
- * for repadding images which significantly impacts performance
- */
-
-/*
- *  PSZ needs to be defined before we get here.  Usually it comes from a
- *  -DPSZ=foo on the compilation command line.
- */
-
-#ifndef PSZ
-#define PSZ 8
-#endif
-
-/*
- *  PixelGroup is the data type used to operate on groups of pixels.
- *  We typedef it here to CARD32 with the assumption that you
- *  want to manipulate 32 bits worth of pixels at a time as you can.  If CARD32
- *  is not appropriate for your server, define it to something else
- *  before including this file.  In this case you will also have to define
- *  PGSZB to the size in bytes of PixelGroup.
- */
-#ifndef PixelGroup
-#define PixelGroup CARD32
-#define PGSZB 4
-#endif /* PixelGroup */
-    
-#ifndef CfbBits
-#define CfbBits	CARD32
-#endif
-
-#define PGSZ	(PGSZB << 3)
-#define PPW	(PGSZ/PSZ)
-#define PLST	(PPW-1)
-#define PIM	PLST
-#define PMSK	(((PixelGroup)1 << PSZ) - 1)
-#define PPWMSK  (((PixelGroup)1 << PPW) - 1) /* instead of BITMSK */
-#define PGSZBMSK (((PixelGroup)1 << PGSZB) - 1)
-
-/*  set PWSH = log2(PPW) using brute force */
-
-#if PPW == 1
-#define PWSH 0
-#else
-#if PPW == 2
-#define PWSH 1
-#else
-#if PPW == 4
-#define PWSH 2
-#else
-#if PPW == 8
-#define PWSH 3
-#else
-#if PPW == 16
-#define PWSH 4
-#endif /* PPW == 16 */
-#endif /* PPW == 8 */
-#endif /* PPW == 4 */
-#endif /* PPW == 2 */
-#endif /* PPW == 1 */
-
-/*  Defining PIXEL_ADDR means that individual pixels are addressable by this
- *  machine (as type PixelType).  A possible CFB architecture which supported
- *  8-bits-per-pixel on a non byte-addressable machine would not have this
- *  defined.
- *
- *  Defining FOUR_BIT_CODE means that cfb knows how to stipple on this machine;
- *  eventually, stippling code for 16 and 32 bit devices should be written
- *  which would allow them to also use FOUR_BIT_CODE.  There isn't that
- *  much to do in those cases, but it would make them quite a bit faster.
- */
-
-#if PSZ == 8
-#define PIXEL_ADDR
-typedef CARD8 PixelType;
-#define FOUR_BIT_CODE
-#endif
-
-#if PSZ == 16
-#define PIXEL_ADDR
-typedef CARD16 PixelType;
-#endif
-
-#if PSZ == 24
-#undef PMSK
-#define PMSK	0xFFFFFF
-/*#undef PIM
-#define PIM 3*/
-#define PIXEL_ADDR
-typedef CARD32 PixelType;
-#endif
-
-#if PSZ == 32
-#undef PMSK
-#define PMSK	0xFFFFFFFF
-#define PIXEL_ADDR
-typedef CARD32 PixelType;
-#endif
-
-
-/* the following notes use the following conventions:
-SCREEN LEFT				SCREEN RIGHT
-in this file and maskbits.c, left and right refer to screen coordinates,
-NOT bit numbering in registers.
-
-cfbstarttab[n] 
-	pixels[0,n-1] = 0's	pixels[n,PPW-1] = 1's
-cfbendtab[n] =
-	pixels[0,n-1] = 1's	pixels[n,PPW-1] = 0's
-
-cfbstartpartial[], cfbendpartial[]
-	these are used as accelerators for doing putbits and masking out
-bits that are all contained between longword boudaries.  the extra
-256 bytes of data seems a small price to pay -- code is smaller,
-and narrow things (e.g. window borders) go faster.
-
-the names may seem misleading; they are derived not from which end
-of the word the bits are turned on, but at which end of a scanline
-the table tends to be used.
-
-look at the tables and macros to understand boundary conditions.
-(careful readers will note that starttab[n] = ~endtab[n] for n != 0)
-
------------------------------------------------------------------------
-these two macros depend on the screen's bit ordering.
-in both of them x is a screen position.  they are used to
-combine bits collected from multiple longwords into a
-single destination longword, and to unpack a single
-source longword into multiple destinations.
-
-SCRLEFT(dst, x)
-	takes dst[x, PPW] and moves them to dst[0, PPW-x]
-	the contents of the rest of dst are 0 ONLY IF
-	dst is UNSIGNED.
-	is cast as an unsigned.
-	this is a right shift on the VAX, left shift on
-	Sun and pc-rt.
-
-SCRRIGHT(dst, x)
-	takes dst[0,x] and moves them to dst[PPW-x, PPW]
-	the contents of the rest of dst are 0 ONLY IF
-	dst is UNSIGNED.
-	this is a left shift on the VAX, right shift on
-	Sun and pc-rt.
-
-
-the remaining macros are cpu-independent; all bit order dependencies
-are built into the tables and the two macros above.
-
-maskbits(x, w, startmask, endmask, nlw)
-	for a span of width w starting at position x, returns
-a mask for ragged pixels at start, mask for ragged pixels at end,
-and the number of whole longwords between the ends.
-
-maskpartialbits(x, w, mask)
-	works like maskbits(), except all the pixels are in the
-	same longword (i.e. (x&0xPIM + w) <= PPW)
-
-mask32bits(x, w, startmask, endmask, nlw)
-	as maskbits, but does not calculate nlw.  it is used by
-	cfbGlyphBlt to put down glyphs <= PPW bits wide.
-
-getbits(psrc, x, w, dst)
-	starting at position x in psrc (x < PPW), collect w
-	pixels and put them in the screen left portion of dst.
-	psrc is a longword pointer.  this may span longword boundaries.
-	it special-cases fetching all w bits from one longword.
-
-	+--------+--------+		+--------+
-	|    | m |n|      |	==> 	| m |n|  |
-	+--------+--------+		+--------+
-	    x      x+w			0     w
-	psrc     psrc+1			dst
-			m = PPW - x
-			n = w - m
-
-	implementation:
-	get m pixels, move to screen-left of dst, zeroing rest of dst;
-	get n pixels from next word, move screen-right by m, zeroing
-		 lower m pixels of word.
-	OR the two things together.
-
-putbits(src, x, w, pdst, planemask)
-	starting at position x in pdst, put down the screen-leftmost
-	w bits of src.  pdst is a longword pointer.  this may
-	span longword boundaries.
-	it special-cases putting all w bits into the same longword.
-
-	+--------+			+--------+--------+
-	| m |n|  |		==>	|    | m |n|      |
-	+--------+			+--------+--------+
-	0     w				     x     x+w
-	dst				pdst     pdst+1
-			m = PPW - x
-			n = w - m
-
-	implementation:
-	get m pixels, shift screen-right by x, zero screen-leftmost x
-		pixels; zero rightmost m bits of *pdst and OR in stuff
-		from before the semicolon.
-	shift src screen-left by m, zero bits n-32;
-		zero leftmost n pixels of *(pdst+1) and OR in the
-		stuff from before the semicolon.
-
-putbitsrop(src, x, w, pdst, planemask, ROP)
-	like putbits but calls DoRop with the rasterop ROP (see cfb.h for
-	DoRop)
-
-getleftbits(psrc, w, dst)
-	get the leftmost w (w<=PPW) bits from *psrc and put them
-	in dst.  this is used by the cfbGlyphBlt code for glyphs
-	<=PPW bits wide.
-*/
-
-#if	(BITMAP_BIT_ORDER == MSBFirst)
-#define BitRight(lw,n)	((lw) >> (n))
-#define BitLeft(lw,n)	((lw) << (n))
-#else	/* (BITMAP_BIT_ORDER == LSBFirst) */
-#define BitRight(lw,n)	((lw) << (n))
-#define BitLeft(lw,n)	((lw) >> (n))
-#endif	/* (BITMAP_BIT_ORDER == MSBFirst) */
-
-#define SCRLEFT(lw, n)	BitLeft (lw, (n) * PSZ)
-#define SCRRIGHT(lw, n)	BitRight(lw, (n) * PSZ)
-
-/*
- * Note that the shift direction is independent of the byte ordering of the 
- * machine.  The following is portable code.
- */
-#if PPW == 16
-#define PFILL(p) ( ((p)&PMSK)          | \
-		   ((p)&PMSK) <<   PSZ | \
-		   ((p)&PMSK) << 2*PSZ | \
-		   ((p)&PMSK) << 3*PSZ | \
-		   ((p)&PMSK) << 4*PSZ | \
-		   ((p)&PMSK) << 5*PSZ | \
-		   ((p)&PMSK) << 6*PSZ | \
-		   ((p)&PMSK) << 7*PSZ | \
-		   ((p)&PMSK) << 8*PSZ | \
-		   ((p)&PMSK) << 9*PSZ | \
-		   ((p)&PMSK) << 10*PSZ | \
-		   ((p)&PMSK) << 11*PSZ | \
-		   ((p)&PMSK) << 12*PSZ | \
-		   ((p)&PMSK) << 13*PSZ | \
-		   ((p)&PMSK) << 14*PSZ | \
-		   ((p)&PMSK) << 15*PSZ ) 
-#define PFILL2(p, pf) { \
-    pf = (p) & PMSK; \
-    pf |= (pf << PSZ); \
-    pf |= (pf << 2*PSZ); \
-    pf |= (pf << 4*PSZ); \
-    pf |= (pf << 8*PSZ); \
-}
-#endif /* PPW == 16 */
-#if PPW == 8
-#define PFILL(p) ( ((p)&PMSK)          | \
-		   ((p)&PMSK) <<   PSZ | \
-		   ((p)&PMSK) << 2*PSZ | \
-		   ((p)&PMSK) << 3*PSZ | \
-		   ((p)&PMSK) << 4*PSZ | \
-		   ((p)&PMSK) << 5*PSZ | \
-		   ((p)&PMSK) << 6*PSZ | \
-		   ((p)&PMSK) << 7*PSZ )
-#define PFILL2(p, pf) { \
-    pf = (p) & PMSK; \
-    pf |= (pf << PSZ); \
-    pf |= (pf << 2*PSZ); \
-    pf |= (pf << 4*PSZ); \
-}
-#endif
-#if PPW == 4
-#define PFILL(p) ( ((p)&PMSK)          | \
-		   ((p)&PMSK) <<   PSZ | \
-		   ((p)&PMSK) << 2*PSZ | \
-		   ((p)&PMSK) << 3*PSZ )
-#define PFILL2(p, pf) { \
-    pf = (p) & PMSK; \
-    pf |= (pf << PSZ); \
-    pf |= (pf << 2*PSZ); \
-}
-#endif
-#if PPW == 2
-#define PFILL(p) ( ((p)&PMSK)          | \
-		   ((p)&PMSK) <<   PSZ )
-#define PFILL2(p, pf) { \
-    pf = (p) & PMSK; \
-    pf |= (pf << PSZ); \
-}
-#endif
-#if PPW == 1
-#define PFILL(p)	(p)
-#define PFILL2(p,pf)	(pf = (p))
-#endif
-
-/*
- * Reduced raster op - using precomputed values, perform the above
- * in three instructions
- */
-
-#define DoRRop(dst, and, xor)	(((dst) & (and)) ^ (xor))
-
-#define DoMaskRRop(dst, and, xor, mask) \
-    (((dst) & ((and) | ~(mask))) ^ (xor & mask))
-
-#if PSZ != 32 || PPW != 1
-
-# if (PSZ == 24 && PPW == 1)
-#define maskbits(x, w, startmask, endmask, nlw) {\
-    startmask = cfbstarttab[(x)&3]; \
-    endmask = cfbendtab[((x)+(w)) & 3]; \
-    nlw = ((((x)+(w))*3)>>2) - (((x)*3 +3)>>2); \
-}
-
-#define mask32bits(x, w, startmask, endmask) \
-    startmask = cfbstarttab[(x)&3]; \
-    endmask = cfbendtab[((x)+(w)) & 3];
-
-#define maskpartialbits(x, w, mask) \
-    mask = cfbstartpartial[(x) & 3] & cfbendpartial[((x)+(w)) & 3];
-
-#define maskbits24(x, w, startmask, endmask, nlw) \
-    startmask = cfbstarttab24[(x) & 3]; \
-    endmask = cfbendtab24[((x)+(w)) & 3]; \
-    if (startmask){ \
-	nlw = (((w) - (4 - ((x) & 3))) >> 2); \
-    } else { \
-	nlw = (w) >> 2; \
-    }
-
-#define getbits24(psrc, dst, index) {\
-    register int idx; \
-    switch(idx = ((index)&3)<<1){ \
-    	case 0: \
-		dst = (*(psrc) &cfbmask[idx]); \
-		break; \
-    	case 6: \
-		dst = BitLeft((*(psrc) &cfbmask[idx]), cfb24Shift[idx]); \
-		break; \
-	default: \
-		dst = BitLeft((*(psrc) &cfbmask[idx]), cfb24Shift[idx]) | \
-		BitRight(((*((psrc)+1)) &cfbmask[idx+1]), cfb24Shift[idx+1]); \
-	}; \
-}
-
-#define putbits24(src, w, pdst, planemask, index) {\
-    register PixelGroup dstpixel; \
-    register unsigned int idx; \
-    switch(idx = ((index)&3)<<1){ \
-    	case 0: \
-		dstpixel = (*(pdst) &cfbmask[idx]); \
-		break; \
-    	case 6: \
-		dstpixel = BitLeft((*(pdst) &cfbmask[idx]), cfb24Shift[idx]); \
-		break; \
-	default: \
-		dstpixel = BitLeft((*(pdst) &cfbmask[idx]), cfb24Shift[idx])| \
-		BitRight(((*((pdst)+1)) &cfbmask[idx+1]), cfb24Shift[idx+1]); \
-	}; \
-    dstpixel &= ~(planemask); \
-    dstpixel |= (src & planemask); \
-    *(pdst) &= cfbrmask[idx]; \
-    switch(idx){ \
-    	case 0: \
-		*(pdst) |=  (dstpixel & cfbmask[idx]); \
-		break; \
-    	case 2: \
-    	case 4: \
-		pdst++;idx++; \
-		*(pdst) = ((*(pdst))  & cfbrmask[idx]) | \
-				(BitLeft(dstpixel, cfb24Shift[idx]) & cfbmask[idx]); \
-		pdst--;idx--; \
-    	case 6: \
-		*(pdst) |=  (BitRight(dstpixel, cfb24Shift[idx]) & cfbmask[idx]); \
-		break; \
-	}; \
-}
-
-#define putbitsrop24(src, x, pdst, planemask, rop) \
-{ \
-    register PixelGroup t1, dstpixel; \
-    register unsigned int idx; \
-    switch(idx = (x)<<1){ \
-    	case 0: \
-		dstpixel = (*(pdst) &cfbmask[idx]); \
-		break; \
-    	case 6: \
-		dstpixel = BitLeft((*(pdst) &cfbmask[idx]), cfb24Shift[idx]); \
-		break; \
-	default: \
-		dstpixel = BitLeft((*(pdst) &cfbmask[idx]), cfb24Shift[idx])| \
-		BitRight(((*((pdst)+1)) &cfbmask[idx+1]), cfb24Shift[idx+1]); \
-	}; \
-    DoRop(t1, rop, (src), dstpixel); \
-    dstpixel &= ~planemask; \
-    dstpixel |= (t1 & planemask); \
-    *(pdst) &= cfbrmask[idx]; \
-    switch(idx){ \
-    	case 0: \
-		*(pdst) |= (dstpixel & cfbmask[idx]); \
-		break; \
-    	case 2: \
-    	case 4: \
-		*((pdst)+1) = ((*((pdst)+1))  & cfbrmask[idx+1]) | \
-				(BitLeft(dstpixel, cfb24Shift[idx+1]) & (cfbmask[idx+1])); \
-    	case 6: \
-		*(pdst) |= (BitRight(dstpixel, cfb24Shift[idx]) & cfbmask[idx]); \
-	}; \
-}
-# else  /* PSZ == 24 && PPW == 1 */
-#define maskbits(x, w, startmask, endmask, nlw) \
-    startmask = cfbstarttab[(x)&PIM]; \
-    endmask = cfbendtab[((x)+(w)) & PIM]; \
-    if (startmask) \
-	nlw = (((w) - (PPW - ((x)&PIM))) >> PWSH); \
-    else \
-	nlw = (w) >> PWSH;
-
-#define maskpartialbits(x, w, mask) \
-    mask = cfbstartpartial[(x) & PIM] & cfbendpartial[((x) + (w)) & PIM];
-
-#define mask32bits(x, w, startmask, endmask) \
-    startmask = cfbstarttab[(x)&PIM]; \
-    endmask = cfbendtab[((x)+(w)) & PIM];
-
-/* FIXME */
-#define maskbits24(x, w, startmask, endmask, nlw) \
-    abort()
-#define getbits24(psrc, dst, index) \
-    abort()
-#define putbits24(src, w, pdst, planemask, index) \
-    abort()
-#define putbitsrop24(src, x, pdst, planemask, rop) \
-    abort()
-
-#endif /* PSZ == 24 && PPW == 1 */
-
-#define getbits(psrc, x, w, dst) \
-if ( ((x) + (w)) <= PPW) \
-{ \
-    dst = SCRLEFT(*(psrc), (x)); \
-} \
-else \
-{ \
-    int m; \
-    m = PPW-(x); \
-    dst = (SCRLEFT(*(psrc), (x)) & cfbendtab[m]) | \
-	  (SCRRIGHT(*((psrc)+1), m) & cfbstarttab[m]); \
-}
-
-
-#define putbits(src, x, w, pdst, planemask) \
-if ( ((x)+(w)) <= PPW) \
-{ \
-    PixelGroup tmpmask; \
-    maskpartialbits((x), (w), tmpmask); \
-    tmpmask &= PFILL(planemask); \
-    *(pdst) = (*(pdst) & ~tmpmask) | (SCRRIGHT(src, x) & tmpmask); \
-} \
-else \
-{ \
-    unsigned int m; \
-    unsigned int n; \
-    PixelGroup pm = PFILL(planemask); \
-    m = PPW-(x); \
-    n = (w) - m; \
-    *(pdst) = (*(pdst) & (cfbendtab[x] | ~pm)) | \
-	(SCRRIGHT(src, x) & (cfbstarttab[x] & pm)); \
-    *((pdst)+1) = (*((pdst)+1) & (cfbstarttab[n] | ~pm)) | \
-	(SCRLEFT(src, m) & (cfbendtab[n] & pm)); \
-}
-#if defined(__GNUC__) && defined(mc68020)
-#undef getbits
-#define FASTGETBITS(psrc, x, w, dst) \
-    asm ("bfextu %3{%1:%2},%0" \
-	 : "=d" (dst) : "di" (x), "di" (w), "o" (*(char *)(psrc)))
-
-#define getbits(psrc,x,w,dst) \
-{ \
-    FASTGETBITS(psrc, (x) * PSZ, (w) * PSZ, dst); \
-    dst = SCRLEFT(dst,PPW-(w)); \
-}
-
-#define FASTPUTBITS(src, x, w, pdst) \
-    asm ("bfins %3,%0{%1:%2}" \
-	 : "=o" (*(char *)(pdst)) \
-	 : "di" (x), "di" (w), "d" (src), "0" (*(char *) (pdst)))
-
-#undef putbits
-#define putbits(src, x, w, pdst, planemask) \
-{ \
-    if (planemask != PMSK) { \
-        PixelGroup _m, _pm; \
-        FASTGETBITS(pdst, (x) * PSZ , (w) * PSZ, _m); \
-        PFILL2(planemask, _pm); \
-        _m &= (~_pm); \
-        _m |= (SCRRIGHT(src, PPW-(w)) & _pm); \
-        FASTPUTBITS(_m, (x) * PSZ, (w) * PSZ, pdst); \
-    } else { \
-        FASTPUTBITS(SCRRIGHT(src, PPW-(w)), (x) * PSZ, (w) * PSZ, pdst); \
-    } \
-}
-    
-
-#endif /* mc68020 */
-
-#define putbitsrop(src, x, w, pdst, planemask, rop) \
-if ( ((x)+(w)) <= PPW) \
-{ \
-    PixelGroup tmpmask; \
-    PixelGroup t1, t2; \
-    maskpartialbits((x), (w), tmpmask); \
-    PFILL2(planemask, t1); \
-    tmpmask &= t1; \
-    t1 = SCRRIGHT((src), (x)); \
-    DoRop(t2, rop, t1, *(pdst)); \
-    *(pdst) = (*(pdst) & ~tmpmask) | (t2 & tmpmask); \
-} \
-else \
-{ \
-    CfbBits m; \
-    CfbBits n; \
-    PixelGroup t1, t2; \
-    PixelGroup pm; \
-    PFILL2(planemask, pm); \
-    m = PPW-(x); \
-    n = (w) - m; \
-    t1 = SCRRIGHT((src), (x)); \
-    DoRop(t2, rop, t1, *(pdst)); \
-    *(pdst) = (*(pdst) & (cfbendtab[x] | ~pm)) | (t2 & (cfbstarttab[x] & pm));\
-    t1 = SCRLEFT((src), m); \
-    DoRop(t2, rop, t1, *((pdst) + 1)); \
-    *((pdst)+1) = (*((pdst)+1) & (cfbstarttab[n] | ~pm)) | \
-	(t2 & (cfbendtab[n] & pm)); \
-}
-
-#else /* PSZ == 32 && PPW == 1*/
-
-/*
- * These macros can be optimized for 32-bit pixels since there is no
- * need to worry about left/right edge masking.  These macros were
- * derived from the above using the following reductions:
- *
- *	- x & PIW = 0 	[since PIW = 0]
- *	- all masking tables are only indexed by 0  [ due to above ]
- *	- cfbstartab[0] and cfbendtab[0] = 0 	[ no left/right edge masks]
- *    - cfbstartpartial[0] and cfbendpartial[0] = ~0 [no partial pixel mask]
- *
- * Macro reduction based upon constants cannot be performed automatically
- *       by the compiler since it does not know the contents of the masking
- *       arrays in cfbmskbits.c.
- */
-#define maskbits(x, w, startmask, endmask, nlw) \
-    startmask = endmask = 0; \
-    nlw = (w);
-
-#define maskpartialbits(x, w, mask) \
-    mask = 0xFFFFFFFF;
-
-#define mask32bits(x, w, startmask, endmask) \
-    startmask = endmask = 0;
-
-/*
- * For 32-bit operations, getbits(), putbits(), and putbitsrop() 
- * will only be invoked with x = 0 and w = PPW (1).  The getbits() 
- * macro is only called within left/right edge logic, which doesn't
- * happen for 32-bit pixels.
- */
-#define getbits(psrc, x, w, dst) (dst) = *(psrc)
-
-#define putbits(src, x, w, pdst, planemask) \
-    *(pdst) = (*(pdst) & ~planemask) | (src & planemask);
-
-#define putbitsrop(src, x, w, pdst, planemask, rop) \
-{ \
-    PixelGroup t1; \
-    DoRop(t1, rop, (src), *(pdst)); \
-    *(pdst) = (*(pdst) & ~planemask) | (t1 & planemask); \
-}
-
-#endif /* PSZ != 32 */
-
-/*
- * Use these macros only when you're using the MergeRop stuff
- * in ../mfb/mergerop.h
- */
-
-/* useful only when not spanning destination longwords */
-#if PSZ == 24
-#define putbitsmropshort24(src,x,w,pdst,index) {\
-    PixelGroup   _tmpmask; \
-    PixelGroup   _t1; \
-    maskpartialbits ((x), (w), _tmpmask); \
-    _t1 = SCRRIGHT((src), (x)); \
-    DoMaskMergeRop24(_t1, pdst, _tmpmask, index); \
-}
-#endif
-#define putbitsmropshort(src,x,w,pdst) {\
-    PixelGroup   _tmpmask; \
-    PixelGroup   _t1; \
-    maskpartialbits ((x), (w), _tmpmask); \
-    _t1 = SCRRIGHT((src), (x)); \
-    *pdst = DoMaskMergeRop(_t1, *pdst, _tmpmask); \
-}
-
-/* useful only when spanning destination longwords */
-#define putbitsmroplong(src,x,w,pdst) { \
-    PixelGroup   _startmask, _endmask; \
-    int		    _m; \
-    PixelGroup   _t1; \
-    _m = PPW - (x); \
-    _startmask = cfbstarttab[x]; \
-    _endmask = cfbendtab[(w) - _m]; \
-    _t1 = SCRRIGHT((src), (x)); \
-    pdst[0] = DoMaskMergeRop(_t1,pdst[0],_startmask); \
-    _t1 = SCRLEFT ((src),_m); \
-    pdst[1] = DoMaskMergeRop(_t1,pdst[1],_endmask); \
-}
-
-#define putbitsmrop(src,x,w,pdst) \
-if ((x) + (w) <= PPW) {\
-    putbitsmropshort(src,x,w,pdst); \
-} else { \
-    putbitsmroplong(src,x,w,pdst); \
-}
-
-#if GETLEFTBITS_ALIGNMENT == 1
-#define getleftbits(psrc, w, dst)	dst = *((unsigned int *) psrc)
-#define getleftbits24(psrc, w, dst, idx){	\
-	regiseter int index; \
-	switch(index = ((idx)&3)<<1){ \
-	case 0: \
-	dst = (*((unsigned int *) psrc))&cfbmask[index]; \
-	break; \
-	case 2: \
-	case 4: \
-	dst = BitLeft(((*((unsigned int *) psrc))&cfbmask[index]), cfb24Shift[index]); \
-	dst |= BitRight(((*((unsigned int *) psrc)+1)&cfbmask[index]), cfb4Shift[index]); \
-	break; \
-	case 6: \
-	dst = BitLeft((*((unsigned int *) psrc)),cfb24Shift[index]); \
-	break; \
-	}; \
-}
-#endif /* GETLEFTBITS_ALIGNMENT == 1 */
-
-#define getglyphbits(psrc, x, w, dst) \
-{ \
-    dst = BitLeft((unsigned) *(psrc), (x)); \
-    if ( ((x) + (w)) > 32) \
-	dst |= (BitRight((unsigned) *((psrc)+1), 32-(x))); \
-}
-#if GETLEFTBITS_ALIGNMENT == 2
-#define getleftbits(psrc, w, dst) \
-    { \
-	if ( ((int)(psrc)) & 0x01 ) \
-		getglyphbits( ((unsigned int *)(((char *)(psrc))-1)), 8, (w), (dst) ); \
-	else \
-		dst = *((unsigned int *) psrc); \
-    }
-#endif /* GETLEFTBITS_ALIGNMENT == 2 */
-
-#if GETLEFTBITS_ALIGNMENT == 4
-#define getleftbits(psrc, w, dst) \
-    { \
-	int off, off_b; \
-	off_b = (off = ( ((int)(psrc)) & 0x03)) << 3; \
-	getglyphbits( \
-		(unsigned int *)( ((char *)(psrc)) - off), \
-		(off_b), (w), (dst) \
-	       ); \
-    }
-#endif /* GETLEFTBITS_ALIGNMENT == 4 */
-
-/*
- * getstipplepixels( psrcstip, x, w, ones, psrcpix, destpix )
- *
- * Converts bits to pixels in a reasonable way.  Takes w (1 <= w <= PPW)
- * bits from *psrcstip, starting at bit x; call this a quartet of bits.
- * Then, takes the pixels from *psrcpix corresponding to the one-bits (if
- * ones is TRUE) or the zero-bits (if ones is FALSE) of the quartet
- * and puts these pixels into destpix.
- *
- * Example:
- *
- *      getstipplepixels( &(0x08192A3B), 17, 4, 1, &(0x4C5D6E7F), dest )
- *
- * 0x08192A3B = 0000 1000 0001 1001 0010 1010 0011 1011
- *
- * This will take 4 bits starting at bit 17, so the quartet is 0x5 = 0101.
- * It will take pixels from 0x4C5D6E7F corresponding to the one-bits in this
- * quartet, so dest = 0x005D007F.
- *
- * XXX Works with both byte order.
- * XXX This works for all values of x and w within a doubleword.
- */
-#if (BITMAP_BIT_ORDER == MSBFirst)
-#define getstipplepixels( psrcstip, x, w, ones, psrcpix, destpix ) \
-{ \
-    PixelGroup q; \
-    int m; \
-    if ((m = ((x) - ((PPW*PSZ)-PPW))) > 0) { \
-        q = (*(psrcstip)) << m; \
-	if ( (x)+(w) > (PPW*PSZ) ) \
-	    q |= *((psrcstip)+1) >> ((PPW*PSZ)-m); \
-    } \
-    else \
-        q = (*(psrcstip)) >> -m; \
-    q = QuartetBitsTable[(w)] & ((ones) ? q : ~q); \
-    *(destpix) = (*(psrcpix)) & QuartetPixelMaskTable[q]; \
-}
-/* I just copied this to get the linker satisfied on PowerPC,
- * so this may not be correct at all.
- */
-#define getstipplepixels24(psrcstip,xt,ones,psrcpix,destpix,stipindex) \
-{ \
-    PixelGroup q; \
-    q = *(psrcstip) >> (xt); \
-    q = ((ones) ? q : ~q) & 1; \
-    *(destpix) = (*(psrcpix)) & QuartetPixelMaskTable[q]; \
-}
-#else /* BITMAP_BIT_ORDER == LSB */
-
-/* this must load 32 bits worth; for most machines, thats an int */
-#define CfbFetchUnaligned(x)	ldl_u(x)
-
-#define getstipplepixels( psrcstip, xt, w, ones, psrcpix, destpix ) \
-{ \
-    PixelGroup q; \
-    q = CfbFetchUnaligned(psrcstip) >> (xt); \
-    if ( ((xt)+(w)) > (PPW*PSZ) ) \
-        q |= (CfbFetchUnaligned((psrcstip)+1)) << ((PPW*PSZ)-(xt)); \
-    q = QuartetBitsTable[(w)] & ((ones) ? q : ~q); \
-    *(destpix) = (*(psrcpix)) & QuartetPixelMaskTable[q]; \
-}
-#if PSZ == 24
-#define getstipplepixels24(psrcstip,xt,ones,psrcpix,destpix,stipindex) \
-{ \
-    PixelGroup q; \
-    q = *(psrcstip) >> (xt); \
-    q = ((ones) ? q : ~q) & 1; \
-    *(destpix) = (*(psrcpix)) & QuartetPixelMaskTable[q]; \
-}
-#endif /* PSZ == 24 */
-#endif
-
-extern PixelGroup cfbstarttab[];
-extern PixelGroup cfbendtab[];
-extern PixelGroup cfbstartpartial[];
-extern PixelGroup cfbendpartial[];
-extern PixelGroup cfbrmask[];
-extern PixelGroup cfbmask[];
-extern PixelGroup QuartetBitsTable[];
-extern PixelGroup QuartetPixelMaskTable[];
-#if PSZ == 24
-extern int cfb24Shift[];
-#endif
diff --git a/cfb/cfbpixmap.c b/cfb/cfbpixmap.c
deleted file mode 100644
index 1166f90..0000000
--- a/cfb/cfbpixmap.c
+++ /dev/null
@@ -1,375 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-/* pixmap management
-   written by drewry, september 1986
-
-   on a monchrome device, a pixmap is a bitmap.
-*/
-
-#include <string.h>
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/Xmd.h>
-#include "servermd.h"
-#include "scrnintstr.h"
-#include "pixmapstr.h"
-#include "mi.h"
-#include "cfb.h"
-#include "cfbmskbits.h"
-
-PixmapPtr
-cfbCreatePixmap (pScreen, width, height, depth, usage_hint)
-    ScreenPtr	pScreen;
-    int		width;
-    int		height;
-    int		depth;
-    unsigned	usage_hint;
-{
-    PixmapPtr pPixmap;
-    size_t datasize;
-    size_t paddedWidth;
-
-    paddedWidth = PixmapBytePad(width, depth);
-
-    if (paddedWidth / 4 > 32767 || height > 32767)
-	return NullPixmap;
-    datasize = height * paddedWidth;
-    pPixmap = AllocatePixmap(pScreen, datasize);
-    if (!pPixmap)
-	return NullPixmap;
-    pPixmap->drawable.type = DRAWABLE_PIXMAP;
-    pPixmap->drawable.class = 0;
-    pPixmap->drawable.pScreen = pScreen;
-    pPixmap->drawable.depth = depth;
-    pPixmap->drawable.bitsPerPixel = BitsPerPixel(depth);
-    pPixmap->drawable.id = 0;
-    pPixmap->drawable.serialNumber = NEXT_SERIAL_NUMBER;
-    pPixmap->drawable.x = 0;
-    pPixmap->drawable.y = 0;
-    pPixmap->drawable.width = width;
-    pPixmap->drawable.height = height;
-    pPixmap->devKind = paddedWidth;
-    pPixmap->refcnt = 1;
-    pPixmap->devPrivate.ptr = datasize ?
-		(pointer)((char *)pPixmap + pScreen->totalPixmapSize) : NULL;
-    pPixmap->usage_hint = usage_hint;
-    return pPixmap;
-}
-
-Bool
-cfbDestroyPixmap(pPixmap)
-    PixmapPtr pPixmap;
-{
-    if(--pPixmap->refcnt)
-	return TRUE;
-    dixFreePrivates(pPixmap->devPrivates);
-    xfree(pPixmap);
-    return TRUE;
-}
-
-PixmapPtr
-cfbCopyPixmap(pSrc)
-    register PixmapPtr	pSrc;
-{
-    register PixmapPtr	pDst;
-    int		size;
-    ScreenPtr pScreen;
-
-    size = pSrc->drawable.height * pSrc->devKind;
-    pScreen = pSrc->drawable.pScreen;
-    pDst = (*pScreen->CreatePixmap) (pScreen, pSrc->drawable.width, 
-				pSrc->drawable.height, pSrc->drawable.depth, 0);
-    if (!pDst)
-	return NullPixmap;
-    memmove((char *)pDst->devPrivate.ptr, (char *)pSrc->devPrivate.ptr, size);
-    return pDst;
-}
-
-
-/* replicates a pattern to be a full 32 bits wide.
-   relies on the fact that each scnaline is longword padded.
-   doesn't do anything if pixmap is not a factor of 32 wide.
-   changes width field of pixmap if successful, so that the fast
-	cfbXRotatePixmap code gets used if we rotate the pixmap later.
-	cfbYRotatePixmap code gets used if we rotate the pixmap later.
-
-   calculate number of times to repeat
-   for each scanline of pattern
-      zero out area to be filled with replicate
-      left shift and or in original as many times as needed
-*/
-void
-cfbPadPixmap(pPixmap)
-    PixmapPtr pPixmap;
-{
-    register int width = (pPixmap->drawable.width) * (pPixmap->drawable.bitsPerPixel);
-    register int h;
-    register CfbBits mask;
-    register CfbBits *p;
-    register CfbBits bits; /* real pattern bits */
-    register int i;
-    int rep;                    /* repeat count for pattern */
- 
-    if (width >= PGSZ)
-        return;
-
-    rep = PGSZ/width;
-    if (rep*width != PGSZ)
-        return;
- 
-    mask = mfbGetendtab(width);
- 
-    p = (CfbBits *)(pPixmap->devPrivate.ptr);
-    for (h=0; h < pPixmap->drawable.height; h++)
-    {
-        *p &= mask;
-        bits = *p;
-        for(i=1; i<rep; i++)
-        {
-#if (BITMAP_BIT_ORDER == MSBFirst) 
-            bits >>= width;
-#else
-	    bits <<= width;
-#endif
-            *p |= bits;
-        }
-        p++;
-    }    
-    pPixmap->drawable.width = PGSZ/(pPixmap->drawable.bitsPerPixel);
-}
-
-
-#ifdef notdef
-/*
- * cfb debugging routine -- assumes pixmap is 1 byte deep 
- */
-static cfbdumppixmap(pPix)
-    PixmapPtr	pPix;
-{
-    unsigned int *pw;
-    char *psrc, *pdst;
-    int	i, j;
-    char	line[66];
-
-    ErrorF(  "pPixmap: 0x%x\n", pPix);
-    ErrorF(  "%d wide %d high\n", pPix->drawable.width, pPix->drawable.height);
-    if (pPix->drawable.width > 64)
-    {
-	ErrorF(  "too wide to see\n");
-	return;
-    }
-
-    pw = (unsigned int *) pPix->devPrivate.ptr;
-    psrc = (char *) pw;
-
-/*
-    for ( i=0; i<pPix->drawable.height; ++i )
-	ErrorF( "0x%x\n", pw[i] );
-*/
-
-    for ( i = 0; i < pPix->drawable.height; ++i ) {
-	pdst = line;
-	for(j = 0; j < pPix->drawable.width; j++) {
-	    *pdst++ = *psrc++ ? 'X' : ' ' ;
-	}
-	*pdst++ = '\n';
-	*pdst++ = '\0';
-	ErrorF( "%s", line);
-    }
-}
-#endif /* notdef */
-
-/* Rotates pixmap pPix by w pixels to the right on the screen. Assumes that
- * words are PGSZ bits wide, and that the least significant bit appears on the
- * left.
- */
-void
-cfbXRotatePixmap(pPix, rw)
-    PixmapPtr	pPix;
-    register int rw;
-{
-    register CfbBits	*pw, *pwFinal;
-    register CfbBits	t;
-    int				rot;
-
-    if (pPix == NullPixmap)
-        return;
-
-    switch (((DrawablePtr) pPix)->bitsPerPixel) {
-	case PSZ:
-	    break;
-	case 1:
-	    mfbXRotatePixmap(pPix, rw);
-	    return;
-	default:
-	    ErrorF("cfbXRotatePixmap: unsupported bitsPerPixel %d\n", ((DrawablePtr) pPix)->bitsPerPixel);
-	    return;
-    }
-    pw = (CfbBits *)pPix->devPrivate.ptr;
-    modulus (rw, (int) pPix->drawable.width, rot);
-    if(pPix->drawable.width == PPW)
-    {
-        pwFinal = pw + pPix->drawable.height;
-	while(pw < pwFinal)
-	{
-	    t = *pw;
-	    *pw++ = SCRRIGHT(t, rot) |
-		    (SCRLEFT(t, (PPW-rot)) & cfbendtab[rot]);
-	}
-    }
-    else
-    {
-        ErrorF("cfb internal error: trying to rotate odd-sized pixmap.\n");
-#ifdef notdef
-	register CfbBits *pwTmp;
-	int size, tsize;
-
-	tsize = PixmapBytePad(pPix->drawable.width - rot, pPix->drawable.depth);
-	pwTmp = (CfbBits *) xalloc(pPix->drawable.height * tsize);
-	if (!pwTmp)
-	    return;
-	/* divide pw (the pixmap) in two vertically at (w - rot) and swap */
-	tsize >>= 2;
-	size = pPix->devKind >> SIZE0F(PixelGroup);
-	cfbQuickBlt((CfbBits *)pw, (CfbBits *)pwTmp,
-		    0, 0, 0, 0,
-		    (int)pPix->drawable.width - rot, (int)pPix->drawable.height,
-		    size, tsize);
-	cfbQuickBlt((CfbBits *)pw, (CfbBits *)pw,
-		    (int)pPix->drawable.width - rot, 0, 0, 0,
-		    rot, (int)pPix->drawable.height,
-		    size, size);
-	cfbQuickBlt((CfbBits *)pwTmp, (CfbBits *)pw,
-		    0, 0, rot, 0,
-		    (int)pPix->drawable.width - rot, (int)pPix->drawable.height,
-		    tsize, size);
-	xfree(pwTmp);
-#endif
-    }
-}
-
-/* Rotates pixmap pPix by h lines.  Assumes that h is always less than
-   pPix->drawable.height
-   works on any width.
- */
-void
-cfbYRotatePixmap(pPix, rh)
-    register PixmapPtr	pPix;
-    int	rh;
-{
-    int nbyDown;	/* bytes to move down to row 0; also offset of
-			   row rh */
-    int nbyUp;		/* bytes to move up to line rh; also
-			   offset of first line moved down to 0 */
-    char *pbase;
-    char *ptmp;
-    int	rot;
-
-    if (pPix == NullPixmap)
-	return;
-    switch (((DrawablePtr) pPix)->bitsPerPixel) {
-	case PSZ:
-	    break;
-	case 1:
-	    mfbYRotatePixmap(pPix, rh);
-	    return;
-	default:
-	    ErrorF("cfbYRotatePixmap: unsupported bitsPerPixel %d\n", ((DrawablePtr) pPix)->bitsPerPixel);
-	    return;
-    }
-
-    modulus (rh, (int) pPix->drawable.height, rot);
-    pbase = (char *)pPix->devPrivate.ptr;
-
-    nbyDown = rot * pPix->devKind;
-    nbyUp = (pPix->devKind * pPix->drawable.height) - nbyDown;
-    if(!(ptmp = (char *)xalloc(nbyUp)))
-	return;
-
-    memmove(ptmp, pbase, nbyUp);		/* save the low rows */
-    memmove(pbase, pbase+nbyUp, nbyDown);	/* slide the top rows down */
-    memmove(pbase+nbyDown, ptmp, nbyUp);	/* move lower rows up to row rot */
-    xfree(ptmp);
-}
-
-void
-cfbCopyRotatePixmap(psrcPix, ppdstPix, xrot, yrot)
-    register PixmapPtr psrcPix, *ppdstPix;
-    int	xrot, yrot;
-{
-    register PixmapPtr pdstPix;
-
-    if ((pdstPix = *ppdstPix) &&
-	(pdstPix->devKind == psrcPix->devKind) &&
-	(pdstPix->drawable.height == psrcPix->drawable.height))
-    {
-	memmove((char *)pdstPix->devPrivate.ptr,
-		(char *)psrcPix->devPrivate.ptr,
-	      psrcPix->drawable.height * psrcPix->devKind);
-	pdstPix->drawable.width = psrcPix->drawable.width;
-	pdstPix->drawable.depth = psrcPix->drawable.depth;
-	pdstPix->drawable.bitsPerPixel = psrcPix->drawable.bitsPerPixel;
-	pdstPix->drawable.serialNumber = NEXT_SERIAL_NUMBER;
-    }
-    else
-    {
-	if (pdstPix)
-	    /* FIX XBUG 6168 */
-	    (*pdstPix->drawable.pScreen->DestroyPixmap)(pdstPix);
-	*ppdstPix = pdstPix = cfbCopyPixmap(psrcPix);
-	if (!pdstPix)
-	    return;
-    }
-    cfbPadPixmap(pdstPix);
-    if (xrot)
-	cfbXRotatePixmap(pdstPix, xrot);
-    if (yrot)
-	cfbYRotatePixmap(pdstPix, yrot);
-}
diff --git a/cfb/cfbply1rct.c b/cfb/cfbply1rct.c
deleted file mode 100644
index ce0bcb2..0000000
--- a/cfb/cfbply1rct.c
+++ /dev/null
@@ -1,363 +0,0 @@
-/*
- *
-Copyright 1990, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <stdlib.h>
-
-#include <X11/X.h>
-
-#include "gcstruct.h"
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "regionstr.h"
-#include "scrnintstr.h"
-#include "mistruct.h"
-
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "cfbrrop.h"
-
-void
-RROP_NAME(cfbFillPoly1Rect) (pDrawable, pGC, shape, mode, count, ptsIn)
-    DrawablePtr	pDrawable;
-    GCPtr	pGC;
-    int		shape;
-    int		mode;
-    int		count;
-    DDXPointPtr	ptsIn;
-{
-    cfbPrivGCPtr    devPriv;
-    int		    nwidth;
-    CfbBits	    *addrl, *addr;
-#if PSZ == 24
-    CfbBits	    startmask, endmask;
-    register int    pidx;
-#else
-#if PPW > 1
-    CfbBits	    mask, bits = ~((CfbBits)0);
-#endif
-#endif
-    int		    maxy;
-    int		    origin;
-    register int    vertex1, vertex2;
-    int		    c = 0;
-    BoxPtr	    extents;
-    int		    clip;
-    int		    y;
-    int		    *vertex1p = NULL, *vertex2p;
-    int		    *endp;
-    int		    x1 = 0, x2 = 0;
-    int		    dx1 = 0, dx2 = 0;
-    int		    dy1 = 0, dy2 = 0;
-    int		    e1 = 0, e2 = 0;
-    int		    step1 = 0, step2 = 0;
-    int		    sign1 = 0, sign2 = 0;
-    int		    h;
-    int		    l;
-#if PSZ != 24 && PPW > 1
-    int		    r;
-#endif
-    int		    nmiddle;
-    RROP_DECLARE
-
-    if (mode == CoordModePrevious)
-    {
-	miFillPolygon (pDrawable, pGC, shape, mode, count, ptsIn);
-	return;
-    }
-    
-    devPriv = cfbGetGCPrivate(pGC);
-#ifdef NO_ONE_RECT
-    if (REGION_NUM_RECTS(pGC->pCompositeClip) != 1)
-    {
-	miFillPolygon (pDrawable, pGC, shape, mode, count, ptsIn);
-	return;
-    }
-#endif
-    origin = *((int *) &pDrawable->x);
-    vertex2 = origin - ((origin & 0x8000) << 1);
-    extents = &pGC->pCompositeClip->extents;
-    RROP_FETCH_GCPRIV(devPriv);
-    vertex1 = *((int *) &extents->x1) - vertex2;
-    vertex2 = *((int *) &extents->x2) - vertex2 - 0x00010001;
-    clip = 0;
-    y = 32767;
-    maxy = 0;
-    vertex2p = (int *) ptsIn;
-    endp = vertex2p + count;
-    if (shape == Convex)
-    {
-    	while (count--)
-    	{
-	    c = *vertex2p;
-	    clip |= (c - vertex1) | (vertex2 - c);
-	    c = intToY(c);
-	    if (c < y) 
-	    {
-	    	y = c;
-	    	vertex1p = vertex2p;
-	    }
-	    vertex2p++;
-	    if (c > maxy)
-	    	maxy = c;
-    	}
-    }
-    else
-    {
-	int yFlip = 0;
-	dx1 = 1;
-	x2 = -1;
-	x1 = -1;
-    	while (count--)
-    	{
-	    c = *vertex2p;
-	    clip |= (c - vertex1) | (vertex2 - c);
-	    c = intToY(c);
-	    if (c < y) 
-	    {
-	    	y = c;
-	    	vertex1p = vertex2p;
-	    }
-	    vertex2p++;
-	    if (c > maxy)
-	    	maxy = c;
-	    if (c == x1)
-		continue;
-	    if (dx1 > 0)
-	    {
-		if (x2 < 0)
-		    x2 = c;
-		else
-		    dx2 = dx1 = (c - x1) >> 31;
-	    }
-	    else
-		if ((c - x1) >> 31 != dx1) 
-		{
-		    dx1 = ~dx1;
-		    yFlip++;
-		}
-	    x1 = c;
-       	}
-	x1 = (x2 - c) >> 31;
-	if (x1 != dx1)
-	    yFlip++;
-	if (x1 != dx2)
-	    yFlip++;
-	if (yFlip != 2) 
-	    clip = 0x8000;
-    }
-    if (y == maxy)
-	return;
-
-    if (clip & 0x80008000)
-    {
-	miFillPolygon (pDrawable, pGC, shape, mode, vertex2p - (int *) ptsIn, ptsIn);
-	return;
-    }
-
-#define AddrYPlus(a,y)  (CfbBits *) (((unsigned char *) (a)) + (y) * nwidth)
-
-    cfbGetTypedWidthAndPointer(pDrawable, nwidth, addrl, unsigned char, CfbBits);
-    addrl = AddrYPlus(addrl,y + pDrawable->y);
-    origin = intToX(origin);
-    vertex2p = vertex1p;
-    vertex2 = vertex1 = *vertex2p++;
-    if (vertex2p == endp)
-	vertex2p = (int *) ptsIn;
-#define Setup(c,x,vertex,dx,dy,e,sign,step) {\
-    x = intToX(vertex); \
-    if ((dy = intToY(c) - y)) { \
-    	dx = intToX(c) - x; \
-	step = 0; \
-    	if (dx >= 0) \
-    	{ \
-	    e = 0; \
-	    sign = 1; \
-	    if (dx >= dy) {\
-	    	step = dx / dy; \
-	    	dx = dx % dy; \
-	    } \
-    	} \
-    	else \
-    	{ \
-	    e = 1 - dy; \
-	    sign = -1; \
-	    dx = -dx; \
-	    if (dx >= dy) { \
-		step = - (dx / dy); \
-		dx = dx % dy; \
-	    } \
-    	} \
-    } \
-    x += origin; \
-    vertex = c; \
-}
-
-#define Step(x,dx,dy,e,sign,step) {\
-    x += step; \
-    if ((e += dx) > 0) \
-    { \
-	x += sign; \
-	e -= dy; \
-    } \
-}
-    for (;;)
-    {
-	if (y == intToY(vertex1))
-	{
-	    do
-	    {
-	    	if (vertex1p == (int *) ptsIn)
-		    vertex1p = endp;
-	    	c = *--vertex1p;
-	    	Setup (c,x1,vertex1,dx1,dy1,e1,sign1,step1)
-	    } while (y >= intToY(vertex1));
-	    h = dy1;
-	}
-	else
-	{
-	    Step(x1,dx1,dy1,e1,sign1,step1)
-	    h = intToY(vertex1) - y;
-	}
-	if (y == intToY(vertex2))
-	{
-	    do
-	    {
-	    	c = *vertex2p++;
-	    	if (vertex2p == endp)
-		    vertex2p = (int *) ptsIn;
-	    	Setup (c,x2,vertex2,dx2,dy2,e2,sign2,step2)
-	    } while (y >= intToY(vertex2));
-	    if (dy2 < h)
-		h = dy2;
-	}
-	else
-	{
-	    Step(x2,dx2,dy2,e2,sign2,step2)
-	    if ((c = (intToY(vertex2) - y)) < h)
-		h = c;
-	}
-	/* fill spans for this segment */
-	y += h;
-	for (;;)
-	{
-	    l = x1;
-#if PSZ != 24 && PPW > 1
-	    r = x2;
-#endif
-	    nmiddle = x2 - x1;
-    	    if (nmiddle < 0)
-	    {
-	    	nmiddle = -nmiddle;
-	    	l = x2;
-#if PSZ != 24 && PPW > 1
-	    	r = x1;
-#endif
-    	    }
-#if PPW > 1
-	    c = l & PIM;
-	    l -= c;
-#endif
-
-#if PGSZ == 32
-#define LWRD_SHIFT 2
-#else /* PGSZ == 64 */
-#define LWRD_SHIFT 3
-#endif /* PGSZ */
-
-#if PSZ == 24
-	    addr = (CfbBits *)((char *)addrl + ((l * 3) & ~0x03));
-	    if (nmiddle <= 1){
-	      if (nmiddle)
-	        RROP_SOLID24(addr, l);
-	    } else {
-	      maskbits(l, nmiddle, startmask, endmask, nmiddle);
-	      pidx = l & 3;
-	      if (startmask){
-		RROP_SOLID_MASK(addr, startmask, pidx-1);
-		addr++;
-		if (pidx == 3)
-		  pidx = 0;
-	      }
-	      while (--nmiddle >= 0){
-		RROP_SOLID(addr, pidx);
-		addr++;
-		if (++pidx == 3)
-		  pidx = 0;
-	      }
-	      if (endmask)
-		RROP_SOLID_MASK(addr, endmask, pidx);
-	    }
-#else /* PSZ == 24 */
-#if PWSH > LWRD_SHIFT
-	    l = l >> (PWSH - LWRD_SHIFT);
-#endif
-#if PWSH < LWRD_SHIFT
-	    l = l << (LWRD_SHIFT - PWSH);
-#endif
-	    addr = (CfbBits *) (((char *) addrl) + l);
-#if PPW > 1
-	    if (c + nmiddle < PPW)
-	    {
-	    	mask = SCRRIGHT (bits,c) ^ SCRRIGHT (bits,c+nmiddle);
-	    	RROP_SOLID_MASK(addr,mask);
-	    }
-	    else
-	    {
-	    	if (c)
-	    	{
-	    	    mask = SCRRIGHT(bits, c);
-	    	    RROP_SOLID_MASK(addr,mask);
-	    	    nmiddle += c - PPW;
-	    	    addr++;
-	    	}
-#endif
-	    	nmiddle >>= PWSH;
-		while (--nmiddle >= 0) {
-		    RROP_SOLID(addr); addr++;
-		}
-#if PPW > 1
-	    	if ((mask = ~SCRRIGHT(bits, r & PIM)))
-	    	    RROP_SOLID_MASK(addr,mask);
-	    }
-#endif
-#endif /* PSZ == 24 */
-	    if (!--h)
-		break;
-	    addrl = AddrYPlus (addrl, 1);
-	    Step(x1,dx1,dy1,e1,sign1,step1)
-	    Step(x2,dx2,dy2,e2,sign2,step2)
-	}
-	if (y == maxy)
-	    break;
-	addrl = AddrYPlus (addrl, 1);
-    }
-    RROP_UNDECLARE
-}
diff --git a/cfb/cfbpolypnt.c b/cfb/cfbpolypnt.c
deleted file mode 100644
index 06a768e..0000000
--- a/cfb/cfbpolypnt.c
+++ /dev/null
@@ -1,202 +0,0 @@
-/************************************************************
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-********************************************************/
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include "gcstruct.h"
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "regionstr.h"
-#include "scrnintstr.h"
-#include "cfb.h"
-#include "cfbmskbits.h"
-
-#define isClipped(c,ul,lr)  ((((c) - (ul)) | ((lr) - (c))) & ClipMask)
-
-/* WARNING: pbox contains two shorts. This code assumes they are packed
- * and can be referenced together as an INT32.
- */
-
-#define PointLoop(fill) { \
-    for (nbox = REGION_NUM_RECTS(cclip), pbox = REGION_RECTS(cclip); \
-	 --nbox >= 0; \
-	 pbox++) \
-    { \
-	c1 = *((INT32 *) &pbox->x1) - off; \
-	c2 = *((INT32 *) &pbox->x2) - off - 0x00010001; \
-	for (ppt = (INT32 *) pptInit, i = npt; --i >= 0;) \
-	{ \
-	    pt = *ppt++; \
-	    if (!isClipped(pt,c1,c2)) { \
-		fill \
-	    } \
-	} \
-    } \
-}
-
-#if PSZ == 24
-# include "cfbrrop24.h"
-#endif
-
-void
-cfbPolyPoint(pDrawable, pGC, mode, npt, pptInit)
-    DrawablePtr pDrawable;
-    GCPtr pGC;
-    int mode;
-    int npt;
-    xPoint *pptInit;
-{
-    register INT32   pt;
-    register INT32   c1, c2;
-    register CARD32    ClipMask = 0x80008000;
-    register CfbBits   xor;
-#ifdef PIXEL_ADDR
-    register PixelType   *addrp;
-    register int    npwidth;
-#if PSZ != 24
-    PixelType	    *addrpt;
-#endif
-#else
-    register CfbBits    *addrl;
-    register int    nlwidth;
-    register int    xoffset;
-    CfbBits   *addrlt;
-#endif
-#if PSZ == 24
-    RROP_DECLARE
-    register int xtmp;
-    register PixelType *p;
-#endif
-    register INT32  *ppt;
-    RegionPtr	    cclip;
-    int		    nbox;
-    register int    i;
-    register BoxPtr pbox;
-    CfbBits   and;
-    int		    rop = pGC->alu;
-    int		    off;
-    cfbPrivGCPtr    devPriv;
-    xPoint	    *pptPrev;
-
-    devPriv =cfbGetGCPrivate(pGC);
-    rop = devPriv->rop;
-    if (rop == GXnoop)
-	return;
-    cclip = pGC->pCompositeClip;
-    xor = devPriv->xor;
-    if ((mode == CoordModePrevious) && (npt > 1))
-    {
-	for (pptPrev = pptInit + 1, i = npt - 1; --i >= 0; pptPrev++)
-	{
-	    pptPrev->x += (pptPrev-1)->x;
-	    pptPrev->y += (pptPrev-1)->y;
-	}
-    }
-    off = *((int *) &pDrawable->x);
-    off -= (off & 0x8000) << 1;
-#ifdef PIXEL_ADDR
-    cfbGetPixelWidthAndPointer(pDrawable, npwidth, addrp);
-#if PSZ == 24
-    addrp = addrp + pDrawable->y * npwidth;
-#else
-    addrp = addrp + pDrawable->y * npwidth + pDrawable->x;
-#endif
-    if (rop == GXcopy)
-    {
-#if PSZ == 24
-      RROP_COPY_SETUP(xor)
-#endif
-	if (!(npwidth & (npwidth - 1)))
-	{
-	    npwidth = ffs(npwidth) - 1;
-#if PSZ == 24
-	    PointLoop(
-		      xtmp = pDrawable->x + intToX(pt);
-		      p = addrp + (intToY(pt) << npwidth) + ((xtmp * 3) >>2);
-		      RROP_SOLID24_COPY(p, xtmp))
-#else
-	    PointLoop(*(addrp + (intToY(pt) << npwidth) + intToX(pt)) = xor;)
-#endif
-	}
-#ifdef sun
-	else if (npwidth == 1152)
-	{
-	    register int    y;
-	    PointLoop(y = intToY(pt); *(addrp + (y << 10) + (y << 7) + intToX(pt)) = xor;)
-	}
-#endif
-	else
-	{
-#if PSZ == 24
-	    PointLoop(
-		      xtmp = pDrawable->x + intToX(pt);
-		      p = addrp + intToY(pt) * npwidth + ((xtmp * 3) >> 2);
-		      RROP_SOLID24_COPY(p, xtmp))
-#else
-	    PointLoop(*(addrp + intToY(pt) * npwidth + intToX(pt)) = xor;)
-#endif
-	}
-    }
-    else
-    {
-	and = devPriv->and;
-#if PSZ == 24
-	RROP_SET_SETUP(xor, and)
-	PointLoop(  
-		  xtmp = pDrawable->x + intToX(pt);
-		  p = addrp + intToY(pt) * npwidth + ((xtmp * 3) >> 2);
-		  RROP_SOLID24_SET(p, xtmp))
-#else
-	PointLoop(  addrpt = addrp + intToY(pt) * npwidth + intToX(pt);
-		    *addrpt = DoRRop (*addrpt, and, xor);)
-#endif
-    }
-#else /* !PIXEL_ADDR */
-    cfbGetLongWidthAndPointer(pDrawable, nlwidth, addrl);
-    addrl = addrl + pDrawable->y * nlwidth + (pDrawable->x >> PWSH);
-    xoffset = pDrawable->x & PIM;
-    and = devPriv->and;
-#if PSZ == 24
-    PointLoop(   addrlt = addrl + intToY(pt) * nlwidth
- 	                   + ((intToX(pt) + xoffset) >> PWSH);
- 		   *addrlt = DoRRop (*addrlt,
- 			   and | ~cfbmask[(intToX(pt) + xoffset) & PIM],
- 			   xor & cfbmask[(intToX(pt) + xoffset) & PIM]);
-	     )
-#else
-    PointLoop(   addrlt = addrl + intToY(pt) * nlwidth
- 	                   + ((intToX(pt) + xoffset) >> PWSH);
- 		   *addrlt = DoRRop (*addrlt,
- 			   and | ~cfbmask[((intToX(pt) + xoffset) & 3)<<1],
- 			   xor & cfbmask[((intToX(pt) + xoffset) & 3)<<1]);
-	     )
-#endif
-#endif /* PIXEL_ADDR */
-}
diff --git a/cfb/cfbpush8.c b/cfb/cfbpush8.c
deleted file mode 100644
index 857ec94..0000000
--- a/cfb/cfbpush8.c
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Push Pixels for 8 bit displays.
- */
-
-
-/*
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-*/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#if PSZ == 8
-
-#include	<X11/X.h>
-#include	<X11/Xmd.h>
-#include	<X11/Xproto.h>
-#include	"gcstruct.h"
-#include	"windowstr.h"
-#include	"scrnintstr.h"
-#include	"pixmapstr.h"
-#include	"regionstr.h"
-#include	"cfb.h"
-#include	"cfbmskbits.h"
-#include	"cfb8bit.h"
-#define MFB_CONSTS_ONLY
-#include	"maskbits.h"
-
-void
-cfbPushPixels8 (pGC, pBitmap, pDrawable, dx, dy, xOrg, yOrg)
-    GCPtr	pGC;
-    PixmapPtr	pBitmap;
-    DrawablePtr	pDrawable;
-    int		dx, dy, xOrg, yOrg;
-{
-    register CfbBits   *src, *dst;
-    register CfbBits   pixel;
-    register CfbBits   c, bits;
-    CfbBits   *pdstLine, *psrcLine;
-    CfbBits   *pdstBase;
-    int		    srcWidth;
-    int		    dstWidth;
-    int		    xoff;
-    int		    nBitmapLongs, nPixmapLongs;
-    int		    nBitmapTmp, nPixmapTmp;
-    CfbBits   rightMask;
-    BoxRec	    bbox;
-    cfbPrivGCPtr    devPriv;
-
-    bbox.x1 = xOrg;
-    bbox.y1 = yOrg;
-    bbox.x2 = bbox.x1 + dx;
-    bbox.y2 = bbox.y1 + dy;
-    devPriv = cfbGetGCPrivate(pGC);
-    
-    switch (RECT_IN_REGION(pGC->pScreen, pGC->pCompositeClip, &bbox))
-    {
-      case rgnPART:
-	mfbPushPixels(pGC, pBitmap, pDrawable, dx, dy, xOrg, yOrg);
-      case rgnOUT:
-	return;
-    }
-
-    cfbGetLongWidthAndPointer (pDrawable, dstWidth, pdstBase)
-
-    psrcLine = (CfbBits *) pBitmap->devPrivate.ptr;
-    srcWidth = (int) pBitmap->devKind >> PWSH;
-    
-    pixel = devPriv->xor;
-    xoff = xOrg & PIM;
-    nBitmapLongs = (dx + xoff) >> MFB_PWSH;
-    nPixmapLongs = (dx + PGSZB + xoff) >> PWSH;
-
-    rightMask = ~cfb8BitLenMasks[((dx + xoff) & MFB_PIM)];
-
-    pdstLine = pdstBase + (yOrg * dstWidth) + (xOrg >> PWSH);
-
-    while (dy--)
-    {
-	c = 0;
-	nPixmapTmp = nPixmapLongs;
-	nBitmapTmp = nBitmapLongs;
-	src = psrcLine;
-	dst = pdstLine;
-	while (nBitmapTmp--)
-	{
-	    bits = *src++;
-	    c |= BitRight (bits, xoff);
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	    nPixmapTmp -= 8;
-	    c = 0;
-	    if (xoff)
-		c = BitLeft (bits, PGSZ - xoff);
-	}
-	if (BitLeft (rightMask, xoff))
-	    c |= BitRight (*src, xoff);
-	c &= rightMask;
-	switch (nPixmapTmp) {
-	case 8:
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	case 7:
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	case 6:
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	case 5:
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	case 4:
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	case 3:
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	case 2:
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	case 1:
-	    WriteBitGroup(dst, pixel, GetBitGroup(c));
-	    NextBitGroup(c);
-	    dst++;
-	case 0:
-	    break;
-	}
-	pdstLine += dstWidth;
-	psrcLine += srcWidth;
-    }
-}
-
-#endif
diff --git a/cfb/cfbrctstp8.c b/cfb/cfbrctstp8.c
deleted file mode 100644
index 485d409..0000000
--- a/cfb/cfbrctstp8.c
+++ /dev/null
@@ -1,593 +0,0 @@
-/*
- * Fill 32 bit stippled rectangles for 8 bit frame buffers
- */
-/*
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-Author: Keith Packard, MIT X Consortium
-
-*/
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#if PSZ == 8
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "servermd.h"
-#include "gcstruct.h"
-#include "window.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "windowstr.h"
-
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "cfb8bit.h"
-
-#define MFB_CONSTS_ONLY
-#include "maskbits.h"
-
-void
-cfb8FillRectOpaqueStippled32 (pDrawable, pGC, nBox, pBox)
-    DrawablePtr	    pDrawable;
-    GCPtr	    pGC;
-    int		    nBox;	/* number of boxes to fill */
-    register BoxPtr pBox;	/* pointer to list of boxes to fill */
-{
-    CfbBits   *src;
-    int stippleHeight;
-
-    int nlwDst;		/* width in longwords of the dest pixmap */
-    int w;		/* width of current box */
-    register int h;	/* height of current box */
-    CfbBits startmask;
-    CfbBits endmask;	/* masks for reggedy bits at either end of line */
-    int nlwMiddle;	/* number of longwords between sides of boxes */
-    register int nlw;			/* loop version of nlwMiddle */
-    CfbBits *dstLine;
-    register CfbBits *dst;	/* pointer to bits we're writing */
-    CfbBits *dstTmp;
-    int y;				/* current scan line */
-
-    CfbBits *pbits;/* pointer to start of pixmap */
-    register CfbBits bits;	/* bits from stipple */
-    int	rot;
-    register CfbBits xor;
-    PixmapPtr		    stipple;
-    int	    wEnd;
-
-    stipple = pGC->pRotatedPixmap;
-
-    cfb8CheckOpaqueStipple(pGC->alu, pGC->fgPixel, pGC->bgPixel, pGC->planemask);
-
-    stippleHeight = stipple->drawable.height;
-    src = (CfbBits *)stipple->devPrivate.ptr;
-
-    cfbGetLongWidthAndPointer (pDrawable, nlwDst, pbits)
-
-    while (nBox--)
-    {
-	w = pBox->x2 - pBox->x1;
-	h = pBox->y2 - pBox->y1;
-	y = pBox->y1;
-	dstLine = pbits + (pBox->y1 * nlwDst) + ((pBox->x1 & ~PIM) >> PWSH);
-	if (((pBox->x1 & PIM) + w) <= PPW)
-	{
-	    maskpartialbits(pBox->x1, w, startmask);
-	    nlwMiddle = 0;
-	    endmask = 0;
-	}
-	else
-	{
-	    maskbits (pBox->x1, w, startmask, endmask, nlwMiddle);
-	}
-	rot = (pBox->x1 & ((PGSZ-1) & ~PIM));
-	pBox++;
-	y = y % stippleHeight;
-#if PPW == 4
-	if (cfb8StippleRRop == GXcopy)
-	{
-	    if (w < PGSZ*2)
-	    {
-	    	while (h--)
-	    	{
-	    	    bits = src[y];
-	    	    y++;
-	    	    if (y == stippleHeight)
-		    	y = 0;
-	    	    if (rot)
-		    	RotBitsLeft(bits,rot);
-		    dst = dstLine;
-	    	    dstLine += nlwDst;
-	    	    if (startmask)
-	    	    {
-		    	*dst = (*dst & ~startmask) |
-			       (GetPixelGroup (bits) & startmask);
-		    	dst++;
-		    	RotBitsLeft (bits, PGSZB);
-	    	    }
-		    nlw = nlwMiddle;
-	    	    while (nlw--)
-	    	    {
-			*dst++ = GetPixelGroup(bits);
-		    	RotBitsLeft (bits, PGSZB);
-	    	    }
-	    	    if (endmask)
-	    	    {
-			*dst = (*dst & ~endmask) |
-			       (GetPixelGroup (bits) & endmask);
-	    	    }
-	    	}
-	    }
-	    else
-	    {
-		wEnd = 7 - (nlwMiddle & 7);
-		nlwMiddle = (nlwMiddle >> 3) + 1;
-	    	while (h--)
-	    	{
-		    bits = src[y];
-		    y++;
-		    if (y == stippleHeight)
-			y = 0;
-	    	    if (rot != 0)
-			RotBitsLeft (bits, rot);
-	    	    dstTmp = dstLine;
-	    	    dstLine += nlwDst;
-		    if (startmask)
-		    {
-			*dstTmp = (*dstTmp & ~startmask) |
-				  (GetPixelGroup (bits) & startmask);
-			dstTmp++;
-			RotBitsLeft (bits, PGSZB);
-		    }
-		    w = 7 - wEnd;
-		    while (w--)
-		    {
-			nlw = nlwMiddle;
-			dst = dstTmp;
-			dstTmp++;
-			xor = GetPixelGroup (bits);
-			while (nlw--)
-			{
-			    *dst = xor;
-			    dst += 8;
-			}
-			NextBitGroup (bits);
-		    }
-		    nlwMiddle--;
-		    w = wEnd + 1;
-		    if (endmask)
-		    {
-			dst = dstTmp + (nlwMiddle << 3);
-			*dst = (*dst & ~endmask) |
-			       (GetPixelGroup(bits) & endmask);
-		    }
-		    while (w--)
-		    {
-			nlw = nlwMiddle;
-			dst = dstTmp;
-			dstTmp++;
-			xor = GetPixelGroup (bits);
-			while (nlw--)
-			{
-			    *dst = xor;
-			    dst += 8;
-			}
-			NextBitGroup (bits);
-		    }
-		    nlwMiddle++;
-		}
-	    }
-	}
-	else
-#endif /* PPW == 4 */
-	{
-	    while (h--)
-	    {
-	    	bits = src[y];
-	    	y++;
-	    	if (y == stippleHeight)
-		    y = 0;
-	    	if (rot)
-		    RotBitsLeft(bits,rot);
-		dst = dstLine;
-	    	dstLine += nlwDst;
-	    	if (startmask)
-	    	{
-		    xor = GetBitGroup(bits);
-		    *dst = MaskRRopPixels(*dst, xor, startmask);
-		    dst++;
-		    RotBitsLeft (bits, PGSZB);
-	    	}
-		nlw = nlwMiddle;
-	    	while (nlw--)
-	    	{
-		    RRopBitGroup(dst, GetBitGroup(bits));
-		    dst++;
-		    RotBitsLeft (bits, PGSZB);
-	    	}
-	    	if (endmask)
-	    	{
-		    xor = GetBitGroup(bits);
-		    *dst = MaskRRopPixels(*dst, xor, endmask);
-	    	}
-	    }
-	}
-    }
-}
-
-void
-cfb8FillRectTransparentStippled32 (pDrawable, pGC, nBox, pBox)
-    DrawablePtr	    pDrawable;
-    GCPtr	    pGC;
-    int		    nBox;	/* number of boxes to fill */
-    BoxPtr 	    pBox;	/* pointer to list of boxes to fill */
-{
-    int		    x, y, w, h;
-    int		    nlwMiddle, nlwDst;
-    CfbBits   startmask, endmask;
-    register CfbBits   *dst;
-    CfbBits   *dstLine, *pbits, *dstTmp;
-    CfbBits   *src;
-    register CfbBits   xor;
-    register CfbBits   bits, mask;
-    int		    rot;
-    int		    wEnd;
-    cfbPrivGCPtr    devPriv;
-    PixmapPtr	    stipple;
-    int		    stippleHeight;
-    register int    nlw;
-    
-    devPriv = cfbGetGCPrivate(pGC);
-    stipple = pGC->pRotatedPixmap;
-    src = (CfbBits *)stipple->devPrivate.ptr;
-    stippleHeight = stipple->drawable.height;
-
-    cfb8CheckStipple (pGC->alu, pGC->fgPixel, pGC->planemask);
-
-    cfbGetLongWidthAndPointer (pDrawable, nlwDst, pbits)
-
-    while (nBox--)
-    {
-	x = pBox->x1;
-    	w = pBox->x2 - x;
-	if (((x & PIM) + w) <= PPW)
-	{
-	    maskpartialbits(x, w, startmask);
-	    endmask = 0;
-	    nlwMiddle = 0;
-	}
-	else
-	{
-	    maskbits (x, w, startmask, endmask, nlwMiddle);
-	}
-	rot = (x & ((PGSZ-1) & ~PIM));
-    	y = pBox->y1;
-    	dstLine = pbits + (y * nlwDst) + (x >> PWSH);
-    	h = pBox->y2 - y;
-	pBox++;
-	y %= stippleHeight;
-#if PPW == 4
-	if (cfb8StippleRRop == GXcopy)
-	{
-	    xor = devPriv->xor;
-	    if (w < PGSZ*2)
-	    {
-	    	while (h--)
-	    	{
-		    bits = src[y];
-		    y++;
-		    if (y == stippleHeight)
-			y = 0;
-	    	    if (rot != 0)
-			RotBitsLeft (bits, rot);
-	    	    dst = dstLine;
-	    	    dstLine += nlwDst;
-	    	    if (startmask)
-	    	    {
-		    	mask = cfb8PixelMasks[GetBitGroup(bits)];
-		    	*dst = (*dst & ~(mask & startmask)) |
-		       	       (xor & (mask & startmask));
-		    	dst++;
-		    	RotBitsLeft (bits, PGSZB);
-	    	    }
-		    nlw = nlwMiddle;
-	    	    while (nlw--)
-	    	    {
-		    	WriteBitGroup (dst,xor,GetBitGroup(bits))
-		    	dst++;
-		    	RotBitsLeft (bits, PGSZB);
-	    	    }
-	    	    if (endmask)
-	    	    {
-		    	mask = cfb8PixelMasks[GetBitGroup(bits)];
-		    	*dst = (*dst & ~(mask & endmask)) |
-		       	       (xor & (mask & endmask));
-	    	    }
-	    	}
-	    }
-	    else
-	    {
-		wEnd = 7 - (nlwMiddle & 7);
-		nlwMiddle = (nlwMiddle >> 3) + 1;
-	    	while (h--)
-	    	{
-		    bits = src[y];
-		    y++;
-		    if (y == stippleHeight)
-			y = 0;
-	    	    if (rot != 0)
-			RotBitsLeft (bits, rot);
-	    	    dstTmp = dstLine;
-	    	    dstLine += nlwDst;
-		    if (startmask)
-		    {
-		    	mask = cfb8PixelMasks[GetBitGroup(bits)];
-		    	*dstTmp = (*dstTmp & ~(mask & startmask)) |
-		       	       (xor & (mask & startmask));
-		    	dstTmp++;
-		    	RotBitsLeft (bits, PGSZB);
-		    }
-		    w = 7 - wEnd;
-		    while (w--)
-		    {
-			nlw = nlwMiddle;
-			dst = dstTmp;
-			dstTmp++;
-#if defined(__GNUC__) && defined(mc68020)
-			mask = cfb8PixelMasks[GetBitGroup(bits)];
-			xor = xor & mask;
-			mask = ~mask;
-			while (nlw--)
-			{
-			    *dst = (*dst & mask) | xor;
-			    dst += 8;
-			}
-			xor = devPriv->xor;
-#else
-#define SwitchBitsLoop(body) \
-	while (nlw--)	\
-	{		\
-	    body	\
-	    dst += 8;	\
-	}
-			SwitchBitGroup(dst, xor, GetBitGroup(bits));
-#undef SwitchBitsLoop
-#endif
-			NextBitGroup (bits);
-		    }
-		    nlwMiddle--;
-		    w = wEnd + 1;
-		    if (endmask)
-		    {
-			mask = cfb8PixelMasks[GetBitGroup(bits)];
-			dst = dstTmp + (nlwMiddle << 3);
-			*dst = (*dst & ~(mask & endmask)) |
-			       (xor &  (mask & endmask));
-		    }
-		    while (w--)
-		    {
-			nlw = nlwMiddle;
-			dst = dstTmp;
-			dstTmp++;
-#if defined(__GNUC__) && defined(mc68020)
-			mask = cfb8PixelMasks[GetBitGroup(bits)];
-			xor = xor & mask;
-			mask = ~mask;
-			while (nlw--)
-			{
-			    *dst = (*dst & mask) | xor;
-			    dst += 8;
-			}
-			xor = devPriv->xor;
-#else
-#define SwitchBitsLoop(body) \
-	while (nlw--)	\
-	{		\
-	    body	\
-	    dst += 8;	\
-	}
-			SwitchBitGroup(dst, xor, GetBitGroup(bits));
-#undef SwitchBitsLoop
-#endif
-			NextBitGroup (bits);
-		    }
-		    nlwMiddle++;
-		}
-	    }
-	}
-	else
-#endif /* PPW == 4 */
-	{
-	    while (h--)
-	    {
-		bits = src[y];
-		y++;
-		if (y == stippleHeight)
-		    y = 0;
-	    	if (rot != 0)
-		    RotBitsLeft (bits, rot);
-	    	dst = dstLine;
-	    	dstLine += nlwDst;
-	    	if (startmask)
-	    	{
-		    xor = GetBitGroup(bits);
-		    *dst = MaskRRopPixels(*dst, xor, startmask);
-		    dst++;
-		    RotBitsLeft (bits, PGSZB);
-	    	}
-		nlw = nlwMiddle;
-	    	while (nlw--)
-	    	{
-		    RRopBitGroup(dst, GetBitGroup(bits));
-		    dst++;
-		    RotBitsLeft (bits, PGSZB);
-	    	}
-	    	if (endmask)
-	    	{
-		    xor = GetBitGroup(bits);
-		    *dst = MaskRRopPixels(*dst, xor, endmask);
-	    	}
-	    }
-	}
-    }
-}
-
-
-void
-cfb8FillRectStippledUnnatural (pDrawable, pGC, nBox, pBox)
-    DrawablePtr	    pDrawable;
-    GCPtr	    pGC;
-    int		    nBox;
-    register BoxPtr pBox;
-{
-    CfbBits   *pdstBase;	/* pointer to start of bitmap */
-    CfbBits   *pdstLine;	/* current destination line */
-    int		    nlwDst;	/* width in longwords of bitmap */
-    PixmapPtr	    pStipple;	/* pointer to stipple we want to fill with */
-    int		    nlwMiddle;
-    register int    nlw;
-    int		    x, y, w, h, xrem, xSrc, ySrc;
-    int		    stwidth, stippleWidth;
-    int		    stippleHeight;
-    register CfbBits  bits, inputBits;
-    register int    partBitsLeft;
-    int		    nextPartBits;
-    int		    bitsLeft, bitsWhole;
-    register CfbBits    *pdst;	/* pointer to current word in bitmap */
-    CfbBits   *srcTemp, *srcStart;
-    CfbBits   *psrcBase;
-    CfbBits   startmask, endmask;
-
-    if (pGC->fillStyle == FillStippled)
-	cfb8CheckStipple (pGC->alu, pGC->fgPixel, pGC->planemask);
-    else
-	cfb8CheckOpaqueStipple (pGC->alu, pGC->fgPixel, pGC->bgPixel, pGC->planemask);
-
-    if (cfb8StippleRRop == GXnoop)
-	return;
-
-    /*
-     *  OK,  so what's going on here?  We have two Drawables:
-     *
-     *  The Stipple:
-     *		Depth = 1
-     *		Width = stippleWidth
-     *		Words per scanline = stwidth
-     *		Pointer to pixels = pStipple->devPrivate.ptr
-     */
-
-    pStipple = pGC->stipple;
-
-    stwidth = pStipple->devKind >> PWSH;
-    stippleWidth = pStipple->drawable.width;
-    stippleHeight = pStipple->drawable.height;
-    psrcBase = (CfbBits *) pStipple->devPrivate.ptr;
-
-    /*
-     *	The Target:
-     *		Depth = PSZ
-     *		Width = determined from *pwidth
-     *		Words per scanline = nlwDst
-     *		Pointer to pixels = addrlBase
-     */
-
-    xSrc = pDrawable->x;
-    ySrc = pDrawable->y;
-
-    cfbGetLongWidthAndPointer (pDrawable, nlwDst, pdstBase)
-
-    /* this replaces rotating the stipple. Instead we just adjust the offset
-     * at which we start grabbing bits from the stipple.
-     * Ensure that ppt->x - xSrc >= 0 and ppt->y - ySrc >= 0,
-     * so that iline and xrem always stay within the stipple bounds.
-     */
-
-    xSrc += (pGC->patOrg.x % stippleWidth) - stippleWidth;
-    ySrc += (pGC->patOrg.y % stippleHeight) - stippleHeight;
-
-    bitsWhole = stippleWidth;
-
-    while (nBox--)
-    {
-	x = pBox->x1;
-	y = pBox->y1;
-	w = pBox->x2 - x;
-	h = pBox->y2 - y;
-	pBox++;
-	pdstLine = pdstBase + y * nlwDst + (x >> PWSH);
-	y = (y - ySrc) % stippleHeight;
-	srcStart = psrcBase + y * stwidth;
-	xrem = ((x & ~PIM) - xSrc) % stippleWidth;
-	if (((x & PIM) + w) < PPW)
-	{
-	    maskpartialbits (x, w, startmask);
-	    nlwMiddle = 0;
-	    endmask = 0;
-	}
-	else
-	{
-	    maskbits (x, w, startmask, endmask, nlwMiddle);
-	}
-	while (h--)
-	{
-    	    srcTemp = srcStart + (xrem >> MFB_PWSH);
-    	    bitsLeft = stippleWidth - (xrem & ~MFB_PIM);
-	    NextUnnaturalStippleWord
-	    NextSomeBits (inputBits, (xrem & MFB_PIM));
-	    partBitsLeft -= (xrem & MFB_PIM);
-	    NextUnnaturalStippleBits
-	    nlw = nlwMiddle;
-	    pdst = pdstLine;
-	    if (startmask)
-	    {
-		*pdst = MaskRRopPixels(*pdst,bits,startmask);
-		pdst++;
-		NextUnnaturalStippleBits
-	    }
-	    while (nlw--)
-	    {
-		*pdst = RRopPixels(*pdst,bits);
-		pdst++;
-		NextUnnaturalStippleBits
-	    }
-	    if (endmask)
-		*pdst = MaskRRopPixels(*pdst,bits,endmask);
-	    pdstLine += nlwDst;
-	    y++;
-	    srcStart += stwidth;
-	    if (y == stippleHeight)
-	    {
-		y = 0;
-		srcStart = psrcBase;
-	    }
-	}
-    }
-}
-
-#endif /* PSZ == 8 */
diff --git a/cfb/cfbrrop.c b/cfb/cfbrrop.c
deleted file mode 100644
index ffd8138..0000000
--- a/cfb/cfbrrop.c
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- *
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- */
-
-/* cfb reduced rasterop computations */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include <X11/Xproto.h>
-#include "cfb.h"
-#include "cfbmskbits.h"
-
-/* A description:
- *
- * There are four possible operations on each bit in the destination word,
- *
- *	    1	2   3	4
- *
- *    0	    0	0   1	1
- *    1	    0	1   0	1
- *
- * On examination of the reduced rop equation (dst = (dst & and) ^ xor),
- * these four fall to reduced rops as follows:
- *
- *  and	    0	1   1	0
- *  xor	    0	0   1	1
- *
- * or, (if 'and' is expensive) (dst = (dst | or) ^ xor)
- *
- *  or	    1	0   0	1
- *  xor	    1	0   1	0
- *
- * The trouble with using this later equation is that trivial
- * rasterop reduction is more difficult; some common rasterops
- * use complicated expressions of xor/and instead of the simple
- * ones while other common rasterops are not made any simpler:
- *
- * GXcopy:	*dst = ~xor		instead of  *dst = xor
- * GXand:	*dst = *dst & ~or	instead of  *dst = *dst & and
- * GXor:	*dst = *dst | or	instead of  *dst = *dst | xor
- * GXxor:	*dst = *dst ^ xor	instead of  *dst = *dst ^ xor
- *
- * If you're really set on using this second mechanism, the changes
- * are pretty simple.
- *
- * All that remains is to provide a mechanism for computing and/xor values
- * based on the raster op and foreground value.
- *
- * The 16 rops fall as follows, with the associated reduced
- * rop and/xor and or/xor values.  The values in parenthesis following the
- * reduced values gives an equation using the source value for
- * the reduced value, and is one of {0, src, ~src, 1} as appropriate.
- *
- *	clear		and		andReverse	copy
- *     src  0	1	    0   1	    0	1	    0	1
- *  dst	0   0	0	0   0   0	0   0	1	0   0	1
- *	1   0	0	1   0   1	1   0	0	1   0	1
- *
- *  and	    0	0 (0)	    0   1 (src)	    0	1 (src)	    0	0 (0)
- *  xor	    0	0 (0)	    0   0 (0)	    0	1 (src)	    0	1 (src)
- *
- *  or	    1	1 (1)	    1	0 (~src)    1	0 (~src)    1	1 (1)
- *  xor	    1	1 (1)	    1	0 (~src)    1	1 (1)	    1	0 (~src)
- *
- *	andInverted	noop		xor		or
- *     src  0	1	    0   1	    0	1	    0	1
- *  dst	0   0	0	0   0   0	0   0	1	0   0	1
- *	1   1	0	1   1   1	1   1	0	1   1	1
- *
- *  and	    1	0 (~src)    1   1 (1)	    1	1 (1)	    1	0 (~src)
- *  xor	    0	0 (0)	    0   0 (0)	    0	1 (src)	    0	1 (src)
- *
- *  or	    0	1 (src)	    0	0 (0)	    0	0 (0)	    0	1 (src)
- *  xor	    0	1 (src)	    0	0 (0)	    0	1 (src)	    0	0 (0)
- *
- *	nor		equiv		invert		orReverse
- *     src  0	1	    0   1	    0	1	    0	1
- *  dst	0   1	0	0   1   0	0   1	1	0   1	1
- *	1   0	0	1   0   1	1   0	0	1   0	1
- *
- *  and	    1	0 (~src)    1   1 (1)	    1	1 (1)	    1	0 (~src)
- *  xor	    1	0 (~src)    1   0 (~src)    1	1 (1)	    1	1 (1)
- *
- *  or	    0	1 (src)	    0	0 (0)	    0	0 (0)	    0	1 (src)
- *  xor	    1	1 (1)	    1	0 (~src)    1	1 (1)	    1	0 (~src)
- *
- *	copyInverted	orInverted	nand		set
- *     src  0	1	    0   1	    0	1	    0	1
- *  dst	0   1	0	0   1   0	0   1	1	0   1	1
- *	1   1	0	1   1   1	1   1	0	1   1	1
- *
- *  and	    0	0 (0)	    0   1 (src)	    0	1 (src)	    0	0 (0)
- *  xor	    1	0 (~src)    1   0 (~src)    1	1 (1)	    1	1 (1)
- *
- *  or	    1	1 (1)	    1	0 (~src)    1	0 (~src)    1	1 (1)
- *  xor	    0	1 (src)	    0	0 (0)	    0	1 (src)	    0	0 (0)
- */
-
-int
-cfbReduceRasterOp (rop, fg, pm, andp, xorp)
-    int		    rop;
-    CfbBits   fg, pm;
-    CfbBits   *andp, *xorp;
-{
-    CfbBits   and, xor;
-    int		    rrop;
-
-    fg = PFILL (fg);
-    pm = PFILL (pm);
-    switch (rop)
-    {
-    case GXclear:
-    	and = 0;
-    	xor = 0;
-	break;
-    case GXand:
-	and = fg;
-	xor = 0;
-	break;
-    case GXandReverse:
-	and = fg;
-	xor = fg;
-	break;
-    case GXcopy:
-	and = 0;
-	xor = fg;
-	break;
-    case GXandInverted:
-	and = ~fg;
-	xor = 0;
-	break;
-    case GXnoop:
-	and = ~0;
-	xor = 0;
-	break;
-    case GXxor:
-	and = ~0;
-	xor = fg;
-	break;
-    case GXor:
-	and = ~fg;
-	xor = fg;
-	break;
-    case GXnor:
-	and = ~fg;
-	xor = ~fg;
-	break;
-    case GXequiv:
-	and = ~0;
-	xor = ~fg;
-	break;
-    case GXinvert:
-	and = ~0;
-	xor = ~0;
-	break;
-    case GXorReverse:
-	and = ~fg;
-	xor = ~0;
-	break;
-    case GXcopyInverted:
-	and = 0;
-	xor = ~fg;
-	break;
-    case GXorInverted:
-	and = fg;
-	xor = ~fg;
-	break;
-    case GXnand:
-	and = fg;
-	xor = ~0;
-	break;
-    case GXset:
-	and = 0;
-	xor = ~0;
-	break;
-    default:
-	and = xor = 0;
-	break;
-    }
-    and |= ~pm;
-    xor &= pm;
-    *andp = and;
-    *xorp = xor;
-    /* check for some special cases to reduce computation */
-    if (and == 0)
-	rrop = GXcopy;
-    /* nothing checks for GXnoop
-    else if (and == ~0 && xor == 0)
-	rrop = GXnoop;
-    */
-    else if (and == ~0)
-	rrop = GXxor;
-    else if (xor == 0)
-	rrop = GXand;
-    else if ( (and ^ xor) == ~0) /* fix XBUG 6541 */
-	rrop = GXor;
-    else
-	rrop = GXset;   /* rop not reduced */
-    return rrop;
-}
diff --git a/cfb/cfbrrop.h b/cfb/cfbrrop.h
deleted file mode 100644
index e9ca881..0000000
--- a/cfb/cfbrrop.h
+++ /dev/null
@@ -1,343 +0,0 @@
-/*
- *
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- */
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifndef GXcopy
-#include <X11/X.h>
-#endif
-
-#define RROP_FETCH_GC(gc) \
-    RROP_FETCH_GCPRIV((cfbPrivGCPtr)dixLookupPrivate(&(gc)->devPrivates, \
-						     cfbGCPrivateKey))
-
-#ifndef RROP
-#define RROP GXset
-#endif
-
-#if RROP == GXcopy
-#if PSZ == 24
-#define RROP_DECLARE	register CfbBits	rrop_xor; \
-    CfbBits piQxelXor[3], spiQxelXor[8];
-#define RROP_FETCH_GCPRIV(devPriv)  rrop_xor = (devPriv)->xor; \
-    spiQxelXor[0] = rrop_xor & 0xFFFFFF; \
-    spiQxelXor[2] = rrop_xor << 24; \
-    spiQxelXor[3] = (rrop_xor & 0xFFFF00)>> 8; \
-    spiQxelXor[4] = rrop_xor << 16; \
-    spiQxelXor[5] = (rrop_xor & 0xFF0000)>> 16; \
-    spiQxelXor[6] = rrop_xor << 8; \
-    spiQxelXor[1] = spiQxelXor[7] = 0; \
-    piQxelXor[0] = (rrop_xor & 0xFFFFFF)|(rrop_xor << 24); \
-    piQxelXor[1] = (rrop_xor << 16)|((rrop_xor & 0xFFFF00)>> 8); \
-    piQxelXor[2] = (rrop_xor << 8)|((rrop_xor & 0xFF0000)>> 16);
-#define RROP_SOLID24(dst,index)	    {\
-	    register int idx = ((index) & 3)<< 1; \
-	    *(dst) = (*(dst) & cfbrmask[idx])|spiQxelXor[idx]; \
-	    if (idx == 2  ||  idx == 4){ \
-              idx++; \
-	      *((dst)+1) = (*((dst)+1) & cfbrmask[idx])|spiQxelXor[idx]; \
-	    } \
-	}
-#define RROP_SOLID(dst, idx) \
-	    (*(dst) = piQxelXor[(idx)])
-#define RROP_SOLID_MASK(dst,mask,idx) \
-	    (*(dst) = (*(dst) & ~(mask))|(piQxelXor[(idx)] & (mask)))
-#define RROP_UNDECLARE (void)piQxelXor;  (void)spiQxelXor;
-#else
-#define RROP_FETCH_GCPRIV(devPriv)  rrop_xor = (devPriv)->xor;
-#define RROP_DECLARE	register CfbBits	rrop_xor;
-#define RROP_SOLID(dst)	    (*(dst) = (rrop_xor))
-#define RROP_SOLID_MASK(dst,mask) (*(dst) = (*(dst) & ~(mask)) | ((rrop_xor) & (mask)))
-#define RROP_UNDECLARE
-#endif
-#define RROP_NAME(prefix)   RROP_NAME_CAT(prefix,Copy)
-#endif /* GXcopy */
-
-#if RROP == GXxor
-#if PSZ == 24
-#define RROP_DECLARE	register CfbBits	rrop_xor; \
-    CfbBits piQxelXor[3], spiQxelXor[8];
-#define RROP_FETCH_GCPRIV(devPriv)  rrop_xor = (devPriv)->xor; \
-    spiQxelXor[0] = rrop_xor & 0xFFFFFF; \
-    spiQxelXor[2] = rrop_xor << 24; \
-    spiQxelXor[3] = (rrop_xor & 0xFFFF00)>> 8; \
-    spiQxelXor[4] = rrop_xor << 16; \
-    spiQxelXor[5] = (rrop_xor & 0xFF0000)>> 16; \
-    spiQxelXor[6] = rrop_xor << 8; \
-    spiQxelXor[1] = spiQxelXor[7] = 0; \
-    piQxelXor[0] = (rrop_xor & 0xFFFFFF)|(rrop_xor << 24); \
-    piQxelXor[1] = (rrop_xor << 16)|((rrop_xor & 0xFFFF00)>> 8); \
-    piQxelXor[2] = (rrop_xor << 8)|((rrop_xor & 0xFF0000)>> 16);
-#define RROP_SOLID24(dst,index)	     {\
-	    register int idx = ((index) & 3)<< 1; \
-	    *(dst) ^= spiQxelXor[idx]; \
-	    if (idx == 2  ||  idx == 4) \
-	      *((dst)+1) ^= spiQxelXor[idx+1]; \
-	}
-#define RROP_SOLID(dst,idx) \
-	    (*(dst) ^= piQxelXor[(idx)])
-#define RROP_SOLID_MASK(dst,mask,idx) \
-	    (*(dst) ^= (piQxelXor[(idx)] & (mask)))
-#define RROP_UNDECLARE (void)piQxelXor; (void)spiQxelXor;
-#else
-#define RROP_DECLARE	register CfbBits	rrop_xor;
-#define RROP_FETCH_GCPRIV(devPriv)  rrop_xor = (devPriv)->xor;
-#define RROP_SOLID(dst)	    (*(dst) ^= (rrop_xor))
-#define RROP_SOLID_MASK(dst,mask) (*(dst) ^= ((rrop_xor) & (mask)))
-#define RROP_UNDECLARE
-#endif
-#define RROP_NAME(prefix)   RROP_NAME_CAT(prefix,Xor)
-#endif /* GXxor */
-
-#if RROP == GXand
-#if PSZ == 24
-#define RROP_DECLARE	register CfbBits	rrop_and; \
-    CfbBits piQxelAnd[3], spiQxelAnd[6];
-#define RROP_FETCH_GCPRIV(devPriv)  rrop_and = (devPriv)->and; \
-    spiQxelAnd[0] = (rrop_and & 0xFFFFFF) | 0xFF000000; \
-    spiQxelAnd[2] = (rrop_and << 24) | 0xFFFFFF; \
-    spiQxelAnd[3] = ((rrop_and & 0xFFFF00)>> 8) | 0xFFFF0000; \
-    spiQxelAnd[4] = (rrop_and << 16) | 0xFFFF; \
-    spiQxelAnd[5] = ((rrop_and & 0xFF0000)>> 16) | 0xFFFFFF00; \
-    spiQxelAnd[1] = (rrop_and << 8) | 0xFF; \
-    piQxelAnd[0] = (rrop_and & 0xFFFFFF)|(rrop_and << 24); \
-    piQxelAnd[1] = (rrop_and << 16)|((rrop_and & 0xFFFF00)>> 8); \
-    piQxelAnd[2] = (rrop_and << 8)|((rrop_and & 0xFF0000)>> 16); 
-#define RROP_SOLID24(dst,index)	    {\
-	    switch((index) & 3){ \
-	    case 0: \
-	      *(dst) &= spiQxelAnd[0]; \
-	      break; \
-	    case 3: \
-	      *(dst) &= spiQxelAnd[1]; \
-	      break; \
-	    case 1: \
-	      *(dst) &= spiQxelAnd[2]; \
-	      *((dst)+1) &= spiQxelAnd[3]; \
-	      break; \
-	    case 2: \
-	      *(dst) &= spiQxelAnd[4]; \
-	      *((dst)+1) &= spiQxelAnd[5]; \
-	      break; \
-	    } \
-	    }
-#define RROP_SOLID(dst,idx) \
-	    (*(dst) &= piQxelAnd[(idx)])
-#define RROP_SOLID_MASK(dst,mask,idx) \
-	    (*(dst) &= (piQxelAnd[(idx)] | ~(mask)))
-#define RROP_UNDECLARE (void)piQxelAnd; (void)spiQxelAnd;
-#else
-#define RROP_DECLARE	register CfbBits	rrop_and;
-#define RROP_FETCH_GCPRIV(devPriv)  rrop_and = (devPriv)->and;
-#define RROP_SOLID(dst)	    (*(dst) &= (rrop_and))
-#define RROP_SOLID_MASK(dst,mask) (*(dst) &= ((rrop_and) | ~(mask)))
-#define RROP_UNDECLARE
-#endif
-#define RROP_NAME(prefix)   RROP_NAME_CAT(prefix,And)
-#endif /* GXand */
-
-#if RROP == GXor
-#if PSZ == 24
-#define RROP_DECLARE	register CfbBits	rrop_or; \
-    CfbBits piQxelOr[3], spiQxelOr[6];
-#define RROP_FETCH_GCPRIV(devPriv)  rrop_or = (devPriv)->xor; \
-    spiQxelOr[0] = rrop_or & 0xFFFFFF; \
-    spiQxelOr[1] = rrop_or << 24; \
-    spiQxelOr[2] = rrop_or << 16; \
-    spiQxelOr[3] = rrop_or << 8; \
-    spiQxelOr[4] = (rrop_or & 0xFFFF00)>> 8; \
-    spiQxelOr[5] = (rrop_or & 0xFF0000)>> 16; \
-    piQxelOr[0] = (rrop_or & 0xFFFFFF)|(rrop_or << 24); \
-    piQxelOr[1] = (rrop_or << 16)|((rrop_or & 0xFFFF00)>> 8); \
-    piQxelOr[2] = (rrop_or << 8)|((rrop_or & 0xFF0000)>> 16);
-#define RROP_SOLID24(dst,index)	     {\
-	    switch((index) & 3){ \
-	    case 0: \
-	      *(dst) |= spiQxelOr[0]; \
-	      break; \
-	    case 3: \
-	      *(dst) |= spiQxelOr[3]; \
-	      break; \
-	    case 1: \
-	      *(dst) |= spiQxelOr[1]; \
-	      *((dst)+1) |= spiQxelOr[4]; \
-	      break; \
-	    case 2: \
-	      *(dst) |= spiQxelOr[2]; \
-	      *((dst)+1) |= spiQxelOr[5]; \
-	      break; \
-	    } \
-	    }
-#define RROP_SOLID(dst,idx) \
-	    (*(dst) |= piQxelOr[(idx)])
-#define RROP_SOLID_MASK(dst,mask,idx) \
-	    (*(dst) |= (piQxelOr[(idx)] & (mask)))
-#define RROP_UNDECLARE (void)piQxelOr;  (void)spiQxelOr;
-#else
-#define RROP_DECLARE	register CfbBits	rrop_or;
-#define RROP_FETCH_GCPRIV(devPriv)  rrop_or = (devPriv)->xor;
-#define RROP_SOLID(dst)	    (*(dst) |= (rrop_or))
-#define RROP_SOLID_MASK(dst,mask) (*(dst) |= ((rrop_or) & (mask)))
-#define RROP_UNDECLARE
-#endif
-#define RROP_NAME(prefix)   RROP_NAME_CAT(prefix,Or)
-#endif /* GXor */
-
-#if RROP == GXnoop
-#define RROP_DECLARE
-#define RROP_FETCH_GCPRIV(devPriv)
-#define RROP_SOLID(dst)
-#define RROP_SOLID_MASK(dst,mask)
-#define RROP_NAME(prefix)   RROP_NAME_CAT(prefix,Noop)
-#define RROP_UNDECLARE
-#endif /* GXnoop */
-
-#if RROP ==  GXset
-#if PSZ == 24
-#define RROP_DECLARE	    register CfbBits	rrop_and, rrop_xor; \
-    CfbBits piQxelAnd[3], piQxelXor[3],  spiQxelAnd[6], spiQxelXor[6];
-#define RROP_FETCH_GCPRIV(devPriv)  rrop_and = (devPriv)->and; \
-				    rrop_xor = (devPriv)->xor; \
-    spiQxelXor[0] = rrop_xor & 0xFFFFFF; \
-    spiQxelXor[1] = rrop_xor << 24; \
-    spiQxelXor[2] = rrop_xor << 16; \
-    spiQxelXor[3] = rrop_xor << 8; \
-    spiQxelXor[4] = (rrop_xor & 0xFFFF00)>> 8; \
-    spiQxelXor[5] = (rrop_xor & 0xFF0000)>> 16; \
-    spiQxelAnd[0] = (rrop_and & 0xFFFFFF) | 0xFF000000; \
-    spiQxelAnd[1] = (rrop_and << 24) | 0xFFFFFF; \
-    spiQxelAnd[2] = (rrop_and << 16) | 0xFFFF; \
-    spiQxelAnd[3] = (rrop_and << 8) | 0xFF; \
-    spiQxelAnd[4] = ((rrop_and & 0xFFFF00)>> 8) | 0xFFFF0000; \
-    spiQxelAnd[5] = ((rrop_and & 0xFF0000)>> 16) | 0xFFFFFF00; \
-    piQxelAnd[0] = (rrop_and & 0xFFFFFF)|(rrop_and << 24); \
-    piQxelAnd[1] = (rrop_and << 16)|((rrop_and & 0xFFFF00)>> 8); \
-    piQxelAnd[2] = (rrop_and << 8)|((rrop_and & 0xFF0000)>> 16); \
-    piQxelXor[0] = (rrop_xor & 0xFFFFFF)|(rrop_xor << 24); \
-    piQxelXor[1] = (rrop_xor << 16)|((rrop_xor & 0xFFFF00)>> 8); \
-    piQxelXor[2] = (rrop_xor << 8)|((rrop_xor & 0xFF0000)>> 16);
-#define RROP_SOLID24(dst,index)	     {\
-	    switch((index) & 3){ \
-	    case 0: \
-	      *(dst) = ((*(dst) & (piQxelAnd[0] |0xFF000000))^(piQxelXor[0] & 0xFFFFFF)); \
-	      break; \
-	    case 3: \
-	      *(dst) = ((*(dst) & (piQxelAnd[2]|0xFF))^(piQxelXor[2] & 0xFFFFFF00)); \
-	      break; \
-	    case 1: \
-	      *(dst) = ((*(dst) & (piQxelAnd[0]|0xFFFFFF))^(piQxelXor[0] & 0xFF000000)); \
-	      *((dst)+1) = ((*((dst)+1) & (piQxelAnd[1]|0xFFFF0000))^(piQxelXor[1] & 0xFFFF)); \
-	      break; \
-	    case 2: \
-	      *(dst) = ((*(dst) & (piQxelAnd[1]|0xFFFF))^(piQxelXor[1] & 0xFFFF0000)); \
-	      *((dst)+1) = ((*((dst)+1) & (piQxelAnd[2]|0xFFFFFF00))^(piQxelXor[2] & 0xFF)); \
-	      break; \
-	    } \
-	    }
-#define RROP_SOLID(dst,idx) \
-	    (*(dst) = DoRRop (*(dst), piQxelAnd[(idx)], piQxelXor[(idx)]))
-#define RROP_SOLID_MASK(dst,mask,idx) \
-	    (*(dst) = DoMaskRRop (*(dst), piQxelAnd[(idx)], piQxelXor[(idx)], (mask)))
-#define RROP_UNDECLARE (void)piQxelAnd;  (void)piQxelXor; \
-		       (void)spiQxelAnd;  (void)spiQxelXor;
-#else
-#define RROP_DECLARE	    register CfbBits	rrop_and, rrop_xor;
-#define RROP_FETCH_GCPRIV(devPriv)  rrop_and = (devPriv)->and; \
-				    rrop_xor = (devPriv)->xor;
-#define RROP_SOLID(dst)	    (*(dst) = DoRRop (*(dst), rrop_and, rrop_xor))
-#define RROP_SOLID_MASK(dst,mask)   (*(dst) = DoMaskRRop (*(dst), rrop_and, rrop_xor, (mask)))
-#define RROP_UNDECLARE
-#endif
-#define RROP_NAME(prefix)   RROP_NAME_CAT(prefix,General)
-#endif /* GXset */
-
-#define RROP_UNROLL_CASE1(p,i)    case (i): RROP_SOLID((p) - (i));
-#define RROP_UNROLL_CASE2(p,i)    RROP_UNROLL_CASE1(p,(i)+1) RROP_UNROLL_CASE1(p,i)
-#define RROP_UNROLL_CASE4(p,i)    RROP_UNROLL_CASE2(p,(i)+2) RROP_UNROLL_CASE2(p,i)
-#define RROP_UNROLL_CASE8(p,i)    RROP_UNROLL_CASE4(p,(i)+4) RROP_UNROLL_CASE4(p,i)
-#define RROP_UNROLL_CASE16(p,i)   RROP_UNROLL_CASE8(p,(i)+8) RROP_UNROLL_CASE8(p,i)
-#define RROP_UNROLL_CASE32(p,i)   RROP_UNROLL_CASE16(p,(i)+16) RROP_UNROLL_CASE16(p,i)
-#define RROP_UNROLL_CASE3(p)	RROP_UNROLL_CASE2(p,2) RROP_UNROLL_CASE1(p,1)
-#define RROP_UNROLL_CASE7(p)	RROP_UNROLL_CASE4(p,4) RROP_UNROLL_CASE3(p)
-#define RROP_UNROLL_CASE15(p)	RROP_UNROLL_CASE8(p,8) RROP_UNROLL_CASE7(p)
-#define RROP_UNROLL_CASE31(p)	RROP_UNROLL_CASE16(p,16) RROP_UNROLL_CASE15(p)
-#ifdef LONG64
-#define RROP_UNROLL_CASE63(p)	RROP_UNROLL_CASE32(p,32) RROP_UNROLL_CASE31(p)
-#endif /* LONG64 */
-
-#define RROP_UNROLL_LOOP1(p,i) RROP_SOLID((p) + (i));
-#define RROP_UNROLL_LOOP2(p,i) RROP_UNROLL_LOOP1(p,(i)) RROP_UNROLL_LOOP1(p,(i)+1)
-#define RROP_UNROLL_LOOP4(p,i) RROP_UNROLL_LOOP2(p,(i)) RROP_UNROLL_LOOP2(p,(i)+2)
-#define RROP_UNROLL_LOOP8(p,i) RROP_UNROLL_LOOP4(p,(i)) RROP_UNROLL_LOOP4(p,(i)+4)
-#define RROP_UNROLL_LOOP16(p,i) RROP_UNROLL_LOOP8(p,(i)) RROP_UNROLL_LOOP8(p,(i)+8)
-#define RROP_UNROLL_LOOP32(p,i) RROP_UNROLL_LOOP16(p,(i)) RROP_UNROLL_LOOP16(p,(i)+16)
-#ifdef LONG64
-#define RROP_UNROLL_LOOP64(p,i) RROP_UNROLL_LOOP32(p,(i)) RROP_UNROLL_LOOP32(p,(i)+32)
-#endif /* LONG64 */
-
-#if defined (FAST_CONSTANT_OFFSET_MODE) && defined (SHARED_IDCACHE) && (RROP == GXcopy)
-
-#ifdef LONG64
-#define RROP_UNROLL_SHIFT	6
-#define RROP_UNROLL_CASE(p)	RROP_UNROLL_CASE63(p)
-#define RROP_UNROLL_LOOP(p)	RROP_UNROLL_LOOP64(p,-64)
-#else /* not LONG64 */
-#define RROP_UNROLL_SHIFT	5
-#define RROP_UNROLL_CASE(p)	RROP_UNROLL_CASE31(p)
-#define RROP_UNROLL_LOOP(p)	RROP_UNROLL_LOOP32(p,-32)
-#endif /* LONG64 */
-#define RROP_UNROLL		(1<<RROP_UNROLL_SHIFT)
-#define RROP_UNROLL_MASK	(RROP_UNROLL-1)
-
-#define RROP_SPAN(pdst,nmiddle) {\
-    int part = (nmiddle) & RROP_UNROLL_MASK; \
-    (nmiddle) >>= RROP_UNROLL_SHIFT; \
-    (pdst) += part * (sizeof (CfbBits) / sizeof (*pdst)); \
-    switch (part) {\
-	RROP_UNROLL_CASE((CfbBits *) (pdst)) \
-    } \
-    while (--(nmiddle) >= 0) { \
-	(pdst) += RROP_UNROLL * (sizeof (CfbBits) / sizeof (*pdst)); \
-	RROP_UNROLL_LOOP((CfbBits *) (pdst)) \
-    } \
-}
-#else
-#define RROP_SPAN(pdst,nmiddle) \
-    while (--(nmiddle) >= 0) { \
-	RROP_SOLID((CfbBits *) (pdst)); \
-	(pdst) += sizeof (CfbBits) / sizeof (*pdst); \
-    }
-#endif
-
-#if !defined(UNIXCPP) || defined(ANSICPP)
-#define RROP_NAME_CAT(prefix,suffix)	prefix##suffix
-#else
-#define RROP_NAME_CAT(prefix,suffix)	prefix/**/suffix
-#endif
diff --git a/cfb/cfbscrinit.c b/cfb/cfbscrinit.c
deleted file mode 100644
index 6f9ba2e..0000000
--- a/cfb/cfbscrinit.c
+++ /dev/null
@@ -1,223 +0,0 @@
-/************************************************************
-Copyright 1987 by Sun Microsystems, Inc. Mountain View, CA.
-
-                    All Rights Reserved
-
-Permission  to  use,  copy,  modify,  and  distribute   this
-software  and  its documentation for any purpose and without
-fee is hereby granted, provided that the above copyright no-
-tice  appear  in all copies and that both that copyright no-
-tice and this permission notice appear in  supporting  docu-
-mentation,  and  that the names of Sun or The Open Group
-not be used in advertising or publicity pertaining to 
-distribution  of  the software  without specific prior 
-written permission. Sun and The Open Group make no 
-representations about the suitability of this software for 
-any purpose. It is provided "as is" without any express or 
-implied warranty.
-
-SUN DISCLAIMS ALL WARRANTIES WITH REGARD TO  THIS  SOFTWARE,
-INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
-NESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SUN BE  LI-
-ABLE  FOR  ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,  DATA  OR
-PROFITS,  WHETHER  IN  AN  ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
-THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-********************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "servermd.h"
-#include "scrnintstr.h"
-#include "pixmapstr.h"
-#include "resource.h"
-#include "colormap.h"
-#include "colormapst.h"
-#include "cfb.h"
-#include "mi.h"
-#include "mistruct.h"
-#include "dix.h"
-#include "cfbmskbits.h"
-#include "mibstore.h"
-
-Bool
-cfbCloseScreen (index, pScreen)
-    int		index;
-    ScreenPtr	pScreen;
-{
-    int	    d;
-    DepthPtr	depths = pScreen->allowedDepths;
-
-    for (d = 0; d < pScreen->numDepths; d++)
-	xfree (depths[d].vids);
-    xfree (depths);
-    xfree (pScreen->visuals);
-#ifdef CFB_NEED_SCREEN_PRIVATE
-    xfree (dixLookupPrivate(&pScreen->devPrivates, cfbScreenPrivateKey));
-#else
-    xfree (pScreen->devPrivate);
-#endif
-    return TRUE;
-}
-
-static void DestroyColormapNoop(
-        ColormapPtr pColormap)
-{
-    /* NOOP */
-}
-
-static void StoreColorsNoop(
-        ColormapPtr pColormap,
-        int ndef,
-        xColorItem * pdef)
-{
-    /* NOOP */
-}
-
-Bool
-cfbSetupScreen(pScreen, pbits, xsize, ysize, dpix, dpiy, width)
-    register ScreenPtr pScreen;
-    pointer pbits;		/* pointer to screen bitmap */
-    int xsize, ysize;		/* in pixels */
-    int dpix, dpiy;		/* dots per inch */
-    int width;			/* pixel width of frame buffer */
-{
-    if (!cfbAllocatePrivates(pScreen, NULL))
-	return FALSE;
-    pScreen->defColormap = FakeClientID(0);
-    /* let CreateDefColormap do whatever it wants for pixels */ 
-    pScreen->blackPixel = pScreen->whitePixel = (Pixel) 0;
-    pScreen->QueryBestSize = mfbQueryBestSizeWeak();
-    /* SaveScreen */
-    pScreen->GetImage = cfbGetImage;
-    pScreen->GetSpans = cfbGetSpans;
-    pScreen->CreateWindow = cfbCreateWindow;
-    pScreen->DestroyWindow = cfbDestroyWindow;
-    pScreen->PositionWindow = cfbPositionWindow;
-    pScreen->ChangeWindowAttributes = cfbChangeWindowAttributes;
-    pScreen->RealizeWindow = cfbMapWindow;
-    pScreen->UnrealizeWindow = cfbUnmapWindow;
-    pScreen->CopyWindow = cfbCopyWindow;
-    pScreen->CreatePixmap = cfbCreatePixmap;
-    pScreen->DestroyPixmap = cfbDestroyPixmap;
-    pScreen->RealizeFont = mfbRealizeFontWeak();
-    pScreen->UnrealizeFont = mfbUnrealizeFontWeak();
-    pScreen->CreateGC = cfbCreateGC;
-    pScreen->CreateColormap = cfbInitializeColormap;
-    pScreen->DestroyColormap = DestroyColormapNoop;
-    pScreen->InstallColormap = cfbInstallColormap;
-    pScreen->UninstallColormap = cfbUninstallColormap;
-    pScreen->ListInstalledColormaps = cfbListInstalledColormaps;
-    pScreen->StoreColors = StoreColorsNoop;
-    pScreen->ResolveColor = cfbResolveColor;
-    pScreen->BitmapToRegion = mfbPixmapToRegionWeak();
-
-    mfbRegisterCopyPlaneProc (pScreen, cfbCopyPlane);
-    return TRUE;
-}
-
-#ifdef CFB_NEED_SCREEN_PRIVATE
-Bool
-cfbCreateScreenResources(pScreen)
-    ScreenPtr pScreen;
-{
-    Bool retval;
-
-    pointer oldDevPrivate = pScreen->devPrivate;
-    pScreen->devPrivate = dixLookupPrivate(&pScreen->devPrivates,
-					   cfbScreenPrivateKey);
-    retval = miCreateScreenResources(pScreen);
-    dixSetPrivate(&pScreen->devPrivates, cfbScreenPrivateKey,
-		  pScreen->devPrivate);
-    pScreen->devPrivate = oldDevPrivate;
-    return retval;
-}
-#endif
-
-Bool
-cfbFinishScreenInit(pScreen, pbits, xsize, ysize, dpix, dpiy, width)
-    register ScreenPtr pScreen;
-    pointer pbits;		/* pointer to screen bitmap */
-    int xsize, ysize;		/* in pixels */
-    int dpix, dpiy;		/* dots per inch */
-    int width;			/* pixel width of frame buffer */
-{
-#ifdef CFB_NEED_SCREEN_PRIVATE
-    pointer oldDevPrivate;
-#endif
-    VisualPtr	visuals;
-    DepthPtr	depths;
-    int		nvisuals;
-    int		ndepths;
-    int		rootdepth;
-    VisualID	defaultVisual;
-
-    rootdepth = 0;
-    if (!cfbInitVisuals (&visuals, &depths, &nvisuals, &ndepths, &rootdepth,
-			 &defaultVisual,((unsigned long)1<<(PSZ-1)), 8))
-	return FALSE;
-#ifdef CFB_NEED_SCREEN_PRIVATE
-    oldDevPrivate = pScreen->devPrivate;
-#endif
-    if (! miScreenInit(pScreen, pbits, xsize, ysize, dpix, dpiy, width,
-			rootdepth, ndepths, depths,
-			defaultVisual, nvisuals, visuals))
-	return FALSE;
-    /* overwrite miCloseScreen with our own */
-    pScreen->CloseScreen = cfbCloseScreen;
-#ifdef CFB_NEED_SCREEN_PRIVATE
-    pScreen->CreateScreenResources = cfbCreateScreenResources;
-    dixSetPrivate(&pScreen->devPrivates, cfbScreenPrivateKey,
-		  pScreen->devPrivate);
-    pScreen->devPrivate = oldDevPrivate;
-#endif
-    pScreen->GetScreenPixmap = cfbGetScreenPixmap;
-    pScreen->SetScreenPixmap = cfbSetScreenPixmap;
-    return TRUE;
-}
-
-/* dts * (inch/dot) * (25.4 mm / inch) = mm */
-Bool
-cfbScreenInit(pScreen, pbits, xsize, ysize, dpix, dpiy, width)
-    register ScreenPtr pScreen;
-    pointer pbits;		/* pointer to screen bitmap */
-    int xsize, ysize;		/* in pixels */
-    int dpix, dpiy;		/* dots per inch */
-    int width;			/* pixel width of frame buffer */
-{
-    if (!cfbSetupScreen(pScreen, pbits, xsize, ysize, dpix, dpiy, width))
-	return FALSE;
-    return cfbFinishScreenInit(pScreen, pbits, xsize, ysize, dpix, dpiy, width);
-}
-
-PixmapPtr
-cfbGetScreenPixmap(pScreen)
-    ScreenPtr pScreen;
-{
-#ifdef CFB_NEED_SCREEN_PRIVATE
-    return (PixmapPtr)dixLookupPrivate(&pScreen->devPrivates,
-				       cfbScreenPrivateKey);
-#else
-    return (PixmapPtr)pScreen->devPrivate;
-#endif
-}
-
-void
-cfbSetScreenPixmap(pPix)
-    PixmapPtr pPix;
-{
-#ifdef CFB_NEED_SCREEN_PRIVATE
-    if (pPix)
-	dixSetPrivate(&pPix->drawable.pScreen->devPrivates,
-		      cfbScreenPrivateKey, pPix);
-#else
-    if (pPix)
-	pPix->drawable.pScreen->devPrivate = (pointer)pPix;
-#endif
-}
diff --git a/cfb/cfbsetsp.c b/cfb/cfbsetsp.c
deleted file mode 100644
index a000fd9..0000000
--- a/cfb/cfbsetsp.c
+++ /dev/null
@@ -1,316 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "servermd.h"
-
-#include "misc.h"
-#include "regionstr.h"
-#include "gcstruct.h"
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include <mergerop.h>
-
-/* cfbSetScanline -- copies the bits from psrc to the drawable starting at
- * (xStart, y) and continuing to (xEnd, y).  xOrigin tells us where psrc 
- * starts on the scanline. (I.e., if this scanline passes through multiple
- * boxes, we may not want to start grabbing bits at psrc but at some offset
- * further on.) 
- */
-void
-cfbSetScanline(y, xOrigin, xStart, xEnd, psrc, alu, pdstBase, widthDst, planemask)
-    int			y;
-    int			xOrigin;	/* where this scanline starts */
-    int			xStart;		/* first bit to use from scanline */
-    int			xEnd;		/* last bit to use from scanline + 1 */
-    register unsigned int *psrc;
-    register int	alu;		/* raster op */
-    int			*pdstBase;	/* start of the drawable */
-    int			widthDst;	/* width of drawable in words */
-    unsigned long	planemask;
-{
-    int			w;		/* width of scanline in bits */
-    register int	*pdst;		/* where to put the bits */
-    register int	tmpSrc;		/* scratch buffer to collect bits in */
-    int			offSrc;
-    int			nl;
-#if PSZ == 24
-    register char *psrcb, *pdstb;
-    register int	xIndex;
-#else
-    int			dstBit;		/* offset in bits from beginning of
-					 * word */
-    register int	nstart; 	/* number of bits from first partial */
-#if PSZ != 32 || PPW != 1
-    register int	nend; 		/* " " last partial word */
-#endif
-    int			startmask, endmask, nlMiddle;
-#endif
-    DeclareMergeRop()
-
-    InitializeMergeRop(alu,planemask);
-#if PSZ == 24
-    pdst = pdstBase + (y * widthDst);
-    xIndex = xStart;
-    pdstb = (char *)pdst + (xStart * 3);
-    offSrc = xStart - xOrigin;
-    psrcb = (char *)psrc + (offSrc * 3);
-#else
-    pdst = pdstBase + (y * widthDst) + (xStart >> PWSH); 
-    psrc += (xStart - xOrigin) >> PWSH;
-    offSrc = (xStart - xOrigin) & PIM;
-#endif
-    w = xEnd - xStart;
-
-#if PSZ == 24
-    nl = w;
-    while (nl--){
-      psrc = (unsigned int *)((unsigned long)psrcb & ~0x03);
-      getbits24(psrc, tmpSrc, offSrc);
-      pdst = (int *)((unsigned long)pdstb & ~0x03);
-      DoMergeRop24(tmpSrc, pdst, xIndex);
-      offSrc++;
-      psrcb += 3;
-      xIndex++;
-      pdstb += 3;
-    } 
-#else /* PSZ == 24 */
-    dstBit = xStart & PIM;
-    if (dstBit + w <= PPW) 
-    { 
-	maskpartialbits(dstBit, w, startmask);
-	endmask = 0;
-	nlMiddle = 0;
-    } 
-    else 
-    { 
-	maskbits(xStart, w, startmask, endmask, nlMiddle);
-    }
-    if (startmask) 
-	nstart = PPW - dstBit; 
-    else 
-	nstart = 0; 
-#if PSZ != 32 || PPW != 1
-    if (endmask) 
-	nend = xEnd & PIM; 
-    else 
-	nend = 0; 
-#endif
-    if (startmask) 
-    { 
-	getbits(psrc, offSrc, nstart, tmpSrc);
-	putbitsmropshort(tmpSrc, dstBit, nstart, pdst);
-	pdst++; 
-	offSrc += nstart;
-	if (offSrc > PLST)
-	{
-	    psrc++;
-	    offSrc -= PPW;
-	}
-    } 
-    nl = nlMiddle; 
-    while (nl--) 
-    { 
-	getbits(psrc, offSrc, PPW, tmpSrc);
-	*pdst = DoMergeRop(tmpSrc, *pdst);
-	pdst++; 
-	psrc++; 
-    } 
-    if (endmask) 
-    { 
-	getbits(psrc, offSrc, nend, tmpSrc);
-	putbitsmropshort(tmpSrc, 0, nend, pdst);
-    } 
-#endif /* PSZ == 24 */
-}
-
-
-
-/* SetSpans -- for each span copy pwidth[i] bits from psrc to pDrawable at
- * ppt[i] using the raster op from the GC.  If fSorted is TRUE, the scanlines
- * are in increasing Y order.
- * Source bit lines are server scanline padded so that they always begin
- * on a word boundary.
- */ 
-void
-cfbSetSpans(pDrawable, pGC, pcharsrc, ppt, pwidth, nspans, fSorted)
-    DrawablePtr		pDrawable;
-    GCPtr		pGC;
-    char		*pcharsrc;
-    register DDXPointPtr ppt;
-    int			*pwidth;
-    int			nspans;
-    int			fSorted;
-{
-    unsigned int	*psrc = (unsigned int *)pcharsrc;
-    CfbBits	*pdstBase;	/* start of dst bitmap */
-    int 		widthDst;	/* width of bitmap in words */
-    register BoxPtr 	pbox, pboxLast, pboxTest;
-    register DDXPointPtr pptLast;
-    int 		alu;
-    RegionPtr 		prgnDst;
-    int			xStart, xEnd;
-    int			yMax;
-
-    alu = pGC->alu;
-    prgnDst = cfbGetCompositeClip(pGC);
-    pptLast = ppt + nspans;
-
-    cfbGetLongWidthAndPointer (pDrawable, widthDst, pdstBase)
-
-    yMax = (int) pDrawable->y + (int) pDrawable->height;
-
-    pbox = REGION_RECTS(prgnDst);
-    pboxLast = pbox + REGION_NUM_RECTS(prgnDst);
-
-    if(fSorted)
-    {
-    /* scan lines sorted in ascending order. Because they are sorted, we
-     * don't have to check each scanline against each clip box.  We can be
-     * sure that this scanline only has to be clipped to boxes at or after the
-     * beginning of this y-band 
-     */
-	pboxTest = pbox;
-	while(ppt < pptLast)
-	{
-	    pbox = pboxTest;
-	    if(ppt->y >= yMax)
-		break;
-	    while(pbox < pboxLast)
-	    {
-		if(pbox->y1 > ppt->y)
-		{
-		    /* scanline is before clip box */
-		    break;
-		}
-		else if(pbox->y2 <= ppt->y)
-		{
-		    /* clip box is before scanline */
-		    pboxTest = ++pbox;
-		    continue;
-		}
-		else if(pbox->x1 > ppt->x + *pwidth) 
-		{
-		    /* clip box is to right of scanline */
-		    break;
-		}
-		else if(pbox->x2 <= ppt->x)
-		{
-		    /* scanline is to right of clip box */
-		    pbox++;
-		    continue;
-		}
-
-		/* at least some of the scanline is in the current clip box */
-		xStart = max(pbox->x1, ppt->x);
-		xEnd = min(ppt->x + *pwidth, pbox->x2);
-		cfbSetScanline(ppt->y, ppt->x, xStart, xEnd, psrc, alu,
-		    (int *)pdstBase, widthDst, pGC->planemask);
-		if(ppt->x + *pwidth <= pbox->x2)
-		{
-		    /* End of the line, as it were */
-		    break;
-		}
-		else
-		    pbox++;
-	    }
-	    /* We've tried this line against every box; it must be outside them
-	     * all.  move on to the next point */
-	    ppt++;
-	    psrc += PixmapWidthInPadUnits(*pwidth, pDrawable->depth);
-	    pwidth++;
-	}
-    }
-    else
-    {
-    /* scan lines not sorted. We must clip each line against all the boxes */
-	while(ppt < pptLast)
-	{
-	    if(ppt->y >= 0 && ppt->y < yMax)
-	    {
-		
-		for(pbox = REGION_RECTS(prgnDst); pbox< pboxLast; pbox++)
-		{
-		    if(pbox->y1 > ppt->y)
-		    {
-			/* rest of clip region is above this scanline,
-			 * skip it */
-			break;
-		    }
-		    if(pbox->y2 <= ppt->y)
-		    {
-			/* clip box is below scanline */
-			pbox++;
-			break;
-		    }
-		    if(pbox->x1 <= ppt->x + *pwidth &&
-		       pbox->x2 > ppt->x)
-		    {
-			xStart = max(pbox->x1, ppt->x);
-			xEnd = min(pbox->x2, ppt->x + *pwidth);
-			cfbSetScanline(ppt->y, ppt->x, xStart, xEnd, psrc, alu,
-			    (int *)pdstBase, widthDst, pGC->planemask);
-		    }
-
-		}
-	    }
-	psrc += PixmapWidthInPadUnits(*pwidth, pDrawable->depth);
-	ppt++;
-	pwidth++;
-	}
-    }
-}
-
diff --git a/cfb/cfbsolid.c b/cfb/cfbsolid.c
deleted file mode 100644
index 6b8238d..0000000
--- a/cfb/cfbsolid.c
+++ /dev/null
@@ -1,1365 +0,0 @@
-/*
- *
-Copyright 1990, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- */
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "servermd.h"
-#include "gcstruct.h"
-#include "window.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "windowstr.h"
-
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "cfbrrop.h"
-
-#include "mi.h"
-#include "mispans.h"
-
-#if defined(FAST_CONSTANT_OFFSET_MODE) && (RROP != GXcopy)
-# define Expand(left,right,leftAdjust) {\
-    int part = nmiddle & 3; \
-    int widthStep; \
-    widthStep = widthDst - nmiddle - leftAdjust; \
-    nmiddle >>= 2; \
-    pdst = pdstRect; \
-    while (h--) { \
-	left \
-	pdst += part; \
-	switch (part) { \
-	    RROP_UNROLL_CASE3(pdst) \
-	} \
-	m = nmiddle; \
-	while (m) { \
-	    pdst += 4; \
-	    RROP_UNROLL_LOOP4(pdst,-4) \
-	    m--; \
-	} \
-	right \
-	pdst += widthStep; \
-    } \
-}
-#else
-# ifdef RROP_UNROLL
-#  define Expand(left,right,leftAdjust) {\
-    int part = nmiddle & RROP_UNROLL_MASK; \
-    int widthStep; \
-    widthStep = widthDst - nmiddle - leftAdjust; \
-    nmiddle >>= RROP_UNROLL_SHIFT; \
-    pdst = pdstRect; \
-    while (h--) { \
-	left \
-	pdst += part; \
-	switch (part) { \
-	    RROP_UNROLL_CASE(pdst) \
-	} \
-	m = nmiddle; \
-	while (m) { \
-	    pdst += RROP_UNROLL; \
-	    RROP_UNROLL_LOOP(pdst) \
-	    m--; \
-	} \
-	right \
-	pdst += widthStep; \
-    } \
-}
-
-# else
-#  define Expand(left, right, leftAdjust) { \
-    while (h--) { \
-	pdst = pdstRect; \
-	left \
-	m = nmiddle; \
-	while (m--) {\
-	    RROP_SOLID(pdst); \
-	    pdst++; \
-	} \
-	right \
-	pdstRect += widthDst; \
-    } \
-}
-# endif
-#endif
-	
-
-void
-RROP_NAME(cfbFillRectSolid) (pDrawable, pGC, nBox, pBox)
-    DrawablePtr	    pDrawable;
-    GCPtr	    pGC;
-    int		    nBox;
-    BoxPtr	    pBox;
-{
-    register int    m;
-    register CfbBits   *pdst;
-    RROP_DECLARE
-    CfbBits   *pdstBase, *pdstRect;
-    int		    nmiddle;
-    int		    h;
-    int		    w;
-    int		    widthDst;
-#if PSZ == 24
-    int		    leftIndex, rightIndex;
-#else
-    register CfbBits   leftMask, rightMask;
-#endif
-
-    cfbGetLongWidthAndPointer (pDrawable, widthDst, pdstBase)
-
-    RROP_FETCH_GC(pGC)
-    
-    for (; nBox; nBox--, pBox++)
-    {
-    	pdstRect = pdstBase + pBox->y1 * widthDst;
-    	h = pBox->y2 - pBox->y1;
-	w = pBox->x2 - pBox->x1;
-#if PSZ == 8
-	if (w == 1)
-	{
-	    register char    *pdstb = ((char *) pdstRect) + pBox->x1;
-	    int	    incr = widthDst * PGSZB;
-
-	    while (h--)
-	    {
-		RROP_SOLID (pdstb);
-		pdstb += incr;
-	    }
-	}
-	else
-	{
-#endif
-#if PSZ == 24
-	leftIndex = pBox->x1 &3;
-/*	rightIndex = ((leftIndex+w)<5)?0:pBox->x2 &3;*/
-	rightIndex = pBox->x2 &3;
-
-	nmiddle = w - rightIndex;
-	if(leftIndex){
-	  nmiddle -= (4 - leftIndex);
-	}
-	nmiddle >>= 2;
-	if(nmiddle < 0)
-	  nmiddle = 0;
-
-	pdstRect += (pBox->x1 * 3) >> 2;
-	pdst = pdstRect;	
-	switch(leftIndex+w){
-	case 4:
-	    switch(leftIndex){
-	    case 0:
-		while(h--){
-#if RROP == GXcopy
-		    *pdst++ = piQxelXor[0];
-		    *pdst++ = piQxelXor[1];
-		    *pdst-- = piQxelXor[2];
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= piQxelXor[0];
-		    *pdst++ ^= piQxelXor[1];
-		    *pdst-- ^= piQxelXor[2];
-#endif
-#if RROP == GXand
-		    *pdst++ &= piQxelAnd[0];
-		    *pdst++ &= piQxelAnd[1];
-		    *pdst-- &= piQxelAnd[2];
-#endif
-#if RROP == GXor
-		    *pdst++ |= piQxelOr[0];
-		    *pdst++ |= piQxelOr[1];
-		    *pdst-- |= piQxelOr[2];
-#endif
-#if RROP == GXset
-		    *pdst = DoRRop((*pdst), piQxelAnd[0], piQxelXor[0]);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[2], piQxelXor[2]);
-		    pdst--;
-#endif
-		    pdst--;
-		    pdst += widthDst;
-		}
-		break;
-	    case 1:
-		while(h--){
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-		    pdst++;
-		    *pdst++ = piQxelXor[1];
-		    *pdst-- = piQxelXor[2];
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= (piQxelXor[0] & 0xFF000000);
-		    *pdst++ ^= piQxelXor[1];
-		    *pdst-- ^= piQxelXor[2];
-#endif
-#if RROP == GXand
-		    *pdst++ &= (piQxelAnd[0] | 0x00FFFFFF);
-		    *pdst++ &= piQxelAnd[1];
-		    *pdst-- &= piQxelAnd[2];
-#endif
-#if RROP == GXor
-		    *pdst++ |= (piQxelOr[0] & 0xFF000000);
-		    *pdst++ |= piQxelOr[1];
-		    *pdst-- |= piQxelOr[2];
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[0], piQxelXor[0], 0xFF000000);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[2], piQxelXor[2]);
-		    pdst--;
-#endif
-		    pdst--;
-		    pdst += widthDst;
-		}
-		break;
-	    case 2:
-		while(h--){
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFFFF) | (piQxelXor[1] & 0xFFFF0000);
-		    pdst++;
-		    *pdst-- = piQxelXor[2];
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= (piQxelXor[1] & 0xFFFF0000);
-		    *pdst-- ^= piQxelXor[2];
-#endif
-#if RROP == GXand
-		    *pdst++ &= (piQxelAnd[1] | 0xFFFF);
-		    *pdst-- &= piQxelAnd[2];
-#endif
-#if RROP == GXor
-		    *pdst++ |= (piQxelOr[1] & 0xFFFF0000);
-		    *pdst-- |= piQxelOr[2];
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF0000);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[2], piQxelXor[2]);
-		    pdst--;
-#endif
-		    pdst += widthDst;
-		}
-		break;
-	    case 3:
-		while(h--){
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFF) | (piQxelXor[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXxor
-		    *pdst ^= (piQxelXor[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXand
-		    *pdst &= (piQxelAnd[2] | 0xFF);
-#endif
-#if RROP == GXor
-		    *pdst |= (piQxelOr[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFFFFFF00);
-#endif
-		    pdst += widthDst;
-		}
-		break;
-	    }
-	    break;
-	case 3:
-	    switch(leftIndex){
-	    case 0:
-		while(h--){
-#if RROP == GXcopy
-		    *pdst++ = piQxelXor[0];
-		    *pdst++ = piQxelXor[1];
-		    *pdst = ((*pdst) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		    pdst--;
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= piQxelXor[0];
-		    *pdst++ ^= piQxelXor[1];
-		    *pdst-- ^= (piQxelXor[2] & 0xFF);
-#endif
-#if RROP == GXand
-		    *pdst++ &= piQxelAnd[0];
-		    *pdst++ &= piQxelAnd[1];
-		    *pdst-- &= (piQxeAnd[2] | 0xFFFFFF00);
-#endif
-#if RROP == GXor
-		    *pdst++ |= piQxelOr[0];
-		    *pdst++ |= piQxelOr[1];
-		    *pdst-- |= (piQxelOr[2] & 0xFF);
-#endif
-#if RROP == GXset
-		    *pdst = DoRRop((*pdst), piQxelAnd[0], piQxelXor[0]);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-		    pdst++;
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFF);
-		    pdst--;
-#endif
-		    pdst--;
-		    pdst += widthDst;
-		}
-		break;
-	    case 1:
-		while(h--){
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-		    pdst++;
-		    *pdst++ = piQxelXor[1];
-		    *pdst = ((*pdst) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		    pdst--;
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= (piQxelXor[0] & 0xFF000000);
-		    *pdst++ ^= piQxelXor[1];
-		    *pdst-- ^= (piQxelXor[2] & 0xFF);
-#endif
-#if RROP == GXand
-		    *pdst++ &= (piQxelAnd[0] | 0x00FFFFFF);
-		    *pdst++ &= piQxelAnd[1];
-		    *pdst-- &= (piQxelAnd[2] | 0xFFFFFF00);
-#endif
-#if RROP == GXor
-		    *pdst++ |= (piQxelOr[0] & 0xFF000000);
-		    *pdst++ |= piQxelOr[1];
-		    *pdst-- |= (piQxelOr[2] & 0xFF);
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[0], piQxelXor[0], 0xFF000000);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-		    pdst++;
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFF);
-		    pdst--;
-#endif
-		    pdst--;
-		    pdst += widthDst;
-		}
-		break;
-	    case 2:
-		while(h--){
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFFFF) | (piQxelXor[1] & 0xFFFF0000);
-		    pdst++;
-		    *pdst = ((*pdst) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		    pdst--;
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= (piQxelXor[1] & 0xFFFF0000);
-		    *pdst-- ^= (piQxelXor[2] & 0xFF);
-#endif
-#if RROP == GXand
-		    *pdst++ &= (piQxelAnd[1] | 0xFFFF);
-		    *pdst-- &= (piQxelAnd[2] | 0xFFFFFF00);
-#endif
-#if RROP == GXor
-		    *pdst++ |= (piQxelOr[1] & 0xFFFF0000);
-		    *pdst-- |= (piQxelOr[2] & 0xFF);
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF0000);
-		    pdst++;
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFF);
-		    pdst--;
-#endif
-		    pdst += widthDst;
-		}
-		break;
-	    case 3:
-		while(h--){
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFF) | (piQxelXor[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXxor
-		    *pdst ^= (piQxelXor[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXand
-		    *pdst &= (piQxelAnd[2] | 0xFF);
-#endif
-#if RROP == GXor
-		    *pdst |= (piQxelOr[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFFFFFF00);
-#endif
-		    pdst += widthDst;
-		}
-		break;
-	    }
-	    break;
-	case 2: /* leftIndex + w = 2*/
-	    switch(leftIndex){
-	    case 2:
-		while(h--){
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFFFF) | (piQxelXor[1] & 0xFFFF0000);
-		    pdst++;
-		    *pdst = ((*pdst) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		    pdst--;
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= (piQxelXor[1] & 0xFFFF0000);
-		    *pdst-- ^= (piQxelXor[2] & 0xFF);
-#endif
-#if RROP == GXand
-		    *pdst++ &= (piQxelAnd[1] | 0xFFFF0000);
-		    *pdst-- &= (piQxelAnd[2] | 0xFF);
-#endif
-#if RROP == GXor
-		    *pdst++ |= (piQxelOr[1] & 0xFFFF0000);
-		    *pdst-- |= (piQxelOr[2] & 0xFF);
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF0000);
-		    pdst++;
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFF);
-		    pdst--;
-#endif
-		    pdst += widthDst;
-		  }
-		break;
-	    case 1:
-		while(h--){
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-		    pdst++;
-		    *pdst = ((*pdst) & 0xFFFF0000) | (piQxelXor[1] & 0xFFFF);
-		    pdst--;
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= (piQxelXor[0] & 0xFF000000);
-		    *pdst-- ^= (piQxelXor[1] & 0xFFFF);
-#endif
-#if RROP == GXand
-		    *pdst++ &= (piQxelAnd[0] | 0xFFFFFF);
-		    *pdst-- &= (piQxelAnd[1] | 0xFFFF0000);
-#endif
-#if RROP == GXor
-		    *pdst++ |= (piQxelOr[0] & 0xFF000000);
-		    *pdst-- |= (piQxelOr[1] & 0xFFFF);
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[0], piQxelXor[0], 0xFF000000);
-		    pdst++;
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF);
-		    pdst--;
-#endif
-		    pdst += widthDst;
-		  }
-		break;
-	    case 0: /*case 2 leftIndex == 0 */
-		while(h--){
-#if RROP == GXcopy
-		    *pdst++ = piQxelXor[0];
-		    *pdst = ((*pdst) & 0xFFFF0000) | (piQxelXor[1] & 0xFFFF);
-		    pdst--;
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= piQxelXor[0];
-		    *pdst-- ^= (piQxelXor[1] & 0xFFFF);
-#endif
-#if RROP == GXand
-		    *pdst++ &= piQxelAnd[0];
-		    *pdst-- &= (piQxelAnd[1] | 0xFFFF0000);
-#endif
-#if RROP == GXor
-		    *pdst++ |= piQxelOr[0];
-		    *pdst-- |= (piQxelOr[1] & 0xFFFF);
-#endif
-#if RROP == GXset
-		    *pdst = DoRRop((*pdst), piQxelAnd[0], piQxelXor[0]);
-		    pdst++;
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF);
-		    pdst--;
-#endif
-		    pdst += widthDst;
-		}
-		break;
-	    }
-	    break;
-	case 1: /*only if leftIndex = 0 and w = 1*/
-	    while(h--){
-#if RROP == GXcopy
-		*pdst = ((*pdst) & 0xFF000000) | (piQxelXor[0] & 0xFFFFFF);
-#endif
-#if RROP == GXxor
-		*pdst ^= (piQxelXor[0] & 0xFFFFFF);
-#endif
-#if RROP == GXand
-		*pdst &= (piQxelAnd[0] | 0xFF000000);
-#endif
-#if RROP == GXor
-		*pdst |= (piQxelOr[0] & 0xFFFFFF);
-#endif
-#if RROP == GXset
-		*pdst = DoMaskRRop((*pdst), piQxelAnd[0], piQxelXor[0], 0xFFFFFF);
-#endif
-		pdst += widthDst;
-	    }
-	    break;
-	case 0: /*never*/
-	    break;
-	default:
-	    {
-		while(h--){
-		    pdst = pdstRect;
-		    switch(leftIndex){
-		    case 0:
-			break;
-		    case 1:
-#if RROP == GXcopy
-			*pdst = ((*pdst) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-			pdst++;
-			*pdst++ = piQxelXor[1];
-			*pdst++ = piQxelXor[2];
-#endif
-#if RROP == GXxor
-			*pdst++ ^= (piQxelXor[0] & 0xFF000000);
-			*pdst++ ^= piQxelXor[1];
-			*pdst++ ^= piQxelXor[2];
-#endif
-#if RROP == GXand
-			*pdst++ &= (piQxelAnd[0] | 0xFFFFFF);
-			*pdst++ &= piQxelAnd[1];
-			*pdst++ &= piQxelAnd[2];
-#endif
-#if RROP == GXor
-			*pdst++ |= (piQxelOr[0] & 0xFF000000);
-			*pdst++ |= piQxelOr[1];
-			*pdst++ |= piQxelOr[2];
-#endif
-#if RROP == GXset
-			*pdst = DoMaskRRop((*pdst), piQxelAnd[0], piQxelXor[0], 0xFF000000);
-			pdst++;
-			*pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-			pdst++;
-			*pdst = DoRRop((*pdst), piQxelAnd[2], piQxelXor[2]);
-			pdst++;
-#endif
-		    break;
-		    case 2:
-#if RROP == GXcopy
-			*pdst = (((*pdst) & 0xFFFF) | (piQxelXor[1] & 0xFFFF0000));
-			pdst++;
-			*pdst++ = piQxelXor[2];
-#endif
-#if RROP == GXxor
-			*pdst++ ^=(piQxelXor[1] & 0xFFFF0000);
-			*pdst++ ^= piQxelXor[2];
-#endif
-#if RROP == GXand
-			*pdst++ &= (piQxelAnd[1] | 0xFFFF);
-			*pdst++ &= piQxelAnd[2];
-#endif
-#if RROP == GXor
-			*pdst++ |= (piQxelOr[1] & 0xFFFF0000);
-			*pdst++ |= piQxelOr[2];
-#endif
-#if RROP == GXset
-			*pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF0000);
-			pdst++;
-			*pdst = DoRRop((*pdst), piQxelAnd[2], piQxelXor[2]);
-			pdst++;
-#endif
-			break;
-		    case 3:
-#if RROP == GXcopy
-			*pdst = ((*pdst) & 0xFF) | (piQxelXor[2] & 0xFFFFFF00);
-			pdst++;
-#endif
-#if RROP == GXxor
-			*pdst++ ^= (piQxelXor[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXand
-			*pdst++ &= (piQxelAnd[2] | 0xFF);
-#endif
-#if RROP == GXor
-			*pdst++ |= (piQxelOr[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXset
-			*pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFFFFFF00);
-			pdst++;
-#endif
-			break;
-		      }
-		    m = nmiddle;
-		    while(m--){
-#if RROP == GXcopy
-			*pdst++ = piQxelXor[0];
-			*pdst++ = piQxelXor[1];
-			*pdst++ = piQxelXor[2];
-#endif
-#if RROP == GXxor
-			*pdst++ ^= piQxelXor[0];
-			*pdst++ ^= piQxelXor[1];
-			*pdst++ ^= piQxelXor[2];
-#endif
-#if RROP == GXand
-			*pdst++ &= piQxelAnd[0];
-			*pdst++ &= piQxelAnd[1];
-			*pdst++ &= piQxelAnd[2];
-#endif
-#if RROP == GXor
-			*pdst++ |= piQxelOr[0];
-			*pdst++ |= piQxelOr[1];
-			*pdst++ |= piQxelOr[2];
-#endif
-#if RROP == GXset
-			*pdst = DoRRop((*pdst), piQxelAnd[0], piQxelXor[0]);
-			pdst++;
-			*pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-			pdst++;
-			*pdst = DoRRop((*pdst), piQxelAnd[2], piQxelXor[2]);
-			pdst++;
-#endif
-		}
-		switch(rightIndex){
-		case 0:
-		  break;
-		case 1:
-#if RROP == GXcopy
-		  *pdst = ((*pdst) & 0xFF000000) | (piQxelXor[0] & 0xFFFFFF);
-		  pdst++;
-#endif
-#if RROP == GXxor
-		  *pdst++ ^= (piQxelXor[0] & 0xFFFFFF);
-#endif
-#if RROP == GXand
-		  *pdst++ &= (piQxelAnd[0] | 0xFF);
-#endif
-#if RROP == GXor
-		  *pdst++ |= (piQxelOr[0] & 0xFFFFFF);
-#endif
-#if RROP == GXset
-		  *pdst = DoMaskRRop((*pdst), piQxelAnd[0], piQxelXor[0], 0xFFFFFF);
-		  pdst++;
-#endif
-		  break;
-		case 2:
-#if RROP == GXcopy
-		  *pdst++ = piQxelXor[0];
-		  *pdst = ((*pdst) & 0xFFFF0000) | (piQxelXor[1] & 0xFFFF);
-		  pdst++;
-#endif
-#if RROP == GXxor
-		  *pdst++ ^= piQxelXor[0];
-		  *pdst++ ^= (piQxelXor[1] & 0xFFFF);
-#endif
-#if RROP == GXand
-		  *pdst++ &= piQxelAnd[0];
-		  *pdst++ &= (piQxelAnd[1] | 0xFFFF0000);
-#endif
-#if RROP == GXor
-		  *pdst++ |= piQxelOr[0];
-		  *pdst++ |= (piQxelOr[1] & 0xFFFF);
-#endif
-#if RROP == GXset
-		  *pdst = DoRRop((*pdst), piQxelAnd[0], piQxelXor[0]);
-		  pdst++;
-		  *pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF);
-		  pdst++;
-#endif
-		  break;
-		case 3:
-#if RROP == GXcopy
-		  *pdst++ = piQxelXor[0];
-		  *pdst++ = piQxelXor[1];
-		  *pdst = ((*pdst) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		  pdst++;
-#endif
-#if RROP == GXxor
-		  *pdst++ ^= piQxelXor[0];
-		  *pdst++ ^= piQxelXor[1];
-		  *pdst++ ^= (piQxelXor[2] & 0xFF);
-#endif
-#if RROP == GXand
-		  *pdst++ &= piQxelAnd[0];
-		  *pdst++ &= piQxelAnd[1];
-		  *pdst++ &= (piQxelAnd[2] | 0xFFFFFF00);
-#endif
-#if RROP == GXor
-		  *pdst++ |= piQxelOr[0];
-		  *pdst++ |= piQxelOr[1];
-		  *pdst++ |= (piQxelOr[2] & 0xFF);
-#endif
-#if RROP == GXset
-		  *pdst = DoRRop((*pdst), piQxelAnd[0], piQxelXor[0]);
-		  pdst++;
-		  *pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-		  pdst++;
-		  *pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFF);
-		  pdst++;
-#endif
-		  break;
-		}
-		pdstRect += widthDst;
-	    }
-	}
-	}
-#else /* PSZ != 24 */
-	pdstRect += (pBox->x1 >> PWSH);
-	if ((pBox->x1 & PIM) + w <= PPW)
-	{
-	    maskpartialbits(pBox->x1, w, leftMask);
-	    pdst = pdstRect;
-	    while (h--) {
-		RROP_SOLID_MASK (pdst, leftMask);
-		pdst += widthDst;
-	    }
-	}
-	else
-	{
-	    maskbits (pBox->x1, w, leftMask, rightMask, nmiddle);
-	    if (leftMask)
-	    {
-		if (rightMask)	/* left mask and right mask */
-		{
-		    Expand(RROP_SOLID_MASK (pdst, leftMask); pdst++;,
-			   RROP_SOLID_MASK (pdst, rightMask);, 1)
-		}
-		else	/* left mask and no right mask */
-		{
-		    Expand(RROP_SOLID_MASK (pdst, leftMask); pdst++;,
-			   ;, 1)
-		}
-	    }
-	    else
-	    {
-		if (rightMask)	/* no left mask and right mask */
-		{
-		    Expand(;,
-			   RROP_SOLID_MASK (pdst, rightMask);, 0)
-		}
-		else	/* no left mask and no right mask */
-		{
-		    Expand(;,
-			    ;, 0)
-		}
-	    }
-	}
-#endif
-#if PSZ == 8
-	}
-#endif
-    }
-    RROP_UNDECLARE
-}
-
-void
-RROP_NAME(cfbSolidSpans) (pDrawable, pGC, nInit, pptInit, pwidthInit, fSorted)
-    DrawablePtr pDrawable;
-    GCPtr	pGC;
-    int		nInit;			/* number of spans to fill */
-    DDXPointPtr pptInit;		/* pointer to list of start points */
-    int		*pwidthInit;		/* pointer to list of n widths */
-    int 	fSorted;
-{
-    CfbBits   *pdstBase;
-    int		    widthDst;
-
-    RROP_DECLARE
-    
-    register CfbBits  *pdst;
-    register int	    nlmiddle;
-    register int	    w;
-    int			    x;
-    
-				/* next three parameters are post-clip */
-    int		    n;		/* number of spans to fill */
-    DDXPointPtr	    ppt;	/* pointer to list of start points */
-    int		    *pwidthFree;/* copies of the pointers to free */
-    DDXPointPtr	    pptFree;
-    int		    *pwidth;
-    cfbPrivGCPtr    devPriv;
-#if PSZ == 24
-    int		    leftIndex, rightIndex;
-#else
-    register CfbBits  startmask, endmask;
-#endif
-
-    devPriv = cfbGetGCPrivate(pGC);
-    RROP_FETCH_GCPRIV(devPriv)
-    n = nInit * miFindMaxBand(pGC->pCompositeClip);
-    pwidthFree = (int *)xalloc(n * sizeof(int));
-    pptFree = (DDXPointRec *)xalloc(n * sizeof(DDXPointRec));
-    if(!pptFree || !pwidthFree)
-    {
-	if (pptFree) xfree(pptFree);
-	if (pwidthFree) xfree(pwidthFree);
-	return;
-    }
-    pwidth = pwidthFree;
-    ppt = pptFree;
-    n = miClipSpans(pGC->pCompositeClip, pptInit, pwidthInit, nInit,
-		     ppt, pwidth, fSorted);
-
-    cfbGetLongWidthAndPointer (pDrawable, widthDst, pdstBase)
-
-    while (n--)
-    {
-	x = ppt->x;
-	pdst = pdstBase + (ppt->y * widthDst);
-	++ppt;
-	w = *pwidth++;
-	if (!w)
-	    continue;
-#if PSZ == 24
-	leftIndex = x &3;
-/*	rightIndex = ((leftIndex+w)<5)?0:(x+w)&3;*/
-	rightIndex = (x+w)&3;
-
-	nlmiddle = w - rightIndex;
-	if(leftIndex){
-	  nlmiddle -= (4 - leftIndex);
-	}
-/*	nlmiddle += 3;*/
-	nlmiddle >>= 2;
-	if(nlmiddle < 0)
-	  nlmiddle = 0;
-
-	pdst += (x >> 2)*3;
-	pdst += leftIndex? (leftIndex -1):0;
-	switch(leftIndex+w){
-	case 4:
-	    switch(leftIndex){
-	    case 0:
-#if RROP == GXcopy
-		    *pdst++ = piQxelXor[0];
-		    *pdst++ = piQxelXor[1];
-		    *pdst-- = piQxelXor[2];
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= piQxelXor[0];
-		    *pdst++ ^= piQxelXor[1];
-		    *pdst-- ^= piQxelXor[2];
-#endif
-#if RROP == GXand
-		    *pdst++ &= piQxelAnd[0];
-		    *pdst++ &= piQxelAnd[1];
-		    *pdst-- &= piQxelAnd[2];
-#endif
-#if RROP == GXor
-		    *pdst++ |= piQxelOr[0];
-		    *pdst++ |= piQxelOr[1];
-		    *pdst-- |= piQxelOr[2];
-#endif
-#if RROP == GXset
-		    *pdst = DoRRop((*pdst), piQxelAnd[0], piQxelXor[0]);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[2], piQxelXor[2]);
-		    pdst--;
-#endif
-		    pdst--;
-		break;
-	    case 1:
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-		    pdst++;
-		    *pdst++ = piQxelXor[1];
-		    *pdst-- = piQxelXor[2];
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= (piQxelXor[0] & 0xFF000000);
-		    *pdst++ ^= piQxelXor[1];
-		    *pdst-- ^= piQxelXor[2];
-#endif
-#if RROP == GXand
-		    *pdst++ &= (piQxelAnd[0] | 0x00FFFFFF);
-		    *pdst++ &= piQxelAnd[1];
-		    *pdst-- &= piQxelAnd[2];
-#endif
-#if RROP == GXor
-		    *pdst++ |= (piQxelOr[0] & 0xFF000000);
-		    *pdst++ |= piQxelOr[1];
-		    *pdst-- |= piQxelOr[2];
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[0], piQxelXor[0], 0xFF000000);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[2], piQxelXor[2]);
-		    pdst--;
-#endif
-		    pdst--;
-		break;
-	    case 2:
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFFFF) | (piQxelXor[1] & 0xFFFF0000);
-		    pdst++;
-		    *pdst-- = piQxelXor[2];
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= (piQxelXor[1] & 0xFFFF0000);
-		    *pdst-- ^= piQxelXor[2];
-#endif
-#if RROP == GXand
-		    *pdst++ &= (piQxelAnd[1] | 0xFFFF);
-		    *pdst-- &= piQxelAnd[2];
-#endif
-#if RROP == GXor
-		    *pdst++ |= (piQxelOr[1] & 0xFFFF0000);
-		    *pdst-- |= piQxelOr[2];
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF0000);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[2], piQxelXor[2]);
-		    pdst--;
-#endif
-		break;
-	    case 3:
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFF) | (piQxelXor[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXxor
-		    *pdst ^= (piQxelXor[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXand
-		    *pdst &= (piQxelAnd[2] | 0xFF);
-#endif
-#if RROP == GXor
-		    *pdst |= (piQxelOr[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFFFFFF00);
-#endif
-		break;
-	    }
-	    break;
-	case 3:
-	    switch(leftIndex){
-	    case 0:
-#if RROP == GXcopy
-		    *pdst++ = piQxelXor[0];
-		    *pdst++ = piQxelXor[1];
-		    *pdst = ((*pdst) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		    pdst--;
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= piQxelXor[0];
-		    *pdst++ ^= piQxelXor[1];
-		    *pdst-- ^= (piQxelXor[2] & 0xFF);
-#endif
-#if RROP == GXand
-		    *pdst++ &= piQxelAnd[0];
-		    *pdst++ &= piQxelAnd[1];
-		    *pdst-- &= (piQxelAnd[2] | 0xFFFFFF00);
-#endif
-#if RROP == GXor
-		    *pdst++ |= piQxelOr[0];
-		    *pdst++ |= piQxelOr[1];
-
-		    *pdst-- |= (piQxelOr[2] & 0xFF);
-#endif
-#if RROP == GXset
-		    *pdst = DoRRop((*pdst), piQxelAnd[0], piQxelXor[0]);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-		    pdst++;
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFF);
-		    pdst--;
-#endif
-		    pdst--;
-		break;
-	    case 1:
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-		    pdst++;
-		    *pdst++ = piQxelXor[1];
-		    *pdst = ((*pdst) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		    pdst--;
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= (piQxelXor[0] & 0xFF000000);
-		    *pdst++ ^= piQxelXor[1];
-		    *pdst-- ^= (piQxelXor[2] & 0xFF);
-#endif
-#if RROP == GXand
-		    *pdst++ &= (piQxelAnd[0] | 0x00FFFFFF);
-		    *pdst++ &= piQxelAnd[1];
-		    *pdst-- &= (piQxelAnd[2] | 0xFFFFFF00);
-#endif
-#if RROP == GXor
-		    *pdst++ |= (piQxelOr[0] & 0xFF000000);
-		    *pdst++ |= piQxelOr[1];
-		    *pdst-- |= (piQxelOr[2] & 0xFF);
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[0], piQxelXor[0], 0xFF000000);
-		    pdst++;
-		    *pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-		    pdst++;
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFF);
-		    pdst--;
-#endif
-		    pdst--;
-		break;
-	    case 2:
-/*		pdst++;*/
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFFFF) | (piQxelXor[1] & 0xFFFF0000);
-		    pdst++;
-		    *pdst = ((*pdst) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		    pdst--;
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= (piQxelXor[1] & 0xFFFF0000);
-		    *pdst-- ^= (piQxelXor[2] & 0xFF);
-#endif
-#if RROP == GXand
-		    *pdst++ &= (piQxelAnd[1] | 0xFFFF);
-		    *pdst-- &= (piQxelAnd[2] | 0xFFFFFF00);
-#endif
-#if RROP == GXor
-		    *pdst++ |= (piQxelOr[1] & 0xFFFF0000);
-		    *pdst-- |= (piQxelOr[2] & 0xFF);
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF0000);
-		    pdst++;
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFF);
-		    pdst--;
-#endif
-		break;
-	    }
-	    break;
-	case 2: /* leftIndex + w = 2*/
-	    if(leftIndex){
-#if RROP == GXcopy
-		    *pdst = ((*pdst) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-		    pdst++;
-		    *pdst = ((*pdst) & 0xFFFF0000) | (piQxelXor[1] & 0xFFFF);
-		    pdst--;
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= (piQxelXor[0] & 0xFF000000);
-		    *pdst-- ^= (piQxelXor[1] & 0xFFFF);
-#endif
-#if RROP == GXand
-		    *pdst++ &= (piQxelAnd[0] | 0xFFFFFF);
-		    *pdst-- &= (piQxelAnd[1] | 0xFFFF0000);
-#endif
-#if RROP == GXor
-		    *pdst++ |= (piQxelOr[0] & 0xFF000000);
-		    *pdst-- |= (piQxelOr[1] & 0xFFFF);
-#endif
-#if RROP == GXset
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[0], piQxelXor[0], 0xFF000000);
-		    pdst++;
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF);
-		    pdst--;
-#endif
-	    }
-	    else{ /*case 2 leftIndex === 0 */
-#if RROP == GXcopy
-		    *pdst++ = piQxelXor[0];
-		    *pdst = ((*pdst) & 0xFFFF0000) | (piQxelXor[1] & 0xFFFF);
-		    pdst--;
-#endif
-#if RROP == GXxor
-		    *pdst++ ^= piQxelXor[0];
-		    *pdst-- ^= (piQxelXor[1] & 0xFFFF);
-#endif
-#if RROP == GXand
-		    *pdst++ &= piQxelAnd[0];
-		    *pdst-- &= (piQxelAnd[1] | 0xFFFF0000);
-#endif
-#if RROP == GXor
-		    *pdst++ |= piQxelOr[0];
-		    *pdst-- |= (piQxelOr[1] & 0xFFFF);
-#endif
-#if RROP == GXset
-		    *pdst = DoRRop((*pdst), piQxelAnd[0], piQxelXor[0]);
-		    pdst++;
-		    *pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF);
-		    pdst--;
-#endif
-	    }
-	    break;
-	case 1: /*only if leftIndex = 0 and w = 1*/
-#if RROP == GXcopy
-		*pdst = ((*pdst) & 0xFF000000) | (piQxelXor[0] & 0xFFFFFF);
-#endif
-#if RROP == GXxor
-		*pdst ^= (piQxelXor[0] & 0xFFFFFF);
-#endif
-#if RROP == GXand
-		*pdst &= (piQxelAnd[0] | 0xFF000000);
-#endif
-#if RROP == GXor
-		*pdst |= (piQxelOr[0] & 0xFFFFFF);
-#endif
-#if RROP == GXset
-		*pdst = DoMaskRRop((*pdst), piQxelAnd[0], piQxelXor[0], 0xFFFFFF);
-#endif
-	    break;
-	case 0: /*never*/
-	    break;
-	default:
-	{
-	    switch(leftIndex){
-		    case 0:
-			break;
-		    case 1:
-#if RROP == GXcopy
-			*pdst = ((*pdst) & 0xFFFFFF) | (piQxelXor[0] & 0xFF000000);
-			pdst++;
-			*pdst++ = piQxelXor[1];
-			*pdst++ = piQxelXor[2];
-#endif
-#if RROP == GXxor
-			*pdst++ ^= (piQxelXor[0] & 0xFF000000);
-			*pdst++ ^= piQxelXor[1];
-			*pdst++ ^= piQxelXor[2];
-#endif
-#if RROP == GXand
-			*pdst++ &= (piQxelAnd[0] | 0xFFFFFF);
-			*pdst++ &= piQxelAnd[1];
-			*pdst++ &= piQxelAnd[2];
-#endif
-#if RROP == GXor
-			*pdst++ |= (piQxelOr[0] & 0xFF000000);
-			*pdst++ |= piQxelOr[1];
-			*pdst++ |= piQxelOr[2];
-#endif
-#if RROP == GXset
-			*pdst = DoMaskRRop((*pdst), piQxelAnd[0], piQxelXor[0], 0xFF000000);
-			pdst++;
-			*pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-			pdst++;
-			*pdst = DoRRop((*pdst), piQxelAnd[2], piQxelXor[2]);
-			pdst++;
-#endif
-		    break;
-		    case 2:
-#if RROP == GXcopy
-			*pdst = (((*pdst) & 0xFFFF) | (piQxelXor[1] & 0xFFFF0000));
-			pdst++;
-			*pdst++ = piQxelXor[2];
-#endif
-#if RROP == GXxor
-			*pdst++ ^=(piQxelXor[1] & 0xFFFF0000);
-			*pdst++ ^= piQxelXor[2];
-#endif
-#if RROP == GXand
-			*pdst++ &= (piQxelAnd[1] | 0xFFFF);
-			*pdst++ &= piQxelAnd[2];
-#endif
-#if RROP == GXor
-			*pdst++ |= (piQxelOr[1] & 0xFFFF0000);
-			*pdst++ |= piQxelOr[2];
-#endif
-#if RROP == GXset
-			*pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF0000);
-			pdst++;
-			*pdst = DoRRop((*pdst), piQxelAnd[2], piQxelXor[2]);
-			pdst++;
-#endif
-			break;
-		    case 3:
-#if RROP == GXcopy
-			*pdst = ((*pdst) & 0xFF) | (piQxelXor[2] & 0xFFFFFF00);
-			pdst++;
-#endif
-#if RROP == GXxor
-			*pdst++ ^= (piQxelXor[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXand
-			*pdst++ &= (piQxelAnd[2] | 0xFF);
-#endif
-#if RROP == GXor
-			*pdst++ |= (piQxelOr[2] & 0xFFFFFF00);
-#endif
-#if RROP == GXset
-			*pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFFFFFF00);
-			pdst++;
-#endif
-			break;
-		    }
-		    while(nlmiddle--){
-#if RROP == GXcopy
-			*pdst++ = piQxelXor[0];
-			*pdst++ = piQxelXor[1];
-			*pdst++ = piQxelXor[2];
-#endif
-#if RROP == GXxor
-			*pdst++ ^= piQxelXor[0];
-			*pdst++ ^= piQxelXor[1];
-			*pdst++ ^= piQxelXor[2];
-#endif
-#if RROP == GXand
-			*pdst++ &= piQxelAnd[0];
-			*pdst++ &= piQxelAnd[1];
-			*pdst++ &= piQxelAnd[2];
-#endif
-#if RROP == GXor
-			*pdst++ |= piQxelOr[0];
-			*pdst++ |= piQxelOr[1];
-			*pdst++ |= piQxelOr[2];
-#endif
-#if RROP == GXset
-			*pdst = DoRRop((*pdst), piQxelAnd[0], piQxelXor[0]);
-			pdst++;
-			*pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-			pdst++;
-			*pdst = DoRRop((*pdst), piQxelAnd[2], piQxelXor[2]);
-			pdst++;
-#endif
-		}
-		switch(rightIndex){
-		case 0:
-		  break;
-		case 1:
-#if RROP == GXcopy
-		  *pdst = ((*pdst) & 0xFF000000) | (piQxelXor[0] & 0xFFFFFF);
-		  pdst++;
-#endif
-#if RROP == GXxor
-		  *pdst++ ^= (piQxelXor[0] & 0xFFFFFF);
-#endif
-#if RROP == GXand
-		  *pdst++ &= (piQxelAnd[0] | 0xFF);
-#endif
-#if RROP == GXor
-		  *pdst++ |= (piQxelOr[0] & 0xFFFFFF);
-#endif
-#if RROP == GXset
-		  *pdst = DoMaskRRop((*pdst), piQxelAnd[0], piQxelXor[0], 0xFFFFFF);
-#endif
-		  break;
-		case 2:
-#if RROP == GXcopy
-		  *pdst++ = piQxelXor[0];
-		  *pdst = ((*pdst) & 0xFFFF0000) | (piQxelXor[1] & 0xFFFF);
-		  pdst++;
-#endif
-#if RROP == GXxor
-		  *pdst++ ^= piQxelXor[0];
-		  *pdst++ ^= (piQxelXor[1] & 0xFFFF);
-#endif
-#if RROP == GXand
-		  *pdst++ &= piQxelAnd[0];
-		  *pdst++ &= (piQxelAnd[1] | 0xFFFF0000);
-#endif
-#if RROP == GXor
-		  *pdst++ |= piQxelOr[0];
-		  *pdst++ |= (piQxelOr[1] & 0xFFFF);
-#endif
-#if RROP == GXset
-		  *pdst = DoRRop((*pdst), piQxelAnd[0], piQxelXor[0]);
-		  pdst++;
-		  *pdst = DoMaskRRop((*pdst), piQxelAnd[1], piQxelXor[1], 0xFFFF);
-		  pdst++;
-#endif
-		  break;
-		case 3:
-#if RROP == GXcopy
-		  *pdst++ = piQxelXor[0];
-		  *pdst++ = piQxelXor[1];
-		  *pdst = ((*pdst) & 0xFFFFFF00) | (piQxelXor[2] & 0xFF);
-		  pdst++;
-#endif
-#if RROP == GXxor
-		  *pdst++ ^= piQxelXor[0];
-		  *pdst++ ^= piQxelXor[1];
-		  *pdst++ ^= (piQxelXor[2] & 0xFF);
-#endif
-#if RROP == GXand
-		  *pdst++ &= piQxelAnd[0];
-		  *pdst++ &= piQxelAnd[1];
-		  *pdst++ &= (piQxelAnd[2] | 0xFFFFFF00);
-#endif
-#if RROP == GXor
-		  *pdst++ |= piQxelOr[0];
-		  *pdst++ |= piQxelOr[1];
-		  *pdst++ |= (piQxelOr[2] & 0xFF);
-#endif
-#if RROP == GXset
-		  *pdst = DoRRop((*pdst), piQxelAnd[0], piQxelXor[0]);
-		  pdst++;
-		  *pdst = DoRRop((*pdst), piQxelAnd[1], piQxelXor[1]);
-		  pdst++;
-		  *pdst = DoMaskRRop((*pdst), piQxelAnd[2], piQxelXor[2], 0xFF);
-		  pdst++;
-#endif
-		  break;
-		}
-	}
-}
-#else
-#if PSZ == 8
-	if (w <= PGSZB)
-	{
-	    register char   *addrb;
-
-	    addrb = ((char *) pdst) + x;
-	    while (w--)
-	    {
-		RROP_SOLID (addrb);
-		addrb++;
-	    }
-	}
-#else
-	if ((x & PIM) + w <= PPW)
-	{
-	    pdst += x >> PWSH;
-	    maskpartialbits (x, w, startmask);
-	    RROP_SOLID_MASK (pdst, startmask);
-	}
-#endif
-	else
-	{
-	    pdst += x >> PWSH;
-	    maskbits (x, w, startmask, endmask, nlmiddle);
-	    if (startmask)
-	    {
-		RROP_SOLID_MASK (pdst, startmask);
-		++pdst;
-	    }
-	    
-	    RROP_SPAN(pdst,nlmiddle)
-	    if (endmask)
-	    {
-		RROP_SOLID_MASK (pdst, endmask);
-	    }
-	}
-#endif
-    }
-    xfree(pptFree);
-    xfree(pwidthFree);
-    RROP_UNDECLARE
-}
diff --git a/cfb/cfbteblt8.c b/cfb/cfbteblt8.c
deleted file mode 100644
index 9d4ce57..0000000
--- a/cfb/cfbteblt8.c
+++ /dev/null
@@ -1,589 +0,0 @@
-/*
- * TEGblt - ImageText expanded glyph fonts only.  For
- * 8 bit displays, in Copy mode with no clipping.
- */
-
-/*
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-*/
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#if PSZ == 8
-
-#include	<X11/X.h>
-#include	<X11/Xmd.h>
-#include	<X11/Xproto.h>
-#include	"cfb.h"
-#include	<X11/fonts/fontstruct.h>
-#include	"dixfontstr.h"
-#include	"gcstruct.h"
-#include	"windowstr.h"
-#include	"scrnintstr.h"
-#include	"pixmapstr.h"
-#include	"regionstr.h"
-#include	"cfbmskbits.h"
-#include	"cfb8bit.h"
-
-/*
- * this code supports up to 5 characters at a time.  The performance
- * differences between 4 and 5 is usually small (~7% on PMAX) and
- * frequently negative (SPARC and Sun3), so this file is compiled
- * only once for now.  If you want to use the other options, you'll
- * need to hack cfbgc.c as well.
- */
-
-#ifndef NGLYPHS
-#define NGLYPHS 4
-#define DO_COMMON
-#endif
-
-#ifdef DO_COMMON
-#define CFBTEGBLT8 cfbTEGlyphBlt8
-#endif
-
-/*
- * On little-endian machines (or where fonts are padded to 32-bit
- * boundaries) we can use some magic to avoid the expense of getleftbits
- */
-
-#if ((BITMAP_BIT_ORDER == LSBFirst && NGLYPHS >= 4) || GLYPHPADBYTES == 4)
-
-#if GLYPHPADBYTES == 1
-typedef unsigned char	*glyphPointer;
-#define USE_LEFTBITS
-#endif
-
-#if GLYPHPADBYTES == 2
-typedef unsigned short	*glyphPointer;
-#define USE_LEFTBITS
-#endif
-
-#if GLYPHPADBYTES == 4
-typedef unsigned int	*glyphPointer;
-#endif
-
-#define GetBitsL       c = BitLeft (*leftChar++, lshift)
-#define NGetBits1S(r)   c = BitRight(*char1++ r, xoff1)
-#define NGetBits1L(r)   GetBitsL | BitRight(*char1++ r, xoff1)
-#define NGetBits1U(r)   c = *char1++ r
-#define NGetBits2S(r)   NGetBits1S(| BitRight(*char2++ r, widthGlyph))
-#define NGetBits2L(r)   NGetBits1L(| BitRight(*char2++ r, widthGlyph))
-#define NGetBits2U(r)   NGetBits1U(| BitRight(*char2++ r, widthGlyph))
-#define NGetBits3S(r)   NGetBits2S(| BitRight(*char3++ r, widthGlyph))
-#define NGetBits3L(r)   NGetBits2L(| BitRight(*char3++ r, widthGlyph))
-#define NGetBits3U(r)   NGetBits2U(| BitRight(*char3++ r, widthGlyph))
-#define NGetBits4S(r)   NGetBits3S(| BitRight(*char4++ r, widthGlyph))
-#define NGetBits4L(r)   NGetBits3L(| BitRight(*char4++ r, widthGlyph))
-#define NGetBits4U(r)   NGetBits3U(| BitRight(*char4++ r, widthGlyph))
-#define NGetBits5S(r)   NGetBits4S(| BitRight(*char5++ r, widthGlyph))
-#define NGetBits5L(r)   NGetBits4L(| BitRight(*char5++ r, widthGlyph))
-#define NGetBits5U(r)   NGetBits4U(| BitRight(*char5++ r, widthGlyph))
-#define GetBits1S   c = BitRight(*char1++, xoff1)
-#define GetBits1L   GetBitsL | BitRight(*char1++, xoff1)
-#define GetBits1U   c = *char1++
-#define GetBits2S   NGetBits1S(| BitRight(*char2++, widthGlyph))
-#define GetBits2L   NGetBits1L(| BitRight(*char2++, widthGlyph))
-#define GetBits2U   NGetBits1U(| BitRight(*char2++, widthGlyph))
-#define GetBits3S   NGetBits2S(| BitRight(*char3++, widthGlyph))
-#define GetBits3L   NGetBits2L(| BitRight(*char3++, widthGlyph))
-#define GetBits3U   NGetBits2U(| BitRight(*char3++, widthGlyph))
-#define GetBits4S   NGetBits3S(| BitRight(*char4++, widthGlyph))
-#define GetBits4L   NGetBits3L(| BitRight(*char4++, widthGlyph))
-#define GetBits4U   NGetBits3U(| BitRight(*char4++, widthGlyph))
-#define GetBits5S   NGetBits4S(| BitRight(*char5++, widthGlyph))
-#define GetBits5L   NGetBits4L(| BitRight(*char5++, widthGlyph))
-#define GetBits5U   NGetBits4U(| BitRight(*char5++, widthGlyph))
-
-#else
-
-typedef unsigned int	*glyphPointer;
-
-#define USE_LEFTBITS
-#define ALL_LEFTBITS
-
-#define GetBitsL    WGetBitsL
-#define GetBits1S   WGetBits1S
-#define GetBits1L   WGetBits1L
-#define GetBits1U   WGetBits1U
-
-#define GetBits2S   GetBits1S Get1Bits (char2, tmpSrc) \
-		    c |= BitRight(tmpSrc, xoff2);
-#define GetBits2L   GetBits1L Get1Bits (char2, tmpSrc) \
-		    c |= BitRight(tmpSrc, xoff2);
-#define GetBits2U   GetBits1U Get1Bits (char2, tmpSrc) \
-		    c |= BitRight(tmpSrc, xoff2);
-
-#define GetBits3S   GetBits2S Get1Bits (char3, tmpSrc) \
-		    c |= BitRight(tmpSrc, xoff3);
-#define GetBits3L   GetBits2L Get1Bits (char3, tmpSrc) \
-		    c |= BitRight(tmpSrc, xoff3);
-#define GetBits3U   GetBits2U Get1Bits (char3, tmpSrc) \
-		    c |= BitRight(tmpSrc, xoff3);
-
-#define GetBits4S   GetBits3S Get1Bits (char4, tmpSrc) \
-		    c |= BitRight(tmpSrc, xoff4);
-#define GetBits4L   GetBits3L Get1Bits (char4, tmpSrc) \
-		    c |= BitRight(tmpSrc, xoff4);
-#define GetBits4U   GetBits3U Get1Bits (char4, tmpSrc) \
-		    c |= BitRight(tmpSrc, xoff4);
-
-#define GetBits5S   GetBits4S Get1Bits (char5, tmpSrc) \
-		    c |= BitRight(tmpSrc, xoff5);
-#define GetBits5L   GetBits4L Get1Bits (char5, tmpSrc) \
-		    c |= BitRight(tmpSrc, xoff5);
-#define GetBits5U   GetBits4U Get1Bits (char5, tmpSrc) \
-		    c |= BitRight(tmpSrc, xoff5);
-
-#endif
-
-#ifdef USE_LEFTBITS
-
-#define IncChar(c)  (c = (glyphPointer) (((char *) c) + glyphBytes))
-
-#define Get1Bits(ch,dst)    glyphbits (ch, widthGlyph, glyphMask, dst); \
-			    IncChar (ch);
-
-#define glyphbits(bits,width,mask,dst)	getleftbits(bits,width,dst); \
-					dst &= mask;
-
-#define WGetBitsL   Get1Bits(leftChar,c); \
-		    c = BitLeft (c, lshift);
-#define WGetBits1S  Get1Bits (char1, c) \
-		    c = BitRight (c, xoff1);
-#define WGetBits1L  WGetBitsL Get1Bits (char1, tmpSrc) \
-		    c |= BitRight (tmpSrc, xoff1);
-#define WGetBits1U  Get1Bits (char1, c)
-
-#else
-#define WGetBitsL   GetBitsL
-#define WGetBits1S  GetBits1S
-#define WGetBits1L  GetBits1L
-#define WGetBits1U  GetBits1U
-#endif
-
-#if NGLYPHS == 2
-# define GetBitsNS GetBits2S
-# define GetBitsNL GetBits2L
-# define GetBitsNU GetBits2U
-# define LastChar char2
-#ifndef CFBTEGBLT8
-# define CFBTEGBLT8 cfbTEGlyphBlt8x2
-#endif
-#endif
-#if NGLYPHS == 3
-# define GetBitsNS GetBits3S
-# define GetBitsNL GetBits3L
-# define GetBitsNU GetBits3U
-# define LastChar char3
-#ifndef CFBTEGBLT8
-# define CFBTEGBLT8 cfbTEGlyphBlt8x3
-#endif
-#endif
-#if NGLYPHS == 4
-# define GetBitsNS GetBits4S
-# define GetBitsNL GetBits4L
-# define GetBitsNU GetBits4U
-# define LastChar char4
-#ifndef CFBTEGBLT8
-# define CFBTEGBLT8 cfbTEGlyphBlt8x4
-#endif
-#endif
-#if NGLYPHS == 5
-# define GetBitsNS GetBits5S
-# define GetBitsNL GetBits5L
-# define GetBitsNU GetBits5U
-# define LastChar char5
-#ifndef CFBTEGBLT8
-# define CFBTEGBLT8 cfbTEGlyphBlt8x5
-#endif
-#endif
-
-/* another ugly giant macro */
-#define SwitchEm    switch (ew) \
-		    { \
-		    case 0: \
-		    	break; \
-		    case 1: \
-		    	while (hTmp--) { \
-			    GetBits; \
-			    StoreBits0 \
-			    Loop \
-		    	} \
-		    	break; \
-		    case 2: \
-		    	while (hTmp--) { \
-			    GetBits; \
-			    StoreBits0 FirstStep StoreBits(1) \
-			    Loop \
-		    	} \
-		    	break; \
-		    case 3: \
-		    	while (hTmp--) { \
-			    GetBits; \
-			    StoreBits0 FirstStep StoreBits(1) Step StoreBits(2) \
-			    Loop \
-		    	} \
-		    	break; \
-		    case 4: \
-		    	while (hTmp--) { \
-			    GetBits; \
-			    StoreBits0 FirstStep StoreBits(1) Step \
-			    StoreBits(2) Step StoreBits(3) \
-			    Loop \
-		    	} \
-		    	break; \
-		    case 5: \
-		    	while (hTmp--) { \
-			    GetBits; \
-			    StoreBits0 FirstStep StoreBits(1) Step \
-			    StoreBits(2) Step StoreBits(3) Step \
-			    StoreBits(4) \
-			    Loop \
-		    	} \
-		    	break; \
-		    case 6: \
-		    	while (hTmp--) { \
-			    GetBits; \
-			    StoreBits0 FirstStep StoreBits(1) Step \
- 			    StoreBits(2) Step StoreBits(3) Step \
-			    StoreBits(4) Step StoreBits(5) \
-			    Loop \
-		    	} \
-		    	break; \
-		    case 7: \
-		    	while (hTmp--) { \
-			    GetBits; \
-			    StoreBits0 FirstStep StoreBits(1) Step \
-			    StoreBits(2) Step StoreBits(3) Step \
-			    StoreBits(4) Step StoreBits(5) Step \
-			    StoreBits(6) \
-			    Loop \
-		    	} \
-		    	break; \
-		    case 8: \
-		    	while (hTmp--) { \
-			    GetBits; \
-			    StoreBits0 FirstStep StoreBits(1) Step \
-			    StoreBits(2) Step StoreBits(3) Step \
-			    StoreBits(4) Step StoreBits(5) Step \
-			    StoreBits(6) Step StoreBits(7) \
-			    Loop \
-		    	} \
-		    	break; \
-		    }
-
-#ifdef FAST_CONSTANT_OFFSET_MODE
-#define StorePixels(o,p)    dst[o] = p
-#define Loop		    dst += widthDst;
-#else
-#define StorePixels(o,p)    do { *dst = (p); dst++; } while (0)
-#define Loop		    dst += widthLeft;
-#endif
-
-#define Step		    NextBitGroup(c);
-
-#if (BITMAP_BIT_ORDER == MSBFirst)
-#define StoreBits(o)	StorePixels(o,GetPixelGroup(c));
-#define FirstStep	Step
-#else
-#if PGSZ == 64
-#define StoreBits(o)	StorePixels(o,cfb8Pixels[(c) & PGSZBMSK]);
-#define FirstStep	Step
-#else /* PGSZ == 32 */
-#define StoreBits(o)	StorePixels(o,*((CfbBits *) (((char *) cfb8Pixels) + (c & 0x3c))));
-#define FirstStep	c = BitLeft (c, 2);
-#endif /* PGSZ */
-#endif /* BITMAP_BIT_ORDER */
-
-
-void
-CFBTEGBLT8 (pDrawable, pGC, xInit, yInit, nglyph, ppci, pglyphBase)
-    DrawablePtr pDrawable;
-    GC 		*pGC;
-    int 	xInit, yInit;
-    unsigned int nglyph;
-    CharInfoPtr *ppci;		/* array of character info */
-    pointer	pglyphBase;	/* start of array of glyphs */
-{
-    register CfbBits  c;
-    register CfbBits  *dst;
-    register CfbBits  leftMask, rightMask;
-    register int	    hTmp;
-    register int	    xoff1;
-    register glyphPointer   char1;
-    register glyphPointer   char2;
-#if NGLYPHS >= 3
-    register glyphPointer   char3;
-#endif
-#if NGLYPHS >= 4
-    register glyphPointer   char4;
-#endif
-#if NGLYPHS >= 5
-    register glyphPointer   char5;
-#endif
-#ifdef ALL_LEFTBITS
-    int xoff2, xoff3, xoff4, xoff5;
-#endif
-
-    FontPtr		pfont = pGC->font;
-    CfbBits	*dstLine;
-    glyphPointer	oldRightChar;
-    CfbBits	*pdstBase;
-    glyphPointer	leftChar;
-    int			widthDst;
-#ifndef FAST_CONSTANT_OFFSET_MODE
-    int			widthLeft;
-#endif
-    int			widthGlyph;
-    int			h;
-    int			ew;
-    int			x, y;
-    BoxRec		bbox;		/* for clipping */
-    int			lshift;
-    int			widthGlyphs;
-#ifdef USE_LEFTBITS
-    register CfbBits  glyphMask;
-    register CfbBits  tmpSrc;
-    register int	    glyphBytes;
-#endif
-
-    widthGlyph = FONTMAXBOUNDS(pfont,characterWidth);
-    h = FONTASCENT(pfont) + FONTDESCENT(pfont);
-    if (!h)
-	return;
-    x = xInit + FONTMAXBOUNDS(pfont,leftSideBearing) + pDrawable->x;
-    y = yInit - FONTASCENT(pfont) + pDrawable->y;
-    bbox.x1 = x;
-    bbox.x2 = x + (widthGlyph * nglyph);
-    bbox.y1 = y;
-    bbox.y2 = y + h;
-
-    switch (RECT_IN_REGION(pGC->pScreen,  cfbGetCompositeClip(pGC), &bbox))
-    {
-      case rgnPART:
-	cfbImageGlyphBlt8(pDrawable, pGC, xInit, yInit, nglyph, ppci, pglyphBase);
-      case rgnOUT:
-	return;
-    }
-
-    if (!cfb8CheckPixels (pGC->fgPixel, pGC->bgPixel))
-	cfb8SetPixels (pGC->fgPixel, pGC->bgPixel);
-
-    leftChar = 0;
-
-    cfbGetLongWidthAndPointer(pDrawable, widthDst, pdstBase)
-
-#if NGLYPHS == 2
-    widthGlyphs = widthGlyph << 1;
-#else
-#if NGLYPHS == 4
-    widthGlyphs = widthGlyph << 2;
-#else
-    widthGlyphs = widthGlyph * NGLYPHS;
-#endif
-#endif
-
-#ifdef USE_LEFTBITS
-    glyphMask = mfbGetendtab(widthGlyph);
-    glyphBytes = GLYPHWIDTHBYTESPADDED(*ppci);
-#endif
-
-    pdstBase += y * widthDst;
-#ifdef DO_COMMON
-    if (widthGlyphs <= 32)
-#endif
-    	while (nglyph >= NGLYPHS)
-    	{
-	    nglyph -= NGLYPHS;
-	    hTmp = h;
-	    dstLine = pdstBase + (x >> PWSH);
-	    xoff1 = x & PIM;
-	    char1 = (glyphPointer) FONTGLYPHBITS(pglyphBase, *ppci++);
-	    char2 = (glyphPointer) FONTGLYPHBITS(pglyphBase, *ppci++);
-#ifdef ALL_LEFTBITS
-	    xoff2 = xoff1 + widthGlyph;
-#endif
-#if NGLYPHS >= 3
-	    char3 = (glyphPointer) FONTGLYPHBITS(pglyphBase, *ppci++);
-#ifdef ALL_LEFTBITS
-	    xoff3 = xoff2 + widthGlyph;
-#endif
-#endif
-#if NGLYPHS >= 4
-	    char4 = (glyphPointer) FONTGLYPHBITS(pglyphBase, *ppci++);
-#ifdef ALL_LEFTBITS
-	    xoff4 = xoff3 + widthGlyph;
-#endif
-#endif
-#if NGLYPHS >= 5
-	    char5 = (glyphPointer) FONTGLYPHBITS(pglyphBase, *ppci++);
-#ifdef ALL_LEFTBITS
-	    xoff5 = xoff4 + widthGlyph;
-#endif
-#endif
-	    oldRightChar = LastChar;
-	    dst = dstLine;
-	    if (xoff1)
-	    {
-		ew = ((widthGlyphs - (PGSZB - xoff1)) >> PWSH) + 1;
-#ifndef FAST_CONSTANT_OFFSET_MODE
-		widthLeft = widthDst - ew;
-#endif
-	    	if (!leftChar)
-	    	{
-		    leftMask = cfbendtab[xoff1];
-		    rightMask = cfbstarttab[xoff1];
-
-#define StoreBits0	StorePixels (0, (dst[0] & leftMask) | \
-					(GetPixelGroup(c) & rightMask));
-#define GetBits GetBitsNS
-
-		    SwitchEm
-
-#undef GetBits
-#undef StoreBits0
-
-	    	}
-	    	else
-	    	{
-		    lshift = widthGlyph - xoff1;
-    
-#define StoreBits0  StorePixels (0,GetPixelGroup(c));
-#define GetBits GetBitsNL
-    
-		    SwitchEm
-    
-#undef GetBits
-#undef StoreBits0
-    
-	    	}
-	    }
-	    else
-	    {
-#if NGLYPHS == 4 && PGSZ == 32
-	    	ew = widthGlyph;    /* widthGlyphs >> 2 */
-#else
-	    	ew = widthGlyphs >> PWSH;
-#endif
-#ifndef FAST_CONSTANT_OFFSET_MODE
-		widthLeft = widthDst - ew;
-#endif
-
-#define StoreBits0  StorePixels (0,GetPixelGroup(c));
-#define GetBits	GetBitsNU
-
-	    	SwitchEm
-
-#undef GetBits
-#undef StoreBits0
-
-	    }
-	    x += widthGlyphs;
-	    leftChar = oldRightChar;
-    	}
-    while (nglyph--)
-    {
-	xoff1 = x & PIM;
-	char1 = (glyphPointer) FONTGLYPHBITS(pglyphBase, *ppci++);
-	hTmp = h;
-	dstLine = pdstBase + (x >> PWSH);
-	oldRightChar = char1;
-	dst = dstLine;
-	if (xoff1)
-	{
-	    ew = ((widthGlyph - (PGSZB - xoff1)) >> PWSH) + 1;
-#ifndef FAST_CONSTANT_OFFSET_MODE
-	    widthLeft = widthDst - ew;
-#endif
-	    if (!leftChar)
-	    {
-		leftMask = cfbendtab[xoff1];
-		rightMask = cfbstarttab[xoff1];
-
-#define StoreBits0	StorePixels (0, (dst[0] & leftMask) | \
-					(GetPixelGroup(c) & rightMask));
-#define GetBits	WGetBits1S
-
-		SwitchEm
-#undef GetBits
-#undef StoreBits0
-
-	    }
-	    else
-	    {
-		lshift = widthGlyph - xoff1;
-
-#define StoreBits0  StorePixels (0,GetPixelGroup(c));
-#define GetBits WGetBits1L
-
-		SwitchEm
-#undef GetBits
-#undef StoreBits0
-
-	    }
-	}
-	else
-	{
-	    ew = widthGlyph >> PWSH;
-
-#ifndef FAST_CONSTANT_OFFSET_MODE
-	    widthLeft = widthDst - ew;
-#endif
-
-#define StoreBits0  StorePixels (0,GetPixelGroup(c));
-#define GetBits	WGetBits1U
-
-	    SwitchEm
-
-#undef GetBits
-#undef StoreBits0
-
-	}
-	x += widthGlyph;
-	leftChar = oldRightChar;
-    }
-    /*
-     * draw the tail of the last character
-     */
-    xoff1 = x & PIM;
-    if (xoff1)
-    {
-	rightMask = cfbstarttab[xoff1];
-	leftMask = cfbendtab[xoff1];
-	lshift = widthGlyph - xoff1;
-	dst = pdstBase + (x >> PWSH);
-	hTmp = h;
-	while (hTmp--)
-	{
-	    GetBitsL;
-	    *dst = (*dst & rightMask) | (GetPixelGroup(c) & leftMask);
-	    dst += widthDst;
-	}
-    }
-}
-#endif /* PSZ == 8 */
diff --git a/cfb/cfbtegblt.c b/cfb/cfbtegblt.c
deleted file mode 100644
index f04ee3f..0000000
--- a/cfb/cfbtegblt.c
+++ /dev/null
@@ -1,218 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include	<X11/X.h>
-#include	<X11/Xmd.h>
-#include	<X11/Xproto.h>
-#include	"cfb.h"
-#include	<X11/fonts/fontstruct.h>
-#include	"dixfontstr.h"
-#include	"gcstruct.h"
-#include	"windowstr.h"
-#include	"scrnintstr.h"
-#include	"pixmapstr.h"
-#include	"regionstr.h"
-#include	"cfbmskbits.h"
-#include	"mi.h"
-#define MFB_CONSTS_ONLY
-#include	"maskbits.h"
-
-/*
-    this works for fonts with glyphs <= 32 bits wide, on an
-    arbitrarily deep display.  Use cfbTEGlyphBlt8 for 8 bit displays.
-
-    This should be called only with a terminal-emulator font;
-this means that the FIXED_METRICS flag is set, and that
-glyphbounds == charbounds.
-
-    in theory, this goes faster; even if it doesn't, it reduces the
-flicker caused by writing a string over itself with image text (since
-the background gets repainted per character instead of per string.)
-this seems to be important for some converted X10 applications.
-
-    Image text looks at the bits in the glyph and the fg and bg in the
-GC.  it paints a rectangle, as defined in the protocol dcoument,
-and the paints the characters.
-
-*/
-
-void
-cfbTEGlyphBlt(pDrawable, pGC, x, y, nglyph, ppci, pglyphBase)
-    DrawablePtr pDrawable;
-    GC 		*pGC;
-    int 	x, y;
-    unsigned int nglyph;
-    CharInfoPtr *ppci;		/* array of character info */
-    pointer	pglyphBase;	/* start of array of glyphs */
-{
-    FontPtr	pfont = pGC->font;
-    int widthDst;
-    CfbBits *pdstBase;	/* pointer to longword with top row 
-				   of current glyph */
-
-    int w;			/* width of glyph and char */
-    int h;			/* height of glyph and char */
-    register int xpos=x;	/* current x%32  */
-    int ypos=y;			/* current y%32 */
-    register unsigned char *pglyph;
-    int widthGlyph;
-
-    register CfbBits *pdst;/* pointer to current longword in dst */
-    int hTmp;			/* counter for height */
-    BoxRec bbox;		/* for clipping */
-
-    register int wtmp,xtemp,width;
-    CfbBits bgfill,fgfill,*ptemp,tmpDst1,tmpDst2,*pdtmp;
-#if PSZ != 24
-    int tmpx;
-#endif
-
-    xpos += pDrawable->x;
-    ypos += pDrawable->y;
-
-    cfbGetLongWidthAndPointer (pDrawable, widthDst, pdstBase)
-
-    wtmp = FONTMAXBOUNDS(pfont,characterWidth);
-    h = FONTASCENT(pfont) + FONTDESCENT(pfont);
-    widthGlyph = GLYPHWIDTHBYTESPADDED(*ppci);
-
-    xpos += FONTMAXBOUNDS(pfont,leftSideBearing);
-    ypos -= FONTASCENT(pfont);
-
-    bbox.x1 = xpos;
-    bbox.x2 = xpos + (wtmp * nglyph);
-    bbox.y1 = ypos;
-    bbox.y2 = ypos + h;
-
-    fgfill = PFILL(pGC->fgPixel);
-    bgfill = PFILL(pGC->bgPixel);
-
-    switch (RECT_IN_REGION(pGC->pScreen,  cfbGetCompositeClip(pGC), &bbox))
-    {
-      case rgnOUT:
-	break;
-      case rgnPART:
-	/* this is the WRONG thing to do, but it works.
-	   calling the non-terminal text is easy, but slow, given
-	   what we know about the font.
-
-	   the right thing to do is something like:
-	    for each clip rectangle
-		compute at which row the glyph starts to be in it,
-		   and at which row the glyph ceases to be in it
-		compute which is the first glyph inside the left
-		    edge, and the last one inside the right edge
-		draw a fractional first glyph, using only
-		    the rows we know are in
-		draw all the whole glyphs, using the appropriate rows
-		draw any pieces of the last glyph, using the right rows
-
-	   this way, the code would take advantage of knowing that
-	   all glyphs are the same height and don't overlap.
-
-	   one day...
-	*/
-	cfbImageGlyphBlt8(pDrawable, pGC, x, y, nglyph, ppci, pglyphBase);
-	break;
-      case rgnIN:
-
-        pdtmp = pdstBase + (widthDst * ypos);
-        while(nglyph--)
-        {
-
-	    pglyph = FONTGLYPHBITS(pglyphBase, *ppci++);
-            pdst = pdtmp;
-	    hTmp = h;
-
-	    while (hTmp--)
-	    {
-		x = xpos;
-		width = wtmp;
- 	        xtemp = 0;
-
-		while (width > 0)
-		{
-#if PSZ == 24
-		    w = 1;
-		    ptemp = (CfbBits *)(pglyph + ((xtemp *3)>> 2));
-		    getstipplepixels24(ptemp,xtemp,0,&bgfill,&tmpDst1, xtemp);
-		    getstipplepixels24(ptemp,xtemp,1,&fgfill,&tmpDst2, xtemp);
-#else
-		    tmpx = x & PIM;
-		    w = min(width, PPW - tmpx);
-		    w = min(w, (PGSZ - xtemp));
-		    ptemp = (CfbBits *)(pglyph + (xtemp >> MFB_PWSH));
-		    getstipplepixels(ptemp,xtemp,w,0,&bgfill,&tmpDst1);
-		    getstipplepixels(ptemp,xtemp,w,1,&fgfill,&tmpDst2);
-#endif
-
-		    {
-			CfbBits tmpDst = tmpDst1 | tmpDst2;
-#if PSZ == 24
-			CfbBits *pdsttmp = pdst + ((x*3) >> 2);
-			putbits24(tmpDst,w,pdsttmp,pGC->planemask,x);
-#else
-			CfbBits *pdsttmp = pdst + (x >> PWSH);
-			putbits(tmpDst,tmpx,w,pdsttmp,pGC->planemask);
-#endif
-		    }
-		    x += w;
-		    xtemp += w;
-		    width -= w;
-		}
-		pglyph += widthGlyph;
-                pdst += widthDst;
-	    }
-	    xpos += wtmp;
-        }     
-	break;
-    }
-}
diff --git a/cfb/cfbtile32.c b/cfb/cfbtile32.c
deleted file mode 100644
index be016a7..0000000
--- a/cfb/cfbtile32.c
+++ /dev/null
@@ -1,517 +0,0 @@
-/*
- * Fill 32 bit tiled rectangles.  Used by PolyFillRect.
- * no depth dependencies.
- */
-
-/*
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-*/
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "servermd.h"
-#include "gcstruct.h"
-#include "window.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "windowstr.h"
-
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "cfb8bit.h"
-
-#include "mergerop.h"
-
-#include "mi.h"
-#include "mispans.h"
-
-#ifdef sparc
-#define SHARED_IDCACHE
-#endif
-
-#if PSZ == 24
-#define STORE(p)    (*(p) = MROP_PREBUILT_SOLID(srcpix,*(p)))
-/*#define STORE24(p,index)    {\
-	    register int idx = ((index) & 3)<< 1; \
-	    *(p) = (((MROP_PREBUILT_SOLID(srcpix,*(p))<<cfb24Shift[idx])&cfbmask[idx])| \
-	            (*(p)&cfbrmask[idx])); \
-	    idx++; \
-	    (p)++; \
-	    *(p) = (((MROP_PREBUILT_SOLID(srcpix,*(p))>>cfb24Shift[idx])&cfbmask[idx])| \
-	            (*(p)&cfbrmask[idx])); \
-	    (p)--; \
-	}*/
-#define STORE24(p,index)    MROP_PREBUILT_SOLID24(srcpix, (p), index)
-
-#define STORE_MASK(p,mask)    (*(p) = MROP_PREBUILT_MASK(srcpix,*(p),(mask)))
-#define QSTORE(p)    ((*(p) = MROP_PREBUILT_SOLID(((srcpix<<24)|srcpix),*(p))), \
-                      (p)++,(*(p) = MROP_PREBUILT_SOLID(((srcpix<<16)|(srcpix>>8)),*(p))), \
-                      (p)++,(*(p) = MROP_PREBUILT_SOLID(((srcpix<<8)|(srcpix>>16)),*(p))))
-
-#if (MROP == Mcopy) && defined(FAST_CONSTANT_OFFSET_MODE) && defined(SHARED_IDCACHE)
-# define Expand(left,right) {\
-    int part = nlwMiddle & ((PGSZB*2)-1); \
-    nlwMiddle *= 3; \
-    nlwMiddle >>= PWSH + 3; \
-    while (h--) { \
-	srcpix = psrc[srcy]; \
-	MROP_PREBUILD(srcpix); \
-	++srcy; \
-	if (srcy == tileHeight) \
-	    srcy = 0; \
-	left \
-	p += part; \
-	switch (part) { \
-	case 7: \
-	    STORE24(p - 7, xtmp - 7); \
-	case 6: \
-	    STORE24(p - 6, xtmp - 6); \
-	case 5: \
-	    STORE24(p - 5, xtmp - 5); \
-	case 4: \
-	    STORE24(p - 4, xtmp - 4); \
-	case 3: \
-	    STORE24(p - 3, xtmp - 3); \
-	case 2: \
-	    STORE24(p - 2, xtmp - 2); \
-	case 1: \
-	    STORE24(p - 1, xtmp - 1); \
-	} \
-	nlw = nlwMiddle; \
-	while (nlw) { \
-	    STORE24 (p + 0, xtmp + 0); \
-	    STORE24 (p + 1, xtmp + 1); \
-	    STORE24 (p + 2, xtmp + 2); \
-	    STORE24 (p + 3, xtmp + 3); \
-	    STORE24 (p + 4, xtmp + 4); \
-	    STORE24 (p + 5, xtmp + 5); \
-	    STORE24 (p + 6, xtmp + 6); \
-	    STORE24 (p + 7, xtmp + 7); \
-	    p += 8; \
-	    xtmp += 8; \
-	    nlw--; \
-	} \
-	right \
-	p += nlwExtra; \
-    } \
-}
-#else
-#define Expand(left,right) {\
-    while (h--)	{ \
-	srcpix = psrc[srcy]; \
-	MROP_PREBUILD(srcpix); \
-	++srcy; \
-	if (srcy == tileHeight) \
-	    srcy = 0; \
-	left \
-	while (nlw--) \
-	{ \
-	    STORE24(p,xtmp); \
-	    if(xtmp&3) p++; \
-	    xtmp++; \
-	} \
-	right \
-	p += nlwExtra; \
-    } \
-}
-#endif
-#else /*PSZ != 24*/
-#define STORE(p)    (*(p) = MROP_PREBUILT_SOLID(srcpix,*(p)))
-
-#if (MROP == Mcopy) && defined(FAST_CONSTANT_OFFSET_MODE) && defined(SHARED_IDCACHE)
-# define Expand(left,right) {\
-    int part = nlwMiddle & ((PGSZB*2)-1); \
-    nlwMiddle >>= PWSH + 1; \
-    while (h--) { \
-	srcpix = psrc[srcy]; \
-	MROP_PREBUILD(srcpix); \
-	++srcy; \
-	if (srcy == tileHeight) \
-	    srcy = 0; \
-	left \
-	p += part; \
-	switch (part) { \
-	case 7: \
-	    STORE(p - 7); \
-	case 6: \
-	    STORE(p - 6); \
-	case 5: \
-	    STORE(p - 5); \
-	case 4: \
-	    STORE(p - 4); \
-	case 3: \
-	    STORE(p - 3); \
-	case 2: \
-	    STORE(p - 2); \
-	case 1: \
-	    STORE(p - 1); \
-	} \
-	nlw = nlwMiddle; \
-	while (nlw) { \
-	    STORE (p + 0); \
-	    STORE (p + 1); \
-	    STORE (p + 2); \
-	    STORE (p + 3); \
-	    STORE (p + 4); \
-	    STORE (p + 5); \
-	    STORE (p + 6); \
-	    STORE (p + 7); \
-	    p += 8; \
-	    nlw--; \
-	} \
-	right \
-	p += nlwExtra; \
-    } \
-}
-#else
-#define Expand(left,right) {\
-    while (h--)	{ \
-	srcpix = psrc[srcy]; \
-	MROP_PREBUILD(srcpix); \
-	++srcy; \
-	if (srcy == tileHeight) \
-	    srcy = 0; \
-	left \
-	nlw = nlwMiddle; \
-	while (nlw--) \
-	{ \
-	    STORE(p); \
-	    p++; \
-	} \
-	right \
-	p += nlwExtra; \
-    } \
-}
-#endif
-#endif /*PSZ == 24*/
-
-void
-MROP_NAME(cfbFillRectTile32) (pDrawable, pGC, nBox, pBox)
-    DrawablePtr	    pDrawable;
-    GCPtr	    pGC;
-    int		    nBox;	/* number of boxes to fill */
-    BoxPtr 	    pBox;	/* pointer to list of boxes to fill */
-{
-    register CfbBits srcpix;	
-    CfbBits *psrc;		/* pointer to bits in tile, if needed */
-    int tileHeight;	/* height of the tile */
-
-    int nlwDst;		/* width in longwords of the dest pixmap */
-    int w;		/* width of current box */
-    register int h;	/* height of current box */
-    register CfbBits startmask;
-    register CfbBits endmask; /* masks for reggedy bits at either end of line */
-    int nlwMiddle;	/* number of longwords between sides of boxes */
-    int nlwExtra;	/* to get from right of box to left of next span */
-    register int nlw = 0;	/* loop version of nlwMiddle */
-    register CfbBits *p;	/* pointer to bits we're writing */
-    int y;		/* current scan line */
-    int srcy;		/* current tile position */
-
-    CfbBits *pbits;/* pointer to start of pixmap */
-    PixmapPtr	    tile;	/* rotated, expanded tile */
-#if MROP == 0 && PSZ == 24
-    DeclareMergeRop()
-#else
-    MROP_DECLARE_REG()
-#endif
-    MROP_PREBUILT_DECLARE()
-#if PSZ == 24
-    CfbBits xtmp;
-#endif
-
-    tile = pGC->pRotatedPixmap;
-    tileHeight = tile->drawable.height;
-    psrc = (CfbBits *)tile->devPrivate.ptr;
-
-#if MROP == 0 && PSZ == 24
-    InitializeMergeRop(pGC->alu, pGC->planemask);
-#else
-    MROP_INITIALIZE(pGC->alu, pGC->planemask);
-#endif
-
-    cfbGetLongWidthAndPointer (pDrawable, nlwDst, pbits)
-
-    while (nBox--)
-    {
-	w = pBox->x2 - pBox->x1;
-	h = pBox->y2 - pBox->y1;
-	y = pBox->y1;
-#if PSZ == 24
-	xtmp = pBox->x1;
-	p = pbits + (y * nlwDst) + ((pBox->x1*3) >> 2);
-/*	p = pbits + (y * nlwDst) + ((pBox->x1>> 2)*3);*/
-#else
-	p = pbits + (y * nlwDst) + (pBox->x1 >> PWSH);
-#endif
-	srcy = y % tileHeight;
-
-#if PSZ == 24
-	if (w == 1  &&  ((pBox->x1 & 3) == 0  ||  (pBox->x1 & 3) == 3))
-#else
-	if ( ((pBox->x1 & PIM) + w) <= PPW)
-#endif
-	{
-	    maskpartialbits(pBox->x1, w, startmask);
-	    nlwExtra = nlwDst;
-	    while (h--)
-	    {
-		srcpix = psrc[srcy];
-		MROP_PREBUILD(srcpix);
-		++srcy;
-		if (srcy == tileHeight)
-		    srcy = 0;
-		*p = MROP_PREBUILT_MASK (srcpix, *p, startmask);
-		p += nlwExtra;
-	    }
-	}
-	else
-	{
-	    maskbits(pBox->x1, w, startmask, endmask, nlwMiddle);
-	    nlwExtra = nlwDst - nlwMiddle;
-
-	    if (startmask)
-	    {
-		nlwExtra -= 1;
-		if (endmask)
-		{
-		    Expand(*p = MROP_PREBUILT_MASK(srcpix, *p, startmask); p++;,
-			   *p = MROP_PREBUILT_MASK(srcpix, *p, endmask);)
-		}
-		else
-		{
-		    Expand(*p = MROP_PREBUILT_MASK(srcpix, *p, startmask); p++;,
-			   ;)
-		}
-	    }
-	    else
-	    {
-		if (endmask)
-		{
-		    Expand(;,
-			   *p = MROP_PREBUILT_MASK(srcpix, *p, endmask);)
-		}
-		else
-		{
-		    Expand(;,
-			   ;)
-		}
-	    }
-	}
-        pBox++;
-    }
-}
-
-void
-MROP_NAME(cfbTile32FS)(pDrawable, pGC, nInit, pptInit, pwidthInit, fSorted)
-    DrawablePtr pDrawable;
-    GCPtr	pGC;
-    int		nInit;			/* number of spans to fill */
-    DDXPointPtr pptInit;		/* pointer to list of start points */
-    int		*pwidthInit;		/* pointer to list of n widths */
-    int 	fSorted;
-{
-				/* next three parameters are post-clip */
-    int			n;	/* number of spans to fill */
-    DDXPointPtr		ppt;	/* pointer to list of start points */
-    int			*pwidth;/* pointer to list of n widths */
-    CfbBits	*pbits;	/* pointer to start of bitmap */
-    int			nlwDst;	/* width in longwords of bitmap */
-    register CfbBits *p;	/* pointer to current longword in bitmap */
-    register int	w;	/* current span width */
-    register int	nlw;
-    register int	x;
-    register CfbBits startmask;
-    register CfbBits endmask;
-    register CfbBits  srcpix;
-    int			y;
-    int			*pwidthFree;/* copies of the pointers to free */
-    DDXPointPtr		pptFree;
-    PixmapPtr		tile;
-    CfbBits	*psrc;	/* pointer to bits in tile */
-    int			tileHeight;/* height of the tile */
-#if MROP == 0 && PSZ == 24
-    DeclareMergeRop()
-#else
-    MROP_DECLARE_REG()
-#endif
-    MROP_PREBUILT_DECLARE()
-#if PSZ == 24      
-    CfbBits	xtmp;
-#endif
-
-    n = nInit * miFindMaxBand( cfbGetCompositeClip(pGC) );
-    pwidthFree = (int *)xalloc(n * sizeof(int));
-    pptFree = (DDXPointRec *)xalloc(n * sizeof(DDXPointRec));
-    if(!pptFree || !pwidthFree)
-    {
-	if (pptFree) xfree(pptFree);
-	if (pwidthFree) xfree(pwidthFree);
-	return;
-    }
-    pwidth = pwidthFree;
-    ppt = pptFree;
-    n = miClipSpans( cfbGetCompositeClip(pGC),
-		     pptInit, pwidthInit, nInit,
-		     ppt, pwidth, fSorted);
-
-    tile = pGC->pRotatedPixmap;
-    tileHeight = tile->drawable.height;
-    psrc = (CfbBits *)tile->devPrivate.ptr;
-
-#if MROP == 0 && PSZ == 24
-    InitializeMergeRop(pGC->alu, pGC->planemask);
-#else
-    MROP_INITIALIZE(pGC->alu, pGC->planemask);
-#endif
-
-    cfbGetLongWidthAndPointer (pDrawable, nlwDst, pbits)
-
-#if MROP == Mcopy
-    if (!(tileHeight & (tileHeight-1)))
-    {
-	tileHeight--;
-    	while (n--)
-    	{
-	    x = ppt->x;
-	    y = ppt->y;
-	    ++ppt;
-	    w = *pwidth++;
-#if PSZ == 24
-/*	    p = pbits + (y * nlwDst) + ((x*3) >> 2);*/
-	    xtmp = x;
-	    p = pbits + (y * nlwDst) + ((x >> 2)*3);
-#else
-	    p = pbits + (y * nlwDst) + (x >> PWSH);
-#endif
-	    srcpix = psrc[y & tileHeight];
-	    MROP_PREBUILD(srcpix);
-    
-#if PSZ == 24
-	    if ((x & 3) + w < 5)
-#else
-	    if ((x & PIM) + w < PPW)
-#endif
-	    {
-	    	maskpartialbits(x, w, startmask);
-	    	*p = MROP_PREBUILT_MASK (srcpix, *p, startmask);
-	    }
-	    else
-	    {
-	    	maskbits(x, w, startmask, endmask, nlw);
-	    	if (startmask)
-	    	{
-		    *p = MROP_PREBUILT_MASK(srcpix, *p, startmask);
-#if PSZ == 24
-		    if(xtmp&3) p++;
-		    xtmp++;
-#else
-		    p++;
-#endif
-	    	}
-	    	while (nlw--)
-	    	{
-#if PSZ == 24
-		    STORE24(p,xtmp);
-		    if(xtmp&3) p++;
-		    ++xtmp;
-#else
-		    STORE(p);
-		    ++p;
-#endif
-	    	}
-	    	if (endmask)
-	    	{
-		    *p = MROP_PREBUILT_MASK(srcpix, *p, endmask);
-	    	}
-	    }
-    	}
-    }
-    else
-#endif
-    {
-    	while (n--)
-    	{
-	    x = ppt->x;
-	    y = ppt->y;
-	    ++ppt;
-	    w = *pwidth++;
-#if PSZ == 24
-/*	    p = pbits + (y * nlwDst) + ((x *3)>> 2);*/
-	    p = pbits + (y * nlwDst) + ((x >> 2)*3);
-	    xtmp = x;
-#else
-	    p = pbits + (y * nlwDst) + (x >> PWSH);
-#endif
-	    srcpix = psrc[y % tileHeight];
-	    MROP_PREBUILD(srcpix);
-    
-#if PSZ == 24
-	    if ((x & 3) + w < 5)
-#else
-	    if ((x & PIM) + w < PPW)
-#endif
-	    {
-	    	maskpartialbits(x, w, startmask);
-	    	*p = MROP_PREBUILT_MASK (srcpix, *p, startmask);
-	    }
-	    else
-	    {
-	    	maskbits(x, w, startmask, endmask, nlw);
-	    	if (startmask)
-	    	{
-		    *p = MROP_PREBUILT_MASK(srcpix, *p, startmask);
-#if PSZ == 24
-		    if(xtmp&3)p++;
-		    xtmp++;
-#else
-		    p++;
-#endif
-	    	}
-	    	while (nlw--)
-	    	{
-#if PSZ == 24
-		    STORE24(p,xtmp);
-		    if(xtmp&3)p++;
-		    xtmp++;
-#else
-		    STORE(p);
-		    ++p;
-#endif
-	    	}
-	    	if (endmask)
-	    	{
-		    *p = MROP_PREBUILT_MASK(srcpix, *p, endmask);
-	    	}
-	    }
-    	}
-    }
-    xfree(pptFree);
-    xfree(pwidthFree);
-}
diff --git a/cfb/cfbtileodd.c b/cfb/cfbtileodd.c
deleted file mode 100644
index 86a3fa5..0000000
--- a/cfb/cfbtileodd.c
+++ /dev/null
@@ -1,1245 +0,0 @@
-/*
- * Fill odd tiled rectangles and spans.
- * no depth dependencies.
- */
-
-/*
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-*/
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "servermd.h"
-#include "gcstruct.h"
-#include "window.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "windowstr.h"
-
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "cfb8bit.h"
-
-#include "mergerop.h"
-
-#if PSZ == 24
-#define LEFTSHIFT_AMT (3)
-#else /* PSZ != 24 */
-#define LEFTSHIFT_AMT (5 - PWSH)
-#endif /* PSZ == 24*/
-
-#define LastTileBits {\
-    tmp = bits; \
-    if (tileEndPart) \
-	bits = (*pSrc & tileEndMask) | BitRight (*pSrcLine, tileEndLeftShift); \
-    else \
-	bits = *pSrc; \
-}
-
-#if PSZ == 24
-#define ResetTileBits {\
-    pSrc = pSrcLine; \
-    nlwSrc = widthSrc;\
-    if (tileEndPart) { \
-	if (4 - xoff + tileEndPart <= 4) {\
-	    bits = *pSrc++; \
-	    nlwSrc--; \
-	} else \
-	    bits = BitLeft(tmp, tileEndLeftShift) | \
-		   BitRight(bits, tileEndRightShift); \
-	xoff = (xoff + xoffStep) & 3; \
-	leftShift = xoff << LEFTSHIFT_AMT; \
-	rightShift = PGSZ - leftShift; \
-    }\
-}
-#else
-#define ResetTileBits {\
-    pSrc = pSrcLine; \
-    nlwSrc = widthSrc;\
-    if (tileEndPart) { \
-	if (PPW - xoff + tileEndPart <= PPW) {\
-	    bits = *pSrc++; \
-	    nlwSrc--; \
-	} else \
-	    bits = BitLeft(tmp, tileEndLeftShift) | \
-		   BitRight(bits, tileEndRightShift); \
-	xoff = (xoff + xoffStep) & PIM; \
-	leftShift = xoff << LEFTSHIFT_AMT; \
-	rightShift = PGSZ - leftShift; \
-    }\
-}
-#endif
-
-#define NextTileBits {\
-    if (nlwSrc == 1) {\
-	LastTileBits\
-    } else { \
-    	if (nlwSrc == 0) {\
-	    ResetTileBits\
-    	} \
-	if (nlwSrc == 1) {\
-	    LastTileBits\
-	} else {\
-	    tmp = bits; \
-	    bits = *pSrc++; \
-	}\
-    }\
-    nlwSrc--; \
-}
-
-void
-MROP_NAME(cfbFillBoxTileOdd) (pDrawable, nBox, pBox, tile, xrot, yrot, alu, planemask)
-    DrawablePtr	    pDrawable;
-    int		    nBox;	/* number of boxes to fill */
-    register BoxPtr pBox;	/* pointer to list of boxes to fill */
-    PixmapPtr	    tile;	/* tile */
-    int		    xrot, yrot;
-    int		    alu;
-    unsigned long   planemask;
-{
-    int tileWidth;	/* width of tile in pixels */
-    int tileHeight;	/* height of the tile */
-    int widthSrc;
-
-    int widthDst;	/* width in longwords of the dest pixmap */
-    int w;		/* width of current box */
-    int h;		/* height of current box */
-    CfbBits startmask;
-    CfbBits endmask;/* masks for reggedy bits at either end of line */
-    int nlwMiddle;	/* number of longwords between sides of boxes */
-    int nlwSrc;		/* number of whole longwords in source */
-    
-    register int nlw;	/* loop version of nlwMiddle */
-    int srcy;		/* current tile y position */
-    int srcx;		/* current tile x position */
-    int xoffDst, xoffSrc;
-    int leftShift, rightShift;
-
-#if MROP == 0 && PSZ == 24
-    DeclareMergeRop24()
-#else
-    MROP_DECLARE_REG()
-#endif
-
-    CfbBits *pdstBase;	/* pointer to start of dest */
-    CfbBits *pDstLine;	/* poitner to start of dest box */
-    CfbBits *pSrcBase;	/* pointer to start of source */
-    CfbBits *pSrcLine;	/* pointer to start of source line */
-    register CfbBits *pDst;
-    register CfbBits *pSrc;
-    register CfbBits bits, tmp = 0;
-    int xoffStart, xoff;
-    int leftShiftStart, rightShiftStart, nlwSrcStart;
-    CfbBits tileEndMask;
-    int tileEndLeftShift, tileEndRightShift;
-    int	xoffStep;
-    int tileEndPart;
-    int needFirst;
-    CfbBits   narrow[2];
-    CfbBits   narrowMask = 0;
-    int	    narrowShift = 0;
-    Bool    narrowTile;
-
-#if MROP == 0 && PSZ == 24
-    InitializeMergeRop24 (alu, planemask)
-#else
-    MROP_INITIALIZE (alu, planemask)
-#endif
-
-    tileHeight = tile->drawable.height;
-    tileWidth = tile->drawable.width;
-    widthSrc = tile->devKind / PGSZB;
-    narrowTile = FALSE;
-    if (widthSrc == 1)
-    {
-	narrowShift = tileWidth;
-	narrowMask = cfbendpartial [tileWidth];
-	tileWidth *= 2;
-	widthSrc = 2;
-	narrowTile = TRUE;
-    }
-    pSrcBase = (CfbBits *)tile->devPrivate.ptr;
-
-    cfbGetLongWidthAndPointer (pDrawable, widthDst, pdstBase)
-
-#if PSZ == 24
-    tileEndPart = (4 - tileWidth) & 3;
-    tileEndMask = cfbendpartial[tileWidth & 3];
-#else
-    tileEndPart = tileWidth & PIM;
-    tileEndMask = cfbendpartial[tileEndPart];
-#endif /* PSZ == 24 */
-    tileEndLeftShift = (tileEndPart) << LEFTSHIFT_AMT;
-    tileEndRightShift = PGSZ - tileEndLeftShift;
-#if PSZ == 24
-    xoffStep = 4 - tileEndPart;
-#else
-    xoffStep = PPW - tileEndPart;
-#endif /* PSZ == 24 */
-    /*
-     * current assumptions: tile > 32 bits wide.
-     */
-    while (nBox--)
-    {
-	w = pBox->x2 - pBox->x1;
-	h = pBox->y2 - pBox->y1;
-	modulus (pBox->x1 - xrot, tileWidth, srcx);
-	modulus (pBox->y1 - yrot, tileHeight, srcy);
-#if PSZ == 24
-	xoffDst = (4 - pBox->x1) & 3;
-	if (w == 1  &&  (xoffDst == 0  ||  xoffDst == 1))
-#else
-	xoffDst = pBox->x1 & PIM;
-	if (xoffDst + w < PPW)
-#endif
-	{
-	    maskpartialbits(pBox->x1, w, startmask);
-	    endmask = 0;
-	    nlwMiddle = 0;
-	}
-	else
-	{
-	    maskbits (pBox->x1, w, startmask, endmask, nlwMiddle)
-	}
-#if PSZ == 24
-	pDstLine = pdstBase + (pBox->y1 * widthDst) + ((pBox->x1*3) >> 2);
-#else
-	pDstLine = pdstBase + (pBox->y1 * widthDst) + (pBox->x1 >> PWSH);
-#endif
-	pSrcLine = pSrcBase + (srcy * widthSrc);
-#if PSZ == 24
-	xoffSrc = (4 - srcx) & 3;
-#else
-	xoffSrc = srcx & PIM;
-#endif
-	if (xoffSrc >= xoffDst)
-	{
-	    xoffStart = xoffSrc - xoffDst;
-	    needFirst = 1;
-	}
-	else
-	{
-#if PSZ == 24
-	    xoffStart = 4 - (xoffDst - xoffSrc);
-#else
-	    xoffStart = PPW - (xoffDst - xoffSrc);
-#endif
-	    needFirst = 0;
-	}
-	leftShiftStart = (xoffStart) << LEFTSHIFT_AMT;
-	rightShiftStart = PGSZ - leftShiftStart;
-#if PSZ == 24
-	nlwSrcStart = widthSrc - ((srcx*3) >> 2);
-#else
-	nlwSrcStart = widthSrc - (srcx >> PWSH);
-#endif
-	while (h--)
-	{
-	    /* XXX only works when narrowShift >= PPW/2 */
-	    if (narrowTile)
-	    {
-		tmp = pSrcBase[srcy] & narrowMask; /* source width == 1 */
-		narrow[0] = tmp | SCRRIGHT (tmp, narrowShift);
-#if PSZ == 24
-		narrow[1] = BitLeft (tmp, 8) |
-			    BitRight(tmp, 16);
-#else
-		narrow[1] = SCRLEFT (tmp, PPW - narrowShift) |
-			    SCRRIGHT(tmp, 2 * narrowShift - PPW);
-#endif
-		pSrcLine = narrow;
-	    }
-	    xoff = xoffStart;
-	    leftShift = leftShiftStart;
-	    rightShift = rightShiftStart;
-	    nlwSrc = nlwSrcStart;
-#if PSZ == 24
-	    pSrc = pSrcLine + ((srcx * 3) >> 2);
-#else
-	    pSrc = pSrcLine + (srcx >> PWSH);
-#endif
-	    pDst = pDstLine;
-	    bits = 0;
-	    if (needFirst)
-	    {
-		NextTileBits
-	    }
-	    if (startmask)
-	    {
-		NextTileBits
-		tmp = BitLeft(tmp, leftShift);
- 		if (rightShift != PGSZ)
-		    tmp |= BitRight(bits,rightShift);
-		*pDst = MROP_MASK (tmp, *pDst, startmask);
-		++pDst;
-	    }
-	    nlw = nlwMiddle;
-	    while (nlw)
-	    {
-#if MROP == Mcopy
-		if (nlwSrc > 1)
-		{
-		    int nlwPart = nlw;
-
-		    if (nlwPart >= nlwSrc)
-			nlwPart = nlwSrc - 1;
-		    nlw -= nlwPart;
-		    nlwSrc -= nlwPart;
-		    if (rightShift != PGSZ)
-		    {
-			while (nlwPart--)
-			{
-			    tmp = bits;
-			    bits = *pSrc++;
-			    *pDst = MROP_SOLID(BitLeft(tmp, leftShift) |
-					      BitRight (bits, rightShift),
-					      *pDst);
-			    ++pDst;
-			}
-		    }
-		    else
-		    {
-			if (nlwPart)
-			{
-			    *pDst = MROP_SOLID (bits, *pDst);
-			    ++pDst;
-			    nlwPart--;
-			    while (nlwPart--)
-			    {
-				*pDst = MROP_SOLID(*pSrc, *pDst);
-				++pDst; ++pSrc;
-			    }
-			    bits = *pSrc++;
-			}
-		    }
-		}
-		else
-#endif
-		{
-		    NextTileBits
-		    if (rightShift != PGSZ)
-		    {
-			*pDst = MROP_SOLID(BitLeft(tmp, leftShift) |
-					   BitRight(bits, rightShift),
-					   *pDst);
-		    }
-		    else
-		    {
-			*pDst = MROP_SOLID (tmp, *pDst);
-		    }
-		    ++pDst;
-		    nlw--;
-		}
-	    }
-	    if (endmask)
-	    {
-		NextTileBits
-		if (rightShift == PGSZ)
-		    bits = 0;
-		*pDst = MROP_MASK (BitLeft(tmp, leftShift) |
-				   BitRight(bits,rightShift),
-				   *pDst, endmask);
-	    }
-	    pDstLine += widthDst;
-	    pSrcLine += widthSrc;
-	    if (++srcy == tileHeight)
-	    {
-		srcy = 0;
-		pSrcLine = pSrcBase;
-	    }
-	}
-	pBox++;
-    }
-}
-
-void
-MROP_NAME(cfbFillSpanTileOdd) (pDrawable, n, ppt, pwidth, tile, xrot, yrot, alu, planemask)
-    DrawablePtr	pDrawable;
-    int		n;
-    DDXPointPtr	ppt;
-    int		*pwidth;
-    PixmapPtr	tile;
-    int		xrot, yrot;
-    int		alu;
-    unsigned long   planemask;
-{
-    int tileWidth;	/* width of tile in pixels */
-    int tileHeight;	/* height of the tile */
-    int widthSrc;
-
-    int widthDst;		/* width in longwords of the dest pixmap */
-    int w;		/* width of current span */
-    CfbBits startmask;
-    CfbBits endmask;	/* masks for reggedy bits at either end of line */
-    int nlwSrc;		/* number of whole longwords in source */
-    
-    register int nlw;	/* loop version of nlwMiddle */
-    int srcy;		/* current tile y position */
-    int srcx;		/* current tile x position */
-    int xoffDst, xoffSrc;
-    int leftShift, rightShift;
-
-#if MROP == 0 && PSZ == 24
-    DeclareMergeRop24()
-#else
-    MROP_DECLARE_REG()
-#endif
-
-    CfbBits *pdstBase;	/* pointer to start of dest */
-    CfbBits *pDstLine;	/* poitner to start of dest box */
-    CfbBits *pSrcBase;	/* pointer to start of source */
-    CfbBits *pSrcLine;	/* pointer to start of source line */
-    register CfbBits *pDst;
-    register CfbBits *pSrc;
-    register CfbBits bits, tmp = 0;
-    int xoffStart, xoff;
-    int leftShiftStart, rightShiftStart, nlwSrcStart;
-    CfbBits tileEndMask;
-    int tileEndLeftShift, tileEndRightShift;
-    int	xoffStep;
-    int tileEndPart;
-    int needFirst;
-    CfbBits   narrow[2];
-    CfbBits   narrowMask = 0;
-    int	    narrowShift = 0;
-    Bool    narrowTile;
-
-#if MROP == 0 && PSZ == 24
-    InitializeMergeRop24 (alu, planemask)
-#else
-    MROP_INITIALIZE (alu, planemask)
-#endif
-
-    tileHeight = tile->drawable.height;
-    tileWidth = tile->drawable.width;
-    widthSrc = tile->devKind / PGSZB;
-    narrowTile = FALSE;
-    if (widthSrc == 1)
-    {
-	narrowShift = tileWidth;
-	narrowMask = cfbendpartial [tileWidth];
-	tileWidth *= 2;
-	widthSrc = 2;
-	narrowTile = TRUE;
-    }
-    pSrcBase = (CfbBits *)tile->devPrivate.ptr;
-
-    cfbGetLongWidthAndPointer (pDrawable, widthDst, pdstBase)
-
-#if PSZ == 24
-    tileEndPart = (4 - tileWidth) & 3;
-    tileEndMask = cfbendpartial[tileWidth & 3];
-#else
-    tileEndPart = tileWidth & PIM;
-    tileEndMask = cfbendpartial[tileEndPart];
-#endif
-    tileEndLeftShift = (tileEndPart) << LEFTSHIFT_AMT;
-    tileEndRightShift = PGSZ - tileEndLeftShift;
-#if PSZ == 24
-    xoffStep = 4 - tileEndPart;
-#else
-    xoffStep = PPW - tileEndPart;
-#endif
-    while (n--)
-    {
-	w = *pwidth++;
-	modulus (ppt->x - xrot, tileWidth, srcx);
-	modulus (ppt->y - yrot, tileHeight, srcy);
-#if PSZ == 24
-	xoffDst = (4 - ppt->x) & 3;
-	if (w == 1  &&  (xoffDst == 0  ||  xoffDst == 1))
-#else
-	xoffDst = ppt->x & PIM;
-	if (xoffDst + w < PPW)
-#endif
-	{
-	    maskpartialbits(ppt->x, w, startmask);
-	    endmask = 0;
-	    nlw = 0;
-	}
-	else
-	{
-	    maskbits (ppt->x, w, startmask, endmask, nlw)
-	}
-#if PSZ == 24
-	pDstLine = pdstBase + (ppt->y * widthDst)  + ((ppt->x *3)>> 2);
-#else
-	pDstLine = pdstBase + (ppt->y * widthDst) + (ppt->x >> PWSH);
-#endif
-	pSrcLine = pSrcBase + (srcy * widthSrc);
-#if PSZ == 24
-	xoffSrc = (4 - srcx) & 3;
-#else
-	xoffSrc = srcx & PIM;
-#endif
-	if (xoffSrc >= xoffDst)
-	{
-	    xoffStart = xoffSrc - xoffDst;
-	    needFirst = 1;
-	}
-	else
-	{
-#if PSZ == 24
-	    xoffStart = 4 - (xoffDst - xoffSrc);
-#else
-	    xoffStart = PPW - (xoffDst - xoffSrc);
-#endif
-	    needFirst = 0;
-	}
-	leftShiftStart = (xoffStart) << LEFTSHIFT_AMT;
-	rightShiftStart = PGSZ - leftShiftStart;
-#if PSZ == 24
-	nlwSrcStart = widthSrc - ((srcx*3) >> 2);
-#else
-	nlwSrcStart = widthSrc - (srcx >> PWSH);
-#endif
-	/* XXX only works when narrowShift >= PPW/2 */
-	if (narrowTile)
-	{
-	    tmp = pSrcBase[srcy] & narrowMask;	/* source width == 1 */
-	    narrow[0] = tmp | SCRRIGHT (tmp, narrowShift);
-#if PSZ == 24
-	    narrow[1] = BitLeft (tmp, 8) |
-			BitRight(tmp, 16);
-#else
-	    narrow[1] = SCRLEFT (tmp, PPW - narrowShift) |
-			SCRRIGHT(tmp, 2 * narrowShift - PPW);
-#endif
-	    pSrcLine = narrow;
-	}
-	xoff = xoffStart;
-	leftShift = leftShiftStart;
-	rightShift = rightShiftStart;
-	nlwSrc = nlwSrcStart;
-#if PSZ == 24
-	pSrc = pSrcLine + ((srcx * 3) >> 2);
-#else
-	pSrc = pSrcLine + (srcx >> PWSH);
-#endif
-	pDst = pDstLine;
-	bits = 0;
-	if (needFirst)
-	{
-	    NextTileBits
-	}
-	if (startmask)
-	{
-	    NextTileBits
-	    tmp = BitLeft(tmp, leftShift);
-	    if (rightShift != PGSZ)
-		tmp |= BitRight(bits,rightShift);
-	    *pDst = MROP_MASK (tmp, *pDst, startmask);
-	    ++pDst;
-	}
-	while (nlw)
-	{
-#if MROP == Mcopy
-	    if (nlwSrc > 1)
-	    {
-		int nlwPart = nlw;
-
-		if (nlwPart >= nlwSrc)
-		    nlwPart = nlwSrc - 1;
-		nlw -= nlwPart;
-		nlwSrc -= nlwPart;
-		if (rightShift != PGSZ)
-		{
-		    while (nlwPart--)
-		    {
-			tmp = bits;
-			bits = *pSrc++;
-			*pDst = MROP_SOLID(BitLeft(tmp, leftShift) |
-					  BitRight (bits, rightShift),
-					  *pDst);
-			++pDst;
-		    }
-		}
-		else
-		{
-		    if (nlwPart)
-		    {
-			*pDst = MROP_SOLID (bits, *pDst);
-			++pDst;
-			nlwPart--;
-			while (nlwPart--)
-			{
-			    *pDst = MROP_SOLID(*pSrc, *pDst);
-			    ++pDst; ++pSrc;
-			}
-			bits = *pSrc++;
-		    }
-		}
-	    }
-	    else
-#endif
-	    {
-		NextTileBits
-		if (rightShift != PGSZ)
-		{
-		    *pDst = MROP_SOLID(BitLeft(tmp, leftShift) |
-				       BitRight(bits, rightShift),
-				       *pDst);
-		    ++pDst;
-		}
-		else
-		{
-		    *pDst = MROP_SOLID (tmp, *pDst);
-		    ++pDst;
-		}
-		nlw--;
-	    }
-	}
-	if (endmask)
-	{
-	    NextTileBits
-	    if (rightShift == PGSZ)
-		bits = 0;
-	    *pDst = MROP_MASK (BitLeft(tmp, leftShift) |
-			       BitRight(bits,rightShift),
-			       *pDst, endmask);
-	}
-	ppt++;
-    }
-}
-
-# include "fastblt.h"
-
-#define IncSrcPtr   psrc++; if (!--srcRemaining) { srcRemaining = widthSrc; psrc = psrcStart; }
-
-void
-MROP_NAME(cfbFillBoxTile32s) (pDrawable, nBox, pBox, tile, xrot, yrot, alu, planemask)
-    DrawablePtr	    pDrawable;
-    int		    nBox;	/* number of boxes to fill */
-    register BoxPtr pBox;	/* pointer to list of boxes to fill */
-    PixmapPtr	    tile;	/* tile */
-    int		    xrot, yrot;
-    int		    alu;
-    unsigned long   planemask;
-{
-    int	tileWidth;	/* width of tile */
-    int tileHeight;	/* height of the tile */
-    int	widthSrc;	/* width in longwords of the source tile */
-
-    int widthDst;	/* width in longwords of the dest pixmap */
-    int w;		/* width of current box */
-    int h;		/* height of current box */
-    CfbBits startmask;
-    CfbBits endmask;/* masks for reggedy bits at either end of line */
-    int nlMiddle;	/* number of longwords between sides of boxes */
-    
-    register int nl;	/* loop version of nlMiddle */
-    int srcy;		/* current tile y position */
-    int srcx;		/* current tile x position */
-    int	srcRemaining;	/* number of longwords remaining in source */
-    int xoffDst, xoffSrc;
-    int	srcStart;	/* number of longwords source offset at left of box */
-    int	leftShift, rightShift;
-
-#if MROP == 0 && PSZ == 24
-    DeclareMergeRop24()
-#else
-    MROP_DECLARE_REG()
-#endif
-
-    CfbBits	    *pdstBase;	/* pointer to start of dest */
-    CfbBits	    *pdstLine;	/* poitner to start of dest box */
-    CfbBits	    *psrcBase;	/* pointer to start of source */
-    CfbBits	    *psrcLine;	/* pointer to fetch point of source */
-    CfbBits	    *psrcStart;	/* pointer to start of source line */
-    register CfbBits  *pdst;
-    register CfbBits  *psrc;
-    register CfbBits  bits, bits1;
-    register int	    nlTemp;
-
-#if MROP == 0 && PSZ == 24
-    InitializeMergeRop24 (alu, planemask)
-#else
-    MROP_INITIALIZE (alu, planemask)
-#endif
-
-    psrcBase = (CfbBits *)tile->devPrivate.ptr;
-    tileHeight = tile->drawable.height;
-    tileWidth = tile->drawable.width;
-#if PSZ == 24
-    widthSrc = tile->devKind / PGSZB;
-#else
-    widthSrc = tileWidth >> PWSH;
-#endif
-
-    cfbGetLongWidthAndPointer (pDrawable, widthDst, pdstBase)
-
-    while (nBox--)
-    {
-	w = pBox->x2 - pBox->x1;
-	h = pBox->y2 - pBox->y1;
-
-	/* set up source */
-	modulus (pBox->x1 - xrot, tileWidth, srcx);
-	modulus (pBox->y1 - yrot, tileHeight, srcy);
-#if PSZ == 24
-	xoffSrc = (4 - srcx) & 3;
-	srcStart = (srcx * 3) >> 2;
-#else
-	xoffSrc = srcx & PIM;
-	srcStart = (srcx >> PWSH);
-#endif
-	psrcStart = psrcBase + (srcy * widthSrc);
-	psrcLine = psrcStart + srcStart;
-
-	/* set up dest */
-#if PSZ == 24
-	xoffDst = (4 - pBox->x1) & 3;
-	pdstLine = pdstBase + (pBox->y1 * widthDst) + ((pBox->x1*3) >> 2);
-#else
-	xoffDst = pBox->x1 & PIM;
-	pdstLine = pdstBase + (pBox->y1 * widthDst) + (pBox->x1 >> PWSH);
-#endif
-	/* set up masks */
-#if PSZ == 24
-	if (w == 1  &&  (xoffDst == 0  ||  xoffDst == 1))
-#else
-	if (xoffDst + w < PPW)
-#endif
-	{
-	    maskpartialbits(pBox->x1, w, startmask);
-	    endmask = 0;
-	    nlMiddle = 0;
-	}
-	else
-	{
-	    maskbits (pBox->x1, w, startmask, endmask, nlMiddle)
-	}
-	if (xoffSrc == xoffDst)
-	{
-	    while (h--)
-	    {
-		psrc = psrcLine;
-		pdst = pdstLine;
-		srcRemaining = widthSrc - srcStart;
-		if (startmask)
-		{
-		    *pdst = MROP_MASK (*psrc, *pdst, startmask);
-		    pdst++;
-		    IncSrcPtr
-		}
-		nlTemp = nlMiddle;
-		while (nlTemp)
-		{
-		    nl = nlTemp;
-		    if (nl > srcRemaining)
-			nl = srcRemaining;
-
-		    nlTemp -= nl;
-		    srcRemaining -= nl;
-
-#if MROP == Mcopy
-#ifdef LARGE_INSTRUCTION_CACHE
-#ifdef FAST_CONSTANT_OFFSET_MODE
-
-		    psrc += nl & (UNROLL-1);
-		    pdst += nl & (UNROLL-1);
-
-#define BodyOdd(n) pdst[-n] = MROP_SOLID (psrc[-n], pdst[-n]);
-#define BodyEven(n) pdst[-n] = MROP_SOLID (psrc[-n], pdst[-n]);
-
-#define LoopReset \
-pdst += UNROLL; \
-psrc += UNROLL;
-
-#else
-
-#define BodyOdd(n)  *pdst = MROP_SOLID (*psrc, *pdst); pdst++; psrc++;
-#define BodyEven(n) BodyOdd(n)
-
-#define LoopReset   ;
-
-#endif
-		    PackedLoop
-
-#undef BodyOdd
-#undef BodyEven
-#undef LoopReset
-
-#else
-		    DuffL(nl, label1,
-			    *pdst = MROP_SOLID (*psrc, *pdst);
-			    pdst++; psrc++;)
-#endif
-#else
-		    while (nl--) {
-			    *pdst = MROP_SOLID (*psrc, *pdst);
-			    pdst++; psrc++;
-		    }
-#endif
-		    if (!srcRemaining)
-		    {
-			srcRemaining = widthSrc;
-			psrc = psrcStart;
-		    }
-		}
-		if (endmask)
-		{
-		    *pdst = MROP_MASK (*psrc, *pdst, endmask);
-		}
-		pdstLine += widthDst;
-		psrcLine += widthSrc;
-		psrcStart += widthSrc;
-		if (++srcy == tileHeight)
-		{
-		    psrcStart = psrcBase;
-		    psrcLine = psrcStart + srcStart;
-		    srcy = 0;
-		}
-	    }
-	}
-	else
-	{
-	    if (xoffSrc > xoffDst)
-	    {
-		leftShift = (xoffSrc - xoffDst) << LEFTSHIFT_AMT;
-		rightShift = PGSZ - leftShift;
-	    }
-	    else
-	    {
-		rightShift = (xoffDst - xoffSrc) << LEFTSHIFT_AMT;
-		leftShift = PGSZ - rightShift;
-	    }
-	    while (h--)
-	    {
-		psrc = psrcLine;
-		pdst = pdstLine;
-		bits = 0;
-		srcRemaining = widthSrc - srcStart;
-		if (xoffSrc > xoffDst)
-		{
-		    bits = *psrc;
-		    IncSrcPtr
-		}
-		if (startmask)
-		{
-		    bits1 = BitLeft(bits,leftShift);
-		    bits = *psrc;
-		    IncSrcPtr
-		    bits1 |= BitRight(bits,rightShift);
-		    *pdst = MROP_MASK(bits1, *pdst, startmask);
-		    pdst++;
-		}
-		nlTemp = nlMiddle;
-		while (nlTemp)
-		{
-		    nl = nlTemp;
-		    if (nl > srcRemaining)
-			nl = srcRemaining;
-
-		    nlTemp -= nl;
-		    srcRemaining -= nl;
-    
-#if MROP == Mcopy
-#ifdef LARGE_INSTRUCTION_CACHE
-		    bits1 = bits;
-    
-#ifdef FAST_CONSTANT_OFFSET_MODE
-    
-		    psrc += nl & (UNROLL-1);
-		    pdst += nl & (UNROLL-1);
-    
-#define BodyOdd(n) \
-    bits = psrc[-n]; \
-    pdst[-n] = MROP_SOLID(BitLeft(bits1, leftShift) | BitRight(bits, rightShift), pdst[-n]);
-    
-#define BodyEven(n) \
-    bits1 = psrc[-n]; \
-    pdst[-n] = MROP_SOLID(BitLeft(bits, leftShift) | BitRight(bits1, rightShift), pdst[-n]);
-    
-#define LoopReset \
-    pdst += UNROLL; \
-    psrc += UNROLL;
-    
-#else
-    
-#define BodyOdd(n) \
-    bits = *psrc++; \
-    *pdst = MROP_SOLID(BitLeft(bits1, leftShift) | BitRight(bits, rightShift), *pdst); \
-    pdst++;
-	       	   
-#define BodyEven(n) \
-    bits1 = *psrc++; \
-    *pdst = MROP_SOLID(BitLeft(bits, leftShift) | BitRight(bits1, rightShift), *pdst); \
-    pdst++;
-    
-#define LoopReset   ;
-    
-#endif	/* !FAST_CONSTANT_OFFSET_MODE */
-    
-		    PackedLoop
-    
-#undef BodyOdd
-#undef BodyEven
-#undef LoopReset
-    
-#else
-		    DuffL (nl,label2,
-		    	bits1 = BitLeft(bits, leftShift);
-		    	bits = *psrc++;
-		    	*pdst = MROP_SOLID (bits1 | BitRight(bits, rightShift), *pdst);
-		    	pdst++;
-		    )
-#endif
-#else
-		    while (nl--) {
-		    	bits1 = BitLeft(bits, leftShift);
-		    	bits = *psrc++;
-		    	*pdst = MROP_SOLID (bits1 | BitRight(bits, rightShift), *pdst);
-		    	pdst++;
-		    }
-#endif
-		    if (!srcRemaining)
-		    {
-			srcRemaining = widthSrc;
-			psrc = psrcStart;
-		    }
-		}
-
-		if (endmask)
-		{
-		    bits1 = BitLeft(bits, leftShift);
-		    if (BitLeft(endmask, rightShift))
-		    {
-			bits = *psrc;
-			bits1 |= BitRight(bits, rightShift);
-		    }
-		    *pdst = MROP_MASK (bits1, *pdst, endmask);
-		}
-		pdstLine += widthDst;
-		psrcLine += widthSrc;
-		psrcStart += widthSrc;
-		if (++srcy == tileHeight)
-		{
-		    psrcStart = psrcBase;
-		    psrcLine = psrcStart + srcStart;
-		    srcy = 0;
-		}
-	    }
-	}
-	pBox++;
-    }
-}
-
-void
-MROP_NAME(cfbFillSpanTile32s) (pDrawable, n, ppt, pwidth, tile, xrot, yrot, alu, planemask)
-    DrawablePtr	pDrawable;
-    int		n;
-    DDXPointPtr	ppt;
-    int		*pwidth;
-    PixmapPtr	tile;
-    int		xrot, yrot;
-    int		alu;
-    unsigned long   planemask;
-{
-    int	tileWidth;	/* width of tile */
-    int tileHeight;	/* height of the tile */
-    int	widthSrc;	/* width in longwords of the source tile */
-
-    int widthDst;	/* width in longwords of the dest pixmap */
-    int w;		/* width of current box */
-    CfbBits startmask;
-    CfbBits endmask;/* masks for reggedy bits at either end of line */
-    int nlMiddle;	/* number of longwords between sides of boxes */
-    
-    register int nl;	/* loop version of nlMiddle */
-    int srcy;		/* current tile y position */
-    int srcx;		/* current tile x position */
-    int	srcRemaining;	/* number of longwords remaining in source */
-    int xoffDst, xoffSrc;
-    int	srcStart;	/* number of longwords source offset at left of box */
-    int	leftShift, rightShift;
-
-#if MROP == 0 && PSZ == 24
-    DeclareMergeRop24()
-#else
-    MROP_DECLARE_REG()
-#endif
-
-    CfbBits	    *pdstBase;	/* pointer to start of dest */
-    CfbBits	    *pdstLine;	/* poitner to start of dest box */
-    CfbBits	    *psrcBase;	/* pointer to start of source */
-    CfbBits	    *psrcLine;	/* pointer to fetch point of source */
-    CfbBits	    *psrcStart;	/* pointer to start of source line */
-    register CfbBits  *pdst;
-    register CfbBits  *psrc;
-    register CfbBits  bits, bits1;
-    register int	    nlTemp;
-
-#if MROP == 0 && PSZ == 24
-    InitializeMergeRop24 (alu, planemask)
-#else
-    MROP_INITIALIZE (alu, planemask)
-#endif
-
-    psrcBase = (CfbBits *)tile->devPrivate.ptr;
-    tileHeight = tile->drawable.height;
-    tileWidth = tile->drawable.width;
-#if PSZ == 24
-    widthSrc = tile->devKind / PGSZB;
-#else
-    widthSrc = tileWidth >> PWSH;
-#endif
-
-    cfbGetLongWidthAndPointer (pDrawable, widthDst, pdstBase)
-
-    while (n--)
-    {
-	w = *pwidth++;
-
-	/* set up source */
-	modulus (ppt->x - xrot, tileWidth, srcx);
-	modulus (ppt->y - yrot, tileHeight, srcy);
-#if PSZ == 24
-	xoffSrc = (4 - srcx) & 3;
-	srcStart = (srcx * 3) >> 2;
-#else
-	xoffSrc = srcx & PIM;
-	srcStart = (srcx >> PWSH);
-#endif
-	psrcStart = psrcBase + (srcy * widthSrc);
-	psrcLine = psrcStart + srcStart;
-
-	/* set up dest */
-#if PSZ == 24
-	xoffDst = (4 - ppt->x) & 3;
-	pdstLine = pdstBase + (ppt->y * widthDst) + ((ppt->x *3) >> 2);
-	/* set up masks */
-	if (w == 1  &&  (xoffDst == 0  ||  xoffDst == 1))
-#else
-	xoffDst = ppt->x & PIM;
-	pdstLine = pdstBase + (ppt->y * widthDst) + (ppt->x >> PWSH);
-	/* set up masks */
-	if (xoffDst + w < PPW)
-#endif
-	{
-	    maskpartialbits(ppt->x, w, startmask);
-	    endmask = 0;
-	    nlMiddle = 0;
-	}
-	else
-	{
-	    maskbits (ppt->x, w, startmask, endmask, nlMiddle)
-	}
-
-	if (xoffSrc == xoffDst)
-	{
-	    psrc = psrcLine;
-	    pdst = pdstLine;
-	    srcRemaining = widthSrc - srcStart;
-	    if (startmask)
-	    {
-		*pdst = MROP_MASK (*psrc, *pdst, startmask);
-		pdst++;
-		IncSrcPtr
-	    }
-	    nlTemp = nlMiddle;
-	    while (nlTemp)
-	    {
-		nl = nlTemp;
-		if (nl > srcRemaining)
-		    nl = srcRemaining;
-
-		nlTemp -= nl;
-		srcRemaining -= nl;
-
-#if MROP == Mcopy
-#ifdef LARGE_INSTRUCTION_CACHE
-#ifdef FAST_CONSTANT_OFFSET_MODE
-
-		psrc += nl & (UNROLL-1);
-		pdst += nl & (UNROLL-1);
-
-#define BodyOdd(n) pdst[-n] = MROP_SOLID (psrc[-n], pdst[-n]);
-#define BodyEven(n) pdst[-n] = MROP_SOLID (psrc[-n], pdst[-n]);
-
-#define LoopReset \
-pdst += UNROLL; \
-psrc += UNROLL;
-
-#else
-
-#define BodyOdd(n)  *pdst = MROP_SOLID (*psrc, *pdst); pdst++; psrc++;
-#define BodyEven(n) BodyOdd(n)
-
-#define LoopReset   ;
-
-#endif
-		PackedLoop
-
-#undef BodyOdd
-#undef BodyEven
-#undef LoopReset
-
-#else
-		DuffL(nl, label1,
-			*pdst = MROP_SOLID (*psrc, *pdst);
-			pdst++; psrc++;)
-#endif
-#else
-		while (nl--) {
-			*pdst = MROP_SOLID (*psrc, *pdst);
-			pdst++; psrc++;
-		}
-#endif
-		if (!srcRemaining)
-		{
-		    srcRemaining = widthSrc;
-		    psrc = psrcStart;
-		}
-	    }
-	    if (endmask)
-	    {
-		*pdst = MROP_MASK (*psrc, *pdst, endmask);
-	    }
-	}
-	else
-	{
-	    if (xoffSrc > xoffDst)
-	    {
-		leftShift = (xoffSrc - xoffDst) << LEFTSHIFT_AMT;
-		rightShift = PGSZ - leftShift;
-	    }
-	    else
-	    {
-		rightShift = (xoffDst - xoffSrc) << LEFTSHIFT_AMT;
-		leftShift = PGSZ - rightShift;
-	    }
-	    psrc = psrcLine;
-	    pdst = pdstLine;
-	    bits = 0;
-	    srcRemaining = widthSrc - srcStart;
-	    if (xoffSrc > xoffDst)
-	    {
-		bits = *psrc;
-		IncSrcPtr
-	    }
-	    if (startmask)
-	    {
-		bits1 = BitLeft(bits,leftShift);
-		bits = *psrc;
-		IncSrcPtr
-		bits1 |= BitRight(bits,rightShift);
-		*pdst = MROP_MASK(bits1, *pdst, startmask);
-		pdst++;
-	    }
-	    nlTemp = nlMiddle;
-	    while (nlTemp)
-	    {
-		nl = nlTemp;
-		if (nl > srcRemaining)
-		    nl = srcRemaining;
-
-		nlTemp -= nl;
-		srcRemaining -= nl;
-
-#if MROP == Mcopy
-#ifdef LARGE_INSTRUCTION_CACHE
-		bits1 = bits;
-
-#ifdef FAST_CONSTANT_OFFSET_MODE
-
-		psrc += nl & (UNROLL-1);
-		pdst += nl & (UNROLL-1);
-
-#define BodyOdd(n) \
-bits = psrc[-n]; \
-pdst[-n] = MROP_SOLID(BitLeft(bits1, leftShift) | BitRight(bits, rightShift), pdst[-n]);
-
-#define BodyEven(n) \
-bits1 = psrc[-n]; \
-pdst[-n] = MROP_SOLID(BitLeft(bits, leftShift) | BitRight(bits1, rightShift), pdst[-n]);
-
-#define LoopReset \
-pdst += UNROLL; \
-psrc += UNROLL;
-
-#else
-
-#define BodyOdd(n) \
-bits = *psrc++; \
-*pdst = MROP_SOLID(BitLeft(bits1, leftShift) | BitRight(bits, rightShift), *pdst); \
-pdst++;
-	       
-#define BodyEven(n) \
-bits1 = *psrc++; \
-*pdst = MROP_SOLID(BitLeft(bits, leftShift) | BitRight(bits1, rightShift), *pdst); \
-pdst++;
-
-#define LoopReset   ;
-
-#endif	/* !FAST_CONSTANT_OFFSET_MODE */
-
-		PackedLoop
-
-#undef BodyOdd
-#undef BodyEven
-#undef LoopReset
-
-#else
-		DuffL (nl,label2,
-		    bits1 = BitLeft(bits, leftShift);
-		    bits = *psrc++;
-		    *pdst = MROP_SOLID (bits1 | BitRight(bits, rightShift), *pdst);
-		    pdst++;
-		)
-#endif
-#else
-		while (nl--) {
-		    bits1 = BitLeft(bits,leftShift);
-		    bits = *psrc++;
-		    *pdst = MROP_SOLID(bits1|BitRight(bits,rightShift), *pdst);
-		    pdst++;
-		}
-#endif
-		if (!srcRemaining)
-		{
-		    srcRemaining = widthSrc;
-		    psrc = psrcStart;
-		}
-	    }
-
-	    if (endmask)
-	    {
-		bits1 = BitLeft(bits, leftShift);
-		if (BitLeft(endmask, rightShift))
-		{
-		    bits = *psrc;
-		    bits1 |= BitRight(bits, rightShift);
-		}
-		*pdst = MROP_MASK (bits1, *pdst, endmask);
-	    }
-	}
-	ppt++;
-    }
-}
diff --git a/cfb/cfbunmap.h b/cfb/cfbunmap.h
deleted file mode 100644
index db98892..0000000
--- a/cfb/cfbunmap.h
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (C) 1994-1998 The XFree86 Project, Inc.  All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
- * XFREE86 PROJECT BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name of the XFree86 Project shall
- * not be used in advertising or otherwise to promote the sale, use or other
- * dealings in this Software without prior written authorization from the
- * XFree86 Project.
- */
-
-/*
- * Unmap names
- */
-
-#undef CFBNAME
-#undef CATNAME
-
-#undef QuartetBitsTable
-#undef QuartetPixelMaskTable
-#undef cfb8ClippedLineCopy
-#undef cfb8ClippedLineGeneral 
-#undef cfb8ClippedLineXor
-#undef cfb8LineSS1Rect
-#undef cfb8LineSS1RectCopy
-#undef cfb8LineSS1RectGeneral 
-#undef cfb8LineSS1RectPreviousCopy
-#undef cfb8LineSS1RectXor
-#undef cfb8SegmentSS1Rect
-#undef cfb8SegmentSS1RectCopy
-#undef cfb8SegmentSS1RectGeneral 
-#undef cfb8SegmentSS1RectShiftCopy
-#undef cfb8SegmentSS1RectXor
-#undef cfbAllocatePrivates
-#undef cfbBSFuncRec
-#undef cfbBitBlt
-#undef cfbBresD
-#undef cfbBresS
-#undef cfbChangeWindowAttributes
-#undef cfbClearVisualTypes
-#undef cfbCloseScreen
-#undef cfbCreateDefColormap
-#undef cfbCopyArea
-#undef cfbCopyImagePlane
-#undef cfbCopyPixmap
-#undef cfbCopyPlane
-#undef cfbCopyPlaneReduce
-#undef cfbCopyRotatePixmap
-#undef cfbCopyWindow
-#undef cfbCreateGC
-#undef cfbCreatePixmap
-#undef cfbCreateScreenResources
-#undef cfbCreateWindow
-#undef cfbDestroyPixmap
-#undef cfbDestroyWindow
-#undef cfbDoBitblt
-#undef cfbDoBitbltCopy
-#undef cfbDoBitbltGeneral
-#undef cfbDoBitbltOr
-#undef cfbDoBitbltXor
-#undef cfbExpandDirectColors
-#undef cfbFillBoxTile32sCopy
-#undef cfbFillBoxTile32sGeneral
-#undef cfbFillBoxTileOdd
-#undef cfbFillBoxTileOddCopy
-#undef cfbFillBoxTileOddGeneral
-#undef cfbFillPoly1RectCopy
-#undef cfbFillPoly1RectGeneral
-#undef cfbFillRectSolidCopy
-#undef cfbFillRectSolidGeneral
-#undef cfbFillRectSolidXor
-#undef cfbFillRectTile32Copy
-#undef cfbFillRectTile32General
-#undef cfbFillRectTileOdd
-#undef cfbFillSpanTile32sCopy
-#undef cfbFillSpanTile32sGeneral
-#undef cfbFillSpanTileOddCopy
-#undef cfbFillSpanTileOddGeneral
-#undef cfbFinishScreenInit
-#undef cfbGCFuncs
-#undef cfbGCPrivateKey
-#undef cfbGetImage
-#undef cfbGetScreenPixmap
-#undef cfbGetSpans
-#undef cfbHorzS
-#undef cfbImageGlyphBlt8
-#undef cfbInitializeColormap
-#undef cfbInitVisuals
-#undef cfbInstallColormap
-#undef cfbLineSD
-#undef cfbLineSS
-#undef cfbListInstalledColormaps
-#undef cfbMapWindow
-#undef cfbMatchCommon
-#undef cfbNonTEOps
-#undef cfbNonTEOps1Rect
-#undef cfbPadPixmap
-#undef cfbPolyFillArcSolidCopy
-#undef cfbPolyFillArcSolidGeneral
-#undef cfbPolyFillRect
-#undef cfbPolyGlyphBlt8
-#undef cfbPolyGlyphRop8
-#undef cfbPolyPoint
-#undef cfbPositionWindow
-#undef cfbPutImage
-#undef cfbReduceRasterOp
-#undef cfbResolveColor
-#undef cfbRestoreAreas
-#undef cfbSaveAreas
-#undef cfbScreenInit
-#undef cfbScreenPrivateKey
-#undef cfbSegmentSD
-#undef cfbSegmentSS
-#undef cfbSetScanline
-#undef cfbSetScreenPixmap
-#undef cfbSetSpans
-#undef cfbSetVisualTypes
-#undef cfbSetupScreen
-#undef cfbSolidSpansCopy
-#undef cfbSolidSpansGeneral
-#undef cfbSolidSpansXor
-#undef cfbStippleStack
-#undef cfbStippleStackTE
-#undef cfbTEGlyphBlt
-#undef cfbTEOps
-#undef cfbTEOps1Rect
-#undef cfbTile32FSCopy
-#undef cfbTile32FSGeneral
-#undef cfbUninstallColormap
-#undef cfbUnmapWindow
-#undef cfbUnnaturalStippleFS
-#undef cfbUnnaturalTileFS
-#undef cfbValidateGC
-#undef cfbVertS
-#undef cfbWindowPrivateKey
-#undef cfbXRotatePixmap
-#undef cfbYRotatePixmap
-#undef cfbZeroPolyArcSS8Copy
-#undef cfbZeroPolyArcSS8General
-#undef cfbZeroPolyArcSS8Xor
-#undef cfbendpartial
-#undef cfbendtab
-#undef cfbmask
-#undef cfbrmask
-#undef cfbstartpartial
-#undef cfbstarttab
diff --git a/cfb/cfbwindow.c b/cfb/cfbwindow.c
deleted file mode 100644
index 5072876..0000000
--- a/cfb/cfbwindow.c
+++ /dev/null
@@ -1,160 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <stdlib.h>
-
-#include <X11/X.h>
-#include "scrnintstr.h"
-#include "windowstr.h"
-#include "cfb.h"
-#include "mistruct.h"
-#include "regionstr.h"
-#include "cfbmskbits.h"
-
-Bool
-cfbCreateWindow(WindowPtr pWin)
-{
-#ifdef PIXMAP_PER_WINDOW
-    /* Setup pointer to Screen pixmap */
-    dixSetPrivate(&pWin->devPrivates, frameWindowPrivateKey,
-		  cfbGetScreenPixmap(pWin->drawable.pScreen));
-#endif
-
-    return TRUE;
-}
-
-Bool
-cfbDestroyWindow(WindowPtr pWin)
-{
-    return(TRUE);
-}
-
-/*ARGSUSED*/
-Bool
-cfbMapWindow(pWindow)
-    WindowPtr pWindow;
-{
-    return(TRUE);
-}
-
-/*ARGSUSED*/
-Bool
-cfbPositionWindow(WindowPtr pWin, int x, int y)
-{
-    return (TRUE);
-}
-
-/*ARGSUSED*/
-Bool
-cfbUnmapWindow(pWindow)
-    WindowPtr pWindow;
-{
-    return (TRUE);
-}
-
-/* UNCLEAN!
-   this code calls the bitblt helper code directly.
-
-   cfbCopyWindow copies only the parts of the destination that are
-visible in the source.
-*/
-
-
-void 
-cfbCopyWindow(pWin, ptOldOrg, prgnSrc)
-    WindowPtr pWin;
-    DDXPointRec ptOldOrg;
-    RegionPtr prgnSrc;
-{
-    DDXPointPtr pptSrc;
-    register DDXPointPtr ppt;
-    RegionRec rgnDst;
-    register BoxPtr pbox;
-    register int dx, dy;
-    register int i, nbox;
-    WindowPtr pwinRoot;
-
-    pwinRoot = WindowTable[pWin->drawable.pScreen->myNum];
-
-    REGION_NULL(pWin->drawable.pScreen, &rgnDst);
-
-    dx = ptOldOrg.x - pWin->drawable.x;
-    dy = ptOldOrg.y - pWin->drawable.y;
-    REGION_TRANSLATE(pWin->drawable.pScreen, prgnSrc, -dx, -dy);
-    REGION_INTERSECT(pWin->drawable.pScreen, &rgnDst, &pWin->borderClip, prgnSrc);
-
-    pbox = REGION_RECTS(&rgnDst);
-    nbox = REGION_NUM_RECTS(&rgnDst);
-    if(!nbox || !(pptSrc = (DDXPointPtr )xalloc(nbox * sizeof(DDXPointRec))))
-    {
-	REGION_UNINIT(pWin->drawable.pScreen, &rgnDst);
-	return;
-    }
-    ppt = pptSrc;
-
-    for (i = nbox; --i >= 0; ppt++, pbox++)
-    {
-	ppt->x = pbox->x1 + dx;
-	ppt->y = pbox->y1 + dy;
-    }
-
-    cfbDoBitbltCopy((DrawablePtr)pwinRoot, (DrawablePtr)pwinRoot,
-		GXcopy, &rgnDst, pptSrc, ~0L);
-    xfree(pptSrc);
-    REGION_UNINIT(pWin->drawable.pScreen, &rgnDst);
-}
-
-Bool
-cfbChangeWindowAttributes(WindowPtr pWin, unsigned long mask)
-{
-    return (TRUE);
-}
-
diff --git a/cfb/cfbzerarc.c b/cfb/cfbzerarc.c
deleted file mode 100644
index 5b8879e..0000000
--- a/cfb/cfbzerarc.c
+++ /dev/null
@@ -1,322 +0,0 @@
-/************************************************************
-
-Copyright 1989, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-********************************************************/
-
-
-/* Derived from:
- * "Algorithm for drawing ellipses or hyperbolae with a digital plotter"
- * by M. L. V. Pitteway
- * The Computer Journal, November 1967, Volume 10, Number 3, pp. 282-289
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <limits.h>
-
-#include <X11/X.h>
-#include <X11/Xprotostr.h>
-#include "regionstr.h"
-#include "gcstruct.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "cfb.h"
-#include "cfbmskbits.h"
-#include "mizerarc.h"
-#include "cfbrrop.h"
-#include "mi.h"
-
-#ifdef PIXEL_ADDR
-
-static void
-RROP_NAME(cfbZeroArcSS8)(
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    xArc *arc)
-{
-    miZeroArcRec info;
-    Bool do360;
-    register int x;
-    PixelType *addrp;
-    register PixelType *yorgp, *yorgop;
-#if PSZ == 24
-    int xorg, xorg3, xorgo, xorgo3;
-    register int xtmp;
-#endif
-    RROP_DECLARE
-    register int yoffset;
-    int npwidth, dyoffset;
-    register int y, a, b, d, mask;
-    register int k1, k3, dx, dy;
-
-    cfbGetPixelWidthAndPointer(pDraw,npwidth, addrp)
-
-    RROP_FETCH_GC (pGC);
-    do360 = miZeroArcSetup(arc, &info, TRUE);
-    yorgp = addrp + ((info.yorg + pDraw->y) * npwidth);
-    yorgop = addrp + ((info.yorgo + pDraw->y) * npwidth);
-    info.xorg += pDraw->x;
-    info.xorgo += pDraw->x;
-#if PSZ == 24
-    xorg = info.xorg;
-    xorg3 = xorg * 3;
-    info.xorg = (info.xorg * 3) >> 2;
-    xorgo = info.xorgo;
-    xorgo3 = xorgo * 3; 
-    info.xorgo = (info.xorgo * 3) >> 2;
-#endif
-    MIARCSETUP();
-    yoffset = y ? npwidth : 0;
-    dyoffset = 0;
-    mask = info.initialMask;
-    if (!(arc->width & 1))
-    {
-#if PSZ == 24
-	if (mask & 2)
-	    RROP_SOLID24((yorgp + info.xorgo), xorgo);
-	if (mask & 8)
-	    RROP_SOLID24((yorgop + info.xorgo), xorgo);
-#else
-	if (mask & 2)
-	    RROP_SOLID((yorgp + info.xorgo));
-	if (mask & 8)
-	    RROP_SOLID((yorgop + info.xorgo));
-#endif /* PSZ == 24 */
-    }
-    if (!info.end.x || !info.end.y)
-    {
-	mask = info.end.mask;
-	info.end = info.altend;
-    }
-    if (do360 && (arc->width == arc->height) && !(arc->width & 1))
-    {
-	register int xoffset = npwidth;
-#if PSZ == 24
-	PixelType *yorghb = yorgp + (info.h * npwidth);
-	register int tmp1, tmp2, tmp1_3, tmp2_3;
-
-	tmp1 = xorg + info.h;
-	tmp1_3 = tmp1 * 3;
-	tmp2 = xorg - info.h;
-	tmp2_3 = tmp2 * 3;
-	while (1)
-	{
-	    xtmp = (xorg3 + x * 3) >> 2;
-	    RROP_SOLID24(yorgp + yoffset + xtmp, xorg + x);
-	    RROP_SOLID24(yorgop - yoffset + xtmp, xorg + x);
-	    xtmp = (xorg3 - x * 3) >> 2;
-	    RROP_SOLID24(yorgp + yoffset + xtmp, xorg - x);
-	    RROP_SOLID24(yorgop - yoffset + xtmp, xorg - x);
-	    if (a < 0)
-		break;
-	    xtmp = (tmp1_3 - y * 3) >> 2;
-	    RROP_SOLID24(yorghb - xoffset + xtmp, tmp1 - y);
-	    RROP_SOLID24(yorghb + xoffset + xtmp, tmp1 - y);
-	    xtmp = (tmp2_3 + y * 3) >> 2;
-	    RROP_SOLID24(yorghb - xoffset + xtmp, tmp2 + y);
-	    RROP_SOLID24(yorghb + xoffset + xtmp, tmp2 + y);
-	    xoffset += npwidth;
-	    MIARCCIRCLESTEP(yoffset += npwidth;);
-	}
-#else
-	PixelType *yorghb = yorgp + (info.h * npwidth) + info.xorg;
-	PixelType *yorgohb = yorghb - info.h;
-
-	yorgp += info.xorg;
-	yorgop += info.xorg;
-	yorghb += info.h;
-	while (1)
-	{
-	    RROP_SOLID(yorgp + yoffset + x);
-	    RROP_SOLID(yorgp + yoffset - x);
-	    RROP_SOLID(yorgop - yoffset - x);
-	    RROP_SOLID(yorgop - yoffset + x);
-	    if (a < 0)
-		break;
-	    RROP_SOLID(yorghb - xoffset - y);
-	    RROP_SOLID(yorgohb - xoffset + y);
-	    RROP_SOLID(yorgohb + xoffset + y);
-	    RROP_SOLID(yorghb + xoffset - y);
-	    xoffset += npwidth;
-	    MIARCCIRCLESTEP(yoffset += npwidth;);
-	}
-	yorgp -= info.xorg;
-	yorgop -= info.xorg;
-#endif /* PSZ == 24 */
-	x = info.w;
-	yoffset = info.h * npwidth;
-    }
-    else if (do360)
-    {
-	while (y < info.h || x < info.w)
-	{
-	    MIARCOCTANTSHIFT(dyoffset = npwidth;);
-#if PSZ == 24
-	    xtmp = (xorg3 + x * 3) >> 2;
-	    RROP_SOLID24(yorgp + yoffset + xtmp, xorg + x);
-	    RROP_SOLID24(yorgop - yoffset + xtmp, xorg + x);
-	    xtmp = (xorgo3 - x * 3) >> 2;
-	    RROP_SOLID24(yorgp + yoffset + xtmp, xorgo - x);
-	    RROP_SOLID24(yorgop - yoffset + xtmp, xorgo - x);
-#else
-	    RROP_SOLID(yorgp + yoffset + info.xorg + x);
-	    RROP_SOLID(yorgp + yoffset + info.xorgo - x);
-	    RROP_SOLID(yorgop - yoffset + info.xorgo - x);
-	    RROP_SOLID(yorgop - yoffset + info.xorg + x);
-#endif
-	    MIARCSTEP(yoffset += dyoffset;, yoffset += npwidth;);
-	}
-    }
-    else
-    {
-	while (y < info.h || x < info.w)
-	{
-	    MIARCOCTANTSHIFT(dyoffset = npwidth;);
-	    if ((x == info.start.x) || (y == info.start.y))
-	    {
-		mask = info.start.mask;
-		info.start = info.altstart;
-	    }
-#if PSZ == 24
-	    if (mask & 1){
-	      xtmp = (xorg3 + x * 3) >> 2;
-	      RROP_SOLID24(yorgp + yoffset + xtmp, xorg + x);
-	    }
-	    if (mask & 2){
-	      xtmp = (xorgo3 - x * 3) >> 2;
-	      RROP_SOLID24(yorgp + yoffset + xtmp, xorgo - x);
-	    }
-	    if (mask & 4){
-	      xtmp = (xorgo3 - x * 3) >> 2;
-	      RROP_SOLID24(yorgop - yoffset + xtmp, xorgo - x);
-	    }
-	    if (mask & 8){
-	      xtmp = (xorg3 + x * 3) >> 2;
-	      RROP_SOLID24(yorgop - yoffset + xtmp, xorg + x);
-	    }
-#else
-	    if (mask & 1)
-		RROP_SOLID(yorgp + yoffset + info.xorg + x);
-	    if (mask & 2)
-		RROP_SOLID(yorgp + yoffset + info.xorgo - x);
-	    if (mask & 4)
-		RROP_SOLID(yorgop - yoffset + info.xorgo - x);
-	    if (mask & 8)
-		RROP_SOLID(yorgop - yoffset + info.xorg + x);
-#endif /* PSZ == 24 */
-	    if ((x == info.end.x) || (y == info.end.y))
-	    {
-		mask = info.end.mask;
-		info.end = info.altend;
-	    }
-	    MIARCSTEP(yoffset += dyoffset;, yoffset += npwidth;);
-	}
-    }
-    if ((x == info.start.x) || (y == info.start.y))
-	mask = info.start.mask;
-#if PSZ == 24
-    if (mask & 1){
-      xtmp = (xorg3 + x * 3) >> 2;
-      RROP_SOLID24(yorgp + yoffset + xtmp, xorg + x);
-    }
-    if (mask & 4){
-      xtmp = (xorgo3 - x * 3) >> 2;
-      RROP_SOLID24(yorgop - yoffset + xtmp, xorgo - x);
-    }
-#else
-    if (mask & 1)
-	RROP_SOLID(yorgp + yoffset + info.xorg + x);
-    if (mask & 4)
-	RROP_SOLID(yorgop - yoffset + info.xorgo - x);
-#endif /* PSZ == 24 */
-    if (arc->height & 1)
-    {
-#if PSZ == 24
-	if (mask & 2){
-	  xtmp = (xorgo3 - x * 3) >> 2;
-	  RROP_SOLID24(yorgp + yoffset + xtmp, xorgo - x);
-	}
-	if (mask & 8){
-	  xtmp = (xorg3 + x * 3) >> 2;
-	  RROP_SOLID24(yorgop - yoffset + xtmp, xorg + x);
-	}
-#else
-	if (mask & 2)
-	    RROP_SOLID(yorgp + yoffset + info.xorgo - x);
-	if (mask & 8)
-	    RROP_SOLID(yorgop - yoffset + info.xorg + x);
-#endif /* PSZ == 24 */
-    }
-    RROP_UNDECLARE
-}
-
-void
-RROP_NAME (cfbZeroPolyArcSS8) (pDraw, pGC, narcs, parcs)
-    register DrawablePtr	pDraw;
-    GCPtr	pGC;
-    int		narcs;
-    xArc	*parcs;
-{
-    register xArc *arc;
-    register int i;
-    BoxRec box;
-    int x2, y2;
-    RegionPtr cclip;
-
-    cclip = cfbGetCompositeClip(pGC);
-    for (arc = parcs, i = narcs; --i >= 0; arc++)
-    {
-	if (miCanZeroArc(arc))
-	{
-	    box.x1 = arc->x + pDraw->x;
-	    box.y1 = arc->y + pDraw->y;
- 	    /*
- 	     * Because box.x2 and box.y2 get truncated to 16 bits, and the
- 	     * RECT_IN_REGION test treats the resulting number as a signed
- 	     * integer, the RECT_IN_REGION test alone can go the wrong way.
- 	     * This can result in a server crash because the rendering
- 	     * routines in this file deal directly with cpu addresses
- 	     * of pixels to be stored, and do not clip or otherwise check
- 	     * that all such addresses are within their respective pixmaps.
- 	     * So we only allow the RECT_IN_REGION test to be used for
- 	     * values that can be expressed correctly in a signed short.
- 	     */
- 	    x2 = box.x1 + (int)arc->width + 1;
- 	    box.x2 = x2;
- 	    y2 = box.y1 + (int)arc->height + 1;
- 	    box.y2 = y2;
- 	    if ( (x2 <= SHRT_MAX) && (y2 <= SHRT_MAX) &&
- 		    (RECT_IN_REGION(pDraw->pScreen, cclip, &box) == rgnIN) )
-		RROP_NAME (cfbZeroArcSS8) (pDraw, pGC, arc);
-	    else
-		miZeroPolyArc(pDraw, pGC, 1, arc);
-	}
-	else
-	    miPolyArc(pDraw, pGC, 1, arc);
-    }
-}
-
-#endif
diff --git a/cfb/stip68kgnu.h b/cfb/stip68kgnu.h
deleted file mode 100644
index 2da27b4..0000000
--- a/cfb/stip68kgnu.h
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- *
-Copyright 1990, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- */
-
-/*
- * Stipple stack macro for 68k GCC
- */
-
-#define STIPPLE(addr,stipple,value,width,count,shift) \
-    __asm volatile ( \
-       "lea	5f,%/a1\n\
-	moveq	#28,%/d2\n\
-	addl	%2,%/d2\n\
-	moveq	#28,%/d3\n\
-	subql	#4,%2\n\
-	negl	%2\n\
-1:\n\
-	movel	%0,%/a0\n\
-	addl	%6,%0\n\
-	movel	%3 at +,%/d1\n\
-	jeq	3f\n\
-	movel	%/d1,%/d0\n\
-	lsrl	%/d2,%/d0\n\
-	lsll	#5,%/d0\n\
-	lsll	%2,%/d1\n\
-	jmp	%/a1@(%/d0:l)\n\
-2:\n\
-	addl	#4,%/a0\n\
-	movel	%/d1,%/d0\n\
-	lsrl	%/d3,%/d0\n\
-	lsll	#5,%/d0\n\
-	lsll	#4,%/d1\n\
-	jmp	%/a1@(%/d0:l)\n\
-5:\n\
-	jne 2b ; dbra %1,1b ; jra 4f\n\
-	. = 5b + 0x20\n\
-	moveb	%5,%/a0@(3)\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f\n\
-	. = 5b + 0x40\n\
-	moveb	%5,%/a0@(2)\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f\n\
-	. = 5b + 0x60\n\
-	movew	%5,%/a0@(2)\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f\n\
-	. = 5b + 0x80\n\
-	moveb	%5,%/a0@(1)\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f ;\n\
-	. = 5b + 0xa0\n\
-	moveb	%5,%/a0@(3) ; moveb	%5,%/a0@(1)\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f ;\n\
-	. = 5b + 0xc0\n\
-	movew	%5,%/a0@(1)\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f ;\n\
-	. = 5b + 0xe0\n\
-	movew	%5,%/a0@(2) ; moveb	%5,%/a0@(1)\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f ;\n\
-	. = 5b + 0x100\n\
-	moveb	%5,%/a0@\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f ;\n\
-	. = 5b + 0x120\n\
-	moveb	%5,%/a0@(3) ; moveb	%5,%/a0@\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f ;\n\
-	. = 5b + 0x140\n\
-	moveb	%5,%/a0@(2) ; moveb	%5,%/a0@\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f ;\n\
-	. = 5b + 0x160\n\
-	movew	%5,%/a0@(2) ; moveb	%5,%/a0@\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f ;\n\
-	. = 5b + 0x180\n\
-	movew	%5,%/a0@\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f ;\n\
-	. = 5b + 0x1a0\n\
-	moveb	%5,%/a0@(3) ; movew	%5,%/a0@\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f ;\n\
-	. = 5b + 0x1c0\n\
-	moveb	%5,%/a0@(2) ; movew	%5,%/a0@\n\
-	andl	%/d1,%/d1 ; jne 2b ; dbra %1,1b ; jra 4f ;\n\
-	. = 5b + 0x1e0\n\
-	movel	%5,%/a0@\n\
-	andl	%/d1,%/d1 ; jne 2b ; \n\
-3: 	dbra %1,1b ; \n\
-4:\n"\
-	    : "=a" (addr),	    /* %0 */ \
-	      "=d" (count),	    /* %1 */ \
-	      "=d" (shift),	    /* %2 */ \
-	      "=a" (stipple)	    /* %3 */ \
-	    : "0" (addr),	    /* %4 */ \
-	      "d" (value),	    /* %5 */ \
-	      "a" (width),	    /* %6 */ \
-	      "1" (count-1),	    /* %7 */ \
-	      "2" (shift),	    /* %8 */ \
-	      "3" (stipple)	    /* %9 */ \
-	    : /* ctemp */	    "d0", \
- 	      /* c */		    "d1", \
-	      /* lshift */	    "d2", \
-	      /* rshift */	    "d3", \
- 	      /* atemp */	    "a0", \
- 	      /* case */	    "a1")
diff --git a/cfb/stipmips.s b/cfb/stipmips.s
deleted file mode 100644
index c42d9b5..0000000
--- a/cfb/stipmips.s
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
- * $Xorg: stipmips.s,v 1.4 2001/02/09 02:04:39 xorgcvs Exp $
- *
-Copyright 1990, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- */
-
-/*
- * MIPS assembly code for optimized text rendering.
- *
- * Other stippling could be done in assembly, but the payoff is
- * not nearly as large.  Mostly because large areas are heavily
- * optimized already.
- */
-
-#ifdef MIPSEL
-# define BitsR		sll
-# define BitsL		srl
-# define BO(o)		o
-# define HO(o)		o
-# define WO(o)		o
-# define FourBits(dest,bits)	and	dest, bits, 0xf
-#else
-# define BitsR	srl
-# define BitsL	sll
-# define BO(o)		3-o
-# define HO(o)		2-o
-# define WO(o)		o
-# define FourBits(dest,bits)	srl	dest, bits, 28
-#endif
-
-/* reordering instructions would be fatal here */
-	.set	noreorder
-
-	
-/*
- * cfbStippleStack(addr, stipple, value, stride, Count, Shift)
- *               4       5       6      7     16(sp) 20(sp)
- *
- *  Apply successive 32-bit stipples starting at addr, addr+stride, ...
- *
- *  Used for text rendering, but only when no data could be lost
- *  when the stipple is shifted left by Shift bits
- */
-/* arguments */
-#define addr	$4
-#define stipple	$5
-#define value	$6
-#define stride	$7
-#define Count	16($sp)
-#define Shift	20($sp)
-
-/* local variables */
-#define count	$14
-#define shift	$13
-#define atemp	$12
-#define bits	$11
-#define lshift	$9
-#define sbase	$8
-#define stemp	$2
-
-#define CASE_SIZE	5	/* case blocks are 2^5 bytes each */
-#define CASE_MASK	0x1e0	/* first case mask */
-
-#define ForEachLine	$200
-#define NextLine	$201
-#define NextLine1	$202
-#define CaseBegin	$203
-#define ForEachBits	$204
-#define ForEachBits1	$205
-#define NextBits	$206
-
-#ifdef TETEXT
-#define	cfbStippleStack	cfbStippleStackTE
-#endif
-
-	.globl	cfbStippleStack
-	.ent	cfbStippleStack 2
-cfbStippleStack:
-	.frame	$sp, 0, $31
-	lw	count, Count			/* fetch stack params */
-	la	sbase,CaseBegin			/* load up switch table */
-	lw	shift, Shift
-	li	lshift, 4			/* compute offset within */
-	subu	lshift, lshift, shift		/*  stipple of remaining bits */
-#ifdef MIPSEL
-	addu	shift, shift, CASE_SIZE		/* first shift for LSB */
-#else
-	addu	shift, shift, 28-CASE_SIZE	/* first shift for MSB */
-#endif
-	/* do ... while (--count > 0); */
-ForEachLine:
-	lw	bits, 0(stipple)		/* get stipple bits */
-	move	atemp, addr			/* set up for this line */
-#ifdef TETEXT
-	/* Terminal emulator fonts are expanded and have many 0 rows */
-	beqz	bits, NextLine			/* skip out early on 0 */
-#endif
-	addu	addr, addr, stride		/* step for the loop */
-	BitsR	stemp, bits, shift		/* get first bits */
-	and	stemp, stemp, CASE_MASK		/* compute first branch */
-	addu	stemp, stemp, sbase		/*  ... */
-	j	stemp				/*  ... */
-	BitsL	bits, bits, lshift		/* set remaining bits */
-
-ForEachBits:
-	addu	atemp, atemp, 4
-ForEachBits1:
-	FourBits(stemp, bits)			/* compute jump for */
-	sll	stemp, stemp, CASE_SIZE		/*  next four bits */
-	addu	stemp, stemp, sbase		/*  ... */
-	j	stemp				/*  ... */
-	BitsL	bits, bits, 4			/* step for remaining bits */
-CaseBegin:
-	bnez	bits, ForEachBits1		/* 0 */
-	addu	atemp, atemp, 4
-NextLine:
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-	nop
-
-	bnez	bits, ForEachBits		/* 1 */
-	sb	value, BO(0)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-	nop
-					
-	bnez	bits, ForEachBits		/* 2 */
-	sb	value, BO(1)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-	nop
-					
-	bnez	bits, ForEachBits		/* 3 */
-	sh	value, HO(0)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-	nop
-					
-	bnez	bits, ForEachBits		/* 4 */
-	sb	value, BO(2)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-	nop
-					
-	sb	value, BO(0)(atemp)		/* 5 */
-	bnez	bits, ForEachBits
-	sb	value, BO(2)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-					
-	sb	value, BO(1)(atemp)		/* 6 */
-	bnez	bits, ForEachBits
-	sb	value, BO(2)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-					
-	bnez	bits, ForEachBits		/* 7 */
-	swl	value, BO(2)(atemp)		/* untested on MSB */
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-	nop
-					
-	bnez	bits, ForEachBits		/* 8 */
-	sb	value, BO(3)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-	nop
-					
-	sb	value, BO(0)(atemp)		/* 9 */
-	bnez	bits, ForEachBits
-	sb	value, BO(3)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-					
-	sb	value, BO(1)(atemp)		/* a */
-	bnez	bits, ForEachBits
-	sb	value, BO(3)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-
-	sh	value, HO(0)(atemp)		/* b */
-	bnez	bits, ForEachBits
-	sb	value, BO(3)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-					
-	bnez	bits, ForEachBits		/* c */
-	sh	value, HO(2)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-	nop
-					
-	sb	value, BO(0)(atemp)		/* d */
-	bnez	bits, ForEachBits
-	sh	value, HO(2)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-
-	bnez	bits, ForEachBits		/* e */
-	swr	value, BO(1)(atemp)		/* untested on MSB */
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-	nop
-					
-	bnez	bits, ForEachBits		/* f */
-	sw	value, WO(0)(atemp)
- 	addu	count, count, -1
-	bnez	count, ForEachLine
-	addu	stipple, stipple, 4
-	j	$31
-	nop
-	nop
-					
-	.end	cfbStippleStack
diff --git a/cfb/stipsparc.s b/cfb/stipsparc.s
deleted file mode 100644
index dcd440b..0000000
--- a/cfb/stipsparc.s
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * $Xorg: stipsparc.s,v 1.4 2001/02/09 02:04:39 xorgcvs Exp $
- * $XdotOrg:	$
- *
-Copyright 1990, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- */
-/* $XFree86: xc/programs/Xserver/cfb/stipsparc.s,v 1.4 2001/01/17 22:36:38 dawes Exp $ */
-
-/*
- * SPARC assembly code for optimized text rendering.
- *
- * Other stippling could be done in assembly, but the payoff is
- * not nearly as large.  Mostly because large areas are heavily
- * optimized already.
- */
-
-/* not that I expect to ever see an LSB SPARC, but ... */
-#ifdef LITTLE_ENDIAN
-# define BitsR		sll
-# define BitsL		srl
-# define BO(o)		o
-# define HO(o)		o
-# define WO(o)		o
-# define FourBits(dest,bits)	and	bits, 0xf, dest
-#else
-# define BitsR		srl
-# define BitsL		sll
-# define BO(o)		3-o
-# define HO(o)		2-o
-# define WO(o)		o
-# define FourBits(dest,bits)	srl	bits, 28, dest
-#endif
-
-/*
- * cfbStippleStack(addr, stipple, value, stride, Count, Shift)
- *               4       5       6      7     16(sp) 20(sp)
- *
- *  Apply successive 32-bit stipples starting at addr, addr+stride, ...
- *
- *  Used for text rendering, but only when no data could be lost
- *  when the stipple is shifted left by Shift bits
- */
-/* arguments */
-#define addr	%i0
-#define stipple	%i1
-#define value	%i2
-#define stride	%i3
-#define count	%i4
-#define shift	%i5
-
-/* local variables */
-#define atemp	%l0
-#define bits	%l1
-#define lshift	%l2
-#define sbase	%l3
-#define stemp	%l4
-
-#define CASE_SIZE	5	/* case blocks are 2^5 bytes each */
-#define CASE_MASK	0x1e0	/* first case mask */
-
-#define ForEachLine	LY1
-#define NextLine	LY2
-#define CaseBegin	LY3
-#define ForEachBits	LY4
-#define NextBits	LY5
-
-#if defined(SVR4) || defined(__ELF__)
-#ifdef TETEXT
-#define	_cfbStippleStack	cfbStippleStackTE
-#else
-#define	_cfbStippleStack	cfbStippleStack
-#endif
-#else
-#ifdef TETEXT
-#define	_cfbStippleStack	_cfbStippleStackTE
-#endif
-#endif
-	.seg	"text"
-	.proc	16
-	.globl	_cfbStippleStack
-_cfbStippleStack:
-	save	%sp,-64,%sp
-#ifdef SHAREDCODE
-1:
-        call    2f
-        nop
-2:
-        mov     %o7,sbase                       /* sbase = 1b(1:) */
-        add     sbase, CaseBegin-1b, sbase
-#else /* !SHAREDCODE */
-	sethi	%hi(CaseBegin),sbase		/* load up switch table */
-	or	sbase,%lo(CaseBegin),sbase
-#endif /* SHAREDCODE */
-	mov	4,lshift			/* compute offset within */
-	sub	lshift, shift, lshift		/*  stipple of remaining bits */
-#ifdef LITTLE_ENDIAN
-	inc	CASE_SIZE, shift		/* first shift for LSB */
-#else
-	inc	28-CASE_SIZE, shift		/* first shift for MSB */
-#endif
-	/* do ... while (--count > 0); */
-ForEachLine:
-	ld	[stipple],bits			/* get stipple bits */
-	mov	addr,atemp			/* set up for this line */
-#ifdef TETEXT
-	/* Terminal emulator fonts are expanded and have many 0 rows */
-	tst	bits
-	bz	NextLine			/* skip out early on 0 */
-#endif
-	add	addr, stride, addr		/* step for the loop */
-	BitsR	bits, shift, stemp		/* get first bits */
-	and	stemp, CASE_MASK, stemp		/* compute first jump */
-	BitsL	bits, lshift, bits		/* set remaining bits */
-	jmp	sbase+stemp			/*  ... */
-	tst	bits
-
-ForEachBits:
-	inc	4, atemp
-ForEachBits1:
-	FourBits(stemp, bits)			/* compute jump for */
-	sll	stemp, CASE_SIZE, stemp		/*  these four bits */
-	BitsL	bits, 4, bits			/* step for remaining bits */
-	jmp	sbase+stemp			/* jump */
-	tst	bits
-CaseBegin:
-	bnz,a	ForEachBits1			/* 0 */
-	inc	4, atemp
-NextLine:
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-	nop
-
-	bnz	ForEachBits			/* 1 */
-	stb	value, [atemp+BO(0)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-	nop
-					
-	bnz	ForEachBits			/* 2 */
-	stb	value, [atemp+BO(1)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-	nop
-					
-	bnz	ForEachBits			/* 3 */
-	sth	value, [atemp+HO(0)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-	nop
-					
-	bnz	ForEachBits			/* 4 */
-	stb	value, [atemp+BO(2)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-	nop
-					
-	stb	value, [atemp+BO(0)]		/* 5 */
-	bnz	ForEachBits
-	stb	value, [atemp+BO(2)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	stb	value, [atemp+BO(1)]		/* 6 */
-	bnz	ForEachBits
-	stb	value, [atemp+BO(2)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	sth	value, [atemp+HO(0)]		/* 7 */
-	bnz	ForEachBits
-	stb	value, [atemp+BO(2)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	bnz	ForEachBits			/* 8 */
-	stb	value, [atemp+BO(3)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-	nop
-					
-	stb	value, [atemp+BO(0)]		/* 9 */
-	bnz	ForEachBits
-	stb	value, [atemp+BO(3)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	stb	value, [atemp+BO(1)]		/* a */
-	bnz	ForEachBits
-	stb	value, [atemp+BO(3)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	sth	value, [atemp+HO(0)]		/* b */
-	bnz	ForEachBits
-	stb	value, [atemp+BO(3)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	bnz	ForEachBits			/* c */
-	sth	value, [atemp+HO(2)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-	nop
-					
-	stb	value, [atemp+BO(0)]		/* d */
-	bnz	ForEachBits
-	sth	value, [atemp+HO(2)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	stb	value, [atemp+BO(1)]		/* e */
-	bnz	ForEachBits
-	sth	value, [atemp+HO(2)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	bnz	ForEachBits			/* f */
-	st	value, [atemp+WO(0)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
diff --git a/cfb/stipsprc32.s b/cfb/stipsprc32.s
deleted file mode 100644
index 89b031f..0000000
--- a/cfb/stipsprc32.s
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
- * $Xorg: stipsprc32.s,v 1.4 2001/02/09 02:04:39 xorgcvs Exp $
- * $XdotOrg:	$
- *
-Copyright 1990, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
- *
- * Author:  Keith Packard, MIT X Consortium
- */
-/* $XFree86: xc/programs/Xserver/cfb/stipsprc32.s,v 1.4 2001/01/17 22:36:38 dawes Exp $ */
-
-/*
- * SPARC assembly code for optimized text rendering.
- *
- * Other stippling could be done in assembly, but the payoff is
- * not nearly as large.  Mostly because large areas are heavily
- * optimized already.
- */
-
-/* not that I expect to ever see an LSB SPARC, but ... */
-#ifdef LITTLE_ENDIAN
-# define BitsR		sll
-# define BitsL		srl
-# define WO(o)		3-o
-# define FourBits(dest,bits)	and	bits, 0xf, dest
-#else
-# define BitsR		srl
-# define BitsL		sll
-# define WO(o)		o
-# define FourBits(dest,bits)	srl	bits, 28, dest
-#endif
-
-/*
- * cfb32StippleStack(addr, stipple, value, stride, Count, Shift)
- *               4       5       6      7     16(sp) 20(sp)
- *
- *  Apply successive 32-bit stipples starting at addr, addr+stride, ...
- *
- *  Used for text rendering, but only when no data could be lost
- *  when the stipple is shifted left by Shift bits
- */
-/* arguments */
-#define addr	%i0
-#define stipple	%i1
-#define value	%i2
-#define stride	%i3
-#define count	%i4
-#define shift	%i5
-
-/* local variables */
-#define atemp	%l0
-#define bits	%l1
-#define lshift	%l2
-#define sbase	%l3
-#define stemp	%l4
-
-#define CASE_SIZE	5	/* case blocks are 2^5 bytes each */
-#define CASE_MASK	0x1e0	/* first case mask */
-
-#define ForEachLine	LY1
-#define NextLine	LY2
-#define CaseBegin	LY3
-#define ForEachBits	LY4
-#define NextBits	LY5
-
-#if defined(SVR4) || defined(__ELF__)
-#ifdef TETEXT
-#define	_cfb32StippleStack	cfb32StippleStackTE
-#else
-#define	_cfb32StippleStack	cfb32StippleStack
-#endif
-#else
-#ifdef TETEXT
-#define	_cfb32StippleStack	_cfb32StippleStackTE
-#endif
-#endif
-
-	.seg	"text"
-	.proc	16
-	.globl	_cfb32StippleStack
-_cfb32StippleStack:
-	save	%sp,-64,%sp
-#ifdef SHAREDCODE
-1:
-        call    2f
-        nop
-2:
-        mov     %o7,sbase                       /* sbase = 1b(1:) */
-        add     sbase, CaseBegin-1b, sbase
-#else /* !SHAREDCODE */
-	sethi	%hi(CaseBegin),sbase		/* load up switch table */
-	or	sbase,%lo(CaseBegin),sbase
-#endif /* !SHAREDCODE */
-	mov	4,lshift			/* compute offset within */
-	sub	lshift, shift, lshift		/*  stipple of remaining bits */
-#ifdef LITTLE_ENDIAN
-	inc	CASE_SIZE, shift		/* first shift for LSB */
-#else
-	inc	28-CASE_SIZE, shift		/* first shift for MSB */
-#endif
-	/* do ... while (--count > 0); */
-ForEachLine:
-	ld	[stipple],bits			/* get stipple bits */
-	mov	addr,atemp			/* set up for this line */
-#ifdef TETEXT
-	/* Terminal emulator fonts are expanded and have many 0 rows */
-	tst	bits
-	bz	NextLine			/* skip out early on 0 */
-#endif
-	add	addr, stride, addr		/* step for the loop */
-	BitsR	bits, shift, stemp		/* get first bits */
-	and	stemp, CASE_MASK, stemp		/* compute first jump */
-	BitsL	bits, lshift, bits		/* set remaining bits */
-	jmp	sbase+stemp			/*  ... */
-	tst	bits
-
-ForEachBits:
-	inc	16, atemp
-ForEachBits1:
-	FourBits(stemp, bits)			/* compute jump for */
-	sll	stemp, CASE_SIZE, stemp		/*  these four bits */
-	BitsL	bits, 4, bits			/* step for remaining bits */
-	jmp	sbase+stemp			/* jump */
-	tst	bits
-CaseBegin:
-	bnz,a	ForEachBits1			/* 0 */
-	inc	16, atemp
-NextLine:
-	deccc	1, count
-NextLine1:
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-	nop
-
-	bnz	ForEachBits			/* 1 */
-	st	value, [atemp+WO(12)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-	nop
-					
-	bnz	ForEachBits			/* 2 */
-	st	value, [atemp+WO(8)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-	nop
-					
-	st	value, [atemp+WO(8)]		/* 3 */
-	bnz	ForEachBits
-	st	value, [atemp+WO(12)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	bnz	ForEachBits			/* 4 */
-	st	value, [atemp+WO(4)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-	nop
-					
-	st	value, [atemp+WO(4)]		/* 5 */
-	bnz	ForEachBits
-	st	value, [atemp+WO(12)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	st	value, [atemp+WO(4)]		/* 6 */
-	bnz	ForEachBits
-	st	value, [atemp+WO(8)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	st	value, [atemp+WO(4)]		/* 7 */
-	st	value, [atemp+WO(8)]
-	bnz	ForEachBits
-	st	value, [atemp+WO(12)]
-	b	NextLine1
-	deccc	1, count
-	nop
-	nop
-					
-	bnz	ForEachBits			/* 8 */
-	st	value, [atemp+WO(0)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-	nop
-					
-	st	value, [atemp+WO(0)]		/* 9 */
-	bnz	ForEachBits
-	st	value, [atemp+WO(12)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	st	value, [atemp+WO(0)]		/* a */
-	bnz	ForEachBits
-	st	value, [atemp+WO(8)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	st	value, [atemp+WO(0)]		/* b */
-	st	value, [atemp+WO(8)]
-	bnz	ForEachBits
-	st	value, [atemp+WO(12)]
-	b	NextLine1
-	deccc	1, count
-	nop
-	nop
-					
-	st	value, [atemp+WO(0)]		/* c */
-	bnz	ForEachBits
-	st	value, [atemp+WO(4)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
-					
-	st	value, [atemp+WO(0)]		/* d */
-	st	value, [atemp+WO(4)]
-	bnz	ForEachBits
-	st	value, [atemp+WO(12)]
-	b	NextLine1
-	deccc	1, count
-	nop
-	nop
-					
-	st	value, [atemp+WO(0)]		/* e */
-	st	value, [atemp+WO(4)]
-	bnz	ForEachBits
-	st	value, [atemp+WO(8)]
-	b	NextLine1
-	deccc	1, count
-	nop
-	nop
-					
-	st	value, [atemp+WO(0)]		/* f */
-	st	value, [atemp+WO(4)]
-	st	value, [atemp+WO(8)]
-	bnz	ForEachBits
-	st	value, [atemp+WO(12)]
-	deccc	1, count
-	bnz,a	ForEachLine
-	inc	4, stipple
-	ret
-	restore
diff --git a/cfb32/Makefile.am b/cfb32/Makefile.am
deleted file mode 100644
index 681a095..0000000
--- a/cfb32/Makefile.am
+++ /dev/null
@@ -1,9 +0,0 @@
-noinst_LTLIBRARIES = libcfb32.la
-
-include $(top_srcdir)/cfb/Makefile.am.inc
-
-libcfb32_la_SOURCES = $(libcfb_common_sources) $(libcfb_gen_sources)
-
-INCLUDES = $(CFB_INCLUDES) $(DIX_CFLAGS) -I$(top_srcdir)/hw/xfree86/os-support -I$(top_srcdir)/hw/xfree86/common
-
-AM_CFLAGS = -DPSZ=32  $(PLATFORMDEFS)
diff --git a/configure.ac b/configure.ac
index c0a1f23..4e83a42 100644
--- a/configure.ac
+++ b/configure.ac
@@ -575,7 +575,6 @@ AC_ARG_ENABLE(xglx,           AS_HELP_STRING([--enable-xglx], [Build Xglx xgl mo
 AC_ARG_ENABLE(xegl,           AS_HELP_STRING([--enable-xegl], [Build Xegl xgl module (default: no)]), [XEGL=$enableval], [XEGL=no])
 dnl legacy fb support
 AC_ARG_ENABLE(mfb,            AS_HELP_STRING([--enable-mfb], [Build legacy mono framebuffer support (default: enabled)]), [MFB=$enableval], [MFB=$XORG])
-AC_ARG_ENABLE(cfb,            AS_HELP_STRING([--enable-cfb], [Build legacy color framebuffer support (default: enabled)]), [CFB=$enableval], [CFB=$XORG])
 AC_ARG_ENABLE(afb,            AS_HELP_STRING([--enable-afb], [Build legacy advanced framebuffer support (default: enabled)]), [AFB=$enableval], [AFB=$XORG])
 dnl kdrive and its subsystems
 AC_ARG_ENABLE(kdrive,         AS_HELP_STRING([--enable-kdrive], [Build kdrive servers (default: no)]), [KDRIVE=$enableval], [KDRIVE=no])
@@ -1581,12 +1580,10 @@ AM_CONDITIONAL([XF86VIDMODE], [test "x$XF86VIDMODE" = xyes])
 
 dnl legacy fb support
 test "x$MFB" = xauto && MFB="$XORG"
-test "x$CFB" = xauto && CFB="$XORG"
 test "x$AFB" = xauto && AFB="$XORG"
 AM_CONDITIONAL(MFB, [test "x$MFB" = xyes])
-AM_CONDITIONAL(CFB, [test "x$CFB" = xyes])
 AM_CONDITIONAL(AFB, [test "x$AFB" = xyes])
-if test "x$MFB" = xyes -o "x$CFB" = xyes -o "x$AFB" = xyes; then
+if test "x$MFB" = xyes -o "x$AFB" = xyes; then
 	if test "x$XORG" != xyes; then
 		AC_MSG_ERROR([legacy fb support requires the Xorg server])
 	fi
@@ -2135,8 +2132,6 @@ fb/Makefile
 record/Makefile
 XTrap/Makefile
 mfb/Makefile
-cfb/Makefile
-cfb32/Makefile
 config/Makefile
 mi/Makefile
 miext/Makefile
@@ -2195,7 +2190,6 @@ hw/xfree86/xaa/Makefile
 hw/xfree86/xf1bpp/Makefile
 hw/xfree86/xf4bpp/Makefile
 hw/xfree86/xf8_16bpp/Makefile
-hw/xfree86/xf8_32bpp/Makefile
 hw/xfree86/utils/Makefile
 hw/xfree86/utils/cvt/Makefile
 hw/xfree86/utils/gtf/Makefile
diff --git a/hw/xfree86/Makefile.am b/hw/xfree86/Makefile.am
index 03c2c3a..e6cc38a 100644
--- a/hw/xfree86/Makefile.am
+++ b/hw/xfree86/Makefile.am
@@ -16,20 +16,16 @@ if MFB
 MFB_SUBDIR = xf1bpp xf4bpp
 endif
 
-if CFB
-CFB_SUBDIR = xf8_32bpp
-endif
-
 DOC_SUBDIR = doc
 
 SUBDIRS = common ddc dummylib i2c x86emu int10 fbdevhw os-support parser rac \
-	  ramdac shadowfb vbe vgahw xaa $(MFB_SUBDIR) $(CFB_SUBDIR) \
+	  ramdac shadowfb vbe vgahw xaa $(MFB_SUBDIR) \
 	  xf8_16bpp loader dixmods exa modes \
 	  $(DRI_SUBDIR) $(DRI2_SUBDIR) $(XF86UTILS_SUBDIR) $(DOC_SUBDIR)
 
 DIST_SUBDIRS = common ddc dummylib i2c x86emu int10 fbdevhw os-support \
                parser rac ramdac shadowfb vbe vgahw xaa xf1bpp xf4bpp \
-               xf8_16bpp xf8_32bpp loader dixmods dri dri2 exa modes \
+               xf8_16bpp loader dixmods dri dri2 exa modes \
 	       utils doc
 
 bin_PROGRAMS = Xorg
diff --git a/hw/xfree86/dixmods/Makefile.am b/hw/xfree86/dixmods/Makefile.am
index dad2dd3..67967c5 100644
--- a/hw/xfree86/dixmods/Makefile.am
+++ b/hw/xfree86/dixmods/Makefile.am
@@ -18,10 +18,6 @@ if AFB
 AFBMOD = libafb.la
 endif
 
-if CFB
-CFBMOD = libcfb.la libcfb32.la
-endif
-
 if MFB
 MFBMOD = libmfb.la
 endif
@@ -31,7 +27,6 @@ RECORDMOD = librecord.la
 endif
 
 module_LTLIBRARIES = $(AFBMOD) \
-                     $(CFBMOD) \
                      libfb.la \
                      libwfb.la \
                      $(MFBMOD) \
@@ -61,14 +56,6 @@ libafb_la_LDFLAGS = -avoid-version
 libafb_la_LIBADD = $(top_builddir)/afb/libafb.la
 libafb_la_SOURCES = afbmodule.c
 
-libcfb_la_LDFLAGS = -avoid-version
-libcfb_la_LIBADD = $(top_builddir)/cfb/libcfb.la
-libcfb_la_SOURCES = cfbmodule.c
-
-libcfb32_la_LDFLAGS = -avoid-version
-libcfb32_la_LIBADD = $(top_builddir)/cfb32/libcfb32.la
-libcfb32_la_SOURCES = cfb32module.c
-
 libdbe_la_LDFLAGS = -avoid-version
 libdbe_la_LIBADD = $(top_builddir)/dbe/libdbe.la
 libdbe_la_SOURCES = dbemodule.c
diff --git a/hw/xfree86/dixmods/cfb32module.c b/hw/xfree86/dixmods/cfb32module.c
deleted file mode 100644
index 23708e4..0000000
--- a/hw/xfree86/dixmods/cfb32module.c
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 1998 The XFree86 Project, Inc.  All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
- * XFREE86 PROJECT BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name of the XFree86 Project shall
- * not be used in advertising or otherwise to promote the sale, use or other
- * dealings in this Software without prior written authorization from the
- * XFree86 Project.
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include "xf86Module.h"
-
-static MODULESETUPPROTO(cfb32Setup);
-
-static XF86ModuleVersionInfo VersRec =
-{
-	"cfb32",
-	MODULEVENDORSTRING,
-	MODINFOSTRING1,
-	MODINFOSTRING2,
-	XORG_VERSION_CURRENT,
-	1, 0, 0,
-	ABI_CLASS_ANSIC,		/* Only need the ansic layer */
-	ABI_ANSIC_VERSION,
-	MOD_CLASS_NONE,
-	{0,0,0,0}       /* signature, to be patched into the file by a tool */
-};
-
-_X_EXPORT XF86ModuleData cfb32ModuleData = { &VersRec, cfb32Setup, NULL };
-
-static pointer
-cfb32Setup(pointer module, pointer opts, int *errmaj, int *errmin)
-{
-    /* This modules requires cfb, so load it */
-    return LoadSubModule(module, "cfb", NULL, NULL, NULL, NULL,
-			 errmaj, errmin);
-}
diff --git a/hw/xfree86/dixmods/cfbmodule.c b/hw/xfree86/dixmods/cfbmodule.c
deleted file mode 100644
index 07074c1..0000000
--- a/hw/xfree86/dixmods/cfbmodule.c
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 1998 The XFree86 Project, Inc.  All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
- * XFREE86 PROJECT BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name of the XFree86 Project shall
- * not be used in advertising or otherwise to promote the sale, use or other
- * dealings in this Software without prior written authorization from the
- * XFree86 Project.
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include "xf86Module.h"
-
-static MODULESETUPPROTO(cfbSetup);
-
-static XF86ModuleVersionInfo VersRec =
-{
-	"cfb",
-	MODULEVENDORSTRING,
-	MODINFOSTRING1,
-	MODINFOSTRING2,
-	XORG_VERSION_CURRENT,
-	1, 0, 0,
-	ABI_CLASS_ANSIC,		/* Only need the ansic layer */
-	ABI_ANSIC_VERSION,
-	MOD_CLASS_NONE,
-	{0,0,0,0}       /* signature, to be patched into the file by a tool */
-};
-
-_X_EXPORT XF86ModuleData cfbModuleData = { &VersRec, cfbSetup, NULL };
-
-static pointer
-cfbSetup(pointer module, pointer opts, int *errmaj, int *errmin)
-{
-    /* This modules requires mfb, so load it */
-    return LoadSubModule(module, "mfb", NULL, NULL, NULL, NULL,
-			 errmaj, errmin);
-}
diff --git a/hw/xfree86/dixmods/extmod/Makefile.am b/hw/xfree86/dixmods/extmod/Makefile.am
index f90e144..77af62d 100644
--- a/hw/xfree86/dixmods/extmod/Makefile.am
+++ b/hw/xfree86/dixmods/extmod/Makefile.am
@@ -23,7 +23,6 @@ AM_CFLAGS = @DIX_CFLAGS@ @XORG_CFLAGS@
 INCLUDES = @XORG_INCS@ \
            -I$(top_srcdir)/afb \
            -I$(top_srcdir)/mfb \
-           -I$(top_srcdir)/cfb \
            -I$(top_srcdir)/dbe \
            -I$(top_srcdir)/hw/xfree86/loader \
            -I$(top_srcdir)/miext/shadow
diff --git a/hw/xfree86/xf8_32bpp/Makefile.am b/hw/xfree86/xf8_32bpp/Makefile.am
deleted file mode 100644
index 6f51a62..0000000
--- a/hw/xfree86/xf8_32bpp/Makefile.am
+++ /dev/null
@@ -1,37 +0,0 @@
-module_LTLIBRARIES = libxf8_32bpp.la
-
-sdk_HEADERS = cfb8_32.h
-
-INCLUDES = $(XORG_INCS) -I$(top_srcdir)/mfb -I$(top_srcdir)/cfb
-
-AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
-
-libxf8_32bpp_la_LDFLAGS = -avoid-version
-
-libxf8_32bpp_la_SOURCES = \
-	cfbcpyarea.c \
-	cfbcpyplane.c \
-	cfbgcmisc.c \
-	cfbimage.c \
-	cfbpntwin.c \
-	cfbscrinit.c \
-	cfbwindow.c \
-	xf86overlay.c \
-	cfb8_32module.c \
-	cfbgc8.c \
-	cfbgc32.c \
-	cfbgcunder.c
-
-libxf8_32bpp_la_LIBADD = $(top_builddir)/cfb32/libcfb32.la
-
-EXTRA_DIST = cfbgc.c
-
-cfbgc8.c: $(srcdir)/cfbgc.c
-	echo '#define PSZ 8' > $@
-	echo '#include "$(srcdir)/cfbgc.c"' >> $@
-
-cfbgc32.c: $(srcdir)/cfbgc.c
-	echo '#define PSZ 32' > $@
-	echo '#include "$(srcdir)/cfbgc.c"' >> $@
-
-DISTCLEANFILES = cfbgc8.c cfbgc32.c
diff --git a/hw/xfree86/xf8_32bpp/cfb8_32.h b/hw/xfree86/xf8_32bpp/cfb8_32.h
deleted file mode 100644
index 6e985da..0000000
--- a/hw/xfree86/xf8_32bpp/cfb8_32.h
+++ /dev/null
@@ -1,191 +0,0 @@
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#ifndef _CFB8_32_H
-#define _CFB8_32_H
-
-#include "gcstruct.h"
-
-typedef struct {
-   GCOps		*Ops8bpp;
-   GCOps 		*Ops32bpp;
-   unsigned long	changes;	
-   Bool			OpsAre8bpp;  
-} cfb8_32GCRec, *cfb8_32GCPtr;
-
-typedef struct {
-   unsigned char	key;
-   void                (*EnableDisableFBAccess)(int scrnIndex, Bool enable);
-   pointer		visualData;
-} cfb8_32ScreenRec, *cfb8_32ScreenPtr;
-
-
-extern DevPrivateKey cfb8_32GetGCPrivateKey(void);
-extern DevPrivateKey cfb8_32GetScreenPrivateKey(void);
-
-RegionPtr
-cfb8_32CopyArea(
-    DrawablePtr pSrcDraw,
-    DrawablePtr pDstDraw,
-    GC *pGC,
-    int srcx, int srcy,
-    int width, int height,
-    int dstx, int dsty 
-);
-
-void 
-cfbDoBitblt8To32(
-    DrawablePtr pSrc, 
-    DrawablePtr pDst, 
-    int rop,
-    RegionPtr prgnDst, 
-    DDXPointPtr pptSrc,
-    unsigned long planemask
-);
-
-void 
-cfbDoBitblt32To8(
-    DrawablePtr pSrc, 
-    DrawablePtr pDst, 
-    int rop,
-    RegionPtr prgnDst, 
-    DDXPointPtr pptSrc,
-    unsigned long planemask
-);
-
-
-void
-cfb8_32ValidateGC8(
-    GCPtr  		pGC,
-    unsigned long 	changes,
-    DrawablePtr		pDrawable
-);
-
-void
-cfb8_32ValidateGC32(
-    GCPtr  		pGC,
-    unsigned long 	changes,
-    DrawablePtr		pDrawable
-);
-
-void
-cfb32ValidateGC_Underlay(
-    GCPtr  		pGC,
-    unsigned long 	changes,
-    DrawablePtr		pDrawable
-);
-
-Bool cfb8_32CreateGC(GCPtr pGC);
-
-void
-cfb8_32GetSpans(
-   DrawablePtr pDraw,
-   int wMax,
-   DDXPointPtr ppt,
-   int *pwidth,
-   int nspans,
-   char *pchardstStart
-);
-
-void
-cfb8_32PutImage (
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    int depth, 
-    int x, int y, int w, int h,
-    int leftPad,
-    int format,
-    char *pImage
-);
-
-void
-cfb8_32GetImage (
-    DrawablePtr pDraw,
-    int sx, int sy, int w, int h,
-    unsigned int format,
-    unsigned long planeMask,
-    char *pdstLine
-);
-
-Bool
-cfb8_32ScreenInit (
-    ScreenPtr pScreen,
-    pointer pbits,
-    int xsize, int ysize,
-    int dpix, int dpiy,	
-    int width
-);
-
-void
-cfb8_32FillBoxSolid8 (
-   DrawablePtr pDraw,
-   int nbox,
-   BoxPtr pBox,
-   unsigned long color
-);
-
-RegionPtr 
-cfb8_32CopyPlane(
-    DrawablePtr pSrc,
-    DrawablePtr pDst,
-    GCPtr pGC,
-    int srcx, int srcy,
-    int width, int height,
-    int dstx, int dsty,
-    unsigned long bitPlane
-);
-
-void 
-cfbDoBitblt8To8GXcopy(
-    DrawablePtr pSrc, 
-    DrawablePtr pDst, 
-    int rop,
-    RegionPtr prgnDst, 
-    DDXPointPtr pptSrc,
-    unsigned long pm
-);
-
-void 
-cfbDoBitblt24To24GXcopy(
-    DrawablePtr pSrc, 
-    DrawablePtr pDst, 
-    int rop,
-    RegionPtr prgnDst, 
-    DDXPointPtr pptSrc,
-    unsigned long pm
-);
-
-Bool cfb8_32CreateWindow(WindowPtr pWin);
-Bool cfb8_32DestroyWindow(WindowPtr pWin);
-
-Bool
-cfb8_32PositionWindow(
-    WindowPtr pWin,
-    int x, int y
-);
-
-void
-cfb8_32CopyWindow(
-    WindowPtr pWin,
-    DDXPointRec ptOldOrg,
-    RegionPtr prgnSrc
-);
-
-Bool
-cfb8_32ChangeWindowAttributes(
-    WindowPtr pWin,
-    unsigned long mask
-);
-
-
-#define CFB8_32_GET_GC_PRIVATE(pGC) ((cfb8_32GCPtr) \
-    dixLookupPrivate(&(pGC)->devPrivates, cfb8_32GetGCPrivateKey()))
-
-#define CFB8_32_GET_SCREEN_PRIVATE(pScreen) ((cfb8_32ScreenPtr) \
-    dixLookupPrivate(&(pScreen)->devPrivates, cfb8_32GetScreenPrivateKey()))
-
-Bool xf86Overlay8Plus32Init (ScreenPtr pScreen);
-
-#endif /* _CFB8_32_H */
diff --git a/hw/xfree86/xf8_32bpp/cfb8_32module.c b/hw/xfree86/xf8_32bpp/cfb8_32module.c
deleted file mode 100644
index 5afabe5..0000000
--- a/hw/xfree86/xf8_32bpp/cfb8_32module.c
+++ /dev/null
@@ -1,39 +0,0 @@
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include "xf86Module.h"
-
-static MODULESETUPPROTO(xf8_32bppSetup);
-
-static XF86ModuleVersionInfo VersRec =
-{
-        "xf8_32bpp",
-        MODULEVENDORSTRING,
-        MODINFOSTRING1,
-        MODINFOSTRING2,
-        XORG_VERSION_CURRENT,
-        1, 0, 0,
-        ABI_CLASS_ANSIC,                /* Only need the ansic layer */
-        ABI_ANSIC_VERSION,
-        MOD_CLASS_NONE,
-        {0,0,0,0}       /* signature, to be patched into the file by a tool */
-};
-
-_X_EXPORT XF86ModuleData xf8_32bppModuleData = {
-    &VersRec,
-    xf8_32bppSetup,
-    NULL
-};
-
-static pointer
-xf8_32bppSetup(pointer module, pointer opts, int *errmaj, int *errmin)
-{
-    if (!LoadSubModule(module, "cfb", NULL, NULL, NULL, NULL,
-			errmaj, errmin))
-        return NULL;
-    if (!LoadSubModule(module, "cfb32", NULL, NULL, NULL, NULL,
-			errmaj, errmin))
-        return NULL;
-    return (pointer)1;  /* non-NULL required to indicate success */
-}
diff --git a/hw/xfree86/xf8_32bpp/cfbcpyarea.c b/hw/xfree86/xf8_32bpp/cfbcpyarea.c
deleted file mode 100644
index d8f0c6d..0000000
--- a/hw/xfree86/xf8_32bpp/cfbcpyarea.c
+++ /dev/null
@@ -1,549 +0,0 @@
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <stdlib.h>
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "servermd.h"
-#include "scrnintstr.h"
-#include "pixmapstr.h"
-#include "resource.h"
-#include "colormap.h"
-#include "colormapst.h"
-#define PSZ 8
-#include "cfb.h"
-#undef PSZ
-#include "cfb32.h"
-#include "cfb8_32.h"
-#include "mi.h"
-#include "mistruct.h"
-#include "dix.h"
-#include "mibstore.h"
-
-
-RegionPtr
-cfb8_32CopyArea(
-    DrawablePtr pSrcDraw,
-    DrawablePtr pDstDraw,
-    GC *pGC,
-    int srcx, int srcy,
-    int width, int height,
-    int dstx, int dsty 
-){
-
-   if(pSrcDraw->bitsPerPixel == 32) {
-	if(pDstDraw->bitsPerPixel == 32) {
-	    if((pGC->alu == GXcopy) && (pGC->planemask == 0xff000000)) {
-		return cfb32BitBlt (pSrcDraw, pDstDraw,
-            		pGC, srcx, srcy, width, height, dstx, dsty, 
-			cfbDoBitblt8To8GXcopy, 0L);
-	    }
-	    return(cfb32CopyArea(pSrcDraw, pDstDraw, pGC, srcx, srcy,
-		    			width, height, dstx, dsty));
-	} else {
-	    /* have to translate 32 -> 8 copies */
-	    return cfb32BitBlt (pSrcDraw, pDstDraw,
-            		pGC, srcx, srcy, width, height, dstx, dsty, 
-			cfbDoBitblt32To8, 0L);
-	}
-   } else {
-	if(pDstDraw->bitsPerPixel == 32) {
-	    /* have to translate 8 -> 32 copies */
-	    return cfb32BitBlt (pSrcDraw, pDstDraw,
-            		pGC, srcx, srcy, width, height, dstx, dsty, 
-			cfbDoBitblt8To32, 0L);
-	} else {
-	    return(cfbCopyArea(pSrcDraw, pDstDraw, pGC, srcx, srcy,
-		    width, height, dstx, dsty));
-	}
-   }
-}
-
-
-
-
-void 
-cfbDoBitblt8To32(
-    DrawablePtr pSrc, 
-    DrawablePtr pDst, 
-    int rop,
-    RegionPtr prgnDst, 
-    DDXPointPtr pptSrc,
-    unsigned long pm
-){
-    BoxPtr pbox = REGION_RECTS(prgnDst);
-    int nbox = REGION_NUM_RECTS(prgnDst);
-    unsigned char *ptr8, *ptr32;
-    unsigned char *data8, *data32;
-    int pitch8, pitch32;
-    int height, width, i;
-
-    cfbGetByteWidthAndPointer(pSrc, pitch8, ptr8);
-    cfbGetByteWidthAndPointer(pDst, pitch32, ptr32);
-    ptr32 += 3; /* point to the top byte */
-
-    pm >>= 24;
-
-    if((pm == 0xff) && (rop == GXcopy)) {
-	for(;nbox; pbox++, pptSrc++, nbox--) {
-	    data8 = ptr8 + (pptSrc->y * pitch8) + pptSrc->x;
-	    data32 = ptr32 + (pbox->y1 * pitch32) + (pbox->x1 << 2);
-	    width = pbox->x2 - pbox->x1;
-	    height = pbox->y2 - pbox->y1;
-
-	    while(height--) {
-		for(i = 0; i < width; i++)
-		    data32[i << 2] = data8[i];
-		data8 += pitch8;
-		data32 += pitch32;
-	    }
-	}
-    } else {  /* it ain't pretty, but hey */
-	for(;nbox; pbox++, pptSrc++, nbox--) {
-	    data8 = ptr8 + (pptSrc->y * pitch8) + pptSrc->x;
-	    data32 = ptr32 + (pbox->y1 * pitch32) + (pbox->x1 << 2);
-	    width = pbox->x2 - pbox->x1;
-	    height = pbox->y2 - pbox->y1;
-
-	    while(height--) {	
-		switch(rop) {
-		case GXcopy:
-		    for(i = 0; i < width; i++)
-			data32[i<<2] = (data8[i] & pm) | (data32[i<<2] & ~pm);
-		    break;
-		case GXor:
-		    for(i = 0; i < width; i++)
-			data32[i<<2] |= data8[i] & pm;
-		    break;
-		case GXclear:
-		    for(i = 0; i < width; i++)
-			data32[i<<2] &= ~pm;
-		    break;
-		case GXand:
-		    for(i = 0; i < width; i++) 
-			data32[i<<2] &= data8[i] | ~pm;
-		    break;
-		case GXandReverse:
-		    for(i = 0; i < width; i++) 
-			data32[i<<2] = ~data32[i<<2] & (data8[i] | ~pm);
-		    break;
-		case GXandInverted:
-		    for(i = 0; i < width; i++) 
-			data32[i<<2] &= ~data8[i] | ~pm;
-		    break;
-		case GXnoop:
-		    return;
-		case GXxor:
-		    for(i = 0; i < width; i++) 
-			data32[i<<2] ^= data8[i] & pm;
-		    break;
-		case GXnor:
-		    for(i = 0; i < width; i++)
-			data32[i<<2] =  ~(data32[i<<2] | (data8[i] & pm));
-		    break;
-		case GXequiv:
-		    for(i = 0; i < width; i++)
-			data32[i<<2] = ~(data32[i<<2] ^ (data8[i] & pm));
-		    break;
-		case GXinvert:
-		    for(i = 0; i < width; i++)
-			data32[i<<2] ^= pm;
-		    break;
-		case GXorReverse:
-		    for(i = 0; i < width; i++)
-			data32[i<<2] = ~data32[i<<2] | (data8[i] & pm);
-		    break;
-		case GXcopyInverted:
-		    for(i = 0; i < width; i++)
-			data32[i<<2] = (~data8[i] & pm) | (data32[i<<2] & ~pm);
-		    break;
-		case GXorInverted:
-		    for(i = 0; i < width; i++)
-			data32[i<<2] |= ~data8[i] & pm;
-		    break;
-		case GXnand:
-		    for(i = 0; i < width; i++) 
-			data32[i<<2] = ~(data32[i<<2] & (data8[i] | ~pm));
-		    break;
-		case GXset:
-		    for(i = 0; i < width; i++)
-			data32[i<<2] |= pm;
-		    break;
-		}
-	        data8 += pitch8;
-	        data32 += pitch32;
-	    }
-	}
-    }
-}
-
-
-void 
-cfbDoBitblt32To8(
-    DrawablePtr pSrc, 
-    DrawablePtr pDst, 
-    int rop,
-    RegionPtr prgnDst, 
-    DDXPointPtr pptSrc,
-    unsigned long pm
-){
-    BoxPtr pbox = REGION_RECTS(prgnDst);
-    int nbox = REGION_NUM_RECTS(prgnDst);
-    unsigned char *ptr8, *ptr32;
-    unsigned char *data8, *data32;
-    int pitch8, pitch32;
-    int height, width, i;
-
-    cfbGetByteWidthAndPointer(pDst, pitch8, ptr8);
-    cfbGetByteWidthAndPointer(pSrc, pitch32, ptr32);
-    ptr32 += 3; /* point to the top byte */
-
-    if(((pm & 0xff) == 0xff) && (rop == GXcopy)) {
-	for(;nbox; pbox++, pptSrc++, nbox--) {
-	    data8 = ptr8 + (pbox->y1 * pitch8) + pbox->x1;
-	    data32 = ptr32 + (pptSrc->y * pitch32) + (pptSrc->x << 2);
-
-	    width = pbox->x2 - pbox->x1;
-	    height = pbox->y2 - pbox->y1;
-
-	    while(height--) {
-		for(i = 0; i < width; i++)
-		    data8[i] = data32[i << 2];
-		data8 += pitch8;
-		data32 += pitch32;
-	    }
-	}
-    } else {
-	for(;nbox; pbox++, pptSrc++, nbox--) {
-	    data8 = ptr8 + (pbox->y1 * pitch8) + pbox->x1;
-	    data32 = ptr32 + (pptSrc->y * pitch32) + (pptSrc->x << 2);
-
-	    width = pbox->x2 - pbox->x1;
-	    height = pbox->y2 - pbox->y1;
-
-	    while(height--) {	
-		switch(rop) {
-		case GXcopy:
-		    for(i = 0; i < width; i++)
-			data8[i] = (data32[i<<2] & pm) | (data8[i] & ~pm);
-		    break;
-		case GXor:
-		    for(i = 0; i < width; i++)
-			data8[i] |= data32[i<<2] & pm;
-		    break;
-		case GXclear:
-		    for(i = 0; i < width; i++)
-			data8[i] &= ~pm;
-		    break;
-		case GXand:
-		    for(i = 0; i < width; i++)
-			data8[i] &= data32[i<<2] | ~pm;
-		    break;
-		case GXandReverse:
-		    for(i = 0; i < width; i++)
-			data8[i] = ~data8[i] & (data32[i<<2] | ~pm);
-		    break;
-		case GXandInverted:
-		    for(i = 0; i < width; i++)
-			data8[i] &= ~data32[i<<2] | ~pm;
-		    break;
-		case GXnoop:
-		    return;
-		case GXxor:
-		    for(i = 0; i < width; i++) 
-			data8[i] ^= data32[i<<2] & pm;
-		    break;
-		case GXnor:
-		    for(i = 0; i < width; i++)
-			data8[i] = ~(data8[i] | (data32[i<<2] & pm));
-		    break;
-		case GXequiv:
-		    for(i = 0; i < width; i++)
-			data8[i] = ~(data8[i] ^ (data32[i<<2] & pm));
-		    break;
-		case GXinvert:
-		    for(i = 0; i < width; i++)
-			data8[i] ^= pm;
-		    break;
-		case GXorReverse:
-		    for(i = 0; i < width; i++)
-			data8[i] = ~data8[i] | (data32[i<<2] & pm);
-		    break;
-		case GXcopyInverted:
-		    for(i = 0; i < width; i++)
-			data8[i] = (~data32[i<<2] & pm) | (data8[i] & ~pm);
-		    break;
-		case GXorInverted:
-		    for(i = 0; i < width; i++)
-			data8[i] |= ~data32[i<<2] & pm;
-		    break;
-		case GXnand:
-		    for(i = 0; i < width; i++)
-			data8[i] = ~(data8[i] & (data32[i<<2] | ~pm));
-		    break;
-		case GXset:
-		    for(i = 0; i < width; i++)
-			data8[i] |= pm;
-		    break;
-		}
-	        data8 += pitch8;
-	        data32 += pitch32;
-	    }
-	}
-    }
-}
-
-
-
-static void 
-Do8To8Blt(
-   unsigned char *SrcPtr,
-   int SrcPitch,
-   unsigned char *DstPtr,
-   int DstPitch,
-   int nbox,
-   DDXPointPtr pptSrc,
-   BoxPtr pbox,
-   int xdir, int ydir
-){
-   int i, j, width, height, ydir2;
-   CARD8 *src, *dst;
-
-   SrcPtr += 3;
-   DstPtr += 3;
-   xdir *= 4;
-   ydir2 = ydir * DstPitch;
-   ydir *= SrcPitch;
-
-   for(;nbox; pbox++, pptSrc++, nbox--) {
-	src = SrcPtr + (pptSrc->y * SrcPitch) + (pptSrc->x << 2);
-	dst = DstPtr + (pbox->y1 * DstPitch) + (pbox->x1 << 2);
-	width = pbox->x2 - pbox->x1;
-	height = pbox->y2 - pbox->y1;
-
-	if(ydir < 0) {
-	    src += (height - 1) * SrcPitch;
-	    dst += (height - 1) * DstPitch;
-	}
-
-	if(xdir < 0) {
-	    register int tmp = (width - 1) << 2;
-	    src += tmp;
-	    dst += tmp;
-	}
-
-	while(height--) {
-	   for(i = width, j = 0; i--; j+=xdir)
-		dst[j] = src[j];
-	   src += ydir;
-	   dst += ydir2;
-	}
-    }
-}
-
-static void 
-Do24To24Blt(
-   unsigned char *SrcPtr,
-   int SrcPitch,
-   unsigned char *DstPtr,
-   int DstPitch,
-   int nbox,
-   DDXPointPtr pptSrc,
-   BoxPtr pbox,
-   int xdir, int ydir
-){
-   int i, j, width, height, ydir2;
-   CARD8 *src, *dst;
-
-   xdir *= 4;
-   ydir2 = ydir * DstPitch;
-   ydir *= SrcPitch;
-
-   for(;nbox; pbox++, pptSrc++, nbox--) {
-	src = SrcPtr + (pptSrc->y * SrcPitch) + (pptSrc->x << 2);
-	dst = DstPtr + (pbox->y1 * DstPitch) + (pbox->x1 << 2);
-	width = pbox->x2 - pbox->x1;
-	height = pbox->y2 - pbox->y1;
-
-	if(ydir < 0) {
-	    src += (height - 1) * SrcPitch;
-	    dst += (height - 1) * DstPitch;
-	}
-
-	if(xdir < 0) {
-	    register int tmp = (width - 1) << 2;
-	    src += tmp;
-	    dst += tmp;
-	}
-
-	while(height--) {
-	   for(i = width, j = 0; i--; j+=xdir) {
-		*((CARD16*)(dst + j)) = *((CARD32*)(src + j));
-		dst[j + 2] = src[j + 2];
-	   }
-	   src += ydir;
-	   dst += ydir2;
-	}
-    }
-}
-
-
-static void
-cfb8_32DoBitBlt(
-    DrawablePtr	    pSrc, 
-    DrawablePtr	    pDst,
-    RegionPtr	    prgnDst,
-    DDXPointPtr	    pptSrc,
-    void	    (*DoBlt)(
-        unsigned char *SrcPtr,
-        int SrcPitch,
-        unsigned char *DstPtr,
-        int DstPitch,
-        int nbox,
-        DDXPointPtr pptSrc,
-        BoxPtr pbox,
-        int xdir, int ydir)
-){
-    int nbox, careful, SrcPitch, DstPitch;
-    BoxPtr pbox, pboxTmp, pboxNext, pboxBase, pboxNew1, pboxNew2;
-    DDXPointPtr pptTmp, pptNew1, pptNew2;
-    int xdir, ydir;
-    unsigned char *SrcPtr, *DstPtr;
-
-    /* XXX we have to err on the side of safety when both are windows,
-     * because we don't know if IncludeInferiors is being used.
-     */
-    careful = ((pSrc == pDst) ||
-               ((pSrc->type == DRAWABLE_WINDOW) &&
-                (pDst->type == DRAWABLE_WINDOW)));
-
-    pbox = REGION_RECTS(prgnDst);
-    nbox = REGION_NUM_RECTS(prgnDst);
-
-    pboxNew1 = NULL;
-    pptNew1 = NULL;
-    pboxNew2 = NULL;
-    pptNew2 = NULL;
-    if (careful && (pptSrc->y < pbox->y1)) {
-        /* walk source botttom to top */
-	ydir = -1;
-
-	if (nbox > 1) {
-	    /* keep ordering in each band, reverse order of bands */
-	    pboxNew1 = (BoxPtr)xalloc(sizeof(BoxRec) * nbox);
-	    if(!pboxNew1)
-		return;
-	    pptNew1 = (DDXPointPtr)xalloc(sizeof(DDXPointRec) * nbox);
-	    if(!pptNew1) {
-	        xfree(pboxNew1);
-	        return;
-	    }
-	    pboxBase = pboxNext = pbox+nbox-1;
-	    while (pboxBase >= pbox) {
-	        while ((pboxNext >= pbox) &&
-		       (pboxBase->y1 == pboxNext->y1))
-		    pboxNext--;
-	        pboxTmp = pboxNext+1;
-	        pptTmp = pptSrc + (pboxTmp - pbox);
-	        while (pboxTmp <= pboxBase) {
-		    *pboxNew1++ = *pboxTmp++;
-		    *pptNew1++ = *pptTmp++;
-	        }
-	        pboxBase = pboxNext;
-	    }
-	    pboxNew1 -= nbox;
-	    pbox = pboxNew1;
-	    pptNew1 -= nbox;
-	    pptSrc = pptNew1;
-        }
-    } else {
-	/* walk source top to bottom */
-	ydir = 1;
-    }
-
-    if (careful && (pptSrc->x < pbox->x1)) {
-	/* walk source right to left */
-        xdir = -1;
-
-	if (nbox > 1) {
-	    /* reverse order of rects in each band */
-	    pboxNew2 = (BoxPtr)xalloc(sizeof(BoxRec) * nbox);
-	    pptNew2 = (DDXPointPtr)xalloc(sizeof(DDXPointRec) * nbox);
-	    if(!pboxNew2 || !pptNew2) {
-		if (pptNew2) xfree(pptNew2);
-		if (pboxNew2) xfree(pboxNew2);
-		if (pboxNew1) {
-		    xfree(pptNew1);
-		    xfree(pboxNew1);
-		}
-	        return;
-	    }
-	    pboxBase = pboxNext = pbox;
-	    while (pboxBase < pbox+nbox) {
-	        while ((pboxNext < pbox+nbox) &&
-		       (pboxNext->y1 == pboxBase->y1))
-		    pboxNext++;
-	        pboxTmp = pboxNext;
-	        pptTmp = pptSrc + (pboxTmp - pbox);
-	        while (pboxTmp != pboxBase) {
-		    *pboxNew2++ = *--pboxTmp;
-		    *pptNew2++ = *--pptTmp;
-	        }
-	        pboxBase = pboxNext;
-	    }
-	    pboxNew2 -= nbox;
-	    pbox = pboxNew2;
-	    pptNew2 -= nbox;
-	    pptSrc = pptNew2;
-	}
-    } else {
-	/* walk source left to right */
-        xdir = 1;
-    }
-
-    cfbGetByteWidthAndPointer(pSrc, SrcPitch, SrcPtr);
-    cfbGetByteWidthAndPointer(pDst, DstPitch, DstPtr);
-
-    (*DoBlt)(SrcPtr,SrcPitch,DstPtr,DstPitch,nbox,pptSrc,pbox,xdir,ydir);
- 
-    if (pboxNew2) {
-	xfree(pptNew2);
-	xfree(pboxNew2);
-    }
-    if (pboxNew1) {
-	xfree(pptNew1);
-	xfree(pboxNew1);
-    }
-
-}
-
-
-/* A couple routines to speed up full planemask copies */
-
-void 
-cfbDoBitblt8To8GXcopy(
-    DrawablePtr pSrc, 
-    DrawablePtr pDst, 
-    int rop,
-    RegionPtr prgnDst, 
-    DDXPointPtr pptSrc,
-    unsigned long pm
-){
-    cfb8_32DoBitBlt(pSrc, pDst, prgnDst, pptSrc, Do8To8Blt);
-}
-
-
-void 
-cfbDoBitblt24To24GXcopy(
-    DrawablePtr pSrc, 
-    DrawablePtr pDst, 
-    int rop,
-    RegionPtr prgnDst, 
-    DDXPointPtr pptSrc,
-    unsigned long pm
-){
-    cfb8_32DoBitBlt(pSrc, pDst, prgnDst, pptSrc, Do24To24Blt);
-}
diff --git a/hw/xfree86/xf8_32bpp/cfbcpyplane.c b/hw/xfree86/xf8_32bpp/cfbcpyplane.c
deleted file mode 100644
index e10b525..0000000
--- a/hw/xfree86/xf8_32bpp/cfbcpyplane.c
+++ /dev/null
@@ -1,41 +0,0 @@
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include <X11/Xproto.h>
-#include "gcstruct.h"
-#include "windowstr.h"
-#include "scrnintstr.h"
-#include "pixmapstr.h"
-#include "regionstr.h"
-#define PSZ 8
-#include "cfb.h"
-#undef PSZ
-#include "cfb32.h"
-#include "cfb8_32.h"
-#include "mi.h"
-
-
-RegionPtr 
-cfb8_32CopyPlane(
-    DrawablePtr pSrc,
-    DrawablePtr	pDst,
-    GCPtr pGC,
-    int srcx, int srcy,
-    int width, int height,
-    int dstx, int dsty,
-    unsigned long bitPlane
-){
-   /* There's actually much more to it than this */
-
-   if((pDst->bitsPerPixel == 8) && (pSrc->bitsPerPixel != 32)){
-	return(cfbCopyPlane(pSrc, pDst,
-            pGC, srcx, srcy, width, height, dstx, dsty, bitPlane));
-   } 
-
-
-   return(miCopyPlane (pSrc, pDst,
-            pGC, srcx, srcy, width, height, dstx, dsty, bitPlane));
-}
diff --git a/hw/xfree86/xf8_32bpp/cfbgc.c b/hw/xfree86/xf8_32bpp/cfbgc.c
deleted file mode 100644
index a7787ca..0000000
--- a/hw/xfree86/xf8_32bpp/cfbgc.c
+++ /dev/null
@@ -1,646 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-
-
-/*
-
-PSZ		8	16	24	32
-PIXEL_ADDR	True	True	True	True
-NO_ONE_RECT	False	False	False	False
-WriteBitGroup	True	True	True	True
-FOUR_BIT_CODE	True	False	False	False
-LOWMEMFTPT	False	False	False	False
-
-*/
-
-
-/* This gets built twice.  Once for 8bpp and another for 32bpp */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include <X11/Xproto.h>
-#include "cfb.h"
-#include <X11/fonts/fontstruct.h>
-#include "dixfontstr.h"
-#include "gcstruct.h"
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "region.h"
-
-#include "mistruct.h"
-#include "mibstore.h"
-#include "migc.h"
-#include "mioverlay.h"
-
-#include "cfb8_32.h"
-#include "cfbmskbits.h"
-#include "cfb8bit.h"
-
-
-#if PSZ == 8
-# define useTEGlyphBlt  cfbTEGlyphBlt8
-#else
-# ifdef WriteBitGroup
-#  define useTEGlyphBlt cfbImageGlyphBlt8
-# else
-#  define useTEGlyphBlt cfbTEGlyphBlt
-# endif
-#endif
-
-#ifdef WriteBitGroup
-# define useImageGlyphBlt       cfbImageGlyphBlt8
-# define usePolyGlyphBlt        cfbPolyGlyphBlt8
-#else
-# define useImageGlyphBlt       miImageGlyphBlt
-# define usePolyGlyphBlt        miPolyGlyphBlt
-#endif
-
-#ifdef FOUR_BIT_CODE
-# define usePushPixels  cfbPushPixels8
-#else
-# define usePushPixels  mfbPushPixels
-#endif
-
-#ifdef PIXEL_ADDR
-# define ZeroPolyArc    cfbZeroPolyArcSS8Copy
-#else
-# define ZeroPolyArc    miZeroPolyArc
-#endif
-
-
-static GCOps cfb8_32TEOps1Rect = {
-    cfbSolidSpansCopy,
-    cfbSetSpans,
-    cfb8_32PutImage,
-    cfb8_32CopyArea,
-    cfb8_32CopyPlane,
-    cfbPolyPoint,
-#ifdef PIXEL_ADDR
-    cfb8LineSS1Rect,
-    cfb8SegmentSS1Rect,
-#else
-    cfbLineSS,
-    cfbSegmentSS,
-#endif
-    miPolyRectangle,
-    ZeroPolyArc,
-    cfbFillPoly1RectCopy,
-    cfbPolyFillRect,
-    cfbPolyFillArcSolidCopy,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    useTEGlyphBlt,
-    usePolyGlyphBlt,
-    usePushPixels
-};
-
-static GCOps cfb8_32NonTEOps1Rect = {
-    cfbSolidSpansCopy,
-    cfbSetSpans,
-    cfb8_32PutImage,
-    cfb8_32CopyArea,
-    cfb8_32CopyPlane,
-    cfbPolyPoint,
-#ifdef PIXEL_ADDR
-    cfb8LineSS1Rect,
-    cfb8SegmentSS1Rect,
-#else
-    cfbLineSS,
-    cfbSegmentSS,
-#endif
-    miPolyRectangle,
-    ZeroPolyArc,
-    cfbFillPoly1RectCopy,
-    cfbPolyFillRect,
-    cfbPolyFillArcSolidCopy,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    useImageGlyphBlt,
-    usePolyGlyphBlt,
-    usePushPixels
-};
-
-static GCOps cfb8_32TEOps = {
-    cfbSolidSpansCopy,
-    cfbSetSpans,
-    cfb8_32PutImage,
-    cfb8_32CopyArea,
-    cfb8_32CopyPlane,
-    cfbPolyPoint,
-    cfbLineSS,
-    cfbSegmentSS,
-    miPolyRectangle,
-    ZeroPolyArc,
-    miFillPolygon,
-    cfbPolyFillRect,
-    cfbPolyFillArcSolidCopy,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    useTEGlyphBlt,
-    usePolyGlyphBlt,
-    usePushPixels
-};
-
-static GCOps cfb8_32NonTEOps = {
-    cfbSolidSpansCopy,
-    cfbSetSpans,
-    cfb8_32PutImage,
-    cfb8_32CopyArea,
-    cfb8_32CopyPlane,
-    cfbPolyPoint,
-    cfbLineSS,
-    cfbSegmentSS,
-    miPolyRectangle,
-#ifdef PIXEL_ADDR
-    cfbZeroPolyArcSS8Copy,
-#else
-    miZeroPolyArc,
-#endif
-    miFillPolygon,
-    cfbPolyFillRect,
-    cfbPolyFillArcSolidCopy,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    useImageGlyphBlt,
-    usePolyGlyphBlt,
-    usePushPixels
-};
-
-static GCOps *
-cfb8_32MatchCommon (GCPtr pGC, cfbPrivGCPtr devPriv)
-{
-    if (pGC->lineWidth != 0)
-	return 0;
-    if (pGC->lineStyle != LineSolid)
-	return 0;
-    if (pGC->fillStyle != FillSolid)
-	return 0;
-    if (devPriv->rop != GXcopy)
-	return 0;
-    if (pGC->font &&
-	FONTMAXBOUNDS(pGC->font,rightSideBearing) -
-        FONTMINBOUNDS(pGC->font,leftSideBearing) <= 32 &&
-	FONTMINBOUNDS(pGC->font,characterWidth) >= 0)
-    {
-	if (TERMINALFONT(pGC->font)
-#ifdef FOUR_BIT_CODE
-	    && FONTMAXBOUNDS(pGC->font,characterWidth) >= PGSZB
-#endif
-	)
-#ifdef NO_ONE_RECT
-            return &cfb8_32TEOps1Rect;
-#else
-	    if (devPriv->oneRect)
-		return &cfb8_32TEOps1Rect;
-	    else
-		return &cfb8_32TEOps;
-#endif
-	else
-#ifdef NO_ONE_RECT
-	    return &cfb8_32NonTEOps1Rect;
-#else
-	    if (devPriv->oneRect)
-		return &cfb8_32NonTEOps1Rect;
-	    else
-		return &cfb8_32NonTEOps;
-#endif
-    }
-    return 0;
-}
-
-
-/* Clipping conventions
-	if the drawable is a window
-	    CT_REGION ==> pCompositeClip really is the composite
-	    CT_other ==> pCompositeClip is the window clip region
-	if the drawable is a pixmap
-	    CT_REGION ==> pCompositeClip is the translated client region
-		clipped to the pixmap boundary
-	    CT_other ==> pCompositeClip is the pixmap bounding box
-*/
-
-void
-#if PSZ == 8
-cfb8_32ValidateGC8(
-#else
-cfb8_32ValidateGC32(
-#endif
-    GCPtr  		pGC,
-    unsigned long 	changes,
-    DrawablePtr		pDrawable
-){
-    int         mask;		/* stateChanges */
-    int         index;		/* used for stepping through bitfields */
-    int		new_rrop;
-    int         new_line, new_text, new_fillspans, new_fillarea;
-    /* flags for changing the proc vector */
-    cfbPrivGCPtr devPriv;
-    int		oneRect;
-
-    pGC->lastWinOrg.x = pDrawable->x;
-    pGC->lastWinOrg.y = pDrawable->y;
-    devPriv = cfbGetGCPrivate(pGC);
-
-    new_rrop = FALSE;
-    new_line = FALSE;
-    new_text = FALSE;
-    new_fillspans = FALSE;
-    new_fillarea = FALSE;
-
-    /*
-     * if the client clip is different or moved OR the subwindowMode has
-     * changed OR the window's clip has changed since the last validation
-     * we need to recompute the composite clip 
-     */
-
-    if ((changes & (GCClipXOrigin|GCClipYOrigin|GCClipMask|GCSubwindowMode)) ||
-	(pDrawable->serialNumber != (pGC->serialNumber & DRAWABLE_SERIAL_BITS)))
-    {
-	miComputeCompositeClip (pGC, pDrawable);
-#ifdef NO_ONE_RECT
-	devPriv->oneRect = FALSE;
-#else
-	oneRect = REGION_NUM_RECTS(pGC->pCompositeClip) == 1;
-	if (oneRect != devPriv->oneRect)
-	    new_line = TRUE;
-	devPriv->oneRect = oneRect;
-#endif
-    }
-
-    mask = changes;
-    while (mask) {
-	index = lowbit (mask);
-	mask &= ~index;
-
-	switch (index) {
-	case GCFunction:
-	case GCForeground:
-	    new_rrop = TRUE;
-	    break;
-	case GCPlaneMask:
-	    new_rrop = TRUE;
-	    new_text = TRUE;
-	    break;
-	case GCBackground:
-	    break;
-	case GCLineStyle:
-	case GCLineWidth:
-	    new_line = TRUE;
-	    break;
-	case GCJoinStyle:
-	case GCCapStyle:
-	    break;
-	case GCFillStyle:
-	    new_text = TRUE;
-	    new_fillspans = TRUE;
-	    new_line = TRUE;
-	    new_fillarea = TRUE;
-	    break;
-	case GCFillRule:
-	    break;
-	case GCTile:
-	    new_fillspans = TRUE;
-	    new_fillarea = TRUE;
-	    break;
-	case GCStipple:
-	    new_fillspans = TRUE;
-	    new_fillarea = TRUE;
-	    break;
-	case GCTileStipXOrigin:
-	case GCTileStipYOrigin:
-	    break;
-	case GCFont:
-	    new_text = TRUE;
-	    break;
-	case GCSubwindowMode:
-	case GCGraphicsExposures:
-	case GCClipXOrigin:
-	case GCClipYOrigin:
-	case GCClipMask:
-	case GCDashOffset:
-	case GCDashList:
-	case GCArcMode:
-	default:
-	    break;
-	}
-    }
-
-    /*
-     * If the drawable has changed,  ensure suitable
-     * entries are in the proc vector. 
-     */
-    if (pDrawable->serialNumber != (pGC->serialNumber & (DRAWABLE_SERIAL_BITS)))
-	new_fillspans = TRUE;	/* deal with FillSpans later */
-
-    if (new_rrop)
-    {
-	int old_rrop;
-
-	old_rrop = devPriv->rop;
-	devPriv->rop = cfbReduceRasterOp (pGC->alu, pGC->fgPixel,
-					   pGC->planemask,
-					   &devPriv->and, &devPriv->xor);
-	if (old_rrop == devPriv->rop)
-	    new_rrop = FALSE;
-	else
-	{
-#ifdef PIXEL_ADDR
-	    new_line = TRUE;
-#endif
-#ifdef WriteBitGroup
-	    new_text = TRUE;
-#endif
-	    new_fillspans = TRUE;
-	    new_fillarea = TRUE;
-	}
-    }
-
-    if(!pGC->ops)
-	pGC->ops = & cfb8_32NonTEOps;
-
-    if (new_rrop || new_fillspans || new_text || new_fillarea || new_line)
-    {
-	GCOps	*newops;
-
-	if ((newops = cfb8_32MatchCommon (pGC, devPriv)))
- 	{
-	    if (pGC->ops->devPrivate.val)
-		miDestroyGCOps (pGC->ops);
-	    pGC->ops = newops;
-	    new_rrop = new_line = new_fillspans = new_text = new_fillarea = 0;
-	}
- 	else
- 	{
-	    if (!pGC->ops->devPrivate.val)
-	    {
-		pGC->ops = miCreateGCOps (pGC->ops);
-		pGC->ops->devPrivate.val = 1;
-	    }
-	}
-    }
-
-    /* deal with the changes we've collected */
-    if (new_line)
-    {
-	pGC->ops->FillPolygon = miFillPolygon;
-#ifdef NO_ONE_RECT
-	if (pGC->fillStyle == FillSolid)
-	{
-	    switch (devPriv->rop) {
-	    case GXcopy:
-		pGC->ops->FillPolygon = cfbFillPoly1RectCopy;
-		break;
-	    default:
-		pGC->ops->FillPolygon = cfbFillPoly1RectGeneral;
-		break;
-	    }
-	}
-#else
-	if (devPriv->oneRect && pGC->fillStyle == FillSolid)
-	{
-	    switch (devPriv->rop) {
-	    case GXcopy:
-		pGC->ops->FillPolygon = cfbFillPoly1RectCopy;
-		break;
-	    default:
-		pGC->ops->FillPolygon = cfbFillPoly1RectGeneral;
-		break;
-	    }
-	}
-#endif
-	if (pGC->lineWidth == 0)
-	{
-#ifdef PIXEL_ADDR
-	    if ((pGC->lineStyle == LineSolid) && (pGC->fillStyle == FillSolid))
-	    {
-		switch (devPriv->rop)
-		{
-		case GXxor:
-		    pGC->ops->PolyArc = cfbZeroPolyArcSS8Xor;
-		    break;
-		case GXcopy:
-		    pGC->ops->PolyArc = cfbZeroPolyArcSS8Copy;
-		    break;
-		default:
-		    pGC->ops->PolyArc = cfbZeroPolyArcSS8General;
-		    break;
-		}
-	    }
-	    else
-#endif
-		pGC->ops->PolyArc = miZeroPolyArc;
-	}
-	else
-	    pGC->ops->PolyArc = miPolyArc;
-	pGC->ops->PolySegment = miPolySegment;
-	switch (pGC->lineStyle)
-	{
-	case LineSolid:
-	    if(pGC->lineWidth == 0)
-	    {
-		if (pGC->fillStyle == FillSolid)
-		{
-#if defined(PIXEL_ADDR) && !defined(NO_ONE_RECT)
-		    if (devPriv->oneRect &&
-			((pDrawable->x >= pGC->pScreen->width - 32768) &&
-			 (pDrawable->y >= pGC->pScreen->height - 32768)))
-		    {
-			pGC->ops->Polylines = cfb8LineSS1Rect;
-			pGC->ops->PolySegment = cfb8SegmentSS1Rect;
-		    } else
-#endif
-#ifdef NO_ONE_RECT
-		    {
-			pGC->ops->Polylines = cfb8LineSS1Rect;
-			pGC->ops->PolySegment = cfb8SegmentSS1Rect;
-		    }
-#else
-		    {
-		    	pGC->ops->Polylines = cfbLineSS;
-		    	pGC->ops->PolySegment = cfbSegmentSS;
-		    }
-#endif
-		}
- 		else
-		    pGC->ops->Polylines = miZeroLine;
-	    }
-	    else
-		pGC->ops->Polylines = miWideLine;
-	    break;
-	case LineOnOffDash:
-	case LineDoubleDash:
-	    if (pGC->lineWidth == 0 && pGC->fillStyle == FillSolid)
-	    {
-		pGC->ops->Polylines = cfbLineSD;
-		pGC->ops->PolySegment = cfbSegmentSD;
-	    } else
-		pGC->ops->Polylines = miWideDash;
-	    break;
-	}
-    }
-
-    if (new_text && (pGC->font))
-    {
-        if (FONTMAXBOUNDS(pGC->font,rightSideBearing) -
-            FONTMINBOUNDS(pGC->font,leftSideBearing) > 32 ||
-	    FONTMINBOUNDS(pGC->font,characterWidth) < 0)
-        {
-            pGC->ops->PolyGlyphBlt = miPolyGlyphBlt;
-            pGC->ops->ImageGlyphBlt = miImageGlyphBlt;
-        }
-        else
-        {
-#ifdef WriteBitGroup
-	    if (pGC->fillStyle == FillSolid)
-	    {
-		if (devPriv->rop == GXcopy)
-		    pGC->ops->PolyGlyphBlt = cfbPolyGlyphBlt8;
-		else
-#ifdef FOUR_BIT_CODE
-		    pGC->ops->PolyGlyphBlt = cfbPolyGlyphRop8;
-#else
-		    pGC->ops->PolyGlyphBlt = miPolyGlyphBlt;
-#endif
-	    }
-	    else
-#endif
-		pGC->ops->PolyGlyphBlt = miPolyGlyphBlt;
-            /* special case ImageGlyphBlt for terminal emulator fonts */
-#if !defined(WriteBitGroup) || PSZ == 8
-	    if (TERMINALFONT(pGC->font) &&
-		(pGC->planemask & PMSK) == PMSK
-#ifdef FOUR_BIT_CODE
-		&& FONTMAXBOUNDS(pGC->font,characterWidth) >= PGSZB
-#endif
-		)
-	    {
-		pGC->ops->ImageGlyphBlt = useTEGlyphBlt;
-	    }
-            else
-#endif
-	    {
-#ifdef WriteBitGroup
-		if (devPriv->rop == GXcopy &&
-		    pGC->fillStyle == FillSolid &&
-		    (pGC->planemask & PMSK) == PMSK)
-		    pGC->ops->ImageGlyphBlt = cfbImageGlyphBlt8;
-		else
-#endif
-		    pGC->ops->ImageGlyphBlt = miImageGlyphBlt;
-	    }
-        }
-    }    
-
-
-    if (new_fillspans) {
-	switch (pGC->fillStyle) {
-	case FillSolid:
-	    switch (devPriv->rop) {
-	    case GXcopy:
-		pGC->ops->FillSpans = cfbSolidSpansCopy;
-		break;
-	    case GXxor:
-		pGC->ops->FillSpans = cfbSolidSpansXor;
-		break;
-	    default:
-		pGC->ops->FillSpans = cfbSolidSpansGeneral;
-		break;
-	    }
-	    break;
-	case FillTiled:
-	    pGC->ops->FillSpans = cfbUnnaturalTileFS;
-	    break;
-	case FillStippled:
-	case FillOpaqueStippled:
-	    pGC->ops->FillSpans = cfbUnnaturalStippleFS;
-	    break;
-	default:
-	    FatalError("cfbValidateGC: illegal fillStyle\n");
-	}
-    } /* end of new_fillspans */
-
-    if (new_fillarea) {
-#ifndef FOUR_BIT_CODE
-	pGC->ops->PolyFillRect = miPolyFillRect;
-	if (pGC->fillStyle == FillSolid || pGC->fillStyle == FillTiled)
-	{
-	    pGC->ops->PolyFillRect = cfbPolyFillRect;
-	}
-#endif
-#ifdef FOUR_BIT_CODE
-	pGC->ops->PushPixels = mfbPushPixels;
-	if (pGC->fillStyle == FillSolid && devPriv->rop == GXcopy)
-	    pGC->ops->PushPixels = cfbPushPixels8;
-#endif
-	pGC->ops->PolyFillArc = miPolyFillArc;
-	if (pGC->fillStyle == FillSolid)
-	{
-	    switch (devPriv->rop)
-	    {
-	    case GXcopy:
-		pGC->ops->PolyFillArc = cfbPolyFillArcSolidCopy;
-		break;
-	    default:
-		pGC->ops->PolyFillArc = cfbPolyFillArcSolidGeneral;
-		break;
-	    }
-	}
-    }
-}
diff --git a/hw/xfree86/xf8_32bpp/cfbgcmisc.c b/hw/xfree86/xf8_32bpp/cfbgcmisc.c
deleted file mode 100644
index f009afc..0000000
--- a/hw/xfree86/xf8_32bpp/cfbgcmisc.c
+++ /dev/null
@@ -1,150 +0,0 @@
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <stdlib.h>
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include <X11/Xproto.h>
-#define PSZ 8
-#include "cfb.h"
-#undef PSZ
-#include "cfb32.h"
-#include "cfb8_32.h"
-#include <X11/fonts/fontstruct.h>
-#include "dixfontstr.h"
-#include "gcstruct.h"
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "region.h"
-
-#include "mistruct.h"
-#include "mibstore.h"
-#include "migc.h"
-
-
-static void cfb8_32ValidateGC(GCPtr, unsigned long, DrawablePtr);
-static void cfb8_32DestroyGC(GCPtr pGC);
-static void cfb32DestroyGC_Underlay(GCPtr pGC);
-
-static
-GCFuncs cfb8_32GCFuncs = {
-    cfb8_32ValidateGC,
-    miChangeGC,
-    miCopyGC,
-    cfb8_32DestroyGC,
-    miChangeClip,
-    miDestroyClip,
-    miCopyClip,
-};
-
-
-static
-GCFuncs cfb32GCFuncs_Underlay = {
-    cfb32ValidateGC_Underlay,
-    miChangeGC,
-    miCopyGC,
-    cfb32DestroyGC_Underlay,
-    miChangeClip,
-    miDestroyClip,
-    miCopyClip,
-};
-
-static void
-cfb32DestroyGC_Underlay(GCPtr pGC)
-{
-    if (pGC->freeCompClip)
-        REGION_DESTROY(pGC->pScreen, pGC->pCompositeClip);
-
-    if(pGC->ops)
-	miDestroyGCOps(pGC->ops);
-}
-
-
-static void
-cfb8_32DestroyGC(GCPtr pGC)
-{
-    cfb8_32GCPtr pGCPriv = CFB8_32_GET_GC_PRIVATE(pGC);
-
-    if (pGC->freeCompClip)
-        REGION_DESTROY(pGC->pScreen, pGC->pCompositeClip);
-    if(pGCPriv->Ops8bpp)
-	miDestroyGCOps(pGCPriv->Ops8bpp);
-    if(pGCPriv->Ops32bpp)
-	miDestroyGCOps(pGCPriv->Ops32bpp);
-}
-
-Bool
-cfb8_32CreateGC(GCPtr pGC)
-{
-    cfb8_32GCPtr pGCPriv;
-    cfbPrivGC *pPriv;
-
-    if (PixmapWidthPaddingInfo[pGC->depth].padPixelsLog2 == LOG2_BITMAP_PAD)
-        return (mfbCreateGC(pGC));
-
-    pGC->clientClip = NULL;
-    pGC->clientClipType = CT_NONE;
-    pGC->miTranslate = 1;
-    pGC->fExpose = TRUE;
-    pGC->freeCompClip = FALSE;
-    pGC->pRotatedPixmap = (PixmapPtr) NULL;
-
-    pPriv = cfbGetGCPrivate(pGC);
-    pPriv->rop = pGC->alu;
-    pPriv->oneRect = FALSE;
-
-    pGC->ops = NULL;
-
-    if (pGC->depth == 8) {
-	pGC->funcs = &cfb8_32GCFuncs;
-
-	pGCPriv = CFB8_32_GET_GC_PRIVATE(pGC);
-	pGCPriv->Ops8bpp = NULL;
-	pGCPriv->Ops32bpp = NULL;
-	pGCPriv->OpsAre8bpp = FALSE;
-	pGCPriv->changes = 0;
-    } else
-	pGC->funcs = &cfb32GCFuncs_Underlay;
-	
-    return TRUE;
-}
-
-
-static void
-cfb8_32ValidateGC(
-    GCPtr pGC,
-    unsigned long changes,
-    DrawablePtr pDraw
-){
-    cfb8_32GCPtr pGCPriv = CFB8_32_GET_GC_PRIVATE(pGC);
-
-    if(pDraw->bitsPerPixel == 32) {
-	if(pGCPriv->OpsAre8bpp) {
-	    int origChanges = changes;
-	    pGC->ops = pGCPriv->Ops32bpp;
-	    changes |= pGCPriv->changes;
-	    pGCPriv->changes = origChanges;
-	    pGCPriv->OpsAre8bpp = FALSE;
-	} else 
-	    pGCPriv->changes |= changes;
-
-	cfb8_32ValidateGC32(pGC, changes, pDraw);
-	pGCPriv->Ops32bpp = pGC->ops;
-    } else {  /* bitsPerPixel == 8 */
-	if(!pGCPriv->OpsAre8bpp) {
-	    int origChanges = changes;
-	    pGC->ops = pGCPriv->Ops8bpp;
-	    changes |= pGCPriv->changes;
-	    pGCPriv->changes = origChanges;
-	    pGCPriv->OpsAre8bpp = TRUE;
-	} else 
-	    pGCPriv->changes |= changes;
-
-	cfb8_32ValidateGC8(pGC, changes, pDraw);
-	pGCPriv->Ops8bpp = pGC->ops;
-    }
-}
-
diff --git a/hw/xfree86/xf8_32bpp/cfbgcunder.c b/hw/xfree86/xf8_32bpp/cfbgcunder.c
deleted file mode 100644
index d903213..0000000
--- a/hw/xfree86/xf8_32bpp/cfbgcunder.c
+++ /dev/null
@@ -1,620 +0,0 @@
-/***********************************************************
-
-Copyright 1987, 1998  The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its 
-documentation for any purpose and without fee is hereby granted, 
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in 
-supporting documentation, and that the name of Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.  
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-******************************************************************/
-#define PSZ 32
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include <X11/Xproto.h>
-#include "cfb.h"
-#include <X11/fonts/fontstruct.h>
-#include "dixfontstr.h"
-#include "gcstruct.h"
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "region.h"
-
-#include "mistruct.h"
-#include "mibstore.h"
-#include "migc.h"
-#include "mioverlay.h"
-
-#include "cfbmskbits.h"
-#include "cfb8bit.h"
-#include "cfb8_32.h"
-
-#ifdef WriteBitGroup
-#  define useTEGlyphBlt	cfbImageGlyphBlt8
-#else
-#  define useTEGlyphBlt	cfbTEGlyphBlt
-#endif
-
-#ifdef WriteBitGroup
-# define useImageGlyphBlt	cfbImageGlyphBlt8
-# define usePolyGlyphBlt	cfbPolyGlyphBlt8
-#else
-# define useImageGlyphBlt	miImageGlyphBlt
-# define usePolyGlyphBlt	miPolyGlyphBlt
-#endif
-
-#ifdef FOUR_BIT_CODE
-# define usePushPixels	cfbPushPixels8
-#else
-# define usePushPixels	mfbPushPixels
-#endif
-
-#ifdef PIXEL_ADDR
-# define ZeroPolyArc	cfbZeroPolyArcSS8Copy
-#else
-# define ZeroPolyArc	miZeroPolyArc
-#endif
-
-
-static GCOps cfbTEOps1Rect = {
-    cfbSolidSpansCopy,
-    cfbSetSpans,
-    cfbPutImage,
-    cfbCopyArea,
-    cfbCopyPlane,
-    cfbPolyPoint,
-#ifdef PIXEL_ADDR
-    cfb8LineSS1Rect,
-    cfb8SegmentSS1Rect,
-#else
-    cfbLineSS,
-    cfbSegmentSS,
-#endif
-    miPolyRectangle,
-    ZeroPolyArc,
-    cfbFillPoly1RectCopy,
-    cfbPolyFillRect,
-    cfbPolyFillArcSolidCopy,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    useTEGlyphBlt,
-    usePolyGlyphBlt,
-    usePushPixels
-};
-
-static GCOps cfbNonTEOps1Rect = {
-    cfbSolidSpansCopy,
-    cfbSetSpans,
-    cfbPutImage,
-    cfbCopyArea,
-    cfbCopyPlane,
-    cfbPolyPoint,
-#ifdef PIXEL_ADDR
-    cfb8LineSS1Rect,
-    cfb8SegmentSS1Rect,
-#else
-    cfbLineSS,
-    cfbSegmentSS,
-#endif
-    miPolyRectangle,
-    ZeroPolyArc,
-    cfbFillPoly1RectCopy,
-    cfbPolyFillRect,
-    cfbPolyFillArcSolidCopy,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    useImageGlyphBlt,
-    usePolyGlyphBlt,
-    usePushPixels
-};
-
-static GCOps cfbTEOps = {
-    cfbSolidSpansCopy,
-    cfbSetSpans,
-    cfbPutImage,
-    cfbCopyArea,
-    cfbCopyPlane,
-    cfbPolyPoint,
-    cfbLineSS,
-    cfbSegmentSS,
-    miPolyRectangle,
-    ZeroPolyArc,
-    miFillPolygon,
-    cfbPolyFillRect,
-    cfbPolyFillArcSolidCopy,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    useTEGlyphBlt,
-    usePolyGlyphBlt,
-    usePushPixels
-};
-
-static GCOps cfbNonTEOps = {
-    cfbSolidSpansCopy,
-    cfbSetSpans,
-    cfbPutImage,
-    cfbCopyArea,
-    cfbCopyPlane,
-    cfbPolyPoint,
-    cfbLineSS,
-    cfbSegmentSS,
-    miPolyRectangle,
-#ifdef PIXEL_ADDR
-    cfbZeroPolyArcSS8Copy,
-#else
-    miZeroPolyArc,
-#endif
-    miFillPolygon,
-    cfbPolyFillRect,
-    cfbPolyFillArcSolidCopy,
-    miPolyText8,
-    miPolyText16,
-    miImageText8,
-    miImageText16,
-    useImageGlyphBlt,
-    usePolyGlyphBlt,
-    usePushPixels
-};
-
-static GCOps *
-cfb32MatchCommon_Underlay(
-    GCPtr	    pGC,
-    cfbPrivGCPtr    devPriv)
-{
-    if (pGC->lineWidth != 0)
-	return 0;
-    if (pGC->lineStyle != LineSolid)
-	return 0;
-    if (pGC->fillStyle != FillSolid)
-	return 0;
-    if (devPriv->rop != GXcopy)
-	return 0;
-    if (pGC->font &&
-	FONTMAXBOUNDS(pGC->font,rightSideBearing) -
-        FONTMINBOUNDS(pGC->font,leftSideBearing) <= 32 &&
-	FONTMINBOUNDS(pGC->font,characterWidth) >= 0)
-    {
-	if (TERMINALFONT(pGC->font)
-#ifdef FOUR_BIT_CODE
-	    && FONTMAXBOUNDS(pGC->font,characterWidth) >= PGSZB
-#endif
-	)
-#ifdef NO_ONE_RECT
-            return &cfbTEOps1Rect;
-#else
-	    if (devPriv->oneRect)
-		return &cfbTEOps1Rect;
-	    else
-		return &cfbTEOps;
-#endif
-	else
-#ifdef NO_ONE_RECT
-	    return &cfbNonTEOps1Rect;
-#else
-	    if (devPriv->oneRect)
-		return &cfbNonTEOps1Rect;
-	    else
-		return &cfbNonTEOps;
-#endif
-    }
-    return 0;
-}
-
-
-void
-cfb32ValidateGC_Underlay(
-    GCPtr  pGC,
-    unsigned long   changes,
-    DrawablePtr	    pDrawable
-){
-    int         mask;		/* stateChanges */
-    int         index;		/* used for stepping through bitfields */
-    int		new_rrop;
-    int         new_line, new_text, new_fillspans, new_fillarea;
-    /* flags for changing the proc vector */
-    cfbPrivGCPtr devPriv;
-    int		oneRect;
-
-    pGC->lastWinOrg.x = pDrawable->x;
-    pGC->lastWinOrg.y = pDrawable->y;
-    devPriv = cfbGetGCPrivate(pGC);
-
-    new_rrop = FALSE;
-    new_line = FALSE;
-    new_text = FALSE;
-    new_fillspans = FALSE;
-    new_fillarea = FALSE;
-
-    /*
-     * if the client clip is different or moved OR the subwindowMode has
-     * changed OR the window's clip has changed since the last validation
-     * we need to recompute the composite clip 
-     */
-
-    if ((changes & (GCClipXOrigin|GCClipYOrigin|GCClipMask|GCSubwindowMode)) ||
-	(pDrawable->serialNumber != (pGC->serialNumber & DRAWABLE_SERIAL_BITS))
-	)
-    {
-	if(pDrawable->type == DRAWABLE_WINDOW)
-	    miOverlayComputeCompositeClip (pGC, (WindowPtr)pDrawable);
-	else
-	    miComputeCompositeClip (pGC, pDrawable);
-#ifdef NO_ONE_RECT
-	devPriv->oneRect = FALSE;
-#else
-	oneRect = REGION_NUM_RECTS(pGC->pCompositeClip) == 1;
-	if (oneRect != devPriv->oneRect)
-	    new_line = TRUE;
-	devPriv->oneRect = oneRect;
-#endif
-    }
-
-    mask = changes;
-    while (mask) {
-	index = lowbit (mask);
-	mask &= ~index;
-
-	switch (index) {
-	case GCFunction:
-	case GCForeground:
-	    new_rrop = TRUE;
-	    break;
-	case GCPlaneMask:
-	    new_rrop = TRUE;
-	    new_text = TRUE;
-	    break;
-	case GCBackground:
-	    break;
-	case GCLineStyle:
-	case GCLineWidth:
-	    new_line = TRUE;
-	    break;
-	case GCJoinStyle:
-	case GCCapStyle:
-	    break;
-	case GCFillStyle:
-	    new_text = TRUE;
-	    new_fillspans = TRUE;
-	    new_line = TRUE;
-	    new_fillarea = TRUE;
-	    break;
-	case GCFillRule:
-	    break;
-	case GCTile:
-	    new_fillspans = TRUE;
-	    new_fillarea = TRUE;
-	    break;
-	case GCStipple:
-	    new_fillspans = TRUE;
-	    new_fillarea = TRUE;
-	    break;
-	case GCTileStipXOrigin:
-	case GCTileStipYOrigin:
-	    break;
-	case GCFont:
-	    new_text = TRUE;
-	    break;
-	case GCSubwindowMode:
-	case GCGraphicsExposures:
-	case GCClipXOrigin:
-	case GCClipYOrigin:
-	case GCClipMask:
-	case GCDashOffset:
-	case GCDashList:
-	case GCArcMode:
-	default:
-	    break;
-	}
-    }
-
-    /*
-     * If the drawable has changed,  ensure suitable
-     * entries are in the proc vector. 
-     */
-    if (pDrawable->serialNumber != (pGC->serialNumber & (DRAWABLE_SERIAL_BITS)))
-	new_fillspans = TRUE;	/* deal with FillSpans later */
-
-    if (new_rrop)
-    {
-	int old_rrop;
-
-	old_rrop = devPriv->rop;
-	devPriv->rop = cfbReduceRasterOp (pGC->alu, pGC->fgPixel,
-					   pGC->planemask,
-					   &devPriv->and, &devPriv->xor);
-	if (old_rrop == devPriv->rop)
-	    new_rrop = FALSE;
-	else
-	{
-#ifdef PIXEL_ADDR
-	    new_line = TRUE;
-#endif
-#ifdef WriteBitGroup
-	    new_text = TRUE;
-#endif
-	    new_fillspans = TRUE;
-	    new_fillarea = TRUE;
-	}
-    }
-
-    if(!pGC->ops)
-	pGC->ops = & cfbNonTEOps;
-
-
-    if (new_rrop || new_fillspans || new_text || new_fillarea || new_line)
-    {
-	GCOps	*newops;
-
-	if ((newops = cfb32MatchCommon_Underlay (pGC, devPriv)))
- 	{
-	    if (pGC->ops->devPrivate.val)
-		miDestroyGCOps (pGC->ops);
-	    pGC->ops = newops;
-	    new_rrop = new_line = new_fillspans = new_text = new_fillarea = 0;
-	}
- 	else
- 	{
-	    if (!pGC->ops->devPrivate.val)
-	    {
-		pGC->ops = miCreateGCOps (pGC->ops);
-		pGC->ops->devPrivate.val = 1;
-	    }
-	}
-    }
-
-    /* deal with the changes we've collected */
-    if (new_line)
-    {
-	pGC->ops->FillPolygon = miFillPolygon;
-#ifdef NO_ONE_RECT
-	if (pGC->fillStyle == FillSolid)
-	{
-	    switch (devPriv->rop) {
-	    case GXcopy:
-		pGC->ops->FillPolygon = cfbFillPoly1RectCopy;
-		break;
-	    default:
-		pGC->ops->FillPolygon = cfbFillPoly1RectGeneral;
-		break;
-	    }
-	}
-#else
-	if (devPriv->oneRect && pGC->fillStyle == FillSolid)
-	{
-	    switch (devPriv->rop) {
-	    case GXcopy:
-		pGC->ops->FillPolygon = cfbFillPoly1RectCopy;
-		break;
-	    default:
-		pGC->ops->FillPolygon = cfbFillPoly1RectGeneral;
-		break;
-	    }
-	}
-#endif
-	if (pGC->lineWidth == 0)
-	{
-#ifdef PIXEL_ADDR
-	    if ((pGC->lineStyle == LineSolid) && (pGC->fillStyle == FillSolid))
-	    {
-		switch (devPriv->rop)
-		{
-		case GXxor:
-		    pGC->ops->PolyArc = cfbZeroPolyArcSS8Xor;
-		    break;
-		case GXcopy:
-		    pGC->ops->PolyArc = cfbZeroPolyArcSS8Copy;
-		    break;
-		default:
-		    pGC->ops->PolyArc = cfbZeroPolyArcSS8General;
-		    break;
-		}
-	    }
-	    else
-#endif
-		pGC->ops->PolyArc = miZeroPolyArc;
-	}
-	else
-	    pGC->ops->PolyArc = miPolyArc;
-	pGC->ops->PolySegment = miPolySegment;
-	switch (pGC->lineStyle)
-	{
-	case LineSolid:
-	    if(pGC->lineWidth == 0)
-	    {
-		if (pGC->fillStyle == FillSolid)
-		{
-#if defined(PIXEL_ADDR) && !defined(NO_ONE_RECT)
-		    if (devPriv->oneRect &&
-			((pDrawable->x >= pGC->pScreen->width - 32768) &&
-			 (pDrawable->y >= pGC->pScreen->height - 32768)))
-		    {
-			pGC->ops->Polylines = cfb8LineSS1Rect;
-			pGC->ops->PolySegment = cfb8SegmentSS1Rect;
-		    } else
-#endif
-#ifdef NO_ONE_RECT
-		    {
-			pGC->ops->Polylines = cfb8LineSS1Rect;
-			pGC->ops->PolySegment = cfb8SegmentSS1Rect;
-		    }
-#else
-		    {
-		    	pGC->ops->Polylines = cfbLineSS;
-		    	pGC->ops->PolySegment = cfbSegmentSS;
-		    }
-#endif
-		}
- 		else
-		    pGC->ops->Polylines = miZeroLine;
-	    }
-	    else
-		pGC->ops->Polylines = miWideLine;
-	    break;
-	case LineOnOffDash:
-	case LineDoubleDash:
-	    if (pGC->lineWidth == 0 && pGC->fillStyle == FillSolid)
-	    {
-		pGC->ops->Polylines = cfbLineSD;
-		pGC->ops->PolySegment = cfbSegmentSD;
-	    } else
-		pGC->ops->Polylines = miWideDash;
-	    break;
-	}
-    }
-
-    if (new_text && (pGC->font))
-    {
-        if (FONTMAXBOUNDS(pGC->font,rightSideBearing) -
-            FONTMINBOUNDS(pGC->font,leftSideBearing) > 32 ||
-	    FONTMINBOUNDS(pGC->font,characterWidth) < 0)
-        {
-            pGC->ops->PolyGlyphBlt = miPolyGlyphBlt;
-            pGC->ops->ImageGlyphBlt = miImageGlyphBlt;
-        }
-        else
-        {
-#ifdef WriteBitGroup
-	    if (pGC->fillStyle == FillSolid)
-	    {
-		if (devPriv->rop == GXcopy)
-		    pGC->ops->PolyGlyphBlt = cfbPolyGlyphBlt8;
-		else
-#ifdef FOUR_BIT_CODE
-		    pGC->ops->PolyGlyphBlt = cfbPolyGlyphRop8;
-#else
-		    pGC->ops->PolyGlyphBlt = miPolyGlyphBlt;
-#endif
-	    }
-	    else
-#endif
-		pGC->ops->PolyGlyphBlt = miPolyGlyphBlt;
-            /* special case ImageGlyphBlt for terminal emulator fonts */
-#if !defined(WriteBitGroup) || PSZ == 8
-	    if (TERMINALFONT(pGC->font) &&
-		(pGC->planemask & PMSK) == PMSK
-#ifdef FOUR_BIT_CODE
-		&& FONTMAXBOUNDS(pGC->font,characterWidth) >= PGSZB
-#endif
-		)
-	    {
-		pGC->ops->ImageGlyphBlt = useTEGlyphBlt;
-	    }
-            else
-#endif
-	    {
-#ifdef WriteBitGroup
-		if (devPriv->rop == GXcopy &&
-		    pGC->fillStyle == FillSolid &&
-		    (pGC->planemask & PMSK) == PMSK)
-		    pGC->ops->ImageGlyphBlt = cfbImageGlyphBlt8;
-		else
-#endif
-		    pGC->ops->ImageGlyphBlt = miImageGlyphBlt;
-	    }
-        }
-    }    
-
-
-    if (new_fillspans) {
-	switch (pGC->fillStyle) {
-	case FillSolid:
-	    switch (devPriv->rop) {
-	    case GXcopy:
-		pGC->ops->FillSpans = cfbSolidSpansCopy;
-		break;
-	    case GXxor:
-		pGC->ops->FillSpans = cfbSolidSpansXor;
-		break;
-	    default:
-		pGC->ops->FillSpans = cfbSolidSpansGeneral;
-		break;
-	    }
-	    break;
-	case FillTiled:
-	    pGC->ops->FillSpans = cfbUnnaturalTileFS;
-	    break;
-	case FillStippled:
-	case FillOpaqueStippled:
-	    pGC->ops->FillSpans = cfbUnnaturalStippleFS;
-	    break;
-	default:
-	    FatalError("cfbValidateGC: illegal fillStyle\n");
-	}
-    } /* end of new_fillspans */
-
-    if (new_fillarea) {
-#ifndef FOUR_BIT_CODE
-	pGC->ops->PolyFillRect = miPolyFillRect;
-	if (pGC->fillStyle == FillSolid || pGC->fillStyle == FillTiled)
-	{
-	    pGC->ops->PolyFillRect = cfbPolyFillRect;
-	}
-#endif
-#ifdef FOUR_BIT_CODE
-	pGC->ops->PushPixels = mfbPushPixels;
-	if (pGC->fillStyle == FillSolid && devPriv->rop == GXcopy)
-	    pGC->ops->PushPixels = cfbPushPixels8;
-#endif
-	pGC->ops->PolyFillArc = miPolyFillArc;
-	if (pGC->fillStyle == FillSolid)
-	{
-	    switch (devPriv->rop)
-	    {
-	    case GXcopy:
-		pGC->ops->PolyFillArc = cfbPolyFillArcSolidCopy;
-		break;
-	    default:
-		pGC->ops->PolyFillArc = cfbPolyFillArcSolidGeneral;
-		break;
-	    }
-	}
-    }
-}
diff --git a/hw/xfree86/xf8_32bpp/cfbimage.c b/hw/xfree86/xf8_32bpp/cfbimage.c
deleted file mode 100644
index 01a5a5e..0000000
--- a/hw/xfree86/xf8_32bpp/cfbimage.c
+++ /dev/null
@@ -1,174 +0,0 @@
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <stdlib.h>
-#include <string.h>
-
-#include <X11/X.h>
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-#include "gcstruct.h"
-#define PSZ 8
-#include "cfb.h"
-#undef PSZ
-#include "cfb32.h"
-#include "cfb8_32.h"
-#include "servermd.h"
-#include "mi.h"
-
-
-void
-cfb8_32GetImage (
-    DrawablePtr pDraw,
-    int sx, int sy, int w, int h,
-    unsigned int format,
-    unsigned long planemask,
-    char *pdstLine
-){
-    if(!w || !h) return;
-
-    if (!cfbDrawableEnabled (pDraw))
-	    return;
-
-    if(pDraw->depth == 24){
-	cfb32GetImage(pDraw, sx, sy, w, h, format, planemask, pdstLine);
-	return;
-    }
-    
-    if((pDraw->bitsPerPixel == 8) || (pDraw->bitsPerPixel == 1)){
-	cfbGetImage(pDraw, sx, sy, w, h, format, planemask, pdstLine);
-	return;
-    }
-
-    /* source is depth 8, 32 bpp */
-    if(format != ZPixmap) {
-	miGetImage(pDraw, sx, sy, w, h, format, planemask, pdstLine);
-	return;
-    } else {
-	BoxRec box;
-	DDXPointRec ptSrc;
-	RegionRec rgnDst;
-	ScreenPtr pScreen;
-	PixmapPtr pPixmap;
-
-	pScreen = pDraw->pScreen;
-        pPixmap = GetScratchPixmapHeader(pScreen, w, h, 8, 8,
-                        PixmapBytePad(w,8), (pointer)pdstLine);
-        if (!pPixmap)
-            return;
-        if ((planemask & 0xff) != 0xff)
-            memset((char *)pdstLine, 0, pPixmap->devKind * h);
-        ptSrc.x = sx + pDraw->x;
-        ptSrc.y = sy + pDraw->y;
-        box.x1 = 0;
-        box.y1 = 0;
-        box.x2 = w;
-        box.y2 = h;
-        REGION_INIT(pScreen, &rgnDst, &box, 1);
-        cfbDoBitblt32To8(pDraw, (DrawablePtr)pPixmap, GXcopy, &rgnDst,
-                    &ptSrc, planemask);
-        REGION_UNINIT(pScreen, &rgnDst);
-        FreeScratchPixmapHeader(pPixmap);
-    }
-}
-
-void
-cfb8_32PutImage (
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    int depth, 
-    int x, int y, int w, int h,
-    int leftPad,
-    int format,
-    char *pImage
-){
-    if(!w || !h) return;
-
-    if((pDraw->bitsPerPixel == 8) || (format != XYPixmap)){
-	cfbPutImage(pDraw, pGC, depth, x, y, w, h, leftPad, format, pImage);
-	return;
-    } else {  /* moving an 8bpp XYPixmap to a 32bpp screen */
-        unsigned long   oldFg, oldBg;
-        XID             gcv[3];
-        unsigned long   oldPlanemask;
-        unsigned long   i;
-        long            bytesPer;
-
-        oldPlanemask = pGC->planemask;
-        oldFg = pGC->fgPixel;
-        oldBg = pGC->bgPixel;
-        gcv[0] = ~0L;
-        gcv[1] = 0;
-        DoChangeGC(pGC, GCForeground | GCBackground, gcv, 0);
-        bytesPer = (long)h * BitmapBytePad(w + leftPad);
-
-        for (i = 0x80000000; i & 0xff000000; i >>= 1, pImage += bytesPer)
-        {
-            if (i & oldPlanemask)
-            {
-                gcv[0] = i;
-                DoChangeGC(pGC, GCPlaneMask, gcv, 0);
-                ValidateGC(pDraw, pGC);
-                (*pGC->ops->PutImage)(pDraw, pGC, 1, x, y, w, h, leftPad,
-                                 XYBitmap, pImage);
-            }
-        }
-        gcv[0] = oldPlanemask;
-        gcv[1] = oldFg;
-        gcv[2] = oldBg;
-        DoChangeGC(pGC, GCPlaneMask | GCForeground | GCBackground, gcv, 0);
-        ValidateGC(pDraw, pGC);
-    }
-}
-
-
-
-
-void
-cfb8_32GetSpans(
-   DrawablePtr pDraw,
-   int wMax,
-   DDXPointPtr ppt,
-   int *pwidth,
-   int nspans,
-   char *pDst
-){
-   int pitch, i;
-   CARD8 *ptr, *ptrBase;
-
-   if (!cfbDrawableEnabled (pDraw))
-        return;
-
-   if(pDraw->bitsPerPixel == 1) {
-	mfbGetSpans(pDraw, wMax, ppt, pwidth, nspans, pDst);
-	return;
-   }
-
-   if(pDraw->depth == 24) {
-	cfb32GetSpans(pDraw, wMax, ppt, pwidth, nspans, pDst);
-	return;
-   } else if(pDraw->bitsPerPixel == 8) {
-	cfbGetSpans(pDraw, wMax, ppt, pwidth, nspans, pDst);
-	return;
-   }
-
-   /* gotta get spans from a depth 8 window */
-   cfbGetByteWidthAndPointer(pDraw, pitch, ptrBase);
-   ptrBase += 3;  /* point to top byte */
-
-   while(nspans--) {
-	ptr = ptrBase + (ppt->y * pitch) + (ppt->x << 2);
-	
-	for(i = *pwidth; i--; ptr += 4) 
-	   *(pDst++) = *ptr;
-	
-	pDst = (char*)((long)(pDst + 3) & ~3L);
-
-	ppt++; pwidth++;
-   }
-}
-
-
diff --git a/hw/xfree86/xf8_32bpp/cfbpntwin.c b/hw/xfree86/xf8_32bpp/cfbpntwin.c
deleted file mode 100644
index fbf597d..0000000
--- a/hw/xfree86/xf8_32bpp/cfbpntwin.c
+++ /dev/null
@@ -1,51 +0,0 @@
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <X11/X.h>
-
-#include "windowstr.h"
-#include "regionstr.h"
-#include "pixmapstr.h"
-#include "scrnintstr.h"
-
-#define PSZ 8
-#include "cfb.h"
-#undef PSZ
-#include "cfb32.h"
-#include "cfb8_32.h"
-#include "mi.h"
-
-#ifdef PANORAMIX
-#include "panoramiX.h"
-#include "panoramiXsrv.h"
-#endif
-
-void
-cfb8_32FillBoxSolid8(
-   DrawablePtr pDraw,
-   int nbox,
-   BoxPtr pbox,
-   unsigned long color
-){
-    CARD8 *ptr, *data;
-    int pitch, height, width, i;
-    CARD8 c = (CARD8)color;
-
-    cfbGetByteWidthAndPointer(pDraw, pitch, ptr);
-    ptr += 3; /* point to the top byte */
-
-    while(nbox--) {
-	data = ptr + (pbox->y1 * pitch) + (pbox->x1 << 2);
-	width = (pbox->x2 - pbox->x1) << 2;
-	height = pbox->y2 - pbox->y1;
-
-	while(height--) {
-            for(i = 0; i < width; i+=4)
-		data[i] = c;
-            data += pitch;
-	}
-	pbox++;
-    }
-}
diff --git a/hw/xfree86/xf8_32bpp/cfbscrinit.c b/hw/xfree86/xf8_32bpp/cfbscrinit.c
deleted file mode 100644
index c3432b8..0000000
--- a/hw/xfree86/xf8_32bpp/cfbscrinit.c
+++ /dev/null
@@ -1,311 +0,0 @@
-
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "misc.h"
-#include "servermd.h"
-#include "scrnintstr.h"
-#include "pixmapstr.h"
-#include "resource.h"
-#include "colormap.h"
-#include "colormapst.h"
-#define PSZ 8
-#include "cfb.h"
-#undef PSZ
-#include "cfb32.h"
-#include "cfb8_32.h"
-#include "mi.h"
-#include "micmap.h"
-#include "mistruct.h"
-#include "dix.h"
-#include "mibstore.h"
-#include "mioverlay.h"
-#include "xf86.h"
-#include "xf86str.h"
-#include "globals.h"
-
-/* CAUTION:  We require that cfb8 and cfb32 were NOT 
-	compiled with CFB_NEED_SCREEN_PRIVATE */
-
-static DevPrivateKey cfb8_32GCPrivateKey = &cfb8_32GCPrivateKey;
-DevPrivateKey cfb8_32GetGCPrivateKey(void)
-{
-    return cfb8_32GCPrivateKey;
-}
-
-static DevPrivateKey cfb8_32ScreenPrivateKey = &cfb8_32ScreenPrivateKey;
-DevPrivateKey cfb8_32GetScreenPrivateKey(void)
-{
-    return cfb8_32ScreenPrivateKey;
-}
-
-static Bool
-cfb8_32AllocatePrivates(ScreenPtr pScreen)
-{
-   cfb8_32ScreenPtr pScreenPriv;
-
-   if (!(pScreenPriv = xalloc(sizeof(cfb8_32ScreenRec))))
-        return FALSE;
-
-   dixSetPrivate(&pScreen->devPrivates, cfb8_32ScreenPrivateKey, pScreenPriv);
-   
-   
-   /* All cfb will have the same GC and Window private indicies */
-   if(!mfbAllocatePrivates(pScreen, &cfbGCPrivateKey))
-	return FALSE;
-
-   if(!dixRequestPrivate(cfbGCPrivateKey, sizeof(cfbPrivGC)))
-        return FALSE;
-
-   if(!dixRequestPrivate(cfb8_32GCPrivateKey, sizeof(cfb8_32GCRec)))
-        return FALSE;
-
-   return TRUE;
-}
-
-static void DestroyColormapNoop(
-        ColormapPtr pColormap)
-{
-    /* NOOP */
-}
-
-static void StoreColorsNoop(
-        ColormapPtr pColormap,
-        int ndef,
-        xColorItem * pdef)
-{
-    /* NOOP */
-}
-
-static Bool
-cfb8_32SetupScreen(
-    ScreenPtr pScreen,
-    pointer pbits,		/* pointer to screen bitmap */
-    int xsize, int ysize,	/* in pixels */
-    int dpix, int dpiy,		/* dots per inch */
-    int width			/* pixel width of frame buffer */
-){
-    if (!cfb8_32AllocatePrivates(pScreen))
-	return FALSE;
-    pScreen->defColormap = FakeClientID(0);
-    /* let CreateDefColormap do whatever it wants for pixels */ 
-    pScreen->blackPixel = pScreen->whitePixel = (Pixel) 0;
-    pScreen->QueryBestSize = mfbQueryBestSize;
-    /* SaveScreen */
-    pScreen->GetImage = cfb8_32GetImage;
-    pScreen->GetSpans = cfb8_32GetSpans;
-    pScreen->CreateWindow = cfb8_32CreateWindow;
-    pScreen->DestroyWindow = cfb8_32DestroyWindow;	
-    pScreen->PositionWindow = cfb8_32PositionWindow;
-    pScreen->ChangeWindowAttributes = cfb8_32ChangeWindowAttributes;
-    pScreen->RealizeWindow = cfb32MapWindow;			/* OK */
-    pScreen->UnrealizeWindow = cfb32UnmapWindow;		/* OK */
-    pScreen->CopyWindow = cfb8_32CopyWindow;
-    pScreen->CreatePixmap = cfb32CreatePixmap;			/* OK */
-    pScreen->DestroyPixmap = cfb32DestroyPixmap; 		/* OK */
-    pScreen->RealizeFont = mfbRealizeFont;
-    pScreen->UnrealizeFont = mfbUnrealizeFont;
-    pScreen->CreateGC = cfb8_32CreateGC;
-    pScreen->CreateColormap = miInitializeColormap;
-    pScreen->DestroyColormap = DestroyColormapNoop;
-    pScreen->InstallColormap = miInstallColormap;
-    pScreen->UninstallColormap = miUninstallColormap;
-    pScreen->ListInstalledColormaps = miListInstalledColormaps;
-    pScreen->StoreColors = StoreColorsNoop;
-    pScreen->ResolveColor = miResolveColor;
-    pScreen->BitmapToRegion = mfbPixmapToRegion;
-
-    mfbRegisterCopyPlaneProc (pScreen, cfb8_32CopyPlane);
-    return TRUE;
-}
-
-typedef struct {
-    pointer pbits; 
-    int width;   
-} miScreenInitParmsRec, *miScreenInitParmsPtr;
-
-static Bool
-cfb8_32CreateScreenResources(ScreenPtr pScreen)
-{
-    miScreenInitParmsPtr pScrInitParms;
-    int pitch;
-    Bool retval;
-
-    /* get the pitch before mi destroys it */
-    pScrInitParms = (miScreenInitParmsPtr)pScreen->devPrivate;
-    pitch = pScrInitParms->width << 2;
-
-    if((retval = miCreateScreenResources(pScreen))) {
-	/* fix the screen pixmap */
-	PixmapPtr pPix = (PixmapPtr)pScreen->devPrivate;
-	pPix->drawable.bitsPerPixel = 32;
-	pPix->drawable.depth = 8;
-	pPix->devKind = pitch;
-    }
-
-    return retval;
-}
-
-
-static Bool
-cfb8_32CloseScreen (int i, ScreenPtr pScreen)
-{
-    cfb8_32ScreenPtr pScreenPriv = CFB8_32_GET_SCREEN_PRIVATE(pScreen);
-    if(pScreenPriv->visualData)
-	xfree(pScreenPriv->visualData);
-
-    xfree((pointer) pScreenPriv);
-    dixSetPrivate(&pScreen->devPrivates, cfb8_32ScreenPrivateKey, NULL);
-
-    return(cfb32CloseScreen(i, pScreen));
-}
-
-static void
-cfb8_32TransFunc(
-    ScreenPtr pScreen,
-    int nbox,
-    BoxPtr pbox
-){
-    cfb8_32FillBoxSolid8(&(WindowTable[pScreen->myNum]->drawable), 
-			nbox, pbox, xf86Screens[pScreen->myNum]->colorKey);
-}
-
-static Bool
-cfb8_32InOverlayFunc(WindowPtr pWin)
-{
-   return (pWin->drawable.depth == 8);
-}
-
-static Bool
-cfb8_32FinishScreenInit(
-    ScreenPtr pScreen,
-    pointer pbits,		/* pointer to screen bitmap */
-    int xsize, int ysize,	/* in pixels */
-    int dpix, int dpiy,		/* dots per inch */
-    int width			/* pixel width of frame buffer */
-){
-    VisualPtr	visuals;
-    DepthPtr	depths;
-    int		nvisuals;
-    int		ndepths;
-    int		rootdepth;
-    VisualID	defaultVisual;
-
-    rootdepth = 0;
-    if (!miInitVisuals (&visuals, &depths, &nvisuals, &ndepths, &rootdepth,
-			 &defaultVisual,((unsigned long)1<<(32-1)), 8, -1))
-	return FALSE;
-    if (! miScreenInit(pScreen, pbits, xsize, ysize, dpix, dpiy, width,
-			rootdepth, ndepths, depths,
-			defaultVisual, nvisuals, visuals))
-	return FALSE;
-
-    pScreen->CreateScreenResources = cfb8_32CreateScreenResources;
-    pScreen->CloseScreen = cfb8_32CloseScreen;
-    pScreen->GetScreenPixmap = cfb32GetScreenPixmap; 	/* OK */
-    pScreen->SetScreenPixmap = cfb32SetScreenPixmap;	/* OK */
-
-    if (! miInitOverlay(pScreen, cfb8_32InOverlayFunc, cfb8_32TransFunc))
-	return FALSE;
-
-    return TRUE;
-}
-
-static void
-cfb8_32EnableDisableFBAccess (
-    int index,
-    Bool enable
-){
-    ScreenPtr pScreen = screenInfo.screens[index];
-    cfb8_32ScreenPtr pScreenPriv = CFB8_32_GET_SCREEN_PRIVATE(pScreen);
-    
-    miOverlaySetRootClip(pScreen, enable);
-
-    (*pScreenPriv->EnableDisableFBAccess) (index, enable);
-}
-
-static Atom overlayVisualsAtom;
-
-typedef struct {
-    CARD32 overlay_visual;
-    CARD32 transparent_type;
-    CARD32 value;
-    CARD32 layer;
-} overlayVisualRec;
-
-static void
-cfb8_32SetupVisuals (ScreenPtr pScreen)
-{
-    cfb8_32ScreenPtr pScreenPriv = CFB8_32_GET_SCREEN_PRIVATE(pScreen);
-    char atomString[] = {"SERVER_OVERLAY_VISUALS"};
-    overlayVisualRec *overlayVisuals;
-    VisualID *visuals = NULL;
-    int numVisuals = 0;
-    DepthPtr pDepth = pScreen->allowedDepths;
-    int numDepths = pScreen->numDepths;
-    int i;
-
-    /* find depth 8 visuals */
-    for(i = 0; i < numDepths; i++, pDepth++) {
-	if(pDepth->depth == 8) {
-	    numVisuals = pDepth->numVids;
-	    visuals = pDepth->vids;
-	    break;
-	}
-    }
-    
-    if(!numVisuals || !visuals) {
-	ErrorF("No overlay visuals found!\n");
-	return;
-    }
-
-    if(!(overlayVisuals = xalloc(numVisuals * sizeof(overlayVisualRec))))
-	return;
-
-    for(i = 0; i < numVisuals; i++) {
-	overlayVisuals[i].overlay_visual = visuals[i];
-	overlayVisuals[i].transparent_type = 1; /* transparent pixel */
-	overlayVisuals[i].value = pScreenPriv->key;
-	overlayVisuals[i].layer = 1;
-    }    
-
-    overlayVisualsAtom = MakeAtom(atomString, sizeof(atomString) - 1, TRUE);
-    xf86RegisterRootWindowProperty(pScreen->myNum, overlayVisualsAtom,
-			overlayVisualsAtom, 32, numVisuals * 4, overlayVisuals);
-    pScreenPriv->visualData = (pointer)overlayVisuals;
-}
-
-Bool
-cfb8_32ScreenInit(
-    ScreenPtr pScreen,
-    pointer pbits,		/* pointer to screen bitmap */
-    int xsize, int ysize,	/* in pixels */
-    int dpix, int dpiy,		/* dots per inch */
-    int w			/* pixel width of frame buffer */
-){
-    cfb8_32ScreenPtr pScreenPriv;
-    ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
-
-    if (!cfb8_32SetupScreen(pScreen, pbits, xsize, ysize, dpix, dpiy, w))
-	return FALSE;
-
-    pScreenPriv = CFB8_32_GET_SCREEN_PRIVATE(pScreen);
-    pScreenPriv->key = pScrn->colorKey;
-    pScreenPriv->visualData = NULL;
-
-
-    pScreenPriv->EnableDisableFBAccess = pScrn->EnableDisableFBAccess;
-    pScrn->EnableDisableFBAccess = cfb8_32EnableDisableFBAccess;
-
-
-    if(cfb8_32FinishScreenInit(pScreen, pbits, xsize, ysize, dpix, dpiy, w))
-    { 
-	cfb8_32SetupVisuals(pScreen); 
-	return TRUE;
-    }
-    return FALSE;
-}
diff --git a/hw/xfree86/xf8_32bpp/cfbwindow.c b/hw/xfree86/xf8_32bpp/cfbwindow.c
deleted file mode 100644
index 2e6057f..0000000
--- a/hw/xfree86/xf8_32bpp/cfbwindow.c
+++ /dev/null
@@ -1,116 +0,0 @@
-
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <stdlib.h>
-
-#include <X11/X.h>
-#include "scrnintstr.h"
-#include "windowstr.h"
-#define PSZ 8
-#include "cfb.h"
-#undef PSZ
-#include "cfb32.h"
-#include "cfb8_32.h"
-#include "mistruct.h"
-#include "regionstr.h"
-#include "cfbmskbits.h"
-#include "mioverlay.h"
-
-
-/* We don't bother with cfb's fastBackground/Border so we don't
-   need to use the Window privates */
-
-
-Bool
-cfb8_32CreateWindow(WindowPtr pWin)
-{
-    pWin->drawable.bitsPerPixel = 32;
-    return TRUE;
-}
-
-
-Bool
-cfb8_32DestroyWindow(WindowPtr pWin)
-{
-    return TRUE;
-}
-
-Bool
-cfb8_32PositionWindow(
-    WindowPtr pWin,
-    int x, int y
-){
-    return TRUE;
-}
-
-void 
-cfb8_32CopyWindow(pWin, ptOldOrg, prgnSrc)
-    WindowPtr pWin;
-    DDXPointRec ptOldOrg;
-    RegionPtr prgnSrc;
-{
-    ScreenPtr pScreen = pWin->drawable.pScreen;
-    DDXPointPtr ppt, pptSrc;
-    RegionRec rgnDst;
-    RegionPtr borderClip = &pWin->borderClip;
-    BoxPtr pbox;
-    int dx, dy, i, nbox;
-    WindowPtr pwinRoot;
-    Bool doUnderlay = miOverlayCopyUnderlay(pScreen);
-    Bool freeReg = FALSE;
-
-    pwinRoot = WindowTable[pScreen->myNum];
-
-    if(doUnderlay)
-	freeReg = miOverlayCollectUnderlayRegions(pWin, &borderClip);
-
-    REGION_NULL(pScreen, &rgnDst);
-
-    dx = ptOldOrg.x - pWin->drawable.x;
-    dy = ptOldOrg.y - pWin->drawable.y;
-    REGION_TRANSLATE(pScreen, prgnSrc, -dx, -dy);
-    REGION_INTERSECT(pScreen, &rgnDst, borderClip, prgnSrc);
-
-    pbox = REGION_RECTS(&rgnDst);
-    nbox = REGION_NUM_RECTS(&rgnDst);
-    if(!nbox || 
-       !(pptSrc = (DDXPointPtr )xalloc(nbox * sizeof(DDXPointRec))))
-    {
-	REGION_UNINIT(pScreen, &rgnDst);
-	return;
-    }
-    ppt = pptSrc;
-
-    for (i = nbox; --i >= 0; ppt++, pbox++)
-    {
-	ppt->x = pbox->x1 + dx;
-	ppt->y = pbox->y1 + dy;
-    }
-
-    if(doUnderlay)
-	cfbDoBitblt24To24GXcopy((DrawablePtr)pwinRoot, (DrawablePtr)pwinRoot,
-			GXcopy, &rgnDst, pptSrc, ~0);
-    else
-	cfbDoBitblt8To8GXcopy((DrawablePtr)pwinRoot, (DrawablePtr)pwinRoot,
-			GXcopy, &rgnDst, pptSrc, ~0);
-
-    xfree(pptSrc);
-    REGION_UNINIT(pScreen, &rgnDst);
-    if(freeReg) 
-	REGION_DESTROY(pScreen, borderClip);
-}
-
-Bool
-cfb8_32ChangeWindowAttributes(
-    WindowPtr pWin,
-    unsigned long mask
-){
-    return TRUE;
-}
-
-
-
-
diff --git a/hw/xfree86/xf8_32bpp/xf86overlay.c b/hw/xfree86/xf8_32bpp/xf86overlay.c
deleted file mode 100644
index c63b3cf..0000000
--- a/hw/xfree86/xf8_32bpp/xf86overlay.c
+++ /dev/null
@@ -1,1179 +0,0 @@
-
-/*
-   Copyright (C) 1998.  The XFree86 Project Inc.
-
-   Written by Mark Vojkovich (mvojkovi at ucsd.edu)
-*/
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include "misc.h"
-#include "xf86.h"
-#include "xf86_OSproc.h"
-
-#include <X11/X.h>
-#include "scrnintstr.h"
-#include "regionstr.h"
-#include "windowstr.h"
-#include "xf86str.h"
-#include "migc.h"
-#include "gcstruct.h"
-#include "pixmapstr.h"
-#include "colormapst.h"
-#include "cfb8_32.h"
-
-#define IS_DIRTY 	1
-#define IS_SHARED	2
-
-/** Screen Functions **/
-
-static Bool OverlayCloseScreen (int, ScreenPtr);
-static Bool OverlayCreateGC(GCPtr pGC);
-static Bool OverlayDestroyPixmap(PixmapPtr);
-static PixmapPtr OverlayCreatePixmap(ScreenPtr, int, int, int, unsigned);
-static Bool OverlayChangeWindowAttributes(WindowPtr, unsigned long);
-
-/** Funcs **/
-static void OverlayValidateGC(GCPtr, unsigned long, DrawablePtr);
-static void OverlayChangeGC(GCPtr, unsigned long);
-static void OverlayCopyGC(GCPtr, unsigned long, GCPtr);
-static void OverlayDestroyGC(GCPtr);
-static void OverlayChangeClip(GCPtr, int, pointer, int);
-static void OverlayDestroyClip(GCPtr);
-static void OverlayCopyClip(GCPtr, GCPtr);
-
-
-static PixmapPtr OverlayRefreshPixmap(PixmapPtr);
-
-static GCFuncs OverlayGCFuncs = {
-   OverlayValidateGC, OverlayChangeGC, 
-   OverlayCopyGC, OverlayDestroyGC,
-   OverlayChangeClip, OverlayDestroyClip, 
-   OverlayCopyClip
-};
-
-
-/** Pixmap Ops */
-static void	 PixmapFillSpans(DrawablePtr, GCPtr, int, DDXPointPtr, int *,
-				  int);
-static void	 PixmapSetSpans(DrawablePtr, GCPtr, char *, DDXPointPtr,
-				 int *, int, int);
-static void	 PixmapPutImage(DrawablePtr, GCPtr, int, int, int, int, int,
-				 int, int, char *);
-static void	 PixmapPushPixels(GCPtr, PixmapPtr, DrawablePtr, int, int,
-				   int, int);
-static RegionPtr PixmapCopyArea(DrawablePtr, DrawablePtr, GCPtr, int, int,
-				 int, int, int, int);
-static RegionPtr PixmapCopyPlane(DrawablePtr, DrawablePtr, GCPtr, int, int,
-				  int, int, int, int, unsigned long);
-static void	 PixmapPolyPoint(DrawablePtr, GCPtr, int, int, xPoint *);
-static void	 PixmapPolylines(DrawablePtr, GCPtr, int, int, DDXPointPtr);
-static void	 PixmapPolySegment(DrawablePtr, GCPtr, int, xSegment *);
-static void	 PixmapPolyRectangle(DrawablePtr, GCPtr, int, xRectangle *);
-static void	 PixmapPolyArc(DrawablePtr, GCPtr, int, xArc *);
-static void	 PixmapFillPolygon(DrawablePtr, GCPtr, int, int, int,
-				    DDXPointPtr);
-static void	 PixmapPolyFillRect(DrawablePtr, GCPtr, int, xRectangle *);
-static void	 PixmapPolyFillArc(DrawablePtr, GCPtr, int, xArc *);
-static int	 PixmapPolyText8(DrawablePtr, GCPtr, int, int, int, char *);
-static int	 PixmapPolyText16(DrawablePtr, GCPtr, int, int, int,
-				   unsigned short *);
-static void	 PixmapImageText8(DrawablePtr, GCPtr, int, int, int, char *);
-static void	 PixmapImageText16(DrawablePtr, GCPtr, int, int, int,
-				    unsigned short *);
-static void	 PixmapImageGlyphBlt(DrawablePtr, GCPtr, int, int,
-				      unsigned int, CharInfoPtr *, pointer);
-static void	 PixmapPolyGlyphBlt(DrawablePtr, GCPtr, int, int,
-				     unsigned int, CharInfoPtr *, pointer);
-
-static GCOps PixmapGCOps = {
-    PixmapFillSpans, PixmapSetSpans, 
-    PixmapPutImage, PixmapCopyArea, 
-    PixmapCopyPlane, PixmapPolyPoint, 
-    PixmapPolylines, PixmapPolySegment, 
-    PixmapPolyRectangle, PixmapPolyArc, 
-    PixmapFillPolygon, PixmapPolyFillRect, 
-    PixmapPolyFillArc, PixmapPolyText8, 
-    PixmapPolyText16, PixmapImageText8, 
-    PixmapImageText16, PixmapImageGlyphBlt, 
-    PixmapPolyGlyphBlt, PixmapPushPixels,
-    {NULL}		/* devPrivate */
-};
-
-
-/** Window Ops **/
-static void	 WindowFillSpans(DrawablePtr, GCPtr, int, DDXPointPtr, int *,
-				  int);
-static void	 WindowSetSpans(DrawablePtr, GCPtr, char *, DDXPointPtr,
-				 int *, int, int);
-static void	 WindowPutImage(DrawablePtr, GCPtr, int, int, int, int, int,
-				 int, int, char *);
-static void	 WindowPushPixels(GCPtr, PixmapPtr, DrawablePtr, int, int,
-				   int, int);
-static RegionPtr WindowCopyArea(DrawablePtr, DrawablePtr, GCPtr, int, int,
-				 int, int, int, int);
-static RegionPtr WindowCopyPlane(DrawablePtr, DrawablePtr, GCPtr, int, int,
-				  int, int, int, int, unsigned long);
-static void	 WindowPolyPoint(DrawablePtr, GCPtr, int, int, xPoint *);
-static void	 WindowPolylines(DrawablePtr, GCPtr, int, int, DDXPointPtr);
-static void	 WindowPolySegment(DrawablePtr, GCPtr, int, xSegment *);
-static void	 WindowPolyRectangle(DrawablePtr, GCPtr, int, xRectangle *);
-static void	 WindowPolyArc(DrawablePtr, GCPtr, int, xArc *);
-static void	 WindowFillPolygon(DrawablePtr, GCPtr, int, int, int,
-				    DDXPointPtr);
-static void	 WindowPolyFillRect(DrawablePtr, GCPtr, int, xRectangle *);
-static void	 WindowPolyFillArc(DrawablePtr, GCPtr, int, xArc *);
-static int	 WindowPolyText8(DrawablePtr, GCPtr, int, int, int, char *);
-static int	 WindowPolyText16(DrawablePtr, GCPtr, int, int, int,
-				   unsigned short *);
-static void	 WindowImageText8(DrawablePtr, GCPtr, int, int, int, char *);
-static void	 WindowImageText16(DrawablePtr, GCPtr, int, int, int,
-				    unsigned short *);
-static void	 WindowImageGlyphBlt(DrawablePtr, GCPtr, int, int,
-				      unsigned int, CharInfoPtr *, pointer);
-static void	 WindowPolyGlyphBlt(DrawablePtr, GCPtr, int, int,
-				     unsigned int, CharInfoPtr *, pointer);
-
-static GCOps WindowGCOps = {
-    WindowFillSpans, WindowSetSpans, 
-    WindowPutImage, WindowCopyArea, 
-    WindowCopyPlane, WindowPolyPoint, 
-    WindowPolylines, WindowPolySegment, 
-    WindowPolyRectangle, WindowPolyArc, 
-    WindowFillPolygon, WindowPolyFillRect, 
-    WindowPolyFillArc, WindowPolyText8, 
-    WindowPolyText16, WindowImageText8, 
-    WindowImageText16, WindowImageGlyphBlt, 
-    WindowPolyGlyphBlt, WindowPushPixels,
-    {NULL}		/* devPrivate */
-};
-
-/** privates **/
-
-typedef struct {
-   CloseScreenProcPtr		CloseScreen;
-   CreateGCProcPtr		CreateGC;
-   CreatePixmapProcPtr		CreatePixmap;
-   DestroyPixmapProcPtr		DestroyPixmap;
-   ChangeWindowAttributesProcPtr ChangeWindowAttributes;
-   int				LockPrivate;
-} OverlayScreenRec, *OverlayScreenPtr;
-
-typedef struct {
-   GCFuncs		*wrapFuncs;
-   GCOps		*wrapOps;
-   GCOps		*overlayOps;
-   unsigned long 	fg;
-   unsigned long 	bg;
-   unsigned long 	pm;
-   PixmapPtr		tile;
-} OverlayGCRec, *OverlayGCPtr;
-
-typedef struct {
-   PixmapPtr		pix32;
-   CARD32		dirty;
-} OverlayPixmapRec, *OverlayPixmapPtr;
-
-
-static DevPrivateKey OverlayScreenKey = &OverlayScreenKey;
-static DevPrivateKey OverlayGCKey = &OverlayGCKey;
-static DevPrivateKey OverlayPixmapKey = &OverlayPixmapKey;
-
-/** Macros **/
-
-#define TILE_EXISTS(pGC) (!(pGC)->tileIsPixel && (pGC)->tile.pixmap)
-
-#define OVERLAY_GET_PIXMAP_PRIVATE(pPix) ((OverlayPixmapPtr) \
-    dixLookupPrivate(&(pPix)->devPrivates, OverlayPixmapKey))
-
-#define OVERLAY_GET_SCREEN_PRIVATE(pScreen) ((OverlayScreenPtr) \
-    dixLookupPrivate(&(pScreen)->devPrivates, OverlayScreenKey))
-
-#define OVERLAY_GET_GC_PRIVATE(pGC) ((OverlayGCPtr) \
-    dixLookupPrivate(&(pGC)->devPrivates, OverlayGCKey))
-
-#define OVERLAY_GC_FUNC_PROLOGUE(pGC)\
-    OverlayGCPtr pGCPriv = OVERLAY_GET_GC_PRIVATE(pGC);\
-    (pGC)->funcs = pGCPriv->wrapFuncs;\
-    if(pGCPriv->overlayOps) \
-	(pGC)->ops = pGCPriv->wrapOps
-
-#define OVERLAY_GC_FUNC_EPILOGUE(pGC)\
-    pGCPriv->wrapFuncs = (pGC)->funcs;\
-    (pGC)->funcs = &OverlayGCFuncs;\
-    if(pGCPriv->overlayOps) { \
-	pGCPriv->wrapOps = (pGC)->ops;\
-	(pGC)->ops = pGCPriv->overlayOps;\
-    }
-
-#define WINDOW_GC_OP_PROLOGUE(pGC)\
-    OverlayScreenPtr pScreenPriv = OVERLAY_GET_SCREEN_PRIVATE((pGC)->pScreen);\
-    OverlayGCPtr pGCPriv = OVERLAY_GET_GC_PRIVATE(pGC);\
-    unsigned long oldfg = (pGC)->fgPixel;\
-    unsigned long oldbg = (pGC)->bgPixel;\
-    unsigned long oldpm = (pGC)->planemask;\
-    PixmapPtr oldtile = (pGC)->tile.pixmap;\
-    (pGC)->fgPixel = pGCPriv->fg;\
-    (pGC)->bgPixel = pGCPriv->bg;\
-    (pGC)->planemask = pGCPriv->pm;\
-    if(pGCPriv->tile) (pGC)->tile.pixmap = pGCPriv->tile;\
-    (pGC)->funcs = pGCPriv->wrapFuncs;\
-    (pGC)->ops = pGCPriv->wrapOps;\
-    pScreenPriv->LockPrivate++
-    
-
-#define WINDOW_GC_OP_EPILOGUE(pGC)\
-    pGCPriv->wrapOps = (pGC)->ops;\
-    pGCPriv->wrapFuncs = (pGC)->funcs;\
-    (pGC)->fgPixel = oldfg;\
-    (pGC)->bgPixel = oldbg;\
-    (pGC)->planemask = oldpm;\
-    (pGC)->tile.pixmap = oldtile;\
-    (pGC)->funcs = &OverlayGCFuncs;\
-    (pGC)->ops   = &WindowGCOps;\
-    pScreenPriv->LockPrivate--
-
-
-#define PIXMAP_GC_OP_PROLOGUE(pGC)\
-    OverlayGCPtr pGCPriv = OVERLAY_GET_GC_PRIVATE(pGC);\
-    OverlayPixmapPtr pPixPriv = OVERLAY_GET_PIXMAP_PRIVATE((PixmapPtr)pDraw);\
-    pGC->funcs = pGCPriv->wrapFuncs;\
-    pGC->ops = pGCPriv->wrapOps
-    
-#define PIXMAP_GC_OP_EPILOGUE(pGC)\
-    pGCPriv->wrapOps = pGC->ops;\
-    pGC->funcs = &OverlayGCFuncs;\
-    pGC->ops = &PixmapGCOps;\
-    pPixPriv->dirty |= IS_DIRTY
-    
-
-Bool
-xf86Overlay8Plus32Init (ScreenPtr pScreen)
-{
-    OverlayScreenPtr pScreenPriv;
-
-    if (!dixRequestPrivate(OverlayGCKey, sizeof(OverlayGCRec)))
-	return FALSE;
-
-    if (!dixRequestPrivate(OverlayPixmapKey, sizeof(OverlayPixmapRec)))
-	return FALSE;
-
-    if (!(pScreenPriv = xalloc(sizeof(OverlayScreenRec))))
-	return FALSE;
-
-    dixSetPrivate(&pScreen->devPrivates, OverlayScreenKey, pScreenPriv);
-
-    pScreenPriv->CreateGC = pScreen->CreateGC;
-    pScreenPriv->CloseScreen = pScreen->CloseScreen;
-    pScreenPriv->CreatePixmap = pScreen->CreatePixmap;
-    pScreenPriv->DestroyPixmap = pScreen->DestroyPixmap;
-    pScreenPriv->ChangeWindowAttributes = pScreen->ChangeWindowAttributes;
-
-    pScreen->CreateGC = OverlayCreateGC;
-    pScreen->CloseScreen = OverlayCloseScreen;
-    pScreen->CreatePixmap = OverlayCreatePixmap; 
-    pScreen->DestroyPixmap = OverlayDestroyPixmap; 
-    pScreen->ChangeWindowAttributes = OverlayChangeWindowAttributes; 
-
-    pScreenPriv->LockPrivate = 0; 
-
-    /* allocate the key in the default map */
-    if(pScreen->defColormap) {
-	ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
-	ColormapPtr pmap;
-	xColorItem color;
-
-	pmap = (ColormapPtr)LookupIDByType(pScreen->defColormap, RT_COLORMAP);
-
-	pmap->red[pScrn->colorKey].refcnt = AllocPrivate;
-	pmap->red[pScrn->colorKey].fShared = FALSE;
-	pmap->freeRed--;
-	
-	color.red = color.blue = color.green = 0;
-	color.pixel = pScrn->colorKey;
-	color.flags = DoRed | DoGreen | DoBlue;
-
-	StoreColors(pmap, 1, &color);
-    }
-
-    return TRUE;
-}
-
-
-/*********************** Screen Funcs ***********************/
-
-Bool
-OverlayCreateGC(GCPtr pGC)
-{
-    ScreenPtr    pScreen = pGC->pScreen;
-    OverlayGCPtr pGCPriv = OVERLAY_GET_GC_PRIVATE(pGC);
-    OverlayScreenPtr pScreenPriv = OVERLAY_GET_SCREEN_PRIVATE(pScreen);
-    Bool ret;
-
-    pScreen->CreateGC = pScreenPriv->CreateGC;
-
-    if((ret = (*pScreen->CreateGC)(pGC)) && (pGC->depth != 1)) {
-	pGCPriv->wrapFuncs = pGC->funcs;
-	pGC->funcs = &OverlayGCFuncs;
-	pGCPriv->wrapOps = NULL;
-	pGCPriv->overlayOps = NULL;
-	pGCPriv->tile = NULL;
-    }
-
-    pScreen->CreateGC = OverlayCreateGC;
-
-    return ret;
-}
-
-static PixmapPtr 
-OverlayCreatePixmap(ScreenPtr pScreen, int w, int h, int depth,
-		    unsigned usage_hint)
-{
-    OverlayScreenPtr pScreenPriv = OVERLAY_GET_SCREEN_PRIVATE(pScreen);
-    PixmapPtr pPix;
-    
-    pScreen->CreatePixmap = pScreenPriv->CreatePixmap;
-    pPix = (*pScreen->CreatePixmap) (pScreen, w, h, depth, usage_hint);
-    pScreen->CreatePixmap = OverlayCreatePixmap;
-
-    /* We initialize all the privates */
-    if(pPix) {
-	OverlayPixmapPtr pPriv = OVERLAY_GET_PIXMAP_PRIVATE(pPix);
-        pPriv->pix32 = NULL;
-        pPriv->dirty = IS_DIRTY;
-	if(!w || !h)
-	   pPriv->dirty |= IS_SHARED;
-    }
-
-    return pPix;
-}
-
-static Bool
-OverlayDestroyPixmap(PixmapPtr pPix)
-{
-    ScreenPtr pScreen = pPix->drawable.pScreen;
-    OverlayScreenPtr pScreenPriv = OVERLAY_GET_SCREEN_PRIVATE(pScreen);
-    Bool result;
-
-    pScreen->DestroyPixmap = pScreenPriv->DestroyPixmap;
-
-    if((pPix->refcnt == 1) && (pPix->drawable.bitsPerPixel == 8)) {
-	OverlayPixmapPtr pPriv = OVERLAY_GET_PIXMAP_PRIVATE(pPix);
-	if(pPriv->pix32) {
-	   if(pPriv->pix32->refcnt != 1)
-	     ErrorF("Warning! private pix refcnt = %i\n", pPriv->pix32->refcnt);
-	   (*pScreen->DestroyPixmap)(pPriv->pix32);
-	}
-	pPriv->pix32 = NULL;
-    }
-
-    result = (*pScreen->DestroyPixmap) (pPix);
-    pScreen->DestroyPixmap = OverlayDestroyPixmap;
-
-    return result;
-}
-
-static Bool
-OverlayCloseScreen (int i, ScreenPtr pScreen)
-{
-    OverlayScreenPtr pScreenPriv = OVERLAY_GET_SCREEN_PRIVATE(pScreen);
-
-    pScreen->CreateGC = pScreenPriv->CreateGC;
-    pScreen->CloseScreen = pScreenPriv->CloseScreen;
-    pScreen->CreatePixmap = pScreenPriv->CreatePixmap;
-    pScreen->DestroyPixmap = pScreenPriv->DestroyPixmap;
-    pScreen->ChangeWindowAttributes = pScreenPriv->ChangeWindowAttributes;
-
-    xfree ((pointer) pScreenPriv);
-
-    return (*pScreen->CloseScreen) (i, pScreen);
-}
-
-
-
-static Bool
-OverlayChangeWindowAttributes (WindowPtr pWin, unsigned long mask)
-{
-    ScreenPtr pScreen = pWin->drawable.pScreen;
-    OverlayScreenPtr pScreenPriv = OVERLAY_GET_SCREEN_PRIVATE(pScreen);
-    Bool result;    
-
-    if(pWin->drawable.depth == 8) {
-	if((mask & CWBackPixmap) && 
-	   (pWin->backgroundState == BackgroundPixmap)) 	
-		OverlayRefreshPixmap(pWin->background.pixmap);
-
-	if((mask & CWBorderPixmap) && !pWin->borderIsPixel)
-		OverlayRefreshPixmap(pWin->border.pixmap);
-    }
-
-    pScreen->ChangeWindowAttributes = pScreenPriv->ChangeWindowAttributes;
-    result = (*pScreen->ChangeWindowAttributes) (pWin, mask);
-    pScreen->ChangeWindowAttributes = OverlayChangeWindowAttributes;
-
-    return result;
-}
-
-/*********************** GC Funcs *****************************/
-
-
-static PixmapPtr
-OverlayRefreshPixmap(PixmapPtr pix8) 
-{
-    OverlayPixmapPtr pixPriv = OVERLAY_GET_PIXMAP_PRIVATE(pix8);
-    ScreenPtr pScreen = pix8->drawable.pScreen;
-
-    if(!pixPriv->pix32) {
-	PixmapPtr newPix;
-
-	newPix = (*pScreen->CreatePixmap)(pScreen, pix8->drawable.width,
-		pix8->drawable.height, 24, 0);
-	newPix->drawable.depth = 8;  /* Bad Mark! Bad Mark! */
-        pixPriv->pix32 = newPix;
-    }
-
-    if(pixPriv->dirty) {
-	OverlayScreenPtr pScreenPriv = OVERLAY_GET_SCREEN_PRIVATE(pScreen);
-	GCPtr pGC;
-
-	pGC = GetScratchGC(8, pScreen);
-
-	pScreenPriv->LockPrivate++;  /* don't modify this one */
-	ValidateGC((DrawablePtr)pixPriv->pix32, pGC);
-
-	(*pGC->ops->CopyArea)((DrawablePtr)pix8, (DrawablePtr)pixPriv->pix32,
-		pGC, 0, 0, pix8->drawable.width, pix8->drawable.height, 0, 0);  
-	pScreenPriv->LockPrivate--;
-	FreeScratchGC(pGC);
-
-	pixPriv->dirty &= ~IS_DIRTY;
-	pixPriv->pix32->drawable.serialNumber = NEXT_SERIAL_NUMBER;    
-    }
-
-    return pixPriv->pix32;
-}
-
-
-static void
-OverlayValidateGC(
-   GCPtr         pGC,
-   unsigned long changes,
-   DrawablePtr   pDraw 
-){
-    OverlayScreenPtr pScreenPriv = OVERLAY_GET_SCREEN_PRIVATE(pGC->pScreen);
-    OVERLAY_GC_FUNC_PROLOGUE (pGC);
-
-    if(pScreenPriv->LockPrivate < 0) {
-	ErrorF("Something is wrong in OverlayValidateGC!\n");
-	pScreenPriv->LockPrivate = 0;
-    }
-
-    if(pGC->depth == 24) {
-	unsigned long oldpm = pGC->planemask;
-	pGCPriv->overlayOps = NULL;
-
-	if(pDraw->type == DRAWABLE_WINDOW)
-	   pGC->planemask &= 0x00ffffff;
-	else
-	   pGC->planemask |= 0xff000000; 
-
-        if(oldpm != pGC->planemask) changes |= GCPlaneMask;
-
-	(*pGC->funcs->ValidateGC)(pGC, changes, pDraw);
-
-    } else { /* depth == 8 */
-	unsigned long newChanges = 0;
-
-	if(pDraw->bitsPerPixel == 32) {
-	
-	    if(pGC->fillStyle == FillTiled)
-		pGCPriv->tile = OverlayRefreshPixmap(pGC->tile.pixmap);
-	    else pGCPriv->tile = NULL;
-
-	    if(pGCPriv->overlayOps != &WindowGCOps) {
-		newChanges = GCForeground | GCBackground | GCPlaneMask;
-		if(pGCPriv->tile) 
-		    newChanges |= GCTile;
-	    }
-	    pGCPriv->overlayOps = &WindowGCOps;
-
-	    if(!pScreenPriv->LockPrivate) {
-		unsigned long oldfg = pGC->fgPixel;
-		unsigned long oldbg = pGC->bgPixel;
-		unsigned long oldpm = pGC->planemask;
-		PixmapPtr oldtile = pGC->tile.pixmap;
-
-		pGC->fgPixel = pGCPriv->fg = oldfg << 24;
-		pGC->bgPixel = pGCPriv->bg = oldbg << 24;
-		pGC->planemask = pGCPriv->pm = oldpm << 24;
-		if(pGCPriv->tile)
-		    pGC->tile.pixmap = pGCPriv->tile;
-
-		(*pGC->funcs->ValidateGC)(pGC, changes | newChanges, pDraw);
-
-		pGC->fgPixel = oldfg;
-		pGC->bgPixel = oldbg;
-		pGC->planemask = oldpm;
-		pGC->tile.pixmap = oldtile;
-	    } else {
-		pGCPriv->fg = pGC->fgPixel;
-		pGCPriv->bg = pGC->bgPixel;
-		pGCPriv->pm = pGC->planemask;
-
-		(*pGC->funcs->ValidateGC)(pGC, changes | newChanges, pDraw);
-	    }
-
-	} else {  /* bitsPerPixel == 8 */
-	    if(pGCPriv->overlayOps == &WindowGCOps) {
-		newChanges = GCForeground | GCBackground | GCPlaneMask;
-		if(pGCPriv->tile) 
-		    newChanges |= GCTile;
-	    }
-	    pGCPriv->overlayOps = &PixmapGCOps;
-
-	    (*pGC->funcs->ValidateGC)(pGC, changes | newChanges, pDraw);
-	}
-    }
-
-    OVERLAY_GC_FUNC_EPILOGUE (pGC);
-}
-
-
-static void
-OverlayDestroyGC(GCPtr pGC)
-{
-    OVERLAY_GC_FUNC_PROLOGUE (pGC);
-    (*pGC->funcs->DestroyGC)(pGC);
-    OVERLAY_GC_FUNC_EPILOGUE (pGC);
-}
-
-static void
-OverlayChangeGC (
-    GCPtr	    pGC,
-    unsigned long   mask
-){
-    OVERLAY_GC_FUNC_PROLOGUE (pGC);
-    (*pGC->funcs->ChangeGC) (pGC, mask);
-    OVERLAY_GC_FUNC_EPILOGUE (pGC);
-}
-
-static void
-OverlayCopyGC (
-    GCPtr	    pGCSrc, 
-    unsigned long   mask,
-    GCPtr	    pGCDst
-){
-    OVERLAY_GC_FUNC_PROLOGUE (pGCDst);
-    (*pGCDst->funcs->CopyGC) (pGCSrc, mask, pGCDst);
-    OVERLAY_GC_FUNC_EPILOGUE (pGCDst);
-}
-static void
-OverlayChangeClip (
-    GCPtr   pGC,
-    int		type,
-    pointer	pvalue,
-    int		nrects
-){
-    OVERLAY_GC_FUNC_PROLOGUE (pGC);
-    (*pGC->funcs->ChangeClip) (pGC, type, pvalue, nrects);
-    OVERLAY_GC_FUNC_EPILOGUE (pGC);
-}
-
-static void
-OverlayCopyClip(GCPtr pgcDst, GCPtr pgcSrc)
-{
-    OVERLAY_GC_FUNC_PROLOGUE (pgcDst);
-    (* pgcDst->funcs->CopyClip)(pgcDst, pgcSrc);
-    OVERLAY_GC_FUNC_EPILOGUE (pgcDst);
-}
-
-static void
-OverlayDestroyClip(GCPtr pGC)
-{
-    OVERLAY_GC_FUNC_PROLOGUE (pGC);
-    (* pGC->funcs->DestroyClip)(pGC);
-    OVERLAY_GC_FUNC_EPILOGUE (pGC);
-}
-
-
-
-/******************* Window GC ops ***********************/
-
-static void
-WindowFillSpans(
-    DrawablePtr pDraw,
-    GC		*pGC,
-    int		nInit,	
-    DDXPointPtr pptInit,	
-    int *pwidthInit,		
-    int fSorted 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->FillSpans)(pDraw, pGC, nInit, pptInit, pwidthInit, fSorted);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-WindowSetSpans(
-    DrawablePtr		pDraw,
-    GCPtr		pGC,
-    char		*pcharsrc,
-    register DDXPointPtr ppt,
-    int			*pwidth,
-    int			nspans,
-    int			fSorted 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->SetSpans)(pDraw, pGC, pcharsrc, ppt, pwidth, nspans, fSorted);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-WindowPutImage(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		depth, 
-    int x, int y, int w, int h,
-    int		leftPad,
-    int		format,
-    char 	*pImage 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PutImage)(pDraw, pGC, depth, x, y, w, h, 
-						leftPad, format, pImage);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static RegionPtr
-WindowCopyArea(
-    DrawablePtr pSrc,
-    DrawablePtr pDst,
-    GC *pGC,
-    int srcx, int srcy,
-    int width, int height,
-    int dstx, int dsty 
-){
-    RegionPtr ret;
-
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    ret = (*pGC->ops->CopyArea)(pSrc, pDst,
-            pGC, srcx, srcy, width, height, dstx, dsty);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-    return ret;
-}
-
-static RegionPtr
-WindowCopyPlane(
-    DrawablePtr	pSrc,
-    DrawablePtr	pDst,
-    GCPtr pGC,
-    int	srcx, int srcy,
-    int	width, int height,
-    int	dstx, int dsty,
-    unsigned long bitPlane 
-){
-    RegionPtr ret;
-
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    ret = (*pGC->ops->CopyPlane)(pSrc, pDst,
-	       pGC, srcx, srcy, width, height, dstx, dsty, bitPlane);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-    return ret;
-}
-
-static void
-WindowPolyPoint(
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    int mode,
-    int npt,
-    xPoint *pptInit
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolyPoint)(pDraw, pGC, mode, npt, pptInit);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-WindowPolylines(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		mode,		
-    int		npt,		
-    DDXPointPtr pptInit 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->Polylines)(pDraw, pGC, mode, npt, pptInit);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void 
-WindowPolySegment(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		nseg,
-    xSegment	*pSeg 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolySegment)(pDraw, pGC, nseg, pSeg);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-WindowPolyRectangle(
-    DrawablePtr  pDraw,
-    GCPtr        pGC,
-    int	         nRectsInit,
-    xRectangle  *pRectsInit 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolyRectangle)(pDraw, pGC, nRectsInit, pRectsInit);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-WindowPolyArc(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		narcs,
-    xArc	*parcs 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolyArc)(pDraw, pGC, narcs, parcs);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-WindowFillPolygon(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		shape,
-    int		mode,
-    int		count,
-    DDXPointPtr	ptsIn 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->FillPolygon)(pDraw, pGC, shape, mode, count, ptsIn);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void 
-WindowPolyFillRect(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		nrectFill, 
-    xRectangle	*prectInit 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolyFillRect)(pDraw, pGC, nrectFill, prectInit);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-WindowPolyFillArc(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		narcs,
-    xArc	*parcs 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolyFillArc)(pDraw, pGC, narcs, parcs);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static int
-WindowPolyText8(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		x, 
-    int 	y,
-    int 	count,
-    char	*chars 
-){
-    int ret;
-
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    ret = (*pGC->ops->PolyText8)(pDraw, pGC, x, y, count, chars);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-    return ret;
-}
-
-static int
-WindowPolyText16(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		x,
-    int		y,
-    int 	count,
-    unsigned short *chars 
-){
-    int ret;
-
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    ret = (*pGC->ops->PolyText16)(pDraw, pGC, x, y, count, chars);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-    return ret;
-}
-
-static void
-WindowImageText8(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		x, 
-    int		y,
-    int 	count,
-    char	*chars 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->ImageText8)(pDraw, pGC, x, y, count, chars);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-WindowImageText16(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		x,
-    int		y,
-    int 	count,
-    unsigned short *chars 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->ImageText16)(pDraw, pGC, x, y, count, chars);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-WindowImageGlyphBlt(
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    int xInit, int yInit,
-    unsigned int nglyph,
-    CharInfoPtr *ppci,
-    pointer pglyphBase 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->ImageGlyphBlt)(pDraw, pGC, xInit, yInit, nglyph, 
-					ppci, pglyphBase);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-WindowPolyGlyphBlt(
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    int xInit, int yInit,
-    unsigned int nglyph,
-    CharInfoPtr *ppci,
-    pointer pglyphBase 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolyGlyphBlt)(pDraw, pGC, xInit, yInit, nglyph, 
-						ppci, pglyphBase);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-WindowPushPixels(
-    GCPtr	pGC,
-    PixmapPtr	pBitMap,
-    DrawablePtr pDraw,
-    int	dx, int dy, int xOrg, int yOrg 
-){
-    WINDOW_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PushPixels)(pGC, pBitMap, pDraw, dx, dy, xOrg, yOrg);
-    WINDOW_GC_OP_EPILOGUE(pGC);
-}
-
-
-/******************* Pixmap GC ops ***********************/
-
-static void
-PixmapFillSpans(
-    DrawablePtr pDraw,
-    GC		*pGC,
-    int		nInit,	
-    DDXPointPtr pptInit,	
-    int *pwidthInit,		
-    int fSorted 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->FillSpans)(pDraw, pGC, nInit, pptInit, pwidthInit, fSorted);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-PixmapSetSpans(
-    DrawablePtr		pDraw,
-    GCPtr		pGC,
-    char		*pcharsrc,
-    register DDXPointPtr ppt,
-    int			*pwidth,
-    int			nspans,
-    int			fSorted 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->SetSpans)(pDraw, pGC, pcharsrc, ppt, pwidth, nspans, fSorted);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-PixmapPutImage(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		depth, 
-    int x, int y, int w, int h,
-    int		leftPad,
-    int		format,
-    char 	*pImage 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PutImage)(pDraw, pGC, depth, x, y, w, h, 
-						leftPad, format, pImage);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static RegionPtr
-PixmapCopyArea(
-    DrawablePtr pSrc,
-    DrawablePtr pDraw,
-    GC *pGC,
-    int srcx, int srcy,
-    int width, int height,
-    int dstx, int dsty 
-){
-    RegionPtr ret;
-
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    ret = (*pGC->ops->CopyArea)(pSrc, pDraw,
-            pGC, srcx, srcy, width, height, dstx, dsty);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-    return ret;
-}
-
-static RegionPtr
-PixmapCopyPlane(
-    DrawablePtr	pSrc,
-    DrawablePtr	pDraw,
-    GCPtr pGC,
-    int	srcx, int srcy,
-    int	width, int height,
-    int	dstx, int dsty,
-    unsigned long bitPlane 
-){
-    RegionPtr ret;
-
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    ret = (*pGC->ops->CopyPlane)(pSrc, pDraw,
-	       pGC, srcx, srcy, width, height, dstx, dsty, bitPlane);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-    return ret;
-}
-
-static void
-PixmapPolyPoint(
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    int mode,
-    int npt,
-    xPoint *pptInit
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolyPoint)(pDraw, pGC, mode, npt, pptInit);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-PixmapPolylines(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		mode,		
-    int		npt,		
-    DDXPointPtr pptInit 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->Polylines)(pDraw, pGC, mode, npt, pptInit);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void 
-PixmapPolySegment(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		nseg,
-    xSegment	*pSeg 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolySegment)(pDraw, pGC, nseg, pSeg);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-PixmapPolyRectangle(
-    DrawablePtr  pDraw,
-    GCPtr        pGC,
-    int	         nRectsInit,
-    xRectangle  *pRectsInit 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolyRectangle)(pDraw, pGC, nRectsInit, pRectsInit);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-PixmapPolyArc(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		narcs,
-    xArc	*parcs 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolyArc)(pDraw, pGC, narcs, parcs);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-PixmapFillPolygon(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		shape,
-    int		mode,
-    int		count,
-    DDXPointPtr	ptsIn 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->FillPolygon)(pDraw, pGC, shape, mode, count, ptsIn);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void 
-PixmapPolyFillRect(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		nrectFill, 
-    xRectangle	*prectInit 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolyFillRect)(pDraw, pGC, nrectFill, prectInit);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-PixmapPolyFillArc(
-    DrawablePtr	pDraw,
-    GCPtr	pGC,
-    int		narcs,
-    xArc	*parcs 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolyFillArc)(pDraw, pGC, narcs, parcs);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static int
-PixmapPolyText8(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		x, 
-    int 	y,
-    int 	count,
-    char	*chars 
-){
-    int ret;
-
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    ret = (*pGC->ops->PolyText8)(pDraw, pGC, x, y, count, chars);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-    return ret;
-}
-
-static int
-PixmapPolyText16(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		x,
-    int		y,
-    int 	count,
-    unsigned short *chars 
-){
-    int ret;
-
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    ret = (*pGC->ops->PolyText16)(pDraw, pGC, x, y, count, chars);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-    return ret;
-}
-
-static void
-PixmapImageText8(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		x, 
-    int		y,
-    int 	count,
-    char	*chars 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->ImageText8)(pDraw, pGC, x, y, count, chars);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-PixmapImageText16(
-    DrawablePtr pDraw,
-    GCPtr	pGC,
-    int		x,
-    int		y,
-    int 	count,
-    unsigned short *chars 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->ImageText16)(pDraw, pGC, x, y, count, chars);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-PixmapImageGlyphBlt(
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    int xInit, int yInit,
-    unsigned int nglyph,
-    CharInfoPtr *ppci,
-    pointer pglyphBase 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->ImageGlyphBlt)(pDraw, pGC, xInit, yInit, nglyph, 
-					ppci, pglyphBase);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-PixmapPolyGlyphBlt(
-    DrawablePtr pDraw,
-    GCPtr pGC,
-    int xInit, int yInit,
-    unsigned int nglyph,
-    CharInfoPtr *ppci,
-    pointer pglyphBase 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PolyGlyphBlt)(pDraw, pGC, xInit, yInit, nglyph, 
-						ppci, pglyphBase);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-static void
-PixmapPushPixels(
-    GCPtr	pGC,
-    PixmapPtr	pBitMap,
-    DrawablePtr pDraw,
-    int	dx, int dy, int xOrg, int yOrg 
-){
-    PIXMAP_GC_OP_PROLOGUE(pGC);
-    (*pGC->ops->PushPixels)(pGC, pBitMap, pDraw, dx, dy, xOrg, yOrg);
-    PIXMAP_GC_OP_EPILOGUE(pGC);
-}
-
-
commit 059b4876e6350aa1110648788cdfbb3f45b4d66d
Author: Adam Jackson <ajax at redhat.com>
Date:   Fri Apr 11 09:46:48 2008 -0400

    Add doltcompile to .gitignore

diff --git a/.gitignore b/.gitignore
index 837b038..548e784 100644
--- a/.gitignore
+++ b/.gitignore
@@ -24,6 +24,7 @@ config.sub
 configure
 configure.lineno
 depcomp
+doltcompile
 install-sh
 libtool
 ltmain.sh
commit 6d22a9615a0e6ab3d00b0bcb22ff001b6ece02ae
Author: Peter Hutterer <peter at cs.unisa.edu.au>
Date:   Fri Feb 22 11:01:51 2008 +1030

    dix: Call DeleteInputDeviceRequest from CloseDownDevices (#14418)
    
    The DDX (xfree86 anyway) maintains its own device list in addition to the one
    in the DIX. CloseDevice will only remove it from the DIX, not the DDX. If the
    server then restarts (last client disconnects), the DDX devices are still
    there, will be re-initialised, then the hal devices come in and are added too.
    This repeats until we run out of device ids.
    
    This also requires us to strdup() the default pointer/keyboard in
    checkCoreInputDevices.
    
    X.Org Bug 14418 <http://bugs.freedesktop.org/show_bug.cgi?id=14418>

diff --git a/dix/devices.c b/dix/devices.c
index 4b20655..5a726af 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -618,12 +618,12 @@ CloseDownDevices(void)
     for (dev = inputInfo.devices; dev; dev = next)
     {
 	next = dev->next;
-	CloseDevice(dev);
+        DeleteInputDeviceRequest(dev);
     }
     for (dev = inputInfo.off_devices; dev; dev = next)
     {
 	next = dev->next;
-	CloseDevice(dev);
+        DeleteInputDeviceRequest(dev);
     }
     inputInfo.devices = NULL;
     inputInfo.off_devices = NULL;
diff --git a/hw/xfree86/common/xf86Config.c b/hw/xfree86/common/xf86Config.c
index 208e23d..3cc04f0 100644
--- a/hw/xfree86/common/xf86Config.c
+++ b/hw/xfree86/common/xf86Config.c
@@ -1338,8 +1338,8 @@ checkCoreInputDevices(serverLayoutPtr servlayoutp, Bool implicitLayout)
     /* 5. Built-in default. */
     if (!foundPointer) {
 	bzero(&defPtr, sizeof(defPtr));
-	defPtr.inp_identifier = "<default pointer>";
-	defPtr.inp_driver = "mouse";
+	defPtr.inp_identifier = strdup("<default pointer>");
+	defPtr.inp_driver = strdup("mouse");
 	confInput = &defPtr;
 	foundPointer = TRUE;
 	from = X_DEFAULT;
@@ -1385,8 +1385,8 @@ checkCoreInputDevices(serverLayoutPtr servlayoutp, Bool implicitLayout)
     if (!found) {
 	xf86Msg(X_INFO, "No default mouse found, adding one\n");
 	bzero(&defPtr, sizeof(defPtr));
-	defPtr.inp_identifier = "<default pointer>";
-	defPtr.inp_driver = "mouse";
+	defPtr.inp_identifier = strdup("<default pointer>");
+	defPtr.inp_driver = strdup("mouse");
 	confInput = &defPtr;
 	foundPointer = configInput(&Pointer, confInput, from);
         if (foundPointer) {
@@ -1474,8 +1474,8 @@ checkCoreInputDevices(serverLayoutPtr servlayoutp, Bool implicitLayout)
     /* 5. Built-in default. */
     if (!foundKeyboard) {
 	bzero(&defKbd, sizeof(defKbd));
-	defKbd.inp_identifier = "<default keyboard>";
-	defKbd.inp_driver = "kbd";
+	defKbd.inp_identifier = strdup("<default keyboard>");
+	defKbd.inp_driver = strdup("kbd");
 	confInput = &defKbd;
 	foundKeyboard = TRUE;
 	keyboardMsg = "default keyboard configuration";
diff --git a/hw/xfree86/common/xf86Xinput.c b/hw/xfree86/common/xf86Xinput.c
index eafc0e9..d34238e 100644
--- a/hw/xfree86/common/xf86Xinput.c
+++ b/hw/xfree86/common/xf86Xinput.c
@@ -446,11 +446,19 @@ void
 DeleteInputDeviceRequest(DeviceIntPtr pDev)
 {
     LocalDevicePtr pInfo = (LocalDevicePtr) pDev->public.devicePrivate;
-    InputDriverPtr drv = pInfo->drv;
-    IDevRec *idev = pInfo->conf_idev;
+    InputDriverPtr drv;
+    IDevRec *idev;
 
+    if (pInfo) /* need to get these before RemoveDevice */
+    {
+        drv = pInfo->drv;
+        idev = pInfo->conf_idev;
+    }
     RemoveDevice(pDev);
 
+    if (!pInfo) /* VCP and VCK */
+        return;
+
     if(drv->UnInit)
         drv->UnInit(drv, pInfo, 0);
     else
commit 3c337e18b933881e22b0d03312511f1d23a8640b
Author: Tilman Sauerbeck <tilman at code-monkey.de>
Date:   Thu Apr 10 21:36:19 2008 +0200

    Fixed configure.ac for autoconf 2.62.

diff --git a/configure.ac b/configure.ac
index b57dc1a..c0a1f23 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1556,7 +1556,11 @@ if test "x$XORG" = xyes -o "x$XGL" = xyes; then
 	abi_xinput=`extract_abi XINPUT`
 	abi_extension=`extract_abi EXTENSION`
 	abi_font=`extract_abi FONT`
-	AC_SUBST([abi_ansic abi_videodrv abi_xinput abi_extension abi_font])
+	AC_SUBST([abi_ansic])
+	AC_SUBST([abi_videodrv])
+	AC_SUBST([abi_xinput])
+	AC_SUBST([abi_extension])
+	AC_SUBST([abi_font])
 fi
 AM_CONDITIONAL([XORG], [test "x$XORG" = xyes])
 AM_CONDITIONAL([XORG_BUS_LINUXPCI], [test "x$xorg_bus_linuxpci" = xyes])
@@ -2096,7 +2100,9 @@ DIX_CFLAGS="-DHAVE_DIX_CONFIG_H $XSERVER_CFLAGS"
 
 AC_SUBST([DIX_CFLAGS])
 
-AC_SUBST([libdir exec_prefix prefix])
+AC_SUBST([libdir])
+AC_SUBST([exec_prefix])
+AC_SUBST([prefix])
 
 # Man page sections - used in config utils & generating man pages
 XORG_MANPAGE_SECTIONS
commit 13dcde6bf994fae09c67c3edce9de42df61ef043
Author: Eric Anholt <eric at anholt.net>
Date:   Thu Apr 10 11:08:49 2008 -0700

    Fix dolt to error out on compile error, and not print errors on race to mkdir.
    
    Both of these changes have been submitted upstream.

diff --git a/acinclude.m4 b/acinclude.m4
index 0d31e85..cbb68e1 100644
--- a/acinclude.m4
+++ b/acinclude.m4
@@ -65,7 +65,7 @@ dnl Write out shared compilation code.
         cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
 libobjdir="${obj%$objbase}.libs"
 if test ! -d "$libobjdir" ; then
-    mkdir "$libobjdir"
+    mkdir -p "$libobjdir"
     mkdir_ret=$?
     if test "$mkdir_ret" -ne 0 && test ! -d "$libobjdir" ; then
         exit $mkdir_ret
@@ -73,7 +73,7 @@ if test ! -d "$libobjdir" ; then
 fi
 pic_object="$libobjdir/$objbase.o"
 args@<:@$objarg@:>@="$pic_object"
-"${args@<:@@@:>@}" -fPIC -DPIC
+"${args@<:@@@:>@}" -fPIC -DPIC || exit $?
 __DOLTCOMPILE__EOF__
     fi
 
@@ -86,11 +86,11 @@ args@<:@$objarg@:>@="$non_pic_object"
 __DOLTCOMPILE__EOF__
         if test x$enable_shared = xyes; then
             cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
-"${args@<:@@@:>@}" >/dev/null 2>&1
+"${args@<:@@@:>@}" >/dev/null 2>&1 || exit $?
 __DOLTCOMPILE__EOF__
         else
             cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
-"${args@<:@@@:>@}"
+"${args@<:@@@:>@}" || exit $?
 __DOLTCOMPILE__EOF__
         fi
     fi
commit a7e3ad1c6b455bda7c4abb352a20845d1d4574a0
Author: Eric Anholt <eric at anholt.net>
Date:   Thu Apr 10 10:33:11 2008 -0700

    Remove NDEBUG (assert() disable) define from the X Server.
    
    A few pieces of code were abusing this define for other purposes, which are
    converted to #ifndef DEBUG instead.  There should be no ABI consequences
    to this change.
    
    The rationale is that having the define in xorg-server.h also disables
    assert() drivers, which is unexpected, and also difficult to avoid since
    xorg-server.h is included in their config.h, and you can't put a #undef in
    config.h.  As for removing it from the server instead of moving it to an
    internal header, we probably shouldn't have unnecessary assert()s in
    critical server paths anyway, and if we do we could #define NDEBUG in the
    specific cases needed.

diff --git a/configure.ac b/configure.ac
index eb6fcda..b57dc1a 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1099,8 +1099,6 @@ AC_DEFINE(NO_LIBCWRAPPER, 1, [Define to 1 if modules should avoid the libcwrappe
 
 if test "x$DEBUGGING" = xyes; then
        AC_DEFINE(DEBUG, 1, [Enable debugging code])
-else
-       AC_DEFINE(NDEBUG, 1, [Disable some debugging code])
 fi
 AM_CONDITIONAL(DEBUG, [test "x$DEBUGGING" = xyes])
 
diff --git a/hw/kdrive/ephyr/ephyr_draw.c b/hw/kdrive/ephyr/ephyr_draw.c
index 422b7c6..7b579c2 100644
--- a/hw/kdrive/ephyr/ephyr_draw.c
+++ b/hw/kdrive/ephyr/ephyr_draw.c
@@ -28,7 +28,6 @@
 #ifdef HAVE_CONFIG_H
 #include <kdrive-config.h>
 #endif
-#undef NDEBUG	/* No, really.  The whole point of this module is to crash. */
 
 #include "ephyr.h"
 #include "exa_priv.h"
diff --git a/hw/kdrive/ephyr/ephyrlog.h b/hw/kdrive/ephyr/ephyrlog.h
index 71f7977..a07a0a0 100644
--- a/hw/kdrive/ephyr/ephyrlog.h
+++ b/hw/kdrive/ephyr/ephyrlog.h
@@ -31,11 +31,11 @@
 #include <assert.h>
 #include "os.h"
 
-#ifdef NDEBUG
+#ifndef DEBUG
 /*we are not in debug mode*/
 #define EPHYR_LOG(...)
 #define EPHYR_LOG_ERROR(...)
-#endif /*NDEBUG*/
+#endif /*!DEBUG*/
 
 #define ERROR_LOG_LEVEL 3
 #define INFO_LOG_LEVEL 4
diff --git a/hw/kdrive/src/kinput.c b/hw/kdrive/src/kinput.c
index df73942..9e8fd50 100644
--- a/hw/kdrive/src/kinput.c
+++ b/hw/kdrive/src/kinput.c
@@ -1744,7 +1744,7 @@ KdClassifyInput (KdPointerInfo *pi, int type, int x, int y, int z, int b)
     return keyboard;
 }
 
-#ifndef NDEBUG
+#ifdef DEBUG
 char	*kdStateNames[] = {
     "start",
     "button_1_pend",
@@ -1777,7 +1777,7 @@ char *kdActionNames[] = {
     "gen_down_2",
     "gen_up_2",
 };
-#endif
+#endif /* DEBUG */
 
 static void
 KdQueueEvent (DeviceIntPtr pDev, xEvent *ev)
diff --git a/hw/xgl/egl/kinput.c b/hw/xgl/egl/kinput.c
index 774e00e..f892dc1 100644
--- a/hw/xgl/egl/kinput.c
+++ b/hw/xgl/egl/kinput.c
@@ -977,7 +977,7 @@ KdClassifyInput (KdMouseInfo *mi, xEvent *ev)
     return keyboard;
 }
 
-#ifndef NDEBUG
+#ifdef DEBUG
 char	*kdStateNames[] = {
     "start",
     "button_1_pend",
@@ -1010,7 +1010,7 @@ char *kdActionNames[] = {
     "gen_down_2",
     "gen_up_2",
 };
-#endif
+#endif /* DEBUG */
 
 static void
 KdQueueEvent (xEvent *ev)
diff --git a/hw/xquartz/darwinKeyboard.c b/hw/xquartz/darwinKeyboard.c
index 6f2758e..0a8c5c0 100644
--- a/hw/xquartz/darwinKeyboard.c
+++ b/hw/xquartz/darwinKeyboard.c
@@ -76,13 +76,7 @@
 #include "quartzKeyboard.h"
 #include "quartzAudio.h"
 
-#ifdef NDEBUG
-#undef NDEBUG
 #include <assert.h>
-#define NDEBUG 1
-#else
-#include <assert.h>
-#endif
 
 #define AltMask         Mod1Mask
 #define MetaMask        Mod2Mask
diff --git a/hw/xquartz/quartzStartup.c b/hw/xquartz/quartzStartup.c
index e25e155..5ac3017 100644
--- a/hw/xquartz/quartzStartup.c
+++ b/hw/xquartz/quartzStartup.c
@@ -41,13 +41,7 @@
 #include "opaque.h"
 #include "micmap.h"
 
-#ifdef NDEBUG
-#undef NDEBUG
 #include <assert.h>
-#define NDEBUG 1
-#else
-#include <assert.h>
-#endif
 
 char **envpGlobal;      // argcGlobal and argvGlobal
                         // are from dix/globals.c
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index 38639d6..a7c0c6a 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -264,9 +264,6 @@
 /* Support MIT-SHM Extension */
 #undef MITSHM
 
-/* Disable some debugging code */
-#undef NDEBUG
-
 /* Enable some debugging code */
 #undef DEBUG
 
diff --git a/include/xorg-server.h.in b/include/xorg-server.h.in
index 1d41b4c..72b4551 100644
--- a/include/xorg-server.h.in
+++ b/include/xorg-server.h.in
@@ -52,9 +52,6 @@
 /* Support MIT-SHM Extension */
 #undef MITSHM
 
-/* Disable some debugging code */
-#undef NDEBUG
-
 /* Need XFree86 helper functions */
 #undef NEED_XF86_PROTOTYPES
 
commit 7909ebe7f163716520f843fae11ac7bdeffcb57c
Author: Eric Anholt <eric at anholt.net>
Date:   Wed Apr 9 10:43:25 2008 -0700

    dolt: add FreeBSD support (this and ppc have been submitted upstream).

diff --git a/acinclude.m4 b/acinclude.m4
index c496afd..0d31e85 100644
--- a/acinclude.m4
+++ b/acinclude.m4
@@ -27,6 +27,7 @@ if test x$GCC != xyes; then
 fi
 case $host in
 i?86-*-linux*|x86_64-*-linux*|powerpc-*-linux*) ;;
+amd64-*-freebsd*|i386-*-freebsd*|ia64-*-freebsd*) ;;
 *) dolt_supported=no ;;
 esac
 if test x$dolt_supported = xno ; then
commit b4842d8dc3b1619033c5c123c8adc6e164098dc3
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Wed Apr 9 16:17:35 2008 +0200

    dolt works on powerpc Linux.

diff --git a/acinclude.m4 b/acinclude.m4
index 822adbe..c496afd 100644
--- a/acinclude.m4
+++ b/acinclude.m4
@@ -26,7 +26,7 @@ if test x$GCC != xyes; then
     dolt_supported=no
 fi
 case $host in
-i?86-*-linux*|x86_64-*-linux*) ;;
+i?86-*-linux*|x86_64-*-linux*|powerpc-*-linux*) ;;
 *) dolt_supported=no ;;
 esac
 if test x$dolt_supported = xno ; then
commit 0d1746995d91b55e40f233f0c38b56bafe896d38
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Wed Apr 9 13:37:59 2008 +0200

    Fix off-by-one error in ProcXResQueryClients().
    
    Fixes memory corruption reported at
    http://bugs.freedesktop.org/show_bug.cgi?id=14004 .

diff --git a/Xext/xres.c b/Xext/xres.c
index 9bd70c6..f444c4e 100644
--- a/Xext/xres.c
+++ b/Xext/xres.c
@@ -64,7 +64,7 @@ ProcXResQueryClients (ClientPtr client)
 
     REQUEST_SIZE_MATCH(xXResQueryClientsReq);
 
-    current_clients = xalloc((currentMaxClients - 1) * sizeof(int));
+    current_clients = xalloc(currentMaxClients * sizeof(int));
 
     num_clients = 0;
     for(i = 0; i < currentMaxClients; i++) {
commit 6d031cbdefd8072b61645955f01b470a3e6858c1
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Wed Apr 9 14:36:26 2008 +0300

    configure.ac: Do the dolt
    
    Use dolt instead of libtool whereever practical.  See:
    http://lists.debian.org/debian-devel/2008/04/msg00286.html

diff --git a/acinclude.m4 b/acinclude.m4
index f3d8734..822adbe 100644
--- a/acinclude.m4
+++ b/acinclude.m4
@@ -1,3 +1,144 @@
+dnl dolt, a replacement for libtool
+dnl Copyright © 2007-2008 Josh Triplett <josh at freedesktop.org>
+dnl Copying and distribution of this file, with or without modification,
+dnl are permitted in any medium without royalty provided the copyright
+dnl notice and this notice are preserved.
+dnl
+dnl To use dolt, invoke the DOLT macro immediately after the libtool macros.
+dnl Optionally, copy this file into acinclude.m4, to avoid the need to have it
+dnl installed when running autoconf on your project.
+dnl
+dnl git snapshot: 198a3026b347b9220a2f2e2ae23a3049c35af262
+
+AC_DEFUN([DOLT], [
+AC_REQUIRE([AC_CANONICAL_HOST])
+# dolt, a replacement for libtool
+# Josh Triplett <josh at freedesktop.org>
+AC_PATH_PROG(DOLT_BASH, bash)
+AC_MSG_CHECKING([if libtool sucks])
+AC_MSG_RESULT([yup, it does])
+AC_MSG_CHECKING([if dolt supports this host])
+dolt_supported=yes
+if test x$DOLT_BASH = x; then
+    dolt_supported=no
+fi
+if test x$GCC != xyes; then
+    dolt_supported=no
+fi
+case $host in
+i?86-*-linux*|x86_64-*-linux*) ;;
+*) dolt_supported=no ;;
+esac
+if test x$dolt_supported = xno ; then
+    AC_MSG_RESULT([no, falling back to libtool])
+else
+    AC_MSG_RESULT([yes, replacing libtool])
+
+dnl Start writing out doltcompile.
+    cat <<__DOLTCOMPILE__EOF__ >doltcompile
+#!$DOLT_BASH
+__DOLTCOMPILE__EOF__
+    cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
+args=("$[]@")
+for ((arg=0; arg<${#args@<:@@@:>@}; arg++)) ; do
+    if test x"${args@<:@$arg@:>@}" = x-o ; then
+        objarg=$((arg+1))
+        break
+    fi
+done
+if test x$objarg = x ; then
+    echo 'Error: no -o on compiler command line' 1>&2
+    exit 1
+fi
+lo="${args@<:@$objarg@:>@}"
+obj="${lo%.lo}"
+if test x"$lo" = x"$obj" ; then
+    echo "Error: libtool object file name \"$lo\" does not end in .lo" 1>&2
+    exit 1
+fi
+objbase="${obj##*/}"
+__DOLTCOMPILE__EOF__
+
+dnl Write out shared compilation code.
+    if test x$enable_shared = xyes; then
+        cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
+libobjdir="${obj%$objbase}.libs"
+if test ! -d "$libobjdir" ; then
+    mkdir "$libobjdir"
+    mkdir_ret=$?
+    if test "$mkdir_ret" -ne 0 && test ! -d "$libobjdir" ; then
+        exit $mkdir_ret
+    fi
+fi
+pic_object="$libobjdir/$objbase.o"
+args@<:@$objarg@:>@="$pic_object"
+"${args@<:@@@:>@}" -fPIC -DPIC
+__DOLTCOMPILE__EOF__
+    fi
+
+dnl Write out static compilation code.
+dnl Avoid duplicate compiler output if also building shared objects.
+    if test x$enable_static = xyes; then
+        cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
+non_pic_object="$obj.o"
+args@<:@$objarg@:>@="$non_pic_object"
+__DOLTCOMPILE__EOF__
+        if test x$enable_shared = xyes; then
+            cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
+"${args@<:@@@:>@}" >/dev/null 2>&1
+__DOLTCOMPILE__EOF__
+        else
+            cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
+"${args@<:@@@:>@}"
+__DOLTCOMPILE__EOF__
+        fi
+    fi
+
+dnl Write out the code to write the .lo file.
+dnl The second line of the .lo file must match "^# Generated by .*libtool"
+    cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
+{
+echo "# $lo - a libtool object file"
+echo "# Generated by doltcompile, not libtool"
+__DOLTCOMPILE__EOF__
+
+    if test x$enable_shared = xyes; then
+        cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
+echo "pic_object='$pic_object'"
+__DOLTCOMPILE__EOF__
+    else
+        cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
+echo pic_object=none
+__DOLTCOMPILE__EOF__
+    fi
+
+    if test x$enable_static = xyes; then
+        cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
+echo "non_pic_object='$non_pic_object'"
+__DOLTCOMPILE__EOF__
+    else
+        cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
+echo non_pic_object=none
+__DOLTCOMPILE__EOF__
+    fi
+
+    cat <<'__DOLTCOMPILE__EOF__' >>doltcompile
+} > "$lo"
+__DOLTCOMPILE__EOF__
+
+dnl Done writing out doltcompile; substitute it for libtool compilation.
+    chmod +x doltcompile
+    LTCOMPILE='$(top_builddir)/doltcompile $(COMPILE)'
+    AC_SUBST(LTCOMPILE)
+    LTCXXCOMPILE='$(top_builddir)/doltcompile $(CXXCOMPILE)'
+    AC_SUBST(LTCXXCOMPILE)
+fi
+# end dolt
+])
+
+
+
+
 ##### http://autoconf-archive.cryp.to/ac_define_dir.html
 #
 # SYNOPSIS
diff --git a/configure.ac b/configure.ac
index 94151de..eb6fcda 100644
--- a/configure.ac
+++ b/configure.ac
@@ -58,6 +58,7 @@ AC_PROG_LN_S
 AC_LIBTOOL_WIN32_DLL
 AC_DISABLE_STATIC
 AC_PROG_LIBTOOL
+DOLT
 AC_PROG_MAKE_SET
 PKG_PROG_PKG_CONFIG
 AC_PROG_LEX
commit b19027fbaea4c3a146926e862983e0e3411fff3d
Author: Dave Airlie <airlied at linux.ie>
Date:   Wed Apr 9 14:27:58 2008 +1000

    quirk: add quirk for ACR 640x350 default mode is wrong
    
    RH #440186

diff --git a/hw/xfree86/modes/xf86EdidModes.c b/hw/xfree86/modes/xf86EdidModes.c
index 8f7d45d..09d0039 100644
--- a/hw/xfree86/modes/xf86EdidModes.c
+++ b/hw/xfree86/modes/xf86EdidModes.c
@@ -93,6 +93,12 @@ static Bool quirk_prefer_large_60 (int scrnIndex, xf86MonPtr DDC)
 	DDC->vendor.prod_id == 638)
 	return TRUE;
 
+    /* Acer F51 */
+    if (memcmp (DDC->vendor.name, "API", 4) == 0 &&
+	DDC->vendor.prod_id == 0x7602)
+	return TRUE;
+
+
     return FALSE;
 }
 
commit 1f8188656a075dc7b1bb27a0795b5bd43610bbc8
Author: Ben Byer <bbyer at apple.com>
Date:   Tue Apr 8 20:37:25 2008 -0700

    add missing dix-config include
    (cherry picked from commit 126e9bc8c480b403dedc44c1e8c4fe1476340ed9)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 410acdd..78708d2 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -30,6 +30,10 @@ used in advertising or otherwise to promote the sale, use or other dealings
 in this Software without prior written authorization from The Open Group.
  */
 
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
 #define NEED_EVENTS
 #include   <X11/X.h>
 #include   <X11/Xmd.h>
commit 3f51f493b6daf2464e6c2ba5a924219b88a9e57e
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Tue Apr 8 17:02:56 2008 -0700

    XQuartz: Fix issue where clicking on an X11 window might send that event to an X11 window in another space.
    (cherry picked from commit df21312c8b0e9ef0c809bfc57cdf64f27db0d8a7)
    (cherry picked from commit 2d4194a8d124e7a9c7cd1b83635ba6957aa4ae1c)

diff --git a/configure.ac b/configure.ac
index c210963..94151de 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1732,7 +1732,8 @@ if test "X$XQUARTZ" = Xauto; then
 fi
 
 if test "x$XQUARTZ" = xyes; then
-	AC_DEFINE([XQUARTZ],[1],[Have Quartz])
+	AC_DEFINE(XQUARTZ,1,[Have Quartz])
+	AC_DEFINE(ROOTLESS,1,[Build Rootless code])
 
 #glxAGL / glxCGL don't work yet
 #	AC_CACHE_CHECK([for AGL framework],xorg_cv_AGL_framework,[
diff --git a/dix/events.c b/dix/events.c
index 4a8e480..aef333e 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -2171,6 +2171,13 @@ XYToWindow(int x, int y)
 				x - pWin->drawable.x,
 				y - pWin->drawable.y, &box))
 #endif
+#ifdef ROOTLESS
+    /* In rootless mode windows may be offscreen, even when
+     * they're in X's stack. (E.g. if the native window system
+     * implements some form of virtual desktop system).
+     */
+		&& !pWin->rootlessUnhittable
+#endif
 	    )
 	{
 	    if (spriteTraceGood >= spriteTraceSize)
diff --git a/dix/window.c b/dix/window.c
index 9975b5e..499f58e 100644
--- a/dix/window.c
+++ b/dix/window.c
@@ -292,6 +292,9 @@ SetWindowToDefaults(WindowPtr pWin)
     pWin->forcedBS = FALSE;
     pWin->redirectDraw = RedirectDrawNone;
     pWin->forcedBG = FALSE;
+#ifdef ROOTLESS
+    pWin->rootlessUnhittable = FALSE;
+#endif
 }
 
 static void
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 3afbaf8..410acdd 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -56,6 +56,10 @@ in this Software without prior written authorization from The Open Group.
 #include "applewmExt.h"
 #include <X11/extensions/applewm.h>
 
+/* FIXME: Abstract this away into xpr */
+#include <Xplugin.h>
+#include "rootlessWindow.h"
+WindowPtr xprGetXWindow(xp_window_id wid);
 
 /* Fake button press/release for scroll wheel move. */
 #define SCROLLWHEELUPFAKE   4
@@ -228,7 +232,7 @@ void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int neven
 
         case kXquartzWindowState:
             DEBUG_LOG("kXquartzWindowState\n");
-            RootlessNativeWindowStateChanged(xe[i].u.clientMessage.u.l.longs0,
+            RootlessNativeWindowStateChanged(xprGetXWindow(xe[i].u.clientMessage.u.l.longs0),
                                              xe[i].u.clientMessage.u.l.longs1);
             break;
 
diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index 96dc021..6a8cf7c 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -52,7 +52,6 @@
 #include "windowstr.h"
 #include "colormapst.h"
 #include "globals.h"
-#include "rootlessWindow.h"
 
 // System headers
 #include <sys/types.h>
diff --git a/include/windowstr.h b/include/windowstr.h
index e06a2f1..99bd640 100644
--- a/include/windowstr.h
+++ b/include/windowstr.h
@@ -160,6 +160,9 @@ typedef struct _Window {
     unsigned		forcedBS:1;	/* system-supplied backingStore */
     unsigned		redirectDraw:2;	/* COMPOSITE rendering redirect */
     unsigned		forcedBG:1;	/* must have an opaque background */
+#ifdef ROOTLESS
+    unsigned		rootlessUnhittable:1;	/* doesn't hit-test */
+#endif
 } WindowRec;
 
 /*
diff --git a/miext/rootless/rootlessWindow.c b/miext/rootless/rootlessWindow.c
index 0dad44a..17fe690 100644
--- a/miext/rootless/rootlessWindow.c
+++ b/miext/rootless/rootlessWindow.c
@@ -117,12 +117,10 @@ rootlessHasRoot (ScreenPtr pScreen)
 }
 
 void
-RootlessNativeWindowStateChanged (xp_window_id id, unsigned int state)
+RootlessNativeWindowStateChanged (WindowPtr pWin, unsigned int state)
 {
-  WindowPtr pWin;
   RootlessWindowRec *winRec;
 
-  pWin = xprGetXWindow (id);
   if (pWin == NULL) return;
 
   winRec = WINREC (pWin);
@@ -130,7 +128,7 @@ RootlessNativeWindowStateChanged (xp_window_id id, unsigned int state)
 
   winRec->is_offscreen = ((state & XP_WINDOW_STATE_OFFSCREEN) != 0);
   winRec->is_obscured = ((state & XP_WINDOW_STATE_OBSCURED) != 0);
-  //  pWin->rootlessUnhittable = winRec->is_offscreen;
+  pWin->rootlessUnhittable = winRec->is_offscreen;
 }
 
 void
@@ -143,7 +141,7 @@ RootlessNativeWindowMoved (WindowPtr pWin)
   ClientPtr client;
   RootlessWindowRec *winRec = WINREC(pWin);
 
-  if (xp_get_window_bounds (winRec->wid, &bounds) != Success) return;
+  if (xp_get_window_bounds ((xp_window_id)winRec->wid, &bounds) != Success) return;
 
   sx = dixScreenOrigins[pWin->drawable.pScreen->myNum].x + darwinMainScreenX;
   sy = dixScreenOrigins[pWin->drawable.pScreen->myNum].y + darwinMainScreenY;
@@ -1426,6 +1424,10 @@ RootlessReparentWindow(WindowPtr pWin, WindowPtr pPriorParent)
 
     pTopWin = TopLevelParent(pWin);
     assert(pTopWin != pWin);
+    
+    pWin->rootlessUnhittable = FALSE;
+    
+    DeleteProperty (pWin, xa_native_window_id ());
 
     if (WINREC(pTopWin) != NULL) {
         /* We're screwed. */
@@ -1482,7 +1484,7 @@ RootlessFlushWindowColormap (WindowPtr pWin)
   wc.colormap = RootlessColormapCallback;
   wc.colormap_data = pWin->drawable.pScreen;
 
-  configure_window (winRec->wid, XP_COLORMAP, &wc);
+  configure_window ((xp_window_id)winRec->wid, XP_COLORMAP, &wc);
 }
 
 /*
diff --git a/miext/rootless/rootlessWindow.h b/miext/rootless/rootlessWindow.h
index 055589e..45bc4c2 100644
--- a/miext/rootless/rootlessWindow.h
+++ b/miext/rootless/rootlessWindow.h
@@ -36,8 +36,6 @@
 
 #include "rootlessCommon.h"
 
-#include <Xplugin.h>
-
 Bool RootlessCreateWindow(WindowPtr pWin);
 Bool RootlessDestroyWindow(WindowPtr pWin);
 
@@ -57,6 +55,6 @@ void RootlessResizeWindow(WindowPtr pWin, int x, int y,
 void RootlessReparentWindow(WindowPtr pWin, WindowPtr pPriorParent);
 void RootlessChangeBorderWidth(WindowPtr pWin, unsigned int width);
 void RootlessNativeWindowMoved (WindowPtr pWin);
-void RootlessNativeWindowStateChanged (xp_window_id id, unsigned int state); 
+void RootlessNativeWindowStateChanged (WindowPtr pWin, unsigned int state); 
 
 #endif
commit 08073862f8c4e1219b6459708ffd28e2bc35885f
Author: Hasso Tepper <hasso at estpak.ee>
Date:   Tue Apr 8 13:00:38 2008 +0300

    configure.ac: Fix monotonic test harder
    
    This was only introduced in a later version of POSIX, so define that
    version to get it from more conformant systems.

diff --git a/configure.ac b/configure.ac
index 0c84bbc..c210963 100644
--- a/configure.ac
+++ b/configure.ac
@@ -734,7 +734,7 @@ if ! test "x$have_clock_gettime" = xno; then
     CPPFLAGS_SAVE="$CPPFLAGS"
 
     if test x"$glibc" = xyes; then
-        CPPFLAGS="$CPPFLAGS -D_POSIX_C_SOURCE=199309L"
+        CPPFLAGS="$CPPFLAGS -D_POSIX_C_SOURCE=200112L"
     fi
 
     AC_RUN_IFELSE([
commit 726dcd9e4ebfb09c0685450dca6e9fae7e773814
Author: Adam Tkac <atkac at redhat.com>
Date:   Mon Apr 7 10:20:02 2008 -0400

    Fix Xvfb input when building against current X sources.

diff --git a/os/WaitFor.c b/os/WaitFor.c
index 36e01ca..da12976 100644
--- a/os/WaitFor.c
+++ b/os/WaitFor.c
@@ -332,13 +332,9 @@ WaitForSomething(int *pClientsReady)
 
 	    if (XFD_ANYSET (&devicesReadable) || XFD_ANYSET (&clientsReadable))
 		break;
-#ifdef WIN32
-	    /* Windows keyboard and mouse events are added to the input queue
-	       in Block- and WakupHandlers. There is no device to check if  
-	       data is ready. So check here if new input is available */
+	    /* check here for DDXes that queue events during Block/Wakeup */
 	    if (*checkForInput[0] != *checkForInput[1])
 		return 0;
-#endif
 	}
     }
 
commit 0f87b41a432a6472a15ec0c9dee997e3bddbd0f2
Author: Hasso Tepper <hasso at estpak.ee>
Date:   Mon Apr 7 14:09:04 2008 +0300

    configure.ac: DragonFly BSD support
    
    Add support for DragonFly BSD, which is just the same as FreeBSD for all
    of these cases.

diff --git a/configure.ac b/configure.ac
index 025b912..0c84bbc 100644
--- a/configure.ac
+++ b/configure.ac
@@ -313,6 +313,7 @@ case $host_cpu in
 	case $host_os in
 		*linux*)	DEFAULT_INT10=vm86 ;;
 		*freebsd*)	AC_DEFINE(USE_DEV_IO) ;;
+		*dragonfly*)	AC_DEFINE(USE_DEV_IO) ;;
 		*netbsd*)	AC_DEFINE(USE_I386_IOPL)
 				SYS_LIBS=-li386
 				;;
@@ -337,6 +338,7 @@ case $host_cpu in
 	I386_VIDEO=yes
 	case $host_os in
 		*freebsd*)	AC_DEFINE(USE_DEV_IO, 1, [BSD /dev/io]) ;;
+		*dragonfly*)	AC_DEFINE(USE_DEV_IO, 1, [BSD /dev/io]) ;;
 		*netbsd*)	AC_DEFINE(USE_I386_IOPL, 1, [BSD i386 iopl])
 				SYS_LIBS=-lx86_64
 				;;
@@ -367,7 +369,7 @@ DRI2=no
 KDRIVE_HW=no
 dnl it would be nice to autodetect these *CONS_SUPPORTs
 case $host_os in
-  *freebsd*)
+  *freebsd* | *dragonfly*)
 	case $host_os in
 		kfreebsd*-gnu) ;;
 		*) AC_DEFINE(CSRG_BASED, 1, [System is BSD-like]) ;;
@@ -1360,7 +1362,7 @@ if test "x$XORG" = xyes -o "x$XGL" = xyes; then
 			;;
 		esac
 		;;
-	  freebsd* | kfreebsd*-gnu)
+	  freebsd* | kfreebsd*-gnu | dragonfly*)
 	  	XORG_OS="freebsd"
 		XORG_OS_SUBDIR="bsd"
 		xorg_bus_bsdpci="yes"
commit 6b1a27023e48b661c4bb3b61181ac57608d8e448
Author: Owen W. Taylor <otaylor at fishsoup.net>
Date:   Thu Apr 3 14:50:05 2008 -0400

    EXA: Fix TS origin computation when implementing RenderComposite with tiling.

diff --git a/exa/exa_render.c b/exa/exa_render.c
index 38e2a04..da81401 100644
--- a/exa/exa_render.c
+++ b/exa/exa_render.c
@@ -650,7 +650,7 @@ exaComposite(CARD8	op,
 		     !pSrc->transform &&
 		     pSrc->repeatType == RepeatNormal)
 	    {
-		DDXPointRec srcOrg;
+		DDXPointRec patOrg;
 
 		/* Let's see if the driver can do the repeat in one go */
 		if (pExaScr->info->PrepareComposite && !pSrc->alphaMap &&
@@ -674,12 +674,14 @@ exaComposite(CARD8	op,
 					       width, height))
 		    goto done;
 
-		srcOrg.x = (xSrc - xDst) % pSrc->pDrawable->width;
-		srcOrg.y = (ySrc - yDst) % pSrc->pDrawable->height;
+		/* pattern origin is the point in the destination drawable
+		 * corresponding to (0,0) in the source */
+		patOrg.x = xDst - xSrc;
+		patOrg.y = yDst - ySrc;
 
 		ret = exaFillRegionTiled(pDst->pDrawable, &region,
 					 (PixmapPtr)pSrc->pDrawable,
-					 &srcOrg, FB_ALLONES, GXcopy);
+					 &patOrg, FB_ALLONES, GXcopy);
 
 		REGION_UNINIT(pDst->pDrawable->pScreen, &region);
 
commit 539bf3c2836727e7560c64144071b086f8ea32fe
Merge: 3ab33e7... 6c0cfe3...
Author: Sascha Hlusiak <saschahlusiak at arcor.de>
Date:   Mon Apr 7 00:10:16 2008 +0200

    Merge branch 'master' of git+ssh://git.freedesktop.org/git/xorg/xserver

commit 3ab33e7cd46c25dfc461b2a1b13e138225a94524
Author: Sascha Hlusiak <saschahlusiak at arcor.de>
Date:   Sun Apr 6 23:23:47 2008 +0200

    Remove stale code
    
    The jstk code for Joysticks is not used by any module, was never actually compiled and uses an API
    that is deprecated these days.
    
    No reason to keep it.

diff --git a/hw/xfree86/os-support/bsd/Makefile.am b/hw/xfree86/os-support/bsd/Makefile.am
index 4fc270a..6789030 100644
--- a/hw/xfree86/os-support/bsd/Makefile.am
+++ b/hw/xfree86/os-support/bsd/Makefile.am
@@ -72,7 +72,6 @@ libbsd_la_SOURCES = \
 # FIXME: Add these files to the build as needed
 EXTRA_DIST = \
 	bsd_apm.c \
-	bsd_jstk.c \
 	bsd_kqueue_apm.c \
 	bsdResource.c \
 	memrange.h \
diff --git a/hw/xfree86/os-support/bsd/bsd_jstk.c b/hw/xfree86/os-support/bsd/bsd_jstk.c
deleted file mode 100644
index b5b91b0..0000000
--- a/hw/xfree86/os-support/bsd/bsd_jstk.c
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright 1995 by Frederic Lepied, France. <fred at sugix.frmug.fr.net>       
- *                                                                            
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is  hereby granted without fee, provided that
- * the  above copyright   notice appear  in   all  copies and  that both  that
- * copyright  notice   and   this  permission   notice  appear  in  supporting
- * documentation, and that   the  name of  Frederic   Lepied not  be  used  in
- * advertising or publicity pertaining to distribution of the software without
- * specific,  written      prior  permission.     Frederic  Lepied   makes  no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.                   
- *                                                                            
- * FREDERIC  LEPIED DISCLAIMS ALL   WARRANTIES WITH REGARD  TO  THIS SOFTWARE,
- * INCLUDING ALL IMPLIED   WARRANTIES OF MERCHANTABILITY  AND   FITNESS, IN NO
- * EVENT  SHALL FREDERIC  LEPIED BE   LIABLE   FOR ANY  SPECIAL, INDIRECT   OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA  OR PROFITS, WHETHER  IN  AN ACTION OF  CONTRACT,  NEGLIGENCE OR OTHER
- * TORTIOUS  ACTION, ARISING    OUT OF OR   IN  CONNECTION  WITH THE USE    OR
- * PERFORMANCE OF THIS SOFTWARE.
- *
- */
-
-/* Modified for FreeBSD by David Dawes <dawes at XFree86.org> */
-
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <sys/types.h>
-#include <unistd.h>
-#include <string.h>
-#include <errno.h>
-#include <machine/joystick.h>
-#include <fcntl.h>
-
-#include "misc.h"
-#include "xf86.h"
-
-#define JS_RETURN sizeof(struct joystick)
-
-/***********************************************************************
- *
- * xf86JoystickOn --
- *
- * open the device and init timeout according to the device value.
- *
- ***********************************************************************
- */
-
-int
-xf86JoystickOn(char * name, int *timeout, int *centerX, int *centerY)
-{
-  int   status;
-  int   changed = 0;
-  int   timeinmicros;
-  struct joystick	js;
-  
-#ifdef DEBUG
-  ErrorF("xf86JoystickOn: %s\n", name);
-#endif
-  
-  if ((status = open(name, O_RDWR | O_NDELAY, 0)) < 0)
-    {
-      xf86Msg(X_WARNING, "xf86JoystickOn: Cannot open joystick '%s' (%s)\n",
-	      name, strerror(errno));
-      return -1;
-    }
-
-  if (*timeout <= 0) {
-    /* Use the current setting */
-    ioctl(status, JOY_GETTIMEOUT, (char *)&timeinmicros);
-    *timeout = timeinmicros / 1000;
-    if (*timeout == 0)
-      *timeout = 1;
-    changed = 1;
-  }
-  /* Maximum allowed timeout in the FreeBSD driver is 10ms */
-  if (*timeout > 10) {
-    *timeout = 10;
-    changed = 1;
-  }
-  
-  if (changed)
-    xf86Msg(X_PROBED, "Joystick: timeout value = %d\n", *timeout);
-
-  timeinmicros = *timeout * 1000;
-
-  /* Assume the joystick is centred when this is called */
-  read(status, &js, JS_RETURN);
-  if (*centerX < 0) {
-    *centerX = js.x;
-    xf86Msg(X_PROBED, "Joystick: CenterX set to %d\n", *centerX);
-  }
-  if (*centerY < 0) {
-    *centerY = js.y;
-    xf86Msg(X_PROBED, "Joystick: CenterY set to %d\n", *centerY);
-  }
-
-  return status;
-}
-
-/***********************************************************************
- *
- * xf86JoystickInit --
- *
- * called when X device is initialized.
- *
- ***********************************************************************
- */
-
-void
-xf86JoystickInit()
-{
-	return;
-}
-
-/***********************************************************************
- *
- * xf86JoystickOff --
- *
- * close the handle.
- *
- ***********************************************************************
- */
-
-int
-xf86JoystickOff(int *fd, int doclose)
-{
-  int   oldfd;
-  
-  if (((oldfd = *fd) >= 0) && doclose) {
-    close(*fd);
-    *fd = -1;
-  }
-  return oldfd;
-}
-
-/***********************************************************************
- *
- * xf86JoystickGetState --
- *
- * return the state of buttons and the position of the joystick.
- *
- ***********************************************************************
- */
-
-int
-xf86JoystickGetState(int fd, int *x, int *y, int *buttons)
-{
-  struct joystick	js;
-  int                   status;
-  
-  status = read(fd, &js, JS_RETURN);
- 
-  if (status != JS_RETURN)
-    {
-      Error("Joystick read");      
-      return 0;
-    }
-  
-  *x = js.x;
-  *y = js.y;
-  *buttons = js.b1 | (js.b2 << 1);
-#ifdef DEBUG
-  ErrorF("xf86JoystickGetState: x = %d, y = %d, buttons = %d\n", *x, *y,
-	 *buttons);
-#endif
-  
-  return 1;
-}
-
-/*
- * Entry point for XFree86 Loader
- */
-void
-bsd_jstkModuleInit(pointer *data, INT32 *magic)
-{
-    *magic = MAGIC_DONE;
-    *data = NULL;
-}
-/* end of bsd_jstk.c */
diff --git a/hw/xfree86/os-support/linux/Makefile.am b/hw/xfree86/os-support/linux/Makefile.am
index beaae3d..93f09c1 100644
--- a/hw/xfree86/os-support/linux/Makefile.am
+++ b/hw/xfree86/os-support/linux/Makefile.am
@@ -45,7 +45,6 @@ INCLUDES = $(XORG_INCS) $(PLATFORM_INCLUDES) -I/usr/include/drm # FIXME this las
 # FIXME: These need to be added to the build
 LNX_EXTRA_SRCS = \
 	lnx_font.c \
-	lnx_jstk.c \
 	lnxResource.c
 
 EXTRA_DIST = \
diff --git a/hw/xfree86/os-support/linux/lnx_jstk.c b/hw/xfree86/os-support/linux/lnx_jstk.c
deleted file mode 100644
index d77631b..0000000
--- a/hw/xfree86/os-support/linux/lnx_jstk.c
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright 1995 by Frederic Lepied, France. <fred at sugix.frmug.fr.net>       
- *                                                                            
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is  hereby granted without fee, provided that
- * the  above copyright   notice appear  in   all  copies and  that both  that
- * copyright  notice   and   this  permission   notice  appear  in  supporting
- * documentation, and that   the  name of  Frederic   Lepied not  be  used  in
- * advertising or publicity pertaining to distribution of the software without
- * specific,  written      prior  permission.     Frederic  Lepied   makes  no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.                   
- *                                                                            
- * FREDERIC  LEPIED DISCLAIMS ALL   WARRANTIES WITH REGARD  TO  THIS SOFTWARE,
- * INCLUDING ALL IMPLIED   WARRANTIES OF MERCHANTABILITY  AND   FITNESS, IN NO
- * EVENT  SHALL FREDERIC  LEPIED BE   LIABLE   FOR ANY  SPECIAL, INDIRECT   OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA  OR PROFITS, WHETHER  IN  AN ACTION OF  CONTRACT,  NEGLIGENCE OR OTHER
- * TORTIOUS  ACTION, ARISING    OUT OF OR   IN  CONNECTION  WITH THE USE    OR
- * PERFORMANCE OF THIS SOFTWARE.
- *
- */
-
-
-static const char rcs_id[] = "Id: lnx_jstk.c,v 1.1 1995/12/20 14:06:09 lepied Exp";
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <sys/types.h>
-#include <unistd.h>
-#include <string.h>
-#include <errno.h>
-#define inline __inline__
-#include <linux/joystick.h>
-#include <fcntl.h>
-#include <sys/ioctl.h>
-
-#include "xf86.h"
-
-#if !defined(JSIOCGTIMELIMIT)
-/* make 2.1.x joystick.h backward compatable */
-#define JSIOCGTIMELIMIT		JS_GET_TIMELIMIT
-#define JSIOCSTIMELIMIT		JS_SET_TIMELIMIT
-#define js_status		JS_DATA_TYPE
-#endif
-
-
-/***********************************************************************
- *
- * xf86JoystickOn --
- *
- * open the device and init timeout according to the device value.
- *
- ***********************************************************************
- */
-
-int
-xf86JoystickOn(char *name, int *timeout, int *centerX, int *centerY)
-{
-  int			fd;
-  struct js_status	js;
-    
-#ifdef DEBUG
-  ErrorF("xf86JoystickOn %s\n", name);
-#endif
-
-  if ((fd = open(name, O_RDWR | O_NDELAY, 0)) < 0)
-    {
-      xf86Msg(X_WARNING, "Cannot open joystick '%s' (%s)\n", name,
-		strerror(errno));
-      return -1;
-    }
-
-  if (*timeout == 0) {
-    if (ioctl (fd, JSIOCGTIMELIMIT, timeout) == -1) {
-      Error("joystick JSIOCGTIMELIMIT ioctl");
-    }
-    else {
-      xf86Msg(X_CONFIG, "Joystick: timeout value = %d\n", *timeout);
-    }
-  }
-  else {
-    if (ioctl(fd, JSIOCSTIMELIMIT, timeout) == -1) {
-      Error("joystick JSIOCSTIMELIMIT ioctl");
-    }
-  }
-
-  /* Assume the joystick is centred when this is called */
-  read(fd, &js, JS_RETURN);
-  if (*centerX < 0) {
-    *centerX = js.x;
-    xf86Msg(X_CONFIG, "Joystick: CenterX set to %d\n", *centerX);
-  }
-  if (*centerY < 0) {
-    *centerY = js.y;
-    xf86Msg(X_CONFIG, "Joystick: CenterY set to %d\n", *centerY);
-  }
-
-  return fd;
-}
-
-/***********************************************************************
- *
- * xf86JoystickInit --
- *
- * called when X device is initialized.
- *
- ***********************************************************************
- */
-
-void
-xf86JoystickInit()
-{
-	return;
-}
-
-/***********************************************************************
- *
- * xf86JoystickOff --
- *
- * close the handle.
- *
- ***********************************************************************
- */
-
-int
-xf86JoystickOff(int *fd, int doclose)
-{
-  int   oldfd;
-  
-  if (((oldfd = *fd) >= 0) && doclose) {
-    close(*fd);
-    *fd = -1;
-  }
-  return oldfd;
-}
-
-/***********************************************************************
- *
- * xf86JoystickGetState --
- *
- * return the state of buttons and the position of the joystick.
- *
- ***********************************************************************
- */
-
-int
-xf86JoystickGetState(int fd, int *x, int *y, int *buttons)
-{
-  struct js_status	js;
-  int			status;
-  
-  status = read(fd, &js, JS_RETURN);
- 
-  if (status != JS_RETURN)
-    {
-      Error("Joystick read");      
-      return 0;
-    }
-  
-  *x = js.x;
-  *y = js.y;
-  *buttons = js.buttons;
-  
-  return 1;
-}
-
-/*
- * Entry point for XFree86 Loader
- */
-void
-linux_jstkModuleInit(pointer *data, INT32 *magic)
-{
-    *magic = MAGIC_DONE;
-    *data = NULL;
-}
-
-/* end of lnx_jstk.c */
commit 6c0cfe3d43b177c4cfaf7e228f32c655f9a98459
Author: Julien Cristau <jcristau at debian.org>
Date:   Fri Apr 4 19:01:40 2008 +0200

    Fix the clock_gettime check for glibc-based non-Linux systems
    
    We need to define _POSIX_C_SOURCE on glibc, not just Linux, so add a new
    test for the __GLIBC__ macro.

diff --git a/configure.ac b/configure.ac
index 1431f4b..025b912 100644
--- a/configure.ac
+++ b/configure.ac
@@ -705,6 +705,15 @@ if test "x$NEED_DBUS" = xyes; then
 fi
 CONFIG_LIB='$(top_builddir)/config/libconfig.a'
 
+AC_MSG_CHECKING([for glibc...])
+AC_PREPROC_IFELSE([
+#include <features.h>
+#ifndef __GLIBC__
+#error
+#endif
+], glibc=yes, glibc=no)
+AC_MSG_RESULT([$glibc])
+
 AC_CHECK_FUNCS([clock_gettime], [have_clock_gettime=yes],
                [AC_CHECK_LIB([rt], [clock_gettime], [have_clock_gettime=-lrt],
                              [have_clock_gettime=no])])
@@ -720,11 +729,13 @@ if ! test "x$have_clock_gettime" = xno; then
 
     LIBS_SAVE="$LIBS"
     LIBS="$CLOCK_LIBS"
+    CPPFLAGS_SAVE="$CPPFLAGS"
+
+    if test x"$glibc" = xyes; then
+        CPPFLAGS="$CPPFLAGS -D_POSIX_C_SOURCE=199309L"
+    fi
 
     AC_RUN_IFELSE([
-#ifdef __linux__
-#define _POSIX_C_SOURCE 199309L
-#endif
 #include <time.h>
 
 int main(int argc, char *argv[[]]) {
@@ -739,6 +750,7 @@ int main(int argc, char *argv[[]]) {
        [MONOTONIC_CLOCK="cross compiling"])
 
     LIBS="$LIBS_SAVE"
+    CPPFLAGS="$CPPFLAGS_SAVE"
 else
     MONOTONIC_CLOCK=no
 fi
commit cc7c045bae01d90d8f1b750080ba48a96e983c68
Author: Adam Jackson <ajax at redhat.com>
Date:   Fri Apr 4 12:58:12 2008 -0400

    Fix PCI config space cycles from int10 emulator.
    
    The top bit of 0xCF8 is an enable bit, not part of the domain.  Sending
    cycles to domain 128 instead of domain 0 is rarely the right thing to do.

diff --git a/hw/xfree86/int10/helper_exec.c b/hw/xfree86/int10/helper_exec.c
index 9daff22..c3af5bc 100644
--- a/hw/xfree86/int10/helper_exec.c
+++ b/hw/xfree86/int10/helper_exec.c
@@ -461,7 +461,7 @@ Mem_wl(CARD32 addr, CARD32 val)
 static CARD32 PciCfg1Addr = 0;
 
 #define PCI_OFFSET(x) ((x) & 0x000000ff)
-#define PCI_TAG(x)    ((x) & 0xffffff00)
+#define PCI_TAG(x)    ((x) & 0x7fffff00)
 
 static struct pci_device*
 pci_device_for_cfg_address (CARD32 addr)
commit d1de3dda8efe501d4192c8a99c34ab4265316c32
Author: Eric Anholt <eric at anholt.net>
Date:   Mon Mar 17 14:22:39 2008 -0700

    Fix clock_gettime presence detect on FreeBSD.
    
    For non-Linux, _POSIX_C_SOURCE and friends restrict symbols defined rather
    than enabling defines of symbols.  Additionally, CLOCK_MONOTONIC was
    apparently added to the standard around 2000 anyway, not 1993.

diff --git a/configure.ac b/configure.ac
index 985c8e2..1431f4b 100644
--- a/configure.ac
+++ b/configure.ac
@@ -722,7 +722,9 @@ if ! test "x$have_clock_gettime" = xno; then
     LIBS="$CLOCK_LIBS"
 
     AC_RUN_IFELSE([
+#ifdef __linux__
 #define _POSIX_C_SOURCE 199309L
+#endif
 #include <time.h>
 
 int main(int argc, char *argv[[]]) {
commit ec17900f52bbd25d07566834756e5c7e832e0463
Author: Kristian Høgsberg <krh at redhat.com>
Date:   Fri Apr 4 10:46:45 2008 -0400

    Convert __DRIconfigs after we've made sure createNewScreen succeeded.

diff --git a/GL/glx/glxdri.c b/GL/glx/glxdri.c
index ffa9a0b..9cd0738 100644
--- a/GL/glx/glxdri.c
+++ b/GL/glx/glxdri.c
@@ -1117,13 +1117,13 @@ __glXDRIscreenProbe(ScreenPtr pScreen)
 					   &driConfigs,
 					   screen);
 
-    screen->base.fbconfigs = glxConvertConfigs(screen->core, driConfigs);
-
     if (screen->driScreen == NULL) {
 	LogMessage(X_ERROR, "AIGLX error: Calling driver entry point failed");
 	goto handle_error;
     }
 
+    screen->base.fbconfigs = glxConvertConfigs(screen->core, driConfigs);
+
     initializeExtensions(screen);
 
     DRIGetTexOffsetFuncs(pScreen, &screen->texOffsetStart,
commit 16a8ce75585ea360c39e0ffce4f7bb26a359b754
Author: Kristian Høgsberg <krh at redhat.com>
Date:   Thu Apr 3 16:44:32 2008 -0400

    Only autoload RECORD if it was enabled.

diff --git a/hw/xfree86/common/xf86Config.c b/hw/xfree86/common/xf86Config.c
index 8de7426..208e23d 100644
--- a/hw/xfree86/common/xf86Config.c
+++ b/hw/xfree86/common/xf86Config.c
@@ -119,7 +119,9 @@ static ModuleDefault ModuleDefaults[] = {
     {.name = "dbe",      .toLoad = TRUE,    .load_opt=NULL},
     {.name = "glx",      .toLoad = TRUE,    .load_opt=NULL},
     {.name = "freetype", .toLoad = TRUE,    .load_opt=NULL},
+#ifdef XRECORD
     {.name = "record",   .toLoad = TRUE,    .load_opt=NULL},
+#endif
     {.name = "dri",      .toLoad = TRUE,    .load_opt=NULL},
     {.name = "dri2",     .toLoad = TRUE,    .load_opt=NULL},
     {.name = NULL,       .toLoad = FALSE,   .load_opt=NULL}
commit f0915fb3c4a9712200882440a64d11dc595a02bb
Author: Dave Airlie <airlied at redhat.com>
Date:   Fri Apr 4 09:29:51 2008 +1000

    quirk: add quirk for ACER EDID

diff --git a/hw/xfree86/modes/xf86EdidModes.c b/hw/xfree86/modes/xf86EdidModes.c
index f15c396..8f7d45d 100644
--- a/hw/xfree86/modes/xf86EdidModes.c
+++ b/hw/xfree86/modes/xf86EdidModes.c
@@ -158,6 +158,11 @@ static Bool quirk_first_detailed_preferred (int scrnIndex, xf86MonPtr DDC)
 	DDC->vendor.prod_id == 765)
 	return TRUE;
 
+    /* ACR of some sort RH #284231 */
+    if (memcmp (DDC->vendor.name, "ACR", 4) == 0 &&
+	DDC->vendor.prod_id == 2423)
+	return TRUE;
+
     return FALSE;
 }
 
commit 2e42b67b82db0f9128dd00e339b9dfdd9fe6d667
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 2 18:05:34 2008 -0700

    XQuartz: Change reporting of space change to debug log rather than stderr
    (cherry picked from commit ed15556a9fc4ebdb88f42961052fc8456082165f)

diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index 91bf25a..d685fca 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -108,7 +108,7 @@ static void eventHandler(unsigned int type, const void *arg,
             }
             break;
         case  XP_EVENT_SPACE_CHANGED:
-            ErrorF("XP_EVENT_SPACE_CHANGED\n");
+            DEBUG_LOG("XP_EVENT_SPACE_CHANGED\n");
             if(arg_size == sizeof(uint32_t)) {
                 uint32_t space_id = *(uint32_t *)arg;
                 DarwinSendDDXEvent(kXquartzSpaceChanged, 1, space_id);
commit c737d04c758e03e32f692a31ed2a665ccbafa931
Author: Ben Byer <bbyer at apple.com>
Date:   Tue Apr 1 00:40:46 2008 -0700

    The AppKit thread should not be calling directly into the X server
    functions to change state when the keyboard is reloaded; instead,
    pass it as an event.
    (cherry picked from commit 7e653f806ff5508aace059312156f319a9ed4479)

diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index 01e6f41..df92d8b 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -91,13 +91,8 @@ extern int              darwinMainScreenY;
  * Special ddx events understood by the X server
  */
 enum {
-    kXquartzUpdateModifiers   // update all modifier keys
+    kXquartzReloadKeymap      // Reload system keymap
             = LASTEvent+1,    // (from X.h list of event names)
-    kXquartzUpdateButtons,    // update state of mouse buttons 2 and up
-    kXquartzScrollWheel,      // scroll wheel event
-    /*
-     * Quartz-specific events -- not used in IOKit mode
-     */
     kXquartzActivate,         // restore X drawing and cursor
     kXquartzDeactivate,       // clip X drawing and switch to Aqua cursor
     kXquartzSetRootClip,      // enable or disable drawing to the X screen
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index b6cd3f2..3afbaf8 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -289,6 +289,7 @@ Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) {
         FatalError("Couldn't allocate event buffer\n");
 
     mieqInit();
+    mieqSetHandler(kXquartzReloadKeymap, DarwinKeyboardReloadHandler);
     mieqSetHandler(kXquartzActivate, DarwinEventHandler);
     mieqSetHandler(kXquartzDeactivate, DarwinEventHandler);
     mieqSetHandler(kXquartzSetRootClip, DarwinEventHandler);
@@ -322,7 +323,7 @@ void ProcessInputEvents(void) {
     // Empty the signaling pipe
     int x = sizeof(xe);
     while (x == sizeof(xe)) {
-      DEBUG_LOG("draining pipe\n");
+//      DEBUG_LOG("draining pipe\n");
       x = read(darwinEventReadFD, &xe, sizeof(xe));
     }
 }
@@ -412,8 +413,8 @@ void DarwinSendKeyboardEvents(int ev_type, int keycode) {
 
     this_seed = QuartzSystemKeymapSeed();
     if (this_seed != last_seed) {
-      last_seed = this_seed;
-      DarwinKeyboardReload(darwinKeyboard);
+		last_seed = this_seed;
+		DarwinSendDDXEvent(kXquartzReloadKeymap, 0);
     }
   }
 
diff --git a/hw/xquartz/darwinKeyboard.c b/hw/xquartz/darwinKeyboard.c
index 355d9f0..6f2758e 100644
--- a/hw/xquartz/darwinKeyboard.c
+++ b/hw/xquartz/darwinKeyboard.c
@@ -850,16 +850,18 @@ static Bool InitModMap(register KeyClassPtr keyc) {
 }
 
 
-void DarwinKeyboardReload(DeviceIntPtr pDev) {
+void DarwinKeyboardReloadHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents) {
     KeySymsRec keySyms;
-
+	if (dev == NULL) dev = darwinKeyboard;
+	
+	DEBUG_LOG("DarwinKeyboardReloadHandler(%p)\n", dev);
     DarwinLoadKeyboardMapping(&keySyms);
 
-    if (SetKeySymsMap(&pDev->key->curKeySyms, &keySyms)) {
+    if (SetKeySymsMap(&dev->key->curKeySyms, &keySyms)) {
         /* now try to update modifiers. */
 
-        memmove(pDev->key->modifierMap, keyInfo.modMap, MAP_LENGTH);
-        InitModMap(pDev->key);
+        memmove(dev->key->modifierMap, keyInfo.modMap, MAP_LENGTH);
+        InitModMap(dev->key);
     } else DEBUG_LOG("SetKeySymsMap=0\n");
 
     SendMappingNotify(MappingKeyboard, MIN_KEYCODE, NUM_KEYCODES, 0);
diff --git a/hw/xquartz/darwinKeyboard.h b/hw/xquartz/darwinKeyboard.h
index 5cf64c7..762f659 100644
--- a/hw/xquartz/darwinKeyboard.h
+++ b/hw/xquartz/darwinKeyboard.h
@@ -31,7 +31,7 @@
 
 /* Provided for darwinEvents.c */
 extern darwinKeyboardInfo keyInfo;
-void DarwinKeyboardReload(DeviceIntPtr pDev);
+void DarwinKeyboardReloadHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents);
 void DarwinKeyboardInit(DeviceIntPtr pDev);
 int DarwinModifierNXKeycodeToNXKey(unsigned char keycode, int *outSide);
 int DarwinModifierNXKeyToNXKeycode(int key, int side);
diff --git a/hw/xquartz/quartzKeyboard.h b/hw/xquartz/quartzKeyboard.h
index 8131b56..4f495bb 100644
--- a/hw/xquartz/quartzKeyboard.h
+++ b/hw/xquartz/quartzKeyboard.h
@@ -46,7 +46,6 @@ typedef struct darwinKeyboardInfo_struct {
 } darwinKeyboardInfo;
 
 /* These functions need to be implemented by Xquartz, XDarwin, etc. */
-void DarwinKeyboardReload(DeviceIntPtr pDev);
 Bool QuartzReadSystemKeymap(darwinKeyboardInfo *info);
 unsigned int QuartzSystemKeymapSeed(void);
 
commit 15b0084f1ab23042190d8beeb3f088b92dee5a10
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Mar 31 23:31:25 2008 -0700

    formatting cleanup for X11Application.m (no code changes)
    (cherry picked from commit eb083d3f68f459d90417558da1ed00729b749950)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 28bb529..2844fca 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -166,171 +166,170 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
     static TSMDocumentID x11_document;
 	DEBUG_LOG("state=%d, _x_active=%d, \n", state, _x_active)
     if (state) {
-      DarwinSendDDXEvent(kXquartzActivate, 0);
-      
-      if (!_x_active) {
-	if (x11_document == 0 && darwinKeymapFile == NULL) {
-	  OSType types[1];
-	  types[0] = kUnicodeDocument;
-	  NewTSMDocument (1, types, &x11_document, 0);
-	}
-	
-	if (x11_document != 0)	ActivateTSMDocument (x11_document);
-      }
+		DarwinSendDDXEvent(kXquartzActivate, 0);
+
+		if (!_x_active) {
+			if (x11_document == 0 && darwinKeymapFile == NULL) {
+				OSType types[1];
+				types[0] = kUnicodeDocument;
+				NewTSMDocument (1, types, &x11_document, 0);
+			}
+
+			if (x11_document != 0)	ActivateTSMDocument (x11_document);
+		}
     } else {
-      DarwinSendDDXEvent(kXquartzDeactivate, 0);
-      
-      if (_x_active && x11_document != 0)
-		DeactivateTSMDocument (x11_document);
-    }
-    
-    _x_active = state;
+		DarwinSendDDXEvent(kXquartzDeactivate, 0);
+
+		if (_x_active && x11_document != 0)
+			DeactivateTSMDocument (x11_document);
+	}
+
+	_x_active = state;
 }
 
 - (void) became_key:(NSWindow *)win {
-    [self activateX:NO];
+	[self activateX:NO];
 }
 
 - (void) sendEvent:(NSEvent *)e {
-  NSEventType type;
-  BOOL for_appkit, for_x;
-  
-  type = [e type];
-  
-  /* By default pass down the responder chain and to X. */
-  for_appkit = YES;
-  for_x = YES;
-  
-  switch (type) {
-  case NSLeftMouseDown: case NSRightMouseDown: case NSOtherMouseDown:
-  case NSLeftMouseUp: case NSRightMouseUp: case NSOtherMouseUp:
-    if ([e window] != nil) {
-      /* Pointer event has an (AppKit) window. Probably something for the kit. */
-      for_x = NO;
-      if (_x_active) [self activateX:NO];
-    } else if ([self modalWindow] == nil) {
-      /* Must be an X window. Tell appkit it doesn't have focus. */
-      WindowPtr pWin = xprGetXWindowFromAppKit([e windowNumber]);
-      if (pWin) RootlessReorderWindow(pWin);
-      for_appkit = NO;
-      
-      if ([self isActive]) {
-	[self deactivate];
-	
-	if (!_x_active && quartzProcs->IsX11Window([e window],
-						   [e windowNumber]))
-	  [self activateX:YES];
-      }
-    }
-    break;
-      
-  case NSKeyDown: case NSKeyUp:
-    if (_x_active) {
-      static int swallow_up;
-      
-      /* No kit window is focused, so send it to X. */
-      for_appkit = NO;
-      if (type == NSKeyDown) {
-	/* Before that though, see if there are any global
-	   shortcuts bound to it. */
-	
-	if (X11EnableKeyEquivalents
-	    && [[self mainMenu] performKeyEquivalent:e]) {
-	  swallow_up = [e keyCode];
-	  for_x = NO;
-	} else if (!quartzEnableRootless
-		   && ([e modifierFlags] & ALL_KEY_MASKS)
-		   == (NSCommandKeyMask | NSAlternateKeyMask)
-		   && ([e keyCode] == 0 /*a*/
-		    || [e keyCode] == 53 /*Esc*/)) {
-	  swallow_up = 0;
-	  for_x = NO;
+ 	NSEventType type;
+	BOOL for_appkit, for_x;
+
+	type = [e type];
+
+	/* By default pass down the responder chain and to X. */
+	for_appkit = YES;
+	for_x = YES;
+  
+	switch (type) {
+		case NSLeftMouseDown: case NSRightMouseDown: case NSOtherMouseDown:
+		case NSLeftMouseUp: case NSRightMouseUp: case NSOtherMouseUp:
+		if ([e window] != nil) {
+			/* Pointer event has an (AppKit) window. Probably something for the kit. */
+			for_x = NO;
+			if (_x_active) [self activateX:NO];
+		} else if ([self modalWindow] == nil) {
+			/* Must be an X window. Tell appkit it doesn't have focus. */
+			WindowPtr pWin = xprGetXWindowFromAppKit([e windowNumber]);
+			if (pWin) RootlessReorderWindow(pWin);
+			for_appkit = NO;
+
+			if ([self isActive]) {
+				[self deactivate];
+				if (!_x_active && quartzProcs->IsX11Window([e window],
+					[e windowNumber]))
+					[self activateX:YES];
+			}
+		}
+		break;
+
+		case NSKeyDown: case NSKeyUp:
+		if (_x_active) {
+			static int swallow_up;
+
+			/* No kit window is focused, so send it to X. */
+			for_appkit = NO;
+			if (type == NSKeyDown) {
+				/* Before that though, see if there are any global
+				shortcuts bound to it. */
+
+					if (X11EnableKeyEquivalents
+						&& [[self mainMenu] performKeyEquivalent:e]) {
+							swallow_up = [e keyCode];
+							for_x = NO;
+					} else if (!quartzEnableRootless
+						&& ([e modifierFlags] & ALL_KEY_MASKS)
+						== (NSCommandKeyMask | NSAlternateKeyMask)
+						&& ([e keyCode] == 0 /*a*/
+							|| [e keyCode] == 53 /*Esc*/)) {
+						swallow_up = 0;
+						for_x = NO;
 #ifdef DARWIN_DDX_MISSING
-	  DarwinSendDDXEvent(kXquartzToggleFullscreen, 0);
+						DarwinSendDDXEvent(kXquartzToggleFullscreen, 0);
 #endif
+					}
+			} else {
+			/* If we saw a key equivalent on the down, don't pass
+	   			the up through to X. */
+
+				if (swallow_up != 0 && [e keyCode] == swallow_up) {
+					swallow_up = 0;
+					for_x = NO;
+				}
+			}
+    		} else for_x = NO;
+    	break;
+
+		case NSFlagsChanged:
+			/* For the l33t X users who remap modifier keys to normal keysyms. */
+			if (!_x_active) for_x = NO;
+		break;
+
+		case NSAppKitDefined:
+		switch ([e subtype]) {
+			case NSApplicationActivatedEventType:
+      		for_x = NO;
+			if ([self modalWindow] == nil) {
+				for_appkit = NO;
+
+				/* FIXME: hack to avoid having to pass the event to appkit,
+	   			which would cause it to raise one of its windows. */
+				_appFlags._active = YES;
+
+				[self activateX:YES];
+				if ([e data2] & 0x10) X11ApplicationSetFrontProcess();
+			}
+			break;
+
+			case 18: /* ApplicationDidReactivate */
+				if (quartzHasRoot) for_appkit = NO;
+			break;
+
+			case NSApplicationDeactivatedEventType:
+				for_x = NO;
+				[self activateX:NO];
+			break;
+		}
+	break;
+ 
+	default: break; /* for gcc */
 	}
-      } else {
-	/* If we saw a key equivalent on the down, don't pass
-	   the up through to X. */
-	
-	if (swallow_up != 0 && [e keyCode] == swallow_up) {
-	  swallow_up = 0;
-	  for_x = NO;
-	}
-      }
-    } else for_x = NO;
-    break;
-    
-  case NSFlagsChanged:
-    /* For the l33t X users who remap modifier keys to normal keysyms. */
-    if (!_x_active) for_x = NO;
-    break;
-    
-  case NSAppKitDefined:
-    switch ([e subtype]) {
-    case NSApplicationActivatedEventType:
-      for_x = NO;
-      if ([self modalWindow] == nil) {
-		for_appkit = NO;
-	
-	/* FIXME: hack to avoid having to pass the event to appkit,
-	   which would cause it to raise one of its windows. */
-	_appFlags._active = YES;
-	
-	[self activateX:YES];
-	if ([e data2] & 0x10) X11ApplicationSetFrontProcess();
-      }
-      break;
-      
-    case 18: /* ApplicationDidReactivate */
-      if (quartzHasRoot) for_appkit = NO;
-      break;
-      
-    case NSApplicationDeactivatedEventType:
-      for_x = NO;
-      [self activateX:NO];
-      break;
-    }
-    break;
-    
-  default: break; /* for gcc */
-  }
-  
-  if (for_appkit) [super sendEvent:e];
-  
-  if (for_x) send_nsevent (type, e);
+
+	if (for_appkit) [super sendEvent:e];
+
+	if (for_x) send_nsevent (type, e);
 }
 
 - (void) set_window_menu:(NSArray *)list {
-    [_controller set_window_menu:list];
+	[_controller set_window_menu:list];
 }
 
 - (void) set_window_menu_check:(NSNumber *)n {
-    [_controller set_window_menu_check:n];
+	[_controller set_window_menu_check:n];
 }
 
 - (void) set_apps_menu:(NSArray *)list {
-    [_controller set_apps_menu:list];
+	[_controller set_apps_menu:list];
 }
 
 - (void) set_front_process:unused {
-    [NSApp activateIgnoringOtherApps:YES];
+	[NSApp activateIgnoringOtherApps:YES];
 
-    if ([self modalWindow] == nil)
-        [self activateX:YES];
+	if ([self modalWindow] == nil)
+		[self activateX:YES];
 }
 
 - (void) set_can_quit:(NSNumber *)state {
-    [_controller set_can_quit:[state boolValue]];
+	[_controller set_can_quit:[state boolValue]];
 }
 
 - (void) server_ready:unused {
-    [_controller server_ready];
+	[_controller server_ready];
 }
 
 - (void) show_hide_menubar:(NSNumber *)state {
-    if ([state boolValue]) ShowMenuBar ();
-    else HideMenuBar ();
+	if ([state boolValue]) ShowMenuBar ();
+	else HideMenuBar ();
 }
 
 
@@ -348,57 +347,57 @@ static void cfrelease (CFAllocatorRef a, const void *b) {
 }
 
 static CFMutableArrayRef nsarray_to_cfarray (NSArray *in) {
-    CFMutableArrayRef out;
-    CFArrayCallBacks cb;
-    NSObject *ns;
-    const CFTypeRef *cf;
-    int i, count;
-	
-    memset (&cb, 0, sizeof (cb));
-    cb.version = 0;
-    cb.retain = cfretain;
-    cb.release = cfrelease;
-	
-    count = [in count];
-    out = CFArrayCreateMutable (NULL, count, &cb);
-	
-    for (i = 0; i < count; i++) {
-      ns = [in objectAtIndex:i];
-      
-      if ([ns isKindOfClass:[NSArray class]])
-	cf = (CFTypeRef) nsarray_to_cfarray ((NSArray *) ns);
-      else
-	cf = CFRetain ((CFTypeRef) ns);
-      
-      CFArrayAppendValue (out, cf);
-      CFRelease (cf);
-    }
-    
-    return out;
+	CFMutableArrayRef out;
+	CFArrayCallBacks cb;
+	NSObject *ns;
+	const CFTypeRef *cf;
+	int i, count;
+
+	memset (&cb, 0, sizeof (cb));
+	cb.version = 0;
+	cb.retain = cfretain;
+	cb.release = cfrelease;
+
+	count = [in count];
+	out = CFArrayCreateMutable (NULL, count, &cb);
+
+	for (i = 0; i < count; i++) {
+		ns = [in objectAtIndex:i];
+
+		if ([ns isKindOfClass:[NSArray class]])
+			cf = (CFTypeRef) nsarray_to_cfarray ((NSArray *) ns);
+		else
+			cf = CFRetain ((CFTypeRef) ns);
+
+		CFArrayAppendValue (out, cf);
+		CFRelease (cf);
+	}
+
+	return out;
 }
 
 static NSMutableArray * cfarray_to_nsarray (CFArrayRef in) {
-    NSMutableArray *out;
-    const CFTypeRef *cf;
-    NSObject *ns;
-    int i, count;
-	
-    count = CFArrayGetCount (in);
-    out = [[NSMutableArray alloc] initWithCapacity:count];
-	
-    for (i = 0; i < count; i++) {
-      cf = CFArrayGetValueAtIndex (in, i);
-		
-      if (CFGetTypeID (cf) == CFArrayGetTypeID ())
-	ns = cfarray_to_nsarray ((CFArrayRef) cf);
-      else
-	ns = [(id)cf retain];
-      
-      [out addObject:ns];
-      [ns release];
-    }
-    
-    return out;
+	NSMutableArray *out;
+	const CFTypeRef *cf;
+	NSObject *ns;
+	int i, count;
+
+	count = CFArrayGetCount (in);
+	out = [[NSMutableArray alloc] initWithCapacity:count];
+
+	for (i = 0; i < count; i++) {
+		cf = CFArrayGetValueAtIndex (in, i);
+
+		if (CFGetTypeID (cf) == CFArrayGetTypeID ())
+			ns = cfarray_to_nsarray ((CFArrayRef) cf);
+		else
+			ns = [(id)cf retain];
+
+		[out addObject:ns];
+		[ns release];
+	}
+
+	return out;
 }
 
 - (CFPropertyListRef) prefs_get:(NSString *)key {
@@ -855,86 +854,68 @@ convert_flags (unsigned int nsflags) {
     return xflags;
 }
 
-
-// This code should probably be merged with that in XDarwin's XServer.m - BB
 static void send_nsevent (NSEventType type, NSEvent *e) {
-  //    static unsigned int button_state = 0;
-    NSRect screen;
-    NSPoint location;
-    NSWindow *window;
-    int pointer_x, pointer_y, ev_button, ev_type;
-    float pressure, tilt_x, tilt_y;
-
-    //    int num_events=0, i=0, state;
-    // xEvent xe;
-	
-    /* convert location to global top-left coordinates */
-    location = [e locationInWindow];
-    window = [e window];
-    screen = [[[NSScreen screens] objectAtIndex:0] frame];
-		
+	NSRect screen;
+	NSPoint location;
+	NSWindow *window;
+	int pointer_x, pointer_y, ev_button, ev_type;
+	float pressure, tilt_x, tilt_y;
+
+	/* convert location to global top-left coordinates */
+	location = [e locationInWindow];
+	window = [e window];
+	screen = [[[NSScreen screens] objectAtIndex:0] frame];
+
     if (window != nil)	{
-      NSRect frame = [window frame];
-      pointer_x = location.x + frame.origin.x;
-      pointer_y = (((screen.origin.y + screen.size.height)
-		    - location.y) - frame.origin.y);
-    } else {
-      pointer_x = location.x;
-      pointer_y = (screen.origin.y + screen.size.height) - location.y;
-    }
-    
-    pointer_y -= aquaMenuBarHeight;
-    //    state = convert_flags ([e modifierFlags]);
-    
-    pressure = 0;  // for tablets
-    tilt_x = 0;
-    tilt_y = 0;
-
-    switch (type) {
-    case NSLeftMouseDown:    ev_button=1; ev_type=ButtonPress; goto handle_mouse;
-    case NSOtherMouseDown:   ev_button=2; ev_type=ButtonPress; goto handle_mouse;
-    case NSRightMouseDown:   ev_button=3; ev_type=ButtonPress; goto handle_mouse;
-    case NSLeftMouseUp:      ev_button=1; ev_type=ButtonRelease; goto handle_mouse;
-    case NSOtherMouseUp:     ev_button=2; ev_type=ButtonRelease; goto handle_mouse;
-    case NSRightMouseUp:     ev_button=3; ev_type=ButtonRelease; goto handle_mouse;
-    case NSLeftMouseDragged:  ev_button=1; ev_type=MotionNotify; goto handle_mouse;
-    case NSOtherMouseDragged: ev_button=2; ev_type=MotionNotify; goto handle_mouse;
-    case NSRightMouseDragged: ev_button=3; ev_type=MotionNotify; goto handle_mouse;
-    case NSTabletPoint:
-      pressure = [e pressure];
-      tilt_x = [e tilt].x;
-      tilt_y = [e tilt].y; // fall through
-    case NSMouseMoved: ev_button=0; ev_type=MotionNotify; goto handle_mouse;
-    handle_mouse:
-      
-      /* I'm not sure the below code is necessary or useful (-bb)
-	if(ev_type==ButtonPress) {
-	if (!quartzProcs->IsX11Window([e window], [e windowNumber])) {
-	  fprintf(stderr, "Dropping event because it's not a window\n");
-	  break;
+		NSRect frame = [window frame];
+		pointer_x = location.x + frame.origin.x;
+		pointer_y = (((screen.origin.y + screen.size.height)
+			- location.y) - frame.origin.y);
+	} else {
+		pointer_x = location.x;
+		pointer_y = (screen.origin.y + screen.size.height) - location.y;
 	}
-	button_state |= (1 << ev_button);
-	DarwinSendPointerEvents(ev_type, ev_button, pointer_x, pointer_y);
-      } else if (ev_type==ButtonRelease && (button_state & (1 << ev_button)) == 0) break;
-      */
-
-      //      if ([e subtype] == NSTabletPointEventSubtype) pressure = [e pressure];
-      DarwinSendPointerEvents(ev_type, ev_button, pointer_x, pointer_y,
-			      pressure, tilt_x, tilt_y);
-      break;
-    case NSScrollWheel:
-      DarwinSendScrollEvents([e deltaY], pointer_x, pointer_y,
-			     pressure, tilt_x, tilt_y);
-      break;
-      
-    case NSKeyDown:  // do we need to translate these keyCodes?
-    case NSKeyUp:
-      DarwinSendKeyboardEvents((type == NSKeyDown)?KeyPress:KeyRelease, [e keyCode]);
-      break;
-
-    case NSFlagsChanged:
-      DarwinUpdateModKeys([e modifierFlags]);
-      break;
-    default: break; /* for gcc */
-    }	
+
+	pointer_y -= aquaMenuBarHeight;
+
+	pressure = 0;  // for tablets
+	tilt_x = 0;
+	tilt_y = 0;
+
+	switch (type) {
+		case NSLeftMouseDown:    ev_button=1; ev_type=ButtonPress; goto handle_mouse;
+		case NSOtherMouseDown:   ev_button=2; ev_type=ButtonPress; goto handle_mouse;
+		case NSRightMouseDown:   ev_button=3; ev_type=ButtonPress; goto handle_mouse;
+		case NSLeftMouseUp:      ev_button=1; ev_type=ButtonRelease; goto handle_mouse;
+		case NSOtherMouseUp:     ev_button=2; ev_type=ButtonRelease; goto handle_mouse;
+		case NSRightMouseUp:     ev_button=3; ev_type=ButtonRelease; goto handle_mouse;
+		case NSLeftMouseDragged:  ev_button=1; ev_type=MotionNotify; goto handle_mouse;
+		case NSOtherMouseDragged: ev_button=2; ev_type=MotionNotify; goto handle_mouse;
+		case NSRightMouseDragged: ev_button=3; ev_type=MotionNotify; goto handle_mouse;
+		case NSTabletPoint:
+			pressure = [e pressure];
+			tilt_x = [e tilt].x;
+			tilt_y = [e tilt].y; // fall through
+		case NSMouseMoved: ev_button=0; ev_type=MotionNotify; goto handle_mouse;
+		handle_mouse:
+
+//      if ([e subtype] == NSTabletPointEventSubtype) pressure = [e pressure];
+		DarwinSendPointerEvents(ev_type, ev_button, pointer_x, pointer_y,
+			pressure, tilt_x, tilt_y);
+		break;
+
+		case NSScrollWheel:
+			DarwinSendScrollEvents([e deltaY], pointer_x, pointer_y,
+				pressure, tilt_x, tilt_y);
+		break;
+
+		case NSKeyDown: case NSKeyUp:
+			DarwinSendKeyboardEvents((type == NSKeyDown)?KeyPress:KeyRelease, [e keyCode]);
+		break;
+
+		case NSFlagsChanged:
+			DarwinUpdateModKeys([e modifierFlags]);
+		break;
+		default: break; /* for gcc */
+	}	
 }
commit e9e2d88436597875f102085d216dc0a8fce1450a
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Mar 31 22:55:24 2008 -0700

    moved and renamed QuartzMessageServerThread to
    DarwinSendDDXEvent to make more clear what it actually does.
    (cherry picked from commit bee2b377efc930e25017636e5112093a3a6549c7)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 147b4b4..28bb529 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -1,6 +1,6 @@
 /* X11Application.m -- subclass of NSApplication to multiplex events
  
- Copyright (c) 2002-2007 Apple Inc.
+ Copyright (c) 2002-2008 Apple Inc.
  
  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation files
@@ -166,7 +166,7 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
     static TSMDocumentID x11_document;
 	DEBUG_LOG("state=%d, _x_active=%d, \n", state, _x_active)
     if (state) {
-      QuartzMessageServerThread (kXquartzActivate, 0);
+      DarwinSendDDXEvent(kXquartzActivate, 0);
       
       if (!_x_active) {
 	if (x11_document == 0 && darwinKeymapFile == NULL) {
@@ -178,10 +178,10 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 	if (x11_document != 0)	ActivateTSMDocument (x11_document);
       }
     } else {
-      QuartzMessageServerThread (kXquartzDeactivate, 0);
+      DarwinSendDDXEvent(kXquartzDeactivate, 0);
       
       if (_x_active && x11_document != 0)
-	DeactivateTSMDocument (x11_document);
+		DeactivateTSMDocument (x11_document);
     }
     
     _x_active = state;
@@ -246,7 +246,7 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 	  swallow_up = 0;
 	  for_x = NO;
 #ifdef DARWIN_DDX_MISSING
-	  QuartzMessageServerThread (kXquartzToggleFullscreen, 0);
+	  DarwinSendDDXEvent(kXquartzToggleFullscreen, 0);
 #endif
 	}
       } else {
@@ -271,7 +271,7 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
     case NSApplicationActivatedEventType:
       for_x = NO;
       if ([self modalWindow] == nil) {
-	for_appkit = NO;
+		for_appkit = NO;
 	
 	/* FIXME: hack to avoid having to pass the event to appkit,
 	   which would cause it to raise one of its windows. */
@@ -654,7 +654,7 @@ static NSMutableArray * cfarray_to_nsarray (CFArrayRef in) {
 
 /* This will end up at the end of the responder chain. */
 - (void) copy:sender {
-  QuartzMessageServerThread (kXquartzPasteboardNotify, 1,
+  DarwinSendDDXEvent(kXquartzPasteboardNotify, 1,
 			     AppleWMCopyToPasteboard);
 }
 
diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index aa9fa94..5bf4f4d 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -1,6 +1,6 @@
 /* X11Controller.m -- connect the IB ui, also the NSApp delegate
  
-   Copyright (c) 2002-2007 Apple Inc. All rights reserved.
+   Copyright (c) 2002-2008 Apple Inc. All rights reserved.
  
    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation files
@@ -103,7 +103,7 @@
 {
   [NSApp activateIgnoringOtherApps:YES];
 	
-  QuartzMessageServerThread (kXquartzControllerNotify, 2,
+  DarwinSendDDXEvent(kXquartzControllerNotify, 2,
 			     AppleWMWindowMenuItem, [sender tag]);
 }
 
@@ -254,7 +254,7 @@
   [self remove_window_menu];
   [self install_window_menu:list];
 	
-  QuartzMessageServerThread (kXquartzControllerNotify, 1,
+  DarwinSendDDXEvent(kXquartzControllerNotify, 1,
 			     AppleWMWindowMenuNotify);
 }
 
@@ -539,20 +539,20 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 - (void) hide_window:sender
 {
   if ([X11App x_active])
-    QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMHideWindow);
+    DarwinSendDDXEvent(kXquartzControllerNotify, 1, AppleWMHideWindow);
   else
     NSBeep ();			/* FIXME: something here */
 }
 
 - (IBAction)bring_to_front:sender
 {
-  QuartzMessageServerThread(kXquartzControllerNotify, 1, AppleWMBringAllToFront);
+  DarwinSendDDXEvent(kXquartzControllerNotify, 1, AppleWMBringAllToFront);
 }
 
 - (IBAction)close_window:sender
 {
   if ([X11App x_active])
-    QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMCloseWindow);
+    DarwinSendDDXEvent(kXquartzControllerNotify, 1, AppleWMCloseWindow);
   else
     [[NSApp keyWindow] performClose:sender];
 }
@@ -560,7 +560,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 - (IBAction)minimize_window:sender
 {
   if ([X11App x_active])
-    QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMMinimizeWindow);
+    DarwinSendDDXEvent(kXquartzControllerNotify, 1, AppleWMMinimizeWindow);
   else
     [[NSApp keyWindow] performMiniaturize:sender];
 }
@@ -568,19 +568,19 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 - (IBAction)zoom_window:sender
 {
   if ([X11App x_active])
-    QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMZoomWindow);
+    DarwinSendDDXEvent(kXquartzControllerNotify, 1, AppleWMZoomWindow);
   else
     [[NSApp keyWindow] performZoom:sender];
 }
 
 - (IBAction) next_window:sender
 {
-  QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMNextWindow);
+  DarwinSendDDXEvent(kXquartzControllerNotify, 1, AppleWMNextWindow);
 }
 
 - (IBAction) previous_window:sender
 {
-  QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMPreviousWindow);
+  DarwinSendDDXEvent(kXquartzControllerNotify, 1, AppleWMPreviousWindow);
 }
 
 - (IBAction) enable_fullscreen_changed:sender
@@ -588,7 +588,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
   int value = ![enable_fullscreen intValue];
 	
 #ifdef DARWIN_DDX_MISSING
-  QuartzMessageServerThread (kXquartzSetRootless, 1, value);
+  DarwinSendDDXEvent(kXquartzSetRootless, 1, value);
 #endif
 	
   [NSApp prefs_set_boolean:@PREFS_ROOTLESS value:value];
@@ -598,7 +598,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 - (IBAction) toggle_fullscreen:sender
 {
 #ifdef DARWIN_DDX_MISSING
-  QuartzMessageServerThread (kXquartzToggleFullscreen, 0);
+  DarwinSendDDXEvent(kXquartzToggleFullscreen, 0);
 #endif
 }
 
@@ -661,7 +661,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 
 - (IBAction) quit:sender
 {
-  QuartzMessageServerThread (kXquartzQuit, 0);
+  DarwinSendDDXEvent(kXquartzQuit, 0);
 }
 
 - (IBAction) x11_help:sender
@@ -684,12 +684,12 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 
 - (void) applicationDidHide:(NSNotification *)notify
 {
-  QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMHideAll);
+  DarwinSendDDXEvent(kXquartzControllerNotify, 1, AppleWMHideAll);
 }
 
 - (void) applicationDidUnhide:(NSNotification *)notify
 {
-  QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMShowAll);
+  DarwinSendDDXEvent(kXquartzControllerNotify, 1, AppleWMShowAll);
 }
 
 - (NSApplicationTerminateReply) applicationShouldTerminate:sender
@@ -717,7 +717,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
   [X11App prefs_synchronize];
 	
   /* shutdown the X server, it will exit () for us. */
-  QuartzMessageServerThread (kXquartzQuit, 0);
+  DarwinSendDDXEvent(kXquartzQuit, 0);
 	
   /* In case it doesn't, exit anyway after a while. */
   while (sleep (10) != 0) ;
diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index 8c3cabb..01e6f41 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -1,4 +1,5 @@
 /*
+ * Copyright (C) 2008 Apple, Inc.
  * Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
@@ -120,6 +121,8 @@ enum {
     kXquartzWindowMoved,      // window has moved on screen
 };
 
+void DarwinSendDDXEvent(int type, int argc, ...);
+
 #define ENABLE_DEBUG_LOG 1
 
 #ifdef ENABLE_DEBUG_LOG
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 28a712d..b6cd3f2 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -476,3 +476,31 @@ void DarwinUpdateModKeys(int flags) {
   DarwinUpdateModifiers(KeyPress, ~old_flags & flags);
   old_flags = flags;
 }
+
+
+/*
+ * DarwinSendDDXEvent
+ *  Send the X server thread a message by placing it on the event queue.
+ */
+void DarwinSendDDXEvent(int type, int argc, ...) {
+    xEvent xe;
+    INT32 *argv;
+    int i, max_args;
+    va_list args;
+
+    memset(&xe, 0, sizeof(xe));
+    xe.u.u.type = type;
+    xe.u.clientMessage.u.l.type = type;
+
+    argv = &xe.u.clientMessage.u.l.longs0;
+    max_args = 4;
+
+    if (argc > 0 && argc <= max_args) {
+        va_start (args, argc);
+        for (i = 0; i < argc; i++)
+            argv[i] = (int) va_arg (args, int);
+        va_end (args);
+    }
+
+    mieqEnqueue(NULL, &xe);
+}
diff --git a/hw/xquartz/darwinEvents.h b/hw/xquartz/darwinEvents.h
index 1d8e92a..7c56be9 100644
--- a/hw/xquartz/darwinEvents.h
+++ b/hw/xquartz/darwinEvents.h
@@ -1,4 +1,5 @@
 /*
+ * Copyright (c) 2008 Apple, Inc.
  * Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
@@ -43,4 +44,5 @@ void DarwinUpdateModKeys(int flags);
 
 void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, 
 			int nevents);
+
 #endif  /* _DARWIN_EVENTS_H */
diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index a65bd37..96dc021 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -373,34 +373,3 @@ void QuartzSpaceChanged(uint32_t space_id) {
     /* Do something special here, so we don't depend on quartz-wm for spaces to work... */
     DEBUG_LOG("Space Changed (%u) ... do something interesting...\n", space_id);
 }
-
-/*
- * QuartzMessageServerThread
- *  Send the X server thread a message by placing it on the event queue.
- */
-void
-QuartzMessageServerThread(
-    int type,
-    int argc, ...)
-{
-    xEvent xe;
-    INT32 *argv;
-    int i, max_args;
-    va_list args;
-
-    memset(&xe, 0, sizeof(xe));
-    xe.u.u.type = type;
-    xe.u.clientMessage.u.l.type = type;
-
-    argv = &xe.u.clientMessage.u.l.longs0;
-    max_args = 4;
-
-    if (argc > 0 && argc <= max_args) {
-        va_start (args, argc);
-        for (i = 0; i < argc; i++)
-            argv[i] = (int) va_arg (args, int);
-        va_end (args);
-    }
-
-    mieqEnqueue(NULL, &xe);
-}
diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index 5e14473..91bf25a 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -68,7 +68,7 @@ static void eventHandler(unsigned int type, const void *arg,
     switch (type) {
         case XP_EVENT_DISPLAY_CHANGED:
             DEBUG_LOG("XP_EVENT_DISPLAY_CHANGED\n");
-            QuartzMessageServerThread(kXquartzDisplayChanged, 0);
+            DarwinSendDDXEvent(kXquartzDisplayChanged, 0);
             break;
             
         case XP_EVENT_WINDOW_STATE_CHANGED:
@@ -76,7 +76,7 @@ static void eventHandler(unsigned int type, const void *arg,
                 const xp_window_state_event *ws_arg = arg;
                 
                 DEBUG_LOG("XP_EVENT_WINDOW_STATE_CHANGED: id=%d, state=%d\n", ws_arg->id, ws_arg->state);
-                QuartzMessageServerThread(kXquartzWindowState, 2,
+                DarwinSendDDXEvent(kXquartzWindowState, 2,
                                           ws_arg->id, ws_arg->state);
             } else {
                 DEBUG_LOG("XP_EVENT_WINDOW_STATE_CHANGED: ignored\n");
@@ -88,7 +88,7 @@ static void eventHandler(unsigned int type, const void *arg,
             if (arg_size == sizeof(xp_window_id))  {
                 xp_window_id id = * (xp_window_id *) arg;
                 WindowPtr pWin = xprGetXWindow(id);
-                QuartzMessageServerThread(kXquartzWindowMoved, 1, pWin);
+                DarwinSendDDXEvent(kXquartzWindowMoved, 1, pWin);
             }
             break;
             
@@ -111,7 +111,7 @@ static void eventHandler(unsigned int type, const void *arg,
             ErrorF("XP_EVENT_SPACE_CHANGED\n");
             if(arg_size == sizeof(uint32_t)) {
                 uint32_t space_id = *(uint32_t *)arg;
-                QuartzMessageServerThread(kXquartzSpaceChanged, 1, space_id);
+                DarwinSendDDXEvent(kXquartzSpaceChanged, 1, space_id);
             }
             break;
         default:
commit c1be4e3379d8780dff20390939b657ca0973995a
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Mar 31 21:04:37 2008 -0700

    shovelling code around ...
    (cherry picked from commit 2143182ba49195bbb2e9163ea6872fd68e7a4a85)

diff --git a/dix/main.c b/dix/main.c
index db43473..8f6507f 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -113,6 +113,9 @@ Equipment Corporation.
 #include "dispatch.h"		/* InitProcVectors() */
 #endif
 
+#include <pthread.h>
+pthread_key_t threadname_key=0;
+
 #ifdef DPMSExtension
 #define DPMS_SERVER
 #include <X11/extensions/dpms.h>
@@ -248,6 +251,17 @@ main(int argc, char *argv[], char *envp[])
     char	*xauthfile;
     HWEventQueueType	alwaysCheckForInput[2];
 
+    if(threadname_key == 0) ErrorF("pthread_key_create returned %d\n", pthread_key_create(&threadname_key, NULL));
+    ErrorF("threadname_key = %d\n", threadname_key);
+    if(pthread_getspecific(threadname_key) == NULL) {
+      char *nameptr = malloc(32);
+      sprintf(nameptr, "main thread %d", random());
+      //      strcpy(nameptr, "main thread");
+      ErrorF("calling: pthread_setspecific(%d, %s)=%d\n", threadname_key, nameptr, pthread_setspecific(threadname_key, nameptr));
+      if (pthread_getspecific(threadname_key) != NULL) ErrorF("current thread: %s\n", (char *)pthread_getspecific(threadname_key));
+    } else {
+      if (pthread_getspecific(threadname_key) != NULL) ErrorF("thread was already: %s\n", (char *)pthread_getspecific(threadname_key));
+    }
     display = "0";
 
     InitGlobals();
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 230050f..28a712d 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -52,6 +52,11 @@ in this Software without prior written authorization from The Open Group.
 #include <unistd.h>
 #include <IOKit/hidsystem/IOLLEvent.h>
 
+#define _APPLEWM_SERVER_
+#include "applewmExt.h"
+#include <X11/extensions/applewm.h>
+
+
 /* Fake button press/release for scroll wheel move. */
 #define SCROLLWHEELUPFAKE   4
 #define SCROLLWHEELDOWNFAKE 5
@@ -177,14 +182,103 @@ static void DarwinSimulateMouseClick(
     DarwinUpdateModifiers(KeyPress, modifierMask);
 }
 
+/* Generic handler for Xquartz-specifc events.  When possible, these should
+   be moved into their own individual functions and set as handlers using
+   mieqSetHandler. */
+
 void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents) {
   int i;
 
   DEBUG_LOG("DarwinEventHandler(%d, %p, %p, %d)\n", screenNum, xe, dev, nevents);
   for (i=0; i<nevents; i++) {
-    if (xe[i].u.u.type == kXquartzDeactivate)
-      DarwinReleaseModifiers();
-    QuartzProcessEvent(&xe[i]);
+	switch(xe[i].u.u.type) {
+		case kXquartzControllerNotify:
+            DEBUG_LOG("kXquartzControllerNotify\n");
+            AppleWMSendEvent(AppleWMControllerNotify,
+                             AppleWMControllerNotifyMask,
+                             xe[i].u.clientMessage.u.l.longs0,
+                             xe[i].u.clientMessage.u.l.longs1);
+            break;
+
+        case kXquartzPasteboardNotify:
+            DEBUG_LOG("kXquartzPasteboardNotify\n");
+            AppleWMSendEvent(AppleWMPasteboardNotify,
+                             AppleWMPasteboardNotifyMask,
+                             xe[i].u.clientMessage.u.l.longs0,
+                             xe[i].u.clientMessage.u.l.longs1);
+            break;
+
+        case kXquartzActivate:
+            DEBUG_LOG("kXquartzActivate\n");
+            QuartzShow(xe[i].u.keyButtonPointer.rootX,
+                       xe[i].u.keyButtonPointer.rootY);
+            AppleWMSendEvent(AppleWMActivationNotify,
+                             AppleWMActivationNotifyMask,
+                             AppleWMIsActive, 0);
+            break;
+
+        case kXquartzDeactivate:
+            DEBUG_LOG("kXquartzDeactivate\n");
+      		DarwinReleaseModifiers();
+            AppleWMSendEvent(AppleWMActivationNotify,
+                             AppleWMActivationNotifyMask,
+                             AppleWMIsInactive, 0);
+            QuartzHide();
+            break;
+
+        case kXquartzWindowState:
+            DEBUG_LOG("kXquartzWindowState\n");
+            RootlessNativeWindowStateChanged(xe[i].u.clientMessage.u.l.longs0,
+                                             xe[i].u.clientMessage.u.l.longs1);
+            break;
+
+        case kXquartzWindowMoved:
+            DEBUG_LOG("kXquartzWindowMoved\n");
+            RootlessNativeWindowMoved ((WindowPtr)xe[i].u.clientMessage.u.l.longs0);
+            break;
+
+        case kXquartzToggleFullscreen:
+            DEBUG_LOG("kXquartzToggleFullscreen\n");
+#ifdef DARWIN_DDX_MISSING
+            if (quartzEnableRootless) QuartzSetFullscreen(!quartzHasRoot);
+            else if (quartzHasRoot) QuartzHide();
+            else QuartzShow();
+#else
+    //      ErrorF("kXquartzToggleFullscreen not implemented\n");               
+#endif
+            break;
+
+        case kXquartzSetRootless:
+            DEBUG_LOG("kXquartzSetRootless\n");
+#ifdef DARWIN_DDX_MISSING
+            QuartzSetRootless(xe[i].u.clientMessage.u.l.longs0);
+            if (!quartzEnableRootless && !quartzHasRoot) QuartzHide();
+#else
+    //      ErrorF("kXquartzSetRootless not implemented\n");                    
+#endif
+            break;
+
+        case kXquartzSetRootClip:
+            QuartzSetRootClip((BOOL)xe[i].u.clientMessage.u.l.longs0);
+		     break;
+
+        case kXquartzQuit:
+            GiveUp(0);
+            break;
+
+        case kXquartzBringAllToFront:
+     	    DEBUG_LOG("kXquartzBringAllToFront\n");
+            RootlessOrderAllWindows();
+            break;
+
+		case kXquartzSpaceChanged:
+            DEBUG_LOG("kXquartzSpaceChanged\n");
+            QuartzSpaceChanged(xe[i].u.clientMessage.u.l.longs0);
+
+            break;
+        default:
+            ErrorF("Unknown application defined event type %d.\n", xe[i].u.u.type);
+		}	
   }
 }
 
@@ -199,14 +293,14 @@ Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) {
     mieqSetHandler(kXquartzDeactivate, DarwinEventHandler);
     mieqSetHandler(kXquartzSetRootClip, DarwinEventHandler);
     mieqSetHandler(kXquartzQuit, DarwinEventHandler);
-    mieqSetHandler(kXquartzReadPasteboard, DarwinEventHandler);
-    mieqSetHandler(kXquartzWritePasteboard, DarwinEventHandler);
+    mieqSetHandler(kXquartzReadPasteboard, QuartzReadPasteboard);
+	mieqSetHandler(kXquartzWritePasteboard, QuartzWritePasteboard);
     mieqSetHandler(kXquartzToggleFullscreen, DarwinEventHandler);
     mieqSetHandler(kXquartzSetRootless, DarwinEventHandler);
     mieqSetHandler(kXquartzSpaceChanged, DarwinEventHandler);
     mieqSetHandler(kXquartzControllerNotify, DarwinEventHandler);
     mieqSetHandler(kXquartzPasteboardNotify, DarwinEventHandler);
-    mieqSetHandler(kXquartzDisplayChanged, DarwinEventHandler);
+    mieqSetHandler(kXquartzDisplayChanged, QuartzDisplayChangedHandler);
     mieqSetHandler(kXquartzWindowState, DarwinEventHandler);
     mieqSetHandler(kXquartzWindowMoved, DarwinEventHandler);
 
diff --git a/hw/xquartz/darwinKeyboard.c b/hw/xquartz/darwinKeyboard.c
index 8d1ee8e..355d9f0 100644
--- a/hw/xquartz/darwinKeyboard.c
+++ b/hw/xquartz/darwinKeyboard.c
@@ -730,6 +730,14 @@ static void DarwinBuildModifierMaps(darwinKeyboardInfo *info) {
  *  it to an equivalent X keyboard map and modifier map.
  */
 static void DarwinLoadKeyboardMapping(KeySymsRec *keySyms) {
+  void* callstack[128];
+  int i, frames = backtrace(callstack, 128);
+  char** strs = backtrace_symbols(callstack, frames);
+  for (i = 0; i < frames; ++i) {
+    ErrorF("%s\n", strs[i]);
+  }
+  free(strs);
+
     memset(keyInfo.keyMap, 0, sizeof(keyInfo.keyMap));
 
     /* TODO: Clean this up
diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index ec211cf..a65bd37 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -232,17 +232,17 @@ RREditConnectionInfo (ScreenPtr pScreen)
 #endif
 
 /*
- * QuartzUpdateScreens
+ * QuartzDisplayChangeHandler
  *  Adjust for screen arrangement changes.
  */
-static void QuartzUpdateScreens(void)
+void QuartzDisplayChangedHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents)
 {
     ScreenPtr pScreen;
     WindowPtr pRoot;
     int x, y, width, height, sx, sy;
     xEvent e;
 
-    DEBUG_LOG("QuartzUpdateScreens()\n");
+    DEBUG_LOG("QuartzDisplayChangedHandler()\n");
     if (noPseudoramiXExtension || screenInfo.numScreens != 1)
     {
         /* FIXME: if not using Xinerama, we have multiple screens, and
@@ -308,7 +308,7 @@ static void QuartzUpdateScreens(void)
  *  Calls mode specific screen resume to restore the X clip regions
  *  (if needed) and the X server cursor state.
  */
-static void QuartzShow(
+void QuartzShow(
     int x,      // cursor location
     int y )
 {
@@ -331,7 +331,7 @@ static void QuartzShow(
  *  hidden. Calls mode specific screen suspend to set X clip regions to
  *  prevent drawing (if needed) and restore the Aqua cursor.
  */
-static void QuartzHide(void)
+void QuartzHide(void)
 {
     int i;
 
@@ -350,7 +350,7 @@ static void QuartzHide(void)
  * QuartzSetRootClip
  *  Enable or disable rendering to the X screen.
  */
-static void QuartzSetRootClip(
+void QuartzSetRootClip(
     BOOL enable)
 {
     int i;
@@ -369,7 +369,7 @@ static void QuartzSetRootClip(
  * QuartzSpaceChanged
  *  Unmap offscreen windows, map onscreen windows
  */
-static void QuartzSpaceChanged(uint32_t space_id) {
+void QuartzSpaceChanged(uint32_t space_id) {
     /* Do something special here, so we don't depend on quartz-wm for spaces to work... */
     DEBUG_LOG("Space Changed (%u) ... do something interesting...\n", space_id);
 }
@@ -404,112 +404,3 @@ QuartzMessageServerThread(
 
     mieqEnqueue(NULL, &xe);
 }
-
-
-/*
- * QuartzProcessEvent
- *  Process Quartz specific events.
- */
-void QuartzProcessEvent(xEvent *xe) {
-    switch (xe->u.u.type) {
-        case kXquartzControllerNotify:
-            DEBUG_LOG("kXquartzControllerNotify\n");
-            AppleWMSendEvent(AppleWMControllerNotify,
-                             AppleWMControllerNotifyMask,
-                             xe->u.clientMessage.u.l.longs0,
-                             xe->u.clientMessage.u.l.longs1);
-            break;
-
-        case kXquartzPasteboardNotify:
-            DEBUG_LOG("kXquartzPasteboardNotify\n");
-            AppleWMSendEvent(AppleWMPasteboardNotify,
-                             AppleWMPasteboardNotifyMask,
-                             xe->u.clientMessage.u.l.longs0,
-                             xe->u.clientMessage.u.l.longs1);
-            break;
-
-        case kXquartzActivate:
-            DEBUG_LOG("kXquartzActivate\n");
-            QuartzShow(xe->u.keyButtonPointer.rootX,
-                       xe->u.keyButtonPointer.rootY);
-            AppleWMSendEvent(AppleWMActivationNotify,
-                             AppleWMActivationNotifyMask,
-                             AppleWMIsActive, 0);
-            break;
-
-        case kXquartzDeactivate:
-            DEBUG_LOG("kXquartzDeactivate\n");
-            AppleWMSendEvent(AppleWMActivationNotify,
-                             AppleWMActivationNotifyMask,
-                             AppleWMIsInactive, 0);
-            QuartzHide();
-            break;
-
-        case kXquartzDisplayChanged:
-            DEBUG_LOG("kXquartzDisplayChanged\n");
-            QuartzUpdateScreens();
-            break;
-
-        case kXquartzWindowState:
-            DEBUG_LOG("kXquartzWindowState\n");
-            RootlessNativeWindowStateChanged(xe->u.clientMessage.u.l.longs0,
-		  			     xe->u.clientMessage.u.l.longs1);
-	    break;
-	  
-        case kXquartzWindowMoved:
-            DEBUG_LOG("kXquartzWindowMoved\n");
-            RootlessNativeWindowMoved ((WindowPtr)xe->u.clientMessage.u.l.longs0);
-	    break;
-
-        case kXquartzToggleFullscreen:
-            DEBUG_LOG("kXquartzToggleFullscreen\n");
-#ifdef DARWIN_DDX_MISSING
-            if (quartzEnableRootless) QuartzSetFullscreen(!quartzHasRoot);
-            else if (quartzHasRoot) QuartzHide();
-            else QuartzShow();
-#else
-    //	    ErrorF("kXquartzToggleFullscreen not implemented\n");
-#endif
-            break;
-
-        case kXquartzSetRootless:
-            DEBUG_LOG("kXquartzSetRootless\n");
-#ifdef DARWIN_DDX_MISSING
-            QuartzSetRootless(xe->u.clientMessage.u.l.longs0);
-            if (!quartzEnableRootless && !quartzHasRoot) QuartzHide();
-#else
-    //	    ErrorF("kXquartzSetRootless not implemented\n");
-#endif
-            break;
-
-        case kXquartzSetRootClip:
-            QuartzSetRootClip((BOOL)xe->u.clientMessage.u.l.longs0);
-            break;
-
-        case kXquartzQuit:
-            GiveUp(0);
-            break;
-
-#if 0
-        case kXquartzReadPasteboard:
-            QuartzReadPasteboard();
-            break;
-
-        case kXquartzWritePasteboard:
-            QuartzWritePasteboard();
-            break;
-#endif
-
-        case kXquartzBringAllToFront:
-            DEBUG_LOG("kXquartzBringAllToFront\n");
-            RootlessOrderAllWindows();
-            break;
-
-        case kXquartzSpaceChanged:
-            DEBUG_LOG("kXquartzSpaceChanged\n");
-            QuartzSpaceChanged(xe->u.clientMessage.u.l.longs0);
-            break;
-        default:
-            ErrorF("Unknown application defined event type %d.\n", xe->u.u.type);
-    }
-}
diff --git a/hw/xquartz/quartz.h b/hw/xquartz/quartz.h
index fbe308a..ffe06f9 100644
--- a/hw/xquartz/quartz.h
+++ b/hw/xquartz/quartz.h
@@ -130,5 +130,5 @@ void QuartzInitOutput(int argc,char **argv);
 void QuartzInitInput(int argc, char **argv);
 void QuartzGiveUp(void);
 void QuartzProcessEvent(xEvent *xe);
-
+void QuartzDisplayChangedHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents);
 #endif
commit 985c631b2e1f113039e6e620f030505435fd9815
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Mar 31 20:18:58 2008 -0700

    just a bit of juggling headers around -- we're preparing
    to call our Xquartz-specific event handlers directly
    as mieqHandlers
    (cherry picked from commit 4aedba5aa727e22316e8ca456f7218bea9ee0313)

diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index 8f2511d..002ea41 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -880,7 +880,7 @@ void AbortDDX( void )
  */
 
 void
-xf86SetRootClip (ScreenPtr pScreen, BOOL enable)
+xf86SetRootClip (ScreenPtr pScreen, int enable)
 {
     WindowPtr	pWin = WindowTable[pScreen->myNum];
     WindowPtr	pChild;
diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index 9384b9d..8c3cabb 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -54,7 +54,7 @@ typedef struct {
 void DarwinPrintBanner(void);
 int DarwinParseModifierList(const char *constmodifiers);
 void DarwinAdjustScreenOrigins(ScreenInfo *pScreenInfo);
-void xf86SetRootClip (ScreenPtr pScreen, BOOL enable);
+void xf86SetRootClip (ScreenPtr pScreen, int enable);
 
 #define SCREEN_PRIV(pScreen) ((DarwinFramebufferPtr) \
     dixLookupPrivate(&pScreen->devPrivates, darwinScreenKey))
diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index 5dfdeeb..ec211cf 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -33,6 +33,7 @@
 #endif
 
 #include "quartzCommon.h"
+#include "inputstr.h"
 #include "quartz.h"
 #include "darwin.h"
 #include "darwinEvents.h"
@@ -489,6 +490,7 @@ void QuartzProcessEvent(xEvent *xe) {
             GiveUp(0);
             break;
 
+#if 0
         case kXquartzReadPasteboard:
             QuartzReadPasteboard();
             break;
@@ -496,6 +498,7 @@ void QuartzProcessEvent(xEvent *xe) {
         case kXquartzWritePasteboard:
             QuartzWritePasteboard();
             break;
+#endif
 
         case kXquartzBringAllToFront:
             DEBUG_LOG("kXquartzBringAllToFront\n");
diff --git a/hw/xquartz/quartzCocoa.m b/hw/xquartz/quartzCocoa.m
index 53e3f08..d8f9c69 100644
--- a/hw/xquartz/quartzCocoa.m
+++ b/hw/xquartz/quartzCocoa.m
@@ -37,13 +37,14 @@
 #endif
 
 #include "quartzCommon.h"
+#include "inputstr.h"
 #include "quartzPasteboard.h"
 
 #define BOOL xBOOL
 #include "darwin.h"
-#undef BOOL
 
 #include <Cocoa/Cocoa.h>
+#undef BOOL
 
 #include "pseudoramiX.h"
 
diff --git a/hw/xquartz/quartzPasteboard.c b/hw/xquartz/quartzPasteboard.c
index 0bf84f5..d47047c 100644
--- a/hw/xquartz/quartzPasteboard.c
+++ b/hw/xquartz/quartzPasteboard.c
@@ -34,6 +34,8 @@
 #include <dix-config.h>
 #endif
 
+#include "misc.h"
+#include "inputstr.h"
 #include "quartzPasteboard.h"
 
 #include <X11/Xatom.h>
@@ -76,8 +78,8 @@ static char * QuartzReadCutBuffer(void)
 }
 
 // Write X cut buffer to Mac OS X pasteboard
-// Called by ProcessInputEvents() in response to request from X server thread.
-void QuartzWritePasteboard(void)
+// Called by mieqProcessInputEvents() in response to request from X server thread.
+void QuartzWritePasteboard(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents)
 {
     char *text;
     text = QuartzReadCutBuffer();
@@ -90,8 +92,8 @@ void QuartzWritePasteboard(void)
 #define strequal(a, b) (0 == strcmp((a), (b)))
 
 // Read Mac OS X pasteboard into X cut buffer
-// Called by ProcessInputEvents() in response to request from X server thread.
-void QuartzReadPasteboard(void)
+// Called by mieqProcessInputEvents() in response to request from X server thread.
+void QuartzReadPasteboard(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents)
 {
     char *oldText = QuartzReadCutBuffer();
     char *text = QuartzReadCocoaPasteboard();
diff --git a/hw/xquartz/quartzPasteboard.h b/hw/xquartz/quartzPasteboard.h
index d6a8ee8..b51cd88 100644
--- a/hw/xquartz/quartzPasteboard.h
+++ b/hw/xquartz/quartzPasteboard.h
@@ -34,11 +34,11 @@
 #define _QUARTZPASTEBOARD_H
 
 // Aqua->X 
-void QuartzReadPasteboard(void);
+void QuartzReadPasteboard(int, xEventPtr, DeviceIntPtr, int);
 char * QuartzReadCocoaPasteboard(void);	// caller must free string
 
 // X->Aqua
-void QuartzWritePasteboard(void);
+void QuartzWritePasteboard(int, xEventPtr, DeviceIntPtr, int);
 void QuartzWriteCocoaPasteboard(char *text);
 
 #endif	/* _QUARTZPASTEBOARD_H */
diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index b653a6e..5e14473 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -32,6 +32,7 @@
 #endif
 
 #include "quartzCommon.h"
+#include "inputstr.h"
 #include "quartz.h"
 #include "xpr.h"
 #include "pseudoramiX.h"
commit 89f1d880e83e32b72d35c4dbd6795defa6efa847
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Mar 31 19:47:28 2008 -0700

    nuke DarwinEventQueue
    (cherry picked from commit 1e0ec02202eeaffae480048b91bf02140ee29f8a)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 5b037d2..230050f 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -56,28 +56,10 @@ in this Software without prior written authorization from The Open Group.
 #define SCROLLWHEELUPFAKE   4
 #define SCROLLWHEELDOWNFAKE 5
 
-#define QUEUE_SIZE 256
-
-typedef struct _Event {
-    xEvent      event;
-    ScreenPtr   pScreen;
-} EventRec, *EventPtr;
-
 int input_check_zero, input_check_flag;
 
 static int old_flags = 0;  // last known modifier state
 
-typedef struct _EventQueue {
-    HWEventQueueType    head, tail; /* long for SetInputCheck */
-    CARD32      lastEventTime;      /* to avoid time running backwards */
-    Bool        lastMotion;
-    EventRec    events[QUEUE_SIZE]; /* static allocation for signals */
-    DevicePtr   pKbd, pPtr;         /* device pointer, to get funcs */
-    ScreenPtr   pEnqueueScreen;     /* screen events are being delivered to */
-    ScreenPtr   pDequeueScreen;     /* screen events are being dispatched to */
-} EventQueueRec, *EventQueuePtr;
-
-static EventQueueRec darwinEventQueue;
 xEvent *darwinEvents = NULL;
 
 /*
@@ -231,21 +213,6 @@ Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) {
     return TRUE;
 }
 
-
-/*
- * DarwinEQEnqueue
- *  Must be thread safe with ProcessInputEvents.
- *    DarwinEQEnqueue    - called from event gathering thread
- *    ProcessInputEvents - called from X server thread
- *  DarwinEQEnqueue should never be called from more than one thread.
- * 
- * This should be deprecated in favor of miEQEnqueue -- BB
- */
-void DarwinEQEnqueue(const xEventPtr e) {
-  mieqEnqueue(NULL, e);
-  DarwinPokeEQ();
-}
-
 /*
  * ProcessInputEvents
  *  Read and process events from the event queue until it is empty.
diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index 971c9b2..5dfdeeb 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -401,7 +401,7 @@ QuartzMessageServerThread(
         va_end (args);
     }
 
-    DarwinEQEnqueue(&xe);
+    mieqEnqueue(NULL, &xe);
 }
 
 
commit 8944b77ec0c18476a25ba3179bcc45b338be22b8
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 2 17:47:42 2008 -0700

    continue with gutting darwinEvents.c
    (cherry picked from commit c34fce7051b996633291dddc061b696ff737f3fb)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 46f5675..5b037d2 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -78,7 +78,7 @@ typedef struct _EventQueue {
 } EventQueueRec, *EventQueuePtr;
 
 static EventQueueRec darwinEventQueue;
-xEvent *darwinEvents;
+xEvent *darwinEvents = NULL;
 
 /*
  * DarwinPressModifierMask
@@ -207,8 +207,11 @@ void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int neven
 }
 
 Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) { 
+    if (!darwinEvents)
+        darwinEvents = (xEvent *)xcalloc(sizeof(xEvent), GetMaximumEventsNum());
+    if (!darwinEvents)
+        FatalError("Couldn't allocate event buffer\n");
 
-    darwinEvents = (xEvent *)malloc(sizeof(xEvent) * GetMaximumEventsNum());
     mieqInit();
     mieqSetHandler(kXquartzActivate, DarwinEventHandler);
     mieqSetHandler(kXquartzDeactivate, DarwinEventHandler);
@@ -225,13 +228,6 @@ Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) {
     mieqSetHandler(kXquartzWindowState, DarwinEventHandler);
     mieqSetHandler(kXquartzWindowMoved, DarwinEventHandler);
 
-    darwinEventQueue.head = darwinEventQueue.tail = 0;
-    darwinEventQueue.lastEventTime = GetTimeInMillis ();
-    darwinEventQueue.pKbd = pKbd;
-    darwinEventQueue.pPtr = pPtr;
-    darwinEventQueue.pEnqueueScreen = screenInfo.screens[0];
-    darwinEventQueue.pDequeueScreen = darwinEventQueue.pEnqueueScreen;
-    SetInputCheck(&input_check_zero, &input_check_flag);
     return TRUE;
 }
 
@@ -255,8 +251,6 @@ void DarwinEQEnqueue(const xEventPtr e) {
  *  Read and process events from the event queue until it is empty.
  */
 void ProcessInputEvents(void) {
-    EventRec *e;
-    int     x, y;
     xEvent  xe;
     // button number and modifier mask of currently pressed fake button
     input_check_flag=0;
@@ -265,92 +259,11 @@ void ProcessInputEvents(void) {
     mieqProcessInputEvents();
 
     // Empty the signaling pipe
-    x = sizeof(xe);
-    while (x == sizeof(xe)) 
-        x = read(darwinEventReadFD, &xe, sizeof(xe));
-
-    while (darwinEventQueue.head != darwinEventQueue.tail)
-    {
-        if (screenIsSaved == SCREEN_SAVER_ON)
-            dixSaveScreens (serverClient, SCREEN_SAVER_OFF, ScreenSaverReset);
-
-        e = &darwinEventQueue.events[darwinEventQueue.head];
-        xe = e->event;
-
-        // Shift from global screen coordinates to coordinates relative to
-        // the origin of the current screen.
-        xe.u.keyButtonPointer.rootX -= darwinMainScreenX +
-                dixScreenOrigins[miPointerCurrentScreen()->myNum].x;
-        xe.u.keyButtonPointer.rootY -= darwinMainScreenY +
-                dixScreenOrigins[miPointerCurrentScreen()->myNum].y;
-	
-	/*	ErrorF("old rootX = (%d,%d) darwinMainScreen = (%d,%d) dixScreenOrigins[%d]=(%d,%d)\n",
-	       xe.u.keyButtonPointer.rootX, xe.u.keyButtonPointer.rootY,
-	       darwinMainScreenX, darwinMainScreenY,
-	       miPointerCurrentScreen()->myNum,
-	       dixScreenOrigins[miPointerCurrentScreen()->myNum].x,
-	       dixScreenOrigins[miPointerCurrentScreen()->myNum].y); */
-
-	//Assumption - screen switching can only occur on motion events
-
-        if (e->pScreen != darwinEventQueue.pDequeueScreen)
-        {
-            darwinEventQueue.pDequeueScreen = e->pScreen;
-            x = xe.u.keyButtonPointer.rootX;
-            y = xe.u.keyButtonPointer.rootY;
-            if (darwinEventQueue.head == QUEUE_SIZE - 1)
-                darwinEventQueue.head = 0;
-            else
-                ++darwinEventQueue.head;
-            NewCurrentScreen (darwinEventQueue.pDequeueScreen, x, y);
-        }
-        else
-        {
-            if (darwinEventQueue.head == QUEUE_SIZE - 1)
-                darwinEventQueue.head = 0;
-            else
-                ++darwinEventQueue.head;
-            switch (xe.u.u.type) {
-            case KeyPress:
-            case KeyRelease:
-	      ErrorF("Unexpected Keyboard event in DarwinProcessInputEvents\n");
-	      break;
-
-            case ButtonPress:
-	      ErrorF("Unexpected ButtonPress event in DarwinProcessInputEvents\n");
-                break;
-
-            case ButtonRelease:
-	      ErrorF("Unexpected ButtonRelease event in DarwinProcessInputEvents\n");
-                break;
-
-            case MotionNotify:
-	      ErrorF("Unexpected MotionNotify event in DarwinProcessInputEvents\n");
-                break;
-
-            case kXquartzUpdateModifiers:
-	      ErrorF("Unexpected kXquartzUpdateModifiers event in DarwinProcessInputEvents\n");
-	      break;
-
-            case kXquartzUpdateButtons:
-	      ErrorF("Unexpected kXquartzUpdateButtons event in DarwinProcessInputEvents\n");
-	      break;
-
-            case kXquartzScrollWheel: 
-	      ErrorF("Unexpected kXquartzScrollWheel event in DarwinProcessInputEvents\n");
-	      break;
-
-			case kXquartzDeactivate:
-				DarwinReleaseModifiers();
-				// fall through
-            default:
-                // Check for mode specific event
-                QuartzProcessEvent(&xe);
-            }
-        }
+    int x = sizeof(xe);
+    while (x == sizeof(xe)) {
+      DEBUG_LOG("draining pipe\n");
+      x = read(darwinEventReadFD, &xe, sizeof(xe));
     }
-
-    //    miPointerUpdate();
 }
 
 /* Sends a null byte down darwinEventWriteFD, which will cause the
@@ -368,6 +281,10 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
   static int darwinFakeMouseButtonMask = 0;
   int i, num_events;
 
+	if(!darwinEvents) {
+		ErrorF("DarwinSendPointerEvents called before darwinEvents was initialized\n");
+		return;
+	}
   /* I can't find a spec for this, but at least GTK expects that tablets are
      just like mice, except they have either one or three extra valuators, in this
      order:
@@ -421,6 +338,11 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
 
 void DarwinSendKeyboardEvents(int ev_type, int keycode) {
   int i, num_events;
+	if(!darwinEvents) {
+		ErrorF("DarwinSendKeyboardEvents called before darwinEvents was initialized\n");
+		return;
+	}
+
   if (old_flags == 0 && darwinSyncKeymap && darwinKeymapFile == NULL) {
     /* See if keymap has changed. */
 
@@ -447,6 +369,11 @@ void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y,
 		      tilt_x * INT32_MAX * 1.0f, 
 		      tilt_y * INT32_MAX * 1.0f};
 
+  if(!darwinEvents) {
+		ErrorF("DarwinSendProximityvents called before darwinEvents was initialized\n");
+		return;
+}
+
   num_events = GetProximityEvents(darwinEvents, darwinPointer, ev_type,
 				0, 5, valuators);
       
@@ -465,6 +392,11 @@ void DarwinSendScrollEvents(float count, int pointer_x, int pointer_y,
 		      tilt_x * INT32_MAX * 1.0f, 
 		      tilt_y * INT32_MAX * 1.0f};
 
+	if(!darwinEvents) {
+		ErrorF("DarwinSendScrollEvents called before darwinEvents was initialized\n");
+		return;
+	}
+
   for (count = fabs(count); count > 0.0; count = count - 1.0f) {
     int num_events = GetPointerEvents(darwinEvents, darwinPointer, ButtonPress, ev_button, 
 				      POINTER_ABSOLUTE, 0, 5, valuators);
commit aa6d12e93e8661da841192ef7c3aa7c6a7731c7f
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 2 17:46:59 2008 -0700

    turns out we weren't actually using these files. oops
    (cherry picked from commit bfec44d7b4baf0ad0aae55c8209bc60ac93c5b58)

diff --git a/hw/xquartz/Makefile.am b/hw/xquartz/Makefile.am
index 99d23eb..0753824 100644
--- a/hw/xquartz/Makefile.am
+++ b/hw/xquartz/Makefile.am
@@ -50,8 +50,6 @@ EXTRA_DIST = \
 	quartz.h \
 	quartzAudio.h \
 	quartzCommon.h \
-	quartzCursor.c \
-	quartzCursor.h \
 	quartzForeground.h \
 	quartzKeyboard.h \
 	quartzPasteboard.h
diff --git a/hw/xquartz/quartzCursor.c b/hw/xquartz/quartzCursor.c
deleted file mode 100644
index 10e671a..0000000
--- a/hw/xquartz/quartzCursor.c
+++ /dev/null
@@ -1,646 +0,0 @@
-/**************************************************************
- *
- * Support for using the Quartz Window Manager cursor
- *
- * Copyright (c) 2001-2003 Torrey T. Lyons and Greg Parker.
- *                 All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "quartzCommon.h"
-#include "quartzCursor.h"
-#include "darwin.h"
-
-#include <pthread.h>
-
-#include "mi.h"
-#include "scrnintstr.h"
-#include "cursorstr.h"
-#include "mipointrst.h"
-#include "globals.h"
-
-// Size of the QuickDraw cursor
-#define CURSORWIDTH 16
-#define CURSORHEIGHT 16
-
-typedef struct {
-    int                     qdCursorMode;
-    int                     qdCursorVisible;
-    int                     useQDCursor;
-    QueryBestSizeProcPtr    QueryBestSize;
-    miPointerSpriteFuncPtr  spriteFuncs;
-} QuartzCursorScreenRec, *QuartzCursorScreenPtr;
-
-static DevPrivateKey darwinCursorScreenKey = &darwinCursorScreenKey;
-static CursorPtr quartzLatentCursor = NULL;
-static QD_Cursor gQDArrow; // QuickDraw arrow cursor
-
-// Cursor for the main thread to set (NULL = arrow cursor).
-static CCrsrHandle currentCursor = NULL;
-static pthread_mutex_t cursorMutex;
-static pthread_cond_t cursorCondition;
-
-#define CURSOR_PRIV(pScreen) ((QuartzCursorScreenPtr) \
-    dixLookupPrivate(&pScreen->devPrivates, darwinCursorScreenKey))
-
-#define HIDE_QD_CURSOR(pScreen, visible)                                \
-    if (visible) {                                                      \
-        int ix;                                                         \
-        for (ix = 0; ix < QUARTZ_PRIV(pScreen)->displayCount; ix++) {   \
-            CGDisplayHideCursor(QUARTZ_PRIV(pScreen)->displayIDs[ix]);  \
-        }                                                               \
-        visible = FALSE;                                                \
-    } ((void)0)
-
-#define SHOW_QD_CURSOR(pScreen, visible)                                \
-    {                                                                   \
-        int ix;                                                         \
-        for (ix = 0; ix < QUARTZ_PRIV(pScreen)->displayCount; ix++) {   \
-            CGDisplayShowCursor(QUARTZ_PRIV(pScreen)->displayIDs[ix]);  \
-        }                                                               \
-        visible = TRUE;                                                 \
-    } ((void)0)
-
-#define CHANGE_QD_CURSOR(cursorH)                                       \
-    if (!quartzServerQuitting) {                                        \
-        /* Acquire lock and tell the main thread to change cursor */    \
-        pthread_mutex_lock(&cursorMutex);                               \
-        currentCursor = (CCrsrHandle) (cursorH);                        \
-        QuartzMessageMainThread(kQuartzCursorUpdate, NULL, 0);          \
-                                                                        \
-        /* Wait for the main thread to change the cursor */             \
-        pthread_cond_wait(&cursorCondition, &cursorMutex);              \
-        pthread_mutex_unlock(&cursorMutex);                             \
-    } ((void)0)
-
-
-/*
- * MakeQDCursor helpers: CTAB_ENTER, interleave
- */
-
-// Add a color entry to a ctab
-#define CTAB_ENTER(ctab, index, r, g, b)                                \
-    ctab->ctTable[index].value = index;                                 \
-    ctab->ctTable[index].rgb.red = r;                                   \
-    ctab->ctTable[index].rgb.green = g;                                 \
-    ctab->ctTable[index].rgb.blue = b
-
-// Make an unsigned short by interleaving the bits of bytes c1 and c2.
-// High bit of c1 is first; low bit of c2 is last.
-// Interleave is a built-in INTERCAL operator.
-static unsigned short
-interleave(
-    unsigned char c1,
-    unsigned char c2 )
-{
-    return
-        ((c1 & 0x80) << 8) | ((c2 & 0x80) << 7) |
-        ((c1 & 0x40) << 7) | ((c2 & 0x40) << 6) |
-        ((c1 & 0x20) << 6) | ((c2 & 0x20) << 5) |
-        ((c1 & 0x10) << 5) | ((c2 & 0x10) << 4) |
-        ((c1 & 0x08) << 4) | ((c2 & 0x08) << 3) |
-        ((c1 & 0x04) << 3) | ((c2 & 0x04) << 2) |
-        ((c1 & 0x02) << 2) | ((c2 & 0x02) << 1) |
-        ((c1 & 0x01) << 1) | ((c2 & 0x01) << 0) ;
-}
-
-/*
- * MakeQDCursor
- * Make a QuickDraw color cursor from the given X11 cursor.
- * Warning: This code is nasty. Color cursors were meant to be read
- * from resources; constructing the structures programmatically is messy.
- */
-/*
-    QuickDraw cursor representation:
-    Our color cursor is a 2 bit per pixel pixmap.
-    Each pixel's bits are (source<<1 | mask) from the original X cursor pixel.
-    The cursor's color table maps the colors like this:
-    (2-bit value | X result    | colortable | Mac result)
-             00  | transparent | white      | transparent (white outside mask)
-             01  | back color  | back color | back color
-             10  | undefined   | black      | invert background (just for fun)
-             11  | fore color  | fore color | fore color
-*/
-static CCrsrHandle
-MakeQDCursor(
-    CursorPtr pCursor )
-{
-    CCrsrHandle result;
-    CCrsrPtr curs;
-    int i, w, h;
-    unsigned short rowMask;
-    PixMap *pix;
-    ColorTable *ctab;
-    unsigned short *image;
-
-    result = (CCrsrHandle) NewHandleClear(sizeof(CCrsr));
-    if (!result) return NULL;
-    HLock((Handle)result);
-    curs = *result;
-
-    // Initialize CCrsr
-    curs->crsrType = 0x8001;     // 0x8000 = b&w, 0x8001 = color
-    curs->crsrMap = (PixMapHandle) NewHandleClear(sizeof(PixMap));
-    if (!curs->crsrMap) goto pixAllocFailed;
-    HLock((Handle)curs->crsrMap);
-    pix = *curs->crsrMap;
-    curs->crsrData = NULL;       // raw cursor image data (set below)
-    curs->crsrXData = NULL;      // QD's processed data
-    curs->crsrXValid = 0;        // zero means QD must re-process cursor data
-    curs->crsrXHandle = NULL;    // reserved
-    memset(curs->crsr1Data, 0, CURSORWIDTH*CURSORHEIGHT/8); // b&w data
-    memset(curs->crsrMask,  0, CURSORWIDTH*CURSORHEIGHT/8); // b&w & color mask
-    curs->crsrHotSpot.h = min(CURSORWIDTH,  pCursor->bits->xhot); // hot spot
-    curs->crsrHotSpot.v = min(CURSORHEIGHT, pCursor->bits->yhot); // hot spot
-    curs->crsrXTable = 0;        // reserved
-    curs->crsrID = GetCTSeed();  // unique ID from Color Manager
-
-    // Set the b&w data and mask
-    w = min(pCursor->bits->width,  CURSORWIDTH);
-    h = min(pCursor->bits->height, CURSORHEIGHT);
-    rowMask = ~((1 << (CURSORWIDTH - w)) - 1);
-    for (i = 0; i < h; i++) {
-        curs->crsr1Data[i] = rowMask &
-        ((pCursor->bits->source[i*4]<<8) | pCursor->bits->source[i*4+1]);
-        curs->crsrMask[i] = rowMask &
-        ((pCursor->bits->mask[i*4]<<8)   | pCursor->bits->mask[i*4+1]);
-    }
-
-    // Set the color data and mask
-    // crsrMap: defines bit depth and size and colortable only
-    pix->rowBytes = (CURSORWIDTH * 2 / 8) | 0x8000; // last bit on means PixMap
-    SetRect(&pix->bounds, 0, 0, CURSORWIDTH, CURSORHEIGHT); // see TN 1020
-    pix->pixelSize = 2;
-    pix->cmpCount = 1;
-    pix->cmpSize = 2;
-    // pix->pmTable set below
-
-    // crsrData is the pixel data. crsrMap's baseAddr is not used.
-    curs->crsrData = NewHandleClear(CURSORWIDTH*CURSORHEIGHT * 2 / 8);
-    if (!curs->crsrData) goto imageAllocFailed;
-    HLock((Handle)curs->crsrData);
-    image = (unsigned short *) *curs->crsrData;
-    // Pixel data is just 1-bit data and mask interleaved (see above)
-    for (i = 0; i < h; i++) {
-        unsigned char s, m;
-        s = pCursor->bits->source[i*4] & (rowMask >> 8);
-        m = pCursor->bits->mask[i*4] & (rowMask >> 8);
-        image[2*i] = interleave(s, m);
-        s = pCursor->bits->source[i*4+1] & (rowMask & 0x00ff);
-        m = pCursor->bits->mask[i*4+1] & (rowMask & 0x00ff);
-        image[2*i+1] = interleave(s, m);
-    }
-
-    // Build the color table (entries described above)
-    // NewPixMap allocates a color table handle.
-    pix->pmTable = (CTabHandle) NewHandleClear(sizeof(ColorTable) + 3
-                    * sizeof(ColorSpec));
-    if (!pix->pmTable) goto ctabAllocFailed;
-    HLock((Handle)pix->pmTable);
-    ctab = *pix->pmTable;
-    ctab->ctSeed = GetCTSeed();
-    ctab->ctFlags = 0;
-    ctab->ctSize = 3; // color count - 1
-    CTAB_ENTER(ctab, 0, 0xffff, 0xffff, 0xffff);
-    CTAB_ENTER(ctab, 1, pCursor->backRed, pCursor->backGreen,
-               pCursor->backBlue);
-    CTAB_ENTER(ctab, 2, 0x0000, 0x0000, 0x0000);
-    CTAB_ENTER(ctab, 3, pCursor->foreRed, pCursor->foreGreen,
-               pCursor->foreBlue);
-
-    HUnlock((Handle)pix->pmTable); // ctab
-    HUnlock((Handle)curs->crsrData); // image data
-    HUnlock((Handle)curs->crsrMap); // pix
-    HUnlock((Handle)result); // cursor
-
-    return result;
-
-    // "What we have here is a failure to allocate"
-ctabAllocFailed:
-    HUnlock((Handle)curs->crsrData);
-    DisposeHandle((Handle)curs->crsrData);
-imageAllocFailed:
-    HUnlock((Handle)curs->crsrMap);
-    DisposeHandle((Handle)curs->crsrMap);
-pixAllocFailed:
-    HUnlock((Handle)result);
-    DisposeHandle((Handle)result);
-    return NULL;
-}
-
-
-/*
- * FreeQDCursor
- * Destroy a QuickDraw color cursor created with MakeQDCursor().
- * The cursor must not currently be on screen.
- */
-static void FreeQDCursor(CCrsrHandle cursHandle)
-{
-    CCrsrPtr curs;
-    PixMap *pix;
-
-    HLock((Handle)cursHandle);
-    curs = *cursHandle;
-    HLock((Handle)curs->crsrMap);
-    pix = *curs->crsrMap;
-    DisposeHandle((Handle)pix->pmTable);
-    HUnlock((Handle)curs->crsrMap);
-    DisposeHandle((Handle)curs->crsrMap);
-    DisposeHandle((Handle)curs->crsrData);
-    HUnlock((Handle)cursHandle);
-    DisposeHandle((Handle)cursHandle);
-}
-
-
-/*
-===========================================================================
-
- Pointer sprite functions
-
-===========================================================================
-*/
-
-/*
- * QuartzRealizeCursor
- * Convert the X cursor representation to QuickDraw format if possible.
- */
-Bool
-QuartzRealizeCursor(
-    ScreenPtr pScreen,
-    CursorPtr pCursor )
-{
-    CCrsrHandle qdCursor;
-    QuartzCursorScreenPtr ScreenPriv = CURSOR_PRIV(pScreen);
-
-    if(!pCursor || !pCursor->bits)
-        return FALSE;
-
-    // if the cursor is too big we use a software cursor
-    if ((pCursor->bits->height > CURSORHEIGHT) ||
-        (pCursor->bits->width > CURSORWIDTH) || !ScreenPriv->useQDCursor)
-    {
-        if (quartzRootless) {
-            // rootless can't use a software cursor
-            return TRUE;
-        } else {
-            return (*ScreenPriv->spriteFuncs->RealizeCursor)
-                        (pScreen, pCursor);
-        }
-    }
-
-    // make new cursor image
-    qdCursor = MakeQDCursor(pCursor);
-    if (!qdCursor) return FALSE;
-
-    // save the result
-    dixSetPrivate(&pCursor->devPrivates, pScreen, qdCursor);
-
-    return TRUE;
-}
-
-
-/*
- * QuartzUnrealizeCursor
- * Free the storage space associated with a realized cursor.
- */
-Bool
-QuartzUnrealizeCursor(
-    ScreenPtr pScreen,
-    CursorPtr pCursor )
-{
-    QuartzCursorScreenPtr ScreenPriv = CURSOR_PRIV(pScreen);
-
-    if ((pCursor->bits->height > CURSORHEIGHT) ||
-        (pCursor->bits->width > CURSORWIDTH) || !ScreenPriv->useQDCursor)
-    {
-        if (quartzRootless) {
-            return TRUE;
-        } else {
-            return (*ScreenPriv->spriteFuncs->UnrealizeCursor)
-                        (pScreen, pCursor);
-        }
-    } else {
-        CCrsrHandle oldCursor = dixLookupPrivate(&pCursor->devPrivates,
-						 pScreen);
-        if (currentCursor != oldCursor) {
-            // This should only fail when quitting, in which case we just leak.
-            FreeQDCursor(oldCursor);
-        }
-	dixSetPrivate(&pCursor->devPrivates, pScreen, NULL);
-        return TRUE;
-    }
-}
-
-
-/*
- * QuartzSetCursor
- * Set the cursor sprite and position.
- * Use QuickDraw cursor if possible.
- */
-static void
-QuartzSetCursor(
-    ScreenPtr       pScreen,
-    CursorPtr       pCursor,
-    int             x,
-    int             y)
-{
-    QuartzCursorScreenPtr ScreenPriv = CURSOR_PRIV(pScreen);
-
-    quartzLatentCursor = pCursor;
-
-    // Don't touch Mac OS cursor if X is hidden!
-    if (!quartzServerVisible)
-        return;
-
-    if (!pCursor) {
-        // Remove the cursor completely.
-        HIDE_QD_CURSOR(pScreen, ScreenPriv->qdCursorVisible);
-        if (! ScreenPriv->qdCursorMode)
-            (*ScreenPriv->spriteFuncs->SetCursor)(pScreen, 0, x, y);
-    }
-    else if ((pCursor->bits->height <= CURSORHEIGHT) &&
-             (pCursor->bits->width <= CURSORWIDTH) && ScreenPriv->useQDCursor)
-    {
-        // Cursor is small enough to use QuickDraw directly.
-        if (! ScreenPriv->qdCursorMode)    // remove the X cursor
-            (*ScreenPriv->spriteFuncs->SetCursor)(pScreen, 0, x, y);
-        ScreenPriv->qdCursorMode = TRUE;
-
-        CHANGE_QD_CURSOR(dixLookupPrivate(&pCursor->devPrivates, pScreen));
-        SHOW_QD_CURSOR(pScreen, ScreenPriv->qdCursorVisible);
-    }
-    else if (quartzRootless) {
-        // Rootless can't use a software cursor, so we just use Mac OS arrow.
-        CHANGE_QD_CURSOR(NULL);
-        SHOW_QD_CURSOR(pScreen, ScreenPriv->qdCursorVisible);
-    }
-    else {
-        // Cursor is too big for QuickDraw. Use X software cursor.
-        HIDE_QD_CURSOR(pScreen, ScreenPriv->qdCursorVisible);
-        ScreenPriv->qdCursorMode = FALSE;
-        (*ScreenPriv->spriteFuncs->SetCursor)(pScreen, pCursor, x, y);
-    }
-}
-
-
-/*
- * QuartzReallySetCursor
- * Set the QuickDraw cursor. Called from the main thread since changing the
- * cursor with QuickDraw is not thread safe on dual processor machines.
- */
-void
-QuartzReallySetCursor()
-{
-    pthread_mutex_lock(&cursorMutex);
-
-    if (currentCursor) {
-        SetCCursor(currentCursor);
-    } else {
-        SetCursor(&gQDArrow);
-    }
-
-    pthread_cond_signal(&cursorCondition);
-    pthread_mutex_unlock(&cursorMutex);
-}
-
-
-/*
- * QuartzMoveCursor
- * Move the cursor. This is a noop for QuickDraw.
- */
-static void
-QuartzMoveCursor(
-    ScreenPtr   pScreen,
-    int         x,
-    int         y)
-{
-    QuartzCursorScreenPtr ScreenPriv = CURSOR_PRIV(pScreen);
-
-    // only the X cursor needs to be explicitly moved
-    if (!ScreenPriv->qdCursorMode)
-        (*ScreenPriv->spriteFuncs->MoveCursor)(pScreen, x, y);
-}
-
-
-static miPointerSpriteFuncRec quartzSpriteFuncsRec = {
-    QuartzRealizeCursor,
-    QuartzUnrealizeCursor,
-    QuartzSetCursor,
-    QuartzMoveCursor
-};
-
-
-/*
-===========================================================================
-
- Pointer screen functions
-
-===========================================================================
-*/
-
-/*
- * QuartzCursorOffScreen
- */
-static Bool QuartzCursorOffScreen(ScreenPtr *pScreen, int *x, int *y)
-{
-    return FALSE;
-}
-
-
-/*
- * QuartzCrossScreen
- */
-static void QuartzCrossScreen(ScreenPtr pScreen, Bool entering)
-{
-    return;
-}
-
-
-/*
- * QuartzWarpCursor
- *  Change the cursor position without generating an event or motion history.
- *  The input coordinates (x,y) are in pScreen-local X11 coordinates.
- *
- */
-static void
-QuartzWarpCursor(
-    ScreenPtr               pScreen,
-    int                     x,
-    int                     y)
-{
-    static int              neverMoved = TRUE;
-
-    if (neverMoved) {
-        // Don't move the cursor the first time. This is the jump-to-center
-        // initialization, and it's annoying because we may still be in MacOS.
-        neverMoved = FALSE;
-        return;
-    }
-
-    if (quartzServerVisible) {
-        CGDisplayErr        cgErr;
-        CGPoint             cgPoint;
-        // Only need to do this for one display. Any display will do.
-        CGDirectDisplayID   cgID = QUARTZ_PRIV(pScreen)->displayIDs[0];
-        CGRect              cgRect = CGDisplayBounds(cgID);
-
-        // Convert (x,y) to CoreGraphics screen-local CG coordinates.
-        // This is necessary because the X11 screen and CG screen may not
-        // coincide. (e.g. X11 screen may be moved to dodge the menu bar)
-
-        // Make point in X11 global coordinates
-        cgPoint = CGPointMake(x + dixScreenOrigins[pScreen->myNum].x,
-                              y + dixScreenOrigins[pScreen->myNum].y);
-        // Shift to CoreGraphics global screen coordinates
-        cgPoint.x += darwinMainScreenX;
-        cgPoint.y += darwinMainScreenY;
-        // Shift to CoreGraphics screen-local coordinates
-        cgPoint.x -= cgRect.origin.x;
-        cgPoint.y -= cgRect.origin.y;
-
-        cgErr = CGDisplayMoveCursorToPoint(cgID, cgPoint);
-        if (cgErr != CGDisplayNoErr) {
-            ErrorF("Could not set cursor position with error code 0x%x.\n",
-                    cgErr);
-        }
-    }
-
-    miPointerWarpCursor(pScreen, x, y);
-    miPointerUpdate();
-}
-
-
-static miPointerScreenFuncRec quartzScreenFuncsRec = {
-    QuartzCursorOffScreen,
-    QuartzCrossScreen,
-    QuartzWarpCursor,
-    NULL,
-    NULL 
-};
-
-
-/*
-===========================================================================
-
- Other screen functions
-
-===========================================================================
-*/
-
-/*
- * QuartzCursorQueryBestSize
- * Handle queries for best cursor size
- */
-static void
-QuartzCursorQueryBestSize(
-   int              class,
-   unsigned short   *width,
-   unsigned short   *height,
-   ScreenPtr        pScreen)
-{
-    QuartzCursorScreenPtr ScreenPriv = CURSOR_PRIV(pScreen);
-
-    if (class == CursorShape) {
-        *width = CURSORWIDTH;
-        *height = CURSORHEIGHT;
-    } else {
-        (*ScreenPriv->QueryBestSize)(class, width, height, pScreen);
-    }
-}
-
-
-/*
- * QuartzInitCursor
- * Initialize cursor support
- */
-Bool
-QuartzInitCursor(
-    ScreenPtr   pScreen )
-{
-    QuartzCursorScreenPtr   ScreenPriv;
-    miPointerScreenPtr      PointPriv;
-    DarwinFramebufferPtr    dfb = SCREEN_PRIV(pScreen);
-
-    // initialize software cursor handling (always needed as backup)
-    if (!miDCInitialize(pScreen, &quartzScreenFuncsRec)) {
-        return FALSE;
-    }
-
-    ScreenPriv = xcalloc( 1, sizeof(QuartzCursorScreenRec) );
-    if (!ScreenPriv) return FALSE;
-
-    CURSOR_PRIV(pScreen) = ScreenPriv;
-
-    // override some screen procedures
-    ScreenPriv->QueryBestSize = pScreen->QueryBestSize;
-    pScreen->QueryBestSize = QuartzCursorQueryBestSize;
-
-    // initialize QuickDraw cursor handling
-    GetQDGlobalsArrow(&gQDArrow);
-    PointPriv = (miPointerScreenPtr)
-	dixLookupPrivate(&pScreen->devPrivates, miPointerScreenKey);
-
-    ScreenPriv->spriteFuncs = PointPriv->spriteFuncs;
-    PointPriv->spriteFuncs = &quartzSpriteFuncsRec;
-
-    if (!quartzRootless)
-        ScreenPriv->useQDCursor = QuartzFSUseQDCursor(dfb->colorBitsPerPixel);
-    else
-        ScreenPriv->useQDCursor = TRUE;
-    ScreenPriv->qdCursorMode = TRUE;
-    ScreenPriv->qdCursorVisible = TRUE;
-
-    // initialize cursor mutex lock
-    pthread_mutex_init(&cursorMutex, NULL);
-
-    // initialize condition for waiting
-    pthread_cond_init(&cursorCondition, NULL);
-
-    return TRUE;
-}
-
-
-// X server is hiding. Restore the Aqua cursor.
-void QuartzSuspendXCursor(
-    ScreenPtr pScreen )
-{
-    QuartzCursorScreenPtr ScreenPriv = CURSOR_PRIV(pScreen);
-
-    CHANGE_QD_CURSOR(NULL);
-    SHOW_QD_CURSOR(pScreen, ScreenPriv->qdCursorVisible);
-}
-
-
-// X server is showing. Restore the X cursor.
-void QuartzResumeXCursor(
-    ScreenPtr pScreen,
-    int x,
-    int y )
-{
-    QuartzSetCursor(pScreen, quartzLatentCursor, x, y);
-}
diff --git a/hw/xquartz/quartzCursor.h b/hw/xquartz/quartzCursor.h
deleted file mode 100644
index 56a0209..0000000
--- a/hw/xquartz/quartzCursor.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * quartzCursor.h
- *
- * External interface for Quartz hardware cursor
- *
- * Copyright (c) 2001 Torrey T. Lyons and Greg Parker.
- *                 All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-
-#ifndef QUARTZCURSOR_H
-#define QUARTZCURSOR_H
-
-#include "screenint.h"
-
-Bool QuartzInitCursor(ScreenPtr pScreen);
-void QuartzReallySetCursor(void);
-void QuartzSuspendXCursor(ScreenPtr pScreen);
-void QuartzResumeXCursor(ScreenPtr pScreen, int x, int y);
-
-#endif
commit 6c5962e44730395f81cdb333322c9ad5242c32d4
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Mar 31 18:15:18 2008 -0700

    remove vestigal DarwinEQPointerPost etc
    (cherry picked from commit a25704c423598d596fd7f2ed4290d4b860bd5d5f)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index f7b1419..46f5675 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -251,23 +251,6 @@ void DarwinEQEnqueue(const xEventPtr e) {
 }
 
 /*
- * DarwinEQPointerPost
- *  Post a pointer event. Used by the mipointer.c routines.
- */
-void DarwinEQPointerPost(DeviceIntPtr pdev, xEventPtr e) {
-    (*darwinEventQueue.pPtr->processInputProc)
-            (e, (DeviceIntPtr)darwinEventQueue.pPtr, 1);
-}
-
-
-void DarwinEQSwitchScreen(ScreenPtr pScreen, Bool fromDIX) {
-    darwinEventQueue.pEnqueueScreen = pScreen;
-    if (fromDIX)
-        darwinEventQueue.pDequeueScreen = pScreen;
-}
-
-
-/*
  * ProcessInputEvents
  *  Read and process events from the event queue until it is empty.
  */
diff --git a/hw/xquartz/quartzCursor.c b/hw/xquartz/quartzCursor.c
index f82ccd3..10e671a 100644
--- a/hw/xquartz/quartzCursor.c
+++ b/hw/xquartz/quartzCursor.c
@@ -539,8 +539,8 @@ static miPointerScreenFuncRec quartzScreenFuncsRec = {
     QuartzCursorOffScreen,
     QuartzCrossScreen,
     QuartzWarpCursor,
-    DarwinEQPointerPost,
-    DarwinEQSwitchScreen
+    NULL,
+    NULL 
 };
 
 
diff --git a/hw/xquartz/xpr/xprCursor.c b/hw/xquartz/xpr/xprCursor.c
index e084ef9..2ad8d6f 100644
--- a/hw/xquartz/xpr/xprCursor.c
+++ b/hw/xquartz/xpr/xprCursor.c
@@ -320,8 +320,8 @@ static miPointerScreenFuncRec quartzScreenFuncsRec = {
     QuartzCursorOffScreen,
     QuartzCrossScreen,
     QuartzWarpCursor,
-    DarwinEQPointerPost,
-    DarwinEQSwitchScreen
+    NULL,
+    NULL
 };
 
 
commit c6f0d5d1e51326e5110d27918d834eb0096df7db
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Mar 31 17:48:09 2008 -0700

    gut darwinEQEnqueue, and make it just call mieqEnqueue (for the moment)
    (cherry picked from commit a9e081a60ca227c0d96d4613075d97d6b762366a)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index ce21ff5..f7b1419 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -199,7 +199,11 @@ void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int neven
   int i;
 
   DEBUG_LOG("DarwinEventHandler(%d, %p, %p, %d)\n", screenNum, xe, dev, nevents);
-  for (i=0; i<nevents; i++) QuartzProcessEvent(&xe[i]);
+  for (i=0; i<nevents; i++) {
+    if (xe[i].u.u.type == kXquartzDeactivate)
+      DarwinReleaseModifiers();
+    QuartzProcessEvent(&xe[i]);
+  }
 }
 
 Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) { 
@@ -242,40 +246,10 @@ Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) {
  * This should be deprecated in favor of miEQEnqueue -- BB
  */
 void DarwinEQEnqueue(const xEventPtr e) {
-    HWEventQueueType oldtail, newtail;
-
-    oldtail = darwinEventQueue.tail;
-
-    // mieqEnqueue() collapses successive motion events into one event.
-    // This is difficult to do in a thread-safe way and rarely useful.
-
-    newtail = oldtail + 1;
-    if (newtail == QUEUE_SIZE) newtail = 0;
-    /* Toss events which come in late */
-    if (newtail == darwinEventQueue.head) return;
-
-    darwinEventQueue.events[oldtail].event = *e;
-
-    /*
-     * Make sure that event times don't go backwards - this
-     * is "unnecessary", but very useful
-     */
-    if (e->u.keyButtonPointer.time < darwinEventQueue.lastEventTime &&
-        darwinEventQueue.lastEventTime - e->u.keyButtonPointer.time < 10000)
-    {
-        darwinEventQueue.events[oldtail].event.u.keyButtonPointer.time =
-        darwinEventQueue.lastEventTime;
-    }
-    darwinEventQueue.events[oldtail].pScreen = darwinEventQueue.pEnqueueScreen;
-
-    // Update the tail after the event is prepared
-    darwinEventQueue.tail = newtail;
-
-    // Signal there is an event ready to handle
-    DarwinPokeEQ();
+  mieqEnqueue(NULL, e);
+  DarwinPokeEQ();
 }
 
-
 /*
  * DarwinEQPointerPost
  *  Post a pointer event. Used by the mipointer.c routines.
commit 5b6c273eaa53d7b554d69c2b4865988068e73a26
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Mar 31 17:08:45 2008 -0700

    add prototype for DarwinEventHandler
    (cherry picked from commit 9a03ae33c4f9de830f15eabf3b994882ead7c000)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index b4ff9fd..ce21ff5 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -204,8 +204,6 @@ void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int neven
 
 Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) { 
 
-  void mieqSetHandler(int event, mieqHandler handler);
-
     darwinEvents = (xEvent *)malloc(sizeof(xEvent) * GetMaximumEventsNum());
     mieqInit();
     mieqSetHandler(kXquartzActivate, DarwinEventHandler);
diff --git a/hw/xquartz/darwinEvents.h b/hw/xquartz/darwinEvents.h
index 4960614..1d8e92a 100644
--- a/hw/xquartz/darwinEvents.h
+++ b/hw/xquartz/darwinEvents.h
@@ -41,4 +41,6 @@ void DarwinSendScrollEvents(float count, int pointer_x, int pointer_y,
 			    float pressure, float tilt_x, float tilt_y);
 void DarwinUpdateModKeys(int flags);
 
+void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, 
+			int nevents);
 #endif  /* _DARWIN_EVENTS_H */
commit 3713be8b470b1ac0fcb4f1e4c6b79c526b2196db
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Mar 31 16:30:16 2008 -0700

    add logging of current thread ID to DEBUG_LOG macro
    (cherry picked from commit 5848510cc5a8091b30230ab920d904ca6b159480)

diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index bd1b9a4..9384b9d 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -125,7 +125,7 @@ enum {
 #ifdef ENABLE_DEBUG_LOG
 extern FILE *debug_log_fp;
 #define DEBUG_LOG_NAME "x11-debug.txt"
-#define DEBUG_LOG(msg, args...) if (debug_log_fp) fprintf(debug_log_fp, "%s:%s:%d " msg, __FILE__, __FUNCTION__, __LINE__, ##args ); fflush(debug_log_fp);
+#define DEBUG_LOG(msg, args...) if (debug_log_fp) fprintf(debug_log_fp, "%x:%s:%s:%d " msg, pthread_self(), __FILE__, __FUNCTION__, __LINE__, ##args ); fflush(debug_log_fp);
 #else
 #define DEBUG_LOG(msg, args...) 
 #endif
commit 1400a51ae70d8e498d9ae3975f58ba7c1768ca6f
Author: Ben Byer <bbyer at apple.com>
Date:   Mon Mar 31 16:24:01 2008 -0700

    Begin to move all of our Xquartz DDX-specific event handlers
    to miEQ, in preparation to remove the DDX-specific code entirely.
    (cherry picked from commit 3f4447b95f73a82b3aa0f7b0d1640aba5fb0d1bc)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 2a28b1a..b4ff9fd 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -195,10 +195,34 @@ static void DarwinSimulateMouseClick(
     DarwinUpdateModifiers(KeyPress, modifierMask);
 }
 
+void DarwinEventHandler(int screenNum, xEventPtr xe, DeviceIntPtr dev, int nevents) {
+  int i;
+
+  DEBUG_LOG("DarwinEventHandler(%d, %p, %p, %d)\n", screenNum, xe, dev, nevents);
+  for (i=0; i<nevents; i++) QuartzProcessEvent(&xe[i]);
+}
 
 Bool DarwinEQInit(DevicePtr pKbd, DevicePtr pPtr) { 
+
+  void mieqSetHandler(int event, mieqHandler handler);
+
     darwinEvents = (xEvent *)malloc(sizeof(xEvent) * GetMaximumEventsNum());
     mieqInit();
+    mieqSetHandler(kXquartzActivate, DarwinEventHandler);
+    mieqSetHandler(kXquartzDeactivate, DarwinEventHandler);
+    mieqSetHandler(kXquartzSetRootClip, DarwinEventHandler);
+    mieqSetHandler(kXquartzQuit, DarwinEventHandler);
+    mieqSetHandler(kXquartzReadPasteboard, DarwinEventHandler);
+    mieqSetHandler(kXquartzWritePasteboard, DarwinEventHandler);
+    mieqSetHandler(kXquartzToggleFullscreen, DarwinEventHandler);
+    mieqSetHandler(kXquartzSetRootless, DarwinEventHandler);
+    mieqSetHandler(kXquartzSpaceChanged, DarwinEventHandler);
+    mieqSetHandler(kXquartzControllerNotify, DarwinEventHandler);
+    mieqSetHandler(kXquartzPasteboardNotify, DarwinEventHandler);
+    mieqSetHandler(kXquartzDisplayChanged, DarwinEventHandler);
+    mieqSetHandler(kXquartzWindowState, DarwinEventHandler);
+    mieqSetHandler(kXquartzWindowMoved, DarwinEventHandler);
+
     darwinEventQueue.head = darwinEventQueue.tail = 0;
     darwinEventQueue.lastEventTime = GetTimeInMillis ();
     darwinEventQueue.pKbd = pKbd;
commit 8746daa6732d9837f66d925f2fd74818ecbf8ba2
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Wed Apr 2 15:01:33 2008 -0700

    XQuartz: Fixed missing close-paren in preference pane text.
    (cherry picked from commit ea37e151dc6032d2a1a33cef809f2a7d507aae35)

diff --git a/hw/xquartz/bundle/English.lproj/main.nib/designable.nib b/hw/xquartz/bundle/English.lproj/main.nib/designable.nib
index 672ba90..c159d6e 100644
--- a/hw/xquartz/bundle/English.lproj/main.nib/designable.nib
+++ b/hw/xquartz/bundle/English.lproj/main.nib/designable.nib
@@ -2,7 +2,7 @@
 <archive type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="7.02">
 	<data>
 		<int key="IBDocument.SystemTarget">1050</int>
-		<string key="IBDocument.SystemVersion">9C31</string>
+		<string key="IBDocument.SystemVersion">9C7010</string>
 		<string key="IBDocument.InterfaceBuilderVersion">639</string>
 		<string key="IBDocument.AppKitVersion">949.26</string>
 		<string key="IBDocument.HIToolboxVersion">352.00</string>
@@ -948,7 +948,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 												<object class="NSTextFieldCell" key="NSCell" id="989804990">
 													<int key="NSCellFlags">67239424</int>
 													<int key="NSCellFlags2">4194304</int>
-													<string key="NSContents">When enabled, creation of a new X11 window will cause X11.app to move to the foreground (instead of Finder.app, Terminal.app, etc.</string>
+													<string key="NSContents">When enabled, creation of a new X11 window will cause X11.app to move to the foreground (instead of Finder.app, Terminal.app, etc.)</string>
 													<reference key="NSSupport" ref="26"/>
 													<reference key="NSControlView" ref="57161931"/>
 													<reference key="NSBackgroundColor" ref="57160303"/>
diff --git a/hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib b/hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib
index 91a7c5a..95420e4 100644
Binary files a/hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib and b/hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib differ
commit b5a0a865c3045cc08c33388320d4ec3ab7065efb
Author: Kristian Høgsberg <krh at redhat.com>
Date:   Wed Apr 2 19:21:41 2008 -0400

    Pick up dri2proto from the standard proto header include path.

diff --git a/configure.ac b/configure.ac
index e72e3b9..985c8e2 100644
--- a/configure.ac
+++ b/configure.ac
@@ -860,7 +860,7 @@ AM_CONDITIONAL(DRI2, test "x$DRI2" = xyes)
 if test "x$DRI2" = xyes; then
 	# FIXME: Bump the versions once we have releases of these.
 	AC_DEFINE(DRI2, 1, [Build DRI2 extension])
-	PKG_CHECK_MODULES([DRI2PROTO], [dri2proto >= 1.0.0])
+	PKG_CHECK_MODULES([DRI2PROTO], [dri2proto >= 1.1])
 	PKG_CHECK_MODULES([LIBDRM], [libdrm >= 2.3.1])
 fi
 
diff --git a/hw/xfree86/dri2/dri2ext.c b/hw/xfree86/dri2/dri2ext.c
index d1d52a4..4ae0fda 100644
--- a/hw/xfree86/dri2/dri2ext.c
+++ b/hw/xfree86/dri2/dri2ext.c
@@ -37,12 +37,12 @@
 #define NEED_REPLIES
 #include <X11/X.h>
 #include <X11/Xproto.h>
+#include <X11/extensions/dri2proto.h>
 #include "dixstruct.h"
 #include "scrnintstr.h"
 #include "pixmapstr.h"
 #include "extnsionst.h"
 #include "xf86drm.h"
-#include "dri2proto.h"
 #include "dri2.h"
 
 /* The only xf86 include */
commit 8cde0af3c57f0375ba8ba77af9fdf74b79d9496d
Author: Kristian Høgsberg <krh at redhat.com>
Date:   Wed Apr 2 19:06:40 2008 -0400

    Send the GLX_EXT_texture_from_pixmap attributes to the client.

diff --git a/GL/glx/glxcmds.c b/GL/glx/glxcmds.c
index 36aae61..dcd8352 100644
--- a/GL/glx/glxcmds.c
+++ b/GL/glx/glxcmds.c
@@ -959,7 +959,7 @@ int __glXDisp_GetVisualConfigs(__GLXclientState *cl, GLbyte *pc)
     return Success;
 }
 
-#define __GLX_TOTAL_FBCONFIG_ATTRIBS (28)
+#define __GLX_TOTAL_FBCONFIG_ATTRIBS (33)
 #define __GLX_FBCONFIG_ATTRIBS_LENGTH (__GLX_TOTAL_FBCONFIG_ATTRIBS * 2)
 /**
  * Send the set of GLXFBConfigs to the client.  There is not currently
@@ -1037,6 +1037,11 @@ DoGetFBConfigs(__GLXclientState *cl, unsigned screen)
 	WRITE_PAIR( GLX_TRANSPARENT_ALPHA_VALUE, modes->transparentAlpha );
 	WRITE_PAIR( GLX_TRANSPARENT_INDEX_VALUE, modes->transparentIndex );
 	WRITE_PAIR( GLX_SWAP_METHOD_OML, modes->swapMethod );
+	WRITE_PAIR( GLX_DRAWABLE_TYPE, modes->drawableType );
+	WRITE_PAIR( GLX_BIND_TO_TEXTURE_RGB_EXT, modes->bindToTextureRgb );
+	WRITE_PAIR( GLX_BIND_TO_TEXTURE_RGBA_EXT, modes->bindToTextureRgba );
+	WRITE_PAIR( GLX_BIND_TO_MIPMAP_TEXTURE_EXT, modes->bindToMipmapTexture );
+	WRITE_PAIR( GLX_BIND_TO_TEXTURE_TARGETS_EXT, modes->bindToTextureTargets );
 
 	if (client->swapped) {
 	    __GLX_SWAP_INT_ARRAY(buf, __GLX_FBCONFIG_ATTRIBS_LENGTH);
commit 7c20f65fea3dd3170cde89d7113d85f377671bfb
Author: Kristian Høgsberg <krh at redhat.com>
Date:   Wed Apr 2 18:00:06 2008 -0400

    Add @XORG_CFLAGS@ to satisfy xf86* includes.
    
    Pointed out by Hasso Tepper.

diff --git a/hw/xfree86/dri/Makefile.am b/hw/xfree86/dri/Makefile.am
index 68f1eae..bee3152 100644
--- a/hw/xfree86/dri/Makefile.am
+++ b/hw/xfree86/dri/Makefile.am
@@ -7,7 +7,7 @@ libdri_la_CFLAGS = -I$(top_srcdir)/hw/xfree86/common \
                    -I$(top_builddir)/GL/include \
 		   -I at MESA_SOURCE@/include \
                    -DHAVE_XORG_CONFIG_H \
-                   @DIX_CFLAGS@ @DRIPROTO_CFLAGS@ \
+                   @DIX_CFLAGS@ @XORG_CFLAGS@ @DRIPROTO_CFLAGS@ \
                    @LIBDRM_CFLAGS@ \
                    @GL_CFLAGS@
 libdri_la_LDFLAGS = -module -avoid-version @LIBDRM_LIBS@
diff --git a/hw/xfree86/dri2/Makefile.am b/hw/xfree86/dri2/Makefile.am
index 844c912..fd8962e 100644
--- a/hw/xfree86/dri2/Makefile.am
+++ b/hw/xfree86/dri2/Makefile.am
@@ -2,7 +2,7 @@ libdri2_la_LTLIBRARIES = libdri2.la
 libdri2_la_CFLAGS = \
 	-DHAVE_XORG_CONFIG_H \
 	-I at MESA_SOURCE@/include \
-	@DIX_CFLAGS@ @DRI2PROTO_CFLAGS@ @LIBDRM_CFLAGS@ \
+	@DIX_CFLAGS@ @XORG_CFLAGS@ @DRI2PROTO_CFLAGS@ @LIBDRM_CFLAGS@ \
 	-I$(top_srcdir)/hw/xfree86/common \
 	-I$(top_srcdir)/hw/xfree86/os-support/bus
 
commit b13ab156894074fb38cc812738bc7aeeebd9614d
Author: Kristian Høgsberg <krh at redhat.com>
Date:   Wed Apr 2 12:38:36 2008 -0400

    dri2: Unbreak glcore visual setup.

diff --git a/GL/glx/glxglcore.c b/GL/glx/glxglcore.c
index bbfa02b..972ab88 100644
--- a/GL/glx/glxglcore.c
+++ b/GL/glx/glxglcore.c
@@ -308,10 +308,9 @@ static const int glx_visual_types[] = {
 
 static __GLXconfig *
 createFBConfigsForVisual(__GLXscreen *screen, ScreenPtr pScreen,
-			 VisualPtr visual, __GLXconfig *tail)
+			 VisualPtr visual, __GLXconfig *config)
 {
     int back, depth, stencil;
-    __GLXconfig *config;
 
     /* FIXME: Ok, I'm making all this up... anybody has a better idea? */
 
@@ -347,7 +346,7 @@ createFBConfigsForVisual(__GLXscreen *screen, ScreenPtr pScreen,
 		config->indexBits = config->colorIndexMode ? visual->nplanes : 0;
 	    }
 
-    return tail;
+    return config;
 }
 
 static void
commit b31de6a59044f91f8230aa581c9ca8540289c168
Author: Xiang, Haihao <haihao.xiang at intel.com>
Date:   Wed Apr 2 16:29:30 2008 +1000

    dri2: fix crasher if DRI2Connect fails

diff --git a/hw/xfree86/dri2/dri2ext.c b/hw/xfree86/dri2/dri2ext.c
index ca2e029..d1d52a4 100644
--- a/hw/xfree86/dri2/dri2ext.c
+++ b/hw/xfree86/dri2/dri2ext.c
@@ -114,7 +114,7 @@ ProcDRI2Connect(ClientPtr client)
     ScreenPtr pScreen;
     int fd;
     const char *driverName;
-    char *busId;
+    char *busId = NULL;
     unsigned int sareaHandle;
 
     REQUEST_SIZE_MATCH(xDRI2ConnectReq);
commit ebc56aca8bdfec1918cac3c8380895dfddea48ce
Author: Hong Liu <hong.liu at intel.com>
Date:   Wed Apr 2 10:43:19 2008 +0800

    Bug #15160: quirk Proview AY765C
    
    prefer first detailed timing

diff --git a/hw/xfree86/modes/xf86EdidModes.c b/hw/xfree86/modes/xf86EdidModes.c
index 777bb70..f15c396 100644
--- a/hw/xfree86/modes/xf86EdidModes.c
+++ b/hw/xfree86/modes/xf86EdidModes.c
@@ -153,6 +153,11 @@ static Bool quirk_first_detailed_preferred (int scrnIndex, xf86MonPtr DDC)
 	DDC->vendor.prod_id == 57364)
 	return TRUE;
 
+    /* Proview AY765C 17" LCD. See bug #15160*/
+    if (memcmp (DDC->vendor.name, "PTS", 4) == 0 &&
+	DDC->vendor.prod_id == 765)
+	return TRUE;
+
     return FALSE;
 }
 
commit 9500033b9ecdfaf5a56a4355ffc94d74cb17ca17
Author: Goneri Le Bouder <goneri at rulezlan.org>
Date:   Tue Apr 1 20:19:40 2008 +0200

    xfree86: don't crash in AutoConfig if the primary device is not pci
    
    Only call matchDriverFromFiles() if we found a pci device.
    Debian bug#472823 (http://bugs.debian.org/472823).

diff --git a/hw/xfree86/common/xf86AutoConfig.c b/hw/xfree86/common/xf86AutoConfig.c
index 268b50c..3210e44 100644
--- a/hw/xfree86/common/xf86AutoConfig.c
+++ b/hw/xfree86/common/xf86AutoConfig.c
@@ -436,9 +436,10 @@ chooseVideoDriver(void)
     if (!info) {
 	ErrorF("Primary device is not PCI\n");
     }
-
 #ifdef __linux__
-    matchDriverFromFiles(matches, info->vendor_id, info->device_id);
+    else {
+	matchDriverFromFiles(matches, info->vendor_id, info->device_id);
+    }
 #endif /* __linux__ */
 
     /* TODO Handle multiple drivers claiming to support the same PCI ID */
commit 37b1258f0a288a79ce6a3eef3559e17a67c4dd96
Author: Thomas Jaeger <thjaeger at gmail.com>
Date:   Tue Apr 1 15:27:06 2008 +0300

    XKB: Fix processInputProc wrapping
    
    If input processing is frozen, only wrap realInputProc: don't smash
    processInputProc as well.  When input processing is thawed, pIP will be
    rewrapped correctly.
    
    This supersedes the previous workaround in 50e80c9.
    
    Signed-off-by: Daniel Stone <daniel at fooishbar.org>

diff --git a/include/xkbsrv.h b/include/xkbsrv.h
index ef99e94..040bb93 100644
--- a/include/xkbsrv.h
+++ b/include/xkbsrv.h
@@ -237,6 +237,14 @@ typedef struct	_XkbSrvLedInfo {
 typedef struct
 {
     ProcessInputProc processInputProc;
+    /* If processInputProc is set to something different than realInputProc,
+     * UNWRAP and COND_WRAP will not touch processInputProc and update only
+     * realInputProc.  This ensures that
+     *   processInputProc == (frozen ? EnqueueEvent : realInputProc)
+     *
+     * WRAP_PROCESS_INPUT_PROC should only be called during initialization,
+     * since it may destroy this invariant.
+     */
     ProcessInputProc realInputProc;
     DeviceUnwrapProc unwrapProc;
 } xkbDeviceInfoRec, *xkbDeviceInfoPtr;
@@ -254,14 +262,14 @@ typedef struct
 	    device->public.processInputProc = proc; \
 	oldprocs->processInputProc = \
 	oldprocs->realInputProc = device->public.realInputProc; \
-	if (proc != device->public.enqueueInputProc) \
-		device->public.realInputProc = proc; \
+	device->public.realInputProc = proc; \
 	oldprocs->unwrapProc = device->unwrapProc; \
 	device->unwrapProc = unwrapproc;
 
 #define UNWRAP_PROCESS_INPUT_PROC(device, oldprocs, backupproc) \
-        backupproc = device->public.processInputProc; \
-	device->public.processInputProc = oldprocs->processInputProc; \
+        backupproc = device->public.realInputProc; \
+	if (device->public.processInputProc == device->public.realInputProc)\
+	    device->public.processInputProc = oldprocs->realInputProc; \
 	device->public.realInputProc = oldprocs->realInputProc; \
 	device->unwrapProc = oldprocs->unwrapProc;
 
diff --git a/xkb/xkbActions.c b/xkb/xkbActions.c
index 890cf42..8c72874 100644
--- a/xkb/xkbActions.c
+++ b/xkb/xkbActions.c
@@ -49,15 +49,14 @@ xkbUnwrapProc(DeviceIntPtr device, DeviceHandleProc proc,
                    pointer data)
 {
     xkbDeviceInfoPtr xkbPrivPtr = XKBDEVICEINFO(device);
-    ProcessInputProc tmp = device->public.processInputProc;
-    ProcessInputProc dummy; /* unused, but neede for macro */
+    ProcessInputProc backupproc;
     if(xkbPrivPtr->unwrapProc)
 	xkbPrivPtr->unwrapProc = NULL;
 
-    UNWRAP_PROCESS_INPUT_PROC(device,xkbPrivPtr, dummy);
+    UNWRAP_PROCESS_INPUT_PROC(device,xkbPrivPtr, backupproc);
     proc(device,data);
-    WRAP_PROCESS_INPUT_PROC(device,xkbPrivPtr,
-			    tmp,xkbUnwrapProc);
+    COND_WRAP_PROCESS_INPUT_PROC(device,xkbPrivPtr,
+				 backupproc,xkbUnwrapProc);
 }
 
 
commit a4d034941100c6ca3b7cc4e59952c2745b9306cc
Author: Ben Byer <bbyer at bushing.apple.com>
Date:   Fri Mar 28 20:47:44 2008 -0700

    Add code to track 5 valuators for pointing device, in preparation
    for supporting tablet input in Xquartz.
    (cherry picked from commit 22c8849ea819eb70a14b2e06330b11b22aa63ebc)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 31c80df..147b4b4 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -61,7 +61,7 @@ int X11EnableKeyEquivalents = TRUE;
 int quartzHasRoot = FALSE, quartzEnableRootless = TRUE;
 
 extern int darwinFakeButtons, input_check_flag;
-extern Bool enable_stereo; 
+extern Bool enable_stereo;
 
 extern xEvent *darwinEvents;
 
@@ -153,7 +153,7 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 	
     tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
 	
-    [dict setObject:[NSString stringWithFormat:@"Xquartz %@ - (xorg-server %s)", tem, XSERVER_VERSION] 
+    [dict setObject:[NSString stringWithFormat:@"XQuartz %@ - (xorg-server %s)", tem, XSERVER_VERSION]
 	  forKey:@"ApplicationVersion"];
 	
     [self orderFrontStandardAboutPanelWithOptions: dict];
@@ -501,7 +501,7 @@ static NSMutableArray * cfarray_to_nsarray (CFArrayRef in) {
   
   if (value != NULL
       && CFGetTypeID (value) == CFNumberGetTypeID ()
-      && CFNumberIsFloatType (value)) 
+      && CFNumberIsFloatType (value))
     CFNumberGetValue (value, kCFNumberFloatType, &ret);
   else if (value != NULL && CFGetTypeID (value) == CFStringGetTypeID ())
     ret = CFStringGetDoubleValue (value);
@@ -862,7 +862,9 @@ static void send_nsevent (NSEventType type, NSEvent *e) {
     NSRect screen;
     NSPoint location;
     NSWindow *window;
-    int pointer_x, pointer_y, ev_button, ev_type; 
+    int pointer_x, pointer_y, ev_button, ev_type;
+    float pressure, tilt_x, tilt_y;
+
     //    int num_events=0, i=0, state;
     // xEvent xe;
 	
@@ -884,6 +886,10 @@ static void send_nsevent (NSEventType type, NSEvent *e) {
     pointer_y -= aquaMenuBarHeight;
     //    state = convert_flags ([e modifierFlags]);
     
+    pressure = 0;  // for tablets
+    tilt_x = 0;
+    tilt_y = 0;
+
     switch (type) {
     case NSLeftMouseDown:    ev_button=1; ev_type=ButtonPress; goto handle_mouse;
     case NSOtherMouseDown:   ev_button=2; ev_type=ButtonPress; goto handle_mouse;
@@ -894,6 +900,10 @@ static void send_nsevent (NSEventType type, NSEvent *e) {
     case NSLeftMouseDragged:  ev_button=1; ev_type=MotionNotify; goto handle_mouse;
     case NSOtherMouseDragged: ev_button=2; ev_type=MotionNotify; goto handle_mouse;
     case NSRightMouseDragged: ev_button=3; ev_type=MotionNotify; goto handle_mouse;
+    case NSTabletPoint:
+      pressure = [e pressure];
+      tilt_x = [e tilt].x;
+      tilt_y = [e tilt].y; // fall through
     case NSMouseMoved: ev_button=0; ev_type=MotionNotify; goto handle_mouse;
     handle_mouse:
       
@@ -907,10 +917,14 @@ static void send_nsevent (NSEventType type, NSEvent *e) {
 	DarwinSendPointerEvents(ev_type, ev_button, pointer_x, pointer_y);
       } else if (ev_type==ButtonRelease && (button_state & (1 << ev_button)) == 0) break;
       */
-      DarwinSendPointerEvents(ev_type, ev_button, pointer_x, pointer_y);
+
+      //      if ([e subtype] == NSTabletPointEventSubtype) pressure = [e pressure];
+      DarwinSendPointerEvents(ev_type, ev_button, pointer_x, pointer_y,
+			      pressure, tilt_x, tilt_y);
       break;
-    case NSScrollWheel: 
-      DarwinSendScrollEvents([e deltaY], pointer_x, pointer_y);
+    case NSScrollWheel:
+      DarwinSendScrollEvents([e deltaY], pointer_x, pointer_y,
+			     pressure, tilt_x, tilt_y);
       break;
       
     case NSKeyDown:  // do we need to translate these keyCodes?
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 113cfc1..2a28b1a 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -173,6 +173,9 @@ static void DarwinReleaseModifiers(void) {
 static void DarwinSimulateMouseClick(
     int pointer_x,
     int pointer_y,
+    float pressure,
+    float tilt_x,
+    float tilt_y,
     int whichButton,    // mouse button to be pressed
     int modifierMask)   // modifiers used for the fake click
 {
@@ -183,8 +186,10 @@ static void DarwinSimulateMouseClick(
     DarwinUpdateModifiers(KeyRelease, modifierMask);
 
     // push the mouse button
-    DarwinSendPointerEvents(ButtonPress, whichButton, pointer_x, pointer_y);
-    DarwinSendPointerEvents(ButtonRelease, whichButton, pointer_x, pointer_y);
+    DarwinSendPointerEvents(ButtonPress, whichButton, pointer_x, pointer_y, 
+			    pressure, tilt_x, tilt_y);
+    DarwinSendPointerEvents(ButtonRelease, whichButton, pointer_x, pointer_y, 
+			    pressure, tilt_x, tilt_y);
 
     // restore old modifiers
     DarwinUpdateModifiers(KeyPress, modifierMask);
@@ -378,22 +383,39 @@ void DarwinPokeEQ(void) {
   write(darwinEventWriteFD, &nullbyte, 1);
 }
 
-void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int pointer_y) {
+void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int pointer_y, 
+			     float pressure, float tilt_x, float tilt_y) {
   static int darwinFakeMouseButtonDown = 0;
   static int darwinFakeMouseButtonMask = 0;
   int i, num_events;
-  int valuators[2] = {pointer_x, pointer_y};
+
+  /* I can't find a spec for this, but at least GTK expects that tablets are
+     just like mice, except they have either one or three extra valuators, in this
+     order:
+     
+     X coord, Y coord, pressure, X tilt, Y tilt
+     Pressure and tilt should be represented natively as floats; unfortunately,
+     we can't do that.  Again, GTK seems to record the min/max of each valuator,
+     and then perform scaling back to float itself using that info. Soo.... */
+
+  int valuators[5] = {pointer_x, pointer_y, 
+		      pressure * INT32_MAX * 1.0f, 
+		      tilt_x * INT32_MAX * 1.0f, 
+		      tilt_y * INT32_MAX * 1.0f};
+
   if (ev_type == ButtonPress && darwinFakeButtons && ev_button == 1) {
     // Mimic multi-button mouse with modifier-clicks
     // If both sets of modifiers are pressed,
     // button 2 is clicked.
     if ((old_flags & darwinFakeMouse2Mask) == darwinFakeMouse2Mask) {
-      DarwinSimulateMouseClick(pointer_x, pointer_y, 2, darwinFakeMouse2Mask);
+      DarwinSimulateMouseClick(pointer_x, pointer_y, pressure, 
+			       tilt_x, tilt_y, 2, darwinFakeMouse2Mask);
       darwinFakeMouseButtonDown = 2;
       darwinFakeMouseButtonMask = darwinFakeMouse2Mask;
       return;
     } else if ((old_flags & darwinFakeMouse3Mask) == darwinFakeMouse3Mask) {
-      DarwinSimulateMouseClick(pointer_x, pointer_y, 3, darwinFakeMouse3Mask);
+      DarwinSimulateMouseClick(pointer_x, pointer_y, pressure, 
+			       tilt_x, tilt_y, 3, darwinFakeMouse3Mask);
       darwinFakeMouseButtonDown = 3;
       darwinFakeMouseButtonMask = darwinFakeMouse3Mask;
       return;
@@ -412,7 +434,7 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
   } 
 
   num_events = GetPointerEvents(darwinEvents, darwinPointer, ev_type, ev_button, 
-				POINTER_ABSOLUTE, 0, 2, valuators);
+				POINTER_ABSOLUTE, 0, 5, valuators);
       
   for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
   DarwinPokeEQ();
@@ -438,18 +460,38 @@ void DarwinSendKeyboardEvents(int ev_type, int keycode) {
   DarwinPokeEQ();
 }
 
+void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y, 
+			       float pressure, float tilt_x, float tilt_y) {
+  int i, num_events;
+  int valuators[5] = {pointer_x, pointer_y, 
+		      pressure * INT32_MAX * 1.0f, 
+		      tilt_x * INT32_MAX * 1.0f, 
+		      tilt_y * INT32_MAX * 1.0f};
+
+  num_events = GetProximityEvents(darwinEvents, darwinPointer, ev_type,
+				0, 5, valuators);
+      
+  for(i=0; i<num_events; i++) mieqEnqueue (darwinPointer,&darwinEvents[i]);
+  DarwinPokeEQ();
+}
+
+
 /* Send the appropriate number of button 4 / 5 clicks to emulate scroll wheel */
-void DarwinSendScrollEvents(float count, int pointer_x, int pointer_y) {
+void DarwinSendScrollEvents(float count, int pointer_x, int pointer_y, 
+			    float pressure, float tilt_x, float tilt_y) {
   int i;
   int ev_button = count > 0.0f ? 4 : 5;
-  int valuators[2] = {pointer_x, pointer_y};
+  int valuators[5] = {pointer_x, pointer_y, 
+		      pressure * INT32_MAX * 1.0f, 
+		      tilt_x * INT32_MAX * 1.0f, 
+		      tilt_y * INT32_MAX * 1.0f};
 
   for (count = fabs(count); count > 0.0; count = count - 1.0f) {
     int num_events = GetPointerEvents(darwinEvents, darwinPointer, ButtonPress, ev_button, 
-				      POINTER_ABSOLUTE, 0, 2, valuators);
+				      POINTER_ABSOLUTE, 0, 5, valuators);
     for(i=0; i<num_events; i++) mieqEnqueue(darwinPointer,&darwinEvents[i]);
     num_events = GetPointerEvents(darwinEvents, darwinPointer, ButtonRelease, ev_button, 
-				      POINTER_ABSOLUTE, 0, 2, valuators);
+				      POINTER_ABSOLUTE, 0, 5, valuators);
     for(i=0; i<num_events; i++) mieqEnqueue(darwinPointer,&darwinEvents[i]);
   }
   DarwinPokeEQ();
diff --git a/hw/xquartz/darwinEvents.h b/hw/xquartz/darwinEvents.h
index 82cc26b..4960614 100644
--- a/hw/xquartz/darwinEvents.h
+++ b/hw/xquartz/darwinEvents.h
@@ -32,9 +32,13 @@ void DarwinEQEnqueue(const xEventPtr e);
 void DarwinEQPointerPost(DeviceIntPtr pDev, xEventPtr e);
 void DarwinEQSwitchScreen(ScreenPtr pScreen, Bool fromDIX);
 void DarwinPokeEQ(void);
-void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int pointer_y);
+void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int pointer_y,
+			     float pressure, float tilt_x, float tilt_y);
+void DarwinSendProximityEvents(int ev_type, int pointer_x, int pointer_y, 
+			       float pressure, float tilt_x, float tilt_y);
 void DarwinSendKeyboardEvents(int ev_type, int keycode);
-void DarwinSendScrollEvents(float count, int pointer_x, int pointer_y);
+void DarwinSendScrollEvents(float count, int pointer_x, int pointer_y,
+			    float pressure, float tilt_x, float tilt_y);
 void DarwinUpdateModKeys(int flags);
 
 #endif  /* _DARWIN_EVENTS_H */
commit 6648867d8bd1e86458d2ade77a3ee4567c3d6a97
Author: Ben Byer <bbyer at bushing.apple.com>
Date:   Fri Mar 28 18:27:02 2008 -0700

    add debug statements so we can see if/when our Xinput stubs are getting called.
    (cherry picked from commit 6e160bbe15dd2c2b8685847c06831cb6aebc6f74)

diff --git a/hw/xquartz/darwinXinput.c b/hw/xquartz/darwinXinput.c
index 50ba656..59bae6f 100644
--- a/hw/xquartz/darwinXinput.c
+++ b/hw/xquartz/darwinXinput.c
@@ -62,6 +62,7 @@ SOFTWARE.
 #include <X11/extensions/XI.h>
 #include <X11/extensions/XIproto.h>
 #include "XIstubs.h"
+#include "darwin.h"
 
 /***********************************************************************
  *
@@ -79,6 +80,7 @@ SOFTWARE.
 void
 CloseInputDevice(DeviceIntPtr d, ClientPtr client)
 {
+  DEBUG_LOG("CloseInputDevice(%p, %p)\n", d, client);
 }
 
 /***********************************************************************
@@ -122,7 +124,7 @@ AddOtherInputDevices(void)
     RegisterOtherDevice(dev);
     dev->inited = ((*dev->deviceProc)(dev, DEVICE_INIT) == Success);
     ************************************************************************/
-
+  DEBUG_LOG("AddOtherInputDevices\n");
 }
 
 /***********************************************************************
@@ -150,6 +152,7 @@ AddOtherInputDevices(void)
 void
 OpenInputDevice(DeviceIntPtr dev, ClientPtr client, int *status)
 {
+  DEBUG_LOG("OpenInputDevice(%p, %p, %p)\n", dev, client, status);
 }
 
 /****************************************************************************
@@ -167,6 +170,7 @@ OpenInputDevice(DeviceIntPtr dev, ClientPtr client, int *status)
 int
 SetDeviceMode(ClientPtr client, DeviceIntPtr dev, int mode)
 {
+  DEBUG_LOG("SetDeviceMode(%p, %p, %d)\n", client, dev, mode);
     return BadMatch;
 }
 
@@ -186,7 +190,9 @@ int
 SetDeviceValuators(ClientPtr client, DeviceIntPtr dev,
 		   int *valuators, int first_valuator, int num_valuators)
 {
-    return BadMatch;
+  DEBUG_LOG("SetDeviceValuators(%p, %p, %p, %d, %d)\n", client,
+	    dev, valuators, first_valuator, num_valuators);
+  return BadMatch;
 }
 
 /****************************************************************************
@@ -201,6 +207,8 @@ int
 ChangeDeviceControl(ClientPtr client, DeviceIntPtr dev,
 		    xDeviceCtl * control)
 {
+
+  DEBUG_LOG("ChangeDeviceControl(%p, %p, %p)\n", client, dev, control);
     switch (control->control) {
     case DEVICE_RESOLUTION:
 	return (BadMatch);
@@ -225,7 +233,8 @@ ChangeDeviceControl(ClientPtr client, DeviceIntPtr dev,
 int
 NewInputDeviceRequest(InputOption *options, DeviceIntPtr *pdev)
 {
-    return BadValue;
+  DEBUG_LOG("NewInputDeviceRequest(%p, %p)\n", options, pdev);
+  return BadValue;
 }
 
 /****************************************************************************
@@ -238,4 +247,5 @@ NewInputDeviceRequest(InputOption *options, DeviceIntPtr *pdev)
 void
 DeleteInputDeviceRequest(DeviceIntPtr dev)
 {
+  DEBUG_LOG("DeleteInputDeviceRequest(%p)\n", dev);
 }
commit 19ff23ab0e72a27d05ed4470f75a0934d6f6c1d1
Author: Ben Byer <bbyer at bushing.apple.com>
Date:   Fri Mar 28 18:25:03 2008 -0700

    Remove calls to InitValuatorAxisStruct -- these are now handled in dix by
    InitValuatorDeviceClass.
    Add InitProximityClassDeviceStruct call to prepare for tablet support.
    (cherry picked from commit 1bd980a5b114f5320360943214f8f9f23b29c1e3)

diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index 0dbfafe..8f2511d 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -353,24 +353,8 @@ static int DarwinMouseProc(
             InitPointerDeviceStruct( (DevicePtr)pPointer, map, 5,
 				     GetMotionHistory,
 				     (PtrCtrlProcPtr)NoopDDA,
-				     GetMotionHistorySize(), 2);
-
-#ifdef XINPUT
-            InitValuatorAxisStruct( pPointer,
-                                    0,     // X axis
-                                    0,     // min value
-                                    16000, // max value (fixme screen size?)
-                                    1,     // resolution (fixme ?)
-                                    1,     // min resolution
-                                    1 );   // max resolution
-            InitValuatorAxisStruct( pPointer,
-                                    1,     // X axis
-                                    0,     // min value
-                                    16000, // max value (fixme screen size?)
-                                    1,     // resolution (fixme ?)
-                                    1,     // min resolution
-                                    1 );   // max resolution
-#endif
+				     GetMotionHistorySize(), 5);
+	    InitProximityClassDeviceStruct( (DevicePtr)pPointer);
             break;
 
         case DEVICE_ON:
commit 9f56fc580646a519875b5a1452738d8c6e1fa860
Author: Eamon Walsh <ewalsh at tycho.nsa.gov>
Date:   Mon Mar 31 17:34:07 2008 -0400

    XSELinux: Add a request to get a client's context from a resource ID.

diff --git a/Xext/xselinux.c b/Xext/xselinux.c
index 2e059a4..1e3b4d6 100644
--- a/Xext/xselinux.c
+++ b/Xext/xselinux.c
@@ -1473,6 +1473,24 @@ ProcSELinuxGetSelectionContext(ClientPtr client, pointer privKey)
 }
 
 static int
+ProcSELinuxGetClientContext(ClientPtr client)
+{
+    ClientPtr target;
+    SELinuxSubjectRec *subj;
+    int rc;
+
+    REQUEST(SELinuxGetContextReq);
+    REQUEST_SIZE_MATCH(SELinuxGetContextReq);
+
+    rc = dixLookupClient(&target, stuff->id, client, DixGetAttrAccess);
+    if (rc != Success)
+	return rc;
+
+    subj = dixLookupPrivate(&target->devPrivates, subjectKey);
+    return SELinuxSendContextReply(client, subj->sid);
+}
+
+static int
 SELinuxPopulateItem(SELinuxListItemRec *i, PrivateRec **privPtr, CARD32 id,
 		    int *size)
 {
@@ -1686,6 +1704,8 @@ ProcSELinuxDispatch(ClientPtr client)
 	return ProcSELinuxGetSelectionContext(client, dataKey);
     case X_SELinuxListSelections:
 	return ProcSELinuxListSelections(client);
+    case X_SELinuxGetClientContext:
+	return ProcSELinuxGetClientContext(client);
     default:
 	return BadRequest;
     }
@@ -1783,6 +1803,17 @@ SProcSELinuxListProperties(ClientPtr client)
 }
 
 static int
+SProcSELinuxGetClientContext(ClientPtr client)
+{
+    REQUEST(SELinuxGetContextReq);
+    int n;
+
+    REQUEST_SIZE_MATCH(SELinuxGetContextReq);
+    swapl(&stuff->id, n);
+    return ProcSELinuxGetClientContext(client);
+}
+
+static int
 SProcSELinuxDispatch(ClientPtr client)
 {
     REQUEST(xReq);
@@ -1835,6 +1866,8 @@ SProcSELinuxDispatch(ClientPtr client)
 	return SProcSELinuxGetSelectionContext(client, dataKey);
     case X_SELinuxListSelections:
 	return ProcSELinuxListSelections(client);
+    case X_SELinuxGetClientContext:
+	return SProcSELinuxGetClientContext(client);
     default:
 	return BadRequest;
     }
diff --git a/Xext/xselinux.h b/Xext/xselinux.h
index 2d0de32..7c3ffdc 100644
--- a/Xext/xselinux.h
+++ b/Xext/xselinux.h
@@ -52,6 +52,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #define X_SELinuxGetSelectionContext		19
 #define X_SELinuxGetSelectionDataContext	20
 #define X_SELinuxListSelections			21
+#define X_SELinuxGetClientContext		22
 
 typedef struct {
     CARD8   reqType;
commit c40e0b51f0d9ef5e1f30f233d7db1e6db9d6681b
Author: Kristian Høgsberg <krh at redhat.com>
Date:   Wed Mar 26 19:28:09 2008 -0400

    Implement DRI2 direct rendering and update AIGLX to DRI interface changes.
    
    Get rid of glcontextmodes.[ch] from build, rename __GlcontextModes to
    __GLXcontext.  Drop all #includes of glcontextmodes.h and glcore.h.
    Drop the DRI context modes extension.
    
    Add protocol code to DRI2 module and load DRI2 extension by default.

diff --git a/GL/glx/Makefile.am b/GL/glx/Makefile.am
index 377d760..1d4719c 100644
--- a/GL/glx/Makefile.am
+++ b/GL/glx/Makefile.am
@@ -31,8 +31,6 @@ INCLUDES = \
 
 nodist_libglx_la_SOURCES = indirect_size.h \
 			   glapi.c \
-			   glcontextmodes.c \
-			   glcontextmode.h \
 			   glthread.c \
 			   indirect_dispatch.c \
 			   indirect_dispatch.h \
diff --git a/GL/glx/glxcmds.c b/GL/glx/glxcmds.c
index 3b79cca..36aae61 100644
--- a/GL/glx/glxcmds.c
+++ b/GL/glx/glxcmds.c
@@ -50,7 +50,6 @@
 #include <windowstr.h>
 #include "glxutil.h"
 #include "glxext.h"
-#include "glcontextmodes.h"
 #include "glapitable.h"
 #include "glapi.h"
 #include "glthread.h"
@@ -83,9 +82,9 @@ validGlxScreen(ClientPtr client, int screen, __GLXscreen **pGlxScreen, int *err)
 
 static int
 validGlxFBConfig(ClientPtr client, __GLXscreen *pGlxScreen, XID id,
-		 __GLcontextModes **config, int *err)
+		 __GLXconfig **config, int *err)
 {
-    __GLcontextModes *m;
+    __GLXconfig *m;
 
     for (m = pGlxScreen->fbconfigs; m != NULL; m = m->next)
 	if (m->fbconfigID == id) {
@@ -101,7 +100,7 @@ validGlxFBConfig(ClientPtr client, __GLXscreen *pGlxScreen, XID id,
 
 static int
 validGlxVisual(ClientPtr client, __GLXscreen *pGlxScreen, XID id,
-	       __GLcontextModes **config, int *err)
+	       __GLXconfig **config, int *err)
 {
     int i;
 
@@ -118,7 +117,7 @@ validGlxVisual(ClientPtr client, __GLXscreen *pGlxScreen, XID id,
 }
 
 static int
-validGlxFBConfigForWindow(ClientPtr client, __GLcontextModes *config,
+validGlxFBConfigForWindow(ClientPtr client, __GLXconfig *config,
 			  DrawablePtr pDraw, int *err)
 {
     ScreenPtr pScreen = pDraw->pScreen;
@@ -135,7 +134,7 @@ validGlxFBConfigForWindow(ClientPtr client, __GLcontextModes *config,
     }
 
     /* FIXME: What exactly should we check here... */
-    if (pVisual->class != _gl_convert_to_x_visual_type(config->visualType) ||
+    if (pVisual->class != glxConvertToXVisualType(config->visualType) ||
 	!(config->drawableType & GLX_WINDOW_BIT)) {
 	client->errorValue = pDraw->id;
 	*err = BadMatch;
@@ -161,7 +160,7 @@ static void __glXdirectContextDestroy(__GLXcontext *context)
 }
 
 static __GLXcontext *__glXdirectContextCreate(__GLXscreen *screen,
-					      __GLcontextModes *modes,
+					      __GLXconfig *modes,
 					      __GLXcontext *shareContext)
 {
     __GLXcontext *context;
@@ -186,7 +185,7 @@ static __GLXcontext *__glXdirectContextCreate(__GLXscreen *screen,
 
 static int
 DoCreateContext(__GLXclientState *cl, GLXContextID gcId,
-		GLXContextID shareList, __GLcontextModes *config,
+		GLXContextID shareList, __GLXconfig *config,
 		__GLXscreen *pGlxScreen, GLboolean isDirect)
 {
     ClientPtr client = cl->client;
@@ -248,7 +247,7 @@ DoCreateContext(__GLXclientState *cl, GLXContextID gcId,
     ** a GL core that needs windowing information (e.g., Mesa).
     */
     glxc->pGlxScreen = pGlxScreen;
-    glxc->modes = config;
+    glxc->config = config;
 
     /*
     ** Register this context as a resource.
@@ -276,7 +275,7 @@ DoCreateContext(__GLXclientState *cl, GLXContextID gcId,
 int __glXDisp_CreateContext(__GLXclientState *cl, GLbyte *pc)
 {
     xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc;
-    __GLcontextModes *config;
+    __GLXconfig *config;
     __GLXscreen *pGlxScreen;
     int err;
 
@@ -292,7 +291,7 @@ int __glXDisp_CreateContext(__GLXclientState *cl, GLbyte *pc)
 int __glXDisp_CreateNewContext(__GLXclientState *cl, GLbyte *pc)
 {
     xGLXCreateNewContextReq *req = (xGLXCreateNewContextReq *) pc;
-    __GLcontextModes *config;
+    __GLXconfig *config;
     __GLXscreen *pGlxScreen;
     int err;
 
@@ -309,7 +308,7 @@ int __glXDisp_CreateContextWithConfigSGIX(__GLXclientState *cl, GLbyte *pc)
 {
     xGLXCreateContextWithConfigSGIXReq *req = 
 	(xGLXCreateContextWithConfigSGIXReq *) pc;
-    __GLcontextModes *config;
+    __GLXconfig *config;
     __GLXscreen *pGlxScreen;
     int err;
 
@@ -462,7 +461,7 @@ __glXGetDrawable(__GLXcontext *glxc, GLXDrawable drawId, ClientPtr client,
      * GLXPixmap and we just return the __GLXdrawable.  */
     pGlxDraw = (__GLXdrawable *) LookupIDByType(drawId, __glXDrawableRes);
     if (pGlxDraw != NULL) {
-	if (glxc != NULL && pGlxDraw->modes != glxc->modes) {
+	if (glxc != NULL && pGlxDraw->config != glxc->config) {
 	    client->errorValue = drawId;
 	    *error = BadMatch;
 	    return NULL;
@@ -497,12 +496,12 @@ __glXGetDrawable(__GLXcontext *glxc, GLXDrawable drawId, ClientPtr client,
      * the context screen and that the context fbconfig is compatible
      * with the window visual. */
     if (pDraw->pScreen != glxc->pGlxScreen->pScreen ||
-	!validGlxFBConfigForWindow(client, glxc->modes, pDraw, error))
+	!validGlxFBConfigForWindow(client, glxc->config, pDraw, error))
 	return NULL;
 
     pGlxDraw = glxc->pGlxScreen->createDrawable(glxc->pGlxScreen,
 						pDraw, GLX_DRAWABLE_WINDOW,
-						drawId, glxc->modes);
+						drawId, glxc->config);
 
     /* since we are creating the drawablePrivate, drawId should be new */
     if (!AddResource(drawId, __glXDrawableRes, pGlxDraw)) {
@@ -878,7 +877,7 @@ int __glXDisp_GetVisualConfigs(__GLXclientState *cl, GLbyte *pc)
     ClientPtr client = cl->client;
     xGLXGetVisualConfigsReply reply;
     __GLXscreen *pGlxScreen;
-    __GLcontextModes *modes;
+    __GLXconfig *modes;
     CARD32 buf[__GLX_TOTAL_CONFIG];
     int p, i, err;
     __GLX_DECLARE_SWAP_VARIABLES;
@@ -907,7 +906,7 @@ int __glXDisp_GetVisualConfigs(__GLXclientState *cl, GLbyte *pc)
 
 	p = 0;
 	buf[p++] = modes->visualID;
-	buf[p++] = _gl_convert_to_x_visual_type( modes->visualType );
+	buf[p++] = glxConvertToXVisualType( modes->visualType );
 	buf[p++] = modes->rgbMode;
 
 	buf[p++] = modes->redBits;
@@ -980,7 +979,7 @@ DoGetFBConfigs(__GLXclientState *cl, unsigned screen)
     __GLXscreen *pGlxScreen;
     CARD32 buf[__GLX_FBCONFIG_ATTRIBS_LENGTH];
     int p, err;
-    __GLcontextModes *modes;
+    __GLXconfig *modes;
     __GLX_DECLARE_SWAP_VARIABLES;
     __GLX_DECLARE_SWAP_ARRAY_VARIABLES;
 
@@ -1062,7 +1061,7 @@ int __glXDisp_GetFBConfigsSGIX(__GLXclientState *cl, GLbyte *pc)
 }
 
 static int 
-DoCreateGLXDrawable(ClientPtr client, __GLXscreen *pGlxScreen, __GLcontextModes *config,
+DoCreateGLXDrawable(ClientPtr client, __GLXscreen *pGlxScreen, __GLXconfig *config,
 		    DrawablePtr pDraw, XID glxDrawableId, int type)
 {
     __GLXdrawable *pGlxDraw;
@@ -1086,7 +1085,7 @@ DoCreateGLXDrawable(ClientPtr client, __GLXscreen *pGlxScreen, __GLcontextModes
 }
 
 static int
-DoCreateGLXPixmap(ClientPtr client, __GLXscreen *pGlxScreen, __GLcontextModes *config,
+DoCreateGLXPixmap(ClientPtr client, __GLXscreen *pGlxScreen, __GLXconfig *config,
 		  XID drawableId, XID glxDrawableId)
 {
     DrawablePtr pDraw;
@@ -1144,7 +1143,7 @@ determineTextureTarget(XID glxDrawableID, CARD32 *attribs, CARD32 numAttribs)
 int __glXDisp_CreateGLXPixmap(__GLXclientState *cl, GLbyte *pc)
 {
     xGLXCreateGLXPixmapReq *req = (xGLXCreateGLXPixmapReq *) pc;
-    __GLcontextModes *config;
+    __GLXconfig *config;
     __GLXscreen *pGlxScreen;
     int err;
 
@@ -1160,7 +1159,7 @@ int __glXDisp_CreateGLXPixmap(__GLXclientState *cl, GLbyte *pc)
 int __glXDisp_CreatePixmap(__GLXclientState *cl, GLbyte *pc)
 {
     xGLXCreatePixmapReq *req = (xGLXCreatePixmapReq *) pc;
-    __GLcontextModes *config;
+    __GLXconfig *config;
     __GLXscreen *pGlxScreen;
     int err;
 
@@ -1184,7 +1183,7 @@ int __glXDisp_CreateGLXPixmapWithConfigSGIX(__GLXclientState *cl, GLbyte *pc)
 {
     xGLXCreateGLXPixmapWithConfigSGIXReq *req = 
 	(xGLXCreateGLXPixmapWithConfigSGIXReq *) pc;
-    __GLcontextModes *config;
+    __GLXconfig *config;
     __GLXscreen *pGlxScreen;
     int err;
 
@@ -1246,7 +1245,7 @@ static int
 DoCreatePbuffer(ClientPtr client, int screenNum, XID fbconfigId,
 		int width, int height, XID glxDrawableId)
 {
-    __GLcontextModes	*config;
+    __GLXconfig	*config;
     __GLXscreen		*pGlxScreen;
     PixmapPtr		 pPixmap;
     int			 err;
@@ -1359,7 +1358,7 @@ int __glXDisp_ChangeDrawableAttributesSGIX(__GLXclientState *cl, GLbyte *pc)
 int __glXDisp_CreateWindow(__GLXclientState *cl, GLbyte *pc)
 {
     xGLXCreateWindowReq	*req = (xGLXCreateWindowReq *) pc;
-    __GLcontextModes	*config;
+    __GLXconfig	*config;
     __GLXscreen		*pGlxScreen;
     ClientPtr		 client = cl->client;
     DrawablePtr		 pDraw;
@@ -1473,7 +1472,7 @@ DoQueryContext(__GLXclientState *cl, GLXContextID gcId)
     *pSendBuf++ = GLX_SHARE_CONTEXT_EXT;
     *pSendBuf++ = (int)(ctx->share_id);
     *pSendBuf++ = GLX_VISUAL_ID_EXT;
-    *pSendBuf++ = (int)(ctx->modes->visualID);
+    *pSendBuf++ = (int)(ctx->config->visualID);
     *pSendBuf++ = GLX_SCREEN_EXT;
     *pSendBuf++ = (int)(ctx->pGlxScreen->pScreen->myNum);
 
diff --git a/GL/glx/glxcontext.h b/GL/glx/glxcontext.h
index 4c36801..18d3c6f 100644
--- a/GL/glx/glxcontext.h
+++ b/GL/glx/glxcontext.h
@@ -40,8 +40,6 @@
 **
 */
 
-#include "GL/internal/glcore.h"
-
 typedef struct __GLXtextureFromPixmap __GLXtextureFromPixmap;
 struct __GLXtextureFromPixmap {
     int (*bindTexImage)		(__GLXcontext  *baseContext,
@@ -77,9 +75,9 @@ struct __GLXcontext {
     __GLXcontext *nextReadPriv;
 
     /*
-    ** mode struct for this context
+    ** config struct for this context
     */
-    __GLcontextModes *modes;
+    __GLXconfig *config;
 
     /*
     ** Pointer to screen info data for this context.  This is set
diff --git a/GL/glx/glxdrawable.h b/GL/glx/glxdrawable.h
index f62d1ee..98e301b 100644
--- a/GL/glx/glxdrawable.h
+++ b/GL/glx/glxdrawable.h
@@ -74,7 +74,7 @@ struct __GLXdrawable {
     /*
     ** Configuration of the visual to which this drawable was created.
     */
-    __GLcontextModes *modes;
+    __GLXconfig *config;
 
     /*
     ** Lists of contexts bound to this drawable.  There are two lists here.
diff --git a/GL/glx/glxdri.c b/GL/glx/glxdri.c
index 1e17911..ffa9a0b 100644
--- a/GL/glx/glxdri.c
+++ b/GL/glx/glxdri.c
@@ -52,7 +52,6 @@
 #define DRI_NEW_INTERFACE_ONLY
 #include "glxserver.h"
 #include "glxutil.h"
-#include "glcontextmodes.h"
 
 #include "g_disptab.h"
 #include "glapitable.h"
@@ -61,26 +60,26 @@
 #include "dispatch.h"
 #include "extension_string.h"
 
-#define containerOf(ptr, type, member)			\
-    (type *)( (char *)ptr - offsetof(type,member) )
-
 typedef struct __GLXDRIscreen   __GLXDRIscreen;
 typedef struct __GLXDRIcontext  __GLXDRIcontext;
 typedef struct __GLXDRIdrawable __GLXDRIdrawable;
+typedef struct __GLXDRIconfig	__GLXDRIconfig;
 
 struct __GLXDRIscreen {
     __GLXscreen		 base;
-    __DRIscreen		 driScreen;
+    __DRIscreen		*driScreen;
     void		*driver;
 
     xf86EnterVTProc	*enterVT;
     xf86LeaveVTProc	*leaveVT;
 
-    __DRIcopySubBufferExtension *copySubBuffer;
-    __DRIswapControlExtension *swapControl;
+    const __DRIcoreExtension *core;
+    const __DRIlegacyExtension *legacy;
+    const __DRIcopySubBufferExtension *copySubBuffer;
+    const __DRIswapControlExtension *swapControl;
 
 #ifdef __DRI_TEX_OFFSET
-    __DRItexOffsetExtension *texOffset;
+    const __DRItexOffsetExtension *texOffset;
     DRITexOffsetStartProcPtr texOffsetStart;
     DRITexOffsetFinishProcPtr texOffsetFinish;
     __GLXDRIdrawable *texOffsetOverride[16];
@@ -92,13 +91,13 @@ struct __GLXDRIscreen {
 
 struct __GLXDRIcontext {
     __GLXcontext base;
-    __DRIcontext driContext;
+    __DRIcontext *driContext;
     XID hwContextID;
 };
 
 struct __GLXDRIdrawable {
     __GLXdrawable base;
-    __DRIdrawable driDrawable;
+    __DRIdrawable *driDrawable;
 
     /* Pulled in from old __GLXpixmap */
 #ifdef __DRI_TEX_OFFSET
@@ -109,7 +108,10 @@ struct __GLXDRIdrawable {
 #endif
 };
 
-static const char CREATE_NEW_SCREEN_FUNC[] = __DRI_CREATE_NEW_SCREEN_STRING;
+struct __GLXDRIconfig {
+    __GLXconfig config;
+    __DRIconfig *driConfig;
+};
 
 static void
 __glXDRIleaveServer(GLboolean rendering)
@@ -151,7 +153,7 @@ __glXDRIleaveServer(GLboolean rendering)
 		__GLXDRIdrawable *pGlxPix = texOffsetOverride[j];
 
 		if (pGlxPix && pGlxPix->texname) {
-		    screen->texOffset->setTexOffset(&pGlxPix->ctx->driContext,
+		    screen->texOffset->setTexOffset(pGlxPix->ctx->driContext,
 						    pGlxPix->texname,
 						    pGlxPix->offset,
 						    pGlxPix->base.pDraw->depth,
@@ -219,24 +221,24 @@ static void
 __glXDRIdrawableDestroy(__GLXdrawable *drawable)
 {
     __GLXDRIdrawable *private = (__GLXDRIdrawable *) drawable;
-
+    __GLXDRIscreen *screen;
     int i;
 
     for (i = 0; i < screenInfo.numScreens; i++) {
-	__glXDRIdoReleaseTexImage((__GLXDRIscreen *)
-				  glxGetScreen(screenInfo.screens[i]),
-				  private);
+	screen = (__GLXDRIscreen *) glxGetScreen(screenInfo.screens[i]);
+	__glXDRIdoReleaseTexImage(screen, private);
     }
 
-    (*private->driDrawable.destroyDrawable)(&private->driDrawable);
-
     /* If the X window was destroyed, the dri DestroyWindow hook will
      * aready have taken care of this, so only call if pDraw isn't NULL. */
     if (drawable->pDraw != NULL) {
-	    __glXenterServer(GL_FALSE);
-	    DRIDestroyDrawable(drawable->pDraw->pScreen,
-			       serverClient, drawable->pDraw);
-	    __glXleaveServer(GL_FALSE);
+	screen = (__GLXDRIscreen *) glxGetScreen(drawable->pDraw->pScreen);
+	(*screen->core->destroyDrawable)(private->driDrawable);
+
+	__glXenterServer(GL_FALSE);
+	DRIDestroyDrawable(drawable->pDraw->pScreen,
+			   serverClient, drawable->pDraw);
+	__glXleaveServer(GL_FALSE);
     }
 
     xfree(private);
@@ -255,8 +257,10 @@ static GLboolean
 __glXDRIdrawableSwapBuffers(__GLXdrawable *basePrivate)
 {
     __GLXDRIdrawable *private = (__GLXDRIdrawable *) basePrivate;
+    __GLXDRIscreen *screen =
+	(__GLXDRIscreen *) glxGetScreen(basePrivate->pDraw->pScreen);
 
-    (*private->driDrawable.swapBuffers)(&private->driDrawable);
+    (*screen->core->swapBuffers)(private->driDrawable);
 
     return TRUE;
 }
@@ -266,11 +270,11 @@ static int
 __glXDRIdrawableSwapInterval(__GLXdrawable *baseDrawable, int interval)
 {
     __GLXDRIdrawable *draw = (__GLXDRIdrawable *) baseDrawable;
-    __GLXDRIscreen *screen = (__GLXDRIscreen *)
-	glxGetScreen(baseDrawable->pDraw->pScreen);
+    __GLXDRIscreen *screen =
+	(__GLXDRIscreen *) glxGetScreen(baseDrawable->pDraw->pScreen);
 
     if (screen->swapControl)
-	screen->swapControl->setSwapInterval(&draw->driDrawable, interval);
+	screen->swapControl->setSwapInterval(draw->driDrawable, interval);
 
     return 0;
 }
@@ -285,20 +289,21 @@ __glXDRIdrawableCopySubBuffer(__GLXdrawable *basePrivate,
 	glxGetScreen(basePrivate->pDraw->pScreen);
 
     if (screen->copySubBuffer)
-	screen->copySubBuffer->copySubBuffer(&private->driDrawable,
-					     x, y, w, h);
+	screen->copySubBuffer->copySubBuffer(private->driDrawable, x, y, w, h);
 }
 
 static void
 __glXDRIcontextDestroy(__GLXcontext *baseContext)
 {
     __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
+    __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen;
     Bool retval;
 
-    context->driContext.destroyContext(&context->driContext);
+    screen->core->destroyContext(context->driContext);
 
     __glXenterServer(GL_FALSE);
-    retval = DRIDestroyContext(baseContext->pGlxScreen->pScreen, context->hwContextID);
+    retval = DRIDestroyContext(baseContext->pGlxScreen->pScreen,
+			       context->hwContextID);
     __glXleaveServer(GL_FALSE);
 
     __glXContextDestroy(&context->base);
@@ -309,20 +314,22 @@ static int
 __glXDRIcontextMakeCurrent(__GLXcontext *baseContext)
 {
     __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
+    __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen;
     __GLXDRIdrawable *draw = (__GLXDRIdrawable *) baseContext->drawPriv;
     __GLXDRIdrawable *read = (__GLXDRIdrawable *) baseContext->readPriv;
 
-    return (*context->driContext.bindContext)(&context->driContext,
-					      &draw->driDrawable,
-					      &read->driDrawable);
+    return (*screen->core->bindContext)(context->driContext,
+					draw->driDrawable,
+					read->driDrawable);
 }					      
 
 static int
 __glXDRIcontextLoseCurrent(__GLXcontext *baseContext)
 {
     __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
+    __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen;
 
-    return (*context->driContext.unbindContext)(&context->driContext);
+    return (*screen->core->unbindContext)(context->driContext);
 }
 
 static int
@@ -331,13 +338,10 @@ __glXDRIcontextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc,
 {
     __GLXDRIcontext *dst = (__GLXDRIcontext *) baseDst;
     __GLXDRIcontext *src = (__GLXDRIcontext *) baseSrc;
+    __GLXDRIscreen *screen = (__GLXDRIscreen *) dst->base.pGlxScreen;
 
-    /* FIXME: We will need to add DRIcontext::copyContext for this. */
-
-    (void) dst;
-    (void) src;
-
-    return FALSE;
+    return (*screen->core->copyContext)(dst->driContext,
+					src->driContext, mask);
 }
 
 static int
@@ -346,10 +350,11 @@ __glXDRIcontextForceCurrent(__GLXcontext *baseContext)
     __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
     __GLXDRIdrawable *draw = (__GLXDRIdrawable *) baseContext->drawPriv;
     __GLXDRIdrawable *read = (__GLXDRIdrawable *) baseContext->readPriv;
+    __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen;
 
-    return (*context->driContext.bindContext)(&context->driContext,
-					      &draw->driDrawable,
-					      &read->driDrawable);
+    return (*screen->core->bindContext)(context->driContext,
+					draw->driDrawable,
+					read->driDrawable);
 }
 
 static void
@@ -392,10 +397,8 @@ __glXDRIbindTexImage(__GLXcontext *baseContext,
     int		bpp, override = 0, texname;
     GLenum	format, type;
     ScreenPtr pScreen = glxPixmap->pDraw->pScreen;
-    __GLXDRIdrawable *driDraw =
-	    containerOf(glxPixmap, __GLXDRIdrawable, base);
-    __GLXDRIscreen * const screen =
-	    (__GLXDRIscreen *) glxGetScreen(pScreen);
+    __GLXDRIdrawable *driDraw = (__GLXDRIdrawable *) glxPixmap;
+    __GLXDRIscreen * const screen = (__GLXDRIscreen *) glxGetScreen(pScreen);
 
     CALL_GetIntegerv(GET_DISPATCH(), (glxPixmap->target == GL_TEXTURE_2D ?
 				      GL_TEXTURE_BINDING_2D :
@@ -439,7 +442,7 @@ alreadyin:
 
 	driDraw->texname = texname;
 
-	screen->texOffset->setTexOffset(&driDraw->ctx->driContext, texname, 0,
+	screen->texOffset->setTexOffset(driDraw->ctx->driContext, texname, 0,
 					pixmap->drawable.depth,
 					pixmap->devKind);
     }
@@ -568,9 +571,11 @@ __glXDRIreleaseTexImage(__GLXcontext *baseContext,
 			int buffer,
 			__GLXdrawable *pixmap)
 {
-    __glXDRIdoReleaseTexImage((__GLXDRIscreen *)
-			      glxGetScreen(pixmap->pDraw->pScreen),
-			      containerOf(pixmap, __GLXDRIdrawable, base));
+    __GLXDRIscreen *screen =
+	(__GLXDRIscreen *) glxGetScreen(pixmap->pDraw->pScreen);
+    __GLXDRIdrawable *drawable = (__GLXDRIdrawable *) pixmap;
+
+    __glXDRIdoReleaseTexImage(screen, drawable);
 
     return Success;
 }
@@ -585,7 +590,7 @@ __glXDRIscreenDestroy(__GLXscreen *baseScreen)
 {
     __GLXDRIscreen *screen = (__GLXDRIscreen *) baseScreen;
 
-    screen->driScreen.destroyScreen(&screen->driScreen);
+    screen->core->destroyScreen(screen->driScreen);
 
     dlclose(screen->driver);
 
@@ -596,11 +601,12 @@ __glXDRIscreenDestroy(__GLXscreen *baseScreen)
 
 static __GLXcontext *
 __glXDRIscreenCreateContext(__GLXscreen *baseScreen,
-			    __GLcontextModes *modes,
+			    __GLXconfig *glxConfig,
 			    __GLXcontext *baseShareContext)
 {
     __GLXDRIscreen *screen = (__GLXDRIscreen *) baseScreen;
     __GLXDRIcontext *context, *shareContext;
+    __GLXDRIconfig *config = (__GLXDRIconfig *) glxConfig;
     VisualPtr visual;
     int i;
     GLboolean retval;
@@ -610,7 +616,7 @@ __glXDRIscreenCreateContext(__GLXscreen *baseScreen,
 
     shareContext = (__GLXDRIcontext *) baseShareContext;
     if (shareContext)
-	driShare = &shareContext->driContext;
+	driShare = shareContext->driContext;
     else
 	driShare = NULL;
 
@@ -632,7 +638,7 @@ __glXDRIscreenCreateContext(__GLXscreen *baseScreen,
     /* Find the requested X visual */
     visual = pScreen->visuals;
     for (i = 0; i < pScreen->numVisuals; i++, visual++)
-	if (visual->vid == modes->visualID)
+	if (visual->vid == glxConfig->visualID)
 	    break;
     if (i == pScreen->numVisuals)
 	return GL_FALSE;
@@ -644,15 +650,15 @@ __glXDRIscreenCreateContext(__GLXscreen *baseScreen,
 			      context->hwContextID, &hwContext);
     __glXleaveServer(GL_FALSE);
 
-    context->driContext.private =
-	screen->driScreen.createNewContext(&screen->driScreen,
-					   modes,
-					   0, /* render type */
-					   driShare,
-					   hwContext,
-					   &context->driContext);
+    context->driContext =
+	screen->legacy->createNewContext(screen->driScreen,
+					 config->driConfig,
+					 0, /* render type */
+					 driShare,
+					 hwContext,
+					 context);
 
-    if (context->driContext.private == NULL) {
+    if (context->driContext == NULL) {
     	__glXenterServer(GL_FALSE);
 	retval = DRIDestroyContext(baseScreen->pScreen, context->hwContextID);
     	__glXleaveServer(GL_FALSE);
@@ -668,9 +674,10 @@ __glXDRIscreenCreateDrawable(__GLXscreen *screen,
 			     DrawablePtr pDraw,
 			     int type,
 			     XID drawId,
-			     __GLcontextModes *modes)
+			     __GLXconfig *glxConfig)
 {
     __GLXDRIscreen *driScreen = (__GLXDRIscreen *) screen;
+    __GLXDRIconfig *config = (__GLXDRIconfig *) glxConfig;
     __GLXDRIdrawable *private;
     GLboolean retval;
     drm_drawable_t hwDrawable;
@@ -682,7 +689,7 @@ __glXDRIscreenCreateDrawable(__GLXscreen *screen,
     memset(private, 0, sizeof *private);
 
     if (!__glXDrawableInit(&private->base, screen,
-			   pDraw, type, drawId, modes)) {
+			   pDraw, type, drawId, glxConfig)) {
         xfree(private);
 	return NULL;
     }
@@ -700,13 +707,12 @@ __glXDRIscreenCreateDrawable(__GLXscreen *screen,
     /* The last argument is 'attrs', which is used with pbuffers which
      * we currently don't support. */
 
-    private->driDrawable.private =
-	(driScreen->driScreen.createNewDrawable)(&driScreen->driScreen,
-						 modes,
-						 &private->driDrawable,
-						 hwDrawable, 0, 0, NULL);
+    private->driDrawable =
+	(driScreen->legacy->createNewDrawable)(driScreen->driScreen,
+					       config->driConfig,
+					       hwDrawable, 0, NULL, private);
 
-    if (private->driDrawable.private == NULL) {
+    if (private->driDrawable == NULL) {
 	__glXenterServer(GL_FALSE);
 	DRIDestroyDrawable(screen->pScreen, serverClient, pDraw);
 	__glXleaveServer(GL_FALSE);
@@ -723,10 +729,10 @@ getDrawableInfo(__DRIdrawable *driDrawable,
 		int *x, int *y, int *width, int *height,
 		int *numClipRects, drm_clip_rect_t **ppClipRects,
 		int *backX, int *backY,
-		int *numBackClipRects, drm_clip_rect_t **ppBackClipRects)
+		int *numBackClipRects, drm_clip_rect_t **ppBackClipRects,
+		void *data)
 {
-    __GLXDRIdrawable *drawable = containerOf(driDrawable,
-					     __GLXDRIdrawable, driDrawable);
+    __GLXDRIdrawable *drawable = data;
     ScreenPtr pScreen;
     drm_clip_rect_t *pClipRects, *pBackClipRects;
     GLboolean retval;
@@ -810,10 +816,10 @@ getUST(int64_t *ust)
 static void __glXReportDamage(__DRIdrawable *driDraw,
 			      int x, int y,
 			      drm_clip_rect_t *rects, int num_rects,
-			      GLboolean front_buffer)
+			      GLboolean front_buffer,
+			      void *data)
 {
-    __GLXDRIdrawable *drawable =
-	    containerOf(driDraw, __GLXDRIdrawable, driDrawable);
+    __GLXDRIdrawable *drawable = data;
     DrawablePtr pDraw = drawable->base.pDraw;
     RegionRec region;
 
@@ -827,13 +833,6 @@ static void __glXReportDamage(__DRIdrawable *driDraw,
     __glXleaveServer(GL_FALSE);
 }
 
-/* Table of functions that we export to the driver. */
-static const __DRIcontextModesExtension contextModesExtension = {
-    { __DRI_CONTEXT_MODES, __DRI_CONTEXT_MODES_VERSION },
-    _gl_context_modes_create,
-    _gl_context_modes_destroy,
-};
-
 static const __DRIsystemTimeExtension systemTimeExtension = {
     { __DRI_SYSTEM_TIME, __DRI_SYSTEM_TIME_VERSION },
     getUST,
@@ -851,7 +850,6 @@ static const __DRIdamageExtension damageExtension = {
 };
 
 static const __DRIextension *loader_extensions[] = {
-    &contextModesExtension.base,
     &systemTimeExtension.base,
     &getDrawableInfoExtension.base,
     &damageExtension.base,
@@ -897,7 +895,8 @@ initializeExtensions(__GLXDRIscreen *screen)
     const __DRIextension **extensions;
     int i;
 
-    extensions = screen->driScreen.getExtensions(&screen->driScreen);
+    extensions = screen->core->getExtensions(screen->driScreen);
+
     for (i = 0; extensions[i]; i++) {
 #ifdef __DRI_COPY_SUB_BUFFER
 	if (strcmp(extensions[i]->name, __DRI_COPY_SUB_BUFFER) == 0) {
@@ -931,12 +930,12 @@ initializeExtensions(__GLXDRIscreen *screen)
     }
 }
     
-#define COPY_SUB_BUFFER_INTERNAL_VERSION 20060314
+extern __GLXconfig *
+glxConvertConfigs(const __DRIcoreExtension *core, const __DRIconfig **configs);
 
 static __GLXscreen *
 __glXDRIscreenProbe(ScreenPtr pScreen)
 {
-    PFNCREATENEWSCREENFUNC createNewScreen;
     drm_handle_t hSAREA;
     drmAddress pSAREA = NULL;
     char *BusID;
@@ -953,11 +952,13 @@ __glXDRIscreenProbe(ScreenPtr pScreen)
     drm_handle_t  hFB;
     int        junk;
     __GLXDRIscreen *screen;
-    void *dev_priv = NULL;
     char filename[128];
     Bool isCapable;
     size_t buffer_size;
     ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
+    const __DRIconfig **driConfigs;
+    const __DRIextension **extensions;
+    int i;
 
     if (!xf86LoaderCheckSymbol("DRIQueryDirectRenderingCapable") ||
 	!DRIQueryDirectRenderingCapable(pScreen, &isCapable) ||
@@ -985,9 +986,6 @@ __glXDRIscreenProbe(ScreenPtr pScreen)
     dri_version.minor = XF86DRI_MINOR_VERSION;
     dri_version.patch = XF86DRI_PATCH_VERSION;
 
-    framebuffer.base = NULL;
-    framebuffer.dev_priv = NULL;
-
     if (!DRIOpenConnection(pScreen, &hSAREA, &BusID)) {
 	LogMessage(X_ERROR, "AIGLX error: DRIOpenConnection failed\n");
 	goto handle_error;
@@ -1046,11 +1044,30 @@ __glXDRIscreenProbe(ScreenPtr pScreen)
         goto handle_error;
     }
 
-    createNewScreen = dlsym(screen->driver, CREATE_NEW_SCREEN_FUNC);
-    if (createNewScreen == NULL) {
-	LogMessage(X_ERROR, "AIGLX error: dlsym for %s failed (%s)\n",
-		   CREATE_NEW_SCREEN_FUNC, dlerror());
-      goto handle_error;
+    extensions = dlsym(screen->driver, __DRI_DRIVER_EXTENSIONS);
+    if (extensions == NULL) {
+	LogMessage(X_ERROR, "AIGLX error: %s exports no extensions (%s)\n",
+		   driverName, dlerror());
+	goto handle_error;
+    }
+    
+    for (i = 0; extensions[i]; i++) {
+	if (strcmp(extensions[i]->name, __DRI_CORE) == 0 &&
+	    extensions[i]->version >= __DRI_CORE_VERSION) {
+		screen->core = (__DRIcoreExtension *) extensions[i];
+	}
+
+	if (strcmp(extensions[i]->name, __DRI_LEGACY) == 0 &&
+	    extensions[i]->version >= __DRI_LEGACY_VERSION) {
+		screen->legacy = (__DRIlegacyExtension *) extensions[i];
+	}
+    }
+
+    if (screen->core == NULL || screen->legacy == NULL) {
+	LogMessage(X_ERROR,
+		   "AIGLX error: %s does not export required DRI extension\n",
+		   driverName);
+	goto handle_error;
     }
 
     /*
@@ -1066,19 +1083,6 @@ __glXDRIscreenProbe(ScreenPtr pScreen)
 	goto handle_error;
     }
 
-    /* Sigh... the DRI interface is broken; the DRI driver will free
-     * the dev private pointer using _mesa_free() on screen destroy,
-     * but we can't use _mesa_malloc() here.  In fact, the DRI driver
-     * shouldn't free data it didn't allocate itself, but what can you
-     * do... */
-    dev_priv = xalloc(framebuffer.dev_priv_size);
-    if (dev_priv == NULL) {
-	LogMessage(X_ERROR, "AIGLX error: dev_priv allocation failed");
-	goto handle_error;
-    }
-    memcpy(dev_priv, framebuffer.dev_priv, framebuffer.dev_priv_size);
-    framebuffer.dev_priv = dev_priv;
-
     framebuffer.width = pScreen->width;
     framebuffer.height = pScreen->height;
 
@@ -1101,28 +1105,30 @@ __glXDRIscreenProbe(ScreenPtr pScreen)
 	goto handle_error;
     }
     
-    screen->driScreen.private =
-	(*createNewScreen)(pScreen->myNum,
-			   &screen->driScreen,
-			   &ddx_version,
-			   &dri_version,
-			   &drm_version,
-			   &framebuffer,
-			   pSAREA,
-			   fd,
-			   loader_extensions,
-			   &screen->base.fbconfigs);
-
-    if (screen->driScreen.private == NULL) {
+    screen->driScreen =
+	(*screen->legacy->createNewScreen)(pScreen->myNum,
+					   &ddx_version,
+					   &dri_version,
+					   &drm_version,
+					   &framebuffer,
+					   pSAREA,
+					   fd,
+					   loader_extensions,
+					   &driConfigs,
+					   screen);
+
+    screen->base.fbconfigs = glxConvertConfigs(screen->core, driConfigs);
+
+    if (screen->driScreen == NULL) {
 	LogMessage(X_ERROR, "AIGLX error: Calling driver entry point failed");
 	goto handle_error;
     }
 
+    initializeExtensions(screen);
+
     DRIGetTexOffsetFuncs(pScreen, &screen->texOffsetStart,
 			 &screen->texOffsetFinish);
 
-    initializeExtensions(screen);
-
     __glXScreenInit(&screen->base, pScreen);
 
     buffer_size = __glXGetExtensionString(screen->glx_enable_bits, NULL);
@@ -1155,9 +1161,6 @@ __glXDRIscreenProbe(ScreenPtr pScreen)
     if (framebuffer.base != NULL)
 	drmUnmap((drmAddress)framebuffer.base, framebuffer.size);
 
-    if (dev_priv != NULL)
-	xfree(dev_priv);
-
     if (fd >= 0)
 	drmCloseOnce(fd);
 
diff --git a/GL/glx/glxdri2.c b/GL/glx/glxdri2.c
index fecfb19..40590c1 100644
--- a/GL/glx/glxdri2.c
+++ b/GL/glx/glxdri2.c
@@ -35,20 +35,18 @@
 #include <drm.h>
 #include <GL/gl.h>
 #include <GL/internal/dri_interface.h>
+#include <GL/glxtokens.h>
 
 #include <windowstr.h>
 #include <os.h>
 
 #define _XF86DRI_SERVER_
 #include <xf86drm.h>
-#include <xf86dristr.h>
-#include <xf86str.h>
 #include <xf86.h>
 #include <dri2.h>
 
 #include "glxserver.h"
 #include "glxutil.h"
-#include "glcontextmodes.h"
 
 #include "g_disptab.h"
 #include "glapitable.h"
@@ -57,53 +55,56 @@
 #include "dispatch.h"
 #include "extension_string.h"
 
-#define containerOf(ptr, type, member)			\
-    (type *)( (char *)ptr - offsetof(type,member) )
-
 typedef struct __GLXDRIscreen   __GLXDRIscreen;
 typedef struct __GLXDRIcontext  __GLXDRIcontext;
 typedef struct __GLXDRIdrawable __GLXDRIdrawable;
+typedef struct __GLXDRIconfig	__GLXDRIconfig;
 
 struct __GLXDRIscreen {
     __GLXscreen		 base;
-    __DRIscreen		 driScreen;
+    __DRIscreen		*driScreen;
     void		*driver;
     int			 fd;
 
     xf86EnterVTProc	*enterVT;
     xf86LeaveVTProc	*leaveVT;
 
-    __DRIcopySubBufferExtension *copySubBuffer;
-    __DRIswapControlExtension *swapControl;
-    __DRItexBufferExtension *texBuffer;
+    const __DRIcoreExtension *core;
+    const __DRIcopySubBufferExtension *copySubBuffer;
+    const __DRIswapControlExtension *swapControl;
+    const __DRItexBufferExtension *texBuffer;
 
     unsigned char glx_enable_bits[__GLX_EXT_BYTES];
 };
 
 struct __GLXDRIcontext {
-    __GLXcontext base;
-    __DRIcontext driContext;
-    drm_context_t hwContext;
+    __GLXcontext	 base;
+    __DRIcontext	*driContext;
 };
 
 struct __GLXDRIdrawable {
-    __GLXdrawable base;
-    __DRIdrawable driDrawable;
+    __GLXdrawable	 base;
+    __DRIdrawable	*driDrawable;
+    __GLXDRIscreen	*screen;
 };
 
-static const char CREATE_NEW_SCREEN_FUNC[] = __DRI2_CREATE_NEW_SCREEN_STRING;
+struct __GLXDRIconfig {
+    __GLXconfig config;
+    const __DRIconfig *driConfig;
+};
 
 static void
 __glXDRIdrawableDestroy(__GLXdrawable *drawable)
 {
     __GLXDRIdrawable *private = (__GLXDRIdrawable *) drawable;
-
-    (*private->driDrawable.destroyDrawable)(&private->driDrawable);
+    const __DRIcoreExtension *core = private->screen->core;
+    
+    (*core->destroyDrawable)(private->driDrawable);
 
     /* If the X window was destroyed, the dri DestroyWindow hook will
      * aready have taken care of this, so only call if pDraw isn't NULL. */
     if (drawable->pDraw != NULL)
-	DRI2DestroyDrawable(drawable->pDraw->pScreen, drawable->pDraw);
+	DRI2DestroyDrawable(drawable->pDraw);
 
     xfree(private);
 }
@@ -118,25 +119,25 @@ __glXDRIdrawableResize(__GLXdrawable *glxPriv)
 }
 
 static GLboolean
-__glXDRIdrawableSwapBuffers(__GLXdrawable *basePrivate)
+__glXDRIdrawableSwapBuffers(__GLXdrawable *drawable)
 {
-    __GLXDRIdrawable *private = (__GLXDRIdrawable *) basePrivate;
+    __GLXDRIdrawable *private = (__GLXDRIdrawable *) drawable;
+    const __DRIcoreExtension *core = private->screen->core;
 
-    (*private->driDrawable.swapBuffers)(&private->driDrawable);
+    (*core->swapBuffers)(private->driDrawable);
 
     return TRUE;
 }
 
 
 static int
-__glXDRIdrawableSwapInterval(__GLXdrawable *baseDrawable, int interval)
+__glXDRIdrawableSwapInterval(__GLXdrawable *drawable, int interval)
 {
-    __GLXDRIdrawable *draw = (__GLXDRIdrawable *) baseDrawable;
-    __GLXDRIscreen *screen = (__GLXDRIscreen *)
-	glxGetScreen(baseDrawable->pDraw->pScreen);
+    __GLXDRIdrawable *private = (__GLXDRIdrawable *) drawable;
+    const __DRIswapControlExtension *swapControl = private->screen->swapControl;
 
-    if (screen->swapControl)
-	screen->swapControl->setSwapInterval(&draw->driDrawable, interval);
+    if (swapControl)
+	swapControl->setSwapInterval(private->driDrawable, interval);
 
     return 0;
 }
@@ -147,22 +148,20 @@ __glXDRIdrawableCopySubBuffer(__GLXdrawable *basePrivate,
 			       int x, int y, int w, int h)
 {
     __GLXDRIdrawable *private = (__GLXDRIdrawable *) basePrivate;
-    __GLXDRIscreen *screen = (__GLXDRIscreen *)
-	glxGetScreen(basePrivate->pDraw->pScreen);
+    const __DRIcopySubBufferExtension *copySubBuffer =
+	    private->screen->copySubBuffer;
 
-    if (screen->copySubBuffer)
-	screen->copySubBuffer->copySubBuffer(&private->driDrawable,
-					     x, y, w, h);
+    if (copySubBuffer)
+	(*copySubBuffer->copySubBuffer)(private->driDrawable, x, y, w, h);
 }
 
 static void
 __glXDRIcontextDestroy(__GLXcontext *baseContext)
 {
     __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
-    __GLXDRIscreen *screen = (__GLXDRIscreen *) baseContext->pGlxScreen;
+    __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen;
 
-    context->driContext.destroyContext(&context->driContext);
-    drmDestroyContext(screen->fd, context->hwContext);
+    (*screen->core->destroyContext)(context->driContext);
     __glXContextDestroy(&context->base);
     xfree(context);
 }
@@ -173,18 +172,20 @@ __glXDRIcontextMakeCurrent(__GLXcontext *baseContext)
     __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
     __GLXDRIdrawable *draw = (__GLXDRIdrawable *) baseContext->drawPriv;
     __GLXDRIdrawable *read = (__GLXDRIdrawable *) baseContext->readPriv;
+    __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen;
 
-    return (*context->driContext.bindContext)(&context->driContext,
-					      &draw->driDrawable,
-					      &read->driDrawable);
+    return (*screen->core->bindContext)(context->driContext,
+					draw->driDrawable,
+					read->driDrawable);
 }					      
 
 static int
 __glXDRIcontextLoseCurrent(__GLXcontext *baseContext)
 {
     __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
+    __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen;
 
-    return (*context->driContext.unbindContext)(&context->driContext);
+    return (*screen->core->unbindContext)(context->driContext);
 }
 
 static int
@@ -193,13 +194,10 @@ __glXDRIcontextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc,
 {
     __GLXDRIcontext *dst = (__GLXDRIcontext *) baseDst;
     __GLXDRIcontext *src = (__GLXDRIcontext *) baseSrc;
+    __GLXDRIscreen *screen = (__GLXDRIscreen *) dst->base.pGlxScreen;
 
-    /* FIXME: We will need to add DRIcontext::copyContext for this. */
-
-    (void) dst;
-    (void) src;
-
-    return FALSE;
+    return (*screen->core->copyContext)(dst->driContext,
+					src->driContext, mask);
 }
 
 static int
@@ -208,10 +206,11 @@ __glXDRIcontextForceCurrent(__GLXcontext *baseContext)
     __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
     __GLXDRIdrawable *draw = (__GLXDRIdrawable *) baseContext->drawPriv;
     __GLXDRIdrawable *read = (__GLXDRIdrawable *) baseContext->readPriv;
+    __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen;
 
-    return (*context->driContext.bindContext)(&context->driContext,
-					      &draw->driDrawable,
-					      &read->driDrawable);
+    return (*screen->core->bindContext)(context->driContext,
+					draw->driDrawable,
+					read->driDrawable);
 }
 
 #ifdef __DRI_TEX_BUFFER
@@ -221,19 +220,16 @@ __glXDRIbindTexImage(__GLXcontext *baseContext,
 		     int buffer,
 		     __GLXdrawable *glxPixmap)
 {
-    ScreenPtr pScreen = glxPixmap->pDraw->pScreen;
-    __GLXDRIscreen * const screen = (__GLXDRIscreen *) glxGetScreen(pScreen);
-    PixmapPtr pixmap;
-    __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
     __GLXDRIdrawable *drawable = (__GLXDRIdrawable *) glxPixmap;
+    const __DRItexBufferExtension *texBuffer = drawable->screen->texBuffer;
+    __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
 
-    if (screen->texBuffer == NULL)
+    if (texBuffer == NULL)
         return Success;
 
-    pixmap = (PixmapPtr) glxPixmap->pDraw;
-    screen->texBuffer->setTexBuffer(&context->driContext,
-				    glxPixmap->target,
-				    &drawable->driDrawable);
+    texBuffer->setTexBuffer(context->driContext,
+			    glxPixmap->target,
+			    drawable->driDrawable);
 
     return Success;
 }
@@ -277,7 +273,7 @@ __glXDRIscreenDestroy(__GLXscreen *baseScreen)
 {
     __GLXDRIscreen *screen = (__GLXDRIscreen *) baseScreen;
 
-    screen->driScreen.destroyScreen(&screen->driScreen);
+    (*screen->core->destroyScreen)(screen->driScreen);
 
     dlclose(screen->driver);
 
@@ -288,16 +284,18 @@ __glXDRIscreenDestroy(__GLXscreen *baseScreen)
 
 static __GLXcontext *
 __glXDRIscreenCreateContext(__GLXscreen *baseScreen,
-			    __GLcontextModes *modes,
+			    __GLXconfig *glxConfig,
 			    __GLXcontext *baseShareContext)
 {
     __GLXDRIscreen *screen = (__GLXDRIscreen *) baseScreen;
     __GLXDRIcontext *context, *shareContext;
+    __GLXDRIconfig *config = (__GLXDRIconfig *) glxConfig;
+    const __DRIcoreExtension *core = screen->core;
     __DRIcontext *driShare;
 
     shareContext = (__GLXDRIcontext *) baseShareContext;
     if (shareContext)
-	driShare = &shareContext->driContext;
+	driShare = shareContext->driContext;
     else
 	driShare = NULL;
 
@@ -313,16 +311,9 @@ __glXDRIscreenCreateContext(__GLXscreen *baseScreen,
     context->base.forceCurrent      = __glXDRIcontextForceCurrent;
     context->base.textureFromPixmap = &__glXDRItextureFromPixmap;
 
-    if (drmCreateContext(screen->fd, &context->hwContext))
-	    return GL_FALSE;
-
-    context->driContext.private =
-	screen->driScreen.createNewContext(&screen->driScreen,
-					   modes,
-					   0, /* render type */
-					   driShare,
-					   context->hwContext,
-					   &context->driContext);
+    context->driContext =
+	(*core->createNewContext)(screen->driScreen,
+				  config->driConfig, driShare, context);
 
     return &context->base;
 }
@@ -332,13 +323,13 @@ __glXDRIscreenCreateDrawable(__GLXscreen *screen,
 			     DrawablePtr pDraw,
 			     int type,
 			     XID drawId,
-			     __GLcontextModes *modes)
+			     __GLXconfig *glxConfig)
 {
     __GLXDRIscreen *driScreen = (__GLXDRIscreen *) screen;
+    __GLXDRIconfig *config = (__GLXDRIconfig *) glxConfig;
     __GLXDRIdrawable *private;
     GLboolean retval;
-    drm_drawable_t hwDrawable;
-    unsigned int head;
+    unsigned int handle, head;
 
     private = xalloc(sizeof *private);
     if (private == NULL)
@@ -346,8 +337,9 @@ __glXDRIscreenCreateDrawable(__GLXscreen *screen,
 
     memset(private, 0, sizeof *private);
 
+    private->screen = driScreen;
     if (!__glXDrawableInit(&private->base, screen,
-			   pDraw, type, drawId, modes)) {
+			   pDraw, type, drawId, glxConfig)) {
         xfree(private);
 	return NULL;
     }
@@ -357,14 +349,12 @@ __glXDRIscreenCreateDrawable(__GLXscreen *screen,
     private->base.swapBuffers   = __glXDRIdrawableSwapBuffers;
     private->base.copySubBuffer = __glXDRIdrawableCopySubBuffer;
 
-    retval = DRI2CreateDrawable(screen->pScreen, pDraw,
-				&hwDrawable, &head);
+    retval = DRI2CreateDrawable(pDraw, &handle, &head);
 
-    private->driDrawable.private =
-	(driScreen->driScreen.createNewDrawable)(&driScreen->driScreen,
-						 modes,
-						 &private->driDrawable,
-						 hwDrawable, head, 0, NULL);
+    private->driDrawable =
+	(*driScreen->core->createNewDrawable)(driScreen->driScreen, 
+					      config->driConfig,
+					      handle, head, private);
 
     return &private->base;
 }
@@ -385,44 +375,43 @@ getUST(int64_t *ust)
     }
 }
 
-static void __glXReportDamage(__DRIdrawable *driDraw,
-			      int x, int y,
-			      drm_clip_rect_t *rects, int num_rects,
-			      GLboolean front_buffer)
+static const __DRIsystemTimeExtension systemTimeExtension = {
+    { __DRI_SYSTEM_TIME, __DRI_SYSTEM_TIME_VERSION },
+    getUST,
+    NULL,
+};
+
+static void dri2ReemitDrawableInfo(__DRIdrawable *draw, unsigned int *tail,
+				   void *loaderPrivate)
 {
-    __GLXDRIdrawable *drawable =
-	    containerOf(driDraw, __GLXDRIdrawable, driDrawable);
+    __GLXDRIdrawable *pdraw = loaderPrivate;
+
+    DRI2ReemitDrawableInfo(pdraw->base.pDraw, tail);
+}
+
+static void dri2PostDamage(__DRIdrawable *draw,
+			   struct drm_clip_rect *rects,
+			   int numRects, void *loaderPrivate)
+{ 
+    __GLXDRIdrawable *drawable = loaderPrivate;
     DrawablePtr pDraw = drawable->base.pDraw;
     RegionRec region;
 
-    REGION_INIT(pDraw->pScreen, &region, (BoxPtr) rects, num_rects);
+    REGION_INIT(pDraw->pScreen, &region, (BoxPtr) rects, numRects);
     REGION_TRANSLATE(pScreen, &region, pDraw->x, pDraw->y);
     DamageDamageRegion(pDraw, &region);
     REGION_UNINIT(pDraw->pScreen, &region);
 }
 
-/* Table of functions that we export to the driver. */
-static const __DRIcontextModesExtension contextModesExtension = {
-    { __DRI_CONTEXT_MODES, __DRI_CONTEXT_MODES_VERSION },
-    _gl_context_modes_create,
-    _gl_context_modes_destroy,
-};
-
-static const __DRIsystemTimeExtension systemTimeExtension = {
-    { __DRI_SYSTEM_TIME, __DRI_SYSTEM_TIME_VERSION },
-    getUST,
-    NULL,
-};
-
-static const __DRIdamageExtension damageExtension = {
-    { __DRI_DAMAGE, __DRI_DAMAGE_VERSION },
-    __glXReportDamage,
+static const __DRIloaderExtension loaderExtension = {
+    { __DRI_LOADER, __DRI_LOADER_VERSION },
+    dri2ReemitDrawableInfo,
+    dri2PostDamage
 };
 
 static const __DRIextension *loader_extensions[] = {
-    &contextModesExtension.base,
     &systemTimeExtension.base,
-    &damageExtension.base,
+    &loaderExtension.base,
     NULL
 };
 
@@ -463,11 +452,13 @@ initializeExtensions(__GLXDRIscreen *screen)
     const __DRIextension **extensions;
     int i;
 
-    extensions = screen->driScreen.getExtensions(&screen->driScreen);
+    extensions = screen->core->getExtensions(screen->driScreen);
+
     for (i = 0; extensions[i]; i++) {
 #ifdef __DRI_COPY_SUB_BUFFER
 	if (strcmp(extensions[i]->name, __DRI_COPY_SUB_BUFFER) == 0) {
-	    screen->copySubBuffer = (__DRIcopySubBufferExtension *) extensions[i];
+	    screen->copySubBuffer =
+		(const __DRIcopySubBufferExtension *) extensions[i];
 	    __glXEnableExtension(screen->glx_enable_bits,
 				 "GLX_MESA_copy_sub_buffer");
 	    
@@ -477,7 +468,8 @@ initializeExtensions(__GLXDRIscreen *screen)
 
 #ifdef __DRI_SWAP_CONTROL
 	if (strcmp(extensions[i]->name, __DRI_SWAP_CONTROL) == 0) {
-	    screen->swapControl = (__DRIswapControlExtension *) extensions[i];
+	    screen->swapControl =
+		(const __DRIswapControlExtension *) extensions[i];
 	    __glXEnableExtension(screen->glx_enable_bits,
 				 "GLX_SGI_swap_control");
 	    __glXEnableExtension(screen->glx_enable_bits,
@@ -489,7 +481,8 @@ initializeExtensions(__GLXDRIscreen *screen)
 
 #ifdef __DRI_TEX_BUFFER
 	if (strcmp(extensions[i]->name, __DRI_TEX_BUFFER) == 0) {
-	    screen->texBuffer = (__DRItexBufferExtension *) extensions[i];
+	    screen->texBuffer =
+		(const __DRItexBufferExtension *) extensions[i];
 	    /* GLX_EXT_texture_from_pixmap is always enabled. */
 	    LogMessage(X_INFO, "AIGLX: GLX_EXT_texture_from_pixmap backed by buffer objects\n");
 	}
@@ -498,27 +491,176 @@ initializeExtensions(__GLXDRIscreen *screen)
     }
 }
     
+#define __ATTRIB(attrib, field) \
+    { attrib, offsetof(__GLXconfig, field) }
+
+static const struct { unsigned int attrib, offset; } attribMap[] = {
+    __ATTRIB(__DRI_ATTRIB_BUFFER_SIZE,			rgbBits),
+    __ATTRIB(__DRI_ATTRIB_LEVEL,			level),
+    __ATTRIB(__DRI_ATTRIB_RED_SIZE,			redBits),
+    __ATTRIB(__DRI_ATTRIB_GREEN_SIZE,			greenBits),
+    __ATTRIB(__DRI_ATTRIB_BLUE_SIZE,			blueBits),
+    __ATTRIB(__DRI_ATTRIB_ALPHA_SIZE,			alphaBits),
+    __ATTRIB(__DRI_ATTRIB_DEPTH_SIZE,			depthBits),
+    __ATTRIB(__DRI_ATTRIB_STENCIL_SIZE,			stencilBits),
+    __ATTRIB(__DRI_ATTRIB_ACCUM_RED_SIZE,		accumRedBits),
+    __ATTRIB(__DRI_ATTRIB_ACCUM_GREEN_SIZE,		accumGreenBits),
+    __ATTRIB(__DRI_ATTRIB_ACCUM_BLUE_SIZE,		accumBlueBits),
+    __ATTRIB(__DRI_ATTRIB_ACCUM_ALPHA_SIZE,		accumAlphaBits),
+    __ATTRIB(__DRI_ATTRIB_SAMPLE_BUFFERS,		sampleBuffers),
+    __ATTRIB(__DRI_ATTRIB_SAMPLES,			samples),
+    __ATTRIB(__DRI_ATTRIB_DOUBLE_BUFFER,		doubleBufferMode),
+    __ATTRIB(__DRI_ATTRIB_STEREO,			stereoMode),
+    __ATTRIB(__DRI_ATTRIB_AUX_BUFFERS,			numAuxBuffers),
+    __ATTRIB(__DRI_ATTRIB_TRANSPARENT_TYPE,		transparentPixel),
+    __ATTRIB(__DRI_ATTRIB_TRANSPARENT_INDEX_VALUE,	transparentPixel),
+    __ATTRIB(__DRI_ATTRIB_TRANSPARENT_RED_VALUE,	transparentRed),
+    __ATTRIB(__DRI_ATTRIB_TRANSPARENT_GREEN_VALUE,	transparentGreen),
+    __ATTRIB(__DRI_ATTRIB_TRANSPARENT_BLUE_VALUE,	transparentBlue),
+    __ATTRIB(__DRI_ATTRIB_TRANSPARENT_ALPHA_VALUE,	transparentAlpha),
+    __ATTRIB(__DRI_ATTRIB_FLOAT_MODE,			floatMode),
+    __ATTRIB(__DRI_ATTRIB_RED_MASK,			redMask),
+    __ATTRIB(__DRI_ATTRIB_GREEN_MASK,			greenMask),
+    __ATTRIB(__DRI_ATTRIB_BLUE_MASK,			blueMask),
+    __ATTRIB(__DRI_ATTRIB_ALPHA_MASK,			alphaMask),
+    __ATTRIB(__DRI_ATTRIB_MAX_PBUFFER_WIDTH,		maxPbufferWidth),
+    __ATTRIB(__DRI_ATTRIB_MAX_PBUFFER_HEIGHT,		maxPbufferHeight),
+    __ATTRIB(__DRI_ATTRIB_MAX_PBUFFER_PIXELS,		maxPbufferPixels),
+    __ATTRIB(__DRI_ATTRIB_OPTIMAL_PBUFFER_WIDTH,	optimalPbufferWidth),
+    __ATTRIB(__DRI_ATTRIB_OPTIMAL_PBUFFER_HEIGHT,	optimalPbufferHeight),
+    __ATTRIB(__DRI_ATTRIB_SWAP_METHOD,			swapMethod),
+    __ATTRIB(__DRI_ATTRIB_BIND_TO_TEXTURE_RGB,		bindToTextureRgb),
+    __ATTRIB(__DRI_ATTRIB_BIND_TO_TEXTURE_RGBA,		bindToTextureRgba),
+    __ATTRIB(__DRI_ATTRIB_BIND_TO_MIPMAP_TEXTURE,	bindToMipmapTexture),
+    __ATTRIB(__DRI_ATTRIB_YINVERTED,			yInverted),
+};
+
+#define ARRAY_SIZE(a) (sizeof (a) / sizeof ((a)[0]))
+
+static void
+setScalar(__GLXconfig *config, unsigned int attrib, unsigned int value)
+{
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(attribMap); i++)
+	if (attribMap[i].attrib == attrib) {
+	    *(unsigned int *) ((char *) config + attribMap[i].offset) = value;
+	    return;
+	}
+}
+
+static __GLXconfig *
+createModeFromConfig(const __DRIcoreExtension *core,
+		     const __DRIconfig *driConfig,
+		     unsigned int visualType)
+{
+    __GLXDRIconfig *config;
+    unsigned int attrib, value;
+    int i;
+
+    config = xalloc(sizeof *config);
+
+    config->driConfig = driConfig;
+
+    i = 0;
+    while (core->indexConfigAttrib(driConfig, i++, &attrib, &value)) {
+	switch (attrib) {
+	case __DRI_ATTRIB_RENDER_TYPE:
+	    if (value & __DRI_ATTRIB_RGBA_BIT) {
+		config->config.renderType |= GLX_RGBA_BIT;
+		config->config.rgbMode = GL_TRUE;
+	    } else if (value & __DRI_ATTRIB_COLOR_INDEX_BIT) {
+		config->config.renderType |= GLX_COLOR_INDEX_BIT;
+		config->config.rgbMode = GL_FALSE;
+	    } else {
+		config->config.renderType = 0;
+		config->config.rgbMode = GL_FALSE;
+	    }
+	    break;
+	case __DRI_ATTRIB_CONFIG_CAVEAT:
+	    if (value & __DRI_ATTRIB_NON_CONFORMANT_CONFIG)
+		config->config.visualRating = GLX_NON_CONFORMANT_CONFIG;
+	    else if (value & __DRI_ATTRIB_SLOW_BIT)
+		config->config.visualRating = GLX_SLOW_CONFIG;
+	    else
+		config->config.visualRating = GLX_NONE;
+	    break;
+	case __DRI_ATTRIB_BIND_TO_TEXTURE_TARGETS:
+	    config->config.bindToTextureTargets = 0;
+	    if (value & __DRI_ATTRIB_TEXTURE_1D_BIT)
+		config->config.bindToTextureTargets |= GLX_TEXTURE_1D_BIT_EXT;
+	    if (value & __DRI_ATTRIB_TEXTURE_2D_BIT)
+		config->config.bindToTextureTargets |= GLX_TEXTURE_2D_BIT_EXT;
+	    if (value & __DRI_ATTRIB_TEXTURE_RECTANGLE_BIT)
+		config->config.bindToTextureTargets |= GLX_TEXTURE_RECTANGLE_BIT_EXT;
+	    break;	
+	default:
+	    setScalar(&config->config, attrib, value);
+	    break;
+	}
+    }
+
+    config->config.next = NULL;
+    config->config.xRenderable = GL_TRUE;
+    config->config.visualType = visualType;
+    config->config.drawableType = GLX_WINDOW_BIT | GLX_PIXMAP_BIT;
+
+    return &config->config;
+}
+
+__GLXconfig *
+glxConvertConfigs(const __DRIcoreExtension *core, const __DRIconfig **configs);
+
+__GLXconfig *
+glxConvertConfigs(const __DRIcoreExtension *core, const __DRIconfig **configs)
+{
+    __GLXconfig head, *tail;
+    int i;
+
+    tail = &head;
+    head.next = NULL;
+
+    for (i = 0; configs[i]; i++) {
+	tail->next = createModeFromConfig(core,
+					  configs[i], GLX_TRUE_COLOR);
+	if (tail->next == NULL)
+	    break;
+
+	tail = tail->next;
+    }
+
+    for (i = 0; configs[i]; i++) {
+	tail->next = createModeFromConfig(core,
+					  configs[i], GLX_DIRECT_COLOR);
+	if (tail->next == NULL)
+	    break;
+
+	tail = tail->next;
+    }
+
+    return head.next;
+}
+
 static __GLXscreen *
 __glXDRIscreenProbe(ScreenPtr pScreen)
 {
-    __DRI2_CREATE_NEW_SCREEN_FUNC *createNewScreen;
     const char *driverName;
     __GLXDRIscreen *screen;
     char filename[128];
     size_t buffer_size;
     ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
     unsigned int sareaHandle;
+    const __DRIextension **extensions;
+    const __DRIconfig **driConfigs;
+    int i;
 
     screen = xalloc(sizeof *screen);
     if (screen == NULL)
-      return NULL;
+	return NULL;
     memset(screen, 0, sizeof *screen);
 
     if (!xf86LoaderCheckSymbol("DRI2Connect") ||
-	!DRI2Connect(pScreen,
-		     &screen->fd,
-		     &driverName,
-		     &sareaHandle)) {
+	!DRI2Connect(pScreen, &screen->fd, &driverName, &sareaHandle)) {
 	LogMessage(X_INFO,
 		   "AIGLX: Screen %d is not DRI2 capable\n", pScreen->myNum);
 	return NULL;
@@ -532,8 +674,8 @@ __glXDRIscreenProbe(ScreenPtr pScreen)
 
     __glXInitExtensionEnableBits(screen->glx_enable_bits);
 
-    snprintf(filename, sizeof filename, "%s/%s_dri.so",
-             dri_driver_path, driverName);
+    snprintf(filename, sizeof filename,
+	     "%s/%s_dri.so", dri_driver_path, driverName);
 
     screen->driver = dlopen(filename, RTLD_LAZY | RTLD_LOCAL);
     if (screen->driver == NULL) {
@@ -542,28 +684,43 @@ __glXDRIscreenProbe(ScreenPtr pScreen)
         goto handle_error;
     }
 
-    createNewScreen = dlsym(screen->driver, CREATE_NEW_SCREEN_FUNC);
-    if (createNewScreen == NULL) {
-	LogMessage(X_ERROR, "AIGLX error: dlsym for %s failed (%s)\n",
-		   CREATE_NEW_SCREEN_FUNC, dlerror());
-      goto handle_error;
+    extensions = dlsym(screen->driver, __DRI_DRIVER_EXTENSIONS);
+    if (extensions == NULL) {
+	LogMessage(X_ERROR, "AIGLX error: %s exports no extensions (%s)\n",
+		   driverName, dlerror());
+	goto handle_error;
     }
     
-    screen->driScreen.private =
-	(*createNewScreen)(pScreen->myNum,
-			   &screen->driScreen,
-			   screen->fd,
-			   sareaHandle,
-			   loader_extensions,
-			   &screen->base.fbconfigs);
-
-    if (screen->driScreen.private == NULL) {
+    for (i = 0; extensions[i]; i++) {
+        if (strcmp(extensions[i]->name, __DRI_CORE) == 0 &&
+	    extensions[i]->version >= __DRI_CORE_VERSION) {
+		screen->core = (const __DRIcoreExtension *) extensions[i];
+	}
+    }
+
+    if (screen->core == NULL) {
+	LogMessage(X_ERROR, "AIGLX error: %s exports no DRI extension\n",
+		   driverName);
+	goto handle_error;
+    }
+
+    screen->driScreen =
+	(*screen->core->createNewScreen)(pScreen->myNum,
+					 screen->fd,
+					 sareaHandle,
+					 loader_extensions,
+					 &driConfigs,
+					 screen);
+
+    if (screen->driScreen == NULL) {
 	LogMessage(X_ERROR, "AIGLX error: Calling driver entry point failed");
 	goto handle_error;
     }
 
     initializeExtensions(screen);
 
+    screen->base.fbconfigs = glxConvertConfigs(screen->core, driConfigs);
+
     __glXScreenInit(&screen->base, pScreen);
 
     buffer_size = __glXGetExtensionString(screen->glx_enable_bits, NULL);
diff --git a/GL/glx/glxglcore.c b/GL/glx/glxglcore.c
index 0750e12..bbfa02b 100644
--- a/GL/glx/glxglcore.c
+++ b/GL/glx/glxglcore.c
@@ -46,7 +46,6 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #include <glxcontext.h>
 #include <glxutil.h>
 
-#include "glcontextmodes.h"
 #include "os.h"
 
 typedef struct __GLXMESAscreen   __GLXMESAscreen;
@@ -120,7 +119,7 @@ static __GLXdrawable *
 __glXMesaScreenCreateDrawable(__GLXscreen *screen,
 			      DrawablePtr pDraw, int type,
 			      XID drawId,
-			      __GLcontextModes *modes)
+			      __GLXconfig *modes)
 {
     __GLXMESAdrawable *glxPriv;
     XMesaVisual xm_vis;
@@ -217,7 +216,7 @@ __glXMesaContextForceCurrent(__GLXcontext *baseContext)
 
 static __GLXcontext *
 __glXMesaScreenCreateContext(__GLXscreen *screen,
-			     __GLcontextModes *modes,
+			     __GLXconfig *config,
 			     __GLXcontext *baseShareContext)
 {
     __GLXMESAcontext *context;
@@ -232,7 +231,7 @@ __glXMesaScreenCreateContext(__GLXscreen *screen,
     memset(context, 0, sizeof *context);
 
     context->base.pGlxScreen = screen;
-    context->base.modes      = modes;
+    context->base.config     = config;
 
     context->base.destroy        = __glXMesaContextDestroy;
     context->base.makeCurrent    = __glXMesaContextMakeCurrent;
@@ -240,10 +239,10 @@ __glXMesaScreenCreateContext(__GLXscreen *screen,
     context->base.copy           = __glXMesaContextCopy;
     context->base.forceCurrent   = __glXMesaContextForceCurrent;
 
-    xm_vis = find_mesa_visual(screen, modes->fbconfigID);
+    xm_vis = find_mesa_visual(screen, config->fbconfigID);
     if (!xm_vis) {
 	ErrorF("find_mesa_visual returned NULL for visualID = 0x%04x\n",
-	       modes->visualID);
+	       config->visualID);
 	xfree(context);
 	return NULL;
     }
@@ -282,11 +281,11 @@ static XMesaVisual
 find_mesa_visual(__GLXscreen *screen, XID fbconfigID)
 {
     __GLXMESAscreen *mesaScreen = (__GLXMESAscreen *) screen;
-    const __GLcontextModes *modes;
+    const __GLXconfig *config;
     unsigned i = 0;
 
-    for (modes = screen->fbconfigs; modes != NULL; modes = modes->next) {
- 	if (modes->fbconfigID == fbconfigID)
+    for (config = screen->fbconfigs; config != NULL; config = config->next) {
+ 	if (config->fbconfigID == fbconfigID)
 	    return mesaScreen->xm_vis[i];
 	i++;
     }
@@ -298,18 +297,31 @@ const static int numBack = 2;
 const static int numDepth = 2;
 const static int numStencil = 2;
 
-static __GLcontextModes *
+static const int glx_visual_types[] = {
+    GLX_STATIC_GRAY,
+    GLX_GRAY_SCALE,
+    GLX_STATIC_COLOR,
+    GLX_PSEUDO_COLOR,
+    GLX_TRUE_COLOR,
+    GLX_DIRECT_COLOR
+};
+
+static __GLXconfig *
 createFBConfigsForVisual(__GLXscreen *screen, ScreenPtr pScreen,
-			 VisualPtr visual, __GLcontextModes *config)
+			 VisualPtr visual, __GLXconfig *tail)
 {
     int back, depth, stencil;
+    __GLXconfig *config;
 
     /* FIXME: Ok, I'm making all this up... anybody has a better idea? */
 
     for (back = numBack - 1; back >= 0; back--)
 	for (depth = 0; depth < numDepth; depth++)
 	    for (stencil = 0; stencil < numStencil; stencil++) {
-		config->visualType = _gl_convert_from_x_visual_type(visual->class);
+		config->next = xalloc(sizeof *config);
+		config = config->next;
+
+		config->visualType = glx_visual_types[visual->class];
 		config->xRenderable = GL_TRUE;
 		config->drawableType = GLX_WINDOW_BIT | GLX_PIXMAP_BIT;
 		config->rgbMode = (visual->class >= TrueColor);
@@ -333,35 +345,35 @@ createFBConfigsForVisual(__GLXscreen *screen, ScreenPtr pScreen,
 		config->alphaMask = 0;
 		config->rgbBits = config->rgbMode ? visual->nplanes : 0;
 		config->indexBits = config->colorIndexMode ? visual->nplanes : 0;
-		config = config->next;
 	    }
 
-    return config;
+    return tail;
 }
 
 static void
 createFBConfigs(__GLXscreen *pGlxScreen, ScreenPtr pScreen)
 {
-    __GLcontextModes *configs;
+    __GLXconfig head, *tail;
     int i;
 
     /* We assume here that each existing visual correspond to a
      * different visual class.  Note, this runs before COMPOSITE adds
      * its visual, so it's not entirely crazy. */
     pGlxScreen->numFBConfigs = pScreen->numVisuals * numBack * numDepth * numStencil;
-    pGlxScreen->fbconfigs = _gl_context_modes_create(pGlxScreen->numFBConfigs,
-						     sizeof *configs);
-
-    configs = pGlxScreen->fbconfigs;
+    
+    head.next = NULL;
+    tail = &head;
     for (i = 0; i < pScreen->numVisuals; i++)
-	configs = createFBConfigsForVisual(pGlxScreen, pScreen,
-					   &pScreen->visuals[i], configs);
+	tail = createFBConfigsForVisual(pGlxScreen, pScreen,
+					&pScreen->visuals[i], tail);
+
+    pGlxScreen->fbconfigs = head.next;
 }
 
 static void
 createMesaVisuals(__GLXMESAscreen *pMesaScreen)
 {
-    __GLcontextModes *config;
+    __GLXconfig *config;
     ScreenPtr pScreen;
     VisualPtr visual = NULL;
     int i, j;
diff --git a/GL/glx/glxscreens.c b/GL/glx/glxscreens.c
index 6575b27..b49a775 100644
--- a/GL/glx/glxscreens.c
+++ b/GL/glx/glxscreens.c
@@ -37,6 +37,7 @@
 #include <dix-config.h>
 #endif
 
+#include <GL/glxtokens.h>
 #include <string.h>
 #include <windowstr.h>
 #include <os.h>
@@ -46,7 +47,6 @@
 #include "glxserver.h"
 #include "glxutil.h"
 #include "glxext.h"
-#include "glcontextmodes.h"
 
 static DevPrivateKey glxScreenPrivateKey = &glxScreenPrivateKey;
 
@@ -280,10 +280,23 @@ void GlxSetVisualConfigs(int nconfigs,
      * call it. */
 }
 
+GLint glxConvertToXVisualType(int visualType)
+{
+    static const int x_visual_types[] = {
+	TrueColor,   DirectColor,
+	PseudoColor, StaticColor,
+	GrayScale,   StaticGray
+    };
+
+    return ( (unsigned) (visualType - GLX_TRUE_COLOR) < 6 )
+	? x_visual_types[ visualType - GLX_TRUE_COLOR ] : -1;
+}
+
+
 static void
 filterOutNativeConfigs(__GLXscreen *pGlxScreen)
 {
-    __GLcontextModes *m, *next, *native_modes, **last;
+    __GLXconfig *m, *next, **last;
     ScreenPtr pScreen = pGlxScreen->pScreen;
     int i, depth;
 
@@ -305,12 +318,12 @@ filterOutNativeConfigs(__GLXscreen *pGlxScreen)
 }
 
 static XID
-findVisualForConfig(ScreenPtr pScreen, __GLcontextModes *m)
+findVisualForConfig(ScreenPtr pScreen, __GLXconfig *m)
 {
     int i;
 
     for (i = 0; i < pScreen->numVisuals; i++) {
-	if (_gl_convert_to_x_visual_type(m->visualType) == pScreen->visuals[i].class)
+	if (glxConvertToXVisualType(m->visualType) == pScreen->visuals[i].class)
 	    return pScreen->visuals[i].vid;
     }
 
@@ -405,10 +418,10 @@ findFirstSet(unsigned int v)
 }
 
 static void
-initGlxVisual(VisualPtr visual, __GLcontextModes *config)
+initGlxVisual(VisualPtr visual, __GLXconfig *config)
 {
     config->visualID = visual->vid;
-    visual->class = _gl_convert_to_x_visual_type(config->visualType);
+    visual->class = glxConvertToXVisualType(config->visualType);
     visual->bitsPerRGBValue = config->redBits;
     visual->ColormapEntries = 1 << config->redBits;
     visual->nplanes = config->redBits + config->greenBits + config->blueBits;
@@ -426,15 +439,15 @@ typedef struct {
     GLboolean depthBuffer;
 } FBConfigTemplateRec, *FBConfigTemplatePtr;
 
-static __GLcontextModes *
+static __GLXconfig *
 pickFBConfig(__GLXscreen *pGlxScreen, FBConfigTemplatePtr template, int class)
 {
-    __GLcontextModes *config;
+    __GLXconfig *config;
 
     for (config = pGlxScreen->fbconfigs; config != NULL; config = config->next) {
 	if (config->visualRating != GLX_NONE)
 	    continue;
-	if (_gl_convert_to_x_visual_type(config->visualType) != class)
+	if (glxConvertToXVisualType(config->visualType) != class)
 	    continue;
 	if ((config->doubleBufferMode > 0) != template->doubleBuffer)
 	    continue;
@@ -450,32 +463,36 @@ pickFBConfig(__GLXscreen *pGlxScreen, FBConfigTemplatePtr template, int class)
 static void
 addMinimalSet(__GLXscreen *pGlxScreen)
 {
-    __GLcontextModes *config;
+    __GLXconfig *config;
     VisualPtr visuals;
-    int i;
+    int i, j;
     FBConfigTemplateRec best = { GL_TRUE, GL_TRUE };
     FBConfigTemplateRec minimal = { GL_FALSE, GL_FALSE };
 
     pGlxScreen->visuals = xcalloc(pGlxScreen->pScreen->numVisuals,
-				  sizeof (__GLcontextModes *));
+				  sizeof (__GLXconfig *));
     if (pGlxScreen->visuals == NULL) {
 	ErrorF("Failed to allocate for minimal set of GLX visuals\n");
 	return;
     }
 
-    pGlxScreen->numVisuals = pGlxScreen->pScreen->numVisuals;
     visuals = pGlxScreen->pScreen->visuals;
-    for (i = 0; i < pGlxScreen->numVisuals; i++) {
+    for (i = 0, j = 0; i < pGlxScreen->pScreen->numVisuals; i++) {
 	if (visuals[i].nplanes == 32)
 	    config = pickFBConfig(pGlxScreen, &minimal, visuals[i].class);
 	else
 	    config = pickFBConfig(pGlxScreen, &best, visuals[i].class);
 	if (config == NULL)
 	    config = pGlxScreen->fbconfigs;
-	pGlxScreen->visuals[i] = config;
-	config->visualID = visuals[i].vid;
+	if (config == NULL)
+	    continue;
+
+	pGlxScreen->visuals[j] = config;
+	config->visualID = visuals[j].vid;
+	j++;
     }
 
+    pGlxScreen->numVisuals = j;
 }
 
 static void
@@ -487,12 +504,12 @@ addTypicalSet(__GLXscreen *pGlxScreen)
 static void
 addFullSet(__GLXscreen *pGlxScreen)
 {
-    __GLcontextModes *config;
+    __GLXconfig *config;
     VisualPtr visuals;
     int i, depth;
 
     pGlxScreen->visuals =
-	xcalloc(pGlxScreen->numFBConfigs, sizeof (__GLcontextModes *));
+	xcalloc(pGlxScreen->numFBConfigs, sizeof (__GLXconfig *));
     if (pGlxScreen->visuals == NULL) {
 	ErrorF("Failed to allocate for full set of GLX visuals\n");
 	return;
@@ -522,7 +539,7 @@ void GlxSetVisualConfig(int config)
 
 void __glXScreenInit(__GLXscreen *pGlxScreen, ScreenPtr pScreen)
 {
-    __GLcontextModes *m;
+    __GLXconfig *m;
     int i;
 
     pGlxScreen->pScreen       = pScreen;
diff --git a/GL/glx/glxscreens.h b/GL/glx/glxscreens.h
index f1eef91..39d162d 100644
--- a/GL/glx/glxscreens.h
+++ b/GL/glx/glxscreens.h
@@ -40,8 +40,6 @@
 **
 */
 
-#include "GL/internal/glcore.h"
-
 typedef struct {
     void * (* queryHyperpipeNetworkFunc)(int, int *, int *);
     void * (* queryHyperpipeConfigFunc)(int, int, int *, int *);
@@ -57,6 +55,84 @@ typedef struct {
 void __glXHyperpipeInit(int screen, __GLXHyperpipeExtensionFuncs *funcs);
 void __glXSwapBarrierInit(int screen, __GLXSwapBarrierExtensionFuncs *funcs);
 
+typedef struct __GLXconfig __GLXconfig;
+struct __GLXconfig {
+    __GLXconfig *next;
+    GLboolean rgbMode;
+    GLboolean floatMode;
+    GLboolean colorIndexMode;
+    GLuint doubleBufferMode;
+    GLuint stereoMode;
+
+    GLboolean haveAccumBuffer;
+    GLboolean haveDepthBuffer;
+    GLboolean haveStencilBuffer;
+
+    GLint redBits, greenBits, blueBits, alphaBits;	/* bits per comp */
+    GLuint redMask, greenMask, blueMask, alphaMask;
+    GLint rgbBits;		/* total bits for rgb */
+    GLint indexBits;		/* total bits for colorindex */
+
+    GLint accumRedBits, accumGreenBits, accumBlueBits, accumAlphaBits;
+    GLint depthBits;
+    GLint stencilBits;
+
+    GLint numAuxBuffers;
+
+    GLint level;
+
+    GLint pixmapMode;
+
+    /* GLX */
+    GLint visualID;
+    GLint visualType;     /**< One of the GLX X visual types. (i.e., 
+			   * \c GLX_TRUE_COLOR, etc.)
+			   */
+
+    /* EXT_visual_rating / GLX 1.2 */
+    GLint visualRating;
+
+    /* EXT_visual_info / GLX 1.2 */
+    GLint transparentPixel;
+				/*    colors are floats scaled to ints */
+    GLint transparentRed, transparentGreen, transparentBlue, transparentAlpha;
+    GLint transparentIndex;
+
+    /* ARB_multisample / SGIS_multisample */
+    GLint sampleBuffers;
+    GLint samples;
+
+    /* SGIX_fbconfig / GLX 1.3 */
+    GLint drawableType;
+    GLint renderType;
+    GLint xRenderable;
+    GLint fbconfigID;
+
+    /* SGIX_pbuffer / GLX 1.3 */
+    GLint maxPbufferWidth;
+    GLint maxPbufferHeight;
+    GLint maxPbufferPixels;
+    GLint optimalPbufferWidth;   /* Only for SGIX_pbuffer. */
+    GLint optimalPbufferHeight;  /* Only for SGIX_pbuffer. */
+
+    /* SGIX_visual_select_group */
+    GLint visualSelectGroup;
+
+    /* OML_swap_method */
+    GLint swapMethod;
+
+    GLint screen;
+
+    /* EXT_texture_from_pixmap */
+    GLint bindToTextureRgb;
+    GLint bindToTextureRgba;
+    GLint bindToMipmapTexture;
+    GLint bindToTextureTargets;
+    GLint yInverted;
+};
+
+GLint glxConvertToXVisualType(int visualType);
+
 /*
 ** Screen dependent data.  These methods are the interface between the DIX
 ** and DDX layers of the GLX server extension.  The methods provide an
@@ -67,14 +143,14 @@ struct __GLXscreen {
     void          (*destroy)       (__GLXscreen *screen);
 
     __GLXcontext *(*createContext) (__GLXscreen *screen,
-				    __GLcontextModes *modes,
+				    __GLXconfig *modes,
 				    __GLXcontext *shareContext);
 
     __GLXdrawable *(*createDrawable)(__GLXscreen *context,
 				     DrawablePtr pDraw,
 				     int type,
 				     XID drawId,
-				     __GLcontextModes *modes);
+				     __GLXconfig *modes);
     int            (*swapInterval)  (__GLXdrawable *drawable,
 				     int interval);
 
@@ -84,11 +160,11 @@ struct __GLXscreen {
     ScreenPtr pScreen;
 
     /* Linked list of valid fbconfigs for this screen. */
-    __GLcontextModes *fbconfigs;
+    __GLXconfig *fbconfigs;
     int numFBConfigs;
 
     /* Subset of fbconfigs that are exposed as GLX visuals. */
-    __GLcontextModes **visuals;
+    __GLXconfig **visuals;
     GLint numVisuals;
 
     char *GLextensions;
diff --git a/GL/glx/glxutil.c b/GL/glx/glxutil.c
index f531ed9..11e9f89 100644
--- a/GL/glx/glxutil.c
+++ b/GL/glx/glxutil.c
@@ -49,7 +49,6 @@
 #include "glxutil.h"
 #include "GL/internal/glcore.h"
 #include "GL/glxint.h"
-#include "glcontextmodes.h"
 
 /************************************************************************/
 /* Context stuff */
@@ -140,13 +139,13 @@ __glXUnrefDrawable(__GLXdrawable *glxPriv)
 GLboolean
 __glXDrawableInit(__GLXdrawable *drawable,
 		  __GLXscreen *screen, DrawablePtr pDraw, int type,
-		  XID drawId, __GLcontextModes *modes)
+		  XID drawId, __GLXconfig *config)
 {
     drawable->pDraw = pDraw;
     drawable->type = type;
     drawable->drawId = drawId;
     drawable->refCount = 1;
-    drawable->modes = modes;
+    drawable->config = config;
     drawable->eventMask = 0;
 
     return GL_TRUE;
diff --git a/GL/glx/glxutil.h b/GL/glx/glxutil.h
index 6534c3f..00c7b20 100644
--- a/GL/glx/glxutil.h
+++ b/GL/glx/glxutil.h
@@ -51,7 +51,7 @@ extern void __glXUnrefDrawable(__GLXdrawable *glxPriv);
 extern GLboolean __glXDrawableInit(__GLXdrawable *drawable,
 				   __GLXscreen *screen,
 				   DrawablePtr pDraw, int type, XID drawID,
-				   __GLcontextModes *modes);
+				   __GLXconfig *config);
 
 /* context helper routines */
 extern __GLXcontext *__glXLookupContextByTag(__GLXclientState*, GLXContextTag);
diff --git a/GL/symlink-mesa.sh b/GL/symlink-mesa.sh
index af9adbd..47afdcd 100755
--- a/GL/symlink-mesa.sh
+++ b/GL/symlink-mesa.sh
@@ -227,8 +227,6 @@ symlink_glx() {
     dst_dir glx
 
     action indirect_size.h
-    action glcontextmodes.c
-    action glcontextmodes.h
     action indirect_dispatch.c
     action indirect_dispatch.h
     action indirect_dispatch_swap.c
diff --git a/configure.ac b/configure.ac
index 959f0ae..e72e3b9 100644
--- a/configure.ac
+++ b/configure.ac
@@ -860,7 +860,7 @@ AM_CONDITIONAL(DRI2, test "x$DRI2" = xyes)
 if test "x$DRI2" = xyes; then
 	# FIXME: Bump the versions once we have releases of these.
 	AC_DEFINE(DRI2, 1, [Build DRI2 extension])
-	PKG_CHECK_MODULES([DRIPROTO], [xf86driproto >= 2.0.3])
+	PKG_CHECK_MODULES([DRI2PROTO], [dri2proto >= 1.0.0])
 	PKG_CHECK_MODULES([LIBDRM], [libdrm >= 2.3.1])
 fi
 
diff --git a/hw/xfree86/common/xf86Config.c b/hw/xfree86/common/xf86Config.c
index 4a4aabc..8de7426 100644
--- a/hw/xfree86/common/xf86Config.c
+++ b/hw/xfree86/common/xf86Config.c
@@ -121,6 +121,7 @@ static ModuleDefault ModuleDefaults[] = {
     {.name = "freetype", .toLoad = TRUE,    .load_opt=NULL},
     {.name = "record",   .toLoad = TRUE,    .load_opt=NULL},
     {.name = "dri",      .toLoad = TRUE,    .load_opt=NULL},
+    {.name = "dri2",     .toLoad = TRUE,    .load_opt=NULL},
     {.name = NULL,       .toLoad = FALSE,   .load_opt=NULL}
 };
 
diff --git a/hw/xfree86/dri2/Makefile.am b/hw/xfree86/dri2/Makefile.am
index be3cea4..844c912 100644
--- a/hw/xfree86/dri2/Makefile.am
+++ b/hw/xfree86/dri2/Makefile.am
@@ -2,7 +2,7 @@ libdri2_la_LTLIBRARIES = libdri2.la
 libdri2_la_CFLAGS = \
 	-DHAVE_XORG_CONFIG_H \
 	-I at MESA_SOURCE@/include \
-	@DIX_CFLAGS@ @DRIPROTO_CFLAGS@ @LIBDRM_CFLAGS@ \
+	@DIX_CFLAGS@ @DRI2PROTO_CFLAGS@ @LIBDRM_CFLAGS@ \
 	-I$(top_srcdir)/hw/xfree86/common \
 	-I$(top_srcdir)/hw/xfree86/os-support/bus
 
@@ -10,6 +10,7 @@ libdri2_la_LDFLAGS = -module -avoid-version @LIBDRM_LIBS@
 libdri2_ladir = $(moduledir)/extensions
 libdri2_la_SOURCES = \
 	dri2.c \
-	dri2.h
+	dri2.h \
+	dri2ext.c
 
 sdk_HEADERS = dri2.h
diff --git a/hw/xfree86/dri2/dri2.c b/hw/xfree86/dri2/dri2.c
index d527387..74aef71 100644
--- a/hw/xfree86/dri2/dri2.c
+++ b/hw/xfree86/dri2/dri2.c
@@ -38,6 +38,8 @@
 #include "xf86Module.h"
 #include "scrnintstr.h"
 #include "windowstr.h"
+#include "region.h" 
+#include "damage.h" 
 #include "dri2.h"
 #include <GL/internal/dri_sarea.h>
 
@@ -48,8 +50,9 @@ static DevPrivateKey dri2WindowPrivateKey = &dri2WindowPrivateKey;
 static DevPrivateKey dri2PixmapPrivateKey = &dri2PixmapPrivateKey;
 
 typedef struct _DRI2DrawablePriv {
-    drm_drawable_t		 drawable;
-    unsigned int		 handle;
+    unsigned int		 refCount;
+    unsigned int		 boHandle;
+    unsigned int		 dri2Handle;
 } DRI2DrawablePrivRec, *DRI2DrawablePrivPtr;
 
 typedef struct _DRI2Screen {
@@ -58,6 +61,7 @@ typedef struct _DRI2Screen {
     void			*sarea;
     unsigned int		 sareaSize;
     const char			*driverName;
+    unsigned int		 nextHandle;
 
     __DRIEventBuffer		*buffer;
     int				 locked;
@@ -147,7 +151,7 @@ DRI2PostDrawableConfig(DrawablePtr pDraw)
 
     e = DRI2ScreenAllocEvent(ds, size);
     e->event_header = DRI2_EVENT_HEADER(DRI2_EVENT_DRAWABLE_CONFIG, size);
-    e->drawable = pPriv->drawable;
+    e->drawable = pPriv->dri2Handle;
     e->x = pDraw->x - pPixmap->screen_x;
     e->y = pDraw->y - pPixmap->screen_y;
     e->width = pDraw->width;
@@ -164,7 +168,7 @@ DRI2PostDrawableConfig(DrawablePtr pDraw)
 }
 
 static void
-DRI2PostBufferAttach(DrawablePtr pDraw)
+DRI2PostBufferAttach(DrawablePtr pDraw, Bool force)
 {
     ScreenPtr			 pScreen = pDraw->pScreen;
     DRI2ScreenPtr		 ds = DRI2GetScreen(pScreen);
@@ -173,7 +177,8 @@ DRI2PostBufferAttach(DrawablePtr pDraw)
     PixmapPtr			 pPixmap;
     __DRIBufferAttachEvent	*e;
     size_t			 size;
-    unsigned int		 handle, flags;
+    unsigned int		 flags;
+    unsigned int		 boHandle;
 
     if (pDraw->type == DRAWABLE_WINDOW) {
 	pWin = (WindowPtr) pDraw;
@@ -187,22 +192,20 @@ DRI2PostBufferAttach(DrawablePtr pDraw)
     if (!pPriv)
 	return;
 
-    size = sizeof *e;
-
-    handle = ds->getPixmapHandle(pPixmap, &flags);
-    if (handle == 0 || handle == pPriv->handle)
+    boHandle = ds->getPixmapHandle(pPixmap, &flags);
+    if (boHandle == pPriv->boHandle && !force)
 	return;
 
+    pPriv->boHandle = boHandle;
+    size = sizeof *e;
     e = DRI2ScreenAllocEvent(ds, size);
     e->event_header = DRI2_EVENT_HEADER(DRI2_EVENT_BUFFER_ATTACH, size);
-    e->drawable = pPriv->drawable;
+    e->drawable = pPriv->dri2Handle;
     e->buffer.attachment = DRI_DRAWABLE_BUFFER_FRONT_LEFT;
-    e->buffer.handle = handle;
+    e->buffer.handle = pPriv->boHandle;
     e->buffer.pitch = pPixmap->devKind;
     e->buffer.cpp = pPixmap->drawable.bitsPerPixel / 8;
     e->buffer.flags = flags;
-
-    pPriv->handle = handle;
 }
 
 static void
@@ -223,7 +226,7 @@ DRI2ClipNotify(WindowPtr pWin, int dx, int dy)
     }
 
     DRI2PostDrawableConfig(&pWin->drawable);
-    DRI2PostBufferAttach(&pWin->drawable);
+    DRI2PostBufferAttach(&pWin->drawable, FALSE);
 }
 
 static void
@@ -262,10 +265,10 @@ DRI2CloseScreen(ScreenPtr pScreen)
 }
 
 Bool
-DRI2CreateDrawable(ScreenPtr pScreen, DrawablePtr pDraw,
-		   drm_drawable_t *pDrmDrawable, unsigned int *head)
+DRI2CreateDrawable(DrawablePtr pDraw,
+		   unsigned int *handle, unsigned int *head)
 {
-    DRI2ScreenPtr	ds = DRI2GetScreen(pScreen);
+    DRI2ScreenPtr	ds = DRI2GetScreen(pDraw->pScreen);
     WindowPtr		pWin;
     PixmapPtr		pPixmap;
     DRI2DrawablePrivPtr pPriv;
@@ -283,47 +286,66 @@ DRI2CreateDrawable(ScreenPtr pScreen, DrawablePtr pDraw,
     }
 
     pPriv = dixLookupPrivate(devPrivates, key);
-    if (pPriv == NULL) {
+    if (pPriv != NULL) {
+	pPriv->refCount++;
+    } else {
 	pPriv = xalloc(sizeof *pPriv);
-	if (drmCreateDrawable(ds->fd, &pPriv->drawable))
-	    return FALSE;
-
+	pPriv->refCount = 1;
+	pPriv->boHandle = 0;
+	pPriv->dri2Handle = ds->nextHandle++;
 	dixSetPrivate(devPrivates, key, pPriv);
     }
 
-    *pDrmDrawable = pPriv->drawable;
-
+    *handle = pPriv->dri2Handle;
     *head = ds->buffer->head;
+
     DRI2PostDrawableConfig(pDraw);
-    DRI2PostBufferAttach(pDraw);
+    DRI2PostBufferAttach(pDraw, TRUE);
     DRI2ScreenCommitEvents(ds);
 
     return TRUE;
 }
 
 void
-DRI2DestroyDrawable(ScreenPtr pScreen, DrawablePtr pDraw)
+DRI2DestroyDrawable(DrawablePtr pDraw)
 {
-    DRI2ScreenPtr ds = DRI2GetScreen(pScreen);
-    PixmapPtr pPixmap;
-    WindowPtr pWin;
-    DRI2DrawablePrivPtr pPriv;
+    PixmapPtr		  pPixmap;
+    WindowPtr		  pWin;
+    DRI2DrawablePrivPtr   pPriv;
+    DevPrivateKey	  key;
+    PrivateRec		**devPrivates;
 
     if (pDraw->type == DRAWABLE_WINDOW) {
 	pWin = (WindowPtr) pDraw;
-	pPriv = dixLookupPrivate(&pWin->devPrivates, dri2WindowPrivateKey);
-	dixSetPrivate(&pWin->devPrivates, dri2WindowPrivateKey, NULL);
+	devPrivates = &pWin->devPrivates;
+	key = dri2WindowPrivateKey;
     } else {
 	pPixmap = (PixmapPtr) pDraw;
-	pPriv = dixLookupPrivate(&pPixmap->devPrivates, dri2PixmapPrivateKey);
-	dixSetPrivate(&pPixmap->devPrivates, dri2PixmapPrivateKey, NULL);
+	devPrivates = &pPixmap->devPrivates;
+	key = dri2PixmapPrivateKey;
     }
 
+    pPriv = dixLookupPrivate(devPrivates, key);
     if (pPriv == NULL)
 	return;
     
-    drmDestroyDrawable(ds->fd, pPriv->drawable);
-    xfree(pPriv);
+    pPriv->refCount--;
+    if (pPriv->refCount == 0) {
+	dixSetPrivate(devPrivates, key, NULL);
+	xfree(pPriv);
+    }
+}
+
+void
+DRI2ReemitDrawableInfo(DrawablePtr pDraw, unsigned int *head)
+{
+    DRI2ScreenPtr ds = DRI2GetScreen(pDraw->pScreen);
+
+    *head = ds->buffer->head;
+
+    DRI2PostDrawableConfig(pDraw);
+    DRI2PostBufferAttach(pDraw, TRUE);
+    DRI2ScreenCommitEvents(ds);
 }
 
 Bool
@@ -409,8 +431,9 @@ DRI2ScreenInit(ScreenPtr pScreen, DRI2InfoPtr info)
     if (!ds)
 	return NULL;
 
-    ds->fd = info->fd;
+    ds->fd			= info->fd;
     ds->driverName		= info->driverName;
+    ds->nextHandle		= 1;
 
     ds->getPixmapHandle		= info->getPixmapHandle;
     ds->beginClipNotify		= info->beginClipNotify;
@@ -434,9 +457,21 @@ DRI2ScreenInit(ScreenPtr pScreen, DRI2InfoPtr info)
     return p;
 }
 
+extern ExtensionModule dri2ExtensionModule;
+
 static pointer
 DRI2Setup(pointer module, pointer opts, int *errmaj, int *errmin)
 {
+    static Bool setupDone = FALSE;
+
+    if (!setupDone) {
+	setupDone = TRUE;
+	LoadExtension(&dri2ExtensionModule, FALSE);
+    } else {
+	if (errmaj)
+	    *errmaj = LDR_ONCEONLY;
+    }
+
     return (pointer) 1;
 }
 
diff --git a/hw/xfree86/dri2/dri2.h b/hw/xfree86/dri2/dri2.h
index 126087a..85b3da4 100644
--- a/hw/xfree86/dri2/dri2.h
+++ b/hw/xfree86/dri2/dri2.h
@@ -66,14 +66,16 @@ unsigned int DRI2GetPixmapHandle(PixmapPtr pPixmap,
 void DRI2Lock(ScreenPtr pScreen);
 void DRI2Unlock(ScreenPtr pScreen);
 
-Bool DRI2CreateDrawable(ScreenPtr	 pScreen,
-			DrawablePtr	 pDraw,
-			drm_drawable_t	*pDrmDrawable,
-			unsigned int    *head);
+Bool DRI2CreateDrawable(DrawablePtr pDraw,
+			unsigned int *handle,
+			unsigned int *head);
 
-void DRI2DestroyDrawable(ScreenPtr	pScreen,
-			 DrawablePtr	pDraw);
+void DRI2DestroyDrawable(DrawablePtr pDraw);
 
-void DRI2ExtensionInit(void);
+void DRI2ReemitDrawableInfo(DrawablePtr pDraw,
+			    unsigned int *head);
+
+Bool DRI2PostDamage(DrawablePtr pDrawable,
+		    struct drm_clip_rect *rects, int numRects);
 
 #endif
diff --git a/hw/xfree86/dri2/dri2ext.c b/hw/xfree86/dri2/dri2ext.c
new file mode 100644
index 0000000..ca2e029
--- /dev/null
+++ b/hw/xfree86/dri2/dri2ext.c
@@ -0,0 +1,361 @@
+/*
+ * Copyright © 2008 Red Hat, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Soft-
+ * ware"), to deal in the Software without restriction, including without
+ * limitation the rights to use, copy, modify, merge, publish, distribute,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, provided that the above copyright
+ * notice(s) and this permission notice appear in all copies of the Soft-
+ * ware and that both the above copyright notice(s) and this permission
+ * notice appear in supporting documentation.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
+ * ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY
+ * RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN
+ * THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSE-
+ * QUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFOR-
+ * MANCE OF THIS SOFTWARE.
+ *
+ * Except as contained in this notice, the name of a copyright holder shall
+ * not be used in advertising or otherwise to promote the sale, use or
+ * other dealings in this Software without prior written authorization of
+ * the copyright holder.
+ *
+ * Authors:
+ *   Kristian Høgsberg (krh at redhat.com)
+ */
+
+#ifdef HAVE_XORG_CONFIG_H
+#include <xorg-config.h>
+#endif
+
+#define NEED_REPLIES
+#include <X11/X.h>
+#include <X11/Xproto.h>
+#include "dixstruct.h"
+#include "scrnintstr.h"
+#include "pixmapstr.h"
+#include "extnsionst.h"
+#include "xf86drm.h"
+#include "dri2proto.h"
+#include "dri2.h"
+
+/* The only xf86 include */
+#include "xf86Module.h"
+
+static ExtensionEntry	*dri2Extension;
+static RESTYPE		 dri2DrawableRes;
+
+static Bool
+validScreen(ClientPtr client, int screen, ScreenPtr *pScreen)
+{
+    if (screen >= screenInfo.numScreens) {
+	client->errorValue = screen;
+	return FALSE;
+    }
+
+    *pScreen = screenInfo.screens[screen];
+
+    return TRUE;
+}
+
+static Bool
+validDrawable(ClientPtr client, XID drawable,
+	      DrawablePtr *pDrawable, int *status)
+{
+    *status = dixLookupDrawable(pDrawable, drawable, client, 0, DixReadAccess);
+    if (*status != Success) {
+	client->errorValue = drawable;
+	return FALSE;
+    }
+
+    return TRUE;
+}
+
+static int
+ProcDRI2QueryVersion(ClientPtr client)
+{
+    REQUEST(xDRI2QueryVersionReq);
+    xDRI2QueryVersionReply rep;
+    int n;
+
+    if (client->swapped)
+	swaps(&stuff->length, n);
+
+    REQUEST_SIZE_MATCH(xDRI2QueryVersionReq);
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.majorVersion = DRI2_MAJOR;
+    rep.minorVersion = DRI2_MINOR;
+
+    if (client->swapped) {
+    	swaps(&rep.sequenceNumber, n);
+    	swapl(&rep.length, n);
+	swapl(&rep.majorVersion, n);
+	swapl(&rep.minorVersion, n);
+    }
+
+    WriteToClient(client, sizeof(xDRI2QueryVersionReply), &rep);
+
+    return client->noClientException;
+}
+
+static int
+ProcDRI2Connect(ClientPtr client)
+{
+    REQUEST(xDRI2ConnectReq);
+    xDRI2ConnectReply rep;
+    ScreenPtr pScreen;
+    int fd;
+    const char *driverName;
+    char *busId;
+    unsigned int sareaHandle;
+
+    REQUEST_SIZE_MATCH(xDRI2ConnectReq);
+    if (!validScreen(client, stuff->screen, &pScreen))
+	return BadValue;
+    
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.driverNameLength = 0;
+    rep.busIdLength = 0;
+    rep.sareaHandle = 0;
+
+    if (!DRI2Connect(pScreen, &fd, &driverName, &sareaHandle))
+	goto fail;
+
+    busId = drmGetBusid(fd);
+    if (busId == NULL)
+	goto fail;
+
+    rep.driverNameLength = strlen(driverName);
+    rep.busIdLength = strlen(busId);
+    rep.sareaHandle = sareaHandle;
+    rep.length = (rep.driverNameLength + 3) / 4 + (rep.busIdLength + 3) / 4;
+
+ fail:
+    WriteToClient(client, sizeof(xDRI2ConnectReply), &rep);
+    WriteToClient(client, rep.driverNameLength, driverName);
+    WriteToClient(client, rep.busIdLength, busId);
+    drmFreeBusid(busId);
+
+    return client->noClientException;
+}
+
+static int
+ProcDRI2AuthConnection(ClientPtr client)
+{
+    REQUEST(xDRI2AuthConnectionReq);
+    xDRI2AuthConnectionReply rep;
+    ScreenPtr pScreen;
+
+    REQUEST_SIZE_MATCH(xDRI2AuthConnectionReq);
+    if (!validScreen(client, stuff->screen, &pScreen))
+	return BadValue;
+
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.authenticated = 1;
+
+    if (!DRI2AuthConnection(pScreen, stuff->magic)) {
+        ErrorF("DRI2: Failed to authenticate %lu\n",
+	       (unsigned long) stuff->magic);
+	rep.authenticated = 0;
+    }
+
+    WriteToClient(client, sizeof(xDRI2AuthConnectionReply), &rep);
+
+    return client->noClientException;
+}
+
+static int
+ProcDRI2CreateDrawable(ClientPtr client)
+{
+    REQUEST(xDRI2CreateDrawableReq);
+    xDRI2CreateDrawableReply rep;
+    DrawablePtr pDrawable;
+    unsigned int handle, head;
+    int status;
+
+    REQUEST_SIZE_MATCH(xDRI2CreateDrawableReq);
+
+    if (!validDrawable(client, stuff->drawable, &pDrawable, &status))
+	return status;
+
+    if (!DRI2CreateDrawable(pDrawable, &handle, &head))
+	return BadMatch;
+
+    if (!AddResource(stuff->drawable, dri2DrawableRes, pDrawable)) {
+	DRI2DestroyDrawable(pDrawable);
+	return BadAlloc;
+    }
+
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.handle = handle;
+    rep.head = head;
+
+    WriteToClient(client, sizeof(xDRI2CreateDrawableReply), &rep);
+
+    return client->noClientException;
+}
+
+static int
+ProcDRI2DestroyDrawable(ClientPtr client)
+{
+    REQUEST(xDRI2DestroyDrawableReq);
+    DrawablePtr pDrawable;
+    int status;
+
+    REQUEST_SIZE_MATCH(xDRI2DestroyDrawableReq);
+    if (!validDrawable(client, stuff->drawable, &pDrawable, &status))
+	return status;
+
+    FreeResourceByType(stuff->drawable, dri2DrawableRes, FALSE);
+
+    return client->noClientException;
+}
+
+static int
+ProcDRI2ReemitDrawableInfo(ClientPtr client)
+{
+    REQUEST(xDRI2ReemitDrawableInfoReq);
+    xDRI2ReemitDrawableInfoReply rep;
+    DrawablePtr pDrawable;
+    unsigned int head;
+    int status;
+
+    REQUEST_SIZE_MATCH(xDRI2ReemitDrawableInfoReq);
+    if (!validDrawable(client, stuff->drawable, &pDrawable, &status))
+	return status;
+
+    DRI2ReemitDrawableInfo(pDrawable, &head);
+
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.head = head;
+
+    WriteToClient(client, sizeof(xDRI2ReemitDrawableInfoReply), &rep);
+
+    return client->noClientException;
+}
+
+static int
+ProcDRI2Dispatch (ClientPtr client)
+{
+    REQUEST(xReq);
+    
+    switch (stuff->data) {
+    case X_DRI2QueryVersion:
+	return ProcDRI2QueryVersion(client);
+    }
+
+    if (!LocalClient(client))
+	return BadRequest;
+
+    switch (stuff->data) {
+    case X_DRI2Connect:
+	return ProcDRI2Connect(client);
+    case X_DRI2AuthConnection:
+	return ProcDRI2AuthConnection(client);
+    case X_DRI2CreateDrawable:
+	return ProcDRI2CreateDrawable(client);
+    case X_DRI2DestroyDrawable:
+	return ProcDRI2DestroyDrawable(client);
+    case X_DRI2ReemitDrawableInfo:
+	return ProcDRI2ReemitDrawableInfo(client);
+    default:
+	return BadRequest;
+    }
+}
+
+static int
+SProcDRI2Connect(ClientPtr client)
+{
+    REQUEST(xDRI2ConnectReq);
+    xDRI2ConnectReply rep;
+    int n;
+
+    /* If the client is swapped, it's not local.  Talk to the hand. */
+
+    swaps(&stuff->length, n);
+    if (sizeof(*stuff) / 4 != client->req_len)
+	return BadLength;
+
+    rep.sequenceNumber = client->sequence;
+    swaps(&rep.sequenceNumber, n);
+    rep.length = 0;
+    rep.driverNameLength = 0;
+    rep.busIdLength = 0;
+    rep.sareaHandle = 0;
+
+    return client->noClientException;
+}
+
+static int
+SProcDRI2Dispatch (ClientPtr client)
+{
+    REQUEST(xReq);
+
+    /*
+     * Only local clients are allowed DRI access, but remote clients
+     * still need these requests to find out cleanly.
+     */
+    switch (stuff->data)
+    {
+    case X_DRI2QueryVersion:
+	return ProcDRI2QueryVersion(client);
+    case X_DRI2Connect:
+	return SProcDRI2Connect(client);
+    default:
+	return BadRequest;
+    }
+}
+
+static void
+DRI2ResetProc (ExtensionEntry *extEntry)
+{
+}
+
+static int DRI2DrawableGone(pointer p, XID id)
+{
+    DrawablePtr pDrawable = p;
+
+    DRI2DestroyDrawable(pDrawable);
+
+    return Success;
+}
+
+static void
+DRI2ExtensionInit(void)
+{
+    dri2Extension = AddExtension(DRI2_NAME,
+				 DRI2NumberEvents,
+				 DRI2NumberErrors,
+				 ProcDRI2Dispatch,
+				 SProcDRI2Dispatch,
+				 DRI2ResetProc,
+				 StandardMinorOpcode);
+
+    dri2DrawableRes = CreateNewResourceType(DRI2DrawableGone);
+}
+
+extern Bool noDRI2Extension;
+
+_X_HIDDEN ExtensionModule dri2ExtensionModule = {
+    DRI2ExtensionInit,
+    DRI2_NAME,
+    &noDRI2Extension,
+    NULL,
+    NULL
+};
diff --git a/os/utils.c b/os/utils.c
index 57293ab..d785d46 100644
--- a/os/utils.c
+++ b/os/utils.c
@@ -239,6 +239,9 @@ _X_EXPORT int selinuxEnforcingState = SELINUX_MODE_DEFAULT;
 #ifdef XV
 _X_EXPORT Bool noXvExtension = FALSE;
 #endif
+#ifdef DRI2
+_X_EXPORT Bool noDRI2Extension = FALSE;
+#endif
 
 #define X_INCLUDE_NETDB_H
 #include <X11/Xos_r.h>
commit 8074676d2df8d577b443e3fa5e22d7c71c944bd1
Author: Fredrik Höglund <fredrik at kde.org>
Date:   Mon Mar 31 21:24:59 2008 +0200

    EXA: Optimize the eviction scanning loop in exaOffscreenAlloc.
    
    Reduce the cost of the inner loop, by keeping a set of pointers to the
    first and the last areas in the series, subtracting the cost of the first
    area from the score, and adding the cost of the last area while walking
    the list.  This commit also moves the scanning loop from exaOffscreenAlloc
    into a separate function.
    
    Idea by Michel Dänzer.

diff --git a/exa/exa_offscreen.c b/exa/exa_offscreen.c
index 2701e84..85b5388 100644
--- a/exa/exa_offscreen.c
+++ b/exa/exa_offscreen.c
@@ -73,6 +73,62 @@ ExaOffscreenKickOut (ScreenPtr pScreen, ExaOffscreenArea *area)
 
 #define AREA_SCORE(area) (area->size / (double)(pExaScr->offScreenCounter - area->last_use))
 
+static ExaOffscreenArea *
+exaFindAreaToEvict(ExaScreenPrivPtr pExaScr, int size, int align)
+{
+    ExaOffscreenArea *begin, *end, *best;
+    double score, best_score;
+    int avail, real_size, tmp;
+
+    best_score = UINT_MAX;
+    begin = end = pExaScr->info->offScreenAreas;
+    avail = 0;
+    score = 0;
+    best = 0;
+
+    while (end != NULL)
+    {
+	restart:
+	while (begin != NULL && begin->state == ExaOffscreenLocked)
+	    begin = end = begin->next;
+
+	if (begin == NULL)
+	    break;
+
+	/* adjust size needed to account for alignment loss for this area */
+	real_size = size;
+	tmp = begin->base_offset % align;
+	if (tmp)
+	    real_size += (align - tmp);
+
+	while (avail < real_size && end != NULL)
+	{
+	    if (end->state == ExaOffscreenLocked) {
+		/* Can't more room here, restart after this locked area */
+		avail = 0;
+		score = 0;
+		begin = end;
+		goto restart;
+	    }
+	    avail += end->size;
+	    score += AREA_SCORE(end);
+	    end = end->next;
+	}
+
+	/* Check the score, update best */
+	if (avail >= real_size && score < best_score) {
+	    best = begin;
+	    best_score = score;
+	}
+
+	avail -= begin->size;
+	score -= AREA_SCORE(begin);
+	begin = begin->next;
+    }
+
+    return best;
+}
+
 /**
  * exaOffscreenAlloc allocates offscreen memory
  *
@@ -98,7 +154,7 @@ exaOffscreenAlloc (ScreenPtr pScreen, int size, int align,
                    ExaOffscreenSaveProc save,
                    pointer privData)
 {
-    ExaOffscreenArea *area, *begin, *best;
+    ExaOffscreenArea *area;
     ExaScreenPriv (pScreen);
     int tmp, real_size = 0;
 #if DEBUG_OFFSCREEN
@@ -145,54 +201,8 @@ exaOffscreenAlloc (ScreenPtr pScreen, int size, int align,
 
     if (!area)
     {
-	double best_score;
-	/*
-	 * Kick out existing users to make space.
-	 *
-	 * First, locate a region which can hold the desired object.
-	 */
+	area = exaFindAreaToEvict(pExaScr, size, align);
 
-	/* prev points at the first object to boot */
-	best = NULL;
-	best_score = UINT_MAX;
-	for (begin = pExaScr->info->offScreenAreas; begin != NULL;
-	     begin = begin->next)
-	{
-	    int avail;
-	    double score;
-	    ExaOffscreenArea *scan;
-
-	    if (begin->state == ExaOffscreenLocked)
-		continue;
-
-	    /* adjust size needed to account for alignment loss for this area */
-	    real_size = size;
-	    tmp = begin->base_offset % align;
-	    if (tmp)
-		real_size += (align - tmp);
-
-	    avail = 0;
-	    score = 0;
-	    /* now see if we can make room here, and how "costly" it'll be. */
-	    for (scan = begin; scan != NULL; scan = scan->next)
-	    {
-		if (scan->state == ExaOffscreenLocked) {
-		    /* Can't make room here, start after this locked area. */
-		    begin = scan;
-		    break;
-		}
-		score += AREA_SCORE(scan);
-		avail += scan->size;
-		if (avail >= real_size)
-		    break;
-	    }
-	    /* Is it the best option we've found so far? */
-	    if (avail >= real_size && score < best_score) {
-		best = begin;
-		best_score = score;
-	    }
-	}
-	area = best;
 	if (!area)
 	{
 	    DBG_OFFSCREEN (("Alloc 0x%x -> NOSPACE\n", size));
commit 93d876891dbba41b920a9a29a5de77f647f43928
Author: Fredrik Höglund <fredrik at kde.org>
Date:   Mon Mar 31 21:15:50 2008 +0200

    EXA: Improve the algorithm used for tracking offscreen pixmap use.
    
    Replace the current score keeping algorithm with a rolling counter that's
    incremented in ExaOffscreenMarkUsed, with the previous value being stored
    in the area.  exaOffscreenAlloc uses the difference between the counter
    value and the value in the area when deciding which area to evict.
    It now also takes the size of the areas into account, and favors evicting
    smaller areas.
    
    The credit for these ideas goes to Michel Dänzer.

diff --git a/exa/exa.h b/exa/exa.h
index 0774a70..97ae6c0 100644
--- a/exa/exa.h
+++ b/exa/exa.h
@@ -56,7 +56,7 @@ struct _ExaOffscreenArea {
     int                 base_offset;	/* allocation base */
     int                 offset;         /* aligned offset */
     int                 size;           /* total allocation size */
-    int                 score;
+    unsigned            last_use;
     pointer             privData;
 
     ExaOffscreenSaveProc save;
diff --git a/exa/exa_offscreen.c b/exa/exa_offscreen.c
index c666b00..2701e84 100644
--- a/exa/exa_offscreen.c
+++ b/exa/exa_offscreen.c
@@ -71,6 +71,8 @@ ExaOffscreenKickOut (ScreenPtr pScreen, ExaOffscreenArea *area)
     return exaOffscreenFree (pScreen, area);
 }
 
+#define AREA_SCORE(area) (area->size / (double)(pExaScr->offScreenCounter - area->last_use))
+
 /**
  * exaOffscreenAlloc allocates offscreen memory
  *
@@ -98,7 +100,7 @@ exaOffscreenAlloc (ScreenPtr pScreen, int size, int align,
 {
     ExaOffscreenArea *area, *begin, *best;
     ExaScreenPriv (pScreen);
-    int tmp, real_size = 0, best_score;
+    int tmp, real_size = 0;
 #if DEBUG_OFFSCREEN
     static int number = 0;
     ErrorF("================= ============ allocating a new pixmap %d\n", ++number);
@@ -143,6 +145,7 @@ exaOffscreenAlloc (ScreenPtr pScreen, int size, int align,
 
     if (!area)
     {
+	double best_score;
 	/*
 	 * Kick out existing users to make space.
 	 *
@@ -151,11 +154,12 @@ exaOffscreenAlloc (ScreenPtr pScreen, int size, int align,
 
 	/* prev points at the first object to boot */
 	best = NULL;
-	best_score = INT_MAX;
+	best_score = UINT_MAX;
 	for (begin = pExaScr->info->offScreenAreas; begin != NULL;
 	     begin = begin->next)
 	{
-	    int avail, score;
+	    int avail;
+	    double score;
 	    ExaOffscreenArea *scan;
 
 	    if (begin->state == ExaOffscreenLocked)
@@ -177,8 +181,7 @@ exaOffscreenAlloc (ScreenPtr pScreen, int size, int align,
 		    begin = scan;
 		    break;
 		}
-		/* Score should only be non-zero for ExaOffscreenRemovable */
-		score += scan->score;
+		score += AREA_SCORE(scan);
 		avail += scan->size;
 		if (avail >= real_size)
 		    break;
@@ -230,7 +233,7 @@ exaOffscreenAlloc (ScreenPtr pScreen, int size, int align,
 	new_area->size = area->size - real_size;
 	new_area->state = ExaOffscreenAvail;
 	new_area->save = NULL;
-	new_area->score = 0;
+	new_area->last_use = 0;
 	new_area->next = area->next;
 	area->next = new_area;
 	area->size = real_size;
@@ -244,7 +247,7 @@ exaOffscreenAlloc (ScreenPtr pScreen, int size, int align,
 	area->state = ExaOffscreenRemovable;
     area->privData = privData;
     area->save = save;
-    area->score = 0;
+    area->last_use = pExaScr->offScreenCounter++;
     area->offset = (area->base_offset + align - 1);
     area->offset -= area->offset % align;
 
@@ -395,7 +398,7 @@ exaOffscreenFree (ScreenPtr pScreen, ExaOffscreenArea *area)
 
     area->state = ExaOffscreenAvail;
     area->save = NULL;
-    area->score = 0;
+    area->last_use = 0;
     /*
      * Find previous area
      */
@@ -427,23 +430,11 @@ ExaOffscreenMarkUsed (PixmapPtr pPixmap)
 {
     ExaPixmapPriv (pPixmap);
     ExaScreenPriv (pPixmap->drawable.pScreen);
-    static int iter = 0;
 
     if (!pExaPixmap || !pExaPixmap->area)
 	return;
 
-    /* The numbers here are arbitrary.  We may want to tune these. */
-    pExaPixmap->area->score += 100;
-    if (++iter == 10) {
-	ExaOffscreenArea *area;
-	for (area = pExaScr->info->offScreenAreas; area != NULL;
-	     area = area->next)
-	{
-	    if (area->state == ExaOffscreenRemovable)
-		area->score = (area->score * 7) / 8;
-	}
-	iter = 0;
-    }
+    pExaPixmap->area->last_use = pExaScr->offScreenCounter++;
 }
 
 /**
@@ -472,10 +463,11 @@ exaOffscreenInit (ScreenPtr pScreen)
     area->size = pExaScr->info->memorySize - area->base_offset;
     area->save = NULL;
     area->next = NULL;
-    area->score = 0;
+    area->last_use = 0;
 
     /* Add it to the free areas */
     pExaScr->info->offScreenAreas = area;
+    pExaScr->offScreenCounter = 1;
 
     ExaOffscreenValidate (pScreen);
 
diff --git a/exa/exa_priv.h b/exa/exa_priv.h
index 89f4718..e41f46a 100644
--- a/exa/exa_priv.h
+++ b/exa/exa_priv.h
@@ -120,6 +120,7 @@ typedef struct {
     Bool			 checkDirtyCorrectness;
     unsigned			 disableFbCount;
     Bool			 optimize_migration;
+    unsigned			 offScreenCounter;
 } ExaScreenPrivRec, *ExaScreenPrivPtr;
 
 /*
commit 7034484f0887ea0f8ab956515f2d9301ea5842ce
Author: Daniel Stone <daniel at fooishbar.org>
Date:   Fri Mar 28 10:23:36 2008 +0200

    gitignore: Add two more bits
    
    Get slightly better at ignoring vim swap files, and let people keep
    local changes if they want to.

diff --git a/.gitignore b/.gitignore
index fb2f7e5..837b038 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,11 +8,12 @@ Makefile.in
 *.a
 *.o
 *~
-.*.swp
+.*sw?
 *.pbxuser
 *.mode1v3
 obj*
 build*
+local
 aclocal.m4
 autom4te.cache
 compile
commit b8ea9f2a25aad88aee77a68f8e20ac07276f0dab
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri Mar 28 17:00:08 2008 -0700

    XQuartz: Fixed names of enums to be more consistent
    (cherry picked from commit c309a08806daf5d716a860c709e51eacad2c745a)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index e1581af..31c80df 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -153,7 +153,7 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 	
     tem = [infoDict objectForKey:@"CFBundleShortVersionString"];
 	
-    [dict setObject:[NSString stringWithFormat:@"XQuartz %@ - (xorg-server %s)", tem, XSERVER_VERSION] 
+    [dict setObject:[NSString stringWithFormat:@"Xquartz %@ - (xorg-server %s)", tem, XSERVER_VERSION] 
 	  forKey:@"ApplicationVersion"];
 	
     [self orderFrontStandardAboutPanelWithOptions: dict];
@@ -166,7 +166,7 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
     static TSMDocumentID x11_document;
 	DEBUG_LOG("state=%d, _x_active=%d, \n", state, _x_active)
     if (state) {
-      QuartzMessageServerThread (kXDarwinActivate, 0);
+      QuartzMessageServerThread (kXquartzActivate, 0);
       
       if (!_x_active) {
 	if (x11_document == 0 && darwinKeymapFile == NULL) {
@@ -178,7 +178,7 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 	if (x11_document != 0)	ActivateTSMDocument (x11_document);
       }
     } else {
-      QuartzMessageServerThread (kXDarwinDeactivate, 0);
+      QuartzMessageServerThread (kXquartzDeactivate, 0);
       
       if (_x_active && x11_document != 0)
 	DeactivateTSMDocument (x11_document);
@@ -246,7 +246,7 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 	  swallow_up = 0;
 	  for_x = NO;
 #ifdef DARWIN_DDX_MISSING
-	  QuartzMessageServerThread (kXDarwinToggleFullscreen, 0);
+	  QuartzMessageServerThread (kXquartzToggleFullscreen, 0);
 #endif
 	}
       } else {
@@ -654,7 +654,7 @@ static NSMutableArray * cfarray_to_nsarray (CFArrayRef in) {
 
 /* This will end up at the end of the responder chain. */
 - (void) copy:sender {
-  QuartzMessageServerThread (kXDarwinPasteboardNotify, 1,
+  QuartzMessageServerThread (kXquartzPasteboardNotify, 1,
 			     AppleWMCopyToPasteboard);
 }
 
diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index dfa2074..aa9fa94 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -103,7 +103,7 @@
 {
   [NSApp activateIgnoringOtherApps:YES];
 	
-  QuartzMessageServerThread (kXDarwinControllerNotify, 2,
+  QuartzMessageServerThread (kXquartzControllerNotify, 2,
 			     AppleWMWindowMenuItem, [sender tag]);
 }
 
@@ -254,7 +254,7 @@
   [self remove_window_menu];
   [self install_window_menu:list];
 	
-  QuartzMessageServerThread (kXDarwinControllerNotify, 1,
+  QuartzMessageServerThread (kXquartzControllerNotify, 1,
 			     AppleWMWindowMenuNotify);
 }
 
@@ -539,20 +539,20 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 - (void) hide_window:sender
 {
   if ([X11App x_active])
-    QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMHideWindow);
+    QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMHideWindow);
   else
     NSBeep ();			/* FIXME: something here */
 }
 
 - (IBAction)bring_to_front:sender
 {
-  QuartzMessageServerThread(kXDarwinControllerNotify, 1, AppleWMBringAllToFront);
+  QuartzMessageServerThread(kXquartzControllerNotify, 1, AppleWMBringAllToFront);
 }
 
 - (IBAction)close_window:sender
 {
   if ([X11App x_active])
-    QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMCloseWindow);
+    QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMCloseWindow);
   else
     [[NSApp keyWindow] performClose:sender];
 }
@@ -560,7 +560,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 - (IBAction)minimize_window:sender
 {
   if ([X11App x_active])
-    QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMMinimizeWindow);
+    QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMMinimizeWindow);
   else
     [[NSApp keyWindow] performMiniaturize:sender];
 }
@@ -568,19 +568,19 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 - (IBAction)zoom_window:sender
 {
   if ([X11App x_active])
-    QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMZoomWindow);
+    QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMZoomWindow);
   else
     [[NSApp keyWindow] performZoom:sender];
 }
 
 - (IBAction) next_window:sender
 {
-  QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMNextWindow);
+  QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMNextWindow);
 }
 
 - (IBAction) previous_window:sender
 {
-  QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMPreviousWindow);
+  QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMPreviousWindow);
 }
 
 - (IBAction) enable_fullscreen_changed:sender
@@ -588,7 +588,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
   int value = ![enable_fullscreen intValue];
 	
 #ifdef DARWIN_DDX_MISSING
-  QuartzMessageServerThread (kXDarwinSetRootless, 1, value);
+  QuartzMessageServerThread (kXquartzSetRootless, 1, value);
 #endif
 	
   [NSApp prefs_set_boolean:@PREFS_ROOTLESS value:value];
@@ -598,7 +598,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 - (IBAction) toggle_fullscreen:sender
 {
 #ifdef DARWIN_DDX_MISSING
-  QuartzMessageServerThread (kXDarwinToggleFullscreen, 0);
+  QuartzMessageServerThread (kXquartzToggleFullscreen, 0);
 #endif
 }
 
@@ -661,7 +661,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 
 - (IBAction) quit:sender
 {
-  QuartzMessageServerThread (kXDarwinQuit, 0);
+  QuartzMessageServerThread (kXquartzQuit, 0);
 }
 
 - (IBAction) x11_help:sender
@@ -684,12 +684,12 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 
 - (void) applicationDidHide:(NSNotification *)notify
 {
-  QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMHideAll);
+  QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMHideAll);
 }
 
 - (void) applicationDidUnhide:(NSNotification *)notify
 {
-  QuartzMessageServerThread (kXDarwinControllerNotify, 1, AppleWMShowAll);
+  QuartzMessageServerThread (kXquartzControllerNotify, 1, AppleWMShowAll);
 }
 
 - (NSApplicationTerminateReply) applicationShouldTerminate:sender
@@ -717,7 +717,7 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
   [X11App prefs_synchronize];
 	
   /* shutdown the X server, it will exit () for us. */
-  QuartzMessageServerThread (kXDarwinQuit, 0);
+  QuartzMessageServerThread (kXquartzQuit, 0);
 	
   /* In case it doesn't, exit anyway after a while. */
   while (sleep (10) != 0) ;
diff --git a/hw/xquartz/darwin.c b/hw/xquartz/darwin.c
index 20bcee5..0dbfafe 100644
--- a/hw/xquartz/darwin.c
+++ b/hw/xquartz/darwin.c
@@ -150,7 +150,7 @@ void
 DarwinPrintBanner(void)
 { 
   // this should change depending on which specific server we are building
-  ErrorF("XQuartz starting:\n");
+  ErrorF("Xquartz starting:\n");
   ErrorF("X.org Release 7.2\n"); // This is here to help fink until they fix their packages.
   ErrorF("X.Org X Server %s\nBuild Date: %s\n", XSERVER_VERSION, BUILD_DATE );
 }
@@ -856,7 +856,7 @@ void ddxUseMsg( void )
  */
 void ddxGiveUp( void )
 {
-    ErrorF( "Quitting XQuartz...\n" );
+    ErrorF( "Quitting Xquartz...\n" );
 
     //if (!quartzRootless)
     //    quartzProcs->ReleaseScreens();
diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index 325122d..bd1b9a4 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -90,34 +90,34 @@ extern int              darwinMainScreenY;
  * Special ddx events understood by the X server
  */
 enum {
-    kXDarwinUpdateModifiers   // update all modifier keys
+    kXquartzUpdateModifiers   // update all modifier keys
             = LASTEvent+1,    // (from X.h list of event names)
-    kXDarwinUpdateButtons,    // update state of mouse buttons 2 and up
-    kXDarwinScrollWheel,      // scroll wheel event
+    kXquartzUpdateButtons,    // update state of mouse buttons 2 and up
+    kXquartzScrollWheel,      // scroll wheel event
     /*
      * Quartz-specific events -- not used in IOKit mode
      */
-    kXDarwinActivate,         // restore X drawing and cursor
-    kXDarwinDeactivate,       // clip X drawing and switch to Aqua cursor
-    kXDarwinSetRootClip,      // enable or disable drawing to the X screen
-    kXDarwinQuit,             // kill the X server and release the display
-    kXDarwinReadPasteboard,   // copy Mac OS X pasteboard into X cut buffer
-    kXDarwinWritePasteboard,  // copy X cut buffer onto Mac OS X pasteboard
-    kXDarwinBringAllToFront,  // bring all X windows to front
-    kXDarwinToggleFullscreen, // Enable/Disable fullscreen mode
-    kXDarwinSetRootless,      // Set rootless mode
-    kXDarwinSpaceChanged,     // Spaces changed
+    kXquartzActivate,         // restore X drawing and cursor
+    kXquartzDeactivate,       // clip X drawing and switch to Aqua cursor
+    kXquartzSetRootClip,      // enable or disable drawing to the X screen
+    kXquartzQuit,             // kill the X server and release the display
+    kXquartzReadPasteboard,   // copy Mac OS X pasteboard into X cut buffer
+    kXquartzWritePasteboard,  // copy X cut buffer onto Mac OS X pasteboard
+    kXquartzBringAllToFront,  // bring all X windows to front
+    kXquartzToggleFullscreen, // Enable/Disable fullscreen mode
+    kXquartzSetRootless,      // Set rootless mode
+    kXquartzSpaceChanged,     // Spaces changed
     /*
      * AppleWM events
      */
-    kXDarwinControllerNotify, // send an AppleWMControllerNotify event
-    kXDarwinPasteboardNotify, // notify the WM to copy or paste
+    kXquartzControllerNotify, // send an AppleWMControllerNotify event
+    kXquartzPasteboardNotify, // notify the WM to copy or paste
     /*
      * Xplugin notification events
      */
-    kXDarwinDisplayChanged,   // display configuration has changed
-    kXDarwinWindowState,      // window visibility state has changed
-    kXDarwinWindowMoved,      // window has moved on screen
+    kXquartzDisplayChanged,   // display configuration has changed
+    kXquartzWindowState,      // window visibility state has changed
+    kXquartzWindowMoved,      // window has moved on screen
 };
 
 #define ENABLE_DEBUG_LOG 1
diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 22d8957..113cfc1 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -152,7 +152,7 @@ static void DarwinUpdateModifiers(
 /*
  * DarwinReleaseModifiers
  * This hacky function releases all modifier keys.  It should be called when X11.app
- * is deactivated (kXDarwinDeactivate) to prevent modifiers from getting stuck if they
+ * is deactivated (kXquartzDeactivate) to prevent modifiers from getting stuck if they
  * are held down during a "context" switch -- otherwise, we would miss the KeyUp.
  */
 static void DarwinReleaseModifiers(void) {
@@ -341,22 +341,22 @@ void ProcessInputEvents(void) {
                 break;
 
             case MotionNotify:
-	      ErrorF("Unexpected ButtonRelease event in DarwinProcessInputEvents\n");
+	      ErrorF("Unexpected MotionNotify event in DarwinProcessInputEvents\n");
                 break;
 
-            case kXDarwinUpdateModifiers:
-	      ErrorF("Unexpected ButtonRelease event in DarwinProcessInputEvents\n");
+            case kXquartzUpdateModifiers:
+	      ErrorF("Unexpected kXquartzUpdateModifiers event in DarwinProcessInputEvents\n");
 	      break;
 
-            case kXDarwinUpdateButtons:
-	      ErrorF("Unexpected XDarwinScrollWheel event in DarwinProcessInputEvents\n");
+            case kXquartzUpdateButtons:
+	      ErrorF("Unexpected kXquartzUpdateButtons event in DarwinProcessInputEvents\n");
 	      break;
 
-            case kXDarwinScrollWheel: 
-	      ErrorF("Unexpected XDarwinScrollWheel event in DarwinProcessInputEvents\n");
+            case kXquartzScrollWheel: 
+	      ErrorF("Unexpected kXquartzScrollWheel event in DarwinProcessInputEvents\n");
 	      break;
 
-			case kXDarwinDeactivate:
+			case kXquartzDeactivate:
 				DarwinReleaseModifiers();
 				// fall through
             default:
diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index a034c9f..971c9b2 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -411,24 +411,24 @@ QuartzMessageServerThread(
  */
 void QuartzProcessEvent(xEvent *xe) {
     switch (xe->u.u.type) {
-        case kXDarwinControllerNotify:
-            DEBUG_LOG("kXDarwinControllerNotify\n");
+        case kXquartzControllerNotify:
+            DEBUG_LOG("kXquartzControllerNotify\n");
             AppleWMSendEvent(AppleWMControllerNotify,
                              AppleWMControllerNotifyMask,
                              xe->u.clientMessage.u.l.longs0,
                              xe->u.clientMessage.u.l.longs1);
             break;
 
-        case kXDarwinPasteboardNotify:
-            DEBUG_LOG("kXDarwinPasteboardNotify\n");
+        case kXquartzPasteboardNotify:
+            DEBUG_LOG("kXquartzPasteboardNotify\n");
             AppleWMSendEvent(AppleWMPasteboardNotify,
                              AppleWMPasteboardNotifyMask,
                              xe->u.clientMessage.u.l.longs0,
                              xe->u.clientMessage.u.l.longs1);
             break;
 
-        case kXDarwinActivate:
-            DEBUG_LOG("kXDarwinActivate\n");
+        case kXquartzActivate:
+            DEBUG_LOG("kXquartzActivate\n");
             QuartzShow(xe->u.keyButtonPointer.rootX,
                        xe->u.keyButtonPointer.rootY);
             AppleWMSendEvent(AppleWMActivationNotify,
@@ -436,74 +436,74 @@ void QuartzProcessEvent(xEvent *xe) {
                              AppleWMIsActive, 0);
             break;
 
-        case kXDarwinDeactivate:
-            DEBUG_LOG("kXDarwinDeactivate\n");
+        case kXquartzDeactivate:
+            DEBUG_LOG("kXquartzDeactivate\n");
             AppleWMSendEvent(AppleWMActivationNotify,
                              AppleWMActivationNotifyMask,
                              AppleWMIsInactive, 0);
             QuartzHide();
             break;
 
-        case kXDarwinDisplayChanged:
-            DEBUG_LOG("kXDarwinDisplayChanged\n");
+        case kXquartzDisplayChanged:
+            DEBUG_LOG("kXquartzDisplayChanged\n");
             QuartzUpdateScreens();
             break;
 
-        case kXDarwinWindowState:
-            DEBUG_LOG("kXDarwinWindowState\n");
+        case kXquartzWindowState:
+            DEBUG_LOG("kXquartzWindowState\n");
             RootlessNativeWindowStateChanged(xe->u.clientMessage.u.l.longs0,
 		  			     xe->u.clientMessage.u.l.longs1);
 	    break;
 	  
-        case kXDarwinWindowMoved:
-            DEBUG_LOG("kXDarwinWindowMoved\n");
+        case kXquartzWindowMoved:
+            DEBUG_LOG("kXquartzWindowMoved\n");
             RootlessNativeWindowMoved ((WindowPtr)xe->u.clientMessage.u.l.longs0);
 	    break;
 
-        case kXDarwinToggleFullscreen:
-            DEBUG_LOG("kXDarwinToggleFullscreen\n");
+        case kXquartzToggleFullscreen:
+            DEBUG_LOG("kXquartzToggleFullscreen\n");
 #ifdef DARWIN_DDX_MISSING
             if (quartzEnableRootless) QuartzSetFullscreen(!quartzHasRoot);
             else if (quartzHasRoot) QuartzHide();
             else QuartzShow();
 #else
-    //	    ErrorF("kXDarwinToggleFullscreen not implemented\n");
+    //	    ErrorF("kXquartzToggleFullscreen not implemented\n");
 #endif
             break;
 
-        case kXDarwinSetRootless:
-            DEBUG_LOG("kXDarwinSetRootless\n");
+        case kXquartzSetRootless:
+            DEBUG_LOG("kXquartzSetRootless\n");
 #ifdef DARWIN_DDX_MISSING
             QuartzSetRootless(xe->u.clientMessage.u.l.longs0);
             if (!quartzEnableRootless && !quartzHasRoot) QuartzHide();
 #else
-    //	    ErrorF("kXDarwinSetRootless not implemented\n");
+    //	    ErrorF("kXquartzSetRootless not implemented\n");
 #endif
             break;
 
-        case kXDarwinSetRootClip:
+        case kXquartzSetRootClip:
             QuartzSetRootClip((BOOL)xe->u.clientMessage.u.l.longs0);
             break;
 
-        case kXDarwinQuit:
+        case kXquartzQuit:
             GiveUp(0);
             break;
 
-        case kXDarwinReadPasteboard:
+        case kXquartzReadPasteboard:
             QuartzReadPasteboard();
             break;
 
-        case kXDarwinWritePasteboard:
+        case kXquartzWritePasteboard:
             QuartzWritePasteboard();
             break;
 
-        case kXDarwinBringAllToFront:
-            DEBUG_LOG("kXDarwinBringAllToFront\n");
+        case kXquartzBringAllToFront:
+            DEBUG_LOG("kXquartzBringAllToFront\n");
             RootlessOrderAllWindows();
             break;
 
-        case kXDarwinSpaceChanged:
-            DEBUG_LOG("kXDarwinSpaceChanged\n");
+        case kXquartzSpaceChanged:
+            DEBUG_LOG("kXquartzSpaceChanged\n");
             QuartzSpaceChanged(xe->u.clientMessage.u.l.longs0);
             break;
         default:
diff --git a/hw/xquartz/quartzKeyboard.h b/hw/xquartz/quartzKeyboard.h
index 0c7e70e..8131b56 100644
--- a/hw/xquartz/quartzKeyboard.h
+++ b/hw/xquartz/quartzKeyboard.h
@@ -45,7 +45,7 @@ typedef struct darwinKeyboardInfo_struct {
     unsigned char modifierKeycodes[32][2];
 } darwinKeyboardInfo;
 
-/* These functions need to be implemented by XQuartz, XDarwin, etc. */
+/* These functions need to be implemented by Xquartz, XDarwin, etc. */
 void DarwinKeyboardReload(DeviceIntPtr pDev);
 Bool QuartzReadSystemKeymap(darwinKeyboardInfo *info);
 unsigned int QuartzSystemKeymapSeed(void);
diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index 4dc5846..b653a6e 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -67,7 +67,7 @@ static void eventHandler(unsigned int type, const void *arg,
     switch (type) {
         case XP_EVENT_DISPLAY_CHANGED:
             DEBUG_LOG("XP_EVENT_DISPLAY_CHANGED\n");
-            QuartzMessageServerThread(kXDarwinDisplayChanged, 0);
+            QuartzMessageServerThread(kXquartzDisplayChanged, 0);
             break;
             
         case XP_EVENT_WINDOW_STATE_CHANGED:
@@ -75,7 +75,7 @@ static void eventHandler(unsigned int type, const void *arg,
                 const xp_window_state_event *ws_arg = arg;
                 
                 DEBUG_LOG("XP_EVENT_WINDOW_STATE_CHANGED: id=%d, state=%d\n", ws_arg->id, ws_arg->state);
-                QuartzMessageServerThread(kXDarwinWindowState, 2,
+                QuartzMessageServerThread(kXquartzWindowState, 2,
                                           ws_arg->id, ws_arg->state);
             } else {
                 DEBUG_LOG("XP_EVENT_WINDOW_STATE_CHANGED: ignored\n");
@@ -87,7 +87,7 @@ static void eventHandler(unsigned int type, const void *arg,
             if (arg_size == sizeof(xp_window_id))  {
                 xp_window_id id = * (xp_window_id *) arg;
                 WindowPtr pWin = xprGetXWindow(id);
-                QuartzMessageServerThread(kXDarwinWindowMoved, 1, pWin);
+                QuartzMessageServerThread(kXquartzWindowMoved, 1, pWin);
             }
             break;
             
@@ -110,7 +110,7 @@ static void eventHandler(unsigned int type, const void *arg,
             ErrorF("XP_EVENT_SPACE_CHANGED\n");
             if(arg_size == sizeof(uint32_t)) {
                 uint32_t space_id = *(uint32_t *)arg;
-                QuartzMessageServerThread(kXDarwinSpaceChanged, 1, space_id);
+                QuartzMessageServerThread(kXquartzSpaceChanged, 1, space_id);
             }
             break;
         default:
commit bd28839eb866a9e6dc3ff80f13a67611da7eaf64
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Fri Mar 28 17:02:02 2008 -0700

    =?utf-8?q?XQuartz:=20Another=20Expos=C3=A9=20fix:=20F9=20doesn't=20raise=20all=20windows
    
    =20(cherry=20picked=20from=20commit=20b9cffa20debae73737c674bf75ab65db1bd74556)?=
    MIME-Version: 1.0
    Content-Type: text/plain; charset=utf-8
    Content-Transfer-Encoding: 8bit

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index b7c8763..e1581af 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -314,14 +314,10 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
 }
 
 - (void) set_front_process:unused {
-    /* Hackery needed due to argv[0] hackery */
-    //    [self activateX:YES];
-    ProcessSerialNumber psn = { 0, kCurrentProcess };
-    SetFrontProcess(&psn);
-
-    QuartzMessageServerThread(kXDarwinBringAllToFront, 0);
-    ProcessSerialNumber psn = { 0, kCurrentProcess };
-    SetFrontProcess(&psn);
+    [NSApp activateIgnoringOtherApps:YES];
+
+    if ([self modalWindow] == nil)
+        [self activateX:YES];
 }
 
 - (void) set_can_quit:(NSNumber *)state {
commit 933ffcdf7d2eaaf7caabfe6f861f04bcb149918f
Author: Adam Jackson <ajax at redhat.com>
Date:   Fri Mar 28 17:53:55 2008 -0400

    Compile fix.

diff --git a/hw/xfree86/ddc/xf86DDC.c b/hw/xfree86/ddc/xf86DDC.c
index 7e26722..8dda35a 100644
--- a/hw/xfree86/ddc/xf86DDC.c
+++ b/hw/xfree86/ddc/xf86DDC.c
@@ -119,7 +119,7 @@ DDC2MakeDevice(I2CBusPtr pBus, int address, char *name)
 
 	dev->pI2CBus = pBus;
 	if (!xf86I2CDevInit(dev)) {
-	    xf86DrvMsg(scrnIndex, X_PROBED, "No DDC2 device\n");
+	    xf86DrvMsg(pBus->scrnIndex, X_PROBED, "No DDC2 device\n");
 	    return NULL;
 	}
     }
commit 9e8451d869a4032ddb7de6a62920a3a7b0b1acc1
Author: Adam Jackson <ajax at redhat.com>
Date:   Mon Dec 3 17:38:53 2007 -0500

    Add E-EDID segment selection.

diff --git a/hw/xfree86/ddc/xf86DDC.c b/hw/xfree86/ddc/xf86DDC.c
index 3e51c4e..7e26722 100644
--- a/hw/xfree86/ddc/xf86DDC.c
+++ b/hw/xfree86/ddc/xf86DDC.c
@@ -104,19 +104,14 @@ xf86DoEDID_DDC1(
 }
 
 static I2CDevPtr
-DDC2Init(int scrnIndex, I2CBusPtr pBus)
+DDC2MakeDevice(I2CBusPtr pBus, int address, char *name)
 {
     I2CDevPtr dev = NULL;
-    /*
-     * Slow down the bus so that older monitors don't 
-     * miss things.
-     */
-    pBus->RiseFallTime = 20;
-    
-    if (!(dev = xf86I2CFindDev(pBus, 0x00A0))) {
+
+    if (!(dev = xf86I2CFindDev(pBus, address))) {
 	dev = xf86CreateI2CDevRec();
-	dev->DevName = "ddc2";
-	dev->SlaveAddr = 0xA0;
+	dev->DevName = name;
+	dev->SlaveAddr = address;
 	dev->ByteTimeout = 2200; /* VESA DDC spec 3 p. 43 (+10 %) */
 	dev->StartTimeout = 550;
 	dev->BitTimeout = 40;
@@ -132,33 +127,70 @@ DDC2Init(int scrnIndex, I2CBusPtr pBus)
     return dev;
 }
 
-static unsigned char *
-DDC2Read(I2CDevPtr dev, int start, int len)
+static I2CDevPtr
+DDC2Init(int scrnIndex, I2CBusPtr pBus)
 {
-    unsigned char W_Buffer[2];
-    int w_bytes;
-    unsigned char *R_Buffer;
-    int i;
-    
-    if (start < 0x100) {
-	w_bytes = 1;
-	W_Buffer[0] = start;
-    } else {
-	w_bytes = 2;
-	W_Buffer[0] = start & 0xFF;
-	W_Buffer[1] = (start & 0xFF00) >> 8;
-    }
+    I2CDevPtr dev = NULL;
+
+    /*
+     * Slow down the bus so that older monitors don't 
+     * miss things.
+     */
+    pBus->RiseFallTime = 20;
+ 
+    DDC2MakeDevice(pBus, 0x0060, "E-EDID segment register");
+    dev = DDC2MakeDevice(pBus, 0x00A0, "ddc2");
+
+    return dev;
+}
+
+/* Mmmm, smell the hacks */
+static void
+EEDIDStop(I2CDevPtr d)
+{
+}
+
+/* block is the EDID block number.  a segment is two blocks. */
+static Bool
+DDC2Read(I2CDevPtr dev, int block, unsigned char *R_Buffer)
+{
+    unsigned char W_Buffer[1];
+    int i, segment;
+    I2CDevPtr seg;
+    void (*stop)(I2CDevPtr);
 
-    R_Buffer = xcalloc(sizeof(unsigned char), len);
     for (i = 0; i < RETRIES; i++) {
-	if (xf86I2CWriteRead(dev, W_Buffer, w_bytes, R_Buffer, len)) {
-	    if (!DDC_checksum(R_Buffer, len))
-		return R_Buffer;
+	/* Stop bits reset the segment pointer to 0, so be careful here. */
+	segment = block >> 1;
+	if (segment) {
+	    Bool b;
+	    
+	    if (!(seg = xf86I2CFindDev(dev->pI2CBus, 0x0060)))
+		return FALSE;
+
+	    W_Buffer[0] = segment;
+
+	    stop = dev->pI2CBus->I2CStop;
+	    dev->pI2CBus->I2CStop = EEDIDStop;
+
+	    b = xf86I2CWriteRead(seg, W_Buffer, 1, NULL, 0);
+
+	    dev->pI2CBus->I2CStop = stop;
+	    if (!b) {
+		dev->pI2CBus->I2CStop(dev);
+		continue;
+	    }
+	}
+
+	W_Buffer[0] = (block & 0x01) * EDID1_LEN;
+
+	if (xf86I2CWriteRead(dev, W_Buffer, 1, R_Buffer, EDID1_LEN)) {
+	    if (!DDC_checksum(R_Buffer, EDID1_LEN))
+		return TRUE;
 	}
     }
  
-    xfree(R_Buffer);
-    return NULL;
+    return FALSE;
 }
 
 /**
@@ -189,7 +221,9 @@ xf86DoEEDID(int scrnIndex, I2CBusPtr pBus, int *nblocks)
     Bool noddc = FALSE, noddc2 = FALSE;
     OptionInfoPtr options;
 
-    options = xnfalloc(sizeof(DDCOptions));
+    options = xalloc(sizeof(DDCOptions));
+    if (!options)
+	return NULL;
     memcpy(options, DDCOptions, sizeof(DDCOptions));
     xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, options);
 
@@ -203,10 +237,13 @@ xf86DoEEDID(int scrnIndex, I2CBusPtr pBus, int *nblocks)
     if (!(dev = DDC2Init(scrnIndex, pBus)))
 	return NULL;
 
-    EDID_block = DDC2Read(dev, 0, EDID1_LEN);
+    EDID_block = xcalloc(1, EDID1_LEN);
+    if (!EDID_block)
+	return NULL;
 
-    if (EDID_block)
+    if (DDC2Read(dev, 0, EDID_block)) {
 	tmp = xf86InterpretEDID(scrnIndex, EDID_block);
+    }
 
     if (nblocks) {
 	if (tmp)
commit 0b4aef4d6df7a5525d381de035fbbf78c5fffeef
Author: Adam Jackson <ajax at redhat.com>
Date:   Mon Dec 3 16:00:00 2007 -0500

    Refactor DDC2 code to allow for proper segmented addressing.

diff --git a/hw/xfree86/ddc/xf86DDC.c b/hw/xfree86/ddc/xf86DDC.c
index 98f6006..3e51c4e 100644
--- a/hw/xfree86/ddc/xf86DDC.c
+++ b/hw/xfree86/ddc/xf86DDC.c
@@ -39,13 +39,6 @@ static unsigned int *FetchEDID_DDC1(
     register unsigned int (*)(ScrnInfoPtr)
 );
 
-static unsigned char * DDCRead_DDC2(
-    int scrnIndex,
-    I2CBusPtr pBus, 
-    int start, 
-    int len
-);
-
 typedef enum {
     DDCOPT_NODDC1,
     DDCOPT_NODDC2,
@@ -110,6 +103,64 @@ xf86DoEDID_DDC1(
 	return tmp;
 }
 
+static I2CDevPtr
+DDC2Init(int scrnIndex, I2CBusPtr pBus)
+{
+    I2CDevPtr dev = NULL;
+    /*
+     * Slow down the bus so that older monitors don't 
+     * miss things.
+     */
+    pBus->RiseFallTime = 20;
+    
+    if (!(dev = xf86I2CFindDev(pBus, 0x00A0))) {
+	dev = xf86CreateI2CDevRec();
+	dev->DevName = "ddc2";
+	dev->SlaveAddr = 0xA0;
+	dev->ByteTimeout = 2200; /* VESA DDC spec 3 p. 43 (+10 %) */
+	dev->StartTimeout = 550;
+	dev->BitTimeout = 40;
+	dev->AcknTimeout = 40;
+
+	dev->pI2CBus = pBus;
+	if (!xf86I2CDevInit(dev)) {
+	    xf86DrvMsg(scrnIndex, X_PROBED, "No DDC2 device\n");
+	    return NULL;
+	}
+    }
+
+    return dev;
+}
+
+static unsigned char *
+DDC2Read(I2CDevPtr dev, int start, int len)
+{
+    unsigned char W_Buffer[2];
+    int w_bytes;
+    unsigned char *R_Buffer;
+    int i;
+    
+    if (start < 0x100) {
+	w_bytes = 1;
+	W_Buffer[0] = start;
+    } else {
+	w_bytes = 2;
+	W_Buffer[0] = start & 0xFF;
+	W_Buffer[1] = (start & 0xFF00) >> 8;
+    }
+
+    R_Buffer = xcalloc(sizeof(unsigned char), len);
+    for (i = 0; i < RETRIES; i++) {
+	if (xf86I2CWriteRead(dev, W_Buffer, w_bytes, R_Buffer, len)) {
+	    if (!DDC_checksum(R_Buffer, len))
+		return R_Buffer;
+	}
+    }
+ 
+    xfree(R_Buffer);
+    return NULL;
+}
+
 /**
  * Attempts to probe the monitor for EDID information, if NoDDC and NoDDC2 are
  * unset.  EDID information blocks are interpreted and the results returned in
@@ -133,6 +184,7 @@ xf86DoEEDID(int scrnIndex, I2CBusPtr pBus, int *nblocks)
     ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
     unsigned char *EDID_block = NULL;
     xf86MonPtr tmp = NULL;
+    I2CDevPtr dev = NULL;
     /* Default DDC and DDC2 to enabled. */
     Bool noddc = FALSE, noddc2 = FALSE;
     OptionInfoPtr options;
@@ -144,11 +196,14 @@ xf86DoEEDID(int scrnIndex, I2CBusPtr pBus, int *nblocks)
     xf86GetOptValBool(options, DDCOPT_NODDC, &noddc);
     xf86GetOptValBool(options, DDCOPT_NODDC2, &noddc2);
     xfree(options);
-    
+
     if (noddc || noddc2)
 	return NULL;
 
-    EDID_block = DDCRead_DDC2(scrnIndex, pBus, 0, EDID1_LEN);
+    if (!(dev = DDC2Init(scrnIndex, pBus)))
+	return NULL;
+
+    EDID_block = DDC2Read(dev, 0, EDID1_LEN);
 
     if (EDID_block)
 	tmp = xf86InterpretEDID(scrnIndex, EDID_block);
@@ -247,62 +302,3 @@ FetchEDID_DDC1(register ScrnInfoPtr pScrn,
     } while(--count);
     return (ptr);
 }
-
-static unsigned char *
-DDCRead_DDC2(int scrnIndex, I2CBusPtr pBus, int start, int len)
-{
-    I2CDevPtr dev;
-    unsigned char W_Buffer[2];
-    int w_bytes;
-    unsigned char *R_Buffer;
-    int i;
-    
-    /*
-     * Slow down the bus so that older monitors don't 
-     * miss things.
-     */
-    pBus->RiseFallTime = 20;
-    
-    if (!(dev = xf86I2CFindDev(pBus, 0x00A0))) {
-	dev = xf86CreateI2CDevRec();
-	dev->DevName = "ddc2";
-	dev->SlaveAddr = 0xA0;
-	dev->ByteTimeout = 2200; /* VESA DDC spec 3 p. 43 (+10 %) */
-	dev->StartTimeout = 550;
-	dev->BitTimeout = 40;
-	dev->AcknTimeout = 40;
-
-	dev->pI2CBus = pBus;
-	if (!xf86I2CDevInit(dev)) {
-	    xf86DrvMsg(scrnIndex, X_PROBED, "No DDC2 device\n");
-	    return NULL;
-	}
-    }
-    if (start < 0x100) {
-	w_bytes = 1;
-	W_Buffer[0] = start;
-    } else {
-	w_bytes = 2;
-	W_Buffer[0] = start & 0xFF;
-	W_Buffer[1] = (start & 0xFF00) >> 8;
-    }
-    R_Buffer = xcalloc(1,sizeof(unsigned char) 
-					* (len));
-    for (i=0; i<RETRIES; i++) {
-	if (xf86I2CWriteRead(dev, W_Buffer,w_bytes, R_Buffer,len)) {
-	    if (!DDC_checksum(R_Buffer,len))
-		return R_Buffer;
-
-#ifdef DEBUG
-	    else ErrorF("Checksum error in EDID block\n");
-#endif
-	}
-#ifdef DEBUG
-	else ErrorF("Error reading EDID block\n");
-#endif
-    }
-    
-    xf86DestroyI2CDevRec(dev,TRUE);
-    xfree(R_Buffer);
-    return NULL;
-}
commit 88ece11d6c45c6f4b94f7fb2da64a46e879d7c27
Author: Adam Jackson <ajax at redhat.com>
Date:   Mon Dec 3 15:47:39 2007 -0500

    Start E-EDID support in the DDC module.
    
    Since there's no way to safely know how many blocks xf86DoEDID_DDC2 would
    return, add a new xf86DoEEDID entrypoint to do that, and implement the
    one in terms of the other.

diff --git a/hw/xfree86/ddc/xf86DDC.c b/hw/xfree86/ddc/xf86DDC.c
index 28e2ead..98f6006 100644
--- a/hw/xfree86/ddc/xf86DDC.c
+++ b/hw/xfree86/ddc/xf86DDC.c
@@ -2,6 +2,14 @@
  * 
  * Copyright 1998,1999 by Egbert Eich <Egbert.Eich at Physik.TU-Darmstadt.DE>
  */
+
+/*
+ * Note that DDC1 does not define any method for returning blocks beyond
+ * the first.  DDC2 does, but the original implementation would only ever
+ * read the first block.  If you want to read and parse all blocks, use
+ * xf86DoEEDID().
+ */
+
 #ifdef HAVE_XORG_CONFIG_H
 #include <xorg-config.h>
 #endif
@@ -31,11 +39,6 @@ static unsigned int *FetchEDID_DDC1(
     register unsigned int (*)(ScrnInfoPtr)
 );
 
-static unsigned char* EDID1Read_DDC2(
-    int scrnIndex, 
-    I2CBusPtr pBus
-);
-
 static unsigned char * DDCRead_DDC2(
     int scrnIndex,
     I2CBusPtr pBus, 
@@ -110,16 +113,22 @@ xf86DoEDID_DDC1(
 /**
  * Attempts to probe the monitor for EDID information, if NoDDC and NoDDC2 are
  * unset.  EDID information blocks are interpreted and the results returned in
- * an xf86MonPtr.
+ * an xf86MonPtr.  Unlike xf86DoEDID_DDC[12](), this function will return
+ * the complete EDID data, including all extension blocks.
  *
  * This function does not affect the list of modes used by drivers -- it is up
  * to the driver to decide policy on what to do with EDID information.
  *
  * @return pointer to a new xf86MonPtr containing the EDID information.
  * @return NULL if no monitor attached or failure to interpret the EDID.
+ *
+ * nblocks is an in/out parameter.  If non-zero, it defines the number of
+ * blocks to read from the monitor; zero (or NULL pointer) means read all.
+ * If non-NULL, on return it will be filled in with the number of blocks
+ * read.
  */
 xf86MonPtr
-xf86DoEDID_DDC2(int scrnIndex, I2CBusPtr pBus)
+xf86DoEEDID(int scrnIndex, I2CBusPtr pBus, int *nblocks)
 {
     ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
     unsigned char *EDID_block = NULL;
@@ -129,7 +138,7 @@ xf86DoEDID_DDC2(int scrnIndex, I2CBusPtr pBus)
     OptionInfoPtr options;
 
     options = xnfalloc(sizeof(DDCOptions));
-    (void)memcpy(options, DDCOptions, sizeof(DDCOptions));
+    memcpy(options, DDCOptions, sizeof(DDCOptions));
     xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, options);
 
     xf86GetOptValBool(options, DDCOPT_NODDC, &noddc);
@@ -139,26 +148,39 @@ xf86DoEDID_DDC2(int scrnIndex, I2CBusPtr pBus)
     if (noddc || noddc2)
 	return NULL;
 
-    EDID_block = EDID1Read_DDC2(scrnIndex,pBus);
+    EDID_block = DDCRead_DDC2(scrnIndex, pBus, 0, EDID1_LEN);
 
-    if (EDID_block){
-	tmp = xf86InterpretEDID(scrnIndex,EDID_block);
-    } else {
-#ifdef DEBUG
-	ErrorF("No EDID block returned\n");
-#endif
-	return NULL;
+    if (EDID_block)
+	tmp = xf86InterpretEDID(scrnIndex, EDID_block);
+
+    if (nblocks) {
+	if (tmp)
+	    *nblocks = tmp->no_sections;
+	else
+	    *nblocks = 0;
     }
-#ifdef DEBUG
-    if (!tmp)
-	ErrorF("Cannot interpret EDID block\n");
-    else
-        ErrorF("Sections to follow: %i\n",tmp->no_sections);
-#endif
-    
+
     return tmp;
 }
 
+/**
+ * Attempts to probe the monitor for EDID information, if NoDDC and NoDDC2 are
+ * unset.  EDID information blocks are interpreted and the results returned in
+ * an xf86MonPtr.
+ *
+ * This function does not affect the list of modes used by drivers -- it is up
+ * to the driver to decide policy on what to do with EDID information.
+ *
+ * @return pointer to a new xf86MonPtr containing the EDID information.
+ * @return NULL if no monitor attached or failure to interpret the EDID.
+ */
+xf86MonPtr
+xf86DoEDID_DDC2(int scrnIndex, I2CBusPtr pBus)
+{
+    int nblocks = 1;
+    return xf86DoEEDID(scrnIndex, pBus, &nblocks);
+}
+
 /* 
  * read EDID record , pass it to callback function to interpret.
  * callback function will store it for further use by calling
@@ -226,12 +248,6 @@ FetchEDID_DDC1(register ScrnInfoPtr pScrn,
     return (ptr);
 }
 
-static unsigned char*
-EDID1Read_DDC2(int scrnIndex, I2CBusPtr pBus)
-{
-    return  DDCRead_DDC2(scrnIndex, pBus, 0, EDID1_LEN);
-}
-
 static unsigned char *
 DDCRead_DDC2(int scrnIndex, I2CBusPtr pBus, int start, int len)
 {
diff --git a/hw/xfree86/ddc/xf86DDC.h b/hw/xfree86/ddc/xf86DDC.h
index 3b072dd..6e5bf6f 100644
--- a/hw/xfree86/ddc/xf86DDC.h
+++ b/hw/xfree86/ddc/xf86DDC.h
@@ -35,6 +35,8 @@ extern xf86MonPtr xf86DoEDID_DDC2(
    I2CBusPtr pBus
 );
 
+extern xf86MonPtr xf86DoEEDID(int scrnIndex, I2CBusPtr pBus, int *nblocks);
+
 extern xf86MonPtr xf86PrintEDID(
     xf86MonPtr monPtr
 );
commit b5f98fcea2024c67e598947782913982072cf4fb
Author: Eamon Walsh <ewalsh at tycho.nsa.gov>
Date:   Fri Mar 28 14:01:34 2008 -0400

    XSELinux: Add xorg.conf option for permissive/enforcing/disabled.
    Patch by Joe Nall.
    
    The option goes in the "extmod" subsection.
    TODO: Make it easier for extension modules to handle their own options.

diff --git a/Xext/xselinux.c b/Xext/xselinux.c
index 17ce7af..2e059a4 100644
--- a/Xext/xselinux.c
+++ b/Xext/xselinux.c
@@ -37,6 +37,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #include <libaudit.h>
 
 #include <X11/Xatom.h>
+#include "globals.h"
 #include "resource.h"
 #include "privates.h"
 #include "registry.h"
@@ -1891,16 +1892,36 @@ void
 SELinuxExtensionInit(INITARGS)
 {
     ExtensionEntry *extEntry;
-    struct selinux_opt options[] = { { SELABEL_OPT_VALIDATE, (char *)1 } };
+    struct selinux_opt selabel_option = { SELABEL_OPT_VALIDATE, (char *)1 };
+    struct selinux_opt avc_option = { AVC_OPT_SETENFORCE, (char *)0 };
     security_context_t con;
     int ret = TRUE;
 
-    /* Setup SELinux stuff */
+    /* Check SELinux mode on system */
     if (!is_selinux_enabled()) {
-	ErrorF("SELinux: SELinux not enabled, disabling SELinux support.\n");
+	ErrorF("SELinux: Disabled on system, not enabling in X server\n");
 	return;
     }
 
+    /* Check SELinux mode in configuration file */
+    switch(selinuxEnforcingState) {
+    case SELINUX_MODE_DISABLED:
+	LogMessage(X_INFO, "SELinux: Disabled in configuration file\n");
+	return;
+    case SELINUX_MODE_ENFORCING:
+	LogMessage(X_INFO, "SELinux: Configured in enforcing mode\n");
+	avc_option.value = (char *)1;
+	break;
+    case SELINUX_MODE_PERMISSIVE:
+	LogMessage(X_INFO, "SELinux: Configured in permissive mode\n");
+	avc_option.value = (char *)0;
+	break;
+    default:
+	avc_option.type = AVC_OPT_UNUSED;
+	break;
+    }
+
+    /* Set up SELinux stuff */
     selinux_set_callback(SELINUX_CB_LOG, (union selinux_callback)SELinuxLog);
     selinux_set_callback(SELINUX_CB_AUDIT, (union selinux_callback)SELinuxAudit);
 
@@ -1912,11 +1933,11 @@ SELinuxExtensionInit(INITARGS)
 	FatalError("SELinux: Failed to set up security class mapping\n");
     }
 
-    if (avc_open(NULL, 0) < 0)
+    if (avc_open(&avc_option, 1) < 0)
 	FatalError("SELinux: Couldn't initialize SELinux userspace AVC\n");
     avc_active = 1;
 
-    label_hnd = selabel_open(SELABEL_CTX_X, options, 1);
+    label_hnd = selabel_open(SELABEL_CTX_X, &selabel_option, 1);
     if (!label_hnd)
 	FatalError("SELinux: Failed to open x_contexts mapping in policy\n");
 
diff --git a/hw/xfree86/dixmods/extmod/modinit.c b/hw/xfree86/dixmods/extmod/modinit.c
index d0d892a..8c8a4ce 100644
--- a/hw/xfree86/dixmods/extmod/modinit.c
+++ b/hw/xfree86/dixmods/extmod/modinit.c
@@ -42,7 +42,7 @@ static ExtensionModule extensionModules[] = {
     {
 	SELinuxExtensionInit,
 	SELINUX_EXTENSION_NAME,
-	NULL,
+	&noSELinuxExtension,
 	NULL,
 	NULL
     },
@@ -258,6 +258,27 @@ extmodSetup(pointer module, pointer opts, int *errmaj, int *errmin)
 		}
 	    }
 	}
+
+#ifdef XSELINUX
+	if (! strcmp(SELINUX_EXTENSION_NAME, extensionModules[i].name)) {
+	    pointer o;
+	    selinuxEnforcingState = SELINUX_MODE_DEFAULT;
+
+	    if ((o = xf86FindOption(opts, "SELinux mode disabled"))) {
+		xf86MarkOptionUsed(o);
+		selinuxEnforcingState = SELINUX_MODE_DISABLED;
+	    }
+	    if ((o = xf86FindOption(opts, "SELinux mode permissive"))) {
+		xf86MarkOptionUsed(o);
+		selinuxEnforcingState = SELINUX_MODE_PERMISSIVE;
+	    }
+	    if ((o = xf86FindOption(opts, "SELinux mode enforcing"))) {
+		xf86MarkOptionUsed(o);
+		selinuxEnforcingState = SELINUX_MODE_ENFORCING;
+	    }
+	}
+#endif
+
 	LoadExtension(&extensionModules[i], FALSE);
     }
     /* Need a non-NULL return */
diff --git a/hw/xfree86/loader/dixsym.c b/hw/xfree86/loader/dixsym.c
index d035c76..d6d22c4 100644
--- a/hw/xfree86/loader/dixsym.c
+++ b/hw/xfree86/loader/dixsym.c
@@ -440,6 +440,9 @@ _X_HIDDEN void *dixLookupTab[] = {
 #ifdef XIDLE
     SYMVAR(noXIdleExtension)
 #endif
+#ifdef XSELINUX
+    SYMVAR(noSELinuxExtension)
+#endif
 #ifdef XV
     SYMVAR(noXvExtension)
 #endif
diff --git a/include/globals.h b/include/globals.h
index b230dfc..2ca9531 100644
--- a/include/globals.h
+++ b/include/globals.h
@@ -175,6 +175,16 @@ extern Bool noXInputExtension;
 extern Bool noXIdleExtension;
 #endif
 
+#ifdef XSELINUX
+extern Bool noSELinuxExtension;
+
+#define SELINUX_MODE_DEFAULT    0
+#define SELINUX_MODE_DISABLED   1
+#define SELINUX_MODE_PERMISSIVE 2
+#define SELINUX_MODE_ENFORCING  3
+extern int selinuxEnforcingState;
+#endif
+
 #ifdef XV
 extern Bool noXvExtension;
 #endif
diff --git a/mi/miinitext.c b/mi/miinitext.c
index 3c55eeb..cc4c15c 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -215,6 +215,9 @@ extern Bool noXInputExtension;
 #ifdef XIDLE
 extern Bool noXIdleExtension;
 #endif
+#ifdef XSELINUX
+extern Bool noSELinuxExtension;
+#endif
 #ifdef XV
 extern Bool noXvExtension;
 #endif
@@ -488,6 +491,9 @@ static ExtensionToggle ExtensionToggleList[] =
 #ifdef XKB
     { "XKEYBOARD", &noXkbExtension },
 #endif
+#ifdef XSELINUX
+    { "SELinux", &noSELinuxExtension },
+#endif
     { "XTEST", &noTestExtensions },
 #ifdef XV
     { "XVideo", &noXvExtension },
@@ -597,7 +603,7 @@ InitExtensions(argc, argv)
     if (!noSecurityExtension) SecurityExtensionInit();
 #endif
 #ifdef XSELINUX
-    SELinuxExtensionInit();
+    if (!noSELinuxExtension) SELinuxExtensionInit();
 #endif
 #ifdef XPRINT
     XpExtensionInit(); /* server-specific extension, cannot be disabled */
diff --git a/os/utils.c b/os/utils.c
index 4041028..57293ab 100644
--- a/os/utils.c
+++ b/os/utils.c
@@ -232,6 +232,10 @@ _X_EXPORT Bool noXInputExtension = FALSE;
 #ifdef XIDLE
 _X_EXPORT Bool noXIdleExtension = FALSE;
 #endif
+#ifdef XSELINUX
+_X_EXPORT Bool noSELinuxExtension = FALSE;
+_X_EXPORT int selinuxEnforcingState = SELINUX_MODE_DEFAULT;
+#endif
 #ifdef XV
 _X_EXPORT Bool noXvExtension = FALSE;
 #endif
commit 415e49b940bba2d08870db410ebb47d2add5d836
Author: Jeremy Huddleston <jeremyhu at freedesktop.org>
Date:   Tue Mar 25 23:01:02 2008 -0700

    XQuartz: Sanity-check the removal of the 256-color option
    Fixes the 'one-time-preferences' bug in 2.2.0_rc1
    (cherry picked from commit 38cbd13490fc21724e8eef0ec7e1a20a9cc2e39d)

diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index a9d2add..dfa2074 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -649,7 +649,8 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 
     [depth selectItemAtIndex:[depth indexOfItemWithTag:[NSApp prefs_get_integer:@PREFS_DEPTH default:-1]]];
     // TODO: Add 256 color support
-    [depth removeItemAtIndex:[depth indexOfItemWithTag:8]];
+    if([depth indexOfItemWithTag:8] != -1)
+        [depth removeItemAtIndex:[depth indexOfItemWithTag:8]];
 	
     [enable_fullscreen setIntValue:!quartzEnableRootless];
     // TODO: Add fullscreen support
commit c1d37efe9aae5f2895b3437418f7e4bb2eb3400f
Author: Ben Byer <bbyer at bushing.apple.com>
Date:   Tue Mar 25 19:25:00 2008 -0700

    xquartz: copy in new stubs from Xi/stubs.c to replace our old
    Xinput stubs.  Hey, it's a start.
    (cherry picked from commit 566412b4aece24ae6af8c7c835986b685aa456a2)

diff --git a/hw/xquartz/darwinXinput.c b/hw/xquartz/darwinXinput.c
index e62ec0a..50ba656 100644
--- a/hw/xquartz/darwinXinput.c
+++ b/hw/xquartz/darwinXinput.c
@@ -1,8 +1,7 @@
-
 /*
- * X server support of the XINPUT extension for Darwin
+ * X server support of the XINPUT extension for xquartz
  *
- * This is currently a copy of mi/stubs.c, but eventually this
+ * This is currently a copy of Xi/stubs.c, but eventually this
  * should include more complete XINPUT support.
  */
 
@@ -52,100 +51,17 @@ SOFTWARE.
 
 ********************************************************/
 
+#define	 NEED_EVENTS
 #ifdef HAVE_DIX_CONFIG_H
 #include <dix-config.h>
 #endif
 
-#define	 NEED_EVENTS
 #include <X11/X.h>
 #include <X11/Xproto.h>
 #include "inputstr.h"
 #include <X11/extensions/XI.h>
 #include <X11/extensions/XIproto.h>
 #include "XIstubs.h"
-#include "chgkbd.h"
-
-/***********************************************************************
- *
- * Caller:	ProcXChangeKeyboardDevice
- *
- * This procedure does the implementation-dependent portion of the work
- * needed to change the keyboard device.
- *
- * The X keyboard device has a FocusRec.  If the device that has been 
- * made into the new X keyboard did not have a FocusRec, 
- * ProcXChangeKeyboardDevice will allocate one for it.
- *
- * If you do not want clients to be able to focus the old X keyboard
- * device, call DeleteFocusClassDeviceStruct to free the FocusRec.
- *
- * If you support input devices with keys that you do not want to be 
- * used as the X keyboard, you need to check for them here and return 
- * a BadDevice error.
- *
- * The default implementation is to do nothing (assume you do want
- * clients to be able to focus the old X keyboard).  The commented-out
- * sample code shows what you might do if you don't want the default.
- *
- */
-
-int ChangeKeyboardDevice (DeviceIntPtr old_dev, DeviceIntPtr new_dev) {
-    /***********************************************************************
-     DeleteFocusClassDeviceStruct(old_dev);	 * defined in xchgptr.c *
-    **********************************************************************/
-    return BadMatch;
-}
-
-
-/***********************************************************************
- *
- * Caller:	ProcXChangePointerDevice
- *
- * This procedure does the implementation-dependent portion of the work
- * needed to change the pointer device.
- *
- * The X pointer device does not have a FocusRec.  If the device that
- * has been made into the new X pointer had a FocusRec, 
- * ProcXChangePointerDevice will free it.
- *
- * If you want clients to be able to focus the old pointer device that
- * has now become accessible through the input extension, you need to 
- * add a FocusRec to it here.
- *
- * The XChangePointerDevice protocol request also allows the client
- * to choose which axes of the new pointer device are used to move 
- * the X cursor in the X- and Y- directions.  If the axes are different
- * than the default ones, you need to keep track of that here.
- *
- * If you support input devices with valuators that you do not want to be 
- * used as the X pointer, you need to check for them here and return a 
- * BadDevice error.
- *
- * The default implementation is to do nothing (assume you don't want
- * clients to be able to focus the old X pointer).  The commented-out
- * sample code shows what you might do if you don't want the default.
- *
- */
-
-int
-ChangePointerDevice (
-    DeviceIntPtr	old_dev,
-    DeviceIntPtr	new_dev,
-    unsigned char	x,
-    unsigned char	y)
-    {
-    /***********************************************************************
-    InitFocusClassDeviceStruct(old_dev);	* allow focusing old ptr*
-
-    x_axis = x;					* keep track of new x-axis*
-    y_axis = y;					* keep track of new y-axis*
-    if (x_axis != 0 || y_axis != 1)
-	axes_changed = TRUE;			* remember axes have changed*
-    else
-	axes_changed = FALSE;
-    *************************************************************************/
-    return BadMatch;
-    }
 
 /***********************************************************************
  *
@@ -161,11 +77,9 @@ ChangePointerDevice (
  */
 
 void
-CloseInputDevice (d, client)
-    DeviceIntPtr d;
-    ClientPtr client;
-    {
-    }
+CloseInputDevice(DeviceIntPtr d, ClientPtr client)
+{
+}
 
 /***********************************************************************
  *
@@ -194,8 +108,8 @@ CloseInputDevice (d, client)
  */
 
 void
-AddOtherInputDevices ()
-    {
+AddOtherInputDevices(void)
+{
     /**********************************************************************
      for each uninitialized device, do something like: 
 
@@ -209,7 +123,7 @@ AddOtherInputDevices ()
     dev->inited = ((*dev->deviceProc)(dev, DEVICE_INIT) == Success);
     ************************************************************************/
 
-    }
+}
 
 /***********************************************************************
  *
@@ -234,12 +148,9 @@ AddOtherInputDevices ()
  */
 
 void
-OpenInputDevice (dev, client, status)
-    DeviceIntPtr dev;
-    ClientPtr client;
-    int *status;
-    {
-    }
+OpenInputDevice(DeviceIntPtr dev, ClientPtr client, int *status)
+{
+}
 
 /****************************************************************************
  *
@@ -254,13 +165,10 @@ OpenInputDevice (dev, client, status)
  */
 
 int
-SetDeviceMode (client, dev, mode)
-    register	ClientPtr	client;
-    DeviceIntPtr dev;
-    int		mode;
-    {
+SetDeviceMode(ClientPtr client, DeviceIntPtr dev, int mode)
+{
     return BadMatch;
-    }
+}
 
 /****************************************************************************
  *
@@ -275,15 +183,11 @@ SetDeviceMode (client, dev, mode)
  */
 
 int
-SetDeviceValuators (client, dev, valuators, first_valuator, num_valuators)
-    register	ClientPtr	client;
-    DeviceIntPtr dev;
-    int		*valuators;
-    int		first_valuator;
-    int		num_valuators;
-    {
+SetDeviceValuators(ClientPtr client, DeviceIntPtr dev,
+		   int *valuators, int first_valuator, int num_valuators)
+{
     return BadMatch;
-    }
+}
 
 /****************************************************************************
  *
@@ -294,16 +198,44 @@ SetDeviceValuators (client, dev, valuators, first_valuator, num_valuators)
  */
 
 int
-ChangeDeviceControl (client, dev, control)
-    register	ClientPtr	client;
-    DeviceIntPtr dev;
-    xDeviceCtl	*control;
-    {
-    switch (control->control)
-	{
-	case DEVICE_RESOLUTION:
-	    return (BadMatch);
-	default:
-	    return (BadMatch);
-	}
+ChangeDeviceControl(ClientPtr client, DeviceIntPtr dev,
+		    xDeviceCtl * control)
+{
+    switch (control->control) {
+    case DEVICE_RESOLUTION:
+	return (BadMatch);
+    case DEVICE_ABS_CALIB:
+    case DEVICE_ABS_AREA:
+        return (BadMatch);
+    case DEVICE_CORE:
+        return (BadMatch);
+    default:
+	return (BadMatch);
     }
+}
+
+
+/****************************************************************************
+ *
+ * Caller: configAddDevice (and others)
+ *
+ * Add a new device with the specified options.
+ *
+ */
+int
+NewInputDeviceRequest(InputOption *options, DeviceIntPtr *pdev)
+{
+    return BadValue;
+}
+
+/****************************************************************************
+ *
+ * Caller: configRemoveDevice (and others)
+ *
+ * Remove the specified device previously added.
+ *
+ */
+void
+DeleteInputDeviceRequest(DeviceIntPtr dev)
+{
+}
commit c4a616a741e15865ce0ff98781c6f1dca4d62887
Author: Ben Byer <bbyer at bushing.apple.com>
Date:   Mon Mar 24 22:43:10 2008 -0700

    prevent "fake mouse clicks" from generating spurious extra events
    (cherry picked from commit bd85a24969427e41389688663ead2d4dd41c9999)

diff --git a/hw/xquartz/darwinEvents.c b/hw/xquartz/darwinEvents.c
index 827fd81..22d8957 100644
--- a/hw/xquartz/darwinEvents.c
+++ b/hw/xquartz/darwinEvents.c
@@ -391,10 +391,12 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
       DarwinSimulateMouseClick(pointer_x, pointer_y, 2, darwinFakeMouse2Mask);
       darwinFakeMouseButtonDown = 2;
       darwinFakeMouseButtonMask = darwinFakeMouse2Mask;
+      return;
     } else if ((old_flags & darwinFakeMouse3Mask) == darwinFakeMouse3Mask) {
       DarwinSimulateMouseClick(pointer_x, pointer_y, 3, darwinFakeMouse3Mask);
       darwinFakeMouseButtonDown = 3;
       darwinFakeMouseButtonMask = darwinFakeMouse3Mask;
+      return;
     }
   }
   if (ev_type == ButtonRelease && darwinFakeButtons && darwinFakeMouseButtonDown) {
@@ -406,6 +408,7 @@ void DarwinSendPointerEvents(int ev_type, int ev_button, int pointer_x, int poin
     // Bring modifiers back up to date
     DarwinUpdateModifiers(KeyPress, darwinFakeMouseButtonMask & old_flags);
     darwinFakeMouseButtonMask = 0;
+    return;
   } 
 
   num_events = GetPointerEvents(darwinEvents, darwinPointer, ev_type, ev_button, 
commit c747030a49dd289e873e2b686cd129d840e55468
Author: Dave Airlie <airlied at redhat.com>
Date:   Thu Mar 27 15:18:39 2008 +1000

    quirk: fix LPL monitors properly.
    
    no point having a h cm fix when we really want to copy the sizes from the
    other place.
    
    RH BZ 435216

diff --git a/hw/xfree86/modes/xf86EdidModes.c b/hw/xfree86/modes/xf86EdidModes.c
index 2d1a6ab..777bb70 100644
--- a/hw/xfree86/modes/xf86EdidModes.c
+++ b/hw/xfree86/modes/xf86EdidModes.c
@@ -108,13 +108,6 @@ static Bool quirk_prefer_large_75 (int scrnIndex, xf86MonPtr DDC)
 
 static Bool quirk_detailed_h_in_cm (int scrnIndex, xf86MonPtr DDC)
 {
-    /* Bug #10304: "LGPhilipsLCD LP154W01-A5" */
-    /* Bug #12784: "LGPhilipsLCD LP154W01-TLA2" */
-    /* Red Hat #435216 "LGPhilipsLCD LP154W01-TLAE" */
-    if (memcmp (DDC->vendor.name, "LPL", 4) == 0 &&
-	(DDC->vendor.prod_id == 0 || DDC->vendor.prod_id == 0x2a00))
-	return TRUE;
-
     /* Bug #11603: Funai Electronics PM36B */
     if (memcmp (DDC->vendor.name, "FCM", 4) == 0 &&
 	DDC->vendor.prod_id == 13600)
@@ -137,7 +130,7 @@ static Bool quirk_detailed_use_maximum_size (int scrnIndex, xf86MonPtr DDC)
 {
     /* Bug #10304: LGPhilipsLCD LP154W01-A5 */
     if (memcmp (DDC->vendor.name, "LPL", 4) == 0 &&
-	DDC->vendor.prod_id == 0)
+	(DDC->vendor.prod_id == 0 || DDC->vendor.prod_id == 0x2a00))
 	return TRUE;
 
     return FALSE;
commit 9df915b84d45d39aed7557c98883b20a66da2e96
Merge: 47eb658... 333e712...
Author: Sascha Hlusiak <saschahlusiak at arcor.de>
Date:   Tue Mar 25 17:50:50 2008 +0100

    Merge branch 'master' of git+ssh://git.freedesktop.org/git/xorg/xserver

commit 333e7123dc484888d79c0f5aa3977bd72f1eb341
Author: Adam Jackson <ajax at redhat.com>
Date:   Tue Mar 25 12:48:22 2008 -0400

    Fix that last commit.
    
    I can apply patches, really.

diff --git a/dix/getevents.c b/dix/getevents.c
index 6a2f7ba..bf9331e 100644
--- a/dix/getevents.c
+++ b/dix/getevents.c
@@ -349,7 +349,7 @@ getValuatorEvents(xEvent *events, DeviceIntPtr pDev, int first_valuator,
     for (i = first_valuator; i < final_valuator; i += 6, xv++, events++) {
         xv->type = DeviceValuator;
         xv->first_valuator = i;
-        xv->num_valuators = ((num_valuators - i) > 6) ? 6 : (final_valuator - i);
+        xv->num_valuators = ((final_valuator - i) > 6) ? 6 : (final_valuator - i);
         xv->deviceid = pDev->id;
         switch (final_valuator - i) {
         case 6:
commit 47eb658e802775021e3efec109f95431cca188ca
Author: Sascha Hlusiak <saschahlusiak at arcor.de>
Date:   Tue Mar 25 17:37:25 2008 +0100

    Support to pass arbitrary options via HAL hotplugging
    
    Parse "input.x11_options" and pass every key/name pair to the driver.
    Remove check for input.capabilities, because that's part of the fdi files.
    
    Thanks to Dustin Spicuzza <dustin at virtualroadside.com> for the patch.

diff --git a/config/hal.c b/config/hal.c
index 1575422..f150646 100644
--- a/config/hal.c
+++ b/config/hal.c
@@ -38,9 +38,10 @@
 #include "config-backends.h"
 #include "os.h"
 
-#define TYPE_NONE 0
-#define TYPE_KEYS 1
-#define TYPE_POINTER 2
+
+#define LIBHAL_PROP_KEY "input.x11_options."
+#define LIBHAL_XKB_PROP_KEY "input.xkb."
+
 
 struct config_hal_info {
     DBusConnection *system_bus;
@@ -50,7 +51,8 @@ struct config_hal_info {
 static void
 remove_device(DeviceIntPtr dev)
 {
-    DebugF("[config/hal] removing device %s\n", dev->name);
+    /* this only gets called for devices that have already been added */
+    LogMessage(X_INFO, "config/hal: removing device %s\n", dev->name);
 
     /* Call PIE here so we don't try to dereference a device that's
      * already been removed. */
@@ -105,7 +107,7 @@ get_prop_string(LibHalContext *hal_ctx, const char *udi, const char *name)
     char *prop, *ret;
 
     prop = libhal_device_get_property_string(hal_ctx, udi, name, NULL);
-    DebugF("[config/hal] getting %s on %s returned %s\n", name, udi, prop);
+    LogMessageVerb(X_INFO, 10, "config/hal: getting %s on %s returned %s\n", name, udi, prop);
     if (prop) {
         ret = xstrdup(prop);
         libhal_free_string(prop);
@@ -117,6 +119,9 @@ get_prop_string(LibHalContext *hal_ctx, const char *udi, const char *name)
     return ret;
 }
 
+/* this function is no longer used... keep it here in case its needed in 
+ * the future. */
+#if 0
 static char *
 get_prop_string_array(LibHalContext *hal_ctx, const char *udi, const char *prop)
 {
@@ -150,117 +155,146 @@ get_prop_string_array(LibHalContext *hal_ctx, const char *udi, const char *prop)
 
     return ret;
 }
+#endif 
 
 static void
 device_added(LibHalContext *hal_ctx, const char *udi)
 {
-    char **props;
-    char *path = NULL, *driver = NULL, *name = NULL, *xkb_rules = NULL;
-    char *xkb_model = NULL, *xkb_layout = NULL, *xkb_variant = NULL;
-    char *xkb_options = NULL, *config_info = NULL;
+    char *path = NULL, *driver = NULL, *name = NULL, *config_info = NULL;
     InputOption *options = NULL, *tmpo = NULL;
     DeviceIntPtr dev;
     DBusError error;
-    int type = TYPE_NONE;
-    int i;
-
+	
+    LibHalPropertySet *set = NULL;
+	LibHalPropertySetIterator set_iter;
+    char *psi_key = NULL, *tmp_val, *tmp_key;
+    
+    
     dbus_error_init(&error);
 
-    props = libhal_device_get_property_strlist(hal_ctx, udi,
-                                               "info.capabilities", &error);
-    if (!props) {
-        DebugF("[config/hal] couldn't get capabilities for %s: %s (%s)\n",
-               udi, error.name, error.message);
-        goto out_error;
-    }
-    for (i = 0; props[i]; i++) {
-        /* input.keys is the new, of which input.keyboard is a subset, but
-         * input.keyboard is the old 'we have keys', so we have to keep it
-         * around. */
-        if (strcmp(props[i], "input.keys") == 0 ||
-            strcmp(props[i], "input.keyboard") == 0)
-            type |= TYPE_KEYS;
-        if (strcmp(props[i], "input.mouse") == 0 ||
-            strcmp(props[i], "input.touchpad") == 0)
-            type |= TYPE_POINTER;
-    }
-    libhal_free_string_array(props);
-
-    if (type == TYPE_NONE)
-        goto out_error;
-
     driver = get_prop_string(hal_ctx, udi, "input.x11_driver");
+    if (!driver){
+        /* verbose, don't tell the user unless they _want_ to see it */
+        LogMessageVerb(X_INFO,7,"config/hal: no driver specified for device %s\n", udi);
+        goto unwind;
+    }
+    
     path = get_prop_string(hal_ctx, udi, "input.device");
-    if (!driver || !path) {
-        DebugF("[config/hal] no driver or path specified for %s\n", udi);
+    if (!path) {
+        LogMessage(X_WARNING,"config/hal: no driver or path specified for %s\n", udi);
         goto unwind;
     }
+    
     name = get_prop_string(hal_ctx, udi, "info.product");
     if (!name)
         name = xstrdup("(unnamed)");
 
-    if (type & TYPE_KEYS) {
-        xkb_rules = get_prop_string(hal_ctx, udi, "input.xkb.rules");
-        xkb_model = get_prop_string(hal_ctx, udi, "input.xkb.model");
-        xkb_layout = get_prop_string(hal_ctx, udi, "input.xkb.layout");
-        xkb_variant = get_prop_string(hal_ctx, udi, "input.xkb.variant");
-        xkb_options = get_prop_string_array(hal_ctx, udi, "input.xkb.options");
-    }
-
     options = xcalloc(sizeof(*options), 1);
+    if (!options){
+        LogMessage(X_ERROR, "config/hal: couldn't allocate space for input options!\n");
+        goto unwind;
+    }
+    
     options->key = xstrdup("_source");
     options->value = xstrdup("server/hal");
     if (!options->key || !options->value) {
-        ErrorF("[config] couldn't allocate first key/value pair\n");
+        LogMessage(X_ERROR, "config/hal: couldn't allocate first key/value pair\n");
         goto unwind;
     }
 
+    /* most drivers use device.. not path. evdev uses both however, but the 
+     * path version isn't documented apparently. support both for now. */
     add_option(&options, "path", path);
+    add_option(&options, "device", path);
+    
     add_option(&options, "driver", driver);
     add_option(&options, "name", name);
+    
     config_info = xalloc(strlen(udi) + 5); /* "hal:" and NULL */
-    if (!config_info)
+    if (!config_info) {
+        LogMessage(X_ERROR, "config/hal: couldn't allocate name\n");
         goto unwind;
+    }
     sprintf(config_info, "hal:%s", udi);
 
-    if (xkb_rules)
-        add_option(&options, "xkb_rules", xkb_rules);
-    if (xkb_model)
-        add_option(&options, "xkb_model", xkb_model);
-    if (xkb_layout)
-        add_option(&options, "xkb_layout", xkb_layout);
-    if (xkb_variant)
-        add_option(&options, "xkb_variant", xkb_variant);
-    if (xkb_options)
-        add_option(&options, "xkb_options", xkb_options);
-
-    DebugF("[config/hal] Adding device %s\n", name);
+    /* ok, grab options from hal.. iterate through all properties
+    * and lets see if any of them are options that we can add */
+    set = libhal_device_get_all_properties(hal_ctx, udi, &error);
+    
+    if (!set) {
+        LogMessage(X_ERROR, "config/hal: couldn't get property list for %s: %s (%s)\n",
+               udi, error.name, error.message);
+        goto unwind;
+    }
+	
+    libhal_psi_init(&set_iter,set);
+    while (libhal_psi_has_more(&set_iter)) {
+        /* we are looking for supported keys.. extract and add to options */
+        psi_key = libhal_psi_get_key(&set_iter);    
+        
+        if (psi_key){
+
+            /* normal options first (input.x11_options.<propname>) */
+            if (!strncasecmp(psi_key, LIBHAL_PROP_KEY, sizeof(LIBHAL_PROP_KEY)-1)){
+                
+                /* only support strings for all values */
+                tmp_val = get_prop_string(hal_ctx, udi, psi_key);
+                
+                if (tmp_val){
+                    add_option(&options, psi_key + sizeof(LIBHAL_PROP_KEY)-1, tmp_val);
+                    xfree(tmp_val);
+                }
+            
+            /* evdev's XKB options... we should probably depreciate this usage */
+            } else if (!strncasecmp(psi_key, LIBHAL_XKB_PROP_KEY, sizeof(LIBHAL_XKB_PROP_KEY)-1)){
+                
+                /* only support strings for all values */
+                tmp_val = get_prop_string(hal_ctx, udi, psi_key);
+                
+                if (tmp_val){
+                    /* add "xkb_" + NULL */
+		    tmp_key = xalloc(strlen(psi_key) - ( sizeof(LIBHAL_XKB_PROP_KEY) - 1) + 5);
+                    
+                    if (!tmp_key){
+                        LogMessage(X_ERROR, "config/hal: couldn't allocate memory for option %s\n", psi_key);
+                    } else {
+                        sprintf(tmp_key, "xkb_%s", psi_key + sizeof(LIBHAL_XKB_PROP_KEY)-1);
+                        add_option(&options, tmp_key, tmp_val);
+                        
+                        xfree(tmp_key);
+                    }
+                    xfree(tmp_val);
+                }   
+            }
+        }
+        
+        /* psi_key doesn't need to be freed */
+        libhal_psi_next(&set_iter);
+    }
+	
+    /* this isn't an error, but how else do you output something that the user can see? */
+    LogMessage(X_INFO, "config/hal: Adding input device %s\n", name);
     if (NewInputDeviceRequest(options, &dev) != Success) {
-        ErrorF("[config/hal] NewInputDeviceRequest failed\n");
+        LogMessage(X_ERROR, "config/hal: NewInputDeviceRequest failed\n");
         dev = NULL;
         goto unwind;
     }
 
-    for (; dev; dev = dev->next)
+    for (; dev; dev = dev->next){
+        if (dev->config_info)
+            xfree(dev->config_info);
         dev->config_info = xstrdup(config_info);
+    }
 
 unwind:
+    if (set)
+        libhal_free_property_set(set);
     if (path)
         xfree(path);
     if (driver)
         xfree(driver);
     if (name)
         xfree(name);
-    if (xkb_rules)
-        xfree(xkb_rules);
-    if (xkb_model)
-        xfree(xkb_model);
-    if (xkb_layout)
-        xfree(xkb_layout);
-    if (xkb_variant)
-        xfree(xkb_variant);
-    if (xkb_options)
-        xfree(xkb_options);
     if (config_info)
         xfree(config_info);
     while (!dev && (tmpo = options)) {
@@ -270,7 +304,6 @@ unwind:
         xfree(tmpo);
     }
 
-out_error:
     dbus_error_free(&error);
 
     return;
@@ -286,7 +319,7 @@ disconnect_hook(void *data)
         if (dbus_connection_get_is_connected(info->system_bus)) {
             dbus_error_init(&error);
             if (!libhal_ctx_shutdown(info->hal_ctx, &error))
-                DebugF("[config/hal] couldn't shut down context: %s (%s)\n",
+                LogMessage(X_WARNING, "config/hal: disconnect_hook couldn't shut down context: %s (%s)\n",
                         error.name, error.message);
             dbus_error_free(&error);
         }
@@ -312,21 +345,21 @@ connect_hook(DBusConnection *connection, void *data)
     if (!info->hal_ctx)
         info->hal_ctx = libhal_ctx_new();
     if (!info->hal_ctx) {
-        ErrorF("[config/hal] couldn't create HAL context\n");
+        LogMessage(X_ERROR, "config/hal: couldn't create HAL context\n");
         goto out_err;
     }
 
     if (!libhal_ctx_set_dbus_connection(info->hal_ctx, info->system_bus)) {
-        ErrorF("[config/hal] couldn't associate HAL context with bus\n");
+        LogMessage(X_ERROR, "config/hal: couldn't associate HAL context with bus\n");
         goto out_ctx;
     }
     if (!libhal_ctx_init(info->hal_ctx, &error)) {
-        ErrorF("[config/hal] couldn't initialise context: %s (%s)\n",
+        LogMessage(X_ERROR, "config/hal: couldn't initialise context: %s (%s)\n",
                error.name, error.message);
         goto out_ctx;
     }
     if (!libhal_device_property_watch_all(info->hal_ctx, &error)) {
-        ErrorF("[config/hal] couldn't watch all properties: %s (%s)\n",
+        LogMessage(X_ERROR, "config/hal: couldn't watch all properties: %s (%s)\n",
                error.name, error.message);
         goto out_ctx2;
     }
@@ -346,7 +379,7 @@ connect_hook(DBusConnection *connection, void *data)
 
 out_ctx2:
     if (!libhal_ctx_shutdown(info->hal_ctx, &error))
-        DebugF("[config/hal] couldn't shut down context: %s (%s)\n",
+        LogMessage(X_WARNING, "config/hal: couldn't shut down context: %s (%s)\n",
                error.name, error.message);
 out_ctx:
     libhal_ctx_free(info->hal_ctx);
@@ -374,10 +407,13 @@ config_hal_init(void)
     hal_info.hal_ctx = NULL;
 
     if (!config_dbus_core_add_hook(&hook)) {
-        ErrorF("[config/hal] failed to add D-Bus hook\n");
+        LogMessage(X_ERROR, "config/hal: failed to add D-Bus hook\n");
         return 0;
     }
 
+    /* verbose message */
+    LogMessageVerb(X_INFO,7,"config/hal: initialized");
+    
     return 1;
 }
 
diff --git a/config/x11-input.fdi b/config/x11-input.fdi
index c390706..f2e2d50 100644
--- a/config/x11-input.fdi
+++ b/config/x11-input.fdi
@@ -1,7 +1,57 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <deviceinfo version="0.2">
   <device>
-    <!-- FIXME: Support tablets too. -->
+  
+    <!-- The way this works: 
+    
+    Match against some input device (see the HAL specification for more 
+    information), and then merge in keys, which you can use to specify 
+    the configuration similar to the way you would in xorg.conf. You will 
+    need to restart HAL after making changes. If you are having issues,
+    starting X with the -logverbose 7 flag may yield useful information.
+    
+    Keys Supported:
+    
+        Key "input.x11_driver" (string)
+            This specifies the driver to use. You MUST specify this option,
+            or a driver will not be loaded and the rest will be ignored by
+            Xorg
+            
+        Key "input.x11_options.<option name>" (string)
+            This allows you to specify arbitrary options to pass to the driver.
+            Anything you would normally specify in xorg.conf goes here. So, for
+            option "Mode" in xorg.conf, you would specify the key name of
+            "input.x11_options.Mode". 
+
+	    Do not specify "input.x11_options.Device" since "input.device"
+	    will be used automatically.
+
+        Legacy Keys
+	     "input.xkb.rules"
+             "input.xkb.model"
+             "input.xkb.layout"
+             "input.xkb.variant"
+             "input.xkb.options"
+             
+            These keys are deprecated. Use these instead:
+	     "input.x11_options.XkbRules"
+	     "input.x11_options.XkbModel"
+	     "input.x11_options.XkbLayout"
+	     "input.x11_options.XkbVariant"
+	     "input.x11_options.XkbOptions"
+
+	    See the evdev documentation for more information. 
+    
+    You will probably want to add the following option to the ServerFlags of 
+    your xorg.conf:
+    
+        Option "AllowEmptyInput" "True"
+        
+    FIXME: Support tablets too. 
+    TODO: I think its fixed, can't test
+    
+    -->
+    
     <match key="info.capabilities" contains="input.mouse">
       <merge key="input.x11_driver" type="string">mouse</merge>
       <match key="/org/freedesktop/Hal/devices/computer:system.kernel.name"
@@ -11,21 +61,21 @@
     </match>
 
     <match key="info.capabilities" contains="input.keys">
-      <merge key="input.xkb.rules" type="string">base</merge>
+      <merge key="input.x11_options.XkbRules" type="string">base</merge>
 
       <!-- If we're using Linux, we use evdev by default (falling back to
            keyboard otherwise). -->
       <merge key="input.x11_driver" type="string">keyboard</merge>
-      <merge key="input.xkb.model" type="string">pc105</merge>
+      <merge key="input.x11_options.XkbModel" type="string">pc105</merge>
       <match key="/org/freedesktop/Hal/devices/computer:system.kernel.name"
              string="Linux">
         <merge key="input.x11_driver" type="string">evdev</merge>
-        <merge key="input.xkb.model" type="string">evdev</merge>
+        <merge key="input.x11_options.XkbModel" type="string">evdev</merge>
       </match>
 
-      <merge key="input.xkb.layout" type="string">us</merge>
+      <merge key="input.x11_options.XkbLayout" type="string">us</merge>
 
-      <merge key="input.xkb.variant" type="string" />
+      <merge key="input.x11_options.XkbVariant" type="string" />
     </match>
   </device>
 </deviceinfo>
diff --git a/configure.ac b/configure.ac
index 3b00705..959f0ae 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1009,6 +1009,8 @@ XKB_STUB_LIB='$(top_builddir)/xkb/libxkbstubs.la'
 
 AC_CHECK_FUNC(strcasecmp, [], AC_DEFINE([NEED_STRCASECMP], 1,
                                         [Do not have 'strcasecmp'.]))
+AC_CHECK_FUNC(strncasecmp, [], AC_DEFINE([NEED_STRNCASECMP], 1,
+                                        [Do not have 'strncasecmp'.]))
 
 if test "x$NULL_ROOT_CURSOR" = xyes; then
         AC_DEFINE(NULL_ROOT_CURSOR, 1, [Use an empty root cursor])
commit e7a364425547103a98acabfc67d16e1ae0c2967f
Author: Sascha Hlusiak <saschahlusiak at arcor.de>
Date:   Tue Mar 25 12:32:33 2008 -0400

    Fix getValuatorEvents to compute number of valuators correctly.

diff --git a/dix/getevents.c b/dix/getevents.c
index 3e6fe5a..6a2f7ba 100644
--- a/dix/getevents.c
+++ b/dix/getevents.c
@@ -349,7 +349,7 @@ getValuatorEvents(xEvent *events, DeviceIntPtr pDev, int first_valuator,
     for (i = first_valuator; i < final_valuator; i += 6, xv++, events++) {
         xv->type = DeviceValuator;
         xv->first_valuator = i;
-        xv->num_valuators = ((num_valuators - i) > 6) ? 6 : (num_valuators - i);
+        xv->num_valuators = ((num_valuators - i) > 6) ? 6 : (final_valuator - i);
         xv->deviceid = pDev->id;
         switch (final_valuator - i) {
         case 6:
commit f028e245a7932362656701c08fcfbfa8e8949077
Author: David Nusinow <dnusinow at debian.org>
Date:   Thu Feb 28 19:45:21 2008 -0500

    Bug #10016: Implement WM_CLASS hints in Xephyr.

diff --git a/hw/kdrive/ephyr/ephyr.h b/hw/kdrive/ephyr/ephyr.h
index 8ed7e23..5d58a21 100644
--- a/hw/kdrive/ephyr/ephyr.h
+++ b/hw/kdrive/ephyr/ephyr.h
@@ -28,6 +28,7 @@
 #include <stdio.h>
 #include <unistd.h>
 #include <signal.h>
+#include <libgen.h>
 
 #include "os.h"  		/* for OsSignal() */
 #include "kdrive.h"
diff --git a/hw/kdrive/ephyr/ephyrinit.c b/hw/kdrive/ephyr/ephyrinit.c
index 6196996..47ddb3d 100644
--- a/hw/kdrive/ephyr/ephyrinit.c
+++ b/hw/kdrive/ephyr/ephyrinit.c
@@ -109,6 +109,7 @@ ddxUseMsg (void)
   ErrorF("-nodri               do not use DRI\n");
 #endif
   ErrorF("-noxv                do not use XV\n");
+  ErrorF("-name [name]         define the name in the WM_CLASS property\n");
   ErrorF("\n");
 
   exit(1);
@@ -148,6 +149,11 @@ ddxProcessArgument (int argc, char **argv, int i)
 {
   EPHYR_DBG("mark argv[%d]='%s'", i, argv[i] );
 
+  if (i == 1)
+    {
+      hostx_use_resname(basename(argv[0]), 0);
+    }
+
   if (!strcmp (argv[i], "-parent"))
     {
       if(i+1 < argc)
@@ -223,6 +229,19 @@ ddxProcessArgument (int argc, char **argv, int i)
        EPHYR_LOG ("no XVideo enabled\n") ;
        return 1 ;
    }
+  else if (!strcmp (argv[i], "-name"))
+   {
+       if (i+1 < argc && argv[i+1][0] != '-')
+         {
+           hostx_use_resname(argv[i+1], 1);
+           return 2;
+         }
+       else
+         {
+           UseMsg();
+           return 0;
+         }
+   }
   else if (argv[i][0] == ':')
     {
       hostx_set_display_name(argv[i]);
diff --git a/hw/kdrive/ephyr/hostx.c b/hw/kdrive/ephyr/hostx.c
index fd84ec0..1a71d06 100644
--- a/hw/kdrive/ephyr/hostx.c
+++ b/hw/kdrive/ephyr/hostx.c
@@ -107,6 +107,9 @@ extern EphyrKeySyms   ephyrKeySyms;
 
 extern int            monitorResolution;
 
+char           *ephyrResName = NULL;
+int             ephyrResNameFromCmd = 0;
+
 static void
 hostx_set_fullscreen_hint(void);
 
@@ -296,6 +299,13 @@ hostx_handle_signal (int signum)
               HostXWantDamageDebug);
 }
 
+void
+hostx_use_resname (char *name, int fromcmd)
+{
+  ephyrResName = name;
+  ephyrResNameFromCmd = fromcmd;
+}
+
 int
 hostx_init (void)
 {
@@ -304,6 +314,8 @@ hostx_init (void)
   Pixmap                cursor_pxm;
   XColor                col;
   int                   index;
+  char                  *tmpstr;
+  XClassHint            *class_hint;
 
   attr.event_mask =
     ButtonPressMask
@@ -327,6 +339,8 @@ hostx_init (void)
   HostX.depth   = DefaultDepth(HostX.dpy, HostX.screen);
   HostX.visual  = DefaultVisual(HostX.dpy, HostX.screen);
 
+  class_hint = XAllocClassHint();
+
   for (index = 0 ; index < HostX.n_screens ; index++)
     {
       struct EphyrHostScreen *host_screen = &HostX.screens[index];
@@ -389,9 +403,23 @@ hostx_init (void)
 
               hostx_set_fullscreen_hint();
             }
+
+          if (class_hint) 
+            {
+              tmpstr = getenv("RESOURCE_NAME");
+              if (tmpstr && (!ephyrResNameFromCmd))
+                ephyrResName = tmpstr;
+              class_hint->res_name = ephyrResName;
+              class_hint->res_class = "Xephyr";
+              XSetClassHint(hostx_get_display(), host_screen->win, class_hint);
+
+            }
+
         }
     }
 
+  if (class_hint)
+      XFree(class_hint);
 
   XParseColor (HostX.dpy, DefaultColormap (HostX.dpy,HostX.screen),
                "red", &col);
diff --git a/hw/kdrive/ephyr/hostx.h b/hw/kdrive/ephyr/hostx.h
index 48d3147..47ba61b 100644
--- a/hw/kdrive/ephyr/hostx.h
+++ b/hw/kdrive/ephyr/hostx.h
@@ -145,6 +145,9 @@ hostx_want_preexisting_window(EphyrScreenInfo screen);
 void
 hostx_use_preexisting_window(unsigned long win_id);
 
+void
+hostx_use_resname (char *name, int fromcmd);
+
 void 
 hostx_handle_signal(int signum);
 
commit 862ff9ac92037e13629329eb6ba50ff6bd2c5f71
Author: Adam Jackson <ajax at redhat.com>
Date:   Mon Mar 24 13:37:42 2008 -0400

    Bug #11510: Fix build without RECORD.

diff --git a/Makefile.am b/Makefile.am
index e382d58..71ba2c4 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -30,6 +30,10 @@ if DBE
 DBE_DIR=dbe
 endif
 
+if RECORD
+RECORD_DIR=record
+endif
+
 SUBDIRS = \
 	doc \
 	include \
@@ -48,7 +52,7 @@ SUBDIRS = \
 	$(AFB_DIR) \
 	$(CFB_DIR) \
 	$(CFB32_DIR) \
-	record \
+	$(RECORD_DIR) \
 	xfixes \
 	damageext \
 	$(XTRAP_DIR) \
diff --git a/hw/xfree86/dixmods/Makefile.am b/hw/xfree86/dixmods/Makefile.am
index efc5f4a..dad2dd3 100644
--- a/hw/xfree86/dixmods/Makefile.am
+++ b/hw/xfree86/dixmods/Makefile.am
@@ -26,6 +26,10 @@ if MFB
 MFBMOD = libmfb.la
 endif
 
+if RECORD
+RECORDMOD = librecord.la
+endif
+
 module_LTLIBRARIES = $(AFBMOD) \
                      $(CFBMOD) \
                      libfb.la \
@@ -34,7 +38,7 @@ module_LTLIBRARIES = $(AFBMOD) \
                      libshadow.la
 
 extsmoduledir = $(moduledir)/extensions
-extsmodule_LTLIBRARIES = librecord.la \
+extsmodule_LTLIBRARIES = $(RECORDMOD) \
 			 $(DBEMOD) \
                          $(GLXMODS) \
                          $(XTRAPMOD)
commit 87bfd3bd96c714a1c252d42408b5a1a4ff9dab06
Author: Adam Jackson <ajax at redhat.com>
Date:   Mon Mar 24 13:33:38 2008 -0400

    Bug #11508: Fix build without XV.

diff --git a/hw/xfree86/loader/xf86sym.c b/hw/xfree86/loader/xf86sym.c
index f86a143..24fc44c 100644
--- a/hw/xfree86/loader/xf86sym.c
+++ b/hw/xfree86/loader/xf86sym.c
@@ -68,8 +68,10 @@
 # include "xf86Xinput.h"
 #endif
 #include "xf86OSmouse.h"
+#ifdef XV
 #include "xf86xv.h"
 #include "xf86xvmc.h"
+#endif
 #include "xf86cmap.h"
 #include "xf86fbman.h"
 #include "dgaproc.h"
commit 536f2ff5382aaaace3b55481e15366bb15d87801
Author: Adam Jackson <ajax at redhat.com>
Date:   Mon Mar 24 12:22:19 2008 -0400

    Bug #13962: Re-arm the DPMS timer when re-enabling DPMS.

diff --git a/Xext/dpms.c b/Xext/dpms.c
index 6f01fa3..e3204fe 100644
--- a/Xext/dpms.c
+++ b/Xext/dpms.c
@@ -188,12 +188,15 @@ static int
 ProcDPMSEnable(client)
     register ClientPtr client;
 {
-    /* REQUEST(xDPMSEnableReq); */
+    Bool was_enabled = DPMSEnabled;
 
     REQUEST_SIZE_MATCH(xDPMSEnableReq);
 
-    if (DPMSCapableFlag)
+    if (DPMSCapableFlag) {
 	DPMSEnabled = TRUE;
+	if (!was_enabled)
+	    SetScreenSaverTimer();
+    }
 
     return(client->noClientException);
 }
commit 4217ba0cf0c9bbea3774760e836ab372acf3237c
Author: Julien Cristau <jcristau at debian.org>
Date:   Sat Mar 22 17:31:08 2008 +0100

    xaa: use xf86ReturnOptValBool instead of xf86IsOptionSet
    
    The latter doesn't return the option's value, just whether it's present
    in the configuration.

diff --git a/hw/xfree86/xaa/xaaInitAccel.c b/hw/xfree86/xaa/xaaInitAccel.c
index 1b7c154..53795f0 100644
--- a/hw/xfree86/xaa/xaaInitAccel.c
+++ b/hw/xfree86/xaa/xaaInitAccel.c
@@ -181,7 +181,7 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
 
     if(infoRec->SetupForScreenToScreenCopy &&
        infoRec->SubsequentScreenToScreenCopy &&
-       !xf86IsOptionSet(options, XAAOPT_SCREEN_TO_SCREEN_COPY)) {
+       !xf86ReturnOptValBool(options, XAAOPT_SCREEN_TO_SCREEN_COPY, FALSE)) {
 	HaveScreenToScreenCopy = TRUE;
     } else {
 	infoRec->ScreenToScreenCopyFlags = 0;
@@ -192,10 +192,10 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
     /**** Solid Filled Rects ****/
 
     if(infoRec->SetupForSolidFill && infoRec->SubsequentSolidFillRect &&
-       !xf86IsOptionSet(options, XAAOPT_SOLID_FILL_RECT)) {
+       !xf86ReturnOptValBool(options, XAAOPT_SOLID_FILL_RECT, FALSE)) {
 		HaveSolidFillRect = TRUE;
 	if(infoRec->SubsequentSolidFillTrap &&
-	   !xf86IsOptionSet(options, XAAOPT_SOLID_FILL_TRAP))
+	   !xf86ReturnOptValBool(options, XAAOPT_SOLID_FILL_TRAP, FALSE))
 		HaveSolidFillTrap = TRUE;
 	else
 		infoRec->SubsequentSolidFillTrap = NULL;
@@ -210,10 +210,11 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
 
     if(infoRec->SetupForSolidLine) {
 	if(infoRec->SubsequentSolidTwoPointLine &&
-		!xf86IsOptionSet(options, XAAOPT_SOLID_TWO_POINT_LINE))
+		!xf86ReturnOptValBool(options,
+		                      XAAOPT_SOLID_TWO_POINT_LINE, FALSE))
 	    HaveSolidTwoPointLine = TRUE;
 	if(infoRec->SubsequentSolidBresenhamLine &&
-		!xf86IsOptionSet(options, XAAOPT_SOLID_BRESENHAM_LINE)) {
+		!xf86ReturnOptValBool(options, XAAOPT_SOLID_BRESENHAM_LINE, FALSE)) {
 	    HaveSolidBresenhamLine = TRUE;
 
 	    if(infoRec->SolidBresenhamLineErrorTermBits)
@@ -222,7 +223,8 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
 	}
 
 	if(infoRec->SubsequentSolidHorVertLine &&
-		!xf86IsOptionSet(options, XAAOPT_SOLID_HORVERT_LINE))
+		!xf86ReturnOptValBool(options,
+		                      XAAOPT_SOLID_HORVERT_LINE, FALSE))
 	    HaveSolidHorVertLine = TRUE;
 	else if(HaveSolidTwoPointLine) {
 	    infoRec->SubsequentSolidHorVertLine = 
@@ -265,10 +267,14 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
 
    if(infoRec->SetupForMono8x8PatternFill &&
 		infoRec->SubsequentMono8x8PatternFillRect &&
-		!xf86IsOptionSet(options, XAAOPT_MONO_8x8_PATTERN_FILL_RECT)) {
+		!xf86ReturnOptValBool(options,
+		                      XAAOPT_MONO_8x8_PATTERN_FILL_RECT,
+		                      FALSE)) {
 	HaveMono8x8PatternFillRect = TRUE;
 	if(infoRec->SubsequentMono8x8PatternFillTrap &&
-		!xf86IsOptionSet(options, XAAOPT_MONO_8x8_PATTERN_FILL_TRAP))
+		!xf86ReturnOptValBool(options,
+		                      XAAOPT_MONO_8x8_PATTERN_FILL_TRAP,
+		                      FALSE))
 		HaveMono8x8PatternFillTrap = TRUE;
 
         if(infoRec->Mono8x8PatternFillFlags & 
@@ -318,10 +324,12 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
 
     if(infoRec->SetupForDashedLine && infoRec->DashPatternMaxLength) {
 	if(infoRec->SubsequentDashedTwoPointLine &&
-		!xf86IsOptionSet(options, XAAOPT_DASHED_TWO_POINT_LINE))
+		!xf86ReturnOptValBool(options, XAAOPT_DASHED_TWO_POINT_LINE,
+		                      FALSE))
 	    HaveDashedTwoPointLine = TRUE;
 	if(infoRec->SubsequentDashedBresenhamLine &&
-		!xf86IsOptionSet(options, XAAOPT_DASHED_BRESENHAM_LINE)) {
+		!xf86ReturnOptValBool(options, XAAOPT_DASHED_BRESENHAM_LINE,
+		                      FALSE)) {
 	    HaveDashedBresenhamLine = TRUE;
 
 	    if(infoRec->DashedBresenhamLineErrorTermBits)
@@ -345,10 +353,11 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
 
    if(infoRec->SetupForColor8x8PatternFill &&
       infoRec->SubsequentColor8x8PatternFillRect &&
-      !xf86IsOptionSet(options, XAAOPT_COL_8x8_PATTERN_FILL_RECT)) {
+      !xf86ReturnOptValBool(options, XAAOPT_COL_8x8_PATTERN_FILL_RECT, FALSE)) {
 	HaveColor8x8PatternFillRect = TRUE;
 	if(infoRec->SubsequentColor8x8PatternFillTrap &&
-	   !xf86IsOptionSet(options, XAAOPT_COL_8x8_PATTERN_FILL_TRAP))
+	   !xf86ReturnOptValBool(options, XAAOPT_COL_8x8_PATTERN_FILL_TRAP,
+	                         FALSE))
 		HaveColor8x8PatternFillTrap = TRUE;
 	else
 		infoRec->SubsequentColor8x8PatternFillTrap = NULL;
@@ -381,7 +390,8 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
     if(infoRec->SetupForCPUToScreenColorExpandFill && 
 	infoRec->ColorExpandBase &&
        	infoRec->SubsequentCPUToScreenColorExpandFill &&
-        !xf86IsOptionSet(options, XAAOPT_CPU_TO_SCREEN_COL_EXP_FILL)) {
+        !xf86ReturnOptValBool(options, XAAOPT_CPU_TO_SCREEN_COL_EXP_FILL,
+	                      FALSE)) {
 	int dwordsNeeded = pScrn->virtualX;
 
 	infoRec->ColorExpandRange >>= 2;	/* convert to DWORDS */
@@ -406,7 +416,9 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
        infoRec->SubsequentColorExpandScanline &&
        infoRec->ScanlineColorExpandBuffers && 
        (infoRec->NumScanlineColorExpandBuffers > 0) &&
-       !xf86IsOptionSet(options, XAAOPT_SCANLINE_CPU_TO_SCREEN_COL_EXP_FILL)) {
+       !xf86ReturnOptValBool(options,
+                             XAAOPT_SCANLINE_CPU_TO_SCREEN_COL_EXP_FILL,
+                             FALSE)) {
 	HaveScanlineColorExpansion = TRUE;
     } else {
 	infoRec->ScanlineCPUToScreenColorExpandFillFlags = 0;
@@ -419,7 +431,8 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
 
     if(infoRec->SetupForScreenToScreenColorExpandFill &&
        infoRec->SubsequentScreenToScreenColorExpandFill &&
-       !xf86IsOptionSet(options, XAAOPT_SCREEN_TO_SCREEN_COL_EXP_FILL)) {
+       !xf86ReturnOptValBool(options, XAAOPT_SCREEN_TO_SCREEN_COL_EXP_FILL,
+                             FALSE)) {
 	HaveScreenToScreenColorExpandFill = TRUE;
 	if (!infoRec->CacheColorExpandDensity)
 	    infoRec->CacheColorExpandDensity = 1;
@@ -433,7 +446,7 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
 
     if(infoRec->SetupForImageWrite && infoRec->ImageWriteBase &&
        infoRec->SubsequentImageWriteRect &&
-       !xf86IsOptionSet(options, XAAOPT_IMAGE_WRITE_RECT)) {
+       !xf86ReturnOptValBool(options, XAAOPT_IMAGE_WRITE_RECT, FALSE)) {
 
 	infoRec->ImageWriteRange >>= 2;	/* convert to DWORDS */
 	if(infoRec->ImageWriteFlags & CPU_TRANSFER_BASE_FIXED)
@@ -452,7 +465,8 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
        infoRec->SubsequentImageWriteScanline &&
        infoRec->ScanlineImageWriteBuffers && 
        (infoRec->NumScanlineImageWriteBuffers > 0) &&
-       !xf86IsOptionSet(options, XAAOPT_SCANLINE_IMAGE_WRITE_RECT)) {
+       !xf86ReturnOptValBool(options, XAAOPT_SCANLINE_IMAGE_WRITE_RECT,
+                             FALSE)) {
 	HaveScanlineImageWriteRect = TRUE;
     } else {
 	infoRec->ScanlineImageWriteFlags = 0;
@@ -518,7 +532,8 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
 #define XAAMSG(s) do { if (serverGeneration == 1) xf86ErrorF(s); } while (0)
 
     if((infoRec->Flags & OFFSCREEN_PIXMAPS) && HaveScreenToScreenCopy &&
-		!xf86IsOptionSet(options, XAAOPT_OFFSCREEN_PIXMAPS)) {
+		!xf86ReturnOptValBool(options, XAAOPT_OFFSCREEN_PIXMAPS,
+		                      FALSE)) {
 	XAAMSG("\tOffscreen Pixmaps\n");
     } else {
 	infoRec->Flags &= ~OFFSCREEN_PIXMAPS;
@@ -800,7 +815,7 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
     /**** WriteBitmap ****/
 
     if(infoRec->WriteBitmap && 
-      !xf86IsOptionSet(options, XAAOPT_WRITE_BITMAP)) {
+      !xf86ReturnOptValBool(options, XAAOPT_WRITE_BITMAP, FALSE)) {
 	XAAMSG("\tDriver provided WriteBitmap replacement\n");
     } else if(HaveColorExpansion) {
 	if (infoRec->CPUToScreenColorExpandFillFlags & TRIPLE_BITS_24BPP) {
@@ -959,7 +974,7 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
     /**** WritePixmap ****/
 
     if(infoRec->WritePixmap &&
-      !xf86IsOptionSet(options, XAAOPT_WRITE_PIXMAP)) {
+      !xf86ReturnOptValBool(options, XAAOPT_WRITE_PIXMAP, FALSE)) {
 	XAAMSG("\tDriver provided WritePixmap replacement\n");
     } else if(HaveImageWriteRect) {
 	infoRec->WritePixmap = XAAWritePixmap;
@@ -1433,7 +1448,7 @@ XAAInitAccel(ScreenPtr pScreen, XAAInfoRecPtr infoRec)
     else
 	infoRec->Flags &= ~PIXMAP_CACHE;
 
-    if (xf86IsOptionSet(options, XAAOPT_PIXMAP_CACHE))
+    if (xf86ReturnOptValBool(options, XAAOPT_PIXMAP_CACHE, FALSE))
 	infoRec->Flags &= ~PIXMAP_CACHE;
 
     if(infoRec->WriteMono8x8PatternToCache) {}
commit 6b9d2bb1f7f87acbf275027af9c2982e91e5faed
Author: Julien Cristau <jcristau at debian.org>
Date:   Sat Mar 22 17:28:48 2008 +0100

    exa: use xf86ReturnOptValBool instead of xf86IsOptionSet
    
    The latter doesn't give you the option's value, it just tells you if
    it's present in the configuration.  So using Option "EXANoComposite" "false"
    disabled composite acceleration.

diff --git a/hw/xfree86/exa/examodule.c b/hw/xfree86/exa/examodule.c
index 086639c..e18da0a 100644
--- a/hw/xfree86/exa/examodule.c
+++ b/hw/xfree86/exa/examodule.c
@@ -148,22 +148,23 @@ exaDDXDriverInit(ScreenPtr pScreen)
 				 FALSE);
     }
 
-    if (xf86IsOptionSet(pScreenPriv->options, EXAOPT_NO_COMPOSITE)) {
-	xf86DrvMsg(pScreen->myNum, X_INFO,
+    if (xf86ReturnOptValBool(pScreenPriv->options,
+                             EXAOPT_NO_COMPOSITE, FALSE)) {
+	xf86DrvMsg(pScreen->myNum, X_CONFIG,
 		   "EXA: Disabling Composite operation "
 		   "(RENDER acceleration)\n");
 	pExaScr->info->CheckComposite = NULL;
 	pExaScr->info->PrepareComposite = NULL;
     }
 
-    if (xf86IsOptionSet(pScreenPriv->options, EXAOPT_NO_UTS)) {
-	xf86DrvMsg(pScreen->myNum, X_INFO,
+    if (xf86ReturnOptValBool(pScreenPriv->options, EXAOPT_NO_UTS, FALSE)) {
+	xf86DrvMsg(pScreen->myNum, X_CONFIG,
 		   "EXA: Disabling UploadToScreen\n");
 	pExaScr->info->UploadToScreen = NULL;
     }
 
-    if (xf86IsOptionSet(pScreenPriv->options, EXAOPT_NO_DFS)) {
-	xf86DrvMsg(pScreen->myNum, X_INFO,
+    if (xf86ReturnOptValBool(pScreenPriv->options, EXAOPT_NO_DFS, FALSE)) {
+	xf86DrvMsg(pScreen->myNum, X_CONFIG,
 		   "EXA: Disabling DownloadFromScreen\n");
 	pExaScr->info->DownloadFromScreen = NULL;
     }
commit 63859473965f911515bc6e8d87b32a65ec41eb73
Author: Jeremy Huddleston <jeremy at tifa.local>
Date:   Fri Mar 21 19:31:31 2008 -0700

    XQuartz: Disable 256 color option and fullscreen option
    (cherry picked from commit 7c1964338a33558d3f25e369dfca99e3ef9d10f9)

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index 1cf992d..b7c8763 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -612,8 +612,10 @@ static NSMutableArray * cfarray_to_nsarray (CFArrayRef in) {
 	
     quartzUseSysBeep = [self prefs_get_boolean:@PREFS_SYSBEEP
                         default:quartzUseSysBeep];
-    quartzEnableRootless = [self prefs_get_boolean:@PREFS_ROOTLESS
-                        default:quartzEnableRootless];
+
+    // TODO: Add fullscreen support
+    //quartzEnableRootless = [self prefs_get_boolean:@PREFS_ROOTLESS
+    //                    default:quartzEnableRootless];
 #ifdef DARWIN_DDX_MISSING
     quartzFullscreenDisableHotkeys = ![self prefs_get_boolean:
 					      @PREFS_FULLSCREEN_HOTKEYS default:
@@ -645,6 +647,10 @@ static NSMutableArray * cfarray_to_nsarray (CFArrayRef in) {
 	
     darwinDesiredDepth = [self prefs_get_integer:@PREFS_DEPTH
                           default:darwinDesiredDepth];
+    
+    // TODO: Add 256 color support
+    if(darwinDesiredDepth == 8)
+        darwinDesiredDepth = -1;
 	
     enable_stereo = [self prefs_get_boolean:@PREFS_ENABLE_STEREO
                      default:false];
diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index 3880b3f..a9d2add 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -635,22 +635,27 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 
 - (IBAction) prefs_show:sender
 {
-  [fake_buttons setIntValue:darwinFakeButtons];
-  [use_sysbeep setIntValue:quartzUseSysBeep];
-  [enable_keyequivs setIntValue:X11EnableKeyEquivalents];
-  [sync_keymap setIntValue:darwinSyncKeymap];
-  [sync_keymap setEnabled:darwinKeymapFile == NULL];
-  [click_through setIntValue:[NSApp prefs_get_boolean:@PREFS_CLICK_THROUGH default:NO]];
-  [focus_follows_mouse setIntValue:[NSApp prefs_get_boolean:@PREFS_FFM default:NO]];
-  [focus_on_new_window setIntValue:[NSApp prefs_get_boolean:@PREFS_FOCUS_ON_NEW_WINDOW default:YES]];
-
-  [enable_auth setIntValue:![NSApp prefs_get_boolean:@PREFS_NO_AUTH default:NO]];
-  [enable_tcp setIntValue:![NSApp prefs_get_boolean:@PREFS_NO_TCP default:NO]];
-  [depth selectItemAtIndex:[depth indexOfItemWithTag:[NSApp prefs_get_integer:@PREFS_DEPTH default:-1]]];
-	
-  [enable_fullscreen setIntValue:!quartzEnableRootless];
-	
-  [prefs_panel makeKeyAndOrderFront:sender];
+    [fake_buttons setIntValue:darwinFakeButtons];
+    [use_sysbeep setIntValue:quartzUseSysBeep];
+    [enable_keyequivs setIntValue:X11EnableKeyEquivalents];
+    [sync_keymap setIntValue:darwinSyncKeymap];
+    [sync_keymap setEnabled:darwinKeymapFile == NULL];
+    [click_through setIntValue:[NSApp prefs_get_boolean:@PREFS_CLICK_THROUGH default:NO]];
+    [focus_follows_mouse setIntValue:[NSApp prefs_get_boolean:@PREFS_FFM default:NO]];
+    [focus_on_new_window setIntValue:[NSApp prefs_get_boolean:@PREFS_FOCUS_ON_NEW_WINDOW default:YES]];
+    
+    [enable_auth setIntValue:![NSApp prefs_get_boolean:@PREFS_NO_AUTH default:NO]];
+    [enable_tcp setIntValue:![NSApp prefs_get_boolean:@PREFS_NO_TCP default:NO]];
+
+    [depth selectItemAtIndex:[depth indexOfItemWithTag:[NSApp prefs_get_integer:@PREFS_DEPTH default:-1]]];
+    // TODO: Add 256 color support
+    [depth removeItemAtIndex:[depth indexOfItemWithTag:8]];
+	
+    [enable_fullscreen setIntValue:!quartzEnableRootless];
+    // TODO: Add fullscreen support
+    [enable_fullscreen setEnabled:NO];
+	
+    [prefs_panel makeKeyAndOrderFront:sender];
 }
 
 - (IBAction) quit:sender
diff --git a/hw/xquartz/bundle/English.lproj/main.nib/designable.nib b/hw/xquartz/bundle/English.lproj/main.nib/designable.nib
index adc0340..672ba90 100644
--- a/hw/xquartz/bundle/English.lproj/main.nib/designable.nib
+++ b/hw/xquartz/bundle/English.lproj/main.nib/designable.nib
@@ -472,7 +472,7 @@
 										<characters key="NS.bytes">1</characters>
 									</object>
 									<object class="NSView" key="NSView" id="596750588">
-										<nil key="NSNextResponder"/>
+										<reference key="NSNextResponder" ref="448510093"/>
 										<int key="NSvFlags">256</int>
 										<object class="NSMutableArray" key="NSSubviews">
 											<bool key="EncodedWithXMLCoder">YES</bool>
@@ -616,6 +616,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											</object>
 										</object>
 										<string key="NSFrame">{{10, 33}, {438, 218}}</string>
+										<reference key="NSSuperview" ref="448510093"/>
 									</object>
 									<string key="NSLabel">Input</string>
 									<reference key="NSColor" ref="57160303"/>
@@ -839,7 +840,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 										<characters key="NS.bytes">2</characters>
 									</object>
 									<object class="NSView" key="NSView" id="184765684">
-										<reference key="NSNextResponder" ref="448510093"/>
+										<nil key="NSNextResponder"/>
 										<int key="NSvFlags">256</int>
 										<object class="NSMutableArray" key="NSSubviews">
 											<bool key="EncodedWithXMLCoder">YES</bool>
@@ -956,7 +957,6 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											</object>
 										</object>
 										<string key="NSFrame">{{10, 33}, {438, 218}}</string>
-										<reference key="NSSuperview" ref="448510093"/>
 									</object>
 									<string key="NSLabel">Windows</string>
 									<reference key="NSColor" ref="57160303"/>
@@ -1068,14 +1068,14 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 									<reference key="NSTabView" ref="448510093"/>
 								</object>
 							</object>
-							<reference key="NSSelectedTabViewItem" ref="10973343"/>
+							<reference key="NSSelectedTabViewItem" ref="287591690"/>
 							<reference key="NSFont" ref="463863101"/>
 							<int key="NSTvFlags">0</int>
 							<bool key="NSAllowTruncatedLabels">YES</bool>
 							<bool key="NSDrawsBackground">YES</bool>
 							<object class="NSMutableArray" key="NSSubviews">
 								<bool key="EncodedWithXMLCoder">YES</bool>
-								<reference ref="184765684"/>
+								<reference ref="596750588"/>
 							</object>
 						</object>
 					</object>
@@ -3363,9 +3363,9 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
 					<reference ref="9"/>
 					<string>{{271, 666}, {301, 153}}</string>
-					<string>{{460, 353}, {484, 280}}</string>
+					<string>{{313, 353}, {484, 280}}</string>
 					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
-					<string>{{460, 353}, {484, 280}}</string>
+					<string>{{313, 353}, {484, 280}}</string>
 					<reference ref="9"/>
 					<string>{{184, 290}, {481, 345}}</string>
 					<object class="NSDictionary">
diff --git a/hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib b/hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib
index 400ee5c..91a7c5a 100644
Binary files a/hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib and b/hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib differ
commit 93daa3a3bf1a981757024847882ce92b6bdaae83
Author: Jeremy Huddleston <jeremy at tifa.local>
Date:   Fri Mar 21 19:11:59 2008 -0700

    Xquartz: Added separate preference tab for quartz-wm settings
    Added FFM and "Focus on new window" options
    (cherry picked from commit 6841d078b7cb0b0db3db948d26b4d5ec7747deb8)

diff --git a/hw/xquartz/X11Application.h b/hw/xquartz/X11Application.h
index 86da67f..ea9a6b7 100644
--- a/hw/xquartz/X11Application.h
+++ b/hw/xquartz/X11Application.h
@@ -98,6 +98,8 @@ extern int quartzHasRoot, quartzEnableRootless;
 #define PREFS_XP_OPTIONS            "xp_options"
 #define PREFS_ENABLE_STEREO         "enable_stereo"
 #define PREFS_LOGIN_SHELL           "login_shell"
-#define PREFS_QUARTZ_WM_CLICK_THROUGH "wm_click_through"
+#define PREFS_CLICK_THROUGH         "wm_click_through"
+#define PREFS_FFM                   "wm_ffm"
+#define PREFS_FOCUS_ON_NEW_WINDOW   "wm_focus_on_new_window"
 
 #endif /* X11APPLICATION_H */
diff --git a/hw/xquartz/X11Controller.h b/hw/xquartz/X11Controller.h
index 64d5cd1..8d6a38f 100644
--- a/hw/xquartz/X11Controller.h
+++ b/hw/xquartz/X11Controller.h
@@ -45,6 +45,8 @@
     IBOutlet NSButton *enable_keyequivs;
     IBOutlet NSButton *sync_keymap;
     IBOutlet NSButton *click_through;
+    IBOutlet NSButton *focus_follows_mouse;
+    IBOutlet NSButton *focus_on_new_window;
     IBOutlet NSButton *enable_auth;
     IBOutlet NSButton *enable_tcp;
     IBOutlet NSPopUpButton *depth;
diff --git a/hw/xquartz/X11Controller.m b/hw/xquartz/X11Controller.m
index 5111eaf..3880b3f 100644
--- a/hw/xquartz/X11Controller.m
+++ b/hw/xquartz/X11Controller.m
@@ -609,24 +609,28 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
 
 - (IBAction)prefs_changed:sender
 {
-  darwinFakeButtons = [fake_buttons intValue];
-  quartzUseSysBeep = [use_sysbeep intValue];
-  X11EnableKeyEquivalents = [enable_keyequivs intValue];
-  darwinSyncKeymap = [sync_keymap intValue];
-
-  /* after adding prefs here, also add to [X11Application read_defaults]
+    darwinFakeButtons = [fake_buttons intValue];
+    quartzUseSysBeep = [use_sysbeep intValue];
+    X11EnableKeyEquivalents = [enable_keyequivs intValue];
+    darwinSyncKeymap = [sync_keymap intValue];
+    
+    /* after adding prefs here, also add to [X11Application read_defaults]
      and below */
 	
-  [NSApp prefs_set_boolean:@PREFS_FAKEBUTTONS value:darwinFakeButtons];
-  [NSApp prefs_set_boolean:@PREFS_SYSBEEP value:quartzUseSysBeep];
-  [NSApp prefs_set_boolean:@PREFS_KEYEQUIVS value:X11EnableKeyEquivalents];
-  [NSApp prefs_set_boolean:@PREFS_SYNC_KEYMAP value:darwinSyncKeymap];
-  [NSApp prefs_set_boolean:@PREFS_QUARTZ_WM_CLICK_THROUGH value:[click_through intValue]];
-  [NSApp prefs_set_boolean:@PREFS_NO_AUTH value:![enable_auth intValue]];
-  [NSApp prefs_set_boolean:@PREFS_NO_TCP value:![enable_tcp intValue]];
-  [NSApp prefs_set_integer:@PREFS_DEPTH value:[depth selectedTag]];
+    [NSApp prefs_set_boolean:@PREFS_FAKEBUTTONS value:darwinFakeButtons];
+    [NSApp prefs_set_boolean:@PREFS_SYSBEEP value:quartzUseSysBeep];
+    [NSApp prefs_set_boolean:@PREFS_KEYEQUIVS value:X11EnableKeyEquivalents];
+    [NSApp prefs_set_boolean:@PREFS_SYNC_KEYMAP value:darwinSyncKeymap];
+    [NSApp prefs_set_boolean:@PREFS_CLICK_THROUGH value:[click_through intValue]];
+    [NSApp prefs_set_boolean:@PREFS_FFM value:[focus_follows_mouse intValue]];
+    [NSApp prefs_set_boolean:@PREFS_FOCUS_ON_NEW_WINDOW value:[focus_on_new_window intValue]];
+    [NSApp prefs_set_boolean:@PREFS_NO_AUTH value:![enable_auth intValue]];
+    [NSApp prefs_set_boolean:@PREFS_NO_TCP value:![enable_tcp intValue]];
+    [NSApp prefs_set_integer:@PREFS_DEPTH value:[depth selectedTag]];
+    
+    system("killall -HUP quartz-wm");
 	
-  [NSApp prefs_synchronize];
+    [NSApp prefs_synchronize];
 }
 
 - (IBAction) prefs_show:sender
@@ -636,8 +640,10 @@ objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
   [enable_keyequivs setIntValue:X11EnableKeyEquivalents];
   [sync_keymap setIntValue:darwinSyncKeymap];
   [sync_keymap setEnabled:darwinKeymapFile == NULL];
-  [click_through setIntValue:[NSApp prefs_get_boolean:@PREFS_QUARTZ_WM_CLICK_THROUGH default:NO]];
-	
+  [click_through setIntValue:[NSApp prefs_get_boolean:@PREFS_CLICK_THROUGH default:NO]];
+  [focus_follows_mouse setIntValue:[NSApp prefs_get_boolean:@PREFS_FFM default:NO]];
+  [focus_on_new_window setIntValue:[NSApp prefs_get_boolean:@PREFS_FOCUS_ON_NEW_WINDOW default:YES]];
+
   [enable_auth setIntValue:![NSApp prefs_get_boolean:@PREFS_NO_AUTH default:NO]];
   [enable_tcp setIntValue:![NSApp prefs_get_boolean:@PREFS_NO_TCP default:NO]];
   [depth selectItemAtIndex:[depth indexOfItemWithTag:[NSApp prefs_get_integer:@PREFS_DEPTH default:-1]]];
diff --git a/hw/xquartz/bundle/English.lproj/main.nib/designable.nib b/hw/xquartz/bundle/English.lproj/main.nib/designable.nib
index ea3a0da..adc0340 100644
--- a/hw/xquartz/bundle/English.lproj/main.nib/designable.nib
+++ b/hw/xquartz/bundle/English.lproj/main.nib/designable.nib
@@ -8,8 +8,6 @@
 		<string key="IBDocument.HIToolboxVersion">352.00</string>
 		<object class="NSMutableArray" key="IBDocument.EditedObjectIDs">
 			<bool key="EncodedWithXMLCoder">YES</bool>
-			<integer value="57"/>
-			<integer value="285"/>
 		</object>
 		<object class="NSArray" key="IBDocument.PluginDependencies">
 			<bool key="EncodedWithXMLCoder">YES</bool>
@@ -448,7 +446,7 @@
 			<object class="NSWindowTemplate" id="124913468">
 				<int key="NSWindowStyleMask">3</int>
 				<int key="NSWindowBacking">2</int>
-				<string key="NSWindowRect">{{319, 294}, {481, 345}}</string>
+				<string key="NSWindowRect">{{266, 392}, {484, 280}}</string>
 				<int key="NSWTFlags">1350041600</int>
 				<string key="NSWindowTitle">X11 Preferences</string>
 				<string key="NSWindowClass">NSPanel</string>
@@ -465,7 +463,7 @@
 						<object class="NSTabView" id="448510093">
 							<reference key="NSNextResponder" ref="941366957"/>
 							<int key="NSvFlags">256</int>
-							<string key="NSFrame">{{10, 10}, {458, 325}}</string>
+							<string key="NSFrame">{{13, 10}, {458, 264}}</string>
 							<reference key="NSSuperview" ref="941366957"/>
 							<object class="NSMutableArray" key="NSTabViewItems">
 								<bool key="EncodedWithXMLCoder">YES</bool>
@@ -474,14 +472,14 @@
 										<characters key="NS.bytes">1</characters>
 									</object>
 									<object class="NSView" key="NSView" id="596750588">
-										<reference key="NSNextResponder" ref="448510093"/>
+										<nil key="NSNextResponder"/>
 										<int key="NSvFlags">256</int>
 										<object class="NSMutableArray" key="NSSubviews">
 											<bool key="EncodedWithXMLCoder">YES</bool>
 											<object class="NSButton" id="119157981">
 												<reference key="NSNextResponder" ref="596750588"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{18, 243}, {402, 18}}</string>
+												<string key="NSFrame">{{18, 182}, {402, 18}}</string>
 												<reference key="NSSuperview" ref="596750588"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSButtonCell" key="NSCell" id="990762273">
@@ -508,7 +506,7 @@
 											<object class="NSTextField" id="443008216">
 												<reference key="NSNextResponder" ref="596750588"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{36, 93}, {385, 31}}</string>
+												<string key="NSFrame">{{36, 32}, {385, 31}}</string>
 												<reference key="NSSuperview" ref="596750588"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSTextFieldCell" key="NSCell" id="391919450">
@@ -544,7 +542,7 @@
 											<object class="NSTextField" id="282885445">
 												<reference key="NSNextResponder" ref="596750588"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{36, 208}, {385, 29}}</string>
+												<string key="NSFrame">{{36, 147}, {385, 29}}</string>
 												<reference key="NSSuperview" ref="596750588"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSTextFieldCell" key="NSCell" id="649334366">
@@ -561,7 +559,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSButton" id="842100515">
 												<reference key="NSNextResponder" ref="596750588"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{18, 130}, {402, 18}}</string>
+												<string key="NSFrame">{{18, 69}, {402, 18}}</string>
 												<reference key="NSSuperview" ref="596750588"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSButtonCell" key="NSCell" id="940564599">
@@ -582,7 +580,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSTextField" id="31160162">
 												<reference key="NSNextResponder" ref="596750588"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{36, 159}, {385, 14}}</string>
+												<string key="NSFrame">{{36, 98}, {385, 14}}</string>
 												<reference key="NSSuperview" ref="596750588"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSTextFieldCell" key="NSCell" id="666057093">
@@ -598,7 +596,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSButton" id="179949713">
 												<reference key="NSNextResponder" ref="596750588"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{18, 179}, {402, 18}}</string>
+												<string key="NSFrame">{{18, 118}, {402, 18}}</string>
 												<reference key="NSSuperview" ref="596750588"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSButtonCell" key="NSCell" id="967619578">
@@ -616,46 +614,8 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 													<int key="NSPeriodicInterval">25</int>
 												</object>
 											</object>
-											<object class="NSButton" id="915448994">
-												<reference key="NSNextResponder" ref="596750588"/>
-												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{18, 69}, {402, 18}}</string>
-												<reference key="NSSuperview" ref="596750588"/>
-												<bool key="NSEnabled">YES</bool>
-												<object class="NSButtonCell" key="NSCell" id="117056849">
-													<int key="NSCellFlags">67239424</int>
-													<int key="NSCellFlags2">0</int>
-													<string key="NSContents">Click-through Inactive Windows</string>
-													<reference key="NSSupport" ref="463863101"/>
-													<reference key="NSControlView" ref="915448994"/>
-													<int key="NSButtonFlags">1211912703</int>
-													<int key="NSButtonFlags2">2</int>
-													<reference key="NSAlternateImage" ref="391434389"/>
-													<string key="NSAlternateContents"/>
-													<string key="NSKeyEquivalent"/>
-													<int key="NSPeriodicDelay">200</int>
-													<int key="NSPeriodicInterval">25</int>
-												</object>
-											</object>
-											<object class="NSTextField" id="707276799">
-												<reference key="NSNextResponder" ref="596750588"/>
-												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{33, 32}, {385, 31}}</string>
-												<reference key="NSSuperview" ref="596750588"/>
-												<bool key="NSEnabled">YES</bool>
-												<object class="NSTextFieldCell" key="NSCell" id="318286890">
-													<int key="NSCellFlags">67239424</int>
-													<int key="NSCellFlags2">4194304</int>
-													<string key="NSContents">When enabled, clicking on an inactive window will cause that mouse click to pass through to that window in addition to activating it.</string>
-													<reference key="NSSupport" ref="26"/>
-													<reference key="NSControlView" ref="707276799"/>
-													<reference key="NSBackgroundColor" ref="57160303"/>
-													<reference key="NSTextColor" ref="930815747"/>
-												</object>
-											</object>
 										</object>
-										<string key="NSFrame">{{10, 33}, {438, 279}}</string>
-										<reference key="NSSuperview" ref="448510093"/>
+										<string key="NSFrame">{{10, 33}, {438, 218}}</string>
 									</object>
 									<string key="NSLabel">Input</string>
 									<reference key="NSColor" ref="57160303"/>
@@ -673,7 +633,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSButton" id="418227126">
 												<reference key="NSNextResponder" ref="515308735"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{18, 116}, {402, 18}}</string>
+												<string key="NSFrame">{{18, 55}, {402, 18}}</string>
 												<reference key="NSSuperview" ref="515308735"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSButtonCell" key="NSCell" id="1016069354">
@@ -694,7 +654,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSTextField" id="1039016593">
 												<reference key="NSNextResponder" ref="515308735"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{36, 82}, {385, 28}}</string>
+												<string key="NSFrame">{{36, 21}, {385, 28}}</string>
 												<reference key="NSSuperview" ref="515308735"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSTextFieldCell" key="NSCell" id="624655599">
@@ -710,7 +670,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSPopUpButton" id="709074847">
 												<reference key="NSNextResponder" ref="515308735"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{74, 235}, {128, 26}}</string>
+												<string key="NSFrame">{{74, 174}, {128, 26}}</string>
 												<reference key="NSSuperview" ref="515308735"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSPopUpButtonCell" key="NSCell" id="633115429">
@@ -801,7 +761,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSTextField" id="201731424">
 												<reference key="NSNextResponder" ref="515308735"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{17, 238}, {55, 20}}</string>
+												<string key="NSFrame">{{17, 177}, {55, 20}}</string>
 												<reference key="NSSuperview" ref="515308735"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSTextFieldCell" key="NSCell" id="930265681">
@@ -817,7 +777,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSTextField" id="86150604">
 												<reference key="NSNextResponder" ref="515308735"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{36, 216}, {392, 14}}</string>
+												<string key="NSFrame">{{36, 155}, {392, 14}}</string>
 												<reference key="NSSuperview" ref="515308735"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSTextFieldCell" key="NSCell" id="311969422">
@@ -833,7 +793,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSButton" id="477203622">
 												<reference key="NSNextResponder" ref="515308735"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{18, 182}, {409, 23}}</string>
+												<string key="NSFrame">{{18, 121}, {409, 23}}</string>
 												<reference key="NSSuperview" ref="515308735"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSButtonCell" key="NSCell" id="631531164">
@@ -854,7 +814,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSTextField" id="298603383">
 												<reference key="NSNextResponder" ref="515308735"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{36, 145}, {385, 31}}</string>
+												<string key="NSFrame">{{36, 84}, {385, 31}}</string>
 												<reference key="NSSuperview" ref="515308735"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSTextFieldCell" key="NSCell" id="761107402">
@@ -868,12 +828,140 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 												</object>
 											</object>
 										</object>
-										<string key="NSFrame">{{10, 33}, {438, 279}}</string>
+										<string key="NSFrame">{{10, 33}, {438, 218}}</string>
 									</object>
 									<string key="NSLabel">Output</string>
 									<reference key="NSColor" ref="57160303"/>
 									<reference key="NSTabView" ref="448510093"/>
 								</object>
+								<object class="NSTabViewItem" id="10973343">
+									<object class="NSMutableString" key="NSIdentifier">
+										<characters key="NS.bytes">2</characters>
+									</object>
+									<object class="NSView" key="NSView" id="184765684">
+										<reference key="NSNextResponder" ref="448510093"/>
+										<int key="NSvFlags">256</int>
+										<object class="NSMutableArray" key="NSSubviews">
+											<bool key="EncodedWithXMLCoder">YES</bool>
+											<object class="NSButton" id="657659108">
+												<reference key="NSNextResponder" ref="184765684"/>
+												<int key="NSvFlags">256</int>
+												<string key="NSFrame">{{15, 184}, {402, 18}}</string>
+												<reference key="NSSuperview" ref="184765684"/>
+												<bool key="NSEnabled">YES</bool>
+												<object class="NSButtonCell" key="NSCell" id="259618205">
+													<int key="NSCellFlags">67239424</int>
+													<int key="NSCellFlags2">0</int>
+													<string key="NSContents">Click-through Inactive Windows</string>
+													<reference key="NSSupport" ref="463863101"/>
+													<reference key="NSControlView" ref="657659108"/>
+													<int key="NSButtonFlags">1211912703</int>
+													<int key="NSButtonFlags2">2</int>
+													<reference key="NSAlternateImage" ref="391434389"/>
+													<string key="NSAlternateContents"/>
+													<string key="NSKeyEquivalent"/>
+													<int key="NSPeriodicDelay">200</int>
+													<int key="NSPeriodicInterval">25</int>
+												</object>
+											</object>
+											<object class="NSTextField" id="290578835">
+												<reference key="NSNextResponder" ref="184765684"/>
+												<int key="NSvFlags">256</int>
+												<string key="NSFrame">{{23, 147}, {385, 31}}</string>
+												<reference key="NSSuperview" ref="184765684"/>
+												<bool key="NSEnabled">YES</bool>
+												<object class="NSTextFieldCell" key="NSCell" id="399127858">
+													<int key="NSCellFlags">67239424</int>
+													<int key="NSCellFlags2">4194304</int>
+													<string key="NSContents">When enabled, clicking on an inactive window will cause that mouse click to pass through to that window in addition to activating it.</string>
+													<reference key="NSSupport" ref="26"/>
+													<reference key="NSControlView" ref="290578835"/>
+													<reference key="NSBackgroundColor" ref="57160303"/>
+													<reference key="NSTextColor" ref="930815747"/>
+												</object>
+											</object>
+											<object class="NSButton" id="992839333">
+												<reference key="NSNextResponder" ref="184765684"/>
+												<int key="NSvFlags">256</int>
+												<string key="NSFrame">{{15, 123}, {402, 18}}</string>
+												<reference key="NSSuperview" ref="184765684"/>
+												<bool key="NSEnabled">YES</bool>
+												<object class="NSButtonCell" key="NSCell" id="959555182">
+													<int key="NSCellFlags">67239424</int>
+													<int key="NSCellFlags2">0</int>
+													<string key="NSContents">Focus Follows Mouse</string>
+													<reference key="NSSupport" ref="463863101"/>
+													<reference key="NSControlView" ref="992839333"/>
+													<int key="NSButtonFlags">1211912703</int>
+													<int key="NSButtonFlags2">2</int>
+													<reference key="NSAlternateImage" ref="391434389"/>
+													<string key="NSAlternateContents"/>
+													<string key="NSKeyEquivalent"/>
+													<int key="NSPeriodicDelay">200</int>
+													<int key="NSPeriodicInterval">25</int>
+												</object>
+											</object>
+											<object class="NSTextField" id="138261120">
+												<reference key="NSNextResponder" ref="184765684"/>
+												<int key="NSvFlags">256</int>
+												<string key="NSFrame">{{23, 100}, {385, 17}}</string>
+												<reference key="NSSuperview" ref="184765684"/>
+												<bool key="NSEnabled">YES</bool>
+												<object class="NSTextFieldCell" key="NSCell" id="183409141">
+													<int key="NSCellFlags">67239424</int>
+													<int key="NSCellFlags2">4194304</int>
+													<string key="NSContents">X11 window focus follows the cursor</string>
+													<reference key="NSSupport" ref="26"/>
+													<reference key="NSControlView" ref="138261120"/>
+													<reference key="NSBackgroundColor" ref="57160303"/>
+													<reference key="NSTextColor" ref="930815747"/>
+												</object>
+											</object>
+											<object class="NSButton" id="128352289">
+												<reference key="NSNextResponder" ref="184765684"/>
+												<int key="NSvFlags">256</int>
+												<string key="NSFrame">{{15, 79}, {402, 18}}</string>
+												<reference key="NSSuperview" ref="184765684"/>
+												<bool key="NSEnabled">YES</bool>
+												<object class="NSButtonCell" key="NSCell" id="556463187">
+													<int key="NSCellFlags">67239424</int>
+													<int key="NSCellFlags2">0</int>
+													<string key="NSContents">Focus On New Windows</string>
+													<reference key="NSSupport" ref="463863101"/>
+													<reference key="NSControlView" ref="128352289"/>
+													<int key="NSButtonFlags">1211912703</int>
+													<int key="NSButtonFlags2">2</int>
+													<reference key="NSAlternateImage" ref="391434389"/>
+													<string key="NSAlternateContents"/>
+													<string key="NSKeyEquivalent"/>
+													<int key="NSPeriodicDelay">200</int>
+													<int key="NSPeriodicInterval">25</int>
+												</object>
+											</object>
+											<object class="NSTextField" id="57161931">
+												<reference key="NSNextResponder" ref="184765684"/>
+												<int key="NSvFlags">256</int>
+												<string key="NSFrame">{{23, 45}, {385, 28}}</string>
+												<reference key="NSSuperview" ref="184765684"/>
+												<bool key="NSEnabled">YES</bool>
+												<object class="NSTextFieldCell" key="NSCell" id="989804990">
+													<int key="NSCellFlags">67239424</int>
+													<int key="NSCellFlags2">4194304</int>
+													<string key="NSContents">When enabled, creation of a new X11 window will cause X11.app to move to the foreground (instead of Finder.app, Terminal.app, etc.</string>
+													<reference key="NSSupport" ref="26"/>
+													<reference key="NSControlView" ref="57161931"/>
+													<reference key="NSBackgroundColor" ref="57160303"/>
+													<reference key="NSTextColor" ref="930815747"/>
+												</object>
+											</object>
+										</object>
+										<string key="NSFrame">{{10, 33}, {438, 218}}</string>
+										<reference key="NSSuperview" ref="448510093"/>
+									</object>
+									<string key="NSLabel">Windows</string>
+									<reference key="NSColor" ref="57160303"/>
+									<reference key="NSTabView" ref="448510093"/>
+								</object>
 								<object class="NSTabViewItem" id="348328898">
 									<object class="NSView" key="NSView" id="300811574">
 										<nil key="NSNextResponder"/>
@@ -883,7 +971,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSButton" id="989050925">
 												<reference key="NSNextResponder" ref="300811574"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{18, 243}, {402, 18}}</string>
+												<string key="NSFrame">{{18, 182}, {402, 18}}</string>
 												<reference key="NSSuperview" ref="300811574"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSButtonCell" key="NSCell" id="189594322">
@@ -904,7 +992,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSButton" id="700826966">
 												<reference key="NSNextResponder" ref="300811574"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{18, 166}, {402, 18}}</string>
+												<string key="NSFrame">{{18, 105}, {402, 18}}</string>
 												<reference key="NSSuperview" ref="300811574"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSButtonCell" key="NSCell" id="489340979">
@@ -925,7 +1013,7 @@ ZSBhbmQgcmlnaHQgbW91c2UgYnV0dG9ucy4KA</string>
 											<object class="NSTextField" id="168436707">
 												<reference key="NSNextResponder" ref="300811574"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{36, 195}, {385, 42}}</string>
+												<string key="NSFrame">{{36, 134}, {385, 42}}</string>
 												<reference key="NSSuperview" ref="300811574"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSTextFieldCell" key="NSCell" id="53243865">
@@ -943,7 +1031,7 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 											<object class="NSTextField" id="363817195">
 												<reference key="NSNextResponder" ref="300811574"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{36, 118}, {385, 42}}</string>
+												<string key="NSFrame">{{36, 57}, {385, 42}}</string>
 												<reference key="NSSuperview" ref="300811574"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSTextFieldCell" key="NSCell" id="390084685">
@@ -959,7 +1047,7 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 											<object class="NSTextField" id="223835729">
 												<reference key="NSNextResponder" ref="300811574"/>
 												<int key="NSvFlags">256</int>
-												<string key="NSFrame">{{20, 17}, {404, 14}}</string>
+												<string key="NSFrame">{{20, -44}, {404, 14}}</string>
 												<reference key="NSSuperview" ref="300811574"/>
 												<bool key="NSEnabled">YES</bool>
 												<object class="NSTextFieldCell" key="NSCell" id="283628678">
@@ -973,27 +1061,27 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 												</object>
 											</object>
 										</object>
-										<string key="NSFrame">{{10, 33}, {438, 279}}</string>
+										<string key="NSFrame">{{10, 33}, {438, 218}}</string>
 									</object>
 									<string key="NSLabel">Security</string>
 									<reference key="NSColor" ref="57160303"/>
 									<reference key="NSTabView" ref="448510093"/>
 								</object>
 							</object>
-							<reference key="NSSelectedTabViewItem" ref="287591690"/>
+							<reference key="NSSelectedTabViewItem" ref="10973343"/>
 							<reference key="NSFont" ref="463863101"/>
 							<int key="NSTvFlags">0</int>
 							<bool key="NSAllowTruncatedLabels">YES</bool>
 							<bool key="NSDrawsBackground">YES</bool>
 							<object class="NSMutableArray" key="NSSubviews">
 								<bool key="EncodedWithXMLCoder">YES</bool>
-								<reference ref="596750588"/>
+								<reference ref="184765684"/>
 							</object>
 						</object>
 					</object>
-					<string key="NSFrameSize">{481, 345}</string>
+					<string key="NSFrameSize">{484, 280}</string>
 				</object>
-				<string key="NSScreenRect">{{0, 0}, {1440, 878}}</string>
+				<string key="NSScreenRect">{{0, 0}, {1280, 938}}</string>
 				<string key="NSMinSize">{213, 129}</string>
 				<string key="NSMaxSize">{3.40282e+38, 3.40282e+38}</string>
 				<string key="NSFrameAutosaveName">x11_prefs</string>
@@ -1001,7 +1089,7 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 			<object class="NSWindowTemplate" id="604417141">
 				<int key="NSWindowStyleMask">11</int>
 				<int key="NSWindowBacking">2</int>
-				<string key="NSWindowRect">{{361, 362}, {454, 311}}</string>
+				<string key="NSWindowRect">{{302, 400}, {454, 311}}</string>
 				<int key="NSWTFlags">1350041600</int>
 				<string key="NSWindowTitle">X11 Application Menu</string>
 				<string key="NSWindowClass">NSPanel</string>
@@ -1011,7 +1099,7 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 				<string key="NSWindowContentMaxSize">{10000, 10000}</string>
 				<string key="NSWindowContentMinSize">{320, 240}</string>
 				<object class="NSView" key="NSWindowView" id="85544634">
-					<reference key="NSNextResponder"/>
+					<nil key="NSNextResponder"/>
 					<int key="NSvFlags">256</int>
 					<object class="NSMutableArray" key="NSSubviews">
 						<bool key="EncodedWithXMLCoder">YES</bool>
@@ -1353,9 +1441,8 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 						</object>
 					</object>
 					<string key="NSFrameSize">{454, 311}</string>
-					<reference key="NSSuperview"/>
 				</object>
-				<string key="NSScreenRect">{{0, 0}, {1440, 878}}</string>
+				<string key="NSScreenRect">{{0, 0}, {1280, 938}}</string>
 				<string key="NSMinSize">{320, 262}</string>
 				<string key="NSFrameAutosaveName">x11_apps</string>
 			</object>
@@ -1842,14 +1929,6 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 					<int key="connectionID">549</int>
 				</object>
 				<object class="IBConnectionRecord">
-					<object class="IBActionConnection" key="connection">
-						<string key="label">prefs_changed:</string>
-						<reference key="source" ref="485884620"/>
-						<reference key="destination" ref="915448994"/>
-					</object>
-					<int key="connectionID">300300</int>
-				</object>
-				<object class="IBConnectionRecord">
 					<object class="IBOutletConnection" key="connection">
 						<string key="label">window_separator</string>
 						<reference key="source" ref="485884620"/>
@@ -1859,14 +1938,6 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 				</object>
 				<object class="IBConnectionRecord">
 					<object class="IBOutletConnection" key="connection">
-						<string key="label">click_through</string>
-						<reference key="source" ref="485884620"/>
-						<reference key="destination" ref="915448994"/>
-					</object>
-					<int key="connectionID">300332</int>
-				</object>
-				<object class="IBConnectionRecord">
-					<object class="IBOutletConnection" key="connection">
 						<string key="label">menu</string>
 						<reference key="source" ref="815810918"/>
 						<reference key="destination" ref="524015605"/>
@@ -1881,6 +1952,54 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 					</object>
 					<int key="connectionID">300336</int>
 				</object>
+				<object class="IBConnectionRecord">
+					<object class="IBActionConnection" key="connection">
+						<string key="label">prefs_changed:</string>
+						<reference key="source" ref="485884620"/>
+						<reference key="destination" ref="657659108"/>
+					</object>
+					<int key="connectionID">300389</int>
+				</object>
+				<object class="IBConnectionRecord">
+					<object class="IBActionConnection" key="connection">
+						<string key="label">prefs_changed:</string>
+						<reference key="source" ref="485884620"/>
+						<reference key="destination" ref="992839333"/>
+					</object>
+					<int key="connectionID">300390</int>
+				</object>
+				<object class="IBConnectionRecord">
+					<object class="IBActionConnection" key="connection">
+						<string key="label">prefs_changed:</string>
+						<reference key="source" ref="485884620"/>
+						<reference key="destination" ref="128352289"/>
+					</object>
+					<int key="connectionID">300391</int>
+				</object>
+				<object class="IBConnectionRecord">
+					<object class="IBOutletConnection" key="connection">
+						<string key="label">click_through</string>
+						<reference key="source" ref="485884620"/>
+						<reference key="destination" ref="657659108"/>
+					</object>
+					<int key="connectionID">300392</int>
+				</object>
+				<object class="IBConnectionRecord">
+					<object class="IBOutletConnection" key="connection">
+						<string key="label">focus_follows_mouse</string>
+						<reference key="source" ref="485884620"/>
+						<reference key="destination" ref="992839333"/>
+					</object>
+					<int key="connectionID">300393</int>
+				</object>
+				<object class="IBConnectionRecord">
+					<object class="IBOutletConnection" key="connection">
+						<string key="label">focus_on_new_window</string>
+						<reference key="source" ref="485884620"/>
+						<reference key="destination" ref="128352289"/>
+					</object>
+					<int key="connectionID">300394</int>
+				</object>
 			</object>
 			<object class="IBMutableOrderedSet" key="objectRecords">
 				<object class="NSArray" key="orderedObjects">
@@ -2239,6 +2358,7 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 							<reference ref="287591690"/>
 							<reference ref="960678392"/>
 							<reference ref="348328898"/>
+							<reference ref="10973343"/>
 						</object>
 						<reference key="parent" ref="941366957"/>
 					</object>
@@ -2262,8 +2382,6 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 							<reference ref="842100515"/>
 							<reference ref="31160162"/>
 							<reference ref="179949713"/>
-							<reference ref="915448994"/>
-							<reference ref="707276799"/>
 						</object>
 						<reference key="parent" ref="287591690"/>
 					</object>
@@ -2671,34 +2789,6 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 						<reference key="parent" ref="341113515"/>
 					</object>
 					<object class="IBObjectRecord">
-						<int key="objectID">300296</int>
-						<reference key="object" ref="915448994"/>
-						<object class="NSMutableArray" key="children">
-							<bool key="EncodedWithXMLCoder">YES</bool>
-							<reference ref="117056849"/>
-						</object>
-						<reference key="parent" ref="596750588"/>
-					</object>
-					<object class="IBObjectRecord">
-						<int key="objectID">300297</int>
-						<reference key="object" ref="117056849"/>
-						<reference key="parent" ref="915448994"/>
-					</object>
-					<object class="IBObjectRecord">
-						<int key="objectID">300298</int>
-						<reference key="object" ref="707276799"/>
-						<object class="NSMutableArray" key="children">
-							<bool key="EncodedWithXMLCoder">YES</bool>
-							<reference ref="318286890"/>
-						</object>
-						<reference key="parent" ref="596750588"/>
-					</object>
-					<object class="IBObjectRecord">
-						<int key="objectID">300299</int>
-						<reference key="object" ref="318286890"/>
-						<reference key="parent" ref="707276799"/>
-					</object>
-					<object class="IBObjectRecord">
 						<int key="objectID">295</int>
 						<reference key="object" ref="1063387772"/>
 						<object class="NSMutableArray" key="children">
@@ -2853,6 +2943,113 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 						<reference key="object" ref="444952046"/>
 						<reference key="parent" ref="96874957"/>
 					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300337</int>
+						<reference key="object" ref="10973343"/>
+						<object class="NSMutableArray" key="children">
+							<bool key="EncodedWithXMLCoder">YES</bool>
+							<reference ref="184765684"/>
+						</object>
+						<reference key="parent" ref="448510093"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300338</int>
+						<reference key="object" ref="184765684"/>
+						<object class="NSMutableArray" key="children">
+							<bool key="EncodedWithXMLCoder">YES</bool>
+							<reference ref="657659108"/>
+							<reference ref="290578835"/>
+							<reference ref="992839333"/>
+							<reference ref="138261120"/>
+							<reference ref="128352289"/>
+							<reference ref="57161931"/>
+						</object>
+						<reference key="parent" ref="10973343"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300358</int>
+						<reference key="object" ref="290578835"/>
+						<object class="NSMutableArray" key="children">
+							<bool key="EncodedWithXMLCoder">YES</bool>
+							<reference ref="399127858"/>
+						</object>
+						<reference key="parent" ref="184765684"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300359</int>
+						<reference key="object" ref="657659108"/>
+						<object class="NSMutableArray" key="children">
+							<bool key="EncodedWithXMLCoder">YES</bool>
+							<reference ref="259618205"/>
+						</object>
+						<reference key="parent" ref="184765684"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300360</int>
+						<reference key="object" ref="259618205"/>
+						<reference key="parent" ref="657659108"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300361</int>
+						<reference key="object" ref="399127858"/>
+						<reference key="parent" ref="290578835"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300362</int>
+						<reference key="object" ref="992839333"/>
+						<object class="NSMutableArray" key="children">
+							<bool key="EncodedWithXMLCoder">YES</bool>
+							<reference ref="959555182"/>
+						</object>
+						<reference key="parent" ref="184765684"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300363</int>
+						<reference key="object" ref="959555182"/>
+						<reference key="parent" ref="992839333"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300364</int>
+						<reference key="object" ref="138261120"/>
+						<object class="NSMutableArray" key="children">
+							<bool key="EncodedWithXMLCoder">YES</bool>
+							<reference ref="183409141"/>
+						</object>
+						<reference key="parent" ref="184765684"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300365</int>
+						<reference key="object" ref="183409141"/>
+						<reference key="parent" ref="138261120"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300368</int>
+						<reference key="object" ref="128352289"/>
+						<object class="NSMutableArray" key="children">
+							<bool key="EncodedWithXMLCoder">YES</bool>
+							<reference ref="556463187"/>
+						</object>
+						<reference key="parent" ref="184765684"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300369</int>
+						<reference key="object" ref="556463187"/>
+						<reference key="parent" ref="128352289"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300370</int>
+						<reference key="object" ref="57161931"/>
+						<object class="NSMutableArray" key="children">
+							<bool key="EncodedWithXMLCoder">YES</bool>
+							<reference ref="989804990"/>
+						</object>
+						<reference key="parent" ref="184765684"/>
+					</object>
+					<object class="IBObjectRecord">
+						<int key="objectID">300371</int>
+						<reference key="object" ref="989804990"/>
+						<reference key="parent" ref="57161931"/>
+					</object>
 				</object>
 			</object>
 			<object class="NSMutableDictionary" key="flattenedProperties">
@@ -2919,10 +3116,12 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 					<string>24.IBPluginDependency</string>
 					<string>24.ImportedFromIB2</string>
 					<string>24.editorWindowContentRectSynchronizationRect</string>
+					<string>244.IBEditorWindowLastContentRect</string>
 					<string>244.IBPluginDependency</string>
 					<string>244.IBWindowTemplateEditedContentRect</string>
 					<string>244.ImportedFromIB2</string>
 					<string>244.editorWindowContentRectSynchronizationRect</string>
+					<string>244.lastResizeAction</string>
 					<string>244.windowTemplate.hasMaxSize</string>
 					<string>244.windowTemplate.hasMinSize</string>
 					<string>244.windowTemplate.maxSize</string>
@@ -2971,12 +3170,24 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 					<string>299.IBPluginDependency</string>
 					<string>299.ImportedFromIB2</string>
 					<string>300295.IBShouldRemoveOnLegacySave</string>
-					<string>300296.IBPluginDependency</string>
-					<string>300296.ImportedFromIB2</string>
-					<string>300298.IBPluginDependency</string>
-					<string>300298.ImportedFromIB2</string>
 					<string>300330.IBPluginDependency</string>
 					<string>300330.ImportedFromIB2</string>
+					<string>300337.IBPluginDependency</string>
+					<string>300337.ImportedFromIB2</string>
+					<string>300338.IBPluginDependency</string>
+					<string>300338.ImportedFromIB2</string>
+					<string>300358.IBPluginDependency</string>
+					<string>300358.ImportedFromIB2</string>
+					<string>300359.IBPluginDependency</string>
+					<string>300359.ImportedFromIB2</string>
+					<string>300362.IBPluginDependency</string>
+					<string>300362.ImportedFromIB2</string>
+					<string>300364.IBPluginDependency</string>
+					<string>300364.ImportedFromIB2</string>
+					<string>300368.IBPluginDependency</string>
+					<string>300368.ImportedFromIB2</string>
+					<string>300370.IBPluginDependency</string>
+					<string>300370.ImportedFromIB2</string>
 					<string>305.IBPluginDependency</string>
 					<string>305.ImportedFromIB2</string>
 					<string>310.IBPluginDependency</string>
@@ -3152,10 +3363,24 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
 					<reference ref="9"/>
 					<string>{{271, 666}, {301, 153}}</string>
+					<string>{{460, 353}, {484, 280}}</string>
 					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
-					<string>{{184, 290}, {481, 345}}</string>
+					<string>{{460, 353}, {484, 280}}</string>
 					<reference ref="9"/>
 					<string>{{184, 290}, {481, 345}}</string>
+					<object class="NSDictionary">
+						<bool key="EncodedWithXMLCoder">YES</bool>
+						<object class="NSMutableArray" key="dict.sortedKeys">
+							<bool key="EncodedWithXMLCoder">YES</bool>
+							<string>IBResizeActionFinalFrame</string>
+							<string>IBResizeActionInitialFrame</string>
+						</object>
+						<object class="NSMutableArray" key="dict.values">
+							<bool key="EncodedWithXMLCoder">YES</bool>
+							<string>{{182, 481}, {484, 280}}</string>
+							<string>{{182, 103}, {536, 658}}</string>
+						</object>
+					</object>
 					<reference ref="9"/>
 					<reference ref="9"/>
 					<string>{3.40282e+38, 3.40282e+38}</string>
@@ -3169,11 +3394,11 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 					<string>{{100, 746}, {155, 33}}</string>
 					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
 					<reference ref="9"/>
-					<string>{{537, 545}, {454, 311}}</string>
+					<string>{{407, 545}, {454, 311}}</string>
 					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
 					<reference ref="9"/>
 					<reference ref="9"/>
-					<string>{{537, 545}, {454, 311}}</string>
+					<string>{{407, 545}, {454, 311}}</string>
 					<reference ref="9"/>
 					<string>{{433, 406}, {486, 327}}</string>
 					<object class="NSDictionary">
@@ -3320,6 +3545,18 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 					<reference ref="9"/>
 					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
 					<reference ref="9"/>
+					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
+					<reference ref="9"/>
+					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
+					<reference ref="9"/>
+					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
+					<reference ref="9"/>
+					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
+					<reference ref="9"/>
+					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
+					<reference ref="9"/>
+					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
+					<reference ref="9"/>
 					<string>{{12, 633}, {218, 203}}</string>
 					<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
 					<reference ref="9"/>
@@ -3356,7 +3593,7 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 				</object>
 			</object>
 			<nil key="sourceID"/>
-			<int key="maxID">300336</int>
+			<int key="maxID">300394</int>
 		</object>
 		<object class="IBClassDescriber" key="IBDocument.Classes">
 			<object class="NSMutableArray" key="referencedPartialClassDescriptions">
@@ -3378,6 +3615,17 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 				<object class="IBPartialClassDescription">
 					<string key="className">X11Controller</string>
 					<string key="superclassName">NSObject</string>
+					<object class="IBClassDescriptionSource" key="sourceIdentifier">
+						<string key="majorKey">IBUserSource</string>
+						<string key="minorKey"/>
+					</object>
+				</object>
+			</object>
+			<object class="NSMutableArray" key="referencedPartialClassDescriptionsV3.1+">
+				<bool key="EncodedWithXMLCoder">YES</bool>
+				<object class="IBPartialClassDescription">
+					<string key="className">X11Controller</string>
+					<string key="superclassName">NSObject</string>
 					<object class="NSMutableDictionary" key="actions">
 						<bool key="EncodedWithXMLCoder">YES</bool>
 						<object class="NSMutableArray" key="dict.sortedKeys">
@@ -3439,6 +3687,8 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 							<string>enable_keyequivs</string>
 							<string>enable_tcp</string>
 							<string>fake_buttons</string>
+							<string>focus_follows_mouse</string>
+							<string>focus_on_new_window</string>
 							<string>prefs_panel</string>
 							<string>sync_keymap</string>
 							<string>toggle_fullscreen_item</string>
@@ -3460,6 +3710,8 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 							<string>NSButton</string>
 							<string>NSButton</string>
 							<string>NSButton</string>
+							<string>NSButton</string>
+							<string>NSButton</string>
 							<string>NSPanel</string>
 							<string>NSButton</string>
 							<string>NSMenuItem</string>
@@ -3469,8 +3721,8 @@ d2hpY2ggbWF5IHByZXZlbnQgWDExIGFwcGxpY2F0aW9ucyBmcm9tIGxhdW5jaGluZy4</string>
 						</object>
 					</object>
 					<object class="IBClassDescriptionSource" key="sourceIdentifier">
-						<string key="majorKey">IBUserSource</string>
-						<string key="minorKey"/>
+						<string key="majorKey">IBDocumentRelativeSource</string>
+						<string key="minorKey">../../X11Controller.h</string>
 					</object>
 				</object>
 			</object>
diff --git a/hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib b/hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib
index f60dcba..400ee5c 100644
Binary files a/hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib and b/hw/xquartz/bundle/English.lproj/main.nib/keyedobjects.nib differ
diff --git a/hw/xquartz/quartzCommon.h b/hw/xquartz/quartzCommon.h
index a0d4673..c4bd2d8 100644
--- a/hw/xquartz/quartzCommon.h
+++ b/hw/xquartz/quartzCommon.h
@@ -68,6 +68,7 @@ extern int              quartzEventWriteFD;
 // User preferences used by Quartz modes
 extern int              quartzRootless;
 extern int              quartzUseSysBeep;
+extern int              focusOnNewWindow;
 extern int              quartzUseAGL;
 extern int              quartzEnableKeyEquivalents;
 
@@ -91,17 +92,4 @@ int  QuartzFSUseQDCursor(int depth);
 void QuartzBlockHandler(pointer blockData, OSTimePtr pTimeout, pointer pReadmask);
 void QuartzWakeupHandler(pointer blockData, int result, pointer pReadmask);
 
-// Messages that can be sent to the main thread.
-enum {
-    kQuartzServerHidden,
-    kQuartzServerStarted,
-    kQuartzServerDied,
-    kQuartzCursorUpdate,
-    kQuartzPostEvent,
-    kQuartzSetWindowMenu,
-    kQuartzSetWindowMenuCheck,
-    kQuartzSetFrontProcess,
-    kQuartzSetCanQuit
-};
-
 #endif  /* _QUARTZCOMMON_H */
diff --git a/hw/xquartz/quartzForeground.c b/hw/xquartz/quartzForeground.c
index 0e724de..80a04a1 100644
--- a/hw/xquartz/quartzForeground.c
+++ b/hw/xquartz/quartzForeground.c
@@ -38,7 +38,7 @@ int QuartzMoveToForeground() {
    ProcessSerialNumber psn = { 0, kCurrentProcess };
    OSStatus returnCode = TransformProcessType(& psn, kProcessTransformToForegroundApplication);
    if( returnCode == 0) {
-       fprintf(stderr, "TransformProcessType: Success\n");
+       /* fprintf(stderr, "TransformProcessType: Success\n"); */
        SetFrontProcess(&psn);
    } else {
        fprintf(stderr, "TransformProcessType: Failure\n");
commit c49e11268322712c211f29d51d664d3f8a59b00b
Author: Jeremy Huddleston <jeremy at tifa.local>
Date:   Fri Mar 21 18:07:38 2008 -0700

    XQuartz: Initial framework for dealing with spaces on OS-X
    (cherry picked from commit 9831324998f9d1f05ff944c58c5bf60dcae17355)

diff --git a/hw/xquartz/darwin.h b/hw/xquartz/darwin.h
index c5e2ed8..325122d 100644
--- a/hw/xquartz/darwin.h
+++ b/hw/xquartz/darwin.h
@@ -106,6 +106,7 @@ enum {
     kXDarwinBringAllToFront,  // bring all X windows to front
     kXDarwinToggleFullscreen, // Enable/Disable fullscreen mode
     kXDarwinSetRootless,      // Set rootless mode
+    kXDarwinSpaceChanged,     // Spaces changed
     /*
      * AppleWM events
      */
@@ -116,7 +117,7 @@ enum {
      */
     kXDarwinDisplayChanged,   // display configuration has changed
     kXDarwinWindowState,      // window visibility state has changed
-    kXDarwinWindowMoved       // window has moved on screen
+    kXDarwinWindowMoved,      // window has moved on screen
 };
 
 #define ENABLE_DEBUG_LOG 1
diff --git a/hw/xquartz/quartz.c b/hw/xquartz/quartz.c
index 6f42c53..a034c9f 100644
--- a/hw/xquartz/quartz.c
+++ b/hw/xquartz/quartz.c
@@ -266,7 +266,7 @@ static void QuartzUpdateScreens(void)
     
 #ifndef FAKE_RANDR
     if(!QuartzRandRInit(pScreen))
-      FatalError("Failed to init RandR extension.\n");
+        FatalError("Failed to init RandR extension.\n");
 #endif
 
     DarwinAdjustScreenOrigins(&screenInfo);
@@ -364,6 +364,14 @@ static void QuartzSetRootClip(
     }
 }
 
+/* 
+ * QuartzSpaceChanged
+ *  Unmap offscreen windows, map onscreen windows
+ */
+static void QuartzSpaceChanged(uint32_t space_id) {
+    /* Do something special here, so we don't depend on quartz-wm for spaces to work... */
+    DEBUG_LOG("Space Changed (%u) ... do something interesting...\n", space_id);
+}
 
 /*
  * QuartzMessageServerThread
@@ -494,6 +502,10 @@ void QuartzProcessEvent(xEvent *xe) {
             RootlessOrderAllWindows();
             break;
 
+        case kXDarwinSpaceChanged:
+            DEBUG_LOG("kXDarwinSpaceChanged\n");
+            QuartzSpaceChanged(xe->u.clientMessage.u.l.longs0);
+            break;
         default:
             ErrorF("Unknown application defined event type %d.\n", xe->u.u.type);
     }
diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index db36403..4dc5846 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -63,6 +63,7 @@ static const char *xprOpenGLBundle = "glxCGL.bundle";
  */
 static void eventHandler(unsigned int type, const void *arg,
                          unsigned int arg_size, void *data) {
+    
     switch (type) {
         case XP_EVENT_DISPLAY_CHANGED:
             DEBUG_LOG("XP_EVENT_DISPLAY_CHANGED\n");
@@ -105,6 +106,13 @@ static void eventHandler(unsigned int type, const void *arg,
                 DRISurfaceNotify(*(xp_surface_id *) arg, kind);
             }
             break;
+        case  XP_EVENT_SPACE_CHANGED:
+            ErrorF("XP_EVENT_SPACE_CHANGED\n");
+            if(arg_size == sizeof(uint32_t)) {
+                uint32_t space_id = *(uint32_t *)arg;
+                QuartzMessageServerThread(kXDarwinSpaceChanged, 1, space_id);
+            }
+            break;
         default:
             ErrorF("Unknown XP_EVENT type (%d) in xprScreen:eventHandler\n", type);
     }
@@ -233,7 +241,8 @@ xprDisplayInit(void)
                      | XP_EVENT_WINDOW_STATE_CHANGED
                      | XP_EVENT_WINDOW_MOVED
                      | XP_EVENT_SURFACE_CHANGED
-                     | XP_EVENT_SURFACE_DESTROYED,
+                     | XP_EVENT_SURFACE_DESTROYED
+                     | XP_EVENT_SPACE_CHANGED,
                      eventHandler, NULL);
 
     AppleDRIExtensionInit();
commit 4c76607b699431183ee7e88fa7818cb7644a5a02
Author: Jeremy Huddleston <jeremy at tifa.local>
Date:   Mon Mar 17 23:57:41 2008 -0700

    Rootless: Removed safeAlphaXXXX() in favor of using fb/pixman
    (cherry picked from commit f03202ad15457c98be7ca78cc59bac88cf5f1966)

diff --git a/configure.ac b/configure.ac
index 49f2395..3b00705 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2120,7 +2120,6 @@ miext/damage/Makefile
 miext/shadow/Makefile
 miext/cw/Makefile
 miext/rootless/Makefile
-miext/rootless/safeAlpha/Makefile
 miext/rootless/accel/Makefile
 os/Makefile
 randr/Makefile
diff --git a/hw/xquartz/xpr/Makefile.am b/hw/xquartz/xpr/Makefile.am
index ae1b192..b4d67c7 100644
--- a/hw/xquartz/xpr/Makefile.am
+++ b/hw/xquartz/xpr/Makefile.am
@@ -4,8 +4,7 @@ AM_CFLAGS =  $(XSERVER_CFLAGS) $(DIX_CFLAGS)
 AM_CPPFLAGS = \
 	-I$(srcdir) -I$(srcdir)/.. \
 	-I$(top_srcdir)/miext \
-	-I$(top_srcdir)/miext/rootless \
-	-I$(top_srcdir)/miext/rootless/safeAlpha
+	-I$(top_srcdir)/miext/rootless
 
 Xquartz_SOURCES = \
 	appledri.c \
@@ -41,7 +40,6 @@ Xquartz_LDADD = \
 	$(top_builddir)/record/librecord.la \
 	$(top_builddir)/XTrap/libxtrap.la \
 	$(top_builddir)/miext/rootless/librootless.la \
-	$(top_builddir)/miext/rootless/safeAlpha/libsafeAlpha.la \
 	$(top_builddir)/miext/rootless/accel/librlAccel.la \
 	$(DARWIN_LIBS) $(XSERVER_LIBS) $(XSERVER_SYS_LIBS) -lXplugin
 
diff --git a/hw/xquartz/xpr/xprScreen.c b/hw/xquartz/xpr/xprScreen.c
index e4e1fda..db36403 100644
--- a/hw/xquartz/xpr/xprScreen.c
+++ b/hw/xquartz/xpr/xprScreen.c
@@ -37,7 +37,6 @@
 #include "pseudoramiX.h"
 #include "darwin.h"
 #include "rootless.h"
-#include "safeAlpha/safeAlpha.h"
 #include "dri.h"
 #include "globals.h"
 #include "Xplugin.h"
@@ -341,15 +340,6 @@ xprAddScreen(int index, ScreenPtr pScreen)
 static Bool
 xprSetupScreen(int index, ScreenPtr pScreen)
 {
-    // Add alpha protecting replacements for fb screen functions
-
-#ifdef RENDER
-    {
-        PictureScreenPtr ps = GetPictureScreen(pScreen);
-        ps->Composite = SafeAlphaComposite;
-    }
-#endif /* RENDER */
-
     // Initialize accelerated rootless drawing
     // Note that this must be done before DamageSetup().
     RootlessAccelInit(pScreen);
diff --git a/miext/rootless/Makefile.am b/miext/rootless/Makefile.am
index aa8528e..dc85170 100644
--- a/miext/rootless/Makefile.am
+++ b/miext/rootless/Makefile.am
@@ -1,7 +1,7 @@
 AM_CFLAGS = $(DIX_CFLAGS) $(XSERVER_CFLAGS)
 AM_CPPFLAGS = -I$(top_srcdir)/hw/xfree86/os-support
 
-SUBDIRS = safeAlpha accel
+SUBDIRS = accel
 
 noinst_LTLIBRARIES = librootless.la
 librootless_la_SOURCES = \
diff --git a/miext/rootless/safeAlpha/Makefile.am b/miext/rootless/safeAlpha/Makefile.am
deleted file mode 100644
index a22afb6..0000000
--- a/miext/rootless/safeAlpha/Makefile.am
+++ /dev/null
@@ -1,7 +0,0 @@
-AM_CFLAGS = $(DIX_CFLAGS) $(XSERVER_CFLAGS)
-AM_CPPFLAGS = -I$(srcdir)/.. -I$(top_srcdir)/hw/xfree86/os-support
-
-noinst_LTLIBRARIES = libsafeAlpha.la
-libsafeAlpha_la_SOURCES = safeAlphaPicture.c
-
-EXTRA_DIST = safeAlpha.h
diff --git a/miext/rootless/safeAlpha/safeAlpha.h b/miext/rootless/safeAlpha/safeAlpha.h
deleted file mode 100644
index 9b9b39c..0000000
--- a/miext/rootless/safeAlpha/safeAlpha.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Replacement functions to protect the alpha channel
- */
-/*
- * Copyright (c) 2002-2003 Torrey T. Lyons. All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-
-#ifndef _SAFEALPHA_H
-#define _SAFEALPHA_H
-
-#include "picturestr.h"
-
-#ifdef RENDER
-void
-SafeAlphaComposite(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst,
-                   INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask,
-                   INT16 xDst, INT16 yDst, CARD16 width, CARD16 height);
-#endif /* RENDER */
-
-#endif /* _SAFEALPHA_H */
diff --git a/miext/rootless/safeAlpha/safeAlphaPicture.c b/miext/rootless/safeAlpha/safeAlphaPicture.c
deleted file mode 100644
index 8f66315..0000000
--- a/miext/rootless/safeAlpha/safeAlphaPicture.c
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Support for RENDER extension while protecting the alpha channel
- */
-/*
- * Copyright (c) 2002-2003 Torrey T. Lyons. All Rights Reserved.
- * Copyright (c) 2002 Apple Computer, Inc. All Rights reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-/* This file is largely based on fbcompose.c and fbpict.c, which contain
- * the following copyright:
- *
- * Copyright © 2000 Keith Packard, member of The XFree86 Project, Inc.
- */
-
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-#ifdef RENDER
-
-#include <stddef.h> /* For NULL */
-#include "fb.h"
-#include "picturestr.h"
-#include "mipict.h"
-#include "fbpict.h"
-#include "safeAlpha.h"
-#include "rootlessCommon.h"
-# define mod(a,b)	((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b))
-
-/* Optimized version of fbCompositeSolidMask_nx8x8888 */
-void
-SafeAlphaCompositeSolidMask_nx8x8888(
-    CARD8      op,
-    PicturePtr pSrc,
-    PicturePtr pMask,
-    PicturePtr pDst,
-    INT16      xSrc,
-    INT16      ySrc,
-    INT16      xMask,
-    INT16      yMask,
-    INT16      xDst,
-    INT16      yDst,
-    CARD16     width,
-    CARD16     height)
-{
-    CARD32	src, srca;
-    CARD32	*dstLine, *dst, d, dstMask;
-    CARD8	*maskLine, *mask, m;
-    FbStride	dstStride, maskStride;
-    CARD16	w;
-
-    fbComposeGetSolid(pSrc, src, pDst->format);
-
-    dstMask = FbFullMask (pDst->pDrawable->depth);
-    srca = src >> 24;
-    if (src == 0)
-	return;
-
-    fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1);
-    fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1);
-
-    if (dstMask == FB_ALLONES && pDst->pDrawable->bitsPerPixel == 32 &&
-        width * height > rootless_CompositePixels_threshold &&
-        SCREENREC(pDst->pDrawable->pScreen)->imp->CompositePixels)
-    {
-	void *srcp[2], *destp[2];
-	unsigned int dest_rowbytes[2];
-	unsigned int fn;
-
-	srcp[0] = &src; srcp[1] = &src;
-	/* null rowbytes pointer means use first value as a constant */
-	destp[0] = dstLine; destp[1] = dstLine;
-	dest_rowbytes[0] = dstStride * 4; dest_rowbytes[1] = dest_rowbytes[0];
-	fn = RL_COMPOSITE_FUNCTION(RL_COMPOSITE_OVER, RL_DEPTH_ARGB8888,
-                                   RL_DEPTH_A8, RL_DEPTH_ARGB8888);
-
-	if (SCREENREC(pDst->pDrawable->pScreen)->imp->CompositePixels(
-                width, height, fn, srcp, NULL,
-                maskLine, maskStride,
-                destp, dest_rowbytes) == Success)
-	{
-	    return;
-	}
-    }
-
-    while (height--)
-    {
-	dst = dstLine;
-	dstLine += dstStride;
-	mask = maskLine;
-	maskLine += maskStride;
-	w = width;
-
-	while (w--)
-	{
-	    m = *mask++;
-	    if (m == 0xff)
-	    {
-		if (srca == 0xff)
-		    *dst = src & dstMask;
-		else
-		    *dst = fbOver (src, *dst) & dstMask;
-	    }
-	    else if (m)
-	    {
-		d = fbIn (src, m);
-		*dst = fbOver (d, *dst) & dstMask;
-	    }
-	    dst++;
-	}
-    }
-}
-
-void
-SafeAlphaComposite (CARD8           op,
-                    PicturePtr      pSrc,
-                    PicturePtr      pMask,
-                    PicturePtr      pDst,
-                    INT16           xSrc,
-                    INT16           ySrc,
-                    INT16           xMask,
-                    INT16           yMask,
-                    INT16           xDst,
-                    INT16           yDst,
-                    CARD16          width,
-                    CARD16          height)
-{
-  if (!pSrc) {
-    ErrorF("SafeAlphaComposite: pSrc must not be null!\n");
-    return;
-  }
-
-  if (!pDst) {
-    ErrorF("SafeAlphaComposite: pDst must not be null!\n");
-    return;
-  }
-  
-  int oldDepth = pDst->pDrawable->depth;
-  int oldFormat = pDst->format;
-    
-  /*
-   * We can use the more optimized fbpict code, but it sets bits above
-   * the depth to zero. Temporarily adjust destination depth if needed.
-   */
-  if (pDst->pDrawable->type == DRAWABLE_WINDOW
-        && pDst->pDrawable->depth == 24
-      && pDst->pDrawable->bitsPerPixel == 32)
-    {
-      pDst->pDrawable->depth = 32;
-    }
-    
-  /* For rootless preserve the alpha in x8r8g8b8 which really is
-   * a8r8g8b8
-   */
-  if (oldFormat == PICT_x8r8g8b8)
-    {
-      pDst->format = PICT_a8r8g8b8;
-    }
-    
-  if (pSrc->pDrawable && pMask && pMask->pDrawable &&
-        !pSrc->transform && !pMask->transform &&
-        !pSrc->alphaMap && !pMask->alphaMap &&
-        !pMask->repeat && !pMask->componentAlpha && !pDst->alphaMap &&
-        pMask->format == PICT_a8 &&
-       pSrc->repeatType == RepeatNormal && 
-        pSrc->pDrawable->width == 1 &&
-        pSrc->pDrawable->height == 1 &&
-      (pDst->format == PICT_a8r8g8b8 ||
-         pDst->format == PICT_x8r8g8b8 ||
-         pDst->format == PICT_a8b8g8r8 ||
-       pDst->format == PICT_x8b8g8r8))
-    {
-      fbWalkCompositeRegion (op, pSrc, pMask, pDst,
-			     xSrc, ySrc, xMask, yMask, xDst, yDst,
-			     width, height,
-			     TRUE /* srcRepeat */,
-			     FALSE /* maskRepeat */,
-			     SafeAlphaCompositeSolidMask_nx8x8888);
-    }
-  else
-    {
-      fbComposite (op, pSrc, pMask, pDst,
-		   xSrc, ySrc, xMask, yMask, xDst, yDst, width, height);
-    }
-
-  pDst->pDrawable->depth = oldDepth;
-  pDst->format = oldFormat;
-}
-
-#endif /* RENDER */
commit 87c64cfd6901083da5a9375d0bde65691d374b5b
Author: Jeremy Huddleston <jeremy at tifa.local>
Date:   Fri Mar 14 17:31:54 2008 -0700

    =?utf-8?q?Apple:=20Xserver=20half=20of=20the=20Expos=C3=A9=20bug-fix=20(requires=20updated=20libXplugin=20from=20Apple...=20coming=20with=202.2)
    
    =20(cherry=20picked=20from=20commit=2037be23e8c1d8e5c7a1157e9d66ef3f30a4c472c5)?=
    MIME-Version: 1.0
    Content-Type: text/plain; charset=utf-8
    Content-Transfer-Encoding: 8bit

diff --git a/hw/xquartz/X11Application.m b/hw/xquartz/X11Application.m
index be5511d..1cf992d 100644
--- a/hw/xquartz/X11Application.m
+++ b/hw/xquartz/X11Application.m
@@ -320,6 +320,8 @@ static void message_kit_thread (SEL selector, NSObject *arg) {
     SetFrontProcess(&psn);
 
     QuartzMessageServerThread(kXDarwinBringAllToFront, 0);
+    ProcessSerialNumber psn = { 0, kCurrentProcess };
+    SetFrontProcess(&psn);
 }
 
 - (void) set_can_quit:(NSNumber *)state {
commit 3bbd77ff98478153afe3251de9ba11d757218213
Author: Eamon Walsh <ewalsh at tycho.nsa.gov>
Date:   Thu Mar 20 20:03:02 2008 -0400

    XSELinux: Do a check for whether background "None" is allowed.

diff --git a/Xext/xselinux.c b/Xext/xselinux.c
index 3035898..17ce7af 100644
--- a/Xext/xselinux.c
+++ b/Xext/xselinux.c
@@ -1026,6 +1026,13 @@ SELinuxResource(CallbackListPtr *pcbl, pointer unused, pointer calldata)
     rc = SELinuxDoCheck(subj, obj, class, access_mode, &auditdata);
     if (rc != Success)
 	rec->status = rc;
+
+    /* Perform the background none check on windows */
+    if (access_mode & DixCreateAccess && rec->rtype == RT_WINDOW) {
+	rc = SELinuxDoCheck(subj, obj, class, DixBlendAccess, &auditdata);
+	if (rc != Success)
+	    ((WindowPtr)rec->res)->forcedBG = TRUE;
+    }
 }
 
 static void
commit e323bb426ce8a072d119cb2720b773241259c137
Author: Eamon Walsh <ewalsh at tycho.nsa.gov>
Date:   Thu Mar 20 19:42:09 2008 -0400

    XSELinux: Correctly handle some permission bits that are used more than once.

diff --git a/Xext/xselinux.c b/Xext/xselinux.c
index 18c6526..3035898 100644
--- a/Xext/xselinux.c
+++ b/Xext/xselinux.c
@@ -152,6 +152,12 @@ static struct security_class_mapping map[] = {
     { NULL }
 };
 
+/* x_resource "read" bits from the list above */
+#define SELinuxReadMask (DixReadAccess|DixGetAttrAccess|DixListPropAccess| \
+			 DixGetPropAccess|DixGetFocusAccess|DixListAccess| \
+			 DixShowAccess|DixBlendAccess|DixReceiveAccess| \
+			 DixUseAccess|DixDebugAccess)
+
 /* forward declarations */
 static void SELinuxScreen(CallbackListPtr *, pointer, pointer);
 
@@ -853,6 +859,7 @@ SELinuxSelection(CallbackListPtr *pcbl, pointer unused, pointer calldata)
     SELinuxObjectRec *obj, *data;
     Selection *pSel = *rec->ppSel;
     Atom name = pSel->selection;
+    Mask access_mode = rec->access_mode;
     SELinuxAuditRec auditdata = { .client = rec->client, .selection = name };
     security_id_t tsid;
     int rc;
@@ -861,11 +868,12 @@ SELinuxSelection(CallbackListPtr *pcbl, pointer unused, pointer calldata)
     obj = dixLookupPrivate(&pSel->devPrivates, objectKey);
 
     /* If this is a new object that needs labeling, do it now */
-    if (rec->access_mode & DixCreateAccess) {
+    if (access_mode & DixCreateAccess) {
 	sidput(obj->sid);
 	rc = SELinuxSelectionToSID(name, subj, &obj->sid, &obj->poly);
 	if (rc != Success)
 	    obj->sid = unlabeled_sid;
+	access_mode = DixSetAttrAccess;
     }
     /* If this is a polyinstantiated object, find the right instance */
     else if (obj->poly) {
@@ -890,13 +898,13 @@ SELinuxSelection(CallbackListPtr *pcbl, pointer unused, pointer calldata)
     }
 
     /* Perform the security check */
-    rc = SELinuxDoCheck(subj, obj, SECCLASS_X_SELECTION, rec->access_mode,
+    rc = SELinuxDoCheck(subj, obj, SECCLASS_X_SELECTION, access_mode,
 			&auditdata);
     if (rc != Success)
 	rec->status = rc;
 
     /* Label the content (advisory only) */
-    if (rec->access_mode & DixSetAttrAccess) {
+    if (access_mode & DixSetAttrAccess) {
 	data = dixLookupPrivate(&pSel->devPrivates, dataKey);
 	sidput(data->sid);
 	if (subj->sel_create_sid)
@@ -976,6 +984,7 @@ SELinuxResource(CallbackListPtr *pcbl, pointer unused, pointer calldata)
     SELinuxSubjectRec *subj;
     SELinuxObjectRec *obj;
     SELinuxAuditRec auditdata = { .client = rec->client };
+    Mask access_mode = rec->access_mode;
     PrivateRec **privatePtr;
     security_class_t class;
     int rc, offset;
@@ -997,7 +1006,7 @@ SELinuxResource(CallbackListPtr *pcbl, pointer unused, pointer calldata)
     }
 
     /* If this is a new object that needs labeling, do it now */
-    if (rec->access_mode & DixCreateAccess && offset >= 0) {
+    if (access_mode & DixCreateAccess && offset >= 0) {
 	rc = SELinuxLabelResource(rec, subj, obj, class);
 	if (rc != Success) {
 	    rec->status = rc;
@@ -1005,10 +1014,16 @@ SELinuxResource(CallbackListPtr *pcbl, pointer unused, pointer calldata)
 	}
     }
 
+    /* Collapse generic resource permissions down to read/write */
+    if (class == SECCLASS_X_RESOURCE) {
+	access_mode = !!(rec->access_mode & SELinuxReadMask); /* rd */
+	access_mode |= !!(rec->access_mode & ~SELinuxReadMask) << 1; /* wr */
+    }
+
     /* Perform the security check */
     auditdata.restype = rec->rtype;
     auditdata.id = rec->id;
-    rc = SELinuxDoCheck(subj, obj, class, rec->access_mode, &auditdata);
+    rc = SELinuxDoCheck(subj, obj, class, access_mode, &auditdata);
     if (rc != Success)
 	rec->status = rc;
 }
commit da973e962d09854b571320dee7dd9569060bc39e
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Thu Mar 20 09:18:29 2008 -0400

    Fix RandR 1.2 driver interface conversion of two colour cursors to ARGB
    
    This patch (and not setting HARDWARE_CURSOR_BIT_ORDER_MSBFIRST on big endian
    platforms) fixes it for me with the radeon driver and doesn't break intel.
    
    Correct patch this time :)

diff --git a/hw/xfree86/modes/xf86Cursors.c b/hw/xfree86/modes/xf86Cursors.c
index 08cf78d..57cfcb6 100644
--- a/hw/xfree86/modes/xf86Cursors.c
+++ b/hw/xfree86/modes/xf86Cursors.c
@@ -137,7 +137,8 @@ cursor_bitpos (int flags, int x, Bool mask)
 	mask = !mask;
     if (flags & HARDWARE_CURSOR_NIBBLE_SWAPPED)
 	x = (x & ~3) | (3 - (x & 3));
-    if (flags & HARDWARE_CURSOR_BIT_ORDER_MSBFIRST)
+    if (((flags & HARDWARE_CURSOR_BIT_ORDER_MSBFIRST) == 0) ==
+	(X_BYTE_ORDER == X_BIG_ENDIAN))
 	x = (x & ~7) | (7 - (x & 7));
     if (flags & HARDWARE_CURSOR_SOURCE_MASK_INTERLEAVE_1)
 	x = (x << 1) + mask;
commit f8c1eb29e28818895d744c4e1d6897353d51790b
Author: Alex Deucher <alex at cube.(none)>
Date:   Thu Mar 20 09:14:41 2008 -0400

    Revert "Fix RandR 1.2 driver interface conversion of two colour cursors to ARGB"
    
    This reverts commit 267352579612155adfd4743432d6569b2cdeebde.
    
    Pushed the wrong patch.

diff --git a/hw/xfree86/modes/xf86Cursors.c b/hw/xfree86/modes/xf86Cursors.c
index 4fe94f3..08cf78d 100644
--- a/hw/xfree86/modes/xf86Cursors.c
+++ b/hw/xfree86/modes/xf86Cursors.c
@@ -137,9 +137,7 @@ cursor_bitpos (int flags, int x, Bool mask)
 	mask = !mask;
     if (flags & HARDWARE_CURSOR_NIBBLE_SWAPPED)
 	x = (x & ~3) | (3 - (x & 3));
-#if X_BYTE_ORDER == X_LITTLE_ENDIAN
     if (flags & HARDWARE_CURSOR_BIT_ORDER_MSBFIRST)
-#endif
 	x = (x & ~7) | (7 - (x & 7));
     if (flags & HARDWARE_CURSOR_SOURCE_MASK_INTERLEAVE_1)
 	x = (x << 1) + mask;
commit 267352579612155adfd4743432d6569b2cdeebde
Author: Michel Dänzer <michel at tungstengraphics.com>
Date:   Wed Mar 19 19:12:37 2008 -0400

    Fix RandR 1.2 driver interface conversion of two colour cursors to ARGB
    
    See bug 11796

diff --git a/hw/xfree86/modes/xf86Cursors.c b/hw/xfree86/modes/xf86Cursors.c
index 08cf78d..4fe94f3 100644
--- a/hw/xfree86/modes/xf86Cursors.c
+++ b/hw/xfree86/modes/xf86Cursors.c
@@ -137,7 +137,9 @@ cursor_bitpos (int flags, int x, Bool mask)
 	mask = !mask;
     if (flags & HARDWARE_CURSOR_NIBBLE_SWAPPED)
 	x = (x & ~3) | (3 - (x & 3));
+#if X_BYTE_ORDER == X_LITTLE_ENDIAN
     if (flags & HARDWARE_CURSOR_BIT_ORDER_MSBFIRST)
+#endif
 	x = (x & ~7) | (7 - (x & 7));
     if (flags & HARDWARE_CURSOR_SOURCE_MASK_INTERLEAVE_1)
 	x = (x << 1) + mask;
commit 060a99444ee25a684b0ab9b4819bf8e855aea2d8
Author: Alan Coopersmith <alan.coopersmith at sun.com>
Date:   Wed Mar 19 16:04:16 2008 -0700

    Make Xevie private symbol names less generic
    
    Makes it easier to figure out what you're seeing in the stack trace
    instead of wondering where in the server "ProcSend" is.

diff --git a/Xext/xevie.c b/Xext/xevie.c
index f36ead4..5e20bd9 100644
--- a/Xext/xevie.c
+++ b/Xext/xevie.c
@@ -63,11 +63,13 @@ extern Bool noXkbExtension;
 #endif
 extern int    xeviegrabState;
 
-static int		ProcDispatch (register ClientPtr client), SProcDispatch (register ClientPtr client);
-static void		ResetProc (ExtensionEntry *extEntry);
+static DISPATCH_PROC(ProcXevieDispatch);
+static DISPATCH_PROC(SProcXevieDispatch);
 
-static unsigned char	ReqCode = 0;
-static int		ErrorBase;
+static void		XevieResetProc (ExtensionEntry *extEntry);
+
+static unsigned char	XevieReqCode = 0;
+static int		XevieErrorBase;
 
 int			xevieFlag = 0;
 int	 		xevieClientIndex = 0;
@@ -77,7 +79,7 @@ Mask			xevieMask = 0;
 int       		xevieEventSent = 0;
 int			xevieKBEventSent = 0;
 static DevPrivateKey    xevieDevicePrivateKey = &xevieDevicePrivateKey;
-static Bool                     xevieModifiersOn = FALSE;
+static Bool             xevieModifiersOn = FALSE;
 
 #define XEVIEINFO(dev)  ((xevieDeviceInfoPtr) \
     dixLookupPrivate(&(dev)->devPrivates, xevieDevicePrivateKey))
@@ -108,11 +110,6 @@ typedef struct {
 static xevieKeycQueueRec keycq[KEYC_QUEUE_SIZE] = {{0, NULL}};
 static int keycqHead = 0, keycqTail = 0;
 
-static int              ProcDispatch (ClientPtr), SProcDispatch (ClientPtr);
-static void             ResetProc (ExtensionEntry*);
-
-static int              ErrorBase;
-
 static Bool XevieStart(void);
 static void XevieEnd(int clientIndex);
 static void XevieClientStateCallback(CallbackListPtr *pcbl, pointer nulldata,
@@ -140,23 +137,23 @@ XevieExtensionInit (void)
     if ((extEntry = AddExtension (XEVIENAME,
 				0,
 				XevieNumberErrors,
-				ProcDispatch,
-				SProcDispatch,
-				ResetProc,
+				ProcXevieDispatch,
+				SProcXevieDispatch,
+				XevieResetProc,
 				StandardMinorOpcode))) {
-	ReqCode = (unsigned char)extEntry->base;
-	ErrorBase = extEntry->errorBase;
+	XevieReqCode = (unsigned char)extEntry->base;
+	XevieErrorBase = extEntry->errorBase;
     }
 }
 
 /*ARGSUSED*/
 static 
-void ResetProc (ExtensionEntry *extEntry)
+void XevieResetProc (ExtensionEntry *extEntry)
 {
 }
 
 static 
-int ProcQueryVersion (register ClientPtr client)
+int ProcXevieQueryVersion (register ClientPtr client)
 {
     xXevieQueryVersionReply rep;
 
@@ -171,7 +168,7 @@ int ProcQueryVersion (register ClientPtr client)
 }
 
 static
-int ProcStart (register ClientPtr client)
+int ProcXevieStart (register ClientPtr client)
 {
     xXevieStartReply rep;
 
@@ -212,7 +209,7 @@ int ProcStart (register ClientPtr client)
 }
 
 static
-int ProcEnd (register ClientPtr client)
+int ProcXevieEnd (register ClientPtr client)
 {
     xXevieEndReply rep;
 
@@ -233,7 +230,7 @@ int ProcEnd (register ClientPtr client)
 }
 
 static
-int ProcSend (register ClientPtr client)
+int ProcXevieSend (register ClientPtr client)
 {
     REQUEST (xXevieSendReq);
     xXevieSendReply rep;
@@ -281,7 +278,7 @@ int ProcSend (register ClientPtr client)
 }
 
 static
-int ProcSelectInput (register ClientPtr client)
+int ProcXevieSelectInput (register ClientPtr client)
 {
     REQUEST (xXevieSelectInputReq);
     xXevieSelectInputReply rep;
@@ -299,28 +296,28 @@ int ProcSelectInput (register ClientPtr client)
 }
 
 static 
-int ProcDispatch (register ClientPtr client)
+int ProcXevieDispatch (register ClientPtr client)
 {
     REQUEST (xReq);
     switch (stuff->data)
     {
     case X_XevieQueryVersion:
-	return ProcQueryVersion (client);
+	return ProcXevieQueryVersion (client);
     case X_XevieStart:
-	return ProcStart (client);
+	return ProcXevieStart (client);
     case X_XevieEnd:
-	return ProcEnd (client);
+	return ProcXevieEnd (client);
     case X_XevieSend:
-	return ProcSend (client);
+	return ProcXevieSend (client);
     case X_XevieSelectInput:
-	return ProcSelectInput(client);
+	return ProcXevieSelectInput(client);
     default:
 	return BadRequest;
     }
 }
 
 static 
-int SProcQueryVersion (register ClientPtr client)
+int SProcXevieQueryVersion (register ClientPtr client)
 {
     register int n;
 
@@ -329,11 +326,11 @@ int SProcQueryVersion (register ClientPtr client)
     REQUEST_SIZE_MATCH (xXevieQueryVersionReq);
     swaps (&stuff->client_major_version, n);
     swaps (&stuff->client_minor_version, n);
-    return ProcQueryVersion(client);
+    return ProcXevieQueryVersion(client);
 }
 
 static 
-int SProcStart (ClientPtr client)
+int SProcXevieStart (ClientPtr client)
 {
     register int n;
 
@@ -341,11 +338,11 @@ int SProcStart (ClientPtr client)
     swaps (&stuff->length, n);
     REQUEST_SIZE_MATCH (xXevieStartReq);
     swapl (&stuff->screen, n);
-    return ProcStart (client);
+    return ProcXevieStart (client);
 }
 
 static 
-int SProcEnd (ClientPtr client)
+int SProcXevieEnd (ClientPtr client)
 {
     register int n;
 
@@ -353,11 +350,11 @@ int SProcEnd (ClientPtr client)
     swaps (&stuff->length, n);
     REQUEST_SIZE_MATCH (xXevieEndReq);
     swapl (&stuff->cmap, n);
-    return ProcEnd (client);
+    return ProcXevieEnd (client);
 }
 
 static
-int SProcSend (ClientPtr client)
+int SProcXevieSend (ClientPtr client)
 {
     register int n;
     xEvent eventT;
@@ -375,11 +372,11 @@ int SProcSend (ClientPtr client)
     (*proc)(&stuff->event, &eventT);
     stuff->event = eventT;
     
-    return ProcSend (client);
+    return ProcXevieSend (client);
 }
 
 static
-int SProcSelectInput (ClientPtr client)
+int SProcXevieSelectInput (ClientPtr client)
 {
     register int n;
 
@@ -387,26 +384,26 @@ int SProcSelectInput (ClientPtr client)
     swaps (&stuff->length, n);
     REQUEST_SIZE_MATCH (xXevieSelectInputReq);
     swapl (&stuff->event_mask, n);
-    return ProcSelectInput (client);
+    return ProcXevieSelectInput (client);
 }
 
 
 static 
-int SProcDispatch (register ClientPtr client)
+int SProcXevieDispatch (register ClientPtr client)
 {
     REQUEST(xReq);
     switch (stuff->data)
     {
     case X_XevieQueryVersion:
-	return SProcQueryVersion (client);
+	return SProcXevieQueryVersion (client);
     case X_XevieStart:
-	return SProcStart (client);
+	return SProcXevieStart (client);
     case X_XevieEnd:
-	return SProcEnd (client);
+	return SProcXevieEnd (client);
     case X_XevieSend:
-	return SProcSend (client);
+	return SProcXevieSend (client);
     case X_XevieSelectInput:
-	return SProcSelectInput(client);
+	return SProcXevieSelectInput(client);
     default:
 	return BadRequest;
     }
commit f37046984d7839faefa4d716624e4a85ddde9634
Author: Alan Coopersmith <alan.coopersmith at sun.com>
Date:   Wed Mar 19 14:06:53 2008 -0700

    Xevie cleanups, byteswapping fixes & request length check fixes

diff --git a/Xext/xevie.c b/Xext/xevie.c
index ea409f1..f36ead4 100644
--- a/Xext/xevie.c
+++ b/Xext/xevie.c
@@ -147,8 +147,6 @@ XevieExtensionInit (void)
 	ReqCode = (unsigned char)extEntry->base;
 	ErrorBase = extEntry->errorBase;
     }
-
-    /* PC servers initialize the desktop colors (citems) here! */
 }
 
 /*ARGSUSED*/
@@ -218,6 +216,8 @@ int ProcEnd (register ClientPtr client)
 {
     xXevieEndReply rep;
 
+    REQUEST_SIZE_MATCH (xXevieEndReq);
+    
     if (xevieFlag) {
         if (client->index != xevieClientIndex)
             return BadAccess;
@@ -240,6 +240,8 @@ int ProcSend (register ClientPtr client)
     xEvent *xE;
     static unsigned char lastDetail = 0, lastType = 0;
 
+    REQUEST_SIZE_MATCH (xXevieSendReq);
+    
     if (client->index != xevieClientIndex)
         return BadAccess;
 
@@ -284,10 +286,12 @@ int ProcSelectInput (register ClientPtr client)
     REQUEST (xXevieSelectInputReq);
     xXevieSelectInputReply rep;
 
+    REQUEST_SIZE_MATCH (xXevieSelectInputReq);
+
     if (client->index != xevieClientIndex)
         return BadAccess;
 
-    xevieMask = (long)stuff->event_mask;
+    xevieMask = stuff->event_mask;
     rep.type = X_Reply;
     rep.sequence_number = client->sequence;
     WriteToClient (client, sizeof (xXevieSelectInputReply), (char *)&rep);
@@ -321,7 +325,10 @@ int SProcQueryVersion (register ClientPtr client)
     register int n;
 
     REQUEST(xXevieQueryVersionReq);
-    swaps(&stuff->length, n);
+    swaps (&stuff->length, n);
+    REQUEST_SIZE_MATCH (xXevieQueryVersionReq);
+    swaps (&stuff->client_major_version, n);
+    swaps (&stuff->client_minor_version, n);
     return ProcQueryVersion(client);
 }
 
@@ -332,8 +339,8 @@ int SProcStart (ClientPtr client)
 
     REQUEST (xXevieStartReq);
     swaps (&stuff->length, n);
+    REQUEST_SIZE_MATCH (xXevieStartReq);
     swapl (&stuff->screen, n);
-    REQUEST_AT_LEAST_SIZE (xXevieStartReq);
     return ProcStart (client);
 }
 
@@ -344,8 +351,8 @@ int SProcEnd (ClientPtr client)
 
     REQUEST (xXevieEndReq);
     swaps (&stuff->length, n);
-    REQUEST_AT_LEAST_SIZE (xXevieEndReq);
-    swapl(&stuff->cmap, n);
+    REQUEST_SIZE_MATCH (xXevieEndReq);
+    swapl (&stuff->cmap, n);
     return ProcEnd (client);
 }
 
@@ -353,11 +360,21 @@ static
 int SProcSend (ClientPtr client)
 {
     register int n;
+    xEvent eventT;
+    EventSwapPtr proc;
 
     REQUEST (xXevieSendReq);
     swaps (&stuff->length, n);
-    REQUEST_AT_LEAST_SIZE (xXevieSendReq);
-    swapl(&stuff->event, n);
+    REQUEST_SIZE_MATCH (xXevieSendReq);
+    swapl (&stuff->dataType, n);
+
+    /* Swap event */
+    proc = EventSwapVector[stuff->event.u.u.type & 0177];
+    if (!proc ||  proc == NotImplemented) /* no swapping proc; invalid event type? */
+	return (BadValue);
+    (*proc)(&stuff->event, &eventT);
+    stuff->event = eventT;
+    
     return ProcSend (client);
 }
 
@@ -368,8 +385,8 @@ int SProcSelectInput (ClientPtr client)
 
     REQUEST (xXevieSelectInputReq);
     swaps (&stuff->length, n);
-    REQUEST_AT_LEAST_SIZE (xXevieSelectInputReq);
-    swapl(&stuff->event_mask, n);
+    REQUEST_SIZE_MATCH (xXevieSelectInputReq);
+    swapl (&stuff->event_mask, n);
     return ProcSelectInput (client);
 }
 


More information about the xorg-commit mailing list