Release 941017

Sun Oct 16 13:29:07 1994  Alexandre Julliard  (julliard@lamisun.epfl.ch)

	* [controls/button.c]
	Implemented WM_GETDLGCODE, WM_SETFONT, BM_SETSTYLE, BM_SETCHECK,
	BM_SETSTATE.
	Implemented default button painting.
	Optimised redrawing.
	Fixed owner-draw buttons.

	* [controls/static.c]
	Implemented WM_SETFONT.
	A few optimisations in painting code.
	Bug fix for SS_SIMPLE controls.

	* [if1632/callback.c]
	Preliminary GetCodeHandle().

	* [if1632/gdi.spec]
	Changed 'pascal' to 'pascal16' everywhere it's needed.

	* [include/windows.h]
	Fixed a few data structures.

	* [memory/heap.c]
	Bug fix in HEAP_ReAlloc().

	* [misc/cursor.c]
	Fixed SetCursor().

	* [objects/bitblt.c]
	Fixed PatBlt() when using BLACKNESS or WHITENESS codes.

	* [objects/font.c]
	Better font mapping code.
	Implemented GetTextFace().

	* [objects/region.c]
	Bug fix in REGION_MakePixmap().
	Faster region copying.

	* [objects/text.c]
	Implemented ExtTextOut().
	Implemented DT_NOCLIP style for DrawText().

	* [windows/dc.c]
	Free the bitmap when deleting a memory DC.

	* [windows/dce.c]
	Added support for windows that have no associated X window.
	Implemented DCX_CLIPSIBLINGS and DCX_PARENTCLIP in GetDCEx().

	* [windows/defdlg.c]
	Implemented default push button handling and DM_SETDEFID.
	Implemented WM_NEXTDLGCTL.

	* [windows/dialog.c]
	Implemented default push button handling.
	Beginning of a keyboard interface in dialogs
	(does not really work yet).
	Fixed dialogs that use a special font.

	* [windows/event.c] [windows/focus.c]
	Added support for non-X windows.

	* [windows/graphics.c]
	Rewritten FloodFill() and implemented ExtFloodFill().

	* [windows/message.c]
	Cleaner hardware messages and X events handling.

	* [windows/defwnd.c] [windows/painting.c]
	Implemented WM_SETREDRAW.

	* [windows/win.c]
	Only create an X window for top-level windows, or for the desktop.
	Child windows now use their parent's drawable.

	* [windows/winpos.c]
	Beginning of support for non-X windows (still somewhat broken).
	Implemented *DeferWindowPos().

	* [*/Imakefile]
	Cleaned up some Imakefiles.
	Moved dc.c from windows/ to objects/.
	Moved cursor.c from misc/ to windows/.

Sun Oct 16 12:21:52 1994  Michael Patra <micky@marie.physik.tu-berlin.d400.de>

	* [include/debug.h]
	  [include/stddebug.h]
	  [*/*.c]
        Rewritten all the calls to printf for displaying debug-information
        (messages like "LoadImage: loading SOL (SOL.EXE)" etc.) 
        Added option "-debugmsg" to Wine. Example: "-debugmsg +all" will turn
        all these messages on, "-debugmsg -dll" will turn all messages 
	concerning DLLs off.

	* [controls/combo.c]
	Added some handling for combo controls with ownerdraw-styles
        (just creating and passing the necessary messages to the 
	corresponding listbox control; the edit-control needs to be
	replaced with something else).

	* [controls/edit.c]
	  [windows/dialog.c]
	Added support for use of global heap memory in dialogs with 
	edit controls.

	* [controls/listbox.c]
	Added support for item data.
	ListBoxInsertString(): Fixed bug for elements which are not inserted
	after the currently last element.
	
	* [misc/dos_fs.c]
	  [miscemu/int21.c]
	DOS_ValidDirectory(): Checks whether a given string is in fact the
	valid name of a directory.

Sat Oct 15 17:35:00 PDT 1994		<martin@cs.csufresno.edu>

	* [Imakefile]
	generate wine.sym after creating wine

	* [debugger/dbg.y]
	load "wine.sym" when entering debugger

	* [debugger/info.c]
	symbolic backtrace for 32-bit stack. Breaks 16-bit bt.

Sun Sep  25 12:00:00 PDT 1994   <martin@osiris.cs.csufresno.edu>

	* [rc/rc.y] [rc/rc.h] [rc/rc.l] [rc/winerc.c]
	Files created

Sun Sep 18 11:04:45 MET DST 1994          Dag Asheim (dash@ifi.uio.no)

	* [misc/spy.c]
	Exclude and Include no longer requires a terminating ';' to
	register the last component.

Thu Sep 15 23:10:09 MET DST 1994          Dag Asheim (dash@ifi.uio.no)

	* [Configure]
	Rewrote much of it.  Added capability to generate a wine.ini
	file.  Commented out the processor emulator options until that
	becomes interesting.  Gives a warning if it sees any *.rej
	files.  I hope I haven't assumed to much about the shell/OS so
	that it breaks under *BSD.

	* [misc/dos_fs.c]
	Removed/changed calls to ToUnix() (which calls tolower()) so
	that the part of the pathname which correspond with the drive
	letter on DOS no longer will be mapped to lowercase.  This
	means that it should be possible to have uppercase letters in
	the [drives] section of wine.ini.

	* [LICENSE]
	Cosmetic changes so that it displays better in the window you
	get from pressing "Credit_License" in the "About WINE" window.

Sun Aug 21 21:12:06 MET DST 1994	<erik@xs4all.nl>

	* [controls/menu.c]
	LoadMenu() moved to loader/resource.c.

	* [misc/main.c]
	Added stub for FileCDR().

	* [include/peexe.h]
	Added, from Eric's pe-test.

	* [include/resource.h]
	Added.

	* [loader/resources.c]
	Removed duplicated code in *Resource() functions.
	Moved NE-program specific functions into ne_image.c.
	Moved NE-fileformat functions to ne_resource.c.

	* [pe_image.c] [pe_resource.c]
	Added. Nothing implemented to run PE-executables, resource
	loading only.

	* [misc/file.c]
	Changed OpenFile() to use macros.

	* [misc/shell.c]
	Added NULL-ptr checks to ShellAbout().

	* [miscemu/int21.c]
	Fixed a few typos.

	* [miscemu/kernel.c]
	Added _DI = _DS, to put the caller's instance in DI. Doesn't
	work properly if caller changed DS :-(
diff --git a/BUGS b/BUGS
index b05477e..5ec13e3 100644
--- a/BUGS
+++ b/BUGS
@@ -1,8 +1,8 @@
 - EBP and ESP are sometimes corrupted while running 16-bit code.
 - Dialog Boxes created by WM_CREATE handler aren't visible
-- RegisterClass() with hbrBackground = COLOR_APPWORKSPACE+1 does not work.
 - MDI does not send WM_GETMINMAX message.
 - InitializeLoadedDLLs() can't init LZEXPAND.DLL. (cs:ip => 0:0)
 - LoadCursor does not correctly handle bitmap cursors
 - AllocCSToDSAlias() shouldn't alloc alias for the same segment multiple times.
 - Dialogs don't support resources which are referred to as integers.
+- grep for FIXME in the source files.
diff --git a/ChangeLog b/ChangeLog
index 1e09a06..0ec9eaa 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,194 @@
+Sun Oct 16 13:29:07 1994  Alexandre Julliard  (julliard@lamisun.epfl.ch)
+
+	* [controls/button.c]
+	Implemented WM_GETDLGCODE, WM_SETFONT, BM_SETSTYLE, BM_SETCHECK,
+	BM_SETSTATE.
+	Implemented default button painting.
+	Optimised redrawing.
+	Fixed owner-draw buttons.
+
+	* [controls/static.c]
+	Implemented WM_SETFONT.
+	A few optimisations in painting code.
+	Bug fix for SS_SIMPLE controls.
+
+	* [if1632/callback.c]
+	Preliminary GetCodeHandle().
+
+	* [if1632/gdi.spec]
+	Changed 'pascal' to 'pascal16' everywhere it's needed.
+
+	* [include/windows.h]
+	Fixed a few data structures.
+
+	* [memory/heap.c]
+	Bug fix in HEAP_ReAlloc().
+
+	* [misc/cursor.c]
+	Fixed SetCursor().
+
+	* [objects/bitblt.c]
+	Fixed PatBlt() when using BLACKNESS or WHITENESS codes.
+
+	* [objects/font.c]
+	Better font mapping code.
+	Implemented GetTextFace().
+
+	* [objects/region.c]
+	Bug fix in REGION_MakePixmap().
+	Faster region copying.
+
+	* [objects/text.c]
+	Implemented ExtTextOut().
+	Implemented DT_NOCLIP style for DrawText().
+
+	* [windows/dc.c]
+	Free the bitmap when deleting a memory DC.
+
+	* [windows/dce.c]
+	Added support for windows that have no associated X window.
+	Implemented DCX_CLIPSIBLINGS and DCX_PARENTCLIP in GetDCEx().
+
+	* [windows/defdlg.c]
+	Implemented default push button handling and DM_SETDEFID.
+	Implemented WM_NEXTDLGCTL.
+
+	* [windows/dialog.c]
+	Implemented default push button handling.
+	Beginning of a keyboard interface in dialogs
+	(does not really work yet).
+	Fixed dialogs that use a special font.
+
+	* [windows/event.c] [windows/focus.c]
+	Added support for non-X windows.
+
+	* [windows/graphics.c]
+	Rewritten FloodFill() and implemented ExtFloodFill().
+
+	* [windows/message.c]
+	Cleaner hardware messages and X events handling.
+
+	* [windows/defwnd.c] [windows/painting.c]
+	Implemented WM_SETREDRAW.
+
+	* [windows/win.c]
+	Only create an X window for top-level windows, or for the desktop.
+	Child windows now use their parent's drawable.
+
+	* [windows/winpos.c]
+	Beginning of support for non-X windows (still somewhat broken).
+	Implemented *DeferWindowPos().
+
+	* [*/Imakefile]
+	Cleaned up some Imakefiles.
+	Moved dc.c from windows/ to objects/.
+	Moved cursor.c from misc/ to windows/.
+
+Sun Oct 16 12:21:52 1994  Michael Patra <micky@marie.physik.tu-berlin.d400.de>
+
+	* [include/debug.h]
+	  [include/stddebug.h]
+	  [*/*.c]
+        Rewritten all the calls to printf for displaying debug-information
+        (messages like "LoadImage: loading SOL (SOL.EXE)" etc.) 
+        Added option "-debugmsg" to Wine. Example: "-debugmsg +all" will turn
+        all these messages on, "-debugmsg -dll" will turn all messages 
+	concerning DLLs off.
+
+	* [controls/combo.c]
+	Added some handling for combo controls with ownerdraw-styles
+        (just creating and passing the necessary messages to the 
+	corresponding listbox control; the edit-control needs to be
+	replaced with something else).
+
+	* [controls/edit.c]
+	  [windows/dialog.c]
+	Added support for use of global heap memory in dialogs with 
+	edit controls.
+
+	* [controls/listbox.c]
+	Added support for item data.
+	ListBoxInsertString(): Fixed bug for elements which are not inserted
+	after the currently last element.
+	
+	* [misc/dos_fs.c]
+	  [miscemu/int21.c]
+	DOS_ValidDirectory(): Checks whether a given string is in fact the
+	valid name of a directory.
+
+Sat Oct 15 17:35:00 PDT 1994		<martin@cs.csufresno.edu>
+
+	* [Imakefile]
+	generate wine.sym after creating wine
+
+	* [debugger/dbg.y]
+	load "wine.sym" when entering debugger
+
+	* [debugger/info.c]
+	symbolic backtrace for 32-bit stack. Breaks 16-bit bt.
+
+Sun Sep 18 11:04:45 MET DST 1994          Dag Asheim (dash@ifi.uio.no)
+
+	* [misc/spy.c]
+	Exclude and Include no longer requires a terminating ';' to
+	register the last component.
+
+Thu Sep 15 23:10:09 MET DST 1994          Dag Asheim (dash@ifi.uio.no)
+
+	* [Configure]
+	Rewrote much of it.  Added capability to generate a wine.ini
+	file.  Commented out the processor emulator options until that
+	becomes interesting.  Gives a warning if it sees any *.rej
+	files.  I hope I haven't assumed to much about the shell/OS so
+	that it breaks under *BSD.
+
+	* [misc/dos_fs.c]
+	Removed/changed calls to ToUnix() (which calls tolower()) so
+	that the part of the pathname which correspond with the drive
+	letter on DOS no longer will be mapped to lowercase.  This
+	means that it should be possible to have uppercase letters in
+	the [drives] section of wine.ini.
+
+	* [LICENSE]
+	Cosmetic changes so that it displays better in the window you
+	get from pressing "Credit_License" in the "About WINE" window.
+
+Sun Aug 21 21:12:06 MET DST 1994	<erik@xs4all.nl>
+
+	* [controls/menu.c]
+	LoadMenu() moved to loader/resource.c.
+
+	* [misc/main.c]
+	Added stub for FileCDR().
+
+	* [include/peexe.h]
+	Added, from Eric's pe-test.
+
+	* [include/resource.h]
+	Added.
+
+	* [loader/resources.c]
+	Removed duplicated code in *Resource() functions.
+	Moved NE-program specific functions into ne_image.c.
+	Moved NE-fileformat functions to ne_resource.c.
+
+	* [pe_image.c] [pe_resource.c]
+	Added. Nothing implemented to run PE-executables, resource
+	loading only.
+
+	* [misc/file.c]
+	Changed OpenFile() to use macros.
+
+	* [misc/shell.c]
+	Added NULL-ptr checks to ShellAbout().
+
+	* [miscemu/int21.c]
+	Fixed a few typos.
+
+	* [miscemu/kernel.c]
+	Added _DI = _DS, to put the caller's instance in DI. Doesn't
+	work properly if caller changed DS :-(
+
 ----------------------------------------------------------------------
 Thu Aug 25 15:24:36 EDT 1994            <jrichard@cs.uml.edu>
 
diff --git a/Configure b/Configure
index c2fee7d..9dc4e9e 100644
--- a/Configure
+++ b/Configure
@@ -1,30 +1,57 @@
 #! /bin/sh
+#
+# Configure script for wine
+
+: ${EDITOR:=vi}
+: ${PAGER:=more}
 
 ALLDEFINES=''
 
-echo
+# Ask question 'str' and sets 'var' reply (defaulting to 'def' on CR)
+prompt ()
+{
+	str="$1"
+	var="$2"
+	def="$3"
+
+	eval $var='$def'
+	echo
+	echo -n "$str [$def]? "
+	input=`head -1`  #  When using read, user must double all backslashes
+	if [ -n "$input" ]
+	then
+		eval $var='$input'
+	fi
+}
+
 echo -n 'Build Wine as emulator or library (E/L) [E]? '
 read input
 if [ "$input" = 'l' -o "$input" = 'L' ]
 then
-    WINELIB='#define WINELIB -DWINELIB'
-    ALLDEFINES="$ALLDEFINES -DWINELIB"
+	WINELIB='#define WINELIB -DWINELIB'
+	ALLDEFINES="$ALLDEFINES -DWINELIB"
 else
-    WINELIB=''
-    echo -n 'Use processor emulator (*DOES*NOT*WORK*YET*) (Y/N) [N]? '
-    read input
-    if [ "$input" = 'y' -o "$input" = 'Y' ]
-    then
-	PROCEMU='#define PROCEMU'
-	echo -n 'bochs directory [/usr/src/bochs]? '
-	read input
-	if [ "$input" = '' ]
-	then
-		ALLDEFINES="$ALLDEFINES -DPROC_EMU_DIR=/usr/src/bochs"
-	else
-		ALLDEFINES="$ALLDEFINES -DPROC_EMU_DIR="$input
-	fi
-    fi
+	WINELIB=''
+
+#	Commented out until the processor emulator starts to work.
+#
+#	echo
+#	echo -n 'Use processor emulator (*DOES*NOT*WORK*YET*) (Y/N) [N]? '
+#	read input
+#	if [ "$input" = 'y' -o "$input" = 'Y' ]
+#	then
+#		PROCEMU='#define PROCEMU'
+#		echo
+#		echo -n 'bochs directory [/usr/src/bochs]? '
+#		read input
+#		if [ "$input" = '' ]
+#		then
+#			ALLDEFINES="$ALLDEFINES -DPROC_EMU_DIR=/usr/src/bochs"
+#		else
+#			ALLDEFINES="$ALLDEFINES -DPROC_EMU_DIR="$input
+#		fi
+#	fi
+
 fi
 
 echo
@@ -32,54 +59,154 @@
 read input
 if [ "$input" = 'y' -o "$input" = 'Y' ]
 then
-    SHORTNAMES='#define ShortNames -DSHORTNAMES'
-    ALLDEFINES="$ALLDEFINES -DSHORTNAMES"
+	SHORTNAMES='#define ShortNames -DSHORTNAMES'
+	ALLDEFINES="$ALLDEFINES -DSHORTNAMES"
 else
-    SHORTNAMES=''
+	SHORTNAMES=''
 fi
 
-echo -n 'Global configfile name [/usr/local/etc/wine.conf]? '
+prompt "Global configfile name" WINE_CONFIGFILE /usr/local/etc/wine.conf
+
+WINE_INI_GLOBAL='#define WINE_INI_GLOBAL "'$WINE_CONFIGFILE'"'
+
+if [ -r $WINE_CONFIGFILE ]
+then
+	DEFAULT_ANS=N
+else
+	DEFAULT_ANS=Y
+fi
+
+echo
+echo -n "Do you want to make a config file now (Y/N) [$DEFAULT_ANS]? "
 read input
 if [ "$input" = '' ]
 then
-    WINE_INI_GLOBAL='#define WINE_INI_GLOBAL "/usr/local/etc/wine.conf"'
+	input="$DEFAULT_ANS"
+fi
+if [ "$input" = 'y' -o "$input" = 'Y' ]
+then
+	if [ -r $WINE_CONFIGFILE ]
+	then
+		echo "Backing up the old file to ${WINE_CONFIGFILE}.old."
+		if cp $WINE_CONFIGFILE ${WINE_CONFIGFILE}.old
+		then	:
+		else
+			echo "Error while creating backup file.  Fix it and run Configure again"
+			exit 1
+		fi
+	fi
+
+	case `awk 'BEGIN {s=0} {if ($3=="msdos") s++} END {print s}' /etc/fstab` in
+	0)	CF_C=/c;;
+	1)	CF_C=`awk '{if ($3=="msdos") print $2}' /etc/fstab`;;
+	*)	CF_C=`awk '{if ($3=="msdos") {print $2;exit}}' /etc/fstab`;;
+	esac
+
+	prompt "Which directory do you want to use as A:" CF_A /a
+	prompt "Which directory do you want to use as C:" CF_C $CF_C
+	prompt "Where is the Windows directory" CF_Windows 'c:\windows'
+	prompt "Where is the System directory" CF_System 'c:\windows\system'
+	prompt "Where should Windows apps store temp files" CF_Temp 'c:\temp'
+	prompt "Which path should be used to find executables and DLL's" CF_Path 'c:\windows;c:\windows\system'
+	prompt "Where is sysres.dll" CF_SystemResources `pwd`/sysres.dll
+	prompt "Where is COM1" CF_Com1 '/dev/cua0'
+	prompt "Where is COM2" CF_Com2 '/dev/cua1'
+	prompt "Where is LPT1" CF_Lpt1 '/dev/lp0'
+	prompt "Log messages to which file (CON = stdout)" CF_File 'CON'
+
+	echo
+	sed -n -e 's/^ *\"\(WM_[A-Z0-9]*\)\".*/\1/p' < misc/spy.c | \
+		sort | pr -ta4w83 | sed '1 i\
+Here is the list of messages:\
+\
+' | $PAGER
+
+	prompt "Exclude which messages from the log" CF_Exclude 'WM_SIZE;WM_TIMER'
+
+	echo
+	echo "The config file $WINE_CONFIGFILE now looks like this:"
+	tee $WINE_CONFIGFILE << EOF
+[drives]
+A=$CF_A
+C=$CF_C
+
+[wine]
+Windows=$CF_Windows
+System=$CF_System
+Temp=$CF_Temp
+Path=$CF_Path
+SystemResources=$CF_SystemResources
+
+[serialports]
+Com1=$CF_Com1
+Com2=$CF_Com2
+
+[parallelports]
+Lpt1=$CF_Lpt1
+
+[spy]
+File=$CF_File
+Exclude=$CF_Exclude
+EOF
+
+	echo
+	echo -n "Do you want to edit it using $EDITOR (Y/N) [N]? "
+	read input
+	if [ "$input" = 'y' -o "$input" = 'Y' ]
+	then
+		$EDITOR $WINE_CONFIGFILE
+	fi
 else
-    WINE_INI_GLOBAL='#define WINE_INI_GLOBAL "'$input'"'
+	if [ ! -r $WINE_CONFIGFILE ]
+	then
+		echo 'Ok, remember to make it yourself later.'
+	fi
 fi
 
+NEWBUILD=''
 if [ "`(domainname)`" = 'amscons.com' ]
 then
+    echo
     echo -n 'New build program (Y/N) [N]? '
     read input
     if [ "$input" = 'y' -o "$input" = 'Y' ]
     then
 	NEWBUILD='#define NewBuild -DNEWBUILD'
 	ALLDEFINES="$ALLDEFINES -DNEWBUILD"
-    else
-	NEWBUILD=''
     fi
-else
-    NEWBUILD=''
 fi
 
 NEWLINUXLDT=''
-if [ -f /usr/include/linux/ldt.h ]
+if grep -s seg_not_present /usr/include/linux/ldt.h 2> /dev/null
 then
-	if grep seg_not_present /usr/include/linux/ldt.h
-	then
-		NEWLINUXLDT='#define NEW_LDT_STRUCT'
-	fi
+	NEWLINUXLDT='#define NEW_LDT_STRUCT'
 fi
 
-echo '/* autoconf.h generated automatically.  Run Configure. */' > autoconf.h
-echo $WINELIB >> autoconf.h
-echo $SHORTNAMES >> autoconf.h
-echo $NEWBUILD >> autoconf.h
-echo $WINE_INI_GLOBAL >> autoconf.h
-echo $NEWLINUXLDT >> autoconf.h
-echo $ENDIAN >> autoconf.h
-echo $PROCEMU >> autoconf.h
-echo $PROCEMUDIR >> autoconf.h
-echo "#define AutoDefines  $ALLDEFINES" >> autoconf.h
+cat > autoconf.h << EOF
+/* autoconf.h generated automatically.  Run Configure. */
+$WINELIB
+$SHORTNAMES
+$NEWBUILD
+$WINE_INI_GLOBAL
+$NEWLINUXLDT
+$ENDIAN
+$PROCEMUDIR
+#define AutoDefines $ALLDEFINES
+EOF
 
 xmkmf -a
+
+if [ 0 -lt `find . -name "*.rej" -print | wc -l` ]
+then
+	cat << EOF
+
+WARNING:  You have some files named "*.rej".  Rejected patch files?
+Maybe you tried to upgrade Wine by diff-files, and that patch failed.
+If something doesn't work, this might be the reason.  See "man patch".
+
+List of "*.rej" files:
+
+EOF
+	find . -name "*.rej" -print
+	echo
+fi
diff --git a/DEVELOPERS-HINTS b/DEVELOPERS-HINTS
index 2ea1e9f..d95d87d 100644
--- a/DEVELOPERS-HINTS
+++ b/DEVELOPERS-HINTS
@@ -81,3 +81,37 @@
 Inorder to return values in the registers to the WIN16 program, the handler
 function must exit by calling ReturnFromRegisterFunc().  Look at the function
 DOS3Call() for an example of how this works.
+
+DEBUG MESSAGES:
+
+To display a message only during debugging, you normally write something
+like this:
+
+#ifdef DEBUG_WIN
+	printf("abc...");
+#endif
+
+You can write this shorter (and better) in this way:
+
+	dprintf_win(stddeb,"abc...");
+
+All symbols of the form dprintf_xxxx are macros defined in include/debug.h .
+The macro-definitions are generated by the shell-script tools/make_debug. It
+scans the source code for symbols of this forms and puts the necessary
+macro definitions in include/debug.h and include/stddebug.h . These macros
+test for the symbol DEBUG_XXXX (e.g. dprintf_win refers to DEBUG_WIN) being 
+defined and thus decided whether to actually display the text. If you want
+to enable specific types of messages, simply put the corresponding
+#define DEBUG_XXXX in include/stddebug.h . If you want to enable or disable
+a specific type of message in just one c-source-file, put the corresponding 
+#define DEBUG_XXXX or #undefine DEBUG_XXXX between #include<stddebug.h> and
+#include <debug.h> in that specific file. In addition you can change the 
+types of displayed messages by supplying the "-debugmsg" option to Wine. 
+
+The file handle "stddeb" is intended for displaying standard informational
+messages, whereas "stdnimp" is intended for displaying messages concerning
+not yet implemented functions.
+
+You have to start tools/make_debug only if you introduced a new macro,
+e.g.  dprintf_win32s - not if you just changed one of the #define
+DEBUG_XXX's in include/stddebug.h or in a specific file.
diff --git a/Imakefile b/Imakefile
index fec5a48..5b5f709 100644
--- a/Imakefile
+++ b/Imakefile
@@ -87,7 +87,7 @@
 
 MakeSubdirs($(SUBDIRS))
 DependSubdirs($(SUBDIRS))
-AllTarget(wine)
+AllTarget(wine.sym)
 
 #ifndef WINELIB
 NormalProgramTarget(wine,$(EMUOBJS) $(COMMONOBJS),$(DEPXLIB),$(XLIB),$(SYSLIBS))
@@ -95,9 +95,17 @@
 NormalLibraryTarget(wine,$(LIBOBJS) $(COMMONOBJS))
 #endif
 
+wine.sym: wine
+	nm wine|sort >wine.sym
+
+clean::
+	$(RM) wine.sym
+
 depend::
 
 install::
 
 etags::
 	etags `find . -name '*.[chS]'`
+
+
diff --git a/LICENSE b/LICENSE
index 88add0b..9e0358b 100644
--- a/LICENSE
+++ b/LICENSE
@@ -7,7 +7,7 @@
 copyright notice); and (3) agree to indemnify and hold all prior
 authors, copyright holders and licensors of the work harmless
 from and against all damages arising from use of the work.
-
+ 
 You may distribute sources of derivative works of the work
 provided that (1) (a) all source files of the original work that
 have been modified, (b) all source files of the derivative work
@@ -19,7 +19,7 @@
 of the modification and/or creation.  You are encouraged to make
 the Necessary Sources available under this license in order to
 further the development and acceptance of the work.
-
+ 
 EXCEPT AS OTHERWISE RESTRICTED BY LAW, THIS WORK IS PROVIDED
 WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES OF ANY KIND, INCLUDING
 BUT NOT LIMITED TO, ANY IMPLIED WARRANTIES OF FITNESS FOR A
@@ -27,4 +27,3 @@
 OTHERWISE PROVIDED BY LAW, NO AUTHOR, COPYRIGHT HOLDER OR
 LICENSOR SHALL BE LIABLE TO YOU FOR DAMAGES OF ANY KIND, EVEN IF
 ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
diff --git a/controls/Imakefile b/controls/Imakefile
index 4556b4c..374441d 100644
--- a/controls/Imakefile
+++ b/controls/Imakefile
@@ -5,19 +5,18 @@
 SRCS = \
 	button.c \
 	combo.c \
+	desktop.c \
+	edit.c \
 	listbox.c \
 	menu.c \
 	scroll.c \
 	static.c \
-	edit.c \
-	desktop.c \
 	widgets.c
 
 OBJS = $(SRCS:.c=.o)
 
 WineRelocatableTarget($(TOP)/$(MODULE),,$(OBJS))
 DependTarget()
-CleanTarget()
 
 includes::
 
diff --git a/controls/button.c b/controls/button.c
index 7e2d99e..d20baff 100644
--- a/controls/button.c
+++ b/controls/button.c
@@ -2,126 +2,105 @@
  *
  * Copyright (C) 1993 Johannes Ruscheinski
  * Copyright (C) 1993 David Metcalfe
+ * Copyright (C) 1994 Alexandre Julliard
  */
 
 static char Copyright1[] = "Copyright Johannes Ruscheinski, 1993";
 static char Copyright2[] = "Copyright David Metcalfe, 1993";
+static char Copyright3[] = "Copyright Alexandre Julliard, 1994";
 
-#include <windows.h>
+#include "button.h"
 #include "win.h"
 #include "user.h"
 #include "syscolor.h"
 
 
-LONG ButtonWndProc(HWND hWnd, WORD uMsg, WORD wParam, LONG lParam);
-
-#define NOTIFY_PARENT(hWndCntrl, wNotifyCode) \
-	SendMessage(GetParent(hWndCntrl), WM_COMMAND, \
-		GetDlgCtrlID(hWndCntrl), MAKELPARAM(hWndCntrl, wNotifyCode));
-#define DIM(array)	((sizeof array)/(sizeof array[0]))
-
 extern BOOL GRAPH_DrawBitmap( HDC hdc, HBITMAP hbitmap, int xdest, int ydest,
 			      int xsrc, int ysrc, int width, int height,
 			      int rop );              /* windows/graphics.c */
+extern void GRAPH_DrawReliefRect( HDC hdc, RECT *rect, int thickness,
+                                  BOOL pressed );     /* windows/graphics.c */
+
 extern void DEFWND_SetText( HWND hwnd, LPSTR text );  /* windows/defwnd.c */
 
-static LONG PB_Paint(HWND hWnd);
-static LONG PB_LButtonDown(HWND hWnd, WORD wParam, LONG lParam);
-static LONG PB_LButtonUp(HWND hWnd, WORD wParam, LONG lParam);
-static LONG PB_LButtonDblClk(HWND hWnd, WORD wParam, LONG lParam);
-static LONG PB_KillFocus(HWND hwnd);
-static void DrawRaisedPushButton(HDC hDC, HWND hButton, RECT rc);
-static void DrawPressedPushButton(HDC hDC, HWND hButton, RECT rc);
-static LONG CB_Paint(HWND hWnd);
-static LONG CB_LButtonDown(HWND hWnd, WORD wParam, LONG lParam);
-static LONG CB_LButtonUp(HWND hWnd, WORD wParam, LONG lParam);
-static LONG CB_LButtonDblClk(HWND hWnd, WORD wParam, LONG lParam);
-static LONG CB_KillFocus(HWND hWnd);
-static LONG CB_SetCheck(HWND hWnd, WORD wParam);
-static LONG CB_GetCheck(HWND hWnd);
-static LONG RB_Paint(HWND hWnd);
-static LONG RB_LButtonDown(HWND hWnd, WORD wParam, LONG lParam);
-static LONG RB_LButtonUp(HWND hWnd, WORD wParam, LONG lParam);
-static LONG RB_LButtonDblClk(HWND hWnd, WORD wParam, LONG lParam);
-static LONG RB_KillFocus(HWND hWnd);
-static LONG RB_SetCheck(HWND hWnd, WORD wParam);
-static LONG RB_GetCheck(HWND hWnd);
-static LONG GB_Paint(HWND hWnd);
-static LONG UB_Paint(HWND hWnd);
-static LONG UB_LButtonDown(HWND hWnd, WORD wParam, LONG lParam);
-static LONG UB_LButtonUp(HWND hWnd, WORD wParam, LONG lParam);
-static LONG UB_KillFocus(HWND hWnd);
-static LONG OB_Paint(HWND hWnd);
-static LONG OB_LButtonDown(HWND hWnd, WORD wParam, LONG lParam);
-static LONG OB_LButtonUp(HWND hWnd, WORD wParam, LONG lParam);
-static LONG OB_KillFocus(HWND hWnd);
+static void PB_Paint( HWND hWnd, HDC hDC, WORD action );
+static void CB_Paint( HWND hWnd, HDC hDC, WORD action );
+static void GB_Paint( HWND hWnd, HDC hDC, WORD action );
+static void UB_Paint( HWND hWnd, HDC hDC, WORD action );
+static void OB_Paint( HWND hWnd, HDC hDC, WORD action );
 
-typedef struct
-{
-    LONG (*paintfn)( HWND );
-    LONG (*lButtonDownfn)( HWND, WORD, LONG );
-    LONG (*lButtonUpfn)( HWND, WORD, LONG );
-    LONG (*lButtonDblClkfn)( HWND, WORD, LONG );
-    LONG (*killFocusfn)( HWND );
-    LONG (*setCheckfn)( HWND, WORD );
-    LONG (*getCheckfn)( HWND );
-} BTNFN;
 
 #define MAX_BTN_TYPE  12
 
-static BTNFN btnfn[MAX_BTN_TYPE] =
+static WORD maxCheckState[MAX_BTN_TYPE] =
 {
-    /* BS_PUSHBUTTON */
-    { PB_Paint, PB_LButtonDown, PB_LButtonUp, PB_LButtonDblClk, 
-      PB_KillFocus, NULL, NULL },
-    /* BS_DEFPUSHBUTTON */
-    { PB_Paint, PB_LButtonDown, PB_LButtonUp, PB_LButtonDblClk,
-      PB_KillFocus, NULL, NULL },
-    /* BS_CHECKBOX */
-    { CB_Paint, CB_LButtonDown, CB_LButtonUp, CB_LButtonDblClk,
-      CB_KillFocus, CB_SetCheck, CB_GetCheck },
-    /* BS_AUTOCHECKBOX */
-    { CB_Paint, CB_LButtonDown, CB_LButtonUp, CB_LButtonDblClk,
-      CB_KillFocus, CB_SetCheck, CB_GetCheck },
-    /* BS_RADIOBUTTON */
-    { RB_Paint, RB_LButtonDown, RB_LButtonUp, RB_LButtonDblClk,
-      RB_KillFocus, RB_SetCheck, RB_GetCheck },
-    /* BS_3STATE */
-    { CB_Paint, CB_LButtonDown, CB_LButtonUp, CB_LButtonDblClk,
-      CB_KillFocus, CB_SetCheck, CB_GetCheck },
-    /* BS_AUTO3STATE */
-    { CB_Paint, CB_LButtonDown, CB_LButtonUp, CB_LButtonDblClk,
-      CB_KillFocus, CB_SetCheck, CB_GetCheck },
-    /* BS_GROUPBOX */
-    { GB_Paint, NULL, NULL, NULL, NULL, NULL, NULL },
-    /* BS_USERBUTTON */
-    { UB_Paint, UB_LButtonDown, UB_LButtonUp, NULL, UB_KillFocus, NULL, NULL },
-    /* BS_AUTORADIOBUTTON */
-    { RB_Paint, RB_LButtonDown, RB_LButtonUp, RB_LButtonDblClk,
-      RB_KillFocus, RB_SetCheck, RB_GetCheck },
-    /* Not defined */
-    { NULL, NULL, NULL, NULL, NULL, NULL, NULL },
-    /* BS_OWNERDRAW */
-    { OB_Paint, OB_LButtonDown, OB_LButtonUp, NULL, OB_KillFocus, NULL, NULL }
+    BUTTON_UNCHECKED,   /* BS_PUSHBUTTON */
+    BUTTON_UNCHECKED,   /* BS_DEFPUSHBUTTON */
+    BUTTON_CHECKED,     /* BS_CHECKBOX */
+    BUTTON_CHECKED,     /* BS_AUTOCHECKBOX */
+    BUTTON_CHECKED,     /* BS_RADIOBUTTON */
+    BUTTON_3STATE,      /* BS_3STATE */
+    BUTTON_3STATE,      /* BS_AUTO3STATE */
+    BUTTON_UNCHECKED,   /* BS_GROUPBOX */
+    BUTTON_UNCHECKED,   /* BS_USERBUTTON */
+    BUTTON_CHECKED,     /* BS_AUTORADIOBUTTON */
+    BUTTON_UNCHECKED,   /* Not defined */
+    BUTTON_UNCHECKED    /* BS_OWNERDRAW */
 };
 
+typedef void (*pfPaint)(HWND,HDC,WORD);
+
+static pfPaint btnPaintFunc[MAX_BTN_TYPE] =
+{
+    PB_Paint,    /* BS_PUSHBUTTON */
+    PB_Paint,    /* BS_DEFPUSHBUTTON */
+    CB_Paint,    /* BS_CHECKBOX */
+    CB_Paint,    /* BS_AUTOCHECKBOX */
+    CB_Paint,    /* BS_RADIOBUTTON */
+    CB_Paint,    /* BS_3STATE */
+    CB_Paint,    /* BS_AUTO3STATE */
+    GB_Paint,    /* BS_GROUPBOX */
+    UB_Paint,    /* BS_USERBUTTON */
+    CB_Paint,    /* BS_AUTORADIOBUTTON */
+    NULL,        /* Not defined */
+    OB_Paint     /* BS_OWNERDRAW */
+};
+
+#define PAINT_BUTTON(hwnd,style,action) \
+     if (btnPaintFunc[style]) { \
+         HDC hdc = GetDC( hwnd ); \
+         (btnPaintFunc[style])(hwnd,hdc,action); \
+         ReleaseDC( hwnd, hdc ); }
+
 static HBITMAP hbitmapCheckBoxes = 0;
 static WORD checkBoxWidth = 0, checkBoxHeight = 0;
 
 
 LONG ButtonWndProc(HWND hWnd, WORD uMsg, WORD wParam, LONG lParam)
 {
+        RECT rect;
 	LONG lResult = 0;
 	WND *wndPtr = WIN_FindWndPtr(hWnd);
 	LONG style = wndPtr->dwStyle & 0x0000000F;
+        BUTTONINFO *infoPtr = (BUTTONINFO *)wndPtr->wExtra;
 
 	switch (uMsg) {
-/*	case WM_GETDLGCODE:
-		lResult = DLGC_BUTTON;
-		break;
-*/
+	case WM_GETDLGCODE:
+                switch(style)
+                {
+                case BS_PUSHBUTTON:
+                    return DLGC_BUTTON | DLGC_UNDEFPUSHBUTTON;
+                case BS_DEFPUSHBUTTON:
+                    return DLGC_BUTTON | DLGC_DEFPUSHBUTTON;
+                case BS_RADIOBUTTON:
+                case BS_AUTORADIOBUTTON:
+                    return DLGC_BUTTON | DLGC_RADIOBUTTON;
+                default:
+                    return DLGC_BUTTON;
+                }
+
 	case WM_ENABLE:
-		InvalidateRect(hWnd, NULL, FALSE);
+                PAINT_BUTTON( hWnd, style, ODA_DRAWENTIRE );
 		break;
 
 	case WM_CREATE:
@@ -134,63 +113,134 @@
 		    checkBoxHeight = bmp.bmHeight / 3;
 		}
 		
-		if (style < 0L || style >= (LONG)DIM(btnfn))
+		if (style < 0L || style >= MAX_BTN_TYPE)
 		    lResult = -1L;
 		else
 		{
-		    (WORD)(*(wndPtr->wExtra)) = 0;
+                    infoPtr->state = BUTTON_UNCHECKED;
+                    infoPtr->hFont = 0;
 		    lResult = 0L;
 		}
 		break;
 
+        case WM_ERASEBKGND:
+                break;
+
 	case WM_PAINT:
-		if (btnfn[style].paintfn)
-		    (btnfn[style].paintfn)(hWnd);
+                if (btnPaintFunc[style])
+                {
+                    PAINTSTRUCT ps;
+                    HDC hdc = BeginPaint( hWnd, &ps );
+                    (btnPaintFunc[style])( hWnd, hdc, ODA_DRAWENTIRE );
+                    ReleaseDC( hWnd, hdc );
+                }
 		break;
 
 	case WM_LBUTTONDOWN:
-		if (btnfn[style].lButtonDownfn)
-		    (btnfn[style].lButtonDownfn)(hWnd, wParam, lParam);
+                SendMessage( hWnd, BM_SETSTATE, TRUE, 0 );
+                SetFocus( hWnd );
+                SetCapture( hWnd );
 		break;
 
 	case WM_LBUTTONUP:
-		if (btnfn[style].lButtonUpfn)
-		    (btnfn[style].lButtonUpfn)(hWnd, wParam, lParam);
+                ReleaseCapture();
+                SendMessage( hWnd, BM_SETSTATE, FALSE, 0 );
+                GetClientRect( hWnd, &rect );
+                if (PtInRect( &rect, MAKEPOINT(lParam) ))
+                {
+                    switch(style)
+                    {
+                    case BS_AUTOCHECKBOX:
+                        SendMessage( hWnd, BM_SETCHECK,
+                                    !(infoPtr->state & BUTTON_CHECKED), 0 );
+                        break;
+                    case BS_AUTORADIOBUTTON:
+                        SendMessage( hWnd, BM_SETCHECK, TRUE, 0 );
+                        break;
+                    case BS_AUTO3STATE:
+                        SendMessage( hWnd, BM_SETCHECK,
+                                     (infoPtr->state & BUTTON_3STATE) ? 0 :
+                                     ((infoPtr->state & 3) + 1), 0 );
+                        break;
+                    }
+                    SendMessage( GetParent(hWnd), WM_COMMAND,
+                                 wndPtr->wIDmenu, MAKELPARAM(hWnd,BN_CLICKED));
+                }
 		break;
 
-	case WM_LBUTTONDBLCLK:
-		if (btnfn[style].lButtonDblClkfn)
-		    (btnfn[style].lButtonDblClkfn)(hWnd, wParam, lParam);
-		break;
+        case WM_MOUSEMOVE:
+                if (GetCapture() == hWnd)
+                {
+                    GetClientRect( hWnd, &rect );
+                    if (PtInRect( &rect, MAKEPOINT(lParam)) )
+                       SendMessage( hWnd, BM_SETSTATE, TRUE, 0 );
+                    else SendMessage( hWnd, BM_SETSTATE, FALSE, 0 );
+                }
+                break;
 
         case WM_SETTEXT:
 		DEFWND_SetText( hWnd, (LPSTR)lParam );
-		InvalidateRect( hWnd, NULL, FALSE );
-		UpdateWindow( hWnd );
+                PAINT_BUTTON( hWnd, style, ODA_DRAWENTIRE );
 		return 0;
 
+        case WM_SETFONT:
+                infoPtr->hFont = wParam;
+                if (lParam)
+                    PAINT_BUTTON( hWnd, style, ODA_DRAWENTIRE );
+                break;
+
+        case WM_GETFONT:
+                return infoPtr->hFont;
+
 	case WM_SETFOCUS:
+                infoPtr->state |= BUTTON_HASFOCUS;
+                PAINT_BUTTON( hWnd, style, ODA_FOCUS );
 		break;
 
 	case WM_KILLFOCUS:
-		if (btnfn[style].killFocusfn)
-		    (btnfn[style].killFocusfn)(hWnd);
+                infoPtr->state &= ~BUTTON_HASFOCUS;
+                PAINT_BUTTON( hWnd, style, ODA_FOCUS );
 		break;
 
 	case WM_SYSCOLORCHANGE:
-		InvalidateRect(hWnd, NULL, TRUE);
+		InvalidateRect(hWnd, NULL, FALSE);
 		break;
 
-	case BM_SETCHECK:
-		if (btnfn[style].setCheckfn)
-		    (btnfn[style].setCheckfn)(hWnd, wParam);
+	case BM_SETSTYLE:
+		if ((wParam & 0x0f) >= MAX_BTN_TYPE) break;
+		wndPtr->dwStyle = (wndPtr->dwStyle & 0xfffffff0) 
+		                   | (wParam & 0x0000000f);
+                style = wndPtr->dwStyle & 0x0000000f;
+                PAINT_BUTTON( hWnd, style, ODA_DRAWENTIRE );
 		break;
 
 	case BM_GETCHECK:
-		if (btnfn[style].getCheckfn)
-		    return (btnfn[style].getCheckfn)(hWnd);
+		lResult = infoPtr->state & 3;
 		break;
 
+	case BM_SETCHECK:
+                if (wParam > maxCheckState[style])
+                    wParam = maxCheckState[style];
+		if ((infoPtr->state & 3) != wParam)
+                {
+                    infoPtr->state = (infoPtr->state & ~3) | wParam;
+                    PAINT_BUTTON( hWnd, style, ODA_SELECT );
+                }
+                break;
+
+	case BM_GETSTATE:
+		lResult = infoPtr->state;
+		break;
+
+	case BM_SETSTATE:
+                if (!wParam != !(infoPtr->state & BUTTON_HIGHLIGHTED))
+                {
+                    if (wParam) infoPtr->state |= BUTTON_HIGHLIGHTED;
+                    else infoPtr->state &= ~BUTTON_HIGHLIGHTED;
+                    PAINT_BUTTON( hWnd, style, ODA_SELECT );
+                }
+                break;
+
 	default:
 		lResult = DefWindowProc(hWnd, uMsg, wParam, lParam);
 		break;
@@ -204,457 +254,136 @@
  *       Push Button Functions
  */
 
-static LONG PB_Paint(HWND hWnd)
-{
-    PAINTSTRUCT ps;
-    RECT rc;
-    HDC hDC;
-
-    hDC = BeginPaint(hWnd, &ps);
-    GetClientRect(hWnd, &rc);
-    if (GetCapture() == hWnd)
-	DrawPressedPushButton(hDC, hWnd, rc);
-    else
-	DrawRaisedPushButton(hDC, hWnd, rc);
-    EndPaint(hWnd, &ps);
-    return 0;
-}
-
-static LONG PB_LButtonDown(HWND hWnd, WORD wParam, LONG lParam)
-{
-    SetFocus(hWnd);
-    SetCapture(hWnd);
-    InvalidateRect(hWnd, NULL, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
-}
-
-static LONG PB_LButtonUp(HWND hWnd, WORD wParam, LONG lParam)
+static void PB_Paint( HWND hButton, HDC hDC, WORD action )
 {
     RECT rc;
-
-    ReleaseCapture();
-    GetClientRect(hWnd, &rc);
-    if (PtInRect(&rc, MAKEPOINT(lParam)))
-	NOTIFY_PARENT(hWnd, BN_CLICKED);
-    InvalidateRect(hWnd, NULL, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
-}
-
-static LONG PB_LButtonDblClk(HWND hWnd, WORD wParam, LONG lParam)
-{
-    NOTIFY_PARENT(hWnd, BN_DOUBLECLICKED);
-    return 0;
-}
-
-static LONG PB_KillFocus(HWND hWnd)
-{
-    InvalidateRect(hWnd, NULL, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
-}
-
-static void DrawRaisedPushButton(HDC hDC, HWND hButton, RECT rc)
-{
-	HPEN hOldPen;
-	HBRUSH hOldBrush;
-	HRGN rgn;
-	int len;
-	char *text;
-	POINT points[6];
-	DWORD dwTextSize;
-	int delta;
-	TEXTMETRIC tm;
-	WND *wndPtr = WIN_FindWndPtr( hButton );
-
-	hOldPen = (HPEN)SelectObject(hDC, sysColorObjects.hpenWindowFrame);
-	hOldBrush = (HBRUSH)SelectObject(hDC, sysColorObjects.hbrushBtnFace);
-	SetBkMode(hDC, TRANSPARENT);
-	SetTextColor( hDC, GetSysColor(COLOR_BTNTEXT) );
-	Rectangle(hDC, rc.left, rc.top, rc.right, rc.bottom);
-
-	/* draw button label, if any: */
-	text = USER_HEAP_ADDR( wndPtr->hText );
-	len = strlen(text);
-	if (len >= 1) {
-		rc.left--;	rc.bottom--;
-		DrawText(hDC, text, len, &rc,
-			 DT_SINGLELINE | DT_CENTER| DT_VCENTER);
-	}
-
-	/* draw button highlight */
-	points[0].x = rc.left+2;
-	points[0].y = rc.bottom;
-	points[1].x = rc.left+4;
-	points[1].y = rc.bottom-2;
-	points[2].x = rc.left+4;
-	points[2].y = rc.top+3;
-	points[3].x = rc.right-3;
-	points[3].y = rc.top+3;
-	points[4].x = rc.right-1;
-	points[4].y = rc.top+1;
-	points[5].x = rc.left+2;
-	points[5].y = rc.top+1;
-	rgn = CreatePolygonRgn(points, DIM(points), ALTERNATE);
-	FillRgn(hDC, rgn, sysColorObjects.hbrushBtnHighlight);
-
-	/* draw button shadow: */
-	points[0].x = rc.left+2;
-	points[0].y = rc.bottom;
-	points[1].x = rc.left+4;
-	points[1].y = rc.bottom-2;
-	points[2].x = rc.right-3;
-	points[2].y = rc.bottom-2;
-	points[3].x = rc.right-3;
-	points[3].y = rc.top+3;
-	points[4].x = rc.right-1;
-	points[4].y = rc.top;
-	points[5].x = rc.right-1;
-	points[5].y = rc.bottom;
-	rgn = CreatePolygonRgn(points, DIM(points), ALTERNATE);
-	FillRgn(hDC, rgn, sysColorObjects.hbrushBtnShadow);
-
-	/* do we have the focus? */
-	if (len >= 1 && GetFocus() == hButton) {
-		dwTextSize = GetTextExtent(hDC, text, len);
-		delta = ((rc.right - rc.left) - LOWORD(dwTextSize) - 1) >> 1;
-		rc.left += delta;	rc.right -= delta;
-		GetTextMetrics(hDC, &tm);
-		delta = ((rc.bottom - rc.top) - tm.tmHeight - 1) >> 1;
-		rc.top += delta; 	rc.bottom -= delta;
-		DrawFocusRect(hDC, &rc);
-	}
-
-	SelectObject(hDC, (HANDLE)hOldPen);
-	SelectObject(hDC, (HANDLE)hOldBrush);
-	DeleteObject((HANDLE)rgn);
-}
-
-
-static void DrawPressedPushButton(HDC hDC, HWND hButton, RECT rc)
-{
-	HPEN hOldPen;
-	HBRUSH hOldBrush;
-	int len;
-	char *text;
-	DWORD dwTextSize;
-	int delta;
-	TEXTMETRIC tm;
-	WND *wndPtr = WIN_FindWndPtr( hButton );
-
-	hOldBrush = (HBRUSH)SelectObject(hDC, sysColorObjects.hbrushBtnFace);
-	hOldPen = (HPEN)SelectObject(hDC, sysColorObjects.hpenWindowFrame);
-	SetBkMode(hDC, TRANSPARENT);
-	SetTextColor( hDC, GetSysColor(COLOR_BTNTEXT) );
-	Rectangle(hDC, rc.left, rc.top, rc.right, rc.bottom);
-
-	/* draw button shadow: */
-	SelectObject(hDC, sysColorObjects.hbrushBtnShadow );
-	PatBlt(hDC, rc.left+1, rc.top+1, 1, rc.bottom-rc.top-2, PATCOPY );
-	PatBlt(hDC, rc.left+1, rc.top+1, rc.right-rc.left-2, 1, PATCOPY );
-
-	/* draw button label, if any: */
-	text = USER_HEAP_ADDR( wndPtr->hText );
-	len = strlen(text);
-	if (len >= 1) {
-		rc.top++;	rc.left++;
-		DrawText(hDC, text, len, &rc,
-			 DT_SINGLELINE | DT_CENTER| DT_VCENTER);
-	}
-
-	/* do we have the focus? */
-	if (len >= 1 && GetFocus() == hButton) {
-		dwTextSize = GetTextExtent(hDC, text, len);
-		delta = ((rc.right - rc.left) - LOWORD(dwTextSize) - 1) >> 1;
-		rc.left += delta;	rc.right -= delta;
-		GetTextMetrics(hDC, &tm);
-		delta = ((rc.bottom - rc.top) - tm.tmHeight - 1) >> 1;
-		rc.top += delta; 	rc.bottom -= delta;
-		DrawFocusRect(hDC, &rc);
-	}
-
-	SelectObject(hDC, (HANDLE)hOldPen);
-	SelectObject(hDC, (HANDLE)hOldBrush);
-}
-
-
-/**********************************************************************
- *       Check Box Functions
- */
-
-static LONG CB_Paint(HWND hWnd)
-{
-    PAINTSTRUCT ps;
-    RECT rc;
-    HDC hDC;
-    HBRUSH hBrush;
-    int textlen, delta;
+    HPEN hOldPen;
+    HBRUSH hOldBrush;
     char *text;
+    DWORD dwTextSize;
+    int delta;
     TEXTMETRIC tm;
-    SIZE size;
-    WND *wndPtr = WIN_FindWndPtr(hWnd);
+    WND *wndPtr = WIN_FindWndPtr( hButton );
+    BUTTONINFO *infoPtr = (BUTTONINFO *)wndPtr->wExtra;
 
-    hDC = BeginPaint(hWnd, &ps);
-    GetClientRect(hWnd, &rc);
+    GetClientRect(hButton, &rc);
 
-    hBrush = SendMessage(GetParent(hWnd), WM_CTLCOLOR, (WORD)hDC,
-			 MAKELPARAM(hWnd, CTLCOLOR_BTN));
-    FillRect(hDC, &rc, hBrush);
-
-    text = USER_HEAP_ADDR( wndPtr->hText );
-    textlen = strlen( text );
-    GetTextMetrics(hDC, &tm);
-    delta = (rc.bottom - rc.top - tm.tmHeight) >> 1;
-
-    GRAPH_DrawBitmap( hDC, hbitmapCheckBoxes,
-		      rc.left, rc.top + delta,
-		      ((GetCapture() == hWnd) ?  2*checkBoxWidth : 0) +
-		      (wndPtr->wExtra[0] ? checkBoxWidth : 0),
-		      ((wndPtr->wExtra[0] == 2) ? 2*checkBoxHeight : 0),
-		      checkBoxWidth, checkBoxHeight, SRCCOPY );
-
-    rc.left = checkBoxWidth + tm.tmAveCharWidth / 2;
-    DrawText(hDC, text, textlen, &rc, DT_SINGLELINE | DT_VCENTER);
-
-    /* do we have the focus? */
-    if (GetFocus() == hWnd)
+      /* Send WM_CTLCOLOR to allow changing the font (the colors are fixed) */
+    if (infoPtr->hFont) SelectObject( hDC, infoPtr->hFont );
+    SendMessage( GetParent(hButton), WM_CTLCOLOR, (WORD)hDC,
+                 MAKELPARAM(hButton, CTLCOLOR_BTN) );
+    hOldPen = (HPEN)SelectObject(hDC, sysColorObjects.hpenWindowFrame);
+    hOldBrush = (HBRUSH)SelectObject(hDC, sysColorObjects.hbrushBtnFace);
+    SetBkMode(hDC, TRANSPARENT);
+    Rectangle(hDC, rc.left, rc.top, rc.right, rc.bottom);
+    if (action == ODA_DRAWENTIRE)
     {
-	GetTextExtentPoint(hDC, text, textlen, &size);
-	rc.top += delta - 1;
-	rc.bottom -= delta + 1;
-	rc.left--;
-	rc.right = rc.left + size.cx + 2;
-	DrawFocusRect(hDC, &rc);
+        SetPixel( hDC, rc.left, rc.top, GetSysColor(COLOR_WINDOW) );
+        SetPixel( hDC, rc.left, rc.bottom-1, GetSysColor(COLOR_WINDOW) );
+        SetPixel( hDC, rc.right-1, rc.top, GetSysColor(COLOR_WINDOW) );
+        SetPixel( hDC, rc.right-1, rc.bottom-1, GetSysColor(COLOR_WINDOW) );
+    }
+    InflateRect( &rc, -1, -1 );
+
+    if ((wndPtr->dwStyle & 0x000f) == BS_DEFPUSHBUTTON)
+    {
+        Rectangle(hDC, rc.left, rc.top, rc.right, rc.bottom);
+        InflateRect( &rc, -1, -1 );
     }
 
-    EndPaint(hWnd, &ps);
-    return 0;
-}
-
-static LONG CB_LButtonDown(HWND hWnd, WORD wParam, LONG lParam)
-{
-    RECT rc;
-
-    GetClientRect(hWnd, &rc);
-    SetFocus(hWnd);
-    SetCapture(hWnd);
-    InvalidateRect(hWnd, NULL, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
-}
-
-static LONG CB_LButtonUp(HWND hWnd, WORD wParam, LONG lParam)
-{
-    RECT rc;
-    WND *wndPtr = WIN_FindWndPtr(hWnd);
-    LONG style;
-
-    ReleaseCapture();
-    GetClientRect(hWnd, &rc);
-
-    if (PtInRect(&rc, MAKEPOINT(lParam)))
+    if (infoPtr->state & BUTTON_HIGHLIGHTED)
     {
-	style = wndPtr->dwStyle & 0x0000000F;
-	if (style == BS_AUTOCHECKBOX)
-	{
-	    switch ((WORD)(*(wndPtr->wExtra)))
-	    {
-	    case 0:
-		(WORD)(*(wndPtr->wExtra)) = 1;
-		break;
-
-	    case 1:
-		(WORD)(*(wndPtr->wExtra)) = 0;
-		break;
-	    }
-	}
-	else if (style == BS_AUTO3STATE)
-	{
-	    switch ((WORD)(*(wndPtr->wExtra)))
-	    {
-	    case 0:
-		(WORD)(*(wndPtr->wExtra)) = 1;
-		break;
-
-	    case 1:
-		(WORD)(*(wndPtr->wExtra)) = 2;
-		break;
-
-	    case 2:
-		(WORD)(*(wndPtr->wExtra)) = 0;
-		break;
-	    }
-	}
-	NOTIFY_PARENT(hWnd, BN_CLICKED);
+        /* draw button shadow: */
+        SelectObject(hDC, sysColorObjects.hbrushBtnShadow );
+        PatBlt(hDC, rc.left, rc.top, 1, rc.bottom-rc.top, PATCOPY );
+        PatBlt(hDC, rc.left, rc.top, rc.right-rc.left, 1, PATCOPY );
+        rc.left += 2;  /* To position the text down and right */
+        rc.top  += 2;
     }
-    InvalidateRect(hWnd, NULL, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
-}
-
-static LONG CB_LButtonDblClk(HWND hWnd, WORD wParam, LONG lParam)
-{
-    NOTIFY_PARENT(hWnd, BN_DOUBLECLICKED);
-    return 0;
-}
-
-static LONG CB_KillFocus(HWND hWnd)
-{
-    InvalidateRect(hWnd, NULL, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
-}
-
-static LONG CB_SetCheck(HWND hWnd, WORD wParam)
-{
-    WND *wndPtr = WIN_FindWndPtr(hWnd);
-
-    if ((WORD)(*(wndPtr->wExtra)) != wParam)
-    {
-	RECT rect;
-	GetClientRect( hWnd, &rect );
-	rect.right = rect.left + checkBoxWidth; /* Only invalidate check-box */
-	(WORD)(*(wndPtr->wExtra)) = wParam;
-	InvalidateRect(hWnd, &rect, FALSE);
-	UpdateWindow(hWnd);
-    }
-    return 0;
-}
-
-static LONG CB_GetCheck(HWND hWnd)
-{
-    WORD wResult;
-    WND *wndPtr = WIN_FindWndPtr(hWnd);
-
-    wResult = (WORD)(*(wndPtr->wExtra));
-    return (LONG)wResult;
-}
-
-
-/**********************************************************************
- *       Radio Button Functions
- */
-
-static LONG RB_Paint(HWND hWnd)
-{
-    PAINTSTRUCT ps;
-    RECT rc;
-    HDC hDC;
-    HBRUSH hBrush;
-    int textlen, delta;
-    char *text;
-    TEXTMETRIC tm;
-    SIZE size;
-    WND *wndPtr = WIN_FindWndPtr(hWnd);
-
-    hDC = BeginPaint(hWnd, &ps);
-    GetClientRect(hWnd, &rc);
-
-    hBrush = SendMessage(GetParent(hWnd), WM_CTLCOLOR, (WORD)hDC,
-			 MAKELPARAM(hWnd, CTLCOLOR_BTN));
-    FillRect(hDC, &rc, hBrush);
-
-    GetTextMetrics(hDC, &tm);
-    delta = (rc.bottom - rc.top - tm.tmHeight) >> 1;
-    GRAPH_DrawBitmap( hDC, hbitmapCheckBoxes,
-		      rc.left, rc.top + delta,
-		      ((GetCapture() == hWnd) ?  2*checkBoxWidth : 0) +
-		      (wndPtr->wExtra[0] ? checkBoxWidth : 0), checkBoxHeight,
-		      checkBoxWidth, checkBoxHeight, SRCCOPY );
-
-    text = USER_HEAP_ADDR( wndPtr->hText );
-    textlen = strlen( text );
-    rc.left = checkBoxWidth + tm.tmAveCharWidth / 2;
-    DrawText(hDC, text, textlen, &rc, DT_SINGLELINE | DT_VCENTER);
+    else GRAPH_DrawReliefRect( hDC, &rc, 2, FALSE );
     
-    /* do we have the focus? */
-    if (GetFocus() == hWnd)
+    /* draw button label, if any: */
+    text = USER_HEAP_ADDR( wndPtr->hText );
+    if (text[0])
     {
-	GetTextExtentPoint(hDC, text, textlen, &size);
-	rc.top += delta - 1;
-	rc.bottom -= delta + 1;
-	rc.left--;
-	rc.right = rc.left + size.cx + 2;
-	DrawFocusRect(hDC, &rc);
+        SetTextColor( hDC, (wndPtr->dwStyle & WS_DISABLED) ?
+                     GetSysColor(COLOR_GRAYTEXT) : GetSysColor(COLOR_BTNTEXT));
+        DrawText(hDC, text, -1, &rc,
+                 DT_SINGLELINE | DT_CENTER | DT_VCENTER);
+        /* do we have the focus? */
+        if (infoPtr->state & BUTTON_HASFOCUS)
+        {
+            dwTextSize = GetTextExtent(hDC, text, strlen(text) );
+            delta = ((rc.right - rc.left) - LOWORD(dwTextSize) - 1) >> 1;
+            rc.left += delta;
+            rc.right -= delta;
+            GetTextMetrics(hDC, &tm);
+            delta = ((rc.bottom - rc.top) - tm.tmHeight - 1) >> 1;
+            rc.top += delta; 	rc.bottom -= delta;
+            DrawFocusRect(hDC, &rc);
+        }
     }
 
-    EndPaint(hWnd, &ps);
-    return 0;
+    SelectObject(hDC, (HANDLE)hOldPen);
+    SelectObject(hDC, (HANDLE)hOldBrush);
 }
 
-static LONG RB_LButtonDown(HWND hWnd, WORD wParam, LONG lParam)
+
+/**********************************************************************
+ *       Check Box & Radion Button Functions
+ */
+
+static void CB_Paint( HWND hWnd, HDC hDC, WORD action )
 {
     RECT rc;
+    HBRUSH hBrush;
+    int textlen, delta, x, y;
+    char *text;
+    TEXTMETRIC tm;
+    SIZE size;
+    WND *wndPtr = WIN_FindWndPtr(hWnd);
+    BUTTONINFO *infoPtr = (BUTTONINFO *)wndPtr->wExtra;
 
     GetClientRect(hWnd, &rc);
-    if (GetFocus() != hWnd) SetFocus(hWnd);
-    else rc.right = rc.left + checkBoxWidth;
-    SetCapture(hWnd);
-    InvalidateRect(hWnd, &rc, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
-}
 
-static LONG RB_LButtonUp(HWND hWnd, WORD wParam, LONG lParam)
-{
-    RECT rc;
-    WND *wndPtr = WIN_FindWndPtr(hWnd);
-    LONG style;
+    if (infoPtr->hFont) SelectObject( hDC, infoPtr->hFont );
+    hBrush = SendMessage(GetParent(hWnd), WM_CTLCOLOR, (WORD)hDC,
+			 MAKELPARAM(hWnd, CTLCOLOR_BTN));
+    if (action == ODA_DRAWENTIRE) FillRect(hDC, &rc, hBrush);
 
-    ReleaseCapture();
-    GetClientRect(hWnd, &rc);
+    GetTextMetrics(hDC, &tm);
+    delta = (rc.bottom - rc.top - tm.tmHeight) >> 1;
+    text = USER_HEAP_ADDR( wndPtr->hText );
+    textlen = strlen( text );
 
-    if (PtInRect(&rc, MAKEPOINT(lParam)))
+      /* Draw the check-box bitmap */
+    x = y = 0;
+    if (infoPtr->state & BUTTON_HIGHLIGHTED) x += 2 * checkBoxWidth;
+    if (infoPtr->state & (BUTTON_CHECKED | BUTTON_3STATE)) x += checkBoxWidth;
+    if (((wndPtr->dwStyle & 0x0f) == BS_RADIOBUTTON) ||
+        ((wndPtr->dwStyle & 0x0f) == BS_AUTORADIOBUTTON)) y += checkBoxHeight;
+    else if (infoPtr->state & BUTTON_3STATE) y += 2 * checkBoxHeight;
+    GRAPH_DrawBitmap( hDC, hbitmapCheckBoxes, rc.left, rc.top + delta,
+                      x, y, checkBoxWidth, checkBoxHeight, SRCCOPY );
+    rc.left += checkBoxWidth + tm.tmAveCharWidth / 2;
+
+    if (action == ODA_DRAWENTIRE)
     {
-	style = wndPtr->dwStyle & 0x0000000F;
-	if (style == BS_AUTORADIOBUTTON)
-	    (WORD)(*(wndPtr->wExtra)) = 1;
-	NOTIFY_PARENT(hWnd, BN_CLICKED);
+        if (wndPtr->dwStyle & WS_DISABLED)
+            SetTextColor( hDC, GetSysColor(COLOR_GRAYTEXT) );
+        DrawText(hDC, text, textlen, &rc, DT_SINGLELINE | DT_VCENTER);
     }
-    rc.right = rc.left + checkBoxWidth;
-    InvalidateRect(hWnd, &rc, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
-}
-
-
-static LONG RB_LButtonDblClk(HWND hWnd, WORD wParam, LONG lParam)
-{
-    NOTIFY_PARENT(hWnd, BN_DOUBLECLICKED);
-    return 0;
-}
-
-static LONG RB_KillFocus(HWND hWnd)
-{
-    InvalidateRect(hWnd, NULL, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
-}
-
-static LONG RB_SetCheck(HWND hWnd, WORD wParam)
-{
-    WND *wndPtr = WIN_FindWndPtr(hWnd);
-
-    if ((WORD)(*(wndPtr->wExtra)) != wParam)
+    
+    if ((action == ODA_FOCUS) ||
+        ((action == ODA_DRAWENTIRE) && (infoPtr->state & BUTTON_HASFOCUS)))
     {
-	RECT rc;
-	GetClientRect( hWnd, &rc );
-	rc.right = rc.left + checkBoxWidth;
-	(WORD)(*(wndPtr->wExtra)) = wParam;
-	InvalidateRect(hWnd, &rc, FALSE);
-	UpdateWindow(hWnd);
+        GetTextExtentPoint(hDC, text, textlen, &size);
+        rc.top += delta - 1;
+        rc.bottom -= delta + 1;
+        rc.left--;
+        rc.right = rc.left + size.cx + 2;
+        DrawFocusRect(hDC, &rc);
     }
-    return 0;
-}
-
-static LONG RB_GetCheck(HWND hWnd)
-{
-    WORD wResult;
-    WND *wndPtr = WIN_FindWndPtr(hWnd);
-
-    wResult = (WORD)(*(wndPtr->wExtra));
-    return (LONG)wResult;
 }
 
 
@@ -662,43 +391,37 @@
  *       Group Box Functions
  */
 
-static LONG GB_Paint(HWND hWnd)
+static void GB_Paint( HWND hWnd, HDC hDC, WORD action )
 {
-    PAINTSTRUCT ps;
     RECT rc;
-    HDC hDC;
-    HBRUSH hBrush;
     char *text;
     SIZE size;
     WND *wndPtr = WIN_FindWndPtr( hWnd );
+    BUTTONINFO *infoPtr = (BUTTONINFO *)wndPtr->wExtra;
 
-    hDC = BeginPaint(hWnd, &ps);
+    if (action != ODA_DRAWENTIRE) return;
+
+    if (infoPtr->hFont) SelectObject( hDC, infoPtr->hFont );
+    SendMessage( GetParent(hWnd), WM_CTLCOLOR, (WORD)hDC,
+		 MAKELPARAM(hWnd, CTLCOLOR_BTN));
+    SelectObject( hDC, sysColorObjects.hpenWindowFrame );
+
     GetClientRect(hWnd, &rc);
 
-    SelectObject( hDC, sysColorObjects.hpenWindowFrame );
-    hBrush = SendMessage(GetParent(hWnd), WM_CTLCOLOR, (WORD)hDC,
-			 MAKELPARAM(hWnd, CTLCOLOR_BTN));
-    FillRect(hDC, &rc, hBrush);
+    MoveTo( hDC, rc.left, rc.top+2 );
+    LineTo( hDC, rc.right-1, rc.top+2 );
+    LineTo( hDC, rc.right-1, rc.bottom-1 );
+    LineTo( hDC, rc.left, rc.bottom-1 );
+    LineTo( hDC, rc.left, rc.top+2 );
 
     text = USER_HEAP_ADDR( wndPtr->hText );
     GetTextExtentPoint(hDC, text, strlen(text), &size);
-
-    MoveTo( hDC, 8, 5 );
-    LineTo( hDC, rc.left, 5 );
-    LineTo( hDC, rc.left, rc.bottom-1 );
-    LineTo( hDC, rc.right-1, rc.bottom-1 );
-    LineTo( hDC, rc.right-1, 5 );
-    LineTo( hDC, rc.left + size.cx + 12, 5 );
-
-    rc.left = 10;
-    rc.top = 0;
-    rc.right = rc.left + size.cx + 1;
+    rc.left  += 10;
+    rc.right  = rc.left + size.cx + 1;
     rc.bottom = size.cy;
-    SetTextColor( hDC, GetSysColor(COLOR_WINDOWTEXT) );
+    if (wndPtr->dwStyle & WS_DISABLED)
+        SetTextColor( hDC, GetSysColor(COLOR_GRAYTEXT) );
     DrawText(hDC, text, -1, &rc, DT_SINGLELINE );
-
-    EndPaint(hWnd, &ps);
-    return 0;
 }
 
 
@@ -706,60 +429,25 @@
  *       User Button Functions
  */
 
-static LONG UB_Paint(HWND hWnd)
+static void UB_Paint( HWND hWnd, HDC hDC, WORD action )
 {
-    PAINTSTRUCT ps;
-    HDC hDC;
     RECT rc;
     HBRUSH hBrush;
+    WND *wndPtr = WIN_FindWndPtr( hWnd );
+    BUTTONINFO *infoPtr = (BUTTONINFO *)wndPtr->wExtra;
 
-    hDC = BeginPaint(hWnd, &ps);
+    if (action == ODA_SELECT) return;
+
     GetClientRect(hWnd, &rc);
 
+    if (infoPtr->hFont) SelectObject( hDC, infoPtr->hFont );
     hBrush = SendMessage(GetParent(hWnd), WM_CTLCOLOR, (WORD)hDC,
 			 MAKELPARAM(hWnd, CTLCOLOR_BTN));
     FillRect(hDC, &rc, hBrush);
 
-    NOTIFY_PARENT(hWnd, BN_PAINT);
-
-    /* do we have the focus? */
-    if (GetFocus() == hWnd)
-	DrawFocusRect(hDC, &rc);
-
-    EndPaint(hWnd, &ps);
-    return 0;
-}
-
-static LONG UB_LButtonDown(HWND hWnd, WORD wParam, LONG lParam)
-{
-    SetFocus(hWnd);
-    SetCapture(hWnd);
-    InvalidateRect(hWnd, NULL, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
-}
-
-static LONG UB_LButtonUp(HWND hWnd, WORD wParam, LONG lParam)
-{
-    RECT rc;
-
-    ReleaseCapture();
-    GetClientRect(hWnd, &rc);
-    if (PtInRect(&rc, MAKEPOINT(lParam)))
-    {
-	NOTIFY_PARENT(hWnd, BN_CLICKED);
-	NOTIFY_PARENT(hWnd, BN_UNHILITE);
-    }
-    InvalidateRect(hWnd, NULL, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
-}
-
-static LONG UB_KillFocus(HWND hWnd)
-{
-    InvalidateRect(hWnd, NULL, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
+    if ((action == ODA_FOCUS) ||
+        ((action == ODA_DRAWENTIRE) && (infoPtr->state & BUTTON_HASFOCUS)))
+        DrawFocusRect(hDC, &rc);
 }
 
 
@@ -767,85 +455,29 @@
  *       Ownerdrawn Button Functions
  */
 
-static LONG OB_Paint(HWND hWnd)
+static void OB_Paint( HWND hWnd, HDC hDC, WORD action )
 {
-    PAINTSTRUCT ps;
-    HDC 	hDC;
-    RECT 	rc;
     HANDLE	hDis;
     LPDRAWITEMSTRUCT lpdis;
-    WND *wndPtr = WIN_FindWndPtr(hWnd);
-    hDC = BeginPaint(hWnd, &ps);
-    GetClientRect(hWnd, &rc);
-    hDis = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(DRAWITEMSTRUCT));
-    lpdis = (LPDRAWITEMSTRUCT)USER_HEAP_ADDR(hDis);
-    lpdis->hDC = hDC;
-    lpdis->itemID = 0;
-    CopyRect(&lpdis->rcItem, &rc);
-    lpdis->CtlID = wndPtr->wIDmenu;
-    lpdis->CtlType = ODT_BUTTON;
-    lpdis->itemAction = ODA_DRAWENTIRE;
-/*    printf("ownerdrawn button WM_DRAWITEM CtrlID=%X\n", lpdis->CtlID);*/
-    SendMessage(GetParent(hWnd), WM_DRAWITEM, 1, (LPARAM)lpdis); 
-    USER_HEAP_FREE(hDis);
-    EndPaint(hWnd, &ps);
-    return 0;
-}
+    WND *wndPtr = WIN_FindWndPtr( hWnd );
+    BUTTONINFO *infoPtr = (BUTTONINFO *)wndPtr->wExtra;
 
-static LONG OB_LButtonDown(HWND hWnd, WORD wParam, LONG lParam)
-{
-    HDC 	hDC;
-    HANDLE	hDis;
-    LPDRAWITEMSTRUCT lpdis;
-    WND *wndPtr = WIN_FindWndPtr(hWnd);
-    SetFocus(hWnd);
-    SetCapture(hWnd);
-    hDC = GetDC(hWnd);
-    NOTIFY_PARENT(hWnd, BN_CLICKED);
-    hDis = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(DRAWITEMSTRUCT));
+    if (!(hDis = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(DRAWITEMSTRUCT))))
+        return;
     lpdis = (LPDRAWITEMSTRUCT)USER_HEAP_ADDR(hDis);
-    lpdis->hDC = hDC;
-    lpdis->itemID = 0;
+    lpdis->CtlType    = ODT_BUTTON;
+    lpdis->CtlID      = wndPtr->wIDmenu;
+    lpdis->itemID     = 0;
+    lpdis->itemAction = action;
+    lpdis->itemState  = (infoPtr->state & BUTTON_HASFOCUS) ? ODS_FOCUS : 0 |
+                     (infoPtr->state & BUTTON_HIGHLIGHTED) ? ODS_SELECTED : 0 |
+                     (wndPtr->dwStyle & WS_DISABLED) ? ODS_DISABLED : 0;
+    lpdis->hwndItem   = hWnd;
+    lpdis->hDC        = hDC;
     GetClientRect( hWnd, &lpdis->rcItem );
-    lpdis->CtlID = wndPtr->wIDmenu;
-    lpdis->CtlType = ODT_BUTTON;
-    lpdis->itemAction = ODA_SELECT;
+    lpdis->itemData   = 0;
     SendMessage(GetParent(hWnd), WM_DRAWITEM, 1, (LPARAM)lpdis); 
     USER_HEAP_FREE(hDis);
-    ReleaseDC(hWnd, hDC);
-    return 0;
 }
 
-static LONG OB_LButtonUp(HWND hWnd, WORD wParam, LONG lParam)
-{
-    HDC 	hDC;
-    RECT 	rc;
-    HANDLE	hDis;
-    LPDRAWITEMSTRUCT lpdis;
-    WND *wndPtr = WIN_FindWndPtr(hWnd);
-    ReleaseCapture();
-    hDC = GetDC(hWnd);
-    GetClientRect(hWnd, &rc);
-    if (PtInRect(&rc, MAKEPOINT(lParam)))
-	NOTIFY_PARENT(hWnd, BN_CLICKED);
-    hDis = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(DRAWITEMSTRUCT));
-    lpdis = (LPDRAWITEMSTRUCT)USER_HEAP_ADDR(hDis);
-    lpdis->hDC = hDC;
-    lpdis->itemID = 0;
-    CopyRect(&lpdis->rcItem, &rc);
-    lpdis->CtlID = wndPtr->wIDmenu;
-    lpdis->CtlType = ODT_BUTTON;
-    lpdis->itemAction = ODA_SELECT;
-    SendMessage(GetParent(hWnd), WM_DRAWITEM, 1, (LPARAM)lpdis); 
-    USER_HEAP_FREE(hDis);
-    ReleaseDC(hWnd, hDC);
-    return 0;
-}
-
-static LONG OB_KillFocus(HWND hWnd)
-{
-    InvalidateRect(hWnd, NULL, FALSE);
-    UpdateWindow(hWnd);
-    return 0;
-}
 
diff --git a/controls/combo.c b/controls/combo.c
index d059176..0dc66fb 100644
--- a/controls/combo.c
+++ b/controls/combo.c
@@ -5,11 +5,6 @@
  *
  */
 
-#define DEBUG_COMBO
-/*
-#define DEBUG_COMBO
-*/
-
 static char Copyright[] = "Copyright Martin Ayotte, 1993";
 
 #include <stdio.h>
@@ -22,6 +17,11 @@
 #include "heap.h"
 #include "win.h"
 #include "prototypes.h"
+#include "stddebug.h"
+/* #define DEBUG_COMBO */
+/* #undef  DEBUG_COMBO */
+#include "debug.h"
+
 
 HBITMAP hComboBit = 0;
 
@@ -34,26 +34,22 @@
  */
 LONG ComboBoxWndProc( HWND hwnd, WORD message, WORD wParam, LONG lParam )
 {    
-    WORD	wRet;
     RECT	rect;
     int		y, count;
     int		width, height;
-    int		AltState;
     WND  	*wndPtr;
     LPHEADCOMBO lphc;
-    HDC		hDC, hMemDC;
+    HDC		hDC;
     BITMAP	bm;
     char	str[128];
     PAINTSTRUCT paintstruct;
-    static RECT rectsel;
+    int         style;
     switch(message)
     {
     case WM_CREATE:
 		wndPtr = WIN_FindWndPtr(hwnd);
 		if (wndPtr == NULL) return 0;
-#ifdef DEBUG_COMBO
-		printf("Combo WM_CREATE %lX !\n", lphc);
-#endif
+		dprintf_combo(stddeb,"Combo WM_CREATE %p !\n", lphc);
 		if (hComboBit == (HBITMAP)NULL) 
 		hComboBit = LoadBitmap((HINSTANCE)NULL, MAKEINTRESOURCE(OBM_COMBO));
 		GetObject(hComboBit, sizeof(BITMAP), (LPSTR)&bm);
@@ -77,15 +73,21 @@
 				WS_CHILD | WS_CLIPCHILDREN | WS_VISIBLE | SS_LEFT,
 				0, 0, width - bm.bmHeight, bm.bmHeight, 
 				hwnd, 1, wndPtr->hInstance, 0L);
+		style=0;
+		if ((wndPtr->dwStyle & CBS_HASSTRINGS) == CBS_HASSTRINGS)
+			style |= LBS_HASSTRINGS;
+		if ((wndPtr->dwStyle & CBS_OWNERDRAWFIXED) ==CBS_OWNERDRAWFIXED)
+			style |= LBS_OWNERDRAWFIXED;
+		if ((wndPtr->dwStyle & CBS_OWNERDRAWVARIABLE)==CBS_OWNERDRAWVARIABLE)
+			style |= LBS_OWNERDRAWVARIABLE;
 		lphc->hWndLBox = CreateWindow("LISTBOX", "", 
-			WS_POPUP | WS_BORDER | WS_VSCROLL | LBS_NOTIFY,
+			WS_POPUP | WS_BORDER | WS_VSCROLL | LBS_NOTIFY | style,
 			rect.left, rect.top + bm.bmHeight, 
 			width, height, wndPtr->hwndParent, 0, 
 			wndPtr->hInstance, (LPSTR)MAKELONG(0, hwnd));
 		ShowWindow(lphc->hWndLBox, SW_HIDE);
-#ifdef DEBUG_COMBO
-		printf("Combo Creation LBox=%X!\n", lphc->hWndLBox);
-#endif
+		dprintf_combo(stddeb,"Combo Creation LBox=%X!\n", 
+			      lphc->hWndLBox);
 		return 0;
     case WM_DESTROY:
 		lphc = ComboGetStorageHeader(hwnd);
@@ -99,14 +101,11 @@
 		*((LPHEADCOMBO *)&wndPtr->wExtra[1]) = 0; 
 		printf("Combo WM_DESTROY after clearing wExtra !\n");
 */
-#ifdef DEBUG_COMBO
-		printf("Combo WM_DESTROY %lX !\n", lphc);
-#endif
+		dprintf_combo(stddeb,"Combo WM_DESTROY %p !\n", lphc);
 		return DefWindowProc( hwnd, message, wParam, lParam );
 	case WM_SHOWWINDOW:
-#ifdef DEBUG_COMBO
-		printf("ComboBox WM_SHOWWINDOW hWnd=%04X !\n", hwnd);
-#endif
+		dprintf_combo(stddeb,"ComboBox WM_SHOWWINDOW hWnd=%04X !\n", 
+			      hwnd);
 		if (!(wParam == 0 && lParam == 0L)) {
 			InvalidateRect(hwnd, NULL, TRUE);
 			}
@@ -137,12 +136,12 @@
             }
 		break;
     case WM_LBUTTONDOWN:
-		printf("Combo WM_LBUTTONDOWN wParam=%x lParam=%lX !\n", wParam, lParam);
+		dprintf_combo(stddeb,"Combo WM_LBUTTONDOWN wParam=%x lParam=%lX !\n", wParam, lParam);
 		GetClientRect(hwnd, &rect);
 		rect.left = rect.right - (rect.bottom - rect.top); 
 		hDC = GetDC(hwnd);
 		InflateRect(&rect, -1, -1);
-		DrawReliefRect(hDC, rect, 1, 1);
+		GRAPH_DrawReliefRect(hDC, &rect, 1, 1);
 		ReleaseDC(hwnd, hDC);
 		wndPtr = WIN_FindWndPtr(hwnd);
 		lphc = ComboGetStorageHeader(hwnd);
@@ -153,27 +152,27 @@
 		    SetFocus(lphc->hWndLBox);
 			}
 		else {
-			printf("before Combo Restore Focus !\n");
+			dprintf_combo(stddeb,"before Combo Restore Focus !\n");
 			SetFocus(lphc->hWndEdit);
-			printf("before Combo List Hide !\n");
+			dprintf_combo(stddeb,"before Combo List Hide !\n");
 			ShowWindow(lphc->hWndLBox, SW_HIDE);
-			printf("before Combo List GetCurSel !\n");
+			dprintf_combo(stddeb,"before Combo List GetCurSel !\n");
 			y = SendMessage(lphc->hWndLBox, LB_GETCURSEL, 0, 0L);
 			if (y != LB_ERR) {
-				printf("before Combo List GetText !\n");
+				dprintf_combo(stddeb,"before Combo List GetText !\n");
 				SendMessage(lphc->hWndLBox, LB_GETTEXT, (WORD)y, (LPARAM)str);
 				SendMessage(lphc->hWndEdit, WM_SETTEXT, (WORD)y, (LPARAM)str);
 				}
-			printf("End of Combo List Hide !\n");
+			dprintf_combo(stddeb,"End of Combo List Hide !\n");
 			}
 		break;
     case WM_LBUTTONUP:
-		printf("Combo WM_LBUTTONUP wParam=%x lParam=%lX !\n", wParam, lParam);
+		dprintf_combo(stddeb,"Combo WM_LBUTTONUP wParam=%x lParam=%lX !\n", wParam, lParam);
 		GetClientRect(hwnd, &rect);
 		rect.left = rect.right - (rect.bottom - rect.top); 
 		hDC = GetDC(hwnd);
 		InflateRect(&rect, -1, -1);
-		DrawReliefRect(hDC, rect, 1, 0);
+		GRAPH_DrawReliefRect(hDC, &rect, 1, 0);
 		ReleaseDC(hwnd, hDC);
 		break;
    case WM_KEYDOWN:
@@ -182,7 +181,7 @@
 		if (lphc == NULL) return 0;
 		y = SendMessage(lphc->hWndLBox, LB_GETCURSEL, 0, 0L);
 		count = SendMessage(lphc->hWndLBox, LB_GETCOUNT, 0, 0L);
-		printf("COMBOBOX // GetKeyState(VK_MENU)=%d\n", GetKeyState(VK_MENU));
+		dprintf_combo(stddeb,"COMBOBOX // GetKeyState(VK_MENU)=%d\n", GetKeyState(VK_MENU));
 		if (GetKeyState(VK_MENU) < 0) {
 			lphc->dwState = lphc->dwState ^ CB_SHOWDROPDOWN;
 			if ((lphc->dwState & CB_SHOWDROPDOWN) == CB_SHOWDROPDOWN) {
@@ -223,21 +222,22 @@
 			}
 		break;
     case WM_MEASUREITEM:
-		printf("ComboBoxWndProc WM_MEASUREITEM !\n");
+	dprintf_combo(stddeb,"ComboBoxWndProc WM_MEASUREITEM !\n");
     	return(SendMessage(GetParent(hwnd), WM_MEASUREITEM, wParam, lParam));
     case WM_CTLCOLOR:
     	return(SendMessage(GetParent(hwnd), WM_CTLCOLOR, wParam, lParam));
+    case WM_DRAWITEM:
+	return(SendMessage(GetParent(hwnd), WM_DRAWITEM, wParam, lParam));
     case WM_PAINT:
 		GetClientRect(hwnd, &rect);
 		hDC = BeginPaint(hwnd, &paintstruct);
-		hMemDC = CreateCompatibleDC(hDC);
-		if (hMemDC != 0 && hComboBit != 0) {
+		if (hComboBit != 0) {
 			GetObject(hComboBit, sizeof(BITMAP), (LPSTR)&bm);
-			SelectObject(hMemDC, hComboBit);
-			BitBlt(hDC, rect.right - bm.bmWidth, 0, 
-			bm.bmWidth, bm.bmHeight, hMemDC, 0, 0, SRCCOPY);
+                        GRAPH_DrawBitmap( hDC, hComboBit,
+                                          rect.right - bm.bmWidth, 0,
+                                          0, 0, bm.bmWidth, bm.bmHeight,
+                                          SRCCOPY );
 			}
-		DeleteDC(hMemDC);
 		EndPaint(hwnd, &paintstruct);
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
@@ -264,41 +264,37 @@
 			}
 		break;
 	case CB_ADDSTRING:
-#ifdef DEBUG_COMBO
-		printf("CB_ADDSTRING '%s' !\n", (LPSTR)lParam);
-#endif
+                dprintf_combo(stddeb,"CB_ADDSTRING '%s' !\n", (LPSTR)lParam);
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		return(SendMessage(lphc->hWndLBox, LB_ADDSTRING, wParam, lParam));
     case CB_GETLBTEXT:
-#ifdef DEBUG_COMBO
-		printf("CB_GETLBTEXT #%u !\n", wParam);
-#endif
+		dprintf_combo(stddeb,"CB_GETLBTEXT #%u !\n", wParam);
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		return(SendMessage(lphc->hWndLBox, LB_GETTEXT, wParam, lParam));
     case CB_GETLBTEXTLEN:
-		printf("CB_GETLBTEXTLEN !\n");
+		dprintf_combo(stddeb,"CB_GETLBTEXTLEN !\n");
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		return(SendMessage(lphc->hWndLBox, LB_GETTEXTLEN, wParam, lParam));
     case CB_INSERTSTRING:
-		printf("CB_INSERTSTRING '%s' !\n", (LPSTR)lParam);
+		dprintf_combo(stddeb,"CB_INSERTSTRING '%s' !\n",(LPSTR)lParam);
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		return(SendMessage(lphc->hWndLBox, LB_INSERTSTRING, wParam, lParam));
 	case CB_DELETESTRING:
-		printf("CB_DELETESTRING #%u !\n", wParam);
+		dprintf_combo(stddeb,"CB_DELETESTRING #%u !\n", wParam);
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		return(SendMessage(lphc->hWndLBox, LB_DELETESTRING, wParam, 0L));
 	case CB_RESETCONTENT:
-		printf("CB_RESETCONTENT !\n");
+		dprintf_combo(stddeb,"CB_RESETCONTENT !\n");
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		return(SendMessage(lphc->hWndLBox, LB_RESETCONTENT, 0, 0L));
     case CB_DIR:
-		printf("ComboBox CB_DIR !\n");
+		dprintf_combo(stddeb,"ComboBox CB_DIR !\n");
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		return(SendMessage(lphc->hWndLBox, LB_DIR, wParam, lParam));
@@ -310,34 +306,35 @@
 		if (lphc == NULL) return 0;
 		return(SendMessage(lphc->hWndLBox, LB_GETCOUNT, 0, 0L));
 	case CB_GETCURSEL:
-		printf("ComboBox CB_GETCURSEL !\n");
+		dprintf_combo(stddeb,"ComboBox CB_GETCURSEL !\n");
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		return(SendMessage(lphc->hWndLBox, LB_GETCURSEL, 0, 0L));
     case CB_SETCURSEL:
-		printf("ComboBox CB_SETCURSEL wParam=%X !\n", wParam);
+		dprintf_combo(stddeb,"ComboBox CB_SETCURSEL wParam=%X !\n", wParam);
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		return(SendMessage(lphc->hWndLBox, LB_SETCURSEL, wParam, 0L));
 	case CB_GETEDITSEL:
-		printf("ComboBox CB_GETEDITSEL !\n");
+		dprintf_combo(stddeb,"ComboBox CB_GETEDITSEL !\n");
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 /*        return(SendMessage(lphc->hWndEdit, EM_GETSEL, 0, 0L)); */
 		break;
 	case CB_SETEDITSEL:
-		printf("ComboBox CB_SETEDITSEL lParam=%lX !\n", lParam);
+		dprintf_combo(stddeb,"ComboBox CB_SETEDITSEL lParam=%lX !\n", 
+			      lParam);
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 /*        return(SendMessage(lphc->hWndEdit, EM_SETSEL, 0, lParam)); */
 		break;
 	case CB_SELECTSTRING:
-		printf("ComboBox CB_SELECTSTRING !\n");
+		dprintf_combo(stddeb,"ComboBox CB_SELECTSTRING !\n");
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		break;
 	case CB_SHOWDROPDOWN:
-		printf("ComboBox CB_SHOWDROPDOWN !\n");
+		dprintf_combo(stddeb,"ComboBox CB_SHOWDROPDOWN !\n");
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		lphc->dwState = lphc->dwState | CB_SHOWDROPDOWN;
@@ -352,19 +349,19 @@
 		}
 		break;
     case CB_GETITEMDATA:
-		printf("ComboBox CB_GETITEMDATA wParam=%X !\n", wParam);
+		dprintf_combo(stddeb,"ComboBox CB_GETITEMDATA wParam=%X !\n", wParam);
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		return(SendMessage(lphc->hWndLBox, LB_GETITEMDATA, wParam, 0L));
         break;
     case CB_SETITEMDATA:
-		printf("ComboBox CB_SETITEMDATA wParam=%X lParam=%lX !\n", wParam, lParam);
+		dprintf_combo(stddeb,"ComboBox CB_SETITEMDATA wParam=%04X lParam=%08lX!\n", wParam, lParam);
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 		return(SendMessage(lphc->hWndLBox, LB_SETITEMDATA, wParam, lParam));
         break;
     case CB_LIMITTEXT:
-		printf("ComboBox CB_LIMITTEXT !\n");
+		dprintf_combo(stddeb,"ComboBox CB_LIMITTEXT !\n");
 		lphc = ComboGetStorageHeader(hwnd);
 		if (lphc == NULL) return 0;
 /*        return(SendMessage(lphc->hWndEdit, EM_LIMITTEXT, wParam, 0L)); */
@@ -384,7 +381,7 @@
     LPHEADCOMBO lphc;
     wndPtr = WIN_FindWndPtr(hwnd);
     if (wndPtr == 0) {
-    	printf("Bad Window handle on ComboBox !\n");
+    	fprintf(stderr,"Bad Window handle on ComboBox !\n");
     	return 0;
     	}
     lphc = *((LPHEADCOMBO *)&wndPtr->wExtra[1]);
@@ -399,7 +396,7 @@
     LPHEADCOMBO lphc;
     wndPtr = WIN_FindWndPtr(hwnd);
     if (wndPtr == 0) {
-    	printf("Bad Window handle on ComboBox !\n");
+    	fprintf(stderr,"Bad Window handle on ComboBox !\n");
     	return 0;
     	}
     lphc = (LPHEADCOMBO)malloc(sizeof(HEADCOMBO));
@@ -415,19 +412,20 @@
  */
 BOOL DlgDirSelectComboBox(HWND hDlg, LPSTR lpStr, int nIDLBox)
 {
-	printf("DlgDirSelectComboBox(%04X, '%s', %d) \n",	hDlg, lpStr, nIDLBox);
+	fprintf(stdnimp,"DlgDirSelectComboBox(%04X, '%s', %d) \n",	
+		hDlg, lpStr, nIDLBox);
 }
 
 
 /************************************************************************
- * 					DlgDirListComboBox		[USER.195]
+ * 					DlgDirListComboBox     [USER.195]
  */
 int DlgDirListComboBox(HWND hDlg, LPSTR lpPathSpec, 
 	int nIDLBox, int nIDStat, WORD wType)
 {
 	HWND		hWnd;
-    LPHEADCOMBO lphc;
-	printf("DlgDirListComboBox(%04X, '%s', %d, %d, %04X) \n",
+	LPHEADCOMBO lphc;
+	dprintf_combo(stddeb,"DlgDirListComboBox(%04X, '%s', %d, %d, %04X) \n",
 			hDlg, lpPathSpec, nIDLBox, nIDStat, wType);
 	hWnd = GetDlgItem(hDlg, nIDLBox);
 	lphc = ComboGetStorageHeader(hWnd);
diff --git a/controls/desktop.c b/controls/desktop.c
index 4045177..920ac23 100644
--- a/controls/desktop.c
+++ b/controls/desktop.c
@@ -10,6 +10,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <unistd.h>
 #include "win.h"
 #include "desktop.h"
 #include "prototypes.h"
@@ -213,7 +214,7 @@
 	int i;
 
 	for (i = 0; i < 8; i++) pattern[i] = pat[i] & 0xffff;
-	hbitmap = CreateBitmap( 8, 8, 1, 1, pattern );
+	hbitmap = CreateBitmap( 8, 8, 1, 1, (LPSTR)pattern );
 	infoPtr->hbrushPattern = CreatePatternBrush( hbitmap );
 	DeleteObject( hbitmap );
     }
diff --git a/controls/edit.c b/controls/edit.c
index bcbe8f2..968cc3d 100644
--- a/controls/edit.c
+++ b/controls/edit.c
@@ -8,6 +8,7 @@
 
 static char Copyright[] = "Copyright  David W. Metcalfe, 1994";
 
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <windows.h>
@@ -16,8 +17,11 @@
 #include "class.h"
 #include "user.h"
 #include "scroll.h"
-
+#include "stddebug.h"
 /* #define DEBUG_EDIT /* */
+/* #undef  DEBUG_EDIT /* */
+#include "debug.h"
+
 
 #define NOTIFY_PARENT(hWndCntrl, wNotifyCode) \
 	SendMessage(GetParent(hWndCntrl), WM_COMMAND, \
@@ -190,7 +194,7 @@
 	break;
 
     case EM_FMTLINES:
-	printf("edit: EM_FMTLINES message received\n");
+	fprintf(stdnimp,"edit: EM_FMTLINES message received\n");
 	if (!wParam)
 	    lResult = 1L;
 	else
@@ -224,7 +228,7 @@
 	break;
 
     case EM_GETPASSWORDCHAR:
-	printf("edit: cannot process EM_GETPASSWORDCHAR message\n");
+	fprintf(stdnimp,"edit: cannot process EM_GETPASSWORDCHAR message\n");
 	break;
 
     case EM_GETRECT:
@@ -236,7 +240,7 @@
 	break;
 
     case EM_GETWORDBREAKPROC:
-	printf("edit: cannot process EM_GETWORDBREAKPROC message\n");
+	fprintf(stdnimp,"edit: cannot process EM_GETWORDBREAKPROC message\n");
 	break;
 
     case EM_LIMITTEXT:
@@ -264,7 +268,7 @@
 	break;
 
     case EM_LINESCROLL:
-	printf("edit: cannot process EM_LINESCROLL message\n");
+	fprintf(stdnimp,"edit: cannot process EM_LINESCROLL message\n");
 	break;
 
     case EM_REPLACESEL:
@@ -283,16 +287,16 @@
 	break;
 
     case EM_SETPASSWORDCHAR:
-	printf("edit: cannot process EM_SETPASSWORDCHAR message\n");
+	fprintf(stdnimp,"edit: cannot process EM_SETPASSWORDCHAR message\n");
 	break;
 
     case EM_SETREADONLY:
-	printf("edit: cannot process EM_SETREADONLY message\n");
+	fprintf(stdnimp,"edit: cannot process EM_SETREADONLY message\n");
 	break;
 
     case EM_SETRECT:
     case EM_SETRECTNP:
-	printf("edit: cannot process EM_SETRECT(NP) message\n");
+	fprintf(stdnimp,"edit: cannot process EM_SETRECT(NP) message\n");
 	break;
 
     case EM_SETSEL:
@@ -307,7 +311,7 @@
 	break;
 
     case EM_SETWORDBREAKPROC:
-	printf("edit: cannot process EM_SETWORDBREAKPROC message\n");
+	fprintf(stdnimp,"edit: cannot process EM_SETWORDBREAKPROC message\n");
 	break;
 
     case EM_UNDO:
@@ -317,6 +321,9 @@
 	ShowCaret(hwnd);
 	break;
 
+    case WM_GETDLGCODE:
+        return DLGC_HASSETSEL | DLGC_WANTCHARS | DLGC_WANTARROWS;
+
     case WM_CHAR:
 	EDIT_CharMsg(hwnd, wParam);
 	break;
@@ -351,7 +358,7 @@
 	if ((int)wParam > (len = strlen(textPtr)))
 	{
 	    strcpy((char *)lParam, textPtr);
-	    lResult = (DWORD)len;
+	    lResult = (DWORD)len ;
 	}
 	else
 	    lResult = 0L;
@@ -461,11 +468,17 @@
     char *text;
     int len;
 
-    /* store pointer to local heap in window structure so that */
+    /* store pointer to local or global heap in window structure so that */
     /* EDITSTATE structure itself can be stored on local heap  */
-    (MDESC **)*(LONG *)(wndPtr->wExtra + 2) = 
+    if (HEAP_LocalFindHeap(createStruct->hInstance)!=NULL)
+      (MDESC **)*(LONG *)(wndPtr->wExtra + 2) = 
 	&HEAP_LocalFindHeap(createStruct->hInstance)->free_list;
-
+    else
+      {
+	(MDESC **)*(LONG *)(wndPtr->wExtra + 2) =
+	  GlobalLock(createStruct->hInstance);
+	/* GlobalUnlock(createStruct->hInstance); */
+      }
     /* allocate space for state variable structure */
     (HANDLE)(*(wndPtr->wExtra)) = EDIT_HeapAlloc(hwnd, sizeof(EDITSTATE));
     es = (EDITSTATE *)EDIT_HeapAddr(hwnd, (HANDLE)(*(wndPtr->wExtra)));
@@ -647,7 +660,7 @@
 	/* advance through current line */
 	while (*cp && *cp != '\n')
 	{
-	    len += EDIT_CharWidth(hwnd, *cp, len);
+	    len += EDIT_CharWidth(hwnd, (BYTE)*cp, len);
 	                                     /* width of line in pixels */
 	    cp++;
 	}
@@ -697,10 +710,8 @@
     hdc = BeginPaint(hwnd, &ps);
     rc = ps.rcPaint;
 
-#ifdef DEBUG_EDIT
-    printf("WM_PAINT: rc=(%d,%d), (%d,%d)\n", rc.left, rc.top, 
+    dprintf_edit(stddeb,"WM_PAINT: rc=(%d,%d), (%d,%d)\n", rc.left, rc.top, 
 	   rc.right, rc.bottom);
-#endif
 
     if (es->PaintBkgd)
 	FillWindow(GetParent(hwnd), hwnd, hdc, CTLCOLOR_EDIT);
@@ -728,9 +739,7 @@
     int len = 0;
     char *cp, *cp1;
 
-#ifdef DEBUG_EDIT
-    printf("GetTextLine %d\n", selection);
-#endif
+    dprintf_edit(stddeb,"GetTextLine %d\n", selection);
     cp = cp1 = EDIT_TextLine(hwnd, selection);
     /* advance through line */
     while (*cp && *cp != '\n')
@@ -783,11 +792,9 @@
 	(EDITSTATE *)EDIT_HeapAddr(hwnd, (HANDLE)(*(wndPtr->wExtra)));
 
     for (i = 0; i < len; i++)
-	plen += EDIT_CharWidth(hwnd, *(str + i), pcol + plen);
+	plen += EDIT_CharWidth(hwnd, (BYTE)(*(str + i)), pcol + plen);
 
-#ifdef DEBUG_EDIT
-    printf("EDIT_StrLength: returning %d\n", plen);
-#endif
+    dprintf_edit(stddeb,"EDIT_StrLength: returning %d\n", plen);
     return plen;
 }
 
@@ -838,42 +845,32 @@
     else
 	GetClientRect(hwnd, &rc);
 
-#ifdef DEBUG_EDIT
-    printf("WriteTextLine %d\n", y);
-#endif
+    dprintf_edit(stddeb,"WriteTextLine %d\n", y);
 
     /* make sure y is inside the window */
     if (y < es->wtop || y > (es->wtop + ClientHeight(wndPtr, es)))
     {
-#ifdef DEBUG_EDIT
-	printf("EDIT_WriteTextLine: y (%d) is not a displayed line\n", y);
-#endif
+	dprintf_edit(stddeb,"EDIT_WriteTextLine: y (%d) is not a displayed line\n", y);
 	return;
     }
 
     /* make sure rectangle is within window */
     if (rc.left >= ClientWidth(wndPtr) - 1)
     {
-#ifdef DEBUG_EDIT
-	printf("EDIT_WriteTextLine: rc.left (%d) is greater than right edge\n",
+	dprintf_edit(stddeb,"EDIT_WriteTextLine: rc.left (%d) is greater than right edge\n",
 	       rc.left);
-#endif
 	return;
     }
     if (rc.right <= 0)
     {
-#ifdef DEBUG_EDIT
-	printf("EDIT_WriteTextLine: rc.right (%d) is less than left edge\n",
+	dprintf_edit(stddeb,"EDIT_WriteTextLine: rc.right (%d) is less than left edge\n",
 	       rc.right);
-#endif
 	return;
     }
     if (y - es->wtop < (rc.top / es->txtht) || 
 	y - es->wtop > (rc.bottom / es->txtht))
     {
-#ifdef DEBUG_EDIT
-	printf("EDIT_WriteTextLine: y (%d) is outside window\n", y);
-#endif
+	dprintf_edit(stddeb,"EDIT_WriteTextLine: y (%d) is outside window\n", y);
 	return;
     }
 
@@ -1010,9 +1007,7 @@
     short *charWidths = (short *)EDIT_HeapAddr(hwnd, es->hCharWidths);
     char *blanks = (char *)EDIT_HeapAddr(hwnd, es->hBlankLine);
 
-#ifdef DEBUG_EDIT
-    printf("EDIT_WriteText lp=%s, off=%d, len=%d, row=%d, col=%d, reverse=%d\n", lp, off, len, row, col, reverse);
-#endif
+    dprintf_edit(stddeb,"EDIT_WriteText lp=%s, off=%d, len=%d, row=%d, col=%d, reverse=%d\n", lp, off, len, row, col, reverse);
 
     hdc = GetDC(hwnd);
     hStr = EDIT_GetStr(hwnd, lp, off, len, &diff);
@@ -1111,14 +1106,12 @@
     EDITSTATE *es = 
 	(EDITSTATE *)EDIT_HeapAddr(hwnd, (HANDLE)(*(wndPtr->wExtra)));
 
-#ifdef DEBUG_EDIT
-    printf("EDIT_GetStr %s %d %d\n", lp, off, len);
-#endif
+    dprintf_edit(stddeb,"EDIT_GetStr %s %d %d\n", lp, off, len);
 
     while (i < off)
     {
 	s_i = i;
-	i += EDIT_CharWidth(hwnd, *(lp + ch), i);
+	i += EDIT_CharWidth(hwnd, (BYTE)(*(lp + ch)), i);
 	ch++;
     }
 
@@ -1133,7 +1126,7 @@
 
     while (i < len + off)
     {
-	i += EDIT_CharWidth(hwnd, *(lp + ch), i);
+	i += EDIT_CharWidth(hwnd, (BYTE)(*(lp + ch)), i);
 	ch++;
     }
     
@@ -1142,9 +1135,7 @@
     for (i = ch1, j = 0; i < ch; i++, j++)
 	str[j] = lp[i];
     str[++j] = '\0';
-#ifdef DEBUG_EDIT
-    printf("EDIT_GetStr: returning %s\n", str);
-#endif
+    dprintf_edit(stddeb,"EDIT_GetStr: returning %s\n", str);
     return hStr;
 }
 
@@ -1159,9 +1150,7 @@
     EDITSTATE *es = 
 	(EDITSTATE *)EDIT_HeapAddr(hwnd, (HANDLE)(*(wndPtr->wExtra)));
 
-#ifdef DEBUG_EDIT
-    printf("EDIT_CharMsg: wParam=%c\n", (char)wParam);
-#endif
+    dprintf_edit(stddeb,"EDIT_CharMsg: wParam=%c\n", (char)wParam);
 
     switch (wParam)
     {
@@ -1203,9 +1192,7 @@
     RECT rc;
     BOOL FullPaint = FALSE;
 
-#ifdef DEBUG_EDIT
-    printf("EDIT_KeyTyped: ch=%c\n", (char)ch);
-#endif
+    dprintf_edit(stddeb,"EDIT_KeyTyped: ch=%c\n", (char)ch);
 
     /* delete selected text (if any) */
     if (SelMarked(es))
@@ -1294,14 +1281,14 @@
 
     /* test end of window */
     if (es->WndCol >= ClientWidth(wndPtr) - 
-	                    EDIT_CharWidth(hwnd, ch, es->WndCol + es->wleft))
+	                    EDIT_CharWidth(hwnd, (BYTE)ch, es->WndCol + es->wleft))
     {
 	/* TODO:- Word wrap to be handled here */
 
 /*	if (!(currchar == text + es->MaxTextLen - 2)) */
 	    EDIT_KeyHScroll(hwnd, SB_LINEDOWN);
     }
-    es->WndCol += EDIT_CharWidth(hwnd, ch, es->WndCol + es->wleft);
+    es->WndCol += EDIT_CharWidth(hwnd, (BYTE)ch, es->WndCol + es->wleft);
     es->CurrCol++;
     SetCaretPos(es->WndCol, es->WndRow * es->txtht);
     ShowCaret(hwnd);
@@ -1385,7 +1372,7 @@
     }
     else
     {
-	es->WndCol += EDIT_CharWidth(hwnd, *CurrChar, es->WndCol + es->wleft);
+	es->WndCol += EDIT_CharWidth(hwnd, (BYTE)(*CurrChar), es->WndCol + es->wleft);
 	es->CurrCol++;
 	if (es->WndCol >= ClientWidth(wndPtr))
 	    EDIT_KeyHScroll(hwnd, SB_LINEDOWN);
@@ -1406,9 +1393,8 @@
     EDITSTATE *es = 
 	(EDITSTATE *)EDIT_HeapAddr(hwnd, (HANDLE)(*(wndPtr->wExtra)));
 
-#ifdef DEBUG_EDIT
-    printf("EDIT_Downward: WndRow=%d, wtop=%d, wlines=%d\n", es->WndRow, es->wtop, es->wlines);
-#endif
+    dprintf_edit(stddeb,"EDIT_Downward: WndRow=%d, wtop=%d, wlines=%d\n", 
+	     es->WndRow, es->wtop, es->wlines);
 
     if (IsMultiLine() && (es->WndRow + es->wtop + 1 < es->wlines))
     {
@@ -1469,12 +1455,12 @@
     {
 	--es->CurrCol;
 	if (*CurrChar == VK_TAB)
-	    es->WndCol -= EDIT_CharWidth(hwnd, *CurrChar, 
+	    es->WndCol -= EDIT_CharWidth(hwnd, (BYTE)(*CurrChar), 
 					 EDIT_StrLength(hwnd, 
 					 EDIT_TextLine(hwnd, es->CurrLine), 
 					 es->CurrCol, 0));
 	else
-	    es->WndCol -= EDIT_CharWidth(hwnd, *CurrChar, 0);
+	    es->WndCol -= EDIT_CharWidth(hwnd, (BYTE)(*CurrChar), 0);
 	if (es->WndCol < 0)
 	    EDIT_KeyHScroll(hwnd, SB_LINEUP);
     }
@@ -1502,7 +1488,7 @@
 
     while (*CurrChar && *CurrChar != '\n')
     {
-	es->WndCol += EDIT_CharWidth(hwnd, *CurrChar, es->WndCol + es->wleft);
+	es->WndCol += EDIT_CharWidth(hwnd, (BYTE)(*CurrChar), es->WndCol + es->wleft);
 	es->CurrCol++;
     }
 
@@ -1583,9 +1569,7 @@
     EDITSTATE *es = 
 	(EDITSTATE *)EDIT_HeapAddr(hwnd, (HANDLE)(*(wndPtr->wExtra)));
 
-#ifdef DEBUG_EDIT
-    printf("EDIT_KeyDownMsg: key=%x\n", wParam);
-#endif
+    dprintf_edit(stddeb,"EDIT_KeyDownMsg: key=%x\n", wParam);
 
     HideCaret(hwnd);
     switch (wParam)
@@ -2014,9 +1998,7 @@
     EDITSTATE *es = 
 	(EDITSTATE *)EDIT_HeapAddr(hwnd, (HANDLE)(*(wndPtr->wExtra)));
 
-#ifdef DEBUG_EDIT
-    printf("EDIT_VScrollLine: direction=%d\n", opt);
-#endif
+    dprintf_edit(stddeb,"EDIT_VScrollLine: direction=%d\n", opt);
 
     if (opt == SB_LINEDOWN)
     {
@@ -2222,15 +2204,13 @@
     EDITSTATE *es = 
 	(EDITSTATE *)EDIT_HeapAddr(hwnd, (HANDLE)(*(wndPtr->wExtra)));
 
-#ifdef DEBUG_EDIT
-    printf("EDIT_PixelToChar: row=%d, pixel=%d\n", row, *pixel);
-#endif
+    dprintf_edit(stddeb,"EDIT_PixelToChar: row=%d, pixel=%d\n", row, *pixel);
 
     text = EDIT_TextLine(hwnd, row);
     while (i < *pixel)
     {
 	s_i = i;
-	i += EDIT_CharWidth(hwnd, *(text + ch), i);
+	i += EDIT_CharWidth(hwnd, (BYTE)(*(text + ch)), i);
 	ch++;
     }
 
@@ -2581,9 +2561,7 @@
     EDITSTATE *es = 
 	(EDITSTATE *)EDIT_HeapAddr(hwnd, (HANDLE)(*(wndPtr->wExtra)));
 
-#ifdef DEBUG_EDIT
-    printf("EDIT_ExtendSel: x=%d, y=%d\n", x, y);
-#endif
+    dprintf_edit(stddeb,"EDIT_ExtendSel: x=%d, y=%d\n", x, y);
 
     bbl = es->SelEndLine;
     bbc = es->SelEndCol;
@@ -2657,9 +2635,7 @@
     EDITSTATE *es = 
 	(EDITSTATE *)EDIT_HeapAddr(hwnd, (HANDLE)(*(wndPtr->wExtra)));
 
-#ifdef DEBUG_EDIT
-    printf("EDIT_WriteSel: y=%d start=%d end=%d\n", y, start, end);
-#endif
+    dprintf_edit(stddeb,"EDIT_WriteSel: y=%d start=%d end=%d\n", y, start,end);
     GetClientRect(hwnd, &rc);
 
     /* make sure y is within the window */
@@ -3023,10 +2999,13 @@
 unsigned int EDIT_HeapAlloc(HWND hwnd, int bytes)
 {
     WND *wndPtr = WIN_FindWndPtr(hwnd);
-
-    return ((unsigned int)HEAP_Alloc((MDESC **)
+    unsigned int ret;
+    ret = ((unsigned int)HEAP_Alloc((MDESC **)
 				     *(LONG *)(wndPtr->wExtra + 2), 
 				     GMEM_MOVEABLE, bytes) & 0xffff);
+    if (ret == 0)
+      printf("EDIT_HeapAlloc: Out of heap-memory\n");
+    return ret;
 }
 
 
diff --git a/controls/listbox.c b/controls/listbox.c
index 8b7af56..a639814 100644
--- a/controls/listbox.c
+++ b/controls/listbox.c
@@ -5,9 +5,6 @@
  *
  */
 
-/*
-#define DEBUG_LISTBOX
-*/
 
 static char Copyright[] = "Copyright Martin Ayotte, 1993";
 
@@ -24,6 +21,10 @@
 #include "listbox.h"
 #include "scroll.h"
 #include "prototypes.h"
+#include "stddebug.h"
+/* #define DEBUG_LISTBOX /* */
+/* #undef  DEBUG_LISTBOX /* */
+#include "debug.h"
 
 #define GMEM_ZEROINIT 0x0040
 
@@ -37,7 +38,8 @@
 void ListBoxAskMeasure(WND *wndPtr, LPHEADLIST lphl, LPLISTSTRUCT lpls);
 int ListBoxAddString(HWND hwnd, LPSTR newstr);
 int ListBoxInsertString(HWND hwnd, UINT uIndex, LPSTR newstr);
-int ListBoxGetText(HWND hwnd, UINT uIndex, LPSTR OutStr);
+int ListBoxGetText(HWND hwnd, UINT uIndex, LPSTR OutStr, BOOL bItemData);
+int ListBoxSetItemData(HWND hwnd, UINT uIndex, DWORD ItemData);
 int ListBoxDeleteString(HWND hwnd, UINT uIndex);
 int ListBoxFindString(HWND hwnd, UINT nFirst, LPSTR MatchStr);
 int ListBoxResetContent(HWND hwnd);
@@ -51,6 +53,11 @@
 	LPHEADLIST lphl, LPLISTSTRUCT lpls);
 int ListBoxFindNextMatch(HWND hwnd, WORD wChar);
 
+#define HasStrings(wndPtr) ( \
+  ( ((wndPtr->dwStyle & LBS_OWNERDRAWFIXED) != LBS_OWNERDRAWFIXED) && \
+    ((wndPtr->dwStyle & LBS_OWNERDRAWVARIABLE) != LBS_OWNERDRAWVARIABLE) ) || \
+  ((wndPtr->dwStyle & LBS_HASSTRINGS) == LBS_HASSTRINGS) )
+
 
 /***********************************************************************
  *           ListBoxWndProc 
@@ -69,9 +76,7 @@
 	case WM_CREATE:
 		CreateListBoxStruct(hwnd);
 		lphl = ListBoxGetWindowAndStorage(hwnd, &wndPtr);
-#ifdef DEBUG_LISTBOX
-		printf("ListBox WM_CREATE %lX !\n", lphl);
-#endif
+		dprintf_listbox(stddeb,"ListBox WM_CREATE %lX !\n", lphl);
 		if (lphl == NULL) return 0;
 		createStruct = (CREATESTRUCT *)lParam;
 		if (HIWORD(createStruct->lpCreateParams) != 0)
@@ -97,15 +102,12 @@
 		ListBoxResetContent(hwnd);
 		free(lphl);
 		*((LPHEADLIST *)&wndPtr->wExtra[1]) = 0;
-#ifdef DEBUG_LISTBOX
-		printf("ListBox WM_DESTROY %lX !\n", lphl);
-#endif
+		dprintf_listbox(stddeb,"ListBox WM_DESTROY %lX !\n", lphl);
 		return 0;
 
 	case WM_VSCROLL:
-#ifdef DEBUG_LISTBOX
-		printf("ListBox WM_VSCROLL w=%04X l=%08X !\n", wParam, lParam);
-#endif
+		dprintf_listbox(stddeb,"ListBox WM_VSCROLL w=%04X l=%08X !\n",
+				wParam, lParam);
 		lphl = ListBoxGetStorageHeader(hwnd);
 		if (lphl == NULL) return 0;
 		y = lphl->FirstVisible;
@@ -141,9 +143,8 @@
 		return 0;
 	
 	case WM_HSCROLL:
-#ifdef DEBUG_LISTBOX
-		printf("ListBox WM_HSCROLL w=%04X l=%08X !\n", wParam, lParam);
-#endif
+		dprintf_listbox(stddeb,"ListBox WM_HSCROLL w=%04X l=%08X !\n",
+				wParam, lParam);
 		lphl = ListBoxGetStorageHeader(hwnd);
 		if (lphl == NULL) return 0;
 		y = lphl->FirstVisible;
@@ -220,7 +221,6 @@
 		if (lphl == NULL) return 0;
 		SendMessage(lphl->hWndLogicParent, WM_COMMAND, wndPtr->wIDmenu,
 										MAKELONG(hwnd, LBN_DBLCLK));
-		printf("ListBox Send LBN_DBLCLK !\n");
 		return 0;
 	case WM_MOUSEMOVE:
 		if ((wParam & MK_LBUTTON) != 0) {
@@ -276,10 +276,12 @@
 				hWndCtl = GetNextDlgTabItem(lphl->hWndLogicParent,
 					hwnd, !(GetKeyState(VK_SHIFT) < 0));
 				SetFocus(hWndCtl);
+#ifdef DEBUG_LISTBOX
 				if ((GetKeyState(VK_SHIFT) < 0))
-					printf("ListBox PreviousDlgTabItem %04X !\n", hWndCtl);
+					dprintf_listbox(stddeb,"ListBox PreviousDlgTabItem %04X !\n", hWndCtl);
 				else
-					printf("ListBox NextDlgTabItem %04X !\n", hWndCtl);
+					dprintf_listbox(stddeb,"ListBox NextDlgTabItem %04X !\n", hWndCtl);
+#endif
 				break;
 			case VK_HOME:
 				lphl->ItemFocused = 0;
@@ -352,29 +354,21 @@
 		StdDrawListBox(hwnd);
 		break;
 	case WM_SETFOCUS:
-#ifdef DEBUG_LISTBOX
-		printf("ListBox WM_SETFOCUS !\n");
-#endif
+		dprintf_listbox(stddeb,"ListBox WM_SETFOCUS !\n");
 		lphl = ListBoxGetWindowAndStorage(hwnd, &wndPtr);
 		break;
 	case WM_KILLFOCUS:
-#ifdef DEBUG_LISTBOX
-		printf("ListBox WM_KILLFOCUS !\n");
-#endif
+		dprintf_listbox(stddeb,"ListBox WM_KILLFOCUS !\n");
 		InvalidateRect(hwnd, NULL, TRUE);
 		UpdateWindow(hwnd);
 		break;
 
     case LB_RESETCONTENT:
-#ifdef DEBUG_LISTBOX
-		printf("ListBox LB_RESETCONTENT !\n");
-#endif
+		dprintf_listbox(stddeb,"ListBox LB_RESETCONTENT !\n");
 		ListBoxResetContent(hwnd);
 		return 0;
     case LB_DIR:
-#ifdef DEBUG_LISTBOX
-		printf("ListBox LB_DIR !\n");
-#endif
+		dprintf_listbox(stddeb,"ListBox LB_DIR !\n");
 		wRet = ListBoxDirectory(hwnd, wParam, (LPSTR)lParam);
 		InvalidateRect(hwnd, NULL, TRUE);
 		UpdateWindow(hwnd);
@@ -383,16 +377,12 @@
 		wRet = ListBoxAddString(hwnd, (LPSTR)lParam);
 		return wRet;
 	case LB_GETTEXT:
-		wRet = ListBoxGetText(hwnd, wParam, (LPSTR)lParam);
-#ifdef DEBUG_LISTBOX
-		printf("ListBox LB_GETTEXT #%u '%s' !\n", wParam, (LPSTR)lParam);
-#endif
-		return wRet;
+		wRet = ListBoxGetText(hwnd, wParam, (LPSTR)lParam, FALSE);
+                return wRet;
 	case LB_INSERTSTRING:
 		wRet = ListBoxInsertString(hwnd, wParam, (LPSTR)lParam);
 		return wRet;
 	case LB_DELETESTRING:
-		printf("ListBox LB_DELETESTRING #%u !\n", wParam);
 		wRet = ListBoxDeleteString(hwnd, wParam);
 		return wRet;
 	case LB_FINDSTRING:
@@ -405,13 +395,13 @@
 		return lphl->ItemsCount;
 	case LB_GETCURSEL:
 		lphl = ListBoxGetStorageHeader(hwnd);
-#ifdef DEBUG_LISTBOX
-		printf("ListBox LB_GETCURSEL %u !\n", lphl->ItemFocused);
-#endif
+		dprintf_listbox(stddeb,"ListBox LB_GETCURSEL %u !\n", 
+				lphl->ItemFocused);
 		return lphl->ItemFocused;
 	case LB_GETHORIZONTALEXTENT:
 		return wRet;
 	case LB_GETITEMDATA:
+		wRet = ListBoxGetText(hwnd, wParam, (LPSTR)lParam, TRUE);
 		return wRet;
 	case LB_GETITEMHEIGHT:
 		return wRet;
@@ -441,25 +431,26 @@
 	case LB_SETHORIZONTALEXTENT:
 		return wRet;
 	case LB_SETITEMDATA:
+		wRet = ListBoxSetItemData(hwnd, wParam, lParam);
 		return wRet;
 	case LB_SETTABSTOPS:
 		return wRet;
 	case LB_SETCURSEL:
-#ifdef DEBUG_LISTBOX
-		printf("ListBox LB_SETCURSEL wParam=%x !\n", wParam);
-#endif
+		dprintf_listbox(stddeb,"ListBox LB_SETCURSEL wParam=%x !\n", 
+				wParam);
 		wRet = ListBoxSetCurSel(hwnd, wParam);
 		InvalidateRect(hwnd, NULL, TRUE);
 		UpdateWindow(hwnd);
 		return wRet;
 	case LB_SETSEL:
-		printf("ListBox LB_SETSEL wParam=%x lParam=%lX !\n", wParam, lParam);
+		dprintf_listbox(stddeb,"ListBox LB_SETSEL wParam=%x lParam=%lX !\n", wParam, lParam);
 		wRet = ListBoxSetSel(hwnd, LOWORD(lParam), wParam);
 		InvalidateRect(hwnd, NULL, TRUE);
 		UpdateWindow(hwnd);
 		return wRet;
 	case LB_SETTOPINDEX:
-		printf("ListBox LB_SETTOPINDEX wParam=%x !\n", wParam);
+		dprintf_listbox(stddeb,"ListBox LB_SETTOPINDEX wParam=%x !\n",
+				wParam);
 		lphl = ListBoxGetStorageHeader(hwnd);
 		lphl->FirstVisible = wParam;
 		wndPtr = WIN_FindWndPtr(hwnd);
@@ -469,9 +460,7 @@
 		UpdateWindow(hwnd);
 		break;
 	case LB_SETITEMHEIGHT:
-#ifdef DEBUG_LISTBOX
-		printf("ListBox LB_SETITEMHEIGHT wParam=%x lParam=%lX !\n", wParam, lParam);
-#endif
+		dprintf_listbox(stddeb,"ListBox LB_SETITEMHEIGHT wParam=%x lParam=%lX !\n", wParam, lParam);
 		wRet = ListBoxSetItemHeight(hwnd, wParam, lParam);
 		return wRet;
 
@@ -566,8 +555,8 @@
 			dwOldTextColor = SetTextColor(hdc, 0x00FFFFFFL);
 		    FillRect(hdc, &lpls->dis.rcItem, GetStockObject(BLACK_BRUSH));
 		    }
-		TextOut(hdc, rect.left + 5, h + 2, (char *)lpls->dis.itemData, 
-			strlen((char *)lpls->dis.itemData));
+		TextOut(hdc, rect.left + 5, h + 2, (char *)lpls->itemText, 
+			strlen((char *)lpls->itemText));
 		if (lpls->dis.itemState != 0) {
 			SetTextColor(hdc, dwOldTextColor);
 		    }
@@ -597,7 +586,7 @@
 
 void OwnerDrawListBox(HWND hwnd)
 {
-	WND 	*wndPtr;
+	WND 	*wndPtr,*ParentWndPtr;
 	LPHEADLIST  lphl;
 	LPLISTSTRUCT lpls;
 	PAINTSTRUCT ps;
@@ -631,34 +620,41 @@
 	for (i = 1; i <= lphl->ItemsCount; i++) {
 	    if (i >= lphl->FirstVisible) {
 		lpls->dis.hDC = hdc;
+		lpls->dis.hwndItem = hwnd;
+		lpls->dis.CtlType = ODT_LISTBOX;
 		lpls->dis.itemID = i - 1;
+		if ((!lpls->dis.CtlID)&&(lphl->hWndLogicParent))
+		{
+			ListBoxGetWindowAndStorage(lphl->hWndLogicParent, &ParentWndPtr);
+			lpls->dis.CtlID = ParentWndPtr->wIDmenu;
+		}
 		h2 = lpls->dis.rcItem.bottom - lpls->dis.rcItem.top;
 		lpls->dis.rcItem.top = h;
 		lpls->dis.rcItem.bottom = h + h2;
 		lpls->dis.rcItem.left = rect.left;
 		lpls->dis.rcItem.right = rect.right;
 		lpls->dis.itemAction = ODA_DRAWENTIRE;
-		if (lpls->dis.itemState != 0) {
+/*		if (lpls->dis.itemState != 0) {
 		    lpls->dis.itemAction |= ODA_SELECT;
 		    }
 		if (lphl->ItemFocused == i - 1) {
 		    lpls->dis.itemAction |= ODA_FOCUS;
-		    }
-#ifdef DEBUT_LISTBOX
-		printf("LBOX WM_DRAWITEM #%d left=%d top=%d right=%d bottom=%d !\n", 
-			i, lpls->dis.rcItem.left, lpls->dis.rcItem.top, 
+		    }*/
+		dprintf_listbox(stddeb,"LBOX WM_DRAWITEM #%d left=%d top=%d right=%d bottom=%d !\n", 
+			i-1, lpls->dis.rcItem.left, lpls->dis.rcItem.top, 
 			lpls->dis.rcItem.right, lpls->dis.rcItem.bottom);
-		printf("LBOX WM_DRAWITEM Parent=%X &dis=%lX CtlID=%u !\n", 
+		dprintf_listbox(stddeb,"LBOX WM_DRAWITEM Parent=%X &dis=%lX CtlID=%u !\n", 
 			hWndParent, (LONG)&lpls->dis, lpls->dis.CtlID);
-		printf("LBOX WM_DRAWITEM '%s' !\n", lpls->dis.itemData);
-#endif
-		SendMessage(lphl->hWndLogicParent, WM_DRAWITEM, i, (LPARAM)&lpls->dis);
-		if (lpls->dis.itemState != 0) {
-		    InvertRect(hdc, &lpls->dis.rcItem);
-		    }
+		dprintf_listbox(stddeb,"LBOX WM_DRAWITEM %08X!\n",lpls->dis.itemData);
+		if (HasStrings(wndPtr))
+		  dprintf_listbox(stddeb,"  '%s'\n",lpls->itemText);
+		SendMessage(lphl->hWndLogicParent, WM_DRAWITEM, i-1, (LPARAM)&lpls->dis);
+/*		if (lpls->dis.itemState != 0) {
+  		    InvertRect(hdc, &lpls->dis.rcItem);  
+		    }  */
 		h += h2;
 		lphl->ItemsVisible++;
-		if (h > rect.bottom) goto EndOfPaint;
+		/* if (h > rect.bottom) goto EndOfPaint;*/
 		}
 	    if (lpls->lpNext == NULL) goto EndOfPaint;
 	    lpls = (LPLISTSTRUCT)lpls->lpNext;
@@ -672,6 +668,7 @@
         UpdateWindow(wndPtr->hWndVScroll);
 */
         }
+
 }
 
 
@@ -739,7 +736,7 @@
 	HANDLE hTemp = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(MEASUREITEMSTRUCT));
 	measure = (MEASUREITEMSTRUCT *) USER_HEAP_ADDR(hTemp);
 	if (measure == NULL) {
-		printf("ListBoxAskMeasure() // Bad allocation of Measure struct !\n");
+		fprintf(stderr,"ListBoxAskMeasure() // Bad allocation of Measure struct !\n");
 		return;
 		}
 	measure->CtlType = ODT_LISTBOX;
@@ -767,7 +764,7 @@
     hTemp = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(LISTSTRUCT));
     lplsnew = (LPLISTSTRUCT) USER_HEAP_ADDR(hTemp);
     if (lplsnew == NULL) {
-		printf("ListBoxAddString() // Bad allocation of new item !\n");
+		fprintf(stderr,"ListBoxAddString() // Bad allocation of new item !\n");
 		return LB_ERRSPACE;
 		}
     lpls = lphl->lpFirst;
@@ -780,30 +777,30 @@
     else
 	lphl->lpFirst = lplsnew;
     lphl->ItemsCount++;
-#ifdef DEBUG_LISTBOX
-    printf("Items Count = %u\n", lphl->ItemsCount);
-#endif
+    dprintf_listbox(stddeb,"Items Count = %u\n", lphl->ItemsCount);
     hTemp = 0;
-    if ((wndPtr->dwStyle & LBS_HASSTRINGS) != LBS_HASSTRINGS) {
-	if (((wndPtr->dwStyle & LBS_OWNERDRAWFIXED) != LBS_OWNERDRAWFIXED) &&
-	    ((wndPtr->dwStyle & LBS_OWNERDRAWVARIABLE) != LBS_OWNERDRAWVARIABLE)) {
-	    hTemp = USER_HEAP_ALLOC(GMEM_MOVEABLE, strlen(newstr) + 1);
-	    str = (LPSTR)USER_HEAP_ADDR(hTemp);
-	    if (str == NULL) return LB_ERRSPACE;
-	    strcpy(str, newstr);
-	    newstr = str;
-#ifdef DEBUG_LISTBOX
-	    printf("ListBoxAddString// after strcpy '%s'\n", str);
-#endif
-	    }
-	}
     ListBoxDefaultItem(hwnd, wndPtr, lphl, lplsnew);
+    if (HasStrings(wndPtr))
+      {
+	hTemp = USER_HEAP_ALLOC(GMEM_MOVEABLE, strlen(newstr) + 1);
+	str = (LPSTR)USER_HEAP_ADDR(hTemp);
+	if (str == NULL) return LB_ERRSPACE;
+	strcpy(str, newstr);
+	newstr = str;
+	lplsnew->itemText = str;
+	lplsnew->dis.itemData = 0;
+	dprintf_listbox(stddeb,"ListBoxAddString// after strcpy '%s'\n", str);
+      }
+    else
+      {
+	lplsnew->itemText = NULL;
+	lplsnew->dis.itemData = (DWORD)newstr;
+      }
     lplsnew->hMem = hTemp;
     lplsnew->lpNext = NULL;
     lplsnew->dis.itemID = lphl->ItemsCount;
-    lplsnew->dis.itemData = (DWORD)newstr;
     lplsnew->hData = hTemp;
-	if ((wndPtr->dwStyle & LBS_OWNERDRAWVARIABLE) == LBS_OWNERDRAWVARIABLE) 
+	if (((wndPtr->dwStyle & LBS_OWNERDRAWVARIABLE) == LBS_OWNERDRAWVARIABLE)|| ((wndPtr->dwStyle & LBS_OWNERDRAWFIXED) == LBS_OWNERDRAWFIXED)) 
 		ListBoxAskMeasure(wndPtr, lphl, lplsnew);
     if (wndPtr->dwStyle & WS_VSCROLL)
 	SetScrollRange(hwnd, SB_VERT, 1, lphl->ItemsCount, 
@@ -821,7 +818,7 @@
 	if (wndPtr->dwStyle & WS_HSCROLL)
 	    ShowScrollBar(hwnd, SB_HORZ, TRUE);
 	}
-    return lphl->ItemsCount;
+    return lphl->ItemsCount-1;
 }
 
 
@@ -833,12 +830,14 @@
 	HANDLE	hTemp;
 	LPSTR	str;
 	UINT	Count;
-#ifdef DEBUG_LISTBOX
-    printf("ListBoxInsertString(%04X, %d, %08X);\n", hwnd, uIndex, newstr);
-#endif
+	dprintf_listbox(stddeb,"ListBoxInsertString(%04X, %d, %08X);\n", 
+		    hwnd, uIndex, newstr);
 	if (uIndex == (UINT)-1) return ListBoxAddString(hwnd, newstr);
 	lphl = ListBoxGetWindowAndStorage(hwnd, &wndPtr);
 	if (lphl == NULL) return LB_ERR;
+	/* The following line will cause problems if the content of the */
+	/* listbox is sorted by the listbox itself */
+	if (uIndex == lphl->ItemsCount) return ListBoxAddString(hwnd, newstr);
 	if (uIndex >= lphl->ItemsCount) return LB_ERR;
 	lpls = lphl->lpFirst;
 	if (lpls == NULL) return LB_ERR;
@@ -850,32 +849,44 @@
 	hTemp = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(LISTSTRUCT));
 	lplsnew = (LPLISTSTRUCT) USER_HEAP_ADDR(hTemp);
     if (lplsnew == NULL) {
-		printf("ListBoxInsertString() // Bad allocation of new item !\n");
+		fprintf(stderr,"ListBoxInsertString() // Bad allocation of new item !\n");
 		return LB_ERRSPACE;
 		}
 	ListBoxDefaultItem(hwnd, wndPtr, lphl, lplsnew);
 	lplsnew->hMem = hTemp;
-	lpls->lpNext = lplsnew;
+	if (uIndex == 0)
+	{
+		lplsnew->lpNext = lphl->lpFirst;
+		lphl->lpFirst = lplsnew;
+	}
+	else	
+	{
+		lplsnew->lpNext = lpls->lpNext;
+		lpls->lpNext = lplsnew;
+	}
 	lphl->ItemsCount++;
 	hTemp = 0;
-	if ((wndPtr->dwStyle & LBS_HASSTRINGS) != LBS_HASSTRINGS) {
-		if (((wndPtr->dwStyle & LBS_OWNERDRAWFIXED) != LBS_OWNERDRAWFIXED) &&
-			((wndPtr->dwStyle & LBS_OWNERDRAWVARIABLE) != LBS_OWNERDRAWVARIABLE)) {
-			hTemp = USER_HEAP_ALLOC(GMEM_MOVEABLE, strlen(newstr) + 1);
-			str = (LPSTR)USER_HEAP_ADDR(hTemp);
-			if (str == NULL) return LB_ERRSPACE;
-			strcpy(str, newstr);
-			newstr = str;
+	if (HasStrings(wndPtr))
+	  {
+	    hTemp = USER_HEAP_ALLOC(GMEM_MOVEABLE, strlen(newstr) + 1);
+	    str = (LPSTR)USER_HEAP_ADDR(hTemp);
+	    if (str == NULL) return LB_ERRSPACE;
+	    strcpy(str, newstr);
+	    newstr = str;
+	    lplsnew->itemText = str;
+	    lplsnew->dis.itemData = 0;
 #ifdef DEBUG_LISTBOX
-		    printf("ListBoxInsertString // after strcpy '%s'\n", str);
+	    printf("ListBoxInsertString // after strcpy '%s'\n", str);
 #endif
-			}
-		}
-	lplsnew->lpNext = NULL;
+	  }
+	else
+	  {
+	    lplsnew->itemText = NULL;
+	    lplsnew->dis.itemData = (DWORD)newstr;
+	  }
 	lplsnew->dis.itemID = lphl->ItemsCount;
-	lplsnew->dis.itemData = (DWORD)newstr;
 	lplsnew->hData = hTemp;
-	if ((wndPtr->dwStyle & LBS_OWNERDRAWVARIABLE) == LBS_OWNERDRAWVARIABLE) 
+	if (((wndPtr->dwStyle & LBS_OWNERDRAWVARIABLE) == LBS_OWNERDRAWVARIABLE)|| ((wndPtr->dwStyle & LBS_OWNERDRAWFIXED) == LBS_OWNERDRAWFIXED))
 		ListBoxAskMeasure(wndPtr, lphl, lplsnew);
 	if (wndPtr->dwStyle & WS_VSCROLL)
 		SetScrollRange(hwnd, SB_VERT, 1, lphl->ItemsCount, 
@@ -896,16 +907,18 @@
 #ifdef DEBUG_LISTBOX
     printf("ListBoxInsertString // count=%d\n", lphl->ItemsCount);
 #endif
-	return lphl->ItemsCount;
+	return /* lphl->ItemsCount;*/ uIndex;
 }
 
 
-int ListBoxGetText(HWND hwnd, UINT uIndex, LPSTR OutStr)
+int ListBoxGetText(HWND hwnd, UINT uIndex, LPSTR OutStr, BOOL bItemData)
 {
     WND  	*wndPtr;
     LPHEADLIST 	lphl;
     LPLISTSTRUCT lpls;
     UINT	Count;
+    if (!bItemData)
+    	*OutStr=0;
     lphl = ListBoxGetWindowAndStorage(hwnd, &wndPtr);
     if (lphl == NULL) return LB_ERR;
     if (uIndex >= lphl->ItemsCount) return LB_ERR;
@@ -916,18 +929,38 @@
 	if (lpls->lpNext == NULL) return LB_ERR;
 	lpls = (LPLISTSTRUCT)lpls->lpNext;
     }
-    if (((wndPtr->dwStyle & LBS_OWNERDRAWFIXED) == LBS_OWNERDRAWFIXED) ||
-	    ((wndPtr->dwStyle & LBS_OWNERDRAWVARIABLE) == LBS_OWNERDRAWVARIABLE)) {
-	if ((wndPtr->dwStyle & LBS_HASSTRINGS) != LBS_HASSTRINGS) { 
-	    *((long *)OutStr) = lpls->dis.itemData;
-	    return 4;
-	    }
-	}
+    if (bItemData)
+	return lpls->dis.itemData;
+    if (!(HasStrings(wndPtr)) )
+      {
+	*((long *)OutStr) = lpls->dis.itemData;
+	return 4;
+      }
 	
-    strcpy(OutStr, (char *)lpls->dis.itemData);
+    strcpy(OutStr, lpls->itemText);
     return strlen(OutStr);
 }
 
+int ListBoxSetItemData(HWND hwnd, UINT uIndex, DWORD ItemData)
+{
+    WND         *wndPtr;
+    LPHEADLIST  lphl;
+    LPLISTSTRUCT lpls;
+    UINT        Count;
+    lphl = ListBoxGetWindowAndStorage(hwnd, &wndPtr);
+    if (lphl == NULL) return LB_ERR;
+    if (uIndex >= lphl->ItemsCount) return LB_ERR;
+    lpls = lphl->lpFirst;
+    if (lpls == NULL) return LB_ERR;
+    if (uIndex > lphl->ItemsCount) return LB_ERR;
+    for(Count = 0; Count < uIndex; Count++) {
+        if (lpls->lpNext == NULL) return LB_ERR;
+        lpls = (LPLISTSTRUCT)lpls->lpNext;
+    }
+    lpls->dis.itemData = ItemData;
+    return 1;
+}
+
 
 int ListBoxDeleteString(HWND hwnd, UINT uIndex)
 {
@@ -972,20 +1005,28 @@
 
 int ListBoxFindString(HWND hwnd, UINT nFirst, LPSTR MatchStr)
 {
+    WND          *wndPtr;
     LPHEADLIST 	lphl;
     LPLISTSTRUCT lpls;
     UINT	Count;
-    lphl = ListBoxGetStorageHeader(hwnd);
+    lphl = ListBoxGetWindowAndStorage(hwnd, &wndPtr);
     if (lphl == NULL) return LB_ERR;
     if (nFirst > lphl->ItemsCount) return LB_ERR;
     lpls = lphl->lpFirst;
     if (lpls == NULL) return LB_ERR;
     Count = 0;
     while(lpls != NULL) {
-    	if (strcmp((char *)lpls->dis.itemData, MatchStr) == 0) return Count;
-	lpls = (LPLISTSTRUCT)lpls->lpNext;
-	Count++;
-        }
+      if (HasStrings(wndPtr))
+	{
+	  if (strcmp(lpls->itemText, MatchStr) == 0) return Count;
+	}
+      else
+	{
+	  if (lpls->dis.itemData == (DWORD)MatchStr) return Count;
+	}
+      lpls = (LPLISTSTRUCT)lpls->lpNext;
+      Count++;
+    }
     return LB_ERR;
 }
 
@@ -1004,9 +1045,7 @@
 	lpls2 = lpls;
 	lpls = (LPLISTSTRUCT)lpls->lpNext;
 	if (i != 0) {
-#ifdef DEBUG_LISTBOX
-	    printf("ResetContent #%u\n", i);
-#endif
+	    dprintf_listbox(stddeb,"ResetContent #%u\n", i);
 	    if (lpls2->hData != 0 && lpls2->hData != lpls2->hMem)
 		USER_HEAP_FREE(lpls2->hData);
 	    if (lpls2->hMem != 0) USER_HEAP_FREE(lpls2->hMem);
@@ -1016,8 +1055,8 @@
     lphl->lpFirst = NULL;
     lphl->FirstVisible = 1;
     lphl->ItemsCount = 0;
-    lphl->ItemFocused = 0;
-    lphl->PrevFocused = 0;
+    lphl->ItemFocused = /*0*/-1;
+    lphl->PrevFocused = /*0*/-1;
     if ((wndPtr->dwStyle && LBS_NOTIFY) != 0)
 	SendMessage(lphl->hWndLogicParent, WM_COMMAND, 
     	    wndPtr->wIDmenu, MAKELONG(hwnd, LBN_SELCHANGE));
@@ -1114,53 +1153,64 @@
 
 int ListBoxDirectory(HWND hwnd, UINT attrib, LPSTR filespec)
 {
-	struct dosdirent *dp;
-	struct dosdirent *newdp;
-	struct stat	st;
-	int	x, wRet;
-	char 	temp[256];
+  struct dosdirent *dp;
+  struct dosdirent *newdp;
+  struct stat	st;
+  int	x, wRet;
+  char 	temp[256];
 #ifdef DEBUG_LISTBOX
-	fprintf(stderr,"ListBoxDirectory: %s, %4x\n",filespec,attrib);
+  fprintf(stderr,"ListBoxDirectory: %s, %4x\n",filespec,attrib);
 #endif
-	if ((dp = (struct dosdirent *)DOS_opendir(filespec)) ==NULL) return 0;
-	while (dp = (struct dosdirent *)DOS_readdir(dp)) {
-		if (!dp->inuse) break;
+  if ((dp = (struct dosdirent *)DOS_opendir(filespec)) ==NULL) return 0;
+  while (dp = (struct dosdirent *)DOS_readdir(dp)) 
+    {
+      if (!dp->inuse) break;
 #ifdef DEBUG_LISTBOX
-		printf("ListBoxDirectory %08X '%s' !\n", dp->filename, dp->filename);
+      printf("ListBoxDirectory %08X '%s' !\n", dp->filename, dp->filename);
 #endif
-		if (dp->attribute & FA_DIREC) {
-			if (attrib & DDL_DIRECTORY) {
-				sprintf(temp, "[%s]", dp->filename);
-				if ( (wRet = ListBoxAddString(hwnd, temp)) == LB_ERR) break;
-			}
-		} else 
-		if (attrib & DDL_EXCLUSIVE) {
-	    		if (attrib & (DDL_READWRITE | DDL_READONLY | DDL_HIDDEN | DDL_SYSTEM) )
-		    		if ( (wRet = ListBoxAddString(hwnd, dp->filename)) == LB_ERR)
-		    			break;
-		} else {
-			if ( (wRet = ListBoxAddString(hwnd, dp->filename)) == LB_ERR)
-	    			break;
-		}
-	}
-	DOS_closedir(dp);
-	
-	if (attrib & DDL_DRIVES)
+      if (dp->attribute & FA_DIREC) 
 	{
-		for (x=0;x!=MAX_DOS_DRIVES;x++)
-		{
-			if (DOS_ValidDrive(x))
-			{
-				sprintf(temp, "[-%c-]", 'a'+x);
-				if ( (wRet = ListBoxAddString(hwnd, temp)) == LB_ERR)
-	    				break;
-			}		
-		}
+	  if (attrib & DDL_DIRECTORY) 
+	    {
+	      sprintf(temp, "[%s]", dp->filename);
+	      if ( (wRet = ListBoxAddString(hwnd, temp)) == LB_ERR) break;
+	    }
+	} 
+      else 
+	{
+	  if (attrib & DDL_EXCLUSIVE) 
+	    {
+	      if (attrib & (DDL_READWRITE | DDL_READONLY | DDL_HIDDEN | 
+			    DDL_SYSTEM) )
+		if ( (wRet = ListBoxAddString(hwnd, dp->filename)) 
+		    == LB_ERR)
+		  break;
+	    } 
+	  else 
+	    {
+	      if ( (wRet = ListBoxAddString(hwnd, dp->filename)) == LB_ERR)
+		break;
+	    }
 	}
+    }
+  DOS_closedir(dp);
+	
+  if (attrib & DDL_DRIVES)
+    {
+      for (x=0;x!=MAX_DOS_DRIVES;x++)
+	{
+	  if (DOS_ValidDrive(x))
+	    {
+	      sprintf(temp, "[-%c-]", 'a'+x);
+	      if ( (wRet = ListBoxAddString(hwnd, temp)) == LB_ERR)
+		break;
+	    }		
+	}
+    }
 #ifdef DEBUG_LISTBOX
-	printf("End of ListBoxDirectory !\n");
+  printf("End of ListBoxDirectory !\n");
 #endif
-	return wRet;
+  return wRet;
 }
 
 
@@ -1221,7 +1271,7 @@
 {
     RECT	rect;
 	if (wndPtr == NULL || lphl == NULL || lpls == NULL) {
-		printf("ListBoxDefaultItem() // Bad Pointers !\n");
+		fprintf(stderr,"ListBoxDefaultItem() // Bad Pointers !\n");
 		return FALSE;
 		}
     GetClientRect(hwnd, &rect);
@@ -1259,7 +1309,7 @@
     Count = 0;
     while(lpls != NULL) {
         if (Count > lphl->ItemFocused) {
-	    if (*((char *)lpls->dis.itemData) == (char)wChar) {
+	    if (*(lpls->itemText) == (char)wChar) {
 		lphl->FirstVisible = Count - lphl->ItemsVisible / 2;
 		if (lphl->FirstVisible < 1) lphl->FirstVisible = 1;
 		if ((wndPtr->dwStyle & LBS_MULTIPLESEL) == LBS_MULTIPLESEL) {
@@ -1280,7 +1330,7 @@
     Count = 0;
     lpls = lphl->lpFirst;
     while(lpls != NULL) {
-	if (*((char *)lpls->dis.itemData) == (char)wChar) {
+	if (*(lpls->itemText) == (char)wChar) {
 	    if (Count == lphl->ItemFocused)    return LB_ERR;
 	    lphl->FirstVisible = Count - lphl->ItemsVisible / 2;
 	    if (lphl->FirstVisible < 1) lphl->FirstVisible = 1;
@@ -1307,7 +1357,7 @@
  */
 BOOL DlgDirSelect(HWND hDlg, LPSTR lpStr, int nIDLBox)
 {
-	printf("DlgDirSelect(%04X, '%s', %d) \n",	hDlg, lpStr, nIDLBox);
+      fprintf(stdnimp,"DlgDirSelect(%04X, '%s', %d) \n", hDlg, lpStr, nIDLBox);
 }
 
 
@@ -1318,11 +1368,27 @@
 	int nIDLBox, int nIDStat, WORD wType)
 {
 	HWND	hWnd;
-	printf("DlgDirList(%04X, '%s', %d, %d, %04X) \n",
+	int ret;
+	dprintf_listbox(stddeb,"DlgDirList(%04X, '%s', %d, %d, %04X) \n",
 			hDlg, lpPathSpec, nIDLBox, nIDStat, wType);
-	hWnd = GetDlgItem(hDlg, nIDLBox);
-	ListBoxResetContent(hWnd);
-	return ListBoxDirectory(hWnd, wType, lpPathSpec);
+	if (nIDLBox)
+	  hWnd = GetDlgItem(hDlg, nIDLBox);
+	else
+	  hWnd = 0;
+	if (hWnd)
+	  ListBoxResetContent(hWnd);
+	if (hWnd)
+	  ret=ListBoxDirectory(hWnd, wType, lpPathSpec);
+	else
+	  ret=0;
+	if (nIDStat)
+	  {
+	    int drive;
+	    drive = DOS_GetDefaultDrive();
+	    SendDlgItemMessage(hDlg, nIDStat, WM_SETTEXT, 0, 
+			       (LONG) DOS_GetCurrentDir(drive) );
+	  } 
+	return ret;
 }
 
 
diff --git a/controls/menu.c b/controls/menu.c
index 16e515d..8290dda 100644
--- a/controls/menu.c
+++ b/controls/menu.c
@@ -11,9 +11,6 @@
  * This is probably not the meaning this style has in MS-Windows.
  */
 
-/*
-#define DEBUG_MENU
-*/
 
 #include <ctype.h>
 #include <stdlib.h>
@@ -27,6 +24,14 @@
 #include "user.h"
 #include "win.h"
 #include "message.h"
+#include "debug.h"
+
+/* #define DEBUG_MENU /* */
+/* #undef DEBUG_MENU /* */
+/* #define DEBUG_MENUCALC /* */
+/* #undef DEBUG_MENUCALC /* */
+/* #define DEBUG_MENUSHORTCUT /* */
+/* #undef DEBUG_MENUSHORTCUT /* */
 
   /* Dimension of the menu bitmaps */
 static WORD check_bitmap_width = 0, check_bitmap_height = 0;
@@ -95,7 +100,7 @@
 
     if (!(hSysMenu = LoadMenu( hSysRes, "SYSMENU" )))
     {
-	printf("SysMenu not found in system resources !\n");
+	fprintf(stderr,"SysMenu not found in system resources !\n");
 	return FALSE;
     }
 
@@ -373,10 +378,8 @@
 
     if ((lprect == NULL) || (lppop == NULL)) return;
     if (lppop->nItems == 0) return;
-#ifdef DEBUG_MENUCALC
-	printf("MenuBarCalcSize left=%d top=%d right=%d bottom=%d !\n", 
+	dprintf_menucalc(stddeb,"MenuBarCalcSize left=%d top=%d right=%d bottom=%d !\n", 
 		lprect->left, lprect->top, lprect->right, lprect->bottom);
-#endif
     items = (MENUITEM *)USER_HEAP_ADDR( lppop->hItems );
     lppop->Width  = lprect->right - lprect->left;
     lppop->Height = 0;
@@ -602,9 +605,8 @@
     
     lppop = (LPPOPUPMENU) USER_HEAP_ADDR( wndPtr->wIDmenu );
     if (lppop == NULL || lprect == NULL) return SYSMETRICS_CYMENU;
-#ifdef DEBUG_MENU
-    printf("MENU_DrawMenuBar(%04X, %08X, %08X); !\n", hDC, lprect, lppop);
-#endif
+    dprintf_menu(stddeb,"MENU_DrawMenuBar(%04X, %08X, %08X); !\n", 
+		 hDC, lprect, lppop);
     if (lppop->Height == 0) MENU_MenuBarCalcSize(hDC, lprect, lppop, hwnd);
     lprect->bottom = lprect->top + lppop->Height;
     if (suppress_draw) return lppop->Height;
@@ -1481,9 +1483,8 @@
 BOOL CheckMenuItem(HMENU hMenu, WORD wItemID, WORD wFlags)
 {
 	LPMENUITEM 	lpitem;
-#ifdef DEBUG_MENU
-	printf("CheckMenuItem (%04X, %04X, %04X) !\n", hMenu, wItemID, wFlags);
-#endif
+	dprintf_menu(stddeb,"CheckMenuItem (%04X, %04X, %04X) !\n", 
+		     hMenu, wItemID, wFlags);
 	if (!(lpitem = MENU_FindItem(&hMenu, &wItemID, wFlags))) return FALSE;
 	if (wFlags & MF_CHECKED) lpitem->item_flags |= MF_CHECKED;
 	else lpitem->item_flags &= ~MF_CHECKED;
@@ -1497,9 +1498,8 @@
 BOOL EnableMenuItem(HMENU hMenu, WORD wItemID, WORD wFlags)
 {
     LPMENUITEM 	lpitem;
-#ifdef DEBUG_MENU
-    printf("EnableMenuItem (%04X, %04X, %04X) !\n", hMenu, wItemID, wFlags);
-#endif
+    dprintf_menu(stddeb,"EnableMenuItem (%04X, %04X, %04X) !\n", 
+		 hMenu, wItemID, wFlags);
     if (!(lpitem = MENU_FindItem( &hMenu, &wItemID, wFlags ))) return FALSE;
 
       /* We can't have MF_GRAYED and MF_DISABLED together */
@@ -1527,10 +1527,8 @@
 {
 	LPMENUITEM 	lpitem;
 	int		maxsiz;
-#ifdef DEBUG_MENU
-	printf("GetMenuString(%04X, %04X, %08X, %d, %04X);\n",
+	dprintf_menu(stddeb,"GetMenuString(%04X, %04X, %08X, %d, %04X);\n",
 					hMenu, wItemID, str, nMaxSiz, wFlags);
-#endif
 	if (str == NULL) return FALSE;
 	lpitem = MENU_FindItem( &hMenu, &wItemID, wFlags );
 	if (lpitem != NULL) {
@@ -1540,9 +1538,7 @@
 			}
 		else
 			maxsiz = 0;
-#ifdef DEBUG_MENU
-		printf("GetMenuString // Found !\n");
-#endif
+		dprintf_menu(stddeb,"GetMenuString // Found !\n");
 		return maxsiz;
 		}
 	return 0;
@@ -1556,10 +1552,8 @@
 {
     LPPOPUPMENU menu;
     LPMENUITEM  lpitem;
-#ifdef DEBUG_MENU
-	printf("HiliteMenuItem(%04X, %04X, %04X, %04X);\n", 
+    dprintf_menu(stddeb,"HiliteMenuItem(%04X, %04X, %04X, %04X);\n", 
 						hWnd, hMenu, wItemID, wHilite);
-#endif
     if (!(lpitem = MENU_FindItem( &hMenu, &wItemID, wHilite ))) return FALSE;
     if (!(menu = (LPPOPUPMENU) USER_HEAP_ADDR(hMenu))) return FALSE;
     if (menu->FocusedItem == wItemID) return TRUE;
@@ -1575,9 +1569,8 @@
 WORD GetMenuState(HMENU hMenu, WORD wItemID, WORD wFlags)
 {
     LPMENUITEM lpitem;
-#ifdef DEBUG_MENU
-    printf("GetMenuState(%04X, %04X, %04X);\n", hMenu, wItemID, wFlags);
-#endif
+    dprintf_menu(stddeb,"GetMenuState(%04X, %04X, %04X);\n", 
+		 hMenu, wItemID, wFlags);
     if (!(lpitem = MENU_FindItem( &hMenu, &wItemID, wFlags ))) return -1;
     if (lpitem->item_flags & MF_POPUP)
     {
@@ -1595,14 +1588,11 @@
 WORD GetMenuItemCount(HMENU hMenu)
 {
 	LPPOPUPMENU	menu;
-#ifdef DEBUG_MENU
-	printf("GetMenuItemCount(%04X);\n", hMenu);
-#endif
+	dprintf_menu(stddeb,"GetMenuItemCount(%04X);\n", hMenu);
 	menu = (LPPOPUPMENU) USER_HEAP_ADDR(hMenu);
 	if (menu == NULL) return (WORD)-1;
-#ifdef DEBUG_MENU
-	printf("GetMenuItemCount(%04X) return %d \n", hMenu, menu->nItems);
-#endif
+	dprintf_menu(stddeb,"GetMenuItemCount(%04X) return %d \n", 
+		     hMenu, menu->nItems);
 	return menu->nItems;
 }
 
@@ -1615,9 +1605,7 @@
     LPPOPUPMENU	menu;
     MENUITEM *item;
 
-#ifdef DEBUG_MENU
-    printf("GetMenuItemID(%04X, %d);\n", hMenu, nPos);
-#endif
+    dprintf_menu(stddeb,"GetMenuItemID(%04X, %d);\n", hMenu, nPos);
     if (!(menu = (LPPOPUPMENU) USER_HEAP_ADDR(hMenu))) return -1;
     if ((nPos < 0) || (nPos >= menu->nItems)) return -1;
     item = (MENUITEM *) USER_HEAP_ADDR( menu->hItems );
@@ -1635,14 +1623,12 @@
     MENUITEM *lpitem, *newItems;
     LPPOPUPMENU	menu;
     
-#ifdef DEBUG_MENU
     if (IS_STRING_ITEM(wFlags))
-		printf("InsertMenu (%04X, %04X, %04X, '%s') !\n",
+	   dprintf_menu(stddeb,"InsertMenu (%04X, %04X, %04X, '%s') !\n",
 					hMenu, wFlags, wItemID, lpNewItem);
     else
-		printf("InsertMenu (%04X, %04X, %04X, %04X, %08X) !\n",
+	   dprintf_menu(stddeb,"InsertMenu (%04X, %04X, %04X, %04X, %08X) !\n",
 		                  hMenu, nPos, wFlags, wItemID, lpNewItem);
-#endif
 
       /* Find where to insert new item */
 
@@ -1724,9 +1710,8 @@
 {
     LPPOPUPMENU	menu;
     LPMENUITEM 	lpitem;
-#ifdef DEBUG_MENU
-	printf("RemoveMenu (%04X, %04X, %04X) !\n", hMenu, nPos, wFlags);
-#endif
+	dprintf_menu(stddeb,"RemoveMenu (%04X, %04X, %04X) !\n", 
+		     hMenu, nPos, wFlags);
     if (!(lpitem = MENU_FindItem( &hMenu, &nPos, wFlags ))) return FALSE;
     if (!(menu = (LPPOPUPMENU) USER_HEAP_ADDR(hMenu))) return FALSE;
     
@@ -1774,14 +1759,12 @@
 BOOL ModifyMenu(HMENU hMenu, WORD nPos, WORD wFlags, WORD wItemID, LPSTR lpNewItem)
 {
     LPMENUITEM 	lpitem;
-#ifdef DEBUG_MENU
     if (IS_STRING_ITEM(wFlags))
-	printf("ModifyMenu (%04X, %04X, %04X, %04X, '%s') !\n",
+	dprintf_menu(stddeb,"ModifyMenu (%04X, %04X, %04X, %04X, '%s') !\n",
 	       hMenu, nPos, wFlags, wItemID, lpNewItem);
     else
-	printf("ModifyMenu (%04X, %04X, %04X, %04X, %08X) !\n",
+	dprintf_menu(stddeb,"ModifyMenu (%04X, %04X, %04X, %04X, %08X) !\n",
 	       hMenu, nPos, wFlags, wItemID, lpNewItem);
-#endif
     if (!(lpitem = MENU_FindItem( &hMenu, &nPos, wFlags ))) return FALSE;
     
     if (IS_STRING_ITEM(lpitem->item_flags)) USER_HEAP_FREE( lpitem->hText );
@@ -1832,10 +1815,8 @@
 		HBITMAP hNewCheck, HBITMAP hNewUnCheck)
 {
     LPMENUITEM lpitem;
-#ifdef DEBUG_MENU
-    printf("SetMenuItemBitmaps (%04X, %04X, %04X, %04X, %08X) !\n",
+   dprintf_menu(stddeb,"SetMenuItemBitmaps (%04X, %04X, %04X, %04X, %08X) !\n",
 	    hMenu, nPos, wFlags, hNewCheck, hNewUnCheck);
-#endif
     if (!(lpitem = MENU_FindItem( &hMenu, &nPos, wFlags ))) return FALSE;
 
     if (!hNewCheck && !hNewUnCheck)
@@ -1862,9 +1843,7 @@
 {
     HMENU hMenu;
     LPPOPUPMENU menu;
-#ifdef DEBUG_MENU
-	printf("CreateMenu !\n");
-#endif
+    dprintf_menu(stddeb,"CreateMenu !\n");
     if (!(hMenu = USER_HEAP_ALLOC( GMEM_MOVEABLE, sizeof(POPUPMENU) )))
 	return 0;
     menu = (LPPOPUPMENU) USER_HEAP_ADDR(hMenu);
@@ -1878,9 +1857,7 @@
     menu->hWnd   = 0;
     menu->hItems = 0;
     menu->FocusedItem = NO_SELECTED_ITEM;
-#ifdef DEBUG_MENU
-    printf("CreateMenu // return %04X\n", hMenu);
-#endif
+    dprintf_menu(stddeb,"CreateMenu // return %04X\n", hMenu);
     return hMenu;
 }
 
@@ -1891,9 +1868,7 @@
 BOOL DestroyMenu(HMENU hMenu)
 {
 	LPPOPUPMENU lppop;
-#ifdef DEBUG_MENU
-	printf("DestroyMenu (%04X) !\n", hMenu);
-#endif
+	dprintf_menu(stddeb,"DestroyMenu (%04X) !\n", hMenu);
 	if (hMenu == 0) return FALSE;
 	lppop = (LPPOPUPMENU) USER_HEAP_ADDR(hMenu);
 	if (lppop == NULL) return FALSE;
@@ -1906,44 +1881,15 @@
 	    for (i = lppop->nItems; i > 0; i--, item++)
 	    {
 		if (item->item_flags & MF_POPUP)
-		    DestroyMenu( item->item_flags & MF_POPUP );
+		    DestroyMenu( item->item_id );
 	    }
 	    USER_HEAP_FREE( lppop->hItems );
 	}
 	USER_HEAP_FREE( hMenu );
-#ifdef DEBUG_MENU
-	printf("DestroyMenu (%04X) // End !\n", hMenu);
-#endif
+	dprintf_menu(stddeb,"DestroyMenu (%04X) // End !\n", hMenu);
 	return TRUE;
 }
 
-
-/**********************************************************************
- *			LoadMenu		[USER.150]
- */
-HMENU LoadMenu(HINSTANCE instance, char *menu_name)
-{
-	HMENU     		hMenu;
-	HANDLE		hMenu_desc;
-	MENU_HEADER 	*menu_desc;
-#ifdef DEBUG_MENU
-	if ((LONG)menu_name & 0xFFFF0000L)
-		printf("LoadMenu: instance %02x, menu '%s'\n", instance, menu_name);
-	else
-		printf("LoadMenu: instance %02x, menu '%04X'\n", instance, menu_name);
-#endif
-	if (instance == (HANDLE)NULL)  instance = hSysRes;
-	if (menu_name == NULL || 
-		(hMenu_desc = RSC_LoadMenu(instance, menu_name)) == 0 ||
-		(menu_desc = (MENU_HEADER *) GlobalLock(hMenu_desc)) == NULL) {
-		return 0;
-		}
-	hMenu = LoadMenuIndirect((LPSTR)menu_desc);
-	GlobalUnlock( hMenu_desc );
-	return hMenu;
-}
-
-
 /**********************************************************************
  *			GetSystemMenu		[USER.156]
  */
@@ -1992,19 +1938,19 @@
 	LPPOPUPMENU lpmenu;
 	WND * wndPtr = WIN_FindWndPtr(hWnd);
 	if (wndPtr == NULL) {
-		printf("SetMenu(%04X, %04X) // Bad window handle !\n", hWnd, hMenu);
+		fprintf(stderr,"SetMenu(%04X, %04X) // Bad window handle !\n",
+			hWnd, hMenu);
 		return FALSE;
 		}
-#ifdef DEBUG_MENU
-	printf("SetMenu(%04X, %04X);\n", hWnd, hMenu);
-#endif
+	dprintf_menu(stddeb,"SetMenu(%04X, %04X);\n", hWnd, hMenu);
 	if (GetCapture() == hWnd) ReleaseCapture();
 	wndPtr->wIDmenu = hMenu;
 	if (hMenu != 0)
 	{
 	    lpmenu = (LPPOPUPMENU) USER_HEAP_ADDR(hMenu);
 	    if (lpmenu == NULL) {
-		printf("SetMenu(%04X, %04X) // Bad menu handle !\n", hWnd, hMenu);
+		fprintf(stderr,"SetMenu(%04X, %04X) // Bad menu handle !\n", 
+			hWnd, hMenu);
 		return FALSE;
 		}
 	    lpmenu->hWnd = hWnd;
@@ -2025,9 +1971,7 @@
 {
     LPPOPUPMENU lppop;
     LPMENUITEM 	lpitem;
-#ifdef DEBUG_MENU
-    printf("GetSubMenu (%04X, %04X) !\n", hMenu, nPos);
-#endif
+    dprintf_menu(stddeb,"GetSubMenu (%04X, %04X) !\n", hMenu, nPos);
     if (!(lppop = (LPPOPUPMENU) USER_HEAP_ADDR(hMenu))) return 0;
     if ((WORD)nPos >= lppop->nItems) return 0;
     lpitem = (MENUITEM *) USER_HEAP_ADDR( lppop->hItems );
@@ -2043,15 +1987,12 @@
 {
 	WND		*wndPtr;
 	LPPOPUPMENU lppop;
-#ifdef DEBUG_MENU
-	printf("DrawMenuBar (%04X)\n", hWnd);
-#endif
+	dprintf_menu(stddeb,"DrawMenuBar (%04X)\n", hWnd);
 	wndPtr = WIN_FindWndPtr(hWnd);
 	if (wndPtr != NULL && (wndPtr->dwStyle & WS_CHILD) == 0 && 
 		wndPtr->wIDmenu != 0) {
-#ifdef DEBUG_MENU
-		printf("DrawMenuBar wIDmenu=%04X \n", wndPtr->wIDmenu);
-#endif
+		dprintf_menu(stddeb,"DrawMenuBar wIDmenu=%04X \n", 
+			     wndPtr->wIDmenu);
 		lppop = (LPPOPUPMENU) USER_HEAP_ADDR(wndPtr->wIDmenu);
 		if (lppop == NULL) return;
 
@@ -2089,9 +2030,8 @@
 {
 	HMENU     		hMenu;
 	MENU_HEADER 	*menu_desc;
-#ifdef DEBUG_MENU
-	printf("LoadMenuIndirect: menu_template '%08X'\n", menu_template);
-#endif
+	dprintf_menu(stddeb,"LoadMenuIndirect: menu_template '%08X'\n", 
+		     menu_template);
 	hMenu = CreateMenu();
 	menu_desc = (MENU_HEADER *)menu_template;
 	ParseMenuResource((WORD *)(menu_desc + 1), 0, hMenu); 
@@ -2119,9 +2059,7 @@
 	AppendMenu( hMenu, item->item_flags, item->item_id, item->item_text );
     }
 
-#ifdef DEBUG_MENU
-    printf("CopySysMenu hMenu=%04X !\n", hMenu);
-#endif
+    dprintf_menu(stddeb,"CopySysMenu hMenu=%04X !\n", hMenu);
     return hMenu;
 }
 
diff --git a/controls/scroll.c b/controls/scroll.c
index e962e8c..36c7ef8 100644
--- a/controls/scroll.c
+++ b/controls/scroll.c
@@ -7,9 +7,6 @@
  * by Peter Broadhurst, 940611
  */
 
-/*
-#define DEBUG_SCROLL
-*/
 static char Copyright[] = "Copyright Martin Ayotte, 1993";
 
 #include <stdlib.h>
@@ -22,6 +19,11 @@
 #include "heap.h"
 #include "win.h"
 #include "prototypes.h"
+#include "stddebug.h"
+/* #define DEBUG_SCROLL /* */
+/* #undef  DEBUG_SCROLL /* */
+#include "debug.h"
+
 
 HBITMAP hUpArrow = 0;
 HBITMAP hDnArrow = 0;
@@ -83,16 +85,12 @@
 						lpCreat->cx, 16, SWP_NOZORDER);
 			}
 		CreateScrollBarStruct(hWnd);
-#ifdef DEBUG_SCROLL
-		printf("ScrollBar Creation !\n");
-#endif
+		dprintf_scroll(stddeb,"ScrollBar Creation !\n");
 		return 0;
 	case WM_DESTROY:
 		lphs = ScrollBarGetWindowAndStorage(hWnd, &wndPtr);
 		if (lphs == 0) return 0;
-#ifdef DEBUG_SCROLL
-		printf("ScrollBar WM_DESTROY %lX !\n", lphs);
-#endif
+		dprintf_scroll(stddeb,"ScrollBar WM_DESTROY %lX !\n", lphs);
 		free(lphs);
 		*((LPHEADSCROLL *)&wndPtr->wExtra[1]) = 0;
 		return 0;
@@ -116,9 +114,7 @@
 		return(SendMessage(wndPtr->hwndParent, message, wParam, lParam));
 
     case WM_TIMER:
-#ifdef DEBUG_SCROLL
-		printf("ScrollBar WM_TIMER wParam=%X lParam=%lX !\n", wParam, lParam);
-#endif
+		dprintf_scroll(stddeb,"ScrollBar WM_TIMER wParam=%X lParam=%lX !\n", wParam, lParam);
 		lphs = ScrollBarGetWindowAndStorage(hWnd, &wndPtr);
 		KillTimer(hWnd, wParam);
 		switch(lphs->ButtonDown) {
@@ -175,67 +171,51 @@
 	if (nBar == SB_CTL) {
 		hWndParent = GetParent(hWnd);
 		dwOwner = MAKELONG(0, lphs->hWndOwner);
-#ifdef DEBUG_SCROLL
-		printf("ScrollBarButtonDown SB_CTL // x=%d y=%d\n", x, y);
-#endif
+		dprintf_scroll(stddeb,"ScrollBarButtonDown SB_CTL // x=%d y=%d\n", x, y);
 		}
 	else {
 		hWndParent = hWnd;
 		dwOwner = 0L; 
-#ifdef DEBUG_SCROLL
-		printf("ScrollBarButtonDown SB_?SCROLL // x=%d y=%d\n", x, y);
-#endif
+		dprintf_scroll(stddeb,"ScrollBarButtonDown SB_?SCROLL // x=%d y=%d\n", x, y);
 		}
 /*
 	SetFocus(lphs->hWndOwner);
 */
 	CopyRect(&rect, &lphs->rect);
-#ifdef DEBUG_SCROLL
-	printf("ScrollDown / x=%d y=%d left=%d top=%d right=%d bottom=%d \n",
+	dprintf_scroll(stddeb,"ScrollDown / x=%d y=%d left=%d top=%d right=%d bottom=%d \n",
 					x, y, rect.left, rect.top, rect.right, rect.bottom);
-#endif
 	if (lphs->Direction == WM_VSCROLL) {
 		width = rect.right - rect.left;
 		if (y <= lphs->rectUp.bottom) {
 			lphs->ButtonDown = 1;
 			InvalidateRect(lphs->hWndOwner, &lphs->rectUp, TRUE); 
-#ifdef DEBUG_SCROLL
-			printf("ScrollBarButtonDown send SB_LINEUP\n");
-#endif
+			dprintf_scroll(stddeb,"ScrollBarButtonDown send SB_LINEUP\n");
 			SendMessage(hWndParent, lphs->Direction, 
 								SB_LINEUP, dwOwner);
 			}
 		if (y >= lphs->rectDown.top) {
 			lphs->ButtonDown = 2;
 			InvalidateRect(lphs->hWndOwner, &lphs->rectDown, TRUE); 
-#ifdef DEBUG_SCROLL
-			printf("ScrollBarButtonDown send SB_LINEDOWN\n");
-#endif
+			dprintf_scroll(stddeb,"ScrollBarButtonDown send SB_LINEDOWN\n");
 			SendMessage(hWndParent, lphs->Direction, 
 							SB_LINEDOWN, dwOwner);
 			}
 		if (y > lphs->rectUp.bottom && y < (lphs->CurPix + width)) {
 			lphs->ButtonDown = 5;
-#ifdef DEBUG_SCROLL
-			printf("ScrollBarButtonDown send SB_PAGEUP\n");
-#endif
+			dprintf_scroll(stddeb,"ScrollBarButtonDown send SB_PAGEUP\n");
 			SendMessage(hWndParent, lphs->Direction, 
 								SB_PAGEUP, dwOwner);
 			}
 		if (y < lphs->rectDown.top && y > (lphs->CurPix + (width << 1))) {
 			lphs->ButtonDown = 6;
-#ifdef DEBUG_SCROLL
-			printf("ScrollBarButtonDown send SB_PAGEDOWN\n");
-#endif
+			dprintf_scroll(stddeb,"ScrollBarButtonDown send SB_PAGEDOWN\n");
 			SendMessage(hWndParent, lphs->Direction, 
 							SB_PAGEDOWN, dwOwner);
 			}
 		if (lphs->MaxPix > 0 && y > (lphs->CurPix + width) &&
 			y < (lphs->CurPix + (width << 1))) {
 			lphs->ThumbActive = TRUE;
-#ifdef DEBUG_SCROLL
-			printf("THUMB DOWN !\n");
-#endif
+			dprintf_scroll(stddeb,"THUMB DOWN !\n");
 			}
 		}
 	else {
@@ -243,43 +223,33 @@
 		if (x <= lphs->rectUp.right) {
 			lphs->ButtonDown = 3;
 			InvalidateRect(lphs->hWndOwner, &lphs->rectUp, TRUE); 
-#ifdef DEBUG_SCROLL
-			printf("ScrollBarButtonDown send SB_LINEUP\n");
-#endif
+			dprintf_scroll(stddeb,"ScrollBarButtonDown send SB_LINEUP\n");
 			SendMessage(hWndParent, lphs->Direction, 
 								SB_LINEUP, dwOwner);
 			}
 		if (x >= lphs->rectDown.left) {
 			lphs->ButtonDown = 4;
 			InvalidateRect(lphs->hWndOwner, &lphs->rectDown, TRUE); 
-#ifdef DEBUG_SCROLL
-			printf("ScrollBarButtonDown send SB_LINEDOWN\n");
-#endif
+			dprintf_scroll(stddeb,"ScrollBarButtonDown send SB_LINEDOWN\n");
 			SendMessage(hWndParent, lphs->Direction, 
 							SB_LINEDOWN, dwOwner);
 			}
 		if (x > lphs->rectUp.right && x < (lphs->CurPix + height)) {
 			lphs->ButtonDown = 5;
-#ifdef DEBUG_SCROLL
-			printf("ScrollBarButtonDown send SB_PAGEUP\n");
-#endif
+			dprintf_scroll(stddeb,"ScrollBarButtonDown send SB_PAGEUP\n");
 			SendMessage(hWndParent, lphs->Direction, 
 								SB_PAGEUP, dwOwner);
 			}
 		if (x < lphs->rectDown.left && x > (lphs->CurPix + (height << 1))) {
 			lphs->ButtonDown = 6;
-#ifdef DEBUG_SCROLL
-			printf("ScrollBarButtonDown send SB_PAGEDOWN\n");
-#endif
+			dprintf_scroll(stddeb,"ScrollBarButtonDown send SB_PAGEDOWN\n");
 			SendMessage(hWndParent, lphs->Direction, 
 							SB_PAGEDOWN, dwOwner);
 			}
 		if (lphs->MaxPix > 0 && x > (lphs->CurPix + height) &&
 			x < (lphs->CurPix + (height << 1))) {
 			lphs->ThumbActive = TRUE;
-#ifdef DEBUG_SCROLL
-			printf("THUMB DOWN !\n");
-#endif
+			dprintf_scroll(stddeb,"THUMB DOWN !\n");
 			}
 		}
 	if (lphs->ButtonDown != 0) {
@@ -297,9 +267,7 @@
 	LPHEADSCROLL lphs;
 	RECT	rect, rect2;
 	HDC		hDC;
-#ifdef DEBUG_SCROLL
-	printf("ScrollBarButtonUp // x=%d y=%d\n", x, y); 
-#endif
+	dprintf_scroll(stddeb,"ScrollBarButtonUp // x=%d y=%d\n", x, y); 
 	lphs = GetScrollObjectStruct(hWnd, nBar);
 	if(lphs->ThumbActive)
 	  {
@@ -347,25 +315,19 @@
 	if (nBar == SB_CTL) {
 		hWndParent = GetParent(hWnd);
 		hWndOwner = lphs->hWndOwner;
-#ifdef DEBUG_SCROLL
-		printf("ScrollBarButtonMove SB_CTL // x=%d y=%d\n", x, y);
-#endif
+		dprintf_scroll(stddeb,"ScrollBarButtonMove SB_CTL // x=%d y=%d\n", x, y);
 		}
 	else {
 		hWndParent = hWnd;
 		hWndOwner = 0;
-#ifdef DEBUG_SCROLL
-		printf("ScrollBarButtonMove SB_?SCROLL // x=%d y=%d\n", x, y);
-#endif
+		dprintf_scroll(stddeb,"ScrollBarButtonMove SB_?SCROLL // x=%d y=%d\n", x, y);
 		}
 
 	if(x<lphs->rect.left||x>lphs->rect.right||
 	   y<lphs->rect.top||y>lphs->rect.bottom)
 	  {
 
-#ifdef DEBUG_SCROLL
-	    printf("Rejecting thumb position !\n");
-#endif
+	    dprintf_scroll(stddeb,"Rejecting thumb position !\n");
 	    lphs->ThumbVal=lphs->CurVal;/*revert to last set position*/
 	  }
 	else
@@ -385,9 +347,8 @@
 			      lphs->MaxPix) + lphs->MinVal;
 	  }
 
-#ifdef DEBUG_SCROLL
-	printf("Scroll WM_MOUSEMOVE val=%d pix=%d\n", lphs->ThumbVal, y);
-#endif
+	dprintf_scroll(stddeb,"Scroll WM_MOUSEMOVE val=%d pix=%d\n", 
+		       lphs->ThumbVal, y);
 	SendMessage(hWndParent, lphs->Direction, 
 		SB_THUMBTRACK, MAKELONG(lphs->ThumbVal, hWndOwner));
 }
@@ -399,7 +360,7 @@
     LPHEADSCROLL lphs;
     *(wndPtr) = Ptr = WIN_FindWndPtr(hWnd);
     if (Ptr == 0) {
-    	printf("Bad Window handle on ScrollBar !\n");
+    	fprintf(stderr,"Bad Window handle on ScrollBar !\n");
     	return 0;
     	}
     lphs = *((LPHEADSCROLL *)&Ptr->wExtra[1]);
@@ -413,7 +374,7 @@
     LPHEADSCROLL lphs;
     wndPtr = WIN_FindWndPtr(hWnd);
     if (wndPtr == 0) {
-    	printf("Bad Window handle on ScrollBar !\n");
+    	fprintf(stderr,"Bad Window handle on ScrollBar !\n");
     	return 0;
     	}
     lphs = *((LPHEADSCROLL *)&wndPtr->wExtra[1]);
@@ -427,20 +388,19 @@
 	HWND	hWndParent;
 	HBRUSH 	hBrush;
 	HDC 	hMemDC;
+        HBITMAP hOldBmp;
 	BITMAP	bm;
 	RECT 	rect;
 	UINT  	i, w, w2, h, h2, siz;
 	char	C[128];
 	if (lphs == NULL) return;
-#ifdef DEBUG_SCROLL
-	printf("StdDrawScrollBar nBar=%04X !\n", nBar);
+	dprintf_scroll(stddeb,"StdDrawScrollBar nBar=%04X !\n", nBar);
 	if (lphs->Direction == WM_VSCROLL)
-		printf("StdDrawScrollBar Vertical left=%d top=%d right=%d bottom=%d !\n", 
+		dprintf_scroll(stddeb,"StdDrawScrollBar Vertical left=%d top=%d right=%d bottom=%d !\n", 
 			lprect->left, lprect->top, lprect->right, lprect->bottom);
 	else
-		printf("StdDrawScrollBar Horizontal left=%d top=%d right=%d bottom=%d !\n", 
+		dprintf_scroll(stddeb,"StdDrawScrollBar Horizontal left=%d top=%d right=%d bottom=%d !\n", 
 			lprect->left, lprect->top, lprect->right, lprect->bottom);
-#endif
 	if (nBar == SB_CTL)
 		hWndParent = GetParent(hWnd);
 	else
@@ -489,9 +449,9 @@
 	if (lphs->Direction == WM_VSCROLL) {
 		GetObject(hUpArrow, sizeof(BITMAP), (LPSTR)&bm);
 		if (lphs->ButtonDown == 1)
-			SelectObject(hMemDC, hUpArrowD);
+			hOldBmp = SelectObject(hMemDC, hUpArrowD);
 		else
-			SelectObject(hMemDC, hUpArrow);
+			hOldBmp = SelectObject(hMemDC, hUpArrow);
 		StretchBlt(hDC, rect.left, rect.top, w, h2, hMemDC, 
 			0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY);
 		GetObject(hDnArrow, sizeof(BITMAP), (LPSTR)&bm);
@@ -507,9 +467,9 @@
 	else {
 		GetObject(hLfArrow, sizeof(BITMAP), (LPSTR)&bm);
 		if (lphs->ButtonDown == 3)
-			SelectObject(hMemDC, hLfArrowD);
+			hOldBmp = SelectObject(hMemDC, hLfArrowD);
 		else
-			SelectObject(hMemDC, hLfArrow);
+			hOldBmp = SelectObject(hMemDC, hLfArrow);
 		StretchBlt(hDC, rect.left, rect.top, w2, h, hMemDC, 
 			0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY);
 		GetObject(hRgArrow, sizeof(BITMAP), (LPSTR)&bm);
@@ -522,6 +482,7 @@
 		rect.left += w2;
 		rect.right -= w2;
 		}
+        SelectObject( hMemDC, hOldBmp );
 	DeleteDC(hMemDC);
 	FillRect(hDC, &rect, hBrush);
 	if (lphs->MaxPix != 0) {
@@ -534,9 +495,9 @@
 		FrameRect(hDC, &rect, GetStockObject(BLACK_BRUSH));
 		InflateRect(&rect, -1, -1);
 		FillRect(hDC, &rect, GetStockObject(LTGRAY_BRUSH));
-		DrawReliefRect(hDC, rect, 2, 0);
+		GRAPH_DrawReliefRect(hDC, &rect, 2, 0);
 		InflateRect(&rect, -3, -3);
-		DrawReliefRect(hDC, rect, 1, 1);
+		GRAPH_DrawReliefRect(hDC, &rect, 1, 1);
 		}
 }
 
@@ -555,9 +516,7 @@
 	lphs = AllocScrollBar(WS_VSCROLL, width, height);
     else
 	lphs = AllocScrollBar(WS_HSCROLL, width, height);
-#ifdef DEBUG_SCROLL
-        printf("CreateScrollBarStruct %lX !\n", lphs);
-#endif
+        dprintf_scroll(stddeb,"CreateScrollBarStruct %lX !\n", lphs);
     *((LPHEADSCROLL *)&wndPtr->wExtra[1]) = lphs;
     lphs->hWndOwner = hWnd;
     CopyRect(&lphs->rect, &wndPtr->rectClient);
@@ -587,7 +546,7 @@
 		hRgArrowD = LoadBitmap((HINSTANCE)NULL, MAKEINTRESOURCE(OBM_RGARROWD));
 	lphs = (LPHEADSCROLL)malloc(sizeof(HEADSCROLL));
 	if (lphs == 0) {
-		printf("Bad Memory Alloc on ScrollBar !\n");
+		fprintf(stderr,"Bad Memory Alloc on ScrollBar !\n");
 		return NULL;
 		}
 	lphs->ThumbActive = FALSE;
@@ -630,9 +589,8 @@
 	if (wndPtr->dwStyle & WS_VSCROLL) {
 		if (wndPtr->dwStyle & WS_HSCROLL) height -= SYSMETRICS_CYHSCROLL;
 		lphs = AllocScrollBar(WS_VSCROLL, SYSMETRICS_CXVSCROLL, height);
-#ifdef DEBUG_SCROLL
-		printf("NC_CreateScrollBars Vertical %lX !\n", lphs);
-#endif
+		dprintf_scroll(stddeb,"NC_CreateScrollBars Vertical %lX !\n", 
+			       lphs);
 		lphs->rect.left = width - SYSMETRICS_CYVSCROLL;
 		lphs->rect.right = width;
 		lphs->hWndOwner = hWnd;
@@ -643,9 +601,7 @@
 	if (wndPtr->dwStyle & WS_HSCROLL) {
 		if (wndPtr->dwStyle & WS_VSCROLL) width -= SYSMETRICS_CYVSCROLL;
 		lphs = AllocScrollBar(WS_HSCROLL, width, SYSMETRICS_CYHSCROLL);
-#ifdef DEBUG_SCROLL
-		printf("NC_CreateScrollBars Horizontal %lX !\n", lphs);
-#endif
+		dprintf_scroll(stddeb,"NC_CreateScrollBars Horizontal %lX !\n", lphs);
 		lphs->rect.top = height - SYSMETRICS_CYHSCROLL;
 		lphs->rect.bottom = height;
 		lphs->hWndOwner = hWnd;
@@ -689,12 +645,10 @@
 	if(lphs->CurPix <0)lphs->CurPix=0;
 
     if (lphs->CurPix > lphs->MaxPix)  lphs->CurPix = lphs->MaxPix;
-#ifdef DEBUG_SCROLL
-    printf("SetScrollPos val=%d pixval=%d pixmax%d\n",
+    dprintf_scroll(stddeb,"SetScrollPos val=%d pixval=%d pixmax%d\n",
 	    (short)nPos, lphs->CurPix, lphs->MaxPix);
-    printf("SetScrollPos min=%d max=%d\n", 
+    dprintf_scroll(stddeb,"SetScrollPos min=%d max=%d\n", 
 	    lphs->MinVal, lphs->MaxVal);
-#endif
     if ((bRedraw) && (IsWindowVisible(lphs->hWndOwner))) {
 		if (nBar == SB_CTL) {
 	        InvalidateRect(lphs->hWndOwner, &lphs->rect, TRUE);
@@ -745,9 +699,8 @@
 	  (lphs->MaxVal - lphs->MinVal);
     if(lphs->CurPix <0)lphs->CurPix=0;
     if (lphs->CurPix > lphs->MaxPix)  lphs->CurPix = lphs->MaxPix;
-#ifdef DEBUG_SCROLL
-    printf("SetScrollRange min=%d max=%d\n", lphs->MinVal, lphs->MaxVal);
-#endif
+    dprintf_scroll(stddeb,"SetScrollRange min=%d max=%d\n", 
+		   lphs->MinVal, lphs->MaxVal);
     if ((bRedraw) && (IsWindowVisible(lphs->hWndOwner))) {
 		if (nBar == SB_CTL) {
 	        InvalidateRect(lphs->hWndOwner, &lphs->rect, TRUE);
@@ -785,10 +738,8 @@
 void ShowScrollBar(HWND hWnd, WORD wBar, BOOL bFlag)
 {
 	WND  *wndPtr;
-	printf("ShowScrollBar hWnd=%04X wBar=%d bFlag=%d\n", hWnd, wBar, bFlag);
-#ifdef DEBUG_SCROLL
-	printf("ShowScrollBar hWnd=%04X wBar=%d bFlag=%d\n", hWnd, wBar, bFlag);
-#endif
+	dprintf_scroll(stddeb,"ShowScrollBar hWnd=%04X wBar=%d bFlag=%d\n", 
+		       hWnd, wBar, bFlag);
 	if (wBar == SB_CTL) {
 		if (bFlag)
 			ShowWindow(hWnd, SW_SHOW);
diff --git a/controls/static.c b/controls/static.c
index 5d71bc9..e36b412 100644
--- a/controls/static.c
+++ b/controls/static.c
@@ -11,85 +11,83 @@
 #include <windows.h>
 #include "win.h"
 #include "user.h"
+#include "static.h"
+#include "icon.h"
 
 extern void DEFWND_SetText( HWND hwnd, LPSTR text );  /* windows/defwnd.c */
 
-static LONG PaintTextfn(HWND hwnd);
-static LONG PaintRectfn(HWND hwnd);
-static LONG PaintFramefn(HWND hwnd);
-static LONG PaintIconfn(HWND hwnd);
+static void PaintTextfn( HWND hwnd, HDC hdc );
+static void PaintRectfn( HWND hwnd, HDC hdc );
+static void PaintFramefn( HWND hwnd, HDC hdc );
+static void PaintIconfn( HWND hwnd, HDC hdc );
 
 
-static COLORREF color_windowframe, color_background, color_window,
-                                                     color_windowtext;
+static COLORREF color_windowframe, color_background, color_window;
 
-#define NOTIFY_PARENT(hWndCntrl, wNotifyCode) \
-	SendMessage(GetParent(hWndCntrl), WM_COMMAND, \
-		    GetDlgCtrlID(hWndCntrl), MAKELPARAM(hWndCntrl, wNotifyCode));
-#define DIM(array)	((sizeof array)/(sizeof array[0]))
 
-typedef struct
+typedef void (*pfPaint)(HWND, HDC);
+
+#define LAST_STATIC_TYPE  SS_LEFTNOWORDWRAP
+
+static pfPaint staticPaintFunc[LAST_STATIC_TYPE+1] =
 {
-    LONG (*paintfn)();
-} STATICFN;
-
-#define MAX_STATIC_TYPE  12
-
-static STATICFN staticfn[MAX_STATIC_TYPE] =
-{
-    { (LONG(*)())PaintTextfn },                    /* SS_LEFT */
-    { (LONG(*)())PaintTextfn },                    /* SS_CENTER */
-    { (LONG(*)())PaintTextfn },                    /* SS_RIGHT */
-    { (LONG(*)())PaintIconfn },                    /* SS_ICON */
-    { (LONG(*)())PaintRectfn },                    /* SS_BLACKRECT */
-    { (LONG(*)())PaintRectfn },                    /* SS_GRAYRECT */
-    { (LONG(*)())PaintRectfn },                    /* SS_WHITERECT */
-    { (LONG(*)())PaintFramefn },                   /* SS_BLACKFRAME */
-    { (LONG(*)())PaintFramefn },                   /* SS_GRAYFRAME */
-    { (LONG(*)())PaintFramefn },                   /* SS_WHITEFRAME */
-    { (LONG(*)())PaintTextfn },                    /* SS_SIMPLE */
-    { (LONG(*)())PaintTextfn }                     /* SS_LEFTNOWORDWRAP */
+    PaintTextfn,             /* SS_LEFT */
+    PaintTextfn,             /* SS_CENTER */
+    PaintTextfn,             /* SS_RIGHT */
+    PaintIconfn,             /* SS_ICON */
+    PaintRectfn,             /* SS_BLACKRECT */
+    PaintRectfn,             /* SS_GRAYRECT */
+    PaintRectfn,             /* SS_WHITERECT */
+    PaintFramefn,            /* SS_BLACKFRAME */
+    PaintFramefn,            /* SS_GRAYFRAME */
+    PaintFramefn,            /* SS_WHITEFRAME */
+    NULL,                    /* Not defined */
+    PaintTextfn,             /* SS_SIMPLE */
+    PaintTextfn              /* SS_LEFTNOWORDWRAP */
 };
 
 
+/***********************************************************************
+ *           STATIC_SetIcon
+ *
+ * Set the icon for an SS_ICON control.
+ */
+static void STATIC_SetIcon( HWND hwnd, HICON hicon )
+{
+    WND *wndPtr = WIN_FindWndPtr( hwnd );
+    STATICINFO *infoPtr = (STATICINFO *)wndPtr->wExtra;
+
+    if ((wndPtr->dwStyle & 0x0f) != SS_ICON) return;
+    if (infoPtr->hIcon) DestroyIcon( infoPtr->hIcon );
+    infoPtr->hIcon = hicon;
+    if (hicon)
+    {
+        ICONALLOC *icon = (ICONALLOC *) GlobalLock( hicon );
+        SetWindowPos( hwnd, 0, 0, 0,
+                     icon->descriptor.Width, icon->descriptor.Height,
+                     SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER );
+        GlobalUnlock( hicon );
+    }
+}
+
+
+/***********************************************************************
+ *           StaticWndProc
+ */
 LONG StaticWndProc(HWND hWnd, WORD uMsg, WORD wParam, LONG lParam)
 {
 	LONG lResult = 0;
-	HDC hDC;
-	RECT rc;
-	LPSTR textPtr;
-
 	WND *wndPtr = WIN_FindWndPtr(hWnd);
 	LONG style = wndPtr->dwStyle & 0x0000000F;
+        STATICINFO *infoPtr = (STATICINFO *)wndPtr->wExtra;
 
 	switch (uMsg) {
 	case WM_ENABLE:
 	    InvalidateRect(hWnd, NULL, FALSE);
 	    break;
 
-	case WM_NCCREATE:
-	    if (style == SS_ICON)
-	    {
-		  /* Note: we use wndPtr->hText to store the icon handle */
-		CREATESTRUCT * createStruct = (CREATESTRUCT *)lParam;
-		if (createStruct->lpszName)
-		    wndPtr->hText = LoadIcon( createStruct->hInstance,
-					      createStruct->lpszName );
-		return 1;
-	    }
-	    else return DefWindowProc(hWnd, uMsg, wParam, lParam);
-
-	case WM_NCDESTROY:
-	    if (style == SS_ICON)
-	    {
-		if (wndPtr->hText) DestroyIcon( wndPtr->hText );
-		wndPtr->hText = 0;
-		return 0;
-	    }
-	    else return DefWindowProc(hWnd, uMsg, wParam, lParam);
-
 	case WM_CREATE:
-	    if (style < 0L || style >= (LONG)DIM(staticfn)) {
+	    if (style < 0L || style > LAST_STATIC_TYPE) {
 		lResult = -1L;
 		break;
 		}
@@ -97,49 +95,68 @@
 	    color_windowframe  = GetSysColor(COLOR_WINDOWFRAME);
 	    color_background   = GetSysColor(COLOR_BACKGROUND);
 	    color_window       = GetSysColor(COLOR_WINDOW);
-	    color_windowtext   = GetSysColor(COLOR_WINDOWTEXT);
-	    lResult = 0L;
-	    if (style == SS_ICON) {
-/*
-		SetWindowPos(hWnd, (HWND)NULL, 0, 0, 32, 32,
-				SWP_NOZORDER | SWP_NOMOVE);
-*/
-		}
+	    if (style == SS_ICON)
+            {
+		CREATESTRUCT * createStruct = (CREATESTRUCT *)lParam;
+		if (createStruct->lpszName)
+                    STATIC_SetIcon( hWnd, LoadIcon( createStruct->hInstance,
+                                                    createStruct->lpszName ));
+            }
 	    break;
 
+        case WM_DESTROY:
+            STATIC_SetIcon( hWnd, 0 );  /* Destroy the current icon */
+            break;
+
 	case WM_PAINT:
-	    if (staticfn[style].paintfn)
-		(staticfn[style].paintfn)(hWnd);
+	    if (staticPaintFunc[style])
+            {
+                PAINTSTRUCT ps;
+                BeginPaint( hWnd, &ps );
+		(staticPaintFunc[style])( hWnd, ps.hdc );
+                EndPaint( hWnd, &ps );
+            }
 	    break;
 
 	case WM_SYSCOLORCHANGE:
 	    color_windowframe  = GetSysColor(COLOR_WINDOWFRAME);
 	    color_background   = GetSysColor(COLOR_BACKGROUND);
 	    color_window       = GetSysColor(COLOR_WINDOW);
-	    color_windowtext   = GetSysColor(COLOR_WINDOWTEXT);
 	    InvalidateRect(hWnd, NULL, TRUE);
 	    break;
 
 	case WM_SETTEXT:
-	    if (style == SS_ICON) break;
 	    DEFWND_SetText( hWnd, (LPSTR)lParam );
 	    InvalidateRect( hWnd, NULL, FALSE );
 	    UpdateWindow( hWnd );
 	    break;
 
+        case WM_SETFONT:
+            if (style == SS_ICON) return 0;
+            infoPtr->hFont = wParam;
+            if (LOWORD(lParam))
+            {
+                InvalidateRect( hWnd, NULL, FALSE );
+                UpdateWindow( hWnd );
+            }
+            break;
+
+        case WM_GETFONT:
+            return infoPtr->hFont;
+
 	case WM_NCHITTEST:
 	    return HTTRANSPARENT;
 
+        case WM_GETDLGCODE:
+            return DLGC_STATIC;
+
 	case STM_GETICON:
-	    if (style != SS_ICON) return 0;
-	    return (HICON)wndPtr->hText;
+	    return infoPtr->hIcon;
 
 	case STM_SETICON:
-	    if (style != SS_ICON) return 0;
-	    if (wndPtr->hText) DestroyIcon( wndPtr->hText );
-	    wndPtr->hText = wParam;
-	    InvalidateRect( hWnd, NULL, TRUE );
-	    UpdateWindow( hWnd );
+            STATIC_SetIcon( hWnd, wParam );
+            InvalidateRect( hWnd, NULL, FALSE );
+            UpdateWindow( hWnd );
 	    return 0;
 
 	default:
@@ -151,27 +168,19 @@
 }
 
 
-static LONG PaintTextfn(HWND hwnd)
+static void PaintTextfn( HWND hwnd, HDC hdc )
 {
-    PAINTSTRUCT ps;
     RECT rc;
-    HDC hdc;
     HBRUSH hBrush;
-    HANDLE hText;
     char *text;
-    int textlen;
     WORD wFormat;
 
     WND *wndPtr = WIN_FindWndPtr(hwnd);
     LONG style = wndPtr->dwStyle;
+    STATICINFO *infoPtr = (STATICINFO *)wndPtr->wExtra;
 
-    hdc = BeginPaint(hwnd, &ps);
     GetClientRect(hwnd, &rc);
-
-    textlen = GetWindowTextLength(hwnd);
-    hText = USER_HEAP_ALLOC(0, textlen+1);
-    text = USER_HEAP_ADDR(hText);
-    GetWindowText(hwnd, text, textlen+1);
+    text = USER_HEAP_ADDR( wndPtr->hText );
 
     switch (style & 0x0000000F)
     {
@@ -199,70 +208,48 @@
     if (style & SS_NOPREFIX)
 	wFormat |= DT_NOPREFIX;
 
-    hBrush = SendMessage(GetParent(hwnd), WM_CTLCOLOR, (WORD)hdc,
-		    MAKELONG(hwnd, CTLCOLOR_STATIC));
+    if (infoPtr->hFont) SelectObject( hdc, infoPtr->hFont );
+    hBrush = SendMessage( wndPtr->hwndParent, WM_CTLCOLOR, (WORD)hdc,
+                          MAKELONG(hwnd, CTLCOLOR_STATIC));
     if (hBrush == (HBRUSH)NULL) hBrush = GetStockObject(WHITE_BRUSH);
     FillRect(hdc, &rc, hBrush);
-    DrawText(hdc, text, textlen, &rc, wFormat);
-
-    USER_HEAP_FREE(hText);
-    EndPaint(hwnd, &ps);
+    DrawText(hdc, text, -1, &rc, wFormat);
 }
 
-static LONG PaintRectfn(HWND hwnd)
+static void PaintRectfn( HWND hwnd, HDC hdc )
 {
-    PAINTSTRUCT ps;
     RECT rc;
-    HDC hdc;
-    HPEN hOldPen, hPen;
-    HBRUSH hOldBrush, hBrush;
+    HBRUSH hBrush;
 
     WND *wndPtr = WIN_FindWndPtr(hwnd);
 
-    hdc = BeginPaint(hwnd, &ps);
     GetClientRect(hwnd, &rc);
     
     switch (wndPtr->dwStyle & 0x0000000F)
     {
     case SS_BLACKRECT:
-	hPen = CreatePen(PS_SOLID, 1, color_windowframe);
 	hBrush = CreateSolidBrush(color_windowframe);
 	break;
 
     case SS_GRAYRECT:
-	hPen = CreatePen(PS_SOLID, 1, color_background);
 	hBrush = CreateSolidBrush(color_background);
 	break;
 
     case SS_WHITERECT:
-	hPen = CreatePen(PS_SOLID, 1, color_window);
 	hBrush = CreateSolidBrush(color_window);
 	break;
     }
-
-    hOldPen = (HPEN)SelectObject(hdc, (HANDLE)hPen);
-    hOldBrush = (HBRUSH)SelectObject(hdc, (HANDLE)hBrush);
-    Rectangle(hdc, rc.left, rc.top, rc.right, rc.bottom);
-
-    SelectObject(hdc, (HANDLE)hOldPen);
-    SelectObject(hdc, (HANDLE)hOldBrush);
-    DeleteObject((HANDLE)hPen);
-    DeleteObject((HANDLE)hBrush);
-
-    EndPaint(hwnd, &ps);
+    FillRect( hdc, &rc, hBrush );
 }
 
-static LONG PaintFramefn(HWND hwnd)
+static void PaintFramefn( HWND hwnd, HDC hdc )
 {
-    PAINTSTRUCT ps;
     RECT rc;
-    HDC hdc;
     HPEN hOldPen, hPen;
     HBRUSH hOldBrush, hBrush;
 
     WND *wndPtr = WIN_FindWndPtr(hwnd);
 
-    hdc = BeginPaint(hwnd, &ps);
     GetClientRect(hwnd, &rc);
     
     switch (wndPtr->dwStyle & 0x0000000F)
@@ -289,22 +276,19 @@
     SelectObject(hdc, (HANDLE)hOldBrush);
     DeleteObject((HANDLE)hPen);
     DeleteObject((HANDLE)hBrush);
-
-    EndPaint(hwnd, &ps);
 }
 
 
-static LONG PaintIconfn(HWND hwnd)
+static void PaintIconfn( HWND hwnd, HDC hdc )
 {
-    WND 	*wndPtr;
-    PAINTSTRUCT ps;
     RECT 	rc;
-    HDC 	hdc;
+    HBRUSH      hbrush;
+    WND *wndPtr = WIN_FindWndPtr(hwnd);
+    STATICINFO *infoPtr = (STATICINFO *)wndPtr->wExtra;
 
-    wndPtr = WIN_FindWndPtr(hwnd);
-    hdc = BeginPaint(hwnd, &ps);
     GetClientRect(hwnd, &rc);
-    FillRect(hdc, &rc, GetStockObject(WHITE_BRUSH));
-    if (wndPtr->hText) DrawIcon(hdc, rc.left, rc.top, wndPtr->hText );
-    EndPaint(hwnd, &ps);
+    hbrush = SendMessage( wndPtr->hwndParent, WM_CTLCOLOR, hdc,
+                          MAKELONG(hwnd, CTLCOLOR_STATIC));
+    FillRect( hdc, &rc, hbrush );
+    if (infoPtr->hIcon) DrawIcon( hdc, rc.left, rc.top, infoPtr->hIcon );
 }
diff --git a/controls/widgets.c b/controls/widgets.c
index 104b135..4280476 100644
--- a/controls/widgets.c
+++ b/controls/widgets.c
@@ -7,12 +7,12 @@
 static char Copyright[] = "Copyright  Alexandre Julliard, 1993";
 
 #include "win.h"
+#include "button.h"
+#include "static.h"
 #include "desktop.h"
 #include "mdi.h"
 #include "gdi.h"
 
-LONG ButtonWndProc( HWND hwnd, WORD message, WORD wParam, LONG lParam );
-LONG StaticWndProc( HWND hwnd, WORD message, WORD wParam, LONG lParam );
 LONG ScrollBarWndProc( HWND hwnd, WORD message, WORD wParam, LONG lParam );
 LONG ListBoxWndProc  ( HWND hwnd, WORD message, WORD wParam, LONG lParam );
 LONG ComboBoxWndProc ( HWND hwnd, WORD message, WORD wParam, LONG lParam );
@@ -24,25 +24,25 @@
 
 static WNDCLASS WIDGETS_BuiltinClasses[] =
 {
-    { CS_GLOBALCLASS, (LONG(*)())ButtonWndProc, 0, 2, 
+    { CS_GLOBALCLASS | CS_PARENTDC, ButtonWndProc, 0, sizeof(BUTTONINFO), 
       0, 0, 0, 0, NULL, "BUTTON" },
-    { CS_GLOBALCLASS, (LONG(*)())StaticWndProc, 0, 0,
+    { CS_GLOBALCLASS | CS_PARENTDC, StaticWndProc, 0, sizeof(STATICINFO),
       0, 0, 0, 0, NULL, "STATIC" },
-    { CS_GLOBALCLASS, (LONG(*)())ScrollBarWndProc, 0, 8,
+    { CS_GLOBALCLASS | CS_PARENTDC, ScrollBarWndProc, 0, 8,
       0, 0, 0, 0, NULL, "SCROLLBAR" },
-    { CS_GLOBALCLASS, (LONG(*)())ListBoxWndProc, 0, 8,
+    { CS_GLOBALCLASS | CS_PARENTDC, ListBoxWndProc, 0, 8,
       0, 0, 0, 0, NULL, "LISTBOX" },
-    { CS_GLOBALCLASS, (LONG(*)())ComboBoxWndProc, 0, 8,
+    { CS_GLOBALCLASS | CS_PARENTDC, ComboBoxWndProc, 0, 8,
       0, 0, 0, 0, NULL, "COMBOBOX" },
-    { CS_GLOBALCLASS, (LONG(*)())EditWndProc, 0, 4, 
+    { CS_GLOBALCLASS | CS_PARENTDC, EditWndProc, 0, 4, 
       0, 0, 0, 0, NULL, "EDIT" },
-    { CS_GLOBALCLASS | CS_SAVEBITS, (LONG(*)())PopupMenuWndProc, 0, 8,
+    { CS_GLOBALCLASS | CS_SAVEBITS, PopupMenuWndProc, 0, 8,
       0, 0, 0, 0, NULL, POPUPMENU_CLASS_NAME },
-    { CS_GLOBALCLASS, (LONG(*)())DesktopWndProc, 0, sizeof(DESKTOPINFO),
+    { CS_GLOBALCLASS, DesktopWndProc, 0, sizeof(DESKTOPINFO),
       0, 0, 0, 0, NULL, DESKTOP_CLASS_NAME },
-    { CS_GLOBALCLASS | CS_SAVEBITS, (LONG(*)())DefDlgProc, 0, DLGWINDOWEXTRA,
+    { CS_GLOBALCLASS | CS_SAVEBITS, DefDlgProc, 0, DLGWINDOWEXTRA,
       0, 0, 0, 0, NULL, DIALOG_CLASS_NAME },
-    { CS_GLOBALCLASS, (LONG(*)())MDIClientWndProc, 0, sizeof(MDICLIENTINFO),
+    { CS_GLOBALCLASS, MDIClientWndProc, 0, sizeof(MDICLIENTINFO),
       0, 0, 0, STOCK_LTGRAY_BRUSH, NULL, "MDICLIENT" }
 };
 
diff --git a/debugger/Imakefile b/debugger/Imakefile
index 8f4d8a7..0eae52b 100644
--- a/debugger/Imakefile
+++ b/debugger/Imakefile
@@ -16,12 +16,7 @@
 	lex.yy.c \
 	info.c
 
-OBJS = \
-	dbg.tab.o \
-	break.o \
-	hash.o \
-	lex.yy.o \
-	info.o
+OBJS = $(SRCS:.c=.o)
 
 /*
  * All the SUBDIR stuff
diff --git a/debugger/dbg.y b/debugger/dbg.y
index 907fd0f..f09de83 100644
--- a/debugger/dbg.y
+++ b/debugger/dbg.y
@@ -178,14 +178,16 @@
 
 	/* This is intended to read the entry points from the Windows image, and
 	   insert them in the hash table.  It does not work yet, so it is commented out. */
-#if 0
 	if(!loaded_symbols){
 		loaded_symbols++;
+		read_symboltable("wine.sym");
+#if 0
 		load_entrypoints();
-	}
 #endif
+	}
 
 	/* Remove the breakpoints from memory... */
+	fprintf(stderr,"Removing BPs\n");
 	insert_break(0);
 
 	/* If we stopped on a breakpoint, report this fact */
diff --git a/debugger/hash.c b/debugger/hash.c
index 97254af..468446e 100644
--- a/debugger/hash.c
+++ b/debugger/hash.c
@@ -157,10 +157,10 @@
 
 	struct w_files * wpnt;
 	for(wpnt = wine_files; wpnt; wpnt = wpnt->next){
-		cpnt  = wpnt->nrname_table;
+		cpnt  = wpnt->ne->nrname_table;
 		while(1==1){
-			if( ((int) cpnt)  - ((int)wpnt->nrname_table) >  
-			   wpnt->ne_header->nrname_tab_length)  break;
+			if( ((int) cpnt)  - ((int)wpnt->ne->nrname_table) >  
+			   wpnt->ne->ne_header->nrname_tab_length)  break;
 			len = *cpnt++;
 			strncpy(buffer, cpnt, len);
 			buffer[len] = 0;
@@ -168,7 +168,7 @@
 			j = GetEntryPointFromOrdinal(wpnt, ordinal);		
 			address  = j & 0xffff;
 			j = j >> 16;
-			address |= (wpnt->selector_table[j].selector) << 16;
+			address |= (wpnt->ne->selector_table[j].selector) << 16;
 			fprintf(stderr,"%s -> %x\n", buffer, address);
 			add_hash(buffer, (unsigned int *) address);
 			cpnt += len + 2;
diff --git a/debugger/info.c b/debugger/info.c
index 8df409e..60f3513 100644
--- a/debugger/info.c
+++ b/debugger/info.c
@@ -282,16 +282,18 @@
   }
 
   fprintf(stderr,"Backtrace:\n");
-  fprintf(stderr,"%d %4.4x:%4.4x\n", frameno++, SC_CS, SC_EIP(dbg_mask));
+  fprintf(stderr,"%d ",frameno);
+  print_address(frame->u.win32.saved_ip,stderr);
   cs = SC_CS;
 
   frame = (struct frame *) ((SC_EBP(dbg_mask) & ~1) | (SC_SS << 16));
   while((cs & 3) == 3) {
     /* See if in 32 bit mode or not.  Assume GDT means 32 bit. */
     if ((cs & 7) != 7) {
-      cs = frame->u.win32.saved_cs;
-      fprintf(stderr,"%d %4.4x:%4.4x\n", frameno++, cs, 
-	      frame->u.win32.saved_ip);
+      void CallTo32();
+      fprintf(stderr,"\n%d ",frameno++);
+      print_address(frame->u.win32.saved_ip,stderr);
+      if(frame->u.win32.saved_ip<((char*)CallTo32+1000))break;
       frame = (struct frame *) frame->u.win32.saved_bp;
     } else {
       cs = frame->u.win16.saved_cs;
@@ -301,5 +303,6 @@
 				(SC_SS << 16));
     }
   }
+  putchar('\n');
 }
 
diff --git a/debugger/opcodes/Imakefile b/debugger/opcodes/Imakefile
index 1178f76..fc12d01 100644
--- a/debugger/opcodes/Imakefile
+++ b/debugger/opcodes/Imakefile
@@ -11,9 +11,7 @@
 	dis-buf.c \
 	i386-dis.c
 
-OBJS = \
-	dis-buf.o \
-	i386-dis.o
+OBJS = $(SRCS:.c=.o)
 
 #ifdef xi386
 #define i386 1
@@ -22,7 +20,6 @@
 
 WineRelocatableTarget($(TOP)/$(MODULE),,$(OBJS))
 DependTarget()
-CleanTarget()
 
 includes::
 
diff --git a/debugger/readline/Imakefile b/debugger/readline/Imakefile
index 817f4af..e50e7c5 100644
--- a/debugger/readline/Imakefile
+++ b/debugger/readline/Imakefile
@@ -11,14 +11,10 @@
 	editline.c \
 	sysunix.c
 
-OBJS = \
-	complete.o \
-	editline.o \
-	sysunix.o
+OBJS = $(SRCS:.c=.o)
 
 WineRelocatableTarget($(TOP)/$(MODULE),,$(OBJS))
 DependTarget()
-CleanTarget()
 
 includes::
 
diff --git a/etc/Imakefile b/etc/Imakefile
index b398809..a81b367 100644
--- a/etc/Imakefile
+++ b/etc/Imakefile
@@ -6,6 +6,4 @@
 
 depend::
 
-CleanTarget()
-
 includes::
diff --git a/if1632/Imakefile b/if1632/Imakefile
index 4f25af0..4c15d44 100644
--- a/if1632/Imakefile
+++ b/if1632/Imakefile
@@ -62,15 +62,16 @@
 
 WineRelocatableTarget($(TOP)/$(MODULE),,$(OBJS))
 DependTarget()
-CleanTarget()
 
 pop.h: $(TOP)/tools/build
 	$(TOP)/tools/build -p
 
+call.s: call.S pop.h
+
 includes::
+	touch pop.h
 
 install::
 
 clean::
 	$(RM) dll* dtb* pop.h call.s
-	touch pop.h
diff --git a/if1632/callback.c b/if1632/callback.c
index 3d9fefc..3d69c34 100644
--- a/if1632/callback.c
+++ b/if1632/callback.c
@@ -26,6 +26,12 @@
     unsigned char thunk[10];
 };
 
+static __inline__ int Is16bitAddress(void *address)
+{
+    return ((unsigned int) address 
+	    >= (((FIRST_SELECTOR << 3) | 0x0007) << 16));
+}
+
 /**********************************************************************
  *					PushOn16
  */
@@ -140,9 +146,24 @@
 }
 
 /**********************************************************************
+ *	    GetCodeHandle    (KERNEL.93)
+ */
+HANDLE GetCodeHandle( FARPROC proc )
+{
+    struct thunk_s *tp = (struct thunk_s *)proc;
+
+    /* Return the code segment containing 'proc'. */
+    /* Not sure if this is really correct (shouldn't matter that much). */
+    printf( "STUB: GetCodeHandle(%p) returning %x\n",
+            tp->thunk[8] + (tp->thunk[9] << 8) );
+    return tp->thunk[8] + (tp->thunk[9] << 8);
+}
+
+
+/**********************************************************************
  *					CallWindowProc    (USER.122)
  */
-LONG CallWindowProc( FARPROC func, HWND hwnd, WORD message,
+LONG CallWindowProc( WNDPROC func, HWND hwnd, WORD message,
 		     WORD wParam, LONG lParam )
 {
     SpyMessage(hwnd, message, wParam, lParam);
diff --git a/if1632/gdi.spec b/if1632/gdi.spec
index a4665f8..2eee652 100644
--- a/if1632/gdi.spec
+++ b/if1632/gdi.spec
@@ -5,15 +5,15 @@
 length	490
 
 1   pascal SetBkColor(word long) SetBkColor(1 2)
-2   pascal SetBkMode(word word) SetBkMode(1 2)
-3   pascal SetMapMode(word word) SetMapMode(1 2)
-4   pascal SetROP2(word word) SetROP2(1 2)
-5   pascal SetRelAbs(word word) SetRelAbs(1 2)
-6   pascal SetPolyFillMode(word word) SetPolyFillMode(1 2)
-7   pascal SetStretchBltMode(word word) SetStretchBltMode(1 2)
-8   pascal SetTextCharacterExtra(word s_word) SetTextCharacterExtra(1 2)
+2   pascal16 SetBkMode(word word) SetBkMode(1 2)
+3   pascal16 SetMapMode(word word) SetMapMode(1 2)
+4   pascal16 SetROP2(word word) SetROP2(1 2)
+5   pascal16 SetRelAbs(word word) SetRelAbs(1 2)
+6   pascal16 SetPolyFillMode(word word) SetPolyFillMode(1 2)
+7   pascal16 SetStretchBltMode(word word) SetStretchBltMode(1 2)
+8   pascal16 SetTextCharacterExtra(word s_word) SetTextCharacterExtra(1 2)
 9   pascal SetTextColor(word long) SetTextColor(1 2)
-10  pascal SetTextJustification(word s_word s_word) SetTextJustification(1 2 3)
+10  pascal16 SetTextJustification(word s_word s_word) SetTextJustification(1 2 3)
 11  pascal SetWindowOrg(word s_word s_word) SetWindowOrg(1 2 3)
 12  pascal SetWindowExt(word s_word s_word) SetWindowExt(1 2 3)
 13  pascal SetViewportOrg(word s_word s_word) SetViewportOrg(1 2 3)
@@ -24,146 +24,146 @@
 17  pascal OffsetViewportOrg(word s_word s_word) OffsetViewportOrg(1 2 3)
 18  pascal ScaleViewportExt(word s_word s_word s_word s_word)
 	   ScaleViewportExt(1 2 3 4 5)
-19  pascal LineTo(word s_word s_word) LineTo(1 2 3)
+19  pascal16 LineTo(word s_word s_word) LineTo(1 2 3)
 20  pascal MoveTo(word s_word s_word) MoveTo(1 2 3)
-21  pascal ExcludeClipRect(word s_word s_word s_word s_word)
-	   ExcludeClipRect(1 2 3 4 5)
-22  pascal IntersectClipRect(word s_word s_word s_word s_word)
-	   IntersectClipRect(1 2 3 4 5)
-23  pascal Arc(word s_word s_word s_word s_word s_word s_word s_word s_word)
-	   Arc(1 2 3 4 5 6 7 8 9)
-24  pascal Ellipse(word s_word s_word s_word s_word) Ellipse(1 2 3 4 5)
-25  pascal FloodFill(word word word long) FloodFill(1 2 3 4)
-26  pascal Pie(word s_word s_word s_word s_word s_word s_word s_word s_word)
-	   Pie(1 2 3 4 5 6 7 8 9)
-27  pascal Rectangle(word s_word s_word s_word s_word) Rectangle(1 2 3 4 5)
-28  pascal RoundRect(word s_word s_word s_word s_word s_word s_word)
-	   RoundRect(1 2 3 4 5 6 7)
-29  pascal PatBlt(word s_word s_word s_word s_word long) PatBlt(1 2 3 4 5 6)
-30  pascal SaveDC(word) SaveDC(1)
+21  pascal16 ExcludeClipRect(word s_word s_word s_word s_word)
+	     ExcludeClipRect(1 2 3 4 5)
+22  pascal16 IntersectClipRect(word s_word s_word s_word s_word)
+	     IntersectClipRect(1 2 3 4 5)
+23  pascal16 Arc(word s_word s_word s_word s_word s_word s_word s_word s_word)
+	     Arc(1 2 3 4 5 6 7 8 9)
+24  pascal16 Ellipse(word s_word s_word s_word s_word) Ellipse(1 2 3 4 5)
+25  pascal16 FloodFill(word s_word s_word long) FloodFill(1 2 3 4)
+26  pascal16 Pie(word s_word s_word s_word s_word s_word s_word s_word s_word)
+	     Pie(1 2 3 4 5 6 7 8 9)
+27  pascal16 Rectangle(word s_word s_word s_word s_word) Rectangle(1 2 3 4 5)
+28  pascal16 RoundRect(word s_word s_word s_word s_word s_word s_word)
+	     RoundRect(1 2 3 4 5 6 7)
+29  pascal16 PatBlt(word s_word s_word s_word s_word long) PatBlt(1 2 3 4 5 6)
+30  pascal16 SaveDC(word) SaveDC(1)
 31  pascal SetPixel(word s_word s_word long) SetPixel(1 2 3 4)
-32  pascal OffsetClipRgn(word s_word s_word) OffsetClipRgn(1 2 3)
-33  pascal TextOut(word s_word s_word ptr word) TextOut(1 2 3 4 5)
-34  pascal BitBlt( word s_word s_word s_word s_word word s_word s_word long)
-	   BitBlt(1 2 3 4 5 6 7 8 9)
-35  pascal StretchBlt( word s_word s_word s_word s_word word s_word s_word s_word s_word long)
-           StretchBlt(1 2 3 4 5 6 7 8 9 10 11)
-36  pascal Polygon (word ptr word) Polygon (1 2 3)
-37  pascal Polyline (word ptr word) Polyline (1 2 3)
+32  pascal16 OffsetClipRgn(word s_word s_word) OffsetClipRgn(1 2 3)
+33  pascal16 TextOut(word s_word s_word ptr word) TextOut(1 2 3 4 5)
+34  pascal16 BitBlt( word s_word s_word s_word s_word word s_word s_word long)
+	     BitBlt(1 2 3 4 5 6 7 8 9)
+35  pascal16 StretchBlt( word s_word s_word s_word s_word word s_word s_word s_word s_word long)
+             StretchBlt(1 2 3 4 5 6 7 8 9 10 11)
+36  pascal16 Polygon (word ptr word) Polygon (1 2 3)
+37  pascal16 Polyline (word ptr word) Polyline (1 2 3)
 38  pascal Escape(word word word ptr ptr) Escape(1 2 3 4 5)
-39  pascal RestoreDC(word s_word) RestoreDC(1 2)
-40  pascal FillRgn(word word word) FillRgn(1 2 3)
+39  pascal16 RestoreDC(word s_word) RestoreDC(1 2)
+40  pascal16 FillRgn(word word word) FillRgn(1 2 3)
 #41  pascal FrameRgn
-42  pascal InvertRgn(word word) InvertRgn(1 2)
-43  pascal PaintRgn(word word) PaintRgn(1 2)
-44  pascal SelectClipRgn(word word) SelectClipRgn(1 2)
-45  pascal SelectObject(word word) SelectObject(1 2)
+42  pascal16 InvertRgn(word word) InvertRgn(1 2)
+43  pascal16 PaintRgn(word word) PaintRgn(1 2)
+44  pascal16 SelectClipRgn(word word) SelectClipRgn(1 2)
+45  pascal16 SelectObject(word word) SelectObject(1 2)
 #46  pascal __GP?
-47  pascal CombineRgn(word word word word) CombineRgn(1 2 3 4)
-48  pascal CreateBitmap(word word word word ptr) CreateBitmap(1 2 3 4 5)
-49  pascal CreateBitmapIndirect(ptr) CreateBitmapIndirect(1)
-50  pascal CreateBrushIndirect(ptr) CreateBrushIndirect(1)
-51  pascal CreateCompatibleBitmap(word word word) CreateCompatibleBitmap(1 2 3)
-52  pascal CreateCompatibleDC(word) CreateCompatibleDC(1)
-53  pascal CreateDC(ptr ptr ptr ptr) CreateDC(1 2 3 4)
-54  pascal CreateEllipticRgn(s_word s_word s_word s_word)
-	   CreateEllipticRgn(1 2 3 4)
-55  pascal CreateEllipticRgnIndirect(ptr) CreateEllipticRgnIndirect(1)
-56  pascal CreateFont(s_word s_word s_word s_word s_word word word word 
-	              word word word word word ptr)
-	   CreateFont(1 2 3 4 5 6 7 8 9 10 11 12 13 14)
-57  pascal CreateFontIndirect(ptr) CreateFontIndirect(1)
-58  pascal CreateHatchBrush(word long) CreateHatchBrush(1 2)
-60  pascal CreatePatternBrush(word) CreatePatternBrush(1)
-61  pascal CreatePen(s_word s_word long) CreatePen(1 2 3)
-62  pascal CreatePenIndirect(ptr) CreatePenIndirect(1)
-63  pascal CreatePolygonRgn(ptr word word) CreatePolygonRgn(1 2 3)
-64  pascal CreateRectRgn(s_word s_word s_word s_word) CreateRectRgn(1 2 3 4)
-65  pascal CreateRectRgnIndirect(ptr) CreateRectRgnIndirect(1)
-66  pascal CreateSolidBrush(long) CreateSolidBrush(1)
-67  pascal DPtoLP(word ptr s_word) DPtoLP(1 2 3)
-68  pascal DeleteDC(word) DeleteDC(1)
-69  pascal DeleteObject(word) DeleteObject(1)
-70  pascal EnumFonts(word ptr ptr ptr) EnumFonts(1 2 3 4)
-71  pascal EnumObjects(word word ptr ptr) EnumObjects(1 2 3 4)
-72  pascal EqualRgn(word word) EqualRgn(1 2)
-73  pascal ExcludeVisRect(word s_word s_word s_word s_word)
-	   ExcludeVisRect(1 2 3 4 5)
+47  pascal16 CombineRgn(word word word word) CombineRgn(1 2 3 4)
+48  pascal16 CreateBitmap(word word word word ptr) CreateBitmap(1 2 3 4 5)
+49  pascal16 CreateBitmapIndirect(ptr) CreateBitmapIndirect(1)
+50  pascal16 CreateBrushIndirect(ptr) CreateBrushIndirect(1)
+51  pascal16 CreateCompatibleBitmap(word word word) CreateCompatibleBitmap(1 2 3)
+52  pascal16 CreateCompatibleDC(word) CreateCompatibleDC(1)
+53  pascal16 CreateDC(ptr ptr ptr ptr) CreateDC(1 2 3 4)
+54  pascal16 CreateEllipticRgn(s_word s_word s_word s_word)
+	     CreateEllipticRgn(1 2 3 4)
+55  pascal16 CreateEllipticRgnIndirect(ptr) CreateEllipticRgnIndirect(1)
+56  pascal16 CreateFont(s_word s_word s_word s_word s_word word word word 
+	                word word word word word ptr)
+	     CreateFont(1 2 3 4 5 6 7 8 9 10 11 12 13 14)
+57  pascal16 CreateFontIndirect(ptr) CreateFontIndirect(1)
+58  pascal16 CreateHatchBrush(word long) CreateHatchBrush(1 2)
+60  pascal16 CreatePatternBrush(word) CreatePatternBrush(1)
+61  pascal16 CreatePen(s_word s_word long) CreatePen(1 2 3)
+62  pascal16 CreatePenIndirect(ptr) CreatePenIndirect(1)
+63  pascal16 CreatePolygonRgn(ptr word word) CreatePolygonRgn(1 2 3)
+64  pascal16 CreateRectRgn(s_word s_word s_word s_word) CreateRectRgn(1 2 3 4)
+65  pascal16 CreateRectRgnIndirect(ptr) CreateRectRgnIndirect(1)
+66  pascal16 CreateSolidBrush(long) CreateSolidBrush(1)
+67  pascal16 DPtoLP(word ptr s_word) DPtoLP(1 2 3)
+68  pascal16 DeleteDC(word) DeleteDC(1)
+69  pascal16 DeleteObject(word) DeleteObject(1)
+70  pascal16 EnumFonts(word ptr ptr ptr) EnumFonts(1 2 3 4)
+71  pascal16 EnumObjects(word word ptr ptr) EnumObjects(1 2 3 4)
+72  pascal16 EqualRgn(word word) EqualRgn(1 2)
+73  pascal16 ExcludeVisRect(word s_word s_word s_word s_word)
+	     ExcludeVisRect(1 2 3 4 5)
 74  pascal GetBitmapBits(word long ptr) GetBitmapBits(1 2 3)
 75  pascal GetBkColor(word) GetBkColor(1)
-76  pascal GetBkMode(word) GetBkMode(1)
-77  pascal GetClipBox(word ptr) GetClipBox(1 2)
+76  pascal16 GetBkMode(word) GetBkMode(1)
+77  pascal16 GetClipBox(word ptr) GetClipBox(1 2)
 78  pascal GetCurrentPosition(word) GetCurrentPosition(1)
 79  pascal GetDCOrg(word) GetDCOrg(1)
-80  pascal GetDeviceCaps(word s_word) GetDeviceCaps(1 2)
-81  pascal GetMapMode(word) GetMapMode(1)
-82  pascal GetObject(word word ptr) GetObject(1 2 3)
+80  pascal16 GetDeviceCaps(word s_word) GetDeviceCaps(1 2)
+81  pascal16 GetMapMode(word) GetMapMode(1)
+82  pascal16 GetObject(word word ptr) GetObject(1 2 3)
 83  pascal GetPixel(word s_word s_word) GetPixel(1 2 3)
-84  pascal GetPolyFillMode(word) GetPolyFillMode(1)
-85  pascal GetROP2(word) GetROP2(1)
-86  pascal GetRelAbs(word) GetRelAbs(1)
-87  pascal GetStockObject(word) GetStockObject(1)
-88  pascal GetStretchBltMode(word) GetStretchBltMode(1)
-89  pascal GetTextCharacterExtra(word) GetTextCharacterExtra(1)
+84  pascal16 GetPolyFillMode(word) GetPolyFillMode(1)
+85  pascal16 GetROP2(word) GetROP2(1)
+86  pascal16 GetRelAbs(word) GetRelAbs(1)
+87  pascal16 GetStockObject(word) GetStockObject(1)
+88  pascal16 GetStretchBltMode(word) GetStretchBltMode(1)
+89  pascal16 GetTextCharacterExtra(word) GetTextCharacterExtra(1)
 90  pascal GetTextColor(word) GetTextColor(1)
 91  pascal GetTextExtent(word ptr s_word) GetTextExtent(1 2 3)
-#92  pascal GetTextFace
-93  pascal GetTextMetrics(word ptr) GetTextMetrics(1 2)
+92  pascal16 GetTextFace(word s_word ptr) GetTextFace(1 2 3)
+93  pascal16 GetTextMetrics(word ptr) GetTextMetrics(1 2)
 94  pascal GetViewportExt(word) GetViewportExt(1)
 95  pascal GetViewportOrg(word) GetViewportOrg(1)
 96  pascal GetWindowExt(word) GetWindowExt(1)
 97  pascal GetWindowOrg(word) GetWindowOrg(1)
-98  pascal IntersectVisRect(word s_word s_word s_word s_word)
-	   IntersectVisRect(1 2 3 4 5)
-99  pascal LPtoDP(word ptr s_word) LPtoDP(1 2 3)
-100 pascal LineDDA(s_word s_word s_word s_word ptr long)
-	   LineDDA(1 2 3 4 5 6)
-101 pascal OffsetRgn(word s_word s_word) OffsetRgn(1 2 3)
-102 pascal OffsetVisRgn(word s_word s_word) OffsetVisRgn(1 2 3)
-103 pascal PtVisible(word s_word s_word) PtVisible(1 2 3)
-104 pascal RectVisibleOld(word ptr) RectVisible(1 2)
-105 pascal SelectVisRgn(word word) SelectVisRgn(1 2)
+98  pascal16 IntersectVisRect(word s_word s_word s_word s_word)
+	     IntersectVisRect(1 2 3 4 5)
+99  pascal16 LPtoDP(word ptr s_word) LPtoDP(1 2 3)
+100 pascal16 LineDDA(s_word s_word s_word s_word ptr long)
+	     LineDDA(1 2 3 4 5 6)
+101 pascal16 OffsetRgn(word s_word s_word) OffsetRgn(1 2 3)
+102 pascal16 OffsetVisRgn(word s_word s_word) OffsetVisRgn(1 2 3)
+103 pascal16 PtVisible(word s_word s_word) PtVisible(1 2 3)
+104 pascal16 RectVisibleOld(word ptr) RectVisible(1 2)
+105 pascal16 SelectVisRgn(word word) SelectVisRgn(1 2)
 106 pascal SetBitmapBits(word long ptr) SetBitmapBits(1 2 3)
 117 pascal SetDCOrg(word s_word s_word) SetDCOrg(1 2 3)
 #121 pascal Death
 #122 pascal ReSurRection
-123 pascal PlayMetaFile(word word) PlayMetaFile(1 2)
+123 pascal16 PlayMetaFile(word word) PlayMetaFile(1 2)
 #124 pascal GetMetaFile
-125 pascal CreateMetaFile(ptr) CreateMetaFile(1)
-126 pascal CloseMetaFile(word) CloseMetaFile(1)
-127 pascal DeleteMetaFile(word) DeleteMetaFile(1)
+125 pascal16 CreateMetaFile(ptr) CreateMetaFile(1)
+126 pascal16 CloseMetaFile(word) CloseMetaFile(1)
+127 pascal16 DeleteMetaFile(word) DeleteMetaFile(1)
 128 pascal MulDiv(s_word s_word s_word) MulDiv(1 2 3)
-129 pascal SaveVisRgn(word) SaveVisRgn(1)
-130 pascal RestoreVisRgn(word) RestoreVisRgn(1)
-131 pascal InquireVisRgn(word) InquireVisRgn(1)
-132 pascal SetEnvironment(ptr ptr word) SetEnvironment(1 2 3)
-133 pascal GetEnvironment(ptr ptr word) GetEnvironment(1 2 3)
-134 pascal GetRgnBox(word ptr) GetRgnBox(1 2)
+129 pascal16 SaveVisRgn(word) SaveVisRgn(1)
+130 pascal16 RestoreVisRgn(word) RestoreVisRgn(1)
+131 pascal16 InquireVisRgn(word) InquireVisRgn(1)
+132 pascal16 SetEnvironment(ptr ptr word) SetEnvironment(1 2 3)
+133 pascal16 GetEnvironment(ptr ptr word) GetEnvironment(1 2 3)
+134 pascal16 GetRgnBox(word ptr) GetRgnBox(1 2)
 #135 pascal ScanLr
 #136 pascal RemoveFontResource
 148 pascal SetBrushOrg(word s_word s_word) SetBrushOrg(1 2 3)
 149 pascal GetBrushOrg(word) GetBrushOrg(1)
-150 pascal UnrealizeObject(word) UnrealizeObject(1)
+150 pascal16 UnrealizeObject(word) UnrealizeObject(1)
 #151 pascal CopyMetaFile
-153 pascal CreateIC(ptr ptr ptr ptr) CreateIC(1 2 3 4)
+153 pascal16 CreateIC(ptr ptr ptr ptr) CreateIC(1 2 3 4)
 154 pascal GetNearestColor(word long) GetNearestColor(1 2)
 #155 pascal QueryAbort
-156 pascal CreateDiscardableBitmap(word word word) 
-	   CreateDiscardableBitmap(1 2 3)
+156 pascal16 CreateDiscardableBitmap(word word word) 
+	     CreateDiscardableBitmap(1 2 3)
 #159 pascal GetMetaFileBits
 #160 pascal SetMetaFileBits
-161 pascal PtInRegion(word s_word s_word) PtInRegion(1 2 3)
+161 pascal16 PtInRegion(word s_word s_word) PtInRegion(1 2 3)
 162 pascal GetBitmapDimension(word) GetBitmapDimension(1)
 163 pascal SetBitmapDimension(word s_word s_word) SetBitmapDimension(1 2 3)
 #169 pascal IsDCDirty
 #170 pascal SetDCStatus
-172 pascal SetRectRgn(word s_word s_word s_word s_word) SetRectRgn(1 2 3 4 5)
-173 pascal GetClipRgn(word) GetClipRgn(1)
+172 pascal16 SetRectRgn(word s_word s_word s_word s_word) SetRectRgn(1 2 3 4 5)
+173 pascal16 GetClipRgn(word) GetClipRgn(1)
 #175 pascal EnumMetaFile
-176 pascal PlayMetaFileRecord(word ptr ptr word) PlayMetaFileRecord(1 2 3 4)
-179 pascal GetDCState(word) GetDCState(1)
-180 pascal SetDCState(word word) SetDCState(1 2)
-181 pascal RectInRegionOld(word ptr) RectInRegion(1 2)
+176 pascal16 PlayMetaFileRecord(word ptr ptr word) PlayMetaFileRecord(1 2 3 4)
+179 pascal16 GetDCState(word) GetDCState(1)
+180 pascal16 SetDCState(word word) SetDCState(1 2)
+181 pascal16 RectInRegionOld(word ptr) RectInRegion(1 2)
 #190 pascal SetDCHook
 #191 pascal GetDCHook
 #192 pascal SetHookFlags
@@ -203,7 +203,7 @@
 #246 pascal STARTSPOOLPAGE
 #247 pascal ENDSPOOLPAGE
 #248 pascal QUERYJOB
-250 pascal Copy(ptr ptr word) Copy(1 2 3)
+250 pascal16 Copy(ptr ptr word) Copy(1 2 3)
 #253 pascal DeleteSpoolPage
 #254 pascal SpoolFile
 #300 pascal ENGINEENUMERATEFONT
@@ -221,31 +221,32 @@
 #312 pascal CONVERTOUTLINEFONTFILE
 #313 pascal GETRASTERIZERCAPS
 #314 pascal ENGINEEXTTEXTOUT
-330 pascal EnumFontFamilies(word ptr ptr ptr) EnumFontFamilies(1 2 3 4)
+330 pascal16 EnumFontFamilies(word ptr ptr ptr) EnumFontFamilies(1 2 3 4)
 #332 pascal GETKERNINGPAIRS
-345 pascal GetTextAlign(word) GetTextAlign(1)
-346 pascal SetTextAlign(word word) SetTextAlign(1 2)
-348 pascal Chord(word s_word s_word s_word s_word s_word s_word s_word s_word)
-	   Chord(1 2 3 4 5 6 7 8 9)
+345 pascal16 GetTextAlign(word) GetTextAlign(1)
+346 pascal16 SetTextAlign(word word) SetTextAlign(1 2)
+348 pascal16 Chord(word s_word s_word s_word s_word s_word s_word s_word s_word)
+	     Chord(1 2 3 4 5 6 7 8 9)
 349 pascal SetMapperFlags(word word) SetMapperFlags(1 2)
-350 pascal GetCharWidth(word word word ptr) GetCharWidth(1 2 3 4)
-351 pascal ExtTextOut(word s_word s_word word ptr ptr s_word ptr) 
-		ExtTextOut(1 2 3 4 5 6 7 8)
+350 pascal16 GetCharWidth(word word word ptr) GetCharWidth(1 2 3 4)
+351 pascal16 ExtTextOut(word s_word s_word word ptr ptr s_word ptr) 
+             ExtTextOut(1 2 3 4 5 6 7 8)
 #352 pascal GETPHYSICALFONTHANDLE
 #353 pascal GETASPECTRATIOFILTER
 #354 pascal SHRINKGDIHEAP
-360 pascal CreatePalette(ptr) CreatePalette(1)
-361 pascal GDISelectPalette(word word) GDISelectPalette(1 2)
-362 pascal GDIRealizePalette(word) GDIRealizePalette(1)
-363 pascal GetPaletteEntries(word word word ptr) GetPaletteEntries(1 2 3 4)
-364 pascal SetPaletteEntries(word word word ptr) SetPaletteEntries(1 2 3 4)
-365 pascal RealizeDefaultPalette(word) RealizeDefaultPalette(1)
+360 pascal16 CreatePalette(ptr) CreatePalette(1)
+361 pascal16 GDISelectPalette(word word) GDISelectPalette(1 2)
+362 pascal16 GDIRealizePalette(word) GDIRealizePalette(1)
+363 pascal16 GetPaletteEntries(word word word ptr) GetPaletteEntries(1 2 3 4)
+364 pascal16 SetPaletteEntries(word word word ptr) SetPaletteEntries(1 2 3 4)
+365 pascal16 RealizeDefaultPalette(word) RealizeDefaultPalette(1)
 #366 pascal UPDATECOLORS
 #367 pascal ANIMATEPALETTE
 #368 pascal RESIZEPALETTE
-370 pascal GetNearestPaletteIndex(word long) GetNearestPaletteIndex(1 2)
-375 pascal GetSystemPaletteEntries(word word word ptr)
-	   GetSystemPaletteEntries(1 2 3 4)
+370 pascal16 GetNearestPaletteIndex(word long) GetNearestPaletteIndex(1 2)
+372 pascal16 ExtFloodFill(word s_word s_word long word) ExtFloodFill(1 2 3 4)
+375 pascal16 GetSystemPaletteEntries(word word word ptr)
+	     GetSystemPaletteEntries(1 2 3 4)
 #376 pascal RESETDC
 #377 pascal STARTDOC
 #378 pascal ENDDOC
@@ -260,51 +261,53 @@
 #407 pascal CREATEUSERBITMAP
 #409 pascal CREATEUSERDISCARDABLEBITMAP
 #410 pascal ISVALIDMETAFILE
-411 pascal GetCurLogFont(word) GetCurLogFont(1)
+411 pascal16 GetCurLogFont(word) GetCurLogFont(1)
 #412 pascal ISDCCURRENTPALETTE
 #439 pascal STRETCHDIBITS
-440 pascal SetDIBits(word word word word ptr ptr word) SetDIBits(1 2 3 4 5 6 7)
-441 pascal GetDIBits(word word word word ptr ptr word) GetDIBits(1 2 3 4 5 6 7)
-442 pascal CreateDIBitmap(word ptr long ptr ptr word)
-	   CreateDIBitmap(1 2 3 4 5 6)
-443 pascal SetDIBitsToDevice(word s_word s_word word word word word word word ptr ptr word)
-	   SetDIBitsToDevice(1 2 3 4 5 6 7 8 9 10 11 12)
-444 pascal CreateRoundRectRgn(s_word s_word s_word s_word s_word s_word)
-	   CreateRoundRectRgn(1 2 3 4 5 6)
-445 pascal CreateDIBPatternBrush(word word) CreateDIBPatternBrush(1 2)
+440 pascal16 SetDIBits(word word word word ptr ptr word) SetDIBits(1 2 3 4 5 6 7)
+441 pascal16 GetDIBits(word word word word ptr ptr word) GetDIBits(1 2 3 4 5 6 7)
+442 pascal16 CreateDIBitmap(word ptr long ptr ptr word)
+	     CreateDIBitmap(1 2 3 4 5 6)
+443 pascal16 SetDIBitsToDevice(word s_word s_word word word word word word
+                               word ptr ptr word)
+	     SetDIBitsToDevice(1 2 3 4 5 6 7 8 9 10 11 12)
+444 pascal16 CreateRoundRectRgn(s_word s_word s_word s_word s_word s_word)
+	     CreateRoundRectRgn(1 2 3 4 5 6)
+445 pascal16 CreateDIBPatternBrush(word word) CreateDIBPatternBrush(1 2)
 #449 pascal DEVICECOLORMATCH
-450 pascal PolyPolygon(word ptr ptr word) PolyPolygon(1 2 3 4)
-451 pascal CreatePolyPolygonRgn(ptr ptr word word)
-	   CreatePolyPolygonRgn(1 2 3 4)
+450 pascal16 PolyPolygon(word ptr ptr word) PolyPolygon(1 2 3 4)
+451 pascal16 CreatePolyPolygonRgn(ptr ptr word word)
+	     CreatePolyPolygonRgn(1 2 3 4)
 #452 pascal GDISEEGDIDO
 #460 pascal GDITASKTERMINATION
 461 return SetObjectOwner 4 0
-462 pascal IsGDIObject(word) IsGDIObject(1)
+462 pascal16 IsGDIObject(word) IsGDIObject(1)
 #463 pascal MAKEOBJECTPRIVATE
 #464 pascal FIXUPBOGUSPUBLISHERMETAFILE
-465 pascal RectVisible(word ptr) RectVisible(1 2)
-466 pascal RectInRegion(word ptr) RectInRegion(1 2)
+465 pascal16 RectVisible(word ptr) RectVisible(1 2)
+466 pascal16 RectInRegion(word ptr) RectInRegion(1 2)
 #467 pascal UNICODETOANSI
-468 pascal GetBitmapDimensionEx(word ptr) GetBitmapDimensionEx(1 2)
-469 pascal GetBrushOrgEx(word ptr) GetBrushOrgEx(1 2)
-470 pascal GetCurrentPositionEx(word ptr) GetCurrentPositionEx(1 2)
-471 pascal GetTextExtentPoint(word ptr s_word ptr) GetTextExtentPoint(1 2 3 4)
-472 pascal GetViewportExtEx(word ptr) GetViewportExtEx(1 2)
-473 pascal GetViewportOrgEx(word ptr) GetViewportOrgEx(1 2)
-474 pascal GetWindowExtEx(word ptr) GetWindowExtEx(1 2)
-475 pascal GetWindowOrgEx(word ptr) GetWindowOrgEx(1 2)
-476 pascal OffsetViewportOrgEx(word s_word s_word ptr)
-	   OffsetViewportOrgEx(1 2 3 4)
-477 pascal OffsetWindowOrgEx(word s_word s_word ptr) OffsetWindowOrgEx(1 2 3 4)
-478 pascal SetBitmapDimensionEx(word s_word s_word ptr)
-	   SetBitmapDimensionEx(1 2 3 4)
-479 pascal SetViewportExtEx(word s_word s_word ptr) SetViewportExtEx(1 2 3 4)
-480 pascal SetViewportOrgEx(word s_word s_word ptr) SetViewportOrgEx(1 2 3 4)
-481 pascal SetWindowExtEx(word s_word s_word ptr) SetWindowExtEx(1 2 3 4)
-482 pascal SetWindowOrgEx(word s_word s_word ptr) SetWindowOrgEx(1 2 3 4)
-483 pascal MoveToEx(word s_word s_word ptr) MoveToEx(1 2 3 4)
-484 pascal ScaleViewportExtEx(word s_word s_word s_word s_word ptr)
-	   ScaleViewportExtEx(1 2 3 4 5 6)
-485 pascal ScaleWindowExtEx(word s_word s_word s_word s_word ptr)
-	   ScaleWindowExtEx(1 2 3 4 5 6)
+468 pascal16 GetBitmapDimensionEx(word ptr) GetBitmapDimensionEx(1 2)
+469 pascal16 GetBrushOrgEx(word ptr) GetBrushOrgEx(1 2)
+470 pascal16 GetCurrentPositionEx(word ptr) GetCurrentPositionEx(1 2)
+471 pascal16 GetTextExtentPoint(word ptr s_word ptr) GetTextExtentPoint(1 2 3 4)
+472 pascal16 GetViewportExtEx(word ptr) GetViewportExtEx(1 2)
+473 pascal16 GetViewportOrgEx(word ptr) GetViewportOrgEx(1 2)
+474 pascal16 GetWindowExtEx(word ptr) GetWindowExtEx(1 2)
+475 pascal16 GetWindowOrgEx(word ptr) GetWindowOrgEx(1 2)
+476 pascal16 OffsetViewportOrgEx(word s_word s_word ptr)
+	     OffsetViewportOrgEx(1 2 3 4)
+477 pascal16 OffsetWindowOrgEx(word s_word s_word ptr)
+             OffsetWindowOrgEx(1 2 3 4)
+478 pascal16 SetBitmapDimensionEx(word s_word s_word ptr)
+	     SetBitmapDimensionEx(1 2 3 4)
+479 pascal16 SetViewportExtEx(word s_word s_word ptr) SetViewportExtEx(1 2 3 4)
+480 pascal16 SetViewportOrgEx(word s_word s_word ptr) SetViewportOrgEx(1 2 3 4)
+481 pascal16 SetWindowExtEx(word s_word s_word ptr) SetWindowExtEx(1 2 3 4)
+482 pascal16 SetWindowOrgEx(word s_word s_word ptr) SetWindowOrgEx(1 2 3 4)
+483 pascal16 MoveToEx(word s_word s_word ptr) MoveToEx(1 2 3 4)
+484 pascal16 ScaleViewportExtEx(word s_word s_word s_word s_word ptr)
+	     ScaleViewportExtEx(1 2 3 4 5 6)
+485 pascal16 ScaleWindowExtEx(word s_word s_word s_word s_word ptr)
+	     ScaleWindowExtEx(1 2 3 4 5 6)
 #486 pascal GETASPECTRATIOFILEREX
diff --git a/if1632/kernel.spec b/if1632/kernel.spec
index 663e14e..f3930a5 100644
--- a/if1632/kernel.spec
+++ b/if1632/kernel.spec
@@ -93,7 +93,7 @@
 		      word word word word word) 
 	     KERNEL_InitTask()
 92  pascal16 GetTempDrive(byte) GetTempDrive(1)
-#93 pascal16 GETCODEHANDLE
+93 pascal16 GetCodeHandle(ptr) GetCodeHandle(1)
 #94 DEFINEHANDLETABLE
 95  pascal16 LoadLibrary(ptr) LoadLibrary(1)
 96  pascal16 FreeLibrary(word) FreeLibrary(1)
@@ -108,7 +108,7 @@
 #103 NETBIOSCALL
 #104 GETCODEINFO
 #105 GETEXEVERSION
-#106 SETSWAPAREASIZE
+106 pascal SetSwapAreaSize(word) SetSwapAreaSize(1)
 107 pascal SetErrorMode(word) SetErrorMode(1)
 #108 SWITCHSTACKTO
 #109 SWITCHSTACKBACK
@@ -135,7 +135,7 @@
 	     GetPrivateProfileString(1 2 3 4 5 6)
 129 pascal16 WritePrivateProfileString(ptr ptr ptr ptr)
 	     WritePrivateProfileString(1 2 3 4)
-#130 FILECBR
+130 pascal FileCDR(ptr) FileCDR(1)
 131 pascal GetDOSEnvironment() GetDOSEnvironment()
 132 pascal GetWinFlags() GetWinFlags()
 #133 GETEXEPTR
diff --git a/if1632/relay.c b/if1632/relay.c
index 3122d8b..9bf9682 100644
--- a/if1632/relay.c
+++ b/if1632/relay.c
@@ -110,12 +110,12 @@
 	unsigned short *stack_p;
 	
 	ret_addr = (unsigned int *) ((char *) seg_off + 0x14);
-	printf("Calling %s (%s.%d), 16-bit stack at %04x:%04x, ",
+	printf("Call %s (%s.%d), stack=%04x:%04x, ",
 	       dll_p->export_name,
 	       dll_builtin_table[dll_id].dll_name, ordinal,
 	       seg_off >> 16, seg_off & 0xffff);
-	printf("return to %08x\n", *ret_addr);
-	printf("  ESP %08x, EBP %08x, SS %04x\n", 
+	printf("ret=%08x", *ret_addr);
+	printf("  ESP=%08x, EBP=%08x, SS=%04x\n", 
 	       IF1632_Saved16_esp, IF1632_Saved16_ebp,
 	       IF1632_Saved16_ss);
 
diff --git a/if1632/user.spec b/if1632/user.spec
index 6798d12..673bbc3 100644
--- a/if1632/user.spec
+++ b/if1632/user.spec
@@ -270,9 +270,10 @@
 256 pascal GetDriverInfo(word ptr) GetDriverInfo(1 2)
 257 pascal GetNextDriver(word long) GetNextDriver(1 2)
 258 pascal MapWindowPoints(word word ptr word) MapWindowPoints(1 2 3 4)
-#259 BEGINDEFERWINDOWPOS
-#260 DEFERWINDOWPOS
-#261 ENDDEFERWINDOWPOS
+259 pascal16 BeginDeferWindowPos(s_word) BeginDeferWindowPos(1)
+260 pascal16 DeferWindowPos(word word word s_word s_word s_word s_word word)
+             DeferWindowPos(1 2 3 4 5 6 7 8)
+261 pascal16 EndDeferWindowPos(word) EndDeferWindowPos(1)
 262 pascal GetWindow(word word) GetWindow(1 2)
 263 pascal GetMenuItemCount(word) GetMenuItemCount(1)
 264 pascal GetMenuItemID(word word) GetMenuItemID(1 2)
diff --git a/include/Imakefile b/include/Imakefile
index 4e37987..4821756 100644
--- a/include/Imakefile
+++ b/include/Imakefile
@@ -33,6 +33,4 @@
 
 depend::
 
-CleanTarget()
-
 includes::
diff --git a/include/bitmap.h b/include/bitmap.h
index 9addd88..9a2acfa 100644
--- a/include/bitmap.h
+++ b/include/bitmap.h
@@ -10,9 +10,6 @@
 #include <X11/Xlib.h>
 #include "windows.h"
 
-  /* Handle of the bitmap selected by default in a memory DC */
-extern HBITMAP BITMAP_hbitmapMemDC;
-
   /* GCs used for B&W and color bitmap operations */
 extern GC BITMAP_monoGC, BITMAP_colorGC;
 
diff --git a/include/button.h b/include/button.h
new file mode 100644
index 0000000..b9b0565
--- /dev/null
+++ b/include/button.h
@@ -0,0 +1,33 @@
+/*
+ * Button-class extra info
+ *
+ * Copyright 1994 Alexandre Julliard
+ */
+
+#ifndef BUTTON_H
+#define BUTTON_H
+
+#include "windows.h"
+
+  /* Extra info for BUTTON windows */
+  /* Note: under MS-Windows, state is a BYTE and this structure is */
+  /* only 3 bytes long. I don't think there are programs out there */
+  /* broken enough to rely on this :-) */
+typedef struct
+{
+    WORD   state;   /* Current state */
+    HFONT  hFont;   /* Button font (or 0 for system font) */
+} BUTTONINFO;
+
+  /* Button state values */
+#define BUTTON_UNCHECKED       0x00
+#define BUTTON_CHECKED         0x01
+#define BUTTON_3STATE          0x02
+#define BUTTON_HIGHLIGHTED     0x04
+#define BUTTON_HASFOCUS        0x08
+
+#define BUTTON_STATE(hwnd)     ((WIN_FindWndPtr(hwnd))->wExtra[0])
+
+extern LONG ButtonWndProc( HWND hWnd, WORD uMsg, WORD wParam, LONG lParam );
+
+#endif  /* BUTTON_H */
diff --git a/include/debug.h b/include/debug.h
new file mode 100644
index 0000000..ab06923
--- /dev/null
+++ b/include/debug.h
@@ -0,0 +1,916 @@
+#include <stdio.h>
+
+#define stddeb stdout
+#define stdnimp stderr
+
+# /* Do not remove this line or change anything below this line */
+ 
+ 
+#ifdef DEBUG_NONE_EXT
+#undef DEBUG_ACCEL
+#undef DEBUG_BITMAP
+#undef DEBUG_CARET
+#undef DEBUG_CDAUDIO
+#undef DEBUG_CLASS
+#undef DEBUG_CLIPBOARD
+#undef DEBUG_CLIPPING
+#undef DEBUG_COMBO
+#undef DEBUG_COMM
+#undef DEBUG_CURSOR
+#undef DEBUG_DC
+#undef DEBUG_DIALOG
+#undef DEBUG_DLL
+#undef DEBUG_DOSFS
+#undef DEBUG_DRIVER
+#undef DEBUG_EDIT
+#undef DEBUG_ENUM
+#undef DEBUG_EVENT
+#undef DEBUG_EXEC
+#undef DEBUG_FILE
+#undef DEBUG_FIXUP
+#undef DEBUG_FONT
+#undef DEBUG_GDI
+#undef DEBUG_GRAPHICS
+#undef DEBUG_HEAP
+#undef DEBUG_ICON
+#undef DEBUG_INT
+#undef DEBUG_KEY
+#undef DEBUG_KEYBOARD
+#undef DEBUG_LDT
+#undef DEBUG_LISTBOX
+#undef DEBUG_MCIWAVE
+#undef DEBUG_MDI
+#undef DEBUG_MENU
+#undef DEBUG_MENUCALC
+#undef DEBUG_MESSAGE
+#undef DEBUG_METAFILE
+#undef DEBUG_MODULE
+#undef DEBUG_MSG
+#undef DEBUG_NONCLIENT
+#undef DEBUG_PALETTE
+#undef DEBUG_REGION
+#undef DEBUG_RESOURCE
+#undef DEBUG_SCROLL
+#undef DEBUG_SYSCOLOR
+#undef DEBUG_TEXT
+#undef DEBUG_TIMER
+#undef DEBUG_UTILITY
+#undef DEBUG_WIN
+#endif
+ 
+ 
+#ifdef DEBUG_ALL_EXT
+#define DEBUG_ACCEL
+#define DEBUG_BITMAP
+#define DEBUG_CARET
+#define DEBUG_CDAUDIO
+#define DEBUG_CLASS
+#define DEBUG_CLIPBOARD
+#define DEBUG_CLIPPING
+#define DEBUG_COMBO
+#define DEBUG_COMM
+#define DEBUG_CURSOR
+#define DEBUG_DC
+#define DEBUG_DIALOG
+#define DEBUG_DLL
+#define DEBUG_DOSFS
+#define DEBUG_DRIVER
+#define DEBUG_EDIT
+#define DEBUG_ENUM
+#define DEBUG_EVENT
+#define DEBUG_EXEC
+#define DEBUG_FILE
+#define DEBUG_FIXUP
+#define DEBUG_FONT
+#define DEBUG_GDI
+#define DEBUG_GRAPHICS
+#define DEBUG_HEAP
+#define DEBUG_ICON
+#define DEBUG_INT
+#define DEBUG_KEY
+#define DEBUG_KEYBOARD
+#define DEBUG_LDT
+#define DEBUG_LISTBOX
+#define DEBUG_MCIWAVE
+#define DEBUG_MDI
+#define DEBUG_MENU
+#define DEBUG_MENUCALC
+#define DEBUG_MESSAGE
+#define DEBUG_METAFILE
+#define DEBUG_MODULE
+#define DEBUG_MSG
+#define DEBUG_NONCLIENT
+#define DEBUG_PALETTE
+#define DEBUG_REGION
+#define DEBUG_RESOURCE
+#define DEBUG_SCROLL
+#define DEBUG_SYSCOLOR
+#define DEBUG_TEXT
+#define DEBUG_TIMER
+#define DEBUG_UTILITY
+#define DEBUG_WIN
+#endif
+ 
+ 
+#ifdef DEBUG_RUNTIME
+#ifdef DEBUG_DEFINE_VARIABLES
+short debug_msg_enabled[]={
+#ifdef DEBUG_ACCEL
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_BITMAP
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_CARET
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_CDAUDIO
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_CLASS
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_CLIPBOARD
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_CLIPPING
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_COMBO
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_COMM
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_CURSOR
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_DC
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_DIALOG
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_DLL
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_DOSFS
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_DRIVER
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_EDIT
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_ENUM
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_EVENT
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_EXEC
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_FILE
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_FIXUP
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_FONT
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_GDI
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_GRAPHICS
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_HEAP
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_ICON
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_INT
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_KEY
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_KEYBOARD
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_LDT
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_LISTBOX
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_MCIWAVE
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_MDI
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_MENU
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_MENUCALC
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_MESSAGE
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_METAFILE
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_MODULE
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_MSG
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_NONCLIENT
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_PALETTE
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_REGION
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_RESOURCE
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_SCROLL
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_SYSCOLOR
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_TEXT
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_TIMER
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_UTILITY
+1,
+#else
+0,
+#endif
+#ifdef DEBUG_WIN
+1,
+#else
+0,
+#endif
+0};
+#else
+extern short debug_msg_enabled[];
+#endif
+#endif
+ 
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_accel if(debug_msg_enabled[0]) fprintf
+#else
+#ifdef DEBUG_ACCEL
+#define dprintf_accel fprintf
+#else
+#define dprintf_accel
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_bitmap if(debug_msg_enabled[1]) fprintf
+#else
+#ifdef DEBUG_BITMAP
+#define dprintf_bitmap fprintf
+#else
+#define dprintf_bitmap
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_caret if(debug_msg_enabled[2]) fprintf
+#else
+#ifdef DEBUG_CARET
+#define dprintf_caret fprintf
+#else
+#define dprintf_caret
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_cdaudio if(debug_msg_enabled[3]) fprintf
+#else
+#ifdef DEBUG_CDAUDIO
+#define dprintf_cdaudio fprintf
+#else
+#define dprintf_cdaudio
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_class if(debug_msg_enabled[4]) fprintf
+#else
+#ifdef DEBUG_CLASS
+#define dprintf_class fprintf
+#else
+#define dprintf_class
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_clipboard if(debug_msg_enabled[5]) fprintf
+#else
+#ifdef DEBUG_CLIPBOARD
+#define dprintf_clipboard fprintf
+#else
+#define dprintf_clipboard
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_clipping if(debug_msg_enabled[6]) fprintf
+#else
+#ifdef DEBUG_CLIPPING
+#define dprintf_clipping fprintf
+#else
+#define dprintf_clipping
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_combo if(debug_msg_enabled[7]) fprintf
+#else
+#ifdef DEBUG_COMBO
+#define dprintf_combo fprintf
+#else
+#define dprintf_combo
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_comm if(debug_msg_enabled[8]) fprintf
+#else
+#ifdef DEBUG_COMM
+#define dprintf_comm fprintf
+#else
+#define dprintf_comm
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_cursor if(debug_msg_enabled[9]) fprintf
+#else
+#ifdef DEBUG_CURSOR
+#define dprintf_cursor fprintf
+#else
+#define dprintf_cursor
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_dc if(debug_msg_enabled[10]) fprintf
+#else
+#ifdef DEBUG_DC
+#define dprintf_dc fprintf
+#else
+#define dprintf_dc
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_dialog if(debug_msg_enabled[11]) fprintf
+#else
+#ifdef DEBUG_DIALOG
+#define dprintf_dialog fprintf
+#else
+#define dprintf_dialog
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_dll if(debug_msg_enabled[12]) fprintf
+#else
+#ifdef DEBUG_DLL
+#define dprintf_dll fprintf
+#else
+#define dprintf_dll
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_dosfs if(debug_msg_enabled[13]) fprintf
+#else
+#ifdef DEBUG_DOSFS
+#define dprintf_dosfs fprintf
+#else
+#define dprintf_dosfs
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_driver if(debug_msg_enabled[14]) fprintf
+#else
+#ifdef DEBUG_DRIVER
+#define dprintf_driver fprintf
+#else
+#define dprintf_driver
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_edit if(debug_msg_enabled[15]) fprintf
+#else
+#ifdef DEBUG_EDIT
+#define dprintf_edit fprintf
+#else
+#define dprintf_edit
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_enum if(debug_msg_enabled[16]) fprintf
+#else
+#ifdef DEBUG_ENUM
+#define dprintf_enum fprintf
+#else
+#define dprintf_enum
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_event if(debug_msg_enabled[17]) fprintf
+#else
+#ifdef DEBUG_EVENT
+#define dprintf_event fprintf
+#else
+#define dprintf_event
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_exec if(debug_msg_enabled[18]) fprintf
+#else
+#ifdef DEBUG_EXEC
+#define dprintf_exec fprintf
+#else
+#define dprintf_exec
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_file if(debug_msg_enabled[19]) fprintf
+#else
+#ifdef DEBUG_FILE
+#define dprintf_file fprintf
+#else
+#define dprintf_file
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_fixup if(debug_msg_enabled[20]) fprintf
+#else
+#ifdef DEBUG_FIXUP
+#define dprintf_fixup fprintf
+#else
+#define dprintf_fixup
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_font if(debug_msg_enabled[21]) fprintf
+#else
+#ifdef DEBUG_FONT
+#define dprintf_font fprintf
+#else
+#define dprintf_font
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_gdi if(debug_msg_enabled[22]) fprintf
+#else
+#ifdef DEBUG_GDI
+#define dprintf_gdi fprintf
+#else
+#define dprintf_gdi
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_graphics if(debug_msg_enabled[23]) fprintf
+#else
+#ifdef DEBUG_GRAPHICS
+#define dprintf_graphics fprintf
+#else
+#define dprintf_graphics
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_heap if(debug_msg_enabled[24]) fprintf
+#else
+#ifdef DEBUG_HEAP
+#define dprintf_heap fprintf
+#else
+#define dprintf_heap
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_icon if(debug_msg_enabled[25]) fprintf
+#else
+#ifdef DEBUG_ICON
+#define dprintf_icon fprintf
+#else
+#define dprintf_icon
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_int if(debug_msg_enabled[26]) fprintf
+#else
+#ifdef DEBUG_INT
+#define dprintf_int fprintf
+#else
+#define dprintf_int
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_key if(debug_msg_enabled[27]) fprintf
+#else
+#ifdef DEBUG_KEY
+#define dprintf_key fprintf
+#else
+#define dprintf_key
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_keyboard if(debug_msg_enabled[28]) fprintf
+#else
+#ifdef DEBUG_KEYBOARD
+#define dprintf_keyboard fprintf
+#else
+#define dprintf_keyboard
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_ldt if(debug_msg_enabled[29]) fprintf
+#else
+#ifdef DEBUG_LDT
+#define dprintf_ldt fprintf
+#else
+#define dprintf_ldt
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_listbox if(debug_msg_enabled[30]) fprintf
+#else
+#ifdef DEBUG_LISTBOX
+#define dprintf_listbox fprintf
+#else
+#define dprintf_listbox
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_mciwave if(debug_msg_enabled[31]) fprintf
+#else
+#ifdef DEBUG_MCIWAVE
+#define dprintf_mciwave fprintf
+#else
+#define dprintf_mciwave
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_mdi if(debug_msg_enabled[32]) fprintf
+#else
+#ifdef DEBUG_MDI
+#define dprintf_mdi fprintf
+#else
+#define dprintf_mdi
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_menu if(debug_msg_enabled[33]) fprintf
+#else
+#ifdef DEBUG_MENU
+#define dprintf_menu fprintf
+#else
+#define dprintf_menu
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_menucalc if(debug_msg_enabled[34]) fprintf
+#else
+#ifdef DEBUG_MENUCALC
+#define dprintf_menucalc fprintf
+#else
+#define dprintf_menucalc
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_message if(debug_msg_enabled[35]) fprintf
+#else
+#ifdef DEBUG_MESSAGE
+#define dprintf_message fprintf
+#else
+#define dprintf_message
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_metafile if(debug_msg_enabled[36]) fprintf
+#else
+#ifdef DEBUG_METAFILE
+#define dprintf_metafile fprintf
+#else
+#define dprintf_metafile
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_module if(debug_msg_enabled[37]) fprintf
+#else
+#ifdef DEBUG_MODULE
+#define dprintf_module fprintf
+#else
+#define dprintf_module
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_msg if(debug_msg_enabled[38]) fprintf
+#else
+#ifdef DEBUG_MSG
+#define dprintf_msg fprintf
+#else
+#define dprintf_msg
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_nonclient if(debug_msg_enabled[39]) fprintf
+#else
+#ifdef DEBUG_NONCLIENT
+#define dprintf_nonclient fprintf
+#else
+#define dprintf_nonclient
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_palette if(debug_msg_enabled[40]) fprintf
+#else
+#ifdef DEBUG_PALETTE
+#define dprintf_palette fprintf
+#else
+#define dprintf_palette
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_region if(debug_msg_enabled[41]) fprintf
+#else
+#ifdef DEBUG_REGION
+#define dprintf_region fprintf
+#else
+#define dprintf_region
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_resource if(debug_msg_enabled[42]) fprintf
+#else
+#ifdef DEBUG_RESOURCE
+#define dprintf_resource fprintf
+#else
+#define dprintf_resource
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_scroll if(debug_msg_enabled[43]) fprintf
+#else
+#ifdef DEBUG_SCROLL
+#define dprintf_scroll fprintf
+#else
+#define dprintf_scroll
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_syscolor if(debug_msg_enabled[44]) fprintf
+#else
+#ifdef DEBUG_SYSCOLOR
+#define dprintf_syscolor fprintf
+#else
+#define dprintf_syscolor
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_text if(debug_msg_enabled[45]) fprintf
+#else
+#ifdef DEBUG_TEXT
+#define dprintf_text fprintf
+#else
+#define dprintf_text
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_timer if(debug_msg_enabled[46]) fprintf
+#else
+#ifdef DEBUG_TIMER
+#define dprintf_timer fprintf
+#else
+#define dprintf_timer
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_utility if(debug_msg_enabled[47]) fprintf
+#else
+#ifdef DEBUG_UTILITY
+#define dprintf_utility fprintf
+#else
+#define dprintf_utility
+#endif
+#endif
+ 
+#ifdef DEBUG_RUNTIME
+#define dprintf_win if(debug_msg_enabled[48]) fprintf
+#else
+#ifdef DEBUG_WIN
+#define dprintf_win fprintf
+#else
+#define dprintf_win
+#endif
+#endif
+ 
+ 
+ 
+#ifdef DEBUG_RUNTIME
+#ifdef DEBUG_DEFINE_VARIABLES
+static char *debug_msg_name[] = {
+"accel",
+"bitmap",
+"caret",
+"cdaudio",
+"class",
+"clipboard",
+"clipping",
+"combo",
+"comm",
+"cursor",
+"dc",
+"dialog",
+"dll",
+"dosfs",
+"driver",
+"edit",
+"enum",
+"event",
+"exec",
+"file",
+"fixup",
+"font",
+"gdi",
+"graphics",
+"heap",
+"icon",
+"int",
+"key",
+"keyboard",
+"ldt",
+"listbox",
+"mciwave",
+"mdi",
+"menu",
+"menucalc",
+"message",
+"metafile",
+"module",
+"msg",
+"nonclient",
+"palette",
+"region",
+"resource",
+"scroll",
+"syscolor",
+"text",
+"timer",
+"utility",
+"win",
+""};
+#endif
+#endif
diff --git a/include/dialog.h b/include/dialog.h
index 3b33347..3cc5452 100644
--- a/include/dialog.h
+++ b/include/dialog.h
@@ -16,15 +16,15 @@
    */
 typedef struct
 {
-    LONG      msgResult;
-    FARPROC   dlgProc;
-    LONG      userInfo;
-    HWND      hwndFocus;
-    HFONT     hUserFont;
-    HMENU     hMenu;
-    WORD      xBaseUnit;
+    LONG      msgResult;   /* Result of EndDialog() / Default button id */
+    WNDPROC   dlgProc;     /* Dialog procedure */
+    LONG      userInfo;    /* User information (for DWL_USER) */
+    HWND      hwndFocus;   /* Current control with focus */
+    HFONT     hUserFont;   /* Dialog font */
+    HMENU     hMenu;       /* Dialog menu */
+    WORD      xBaseUnit;   /* Dialog units (depends on the font) */
     WORD      yBaseUnit;
-    WORD      fEnd;
+    WORD      fEnd;        /* EndDialog() called for this dialog */
     HANDLE    hDialogHeap;
 } DIALOGINFO;
 
diff --git a/include/dlls.h b/include/dlls.h
index 292b57f..5a5cdf6 100644
--- a/include/dlls.h
+++ b/include/dlls.h
@@ -17,21 +17,36 @@
     char id[MAX_NAME_LENGTH];
 } RESNAMTAB;
 
+struct ne_data {
+    struct ne_header_s *ne_header;
+    struct ne_segment_table_entry_s *seg_table;
+    struct segment_descriptor_s *selector_table;
+    char *lookup_table;
+    char *nrname_table;
+    char *rname_table;
+    RESNAMTAB *resnamtab;
+};
+
+struct pe_data {
+	struct pe_header_s *pe_header;
+	struct pe_segment_table *pe_seg;
+	struct PE_Import_Directory *pe_import;
+	struct PE_Export_Directory *pe_export;
+	struct PE_Resource_Directory *pe_resource;
+	int resource_offset; /* offset to resource typedirectory in file */
+};
+
 struct w_files
 {
     struct w_files  * next;
     char * name;   /* Name, as it appears in the windows binaries */
     char * filename; /* Actual name of the unix file that satisfies this */
     int fd;
-    struct mz_header_s *mz_header;
-    struct ne_header_s *ne_header;
-    struct ne_segment_table_entry_s *seg_table;
-    struct segment_descriptor_s *selector_table;
-    char * lookup_table;
-    char * nrname_table;
-    char * rname_table;
     unsigned short hinstance;
-    RESNAMTAB *resnamtab;
+    int initialised;
+    struct mz_header_s *mz_header;
+    struct ne_data *ne;
+    struct pe_data *pe;
 };
 
 extern struct  w_files *wine_files;
diff --git a/include/gdi.h b/include/gdi.h
index b86d508..9198f21 100644
--- a/include/gdi.h
+++ b/include/gdi.h
@@ -302,7 +302,6 @@
 extern BOOL GDI_FreeObject( HANDLE );
 extern GDIOBJHDR * GDI_GetObjPtr( HANDLE, WORD );
 
-extern Display * XT_display;  /* Will be removed */
 extern Display * display;
 extern Screen * screen;
 extern Window rootWindow;
diff --git a/include/hook.h b/include/hook.h
index 94f23f8..f70dce8 100644
--- a/include/hook.h
+++ b/include/hook.h
@@ -15,7 +15,7 @@
 {
     HHOOK    next;   /* Next hook in chain */
     HOOKPROC proc;   /* Hook procedure */
-    short    id;     /* Hook id (WH_???) */
+    short    id;     /* Hook id (WH_xxx) */
     HTASK    htask;  /* Task owning this hook */
 } HOOKDATA;
 
diff --git a/include/listbox.h b/include/listbox.h
index 874d69e..22148ec 100644
--- a/include/listbox.h
+++ b/include/listbox.h
@@ -7,6 +7,7 @@
     DRAWITEMSTRUCT 	dis;
     HANDLE		hMem;
     HANDLE		hData;
+    char                *itemText;
     void		*lpNext;
 } LISTSTRUCT;
 typedef LISTSTRUCT FAR* LPLISTSTRUCT;
@@ -26,7 +27,7 @@
     void	*lpFirst; 
     DWORD	dwStyle;
     HWND	hWndLogicParent;
-	HFONT	hFont;
+    HFONT	hFont;
 } HEADLIST;
 typedef HEADLIST FAR* LPHEADLIST;
 
diff --git a/include/msdos.h b/include/msdos.h
index e2b6450..0578218 100644
--- a/include/msdos.h
+++ b/include/msdos.h
@@ -10,6 +10,7 @@
 	char filename[256];
 	char filemask[12];
 	char attribute;
+	char search_attribute;
 	long filesize;
 	long filetime;
 };
diff --git a/include/peexe.h b/include/peexe.h
new file mode 100644
index 0000000..d5ce342
--- /dev/null
+++ b/include/peexe.h
@@ -0,0 +1,214 @@
+/*
+ * Copyright  Eric Youngdale (1994)
+ */
+#ifndef __WINE_PEEXE_H
+#define __WINE_PEEXE_H
+
+
+
+struct coff_header
+{
+	u_short Machine;
+	u_short NumberOfSections;
+        u_long TimeDateStamp;
+        u_long PointerToSymbolTable;
+        u_long NumberOfSymbols;
+        u_short SizeOfOptionalHeader;
+        u_short Characteristics;
+};
+
+
+/* These defines describe the meanings of the bits in the Characteristics
+   field */
+
+#define IMAGE_FILE_RELOCS_STRIPPED	1 /* No relocation info */
+#define IMAGE_FILE_EXECUTABLE_IMAGE	2
+#define IMAGE_FILE_LINE_NUMS_STRIPPED   4
+#define IMAGE_FILE_LOCAL_SYMS_STRIPPED  8
+#define IMAGE_FILE_16BIT_MACHINE	0x40
+#define IMAGE_FILE_BYTES_REVERSED_LO	0x80
+#define IMAGE_FILE_32BIT_MACHINE	0x100
+#define IMAGE_FILE_DEBUG_STRIPPED	0x200
+#define IMAGE_FILE_SYSTEM		0x1000
+#define IMAGE_FILE_DLL			0x2000
+#define IMAGE_FILE_BYTES_REVERSED_HI	0x8000
+
+/* These are the settings of the Machine field. */
+#define IMAGE_FILE_MACHINE_UNKNOWN 0
+#define IMAGE_FILE_MACHINE_I860    0x14d
+#define IMAGE_FILE_MACHINE_I386    0x14c
+#define IMAGE_FILE_MACHINE_R3000	0x162
+#define IMAGE_FILE_MACHINE_R4000	0x166
+#define IMAGE_FILE_MACHINE_ALPHA	0x184
+
+struct Directory
+{
+  u_long Virtual_address;
+  u_long Size;
+};
+
+
+/* Optional coff header - used by NT to provide additional information. */
+
+struct ocoffhdr
+{
+	u_short Magic;  		/* Good old COFF magic 0413 */
+	u_char MajorLinkerVersion;
+	u_char MinorLinkerVersion;
+	u_long SizeOfCode;
+	u_long SizeOfInitializedData;
+	u_long SizeOfUninitializedData;
+	u_long AddressOfEntryPoint;
+	u_long BaseOfCode;
+	u_long BaseOfData;
+	u_long BaseOfImage;
+	u_long SectionAlignment;
+	u_long FileAlignment;
+	u_short MajorOperatingSystemVersion;
+	u_short MinorOperatingSystemVersion;
+	u_short MajorImageVersion;
+	u_short MinorImageVersion;
+	u_short MajorSubsystemVersion;
+	u_short MinorSubsystemVersion;
+	u_long Unknown1;
+	u_long SizeOfImage;
+	u_long SizeOfHeaders;
+	u_long CheckSum;
+	u_short Subsystem;
+	u_short DllCharacteristics;
+	u_long SizeOfStackReserve;
+	u_long SizeOfStackCommit;
+	u_long SizeOfHeapReserve;
+	u_long SizeOfHeapCommit;
+	u_long LoaderFlags;
+	u_long NumberOfRvaAndSizes;
+	struct Directory DataDirectory[16];
+};
+
+/* These are indexes into the DataDirectory array */
+#define IMAGE_FILE_EXPORT_DIRECTORY 0
+#define IMAGE_FILE_IMPORT_DIRECTORY 1
+#define IMAGE_FILE_RESOURCE_DIRECTORY 2
+#define IMAGE_FILE_EXCEPTION_DIRECTORY 3
+#define IMAGE_FILE_SECURITY_DIRECTORY 4
+#define IMAGE_FILE_BASE_RELOCATION_TABLE 5
+#define IMAGE_FILE_DEBUG_DIRECTORY 6
+#define IMAGE_FILE_DESCRIPTION_STRING 7
+#define IMAGE_FILE_MACHINE_VALUE 8  /* Mips */
+#define IMAGE_FILE_THREAD_LOCAL_STORAGE 9
+#define IMAGE_FILE_CALLBACK_DIRECTORY 10
+
+struct pe_header_s
+{
+	char magic[4];  /* Must be 'P', 'E', 0, 0 */
+	struct coff_header coff;
+	struct ocoffhdr    opt_coff;
+};
+
+
+struct pe_segment_table
+{
+  u_char Name[8];
+  u_long Virtual_Size;
+  u_long Virtual_Address;
+  u_long Size_Of_Raw_Data;
+  u_long   PointerToRawData;
+  u_long   PointerToRelocations;
+  u_long   PointerToLinenumbers;
+  u_short  NumberOfRelocations;
+  u_short  NumberOfLinenumbers;
+  u_long   Characteristics;
+};
+
+/* These defines are for the Characteristics bitfield. */
+
+#define IMAGE_SCN_TYPE_CNT_CODE 0x20
+#define IMAGE_SCN_TYPE_CNT_INITIALIZED_DATA 0x40
+#define IMAGE_SCN_TYPE_CNT_UNINITIALIZED_DATA 0x80
+#define IMAGE_SCN_MEM_DISCARDABLE  0x2000000
+#define IMAGE_SCN_MEM_SHARED 	  0x10000000
+#define IMAGE_SCN_MEM_EXECUTE	  0x20000000
+#define IMAGE_SCN_MEM_READ	  0x40000000
+#define IMAGE_SCN_MEM_WRITE	  0x80000000
+
+/*
+ * Import module directory stuff
+ */
+
+struct PE_Import_Directory
+{
+  u_int Import_List;
+  u_int reserved[2];
+  u_int ModuleName;
+  u_int reserved1;
+};
+
+struct pe_import_name
+{
+  u_short Hint;
+  u_char Name[1];
+};
+
+/*
+ * Export module directory stuff
+ */
+
+struct PE_Export_Directory
+{
+  u_long Characteristics;
+  u_long TimeDateStamp;
+  u_short Major_version;
+  u_short Minor_version;
+  u_long Name;
+  u_long Base;
+  u_long Number_Of_Functions;
+  u_long Number_Of_Names;
+  u_long * AddressOfFunctions;
+  u_long * AddressOfNames;
+  u_short * Address_Of_Name_Ordinals;
+};
+
+/*
+ * Resource directory stuff
+ */
+
+struct PE_Resource_Directory
+{
+  u_long Characteristics;
+  u_long TimeDateStamp;
+  u_short MajorVersion;
+  u_short MinorVersion;
+  u_short NumberOfNamedEntries;
+  u_short NumberOfIdEntries;
+};
+
+struct PE_Directory_Entry
+{
+  u_long Name;
+  u_long OffsetToData;
+};
+
+struct PE_Directory_Name_String
+{
+  u_short Length;
+  char NameString[1];
+};
+
+struct PE_Directory_Name_String_U
+{
+  u_short Length;
+  u_short NameString[1];
+};
+
+struct PE_Resource_Leaf_Entry
+{
+  u_long OffsetToData;
+  u_long Size;
+  u_long CodePage;
+  u_long Reserved;
+};
+
+#define IMAGE_RESOURCE_NAME_IS_STRING    0x80000000
+#define IMAGE_RESOURCE_DATA_IS_DIRECTORY 0x80000000
+
+#endif /* __WINE_PEEXE_H */
diff --git a/include/prototypes.h b/include/prototypes.h
index cbeee0b..536d411 100644
--- a/include/prototypes.h
+++ b/include/prototypes.h
@@ -40,16 +40,6 @@
 extern int OpenResourceFile(HANDLE instance);
 extern HBITMAP ConvertCoreBitmap( HDC hdc, BITMAPCOREHEADER * image );
 extern HBITMAP ConvertInfoBitmap( HDC hdc, BITMAPINFO * image );
-extern int FindResourceByNumber(struct resource_nameinfo_s *result_p, 
-				int type_id, int resource_id);
-extern int FindResourceByName(struct resource_nameinfo_s *result_p,
-		     int type_id, char *resource_name);
-extern HICON LoadIcon(HANDLE instance, LPSTR icon_name);
-extern HANDLE RSC_LoadResource(int instance, char *rsc_name, int type,
-				int *image_size_ret);
-extern int LoadString(HANDLE instance, WORD resource_id, LPSTR buffer, int buflen);
-extern HANDLE RSC_LoadMenu(HANDLE instance, LPSTR menu_name);
-extern HBITMAP LoadBitmap(HANDLE instance, LPSTR bmp_name);
 
 /* loader/selector.c */
 
diff --git a/include/resource.h b/include/resource.h
new file mode 100644
index 0000000..36b2b26
--- /dev/null
+++ b/include/resource.h
@@ -0,0 +1,23 @@
+#ifndef __WINE_RESOURCE_H
+#define __WINE_RESOURCE_H
+
+#include "dlls.h"
+
+typedef struct resource_s {
+	struct resource_s *next;
+	HANDLE info_mem;	/* this struct */
+	int size_shift;
+	struct resource_nameinfo_s nameinfo;
+	HANDLE rsc_mem;		/* resource data */
+	/* */
+	HANDLE instance;	/* resource instance */
+	LPSTR name;		/* resource name */
+	LPSTR type;		/* resource type */
+	int count;		/* lock count */
+	int size;		/* resource size */
+	int fd;			/* fd */
+	int offset;		/* offset */
+	struct w_files *wpnt;
+} RESOURCE;
+
+#endif /* __WINE_RESOURCE_H */
diff --git a/include/segmem.h b/include/segmem.h
index c5b03c6..047fea0 100644
--- a/include/segmem.h
+++ b/include/segmem.h
@@ -77,12 +77,6 @@
 
 #define FIRST_SELECTOR	8
 
-static __inline__ int Is16bitAddress(void *address)
-{
-    return ((unsigned int) address 
-	    >= (((FIRST_SELECTOR << 3) | 0x0007) << 16));
-}
-
 extern SEGDESC Segments[];
 
 #endif /* SEGMEM_H */
diff --git a/include/static.h b/include/static.h
new file mode 100644
index 0000000..8dcd000
--- /dev/null
+++ b/include/static.h
@@ -0,0 +1,22 @@
+/*
+ * Static-class extra info
+ *
+ * Copyright 1994 Alexandre Julliard
+ */
+
+#ifndef STATIC_H
+#define STATIC_H
+
+#include "windows.h"
+
+  /* Extra info for STATIC windows */
+typedef struct
+{
+    HFONT  hFont;   /* Control font (or 0 for system font) */
+    WORD   dummy;   /* Don't know what MS-Windows puts in there */
+    HICON  hIcon;   /* Icon handle for SS_ICON controls */ 
+} STATICINFO;
+
+extern LONG StaticWndProc( HWND hWnd, WORD uMsg, WORD wParam, LONG lParam );
+
+#endif  /* STATIC_H */
diff --git a/include/stddebug.h b/include/stddebug.h
new file mode 100644
index 0000000..cda6a2e
--- /dev/null
+++ b/include/stddebug.h
@@ -0,0 +1,178 @@
+/* If you define this you can enable or disable specific debugging- */
+/* messages at run-time by supplying the "-debugmsg" option to Wine */
+#define DEBUG_RUNTIME /* */
+
+
+/* Define this if you want to enable all debugging-messages, except  */
+/* the ones explicitly disabled in a specific *.c-file.              */
+/* #define DEBUG_ALL */
+
+/* Define this if you want to enable all debugging-messages, even    */
+/* the ones explicitly disabled in specific *.c-files.               */
+/* #define DEBUG_ALL_EXT */
+
+/* Define this if you want to disable all debugging-messages, except */
+/* the ones explicitly enabled in a specifiy *.c-file.               */
+/* #define DEBUG_NONE */
+
+/* Define this if you want to disable all debugging-messages, even   */
+/* the ones explicitly enabled in specific *.c-files.                */
+/* #define DEBUG_NONE_EXT */
+
+
+/* You can enable or disable specific debugging-messages here.       */ 
+/* However, this can be overridden in the individual *.c-files       */
+/* between #include <stddebug.h> and #include <debug.h>              */
+
+
+/* #define DEBUG_EDIT      */
+/* #define DEBUG_MENU      */
+/* #define DEBUG_MENUCALC  */
+/* #define DEBUG_SCROLL    */
+/* #define DEBUG_COMBO     */
+/* #define DEBUG_LISTBOX   */
+/* #define DEBUG_TASK      */
+/* #define DEBUG_SELECTORS */
+/* #define DEBUG_RESOURCE  */
+/* #define DEBUG_ACCEL     */
+/* #define DEBUG_FIXUP     */
+/* #define DEBUG_MODULE    */
+/* #define DEBUG_LDT       */
+/* #define DEBUG_HEAP      */
+/* #define DEBUG_MCIWAVE   */
+/* #define DEBUG_MCIWAVE   */
+/* #define DEBUG_INT       */
+/* #define DEBUG_METAFILE  */
+/* #define DEBUG_GDI       */
+/* #define DEBUG_BITMAP    */
+/* #define DEBUG_FONT      */
+/* #define DEBUG_PALETTE   */
+/* #define DEBUG_ICON      */
+/* #define DEBUG_REGION    */
+/* #define DEBUG_TEXT      */
+/* #define DEBUG_CLIPPING  */
+/* #define DEBUG_CARET     */
+/* #define DEBUG_CLASS     */
+/* #define DEBUG_DC        */
+/* #define DEBUG_DIALOG    */
+/* #define DEBUG_MESSAGE   */
+/* #define DEBUG_EVENT     */
+/* #define DEBUG_KEY       */
+/* #define DEBUG_GRAPHICS  */
+/* #define DEBUG_MDI       */
+/* #define DEBUG_MSG       */
+/* #define DEBUG_NONCLIENT */
+/* #define DEBUG_SYSCOLOR  */
+/* #define DEBUG_TIMER     */
+/* #define DEBUG_UTILITY   */
+/* #define DEBUG_WIN       */
+/* #define DEBUG_ENUM      */
+/* #define DEBUG_DLL       */
+ 
+
+# /* Do not remove this line or change anything below this line */
+ 
+#ifdef DEBUG_NONE
+#undef DEBUG_ACCEL
+#undef DEBUG_BITMAP
+#undef DEBUG_CARET
+#undef DEBUG_CDAUDIO
+#undef DEBUG_CLASS
+#undef DEBUG_CLIPBOARD
+#undef DEBUG_CLIPPING
+#undef DEBUG_COMBO
+#undef DEBUG_COMM
+#undef DEBUG_CURSOR
+#undef DEBUG_DC
+#undef DEBUG_DIALOG
+#undef DEBUG_DLL
+#undef DEBUG_DOSFS
+#undef DEBUG_DRIVER
+#undef DEBUG_EDIT
+#undef DEBUG_ENUM
+#undef DEBUG_EVENT
+#undef DEBUG_EXEC
+#undef DEBUG_FILE
+#undef DEBUG_FIXUP
+#undef DEBUG_FONT
+#undef DEBUG_GDI
+#undef DEBUG_GRAPHICS
+#undef DEBUG_HEAP
+#undef DEBUG_ICON
+#undef DEBUG_INT
+#undef DEBUG_KEY
+#undef DEBUG_KEYBOARD
+#undef DEBUG_LDT
+#undef DEBUG_LISTBOX
+#undef DEBUG_MCIWAVE
+#undef DEBUG_MDI
+#undef DEBUG_MENU
+#undef DEBUG_MENUCALC
+#undef DEBUG_MESSAGE
+#undef DEBUG_METAFILE
+#undef DEBUG_MODULE
+#undef DEBUG_MSG
+#undef DEBUG_NONCLIENT
+#undef DEBUG_PALETTE
+#undef DEBUG_REGION
+#undef DEBUG_RESOURCE
+#undef DEBUG_SCROLL
+#undef DEBUG_SYSCOLOR
+#undef DEBUG_TEXT
+#undef DEBUG_TIMER
+#undef DEBUG_UTILITY
+#undef DEBUG_WIN
+#endif
+ 
+ 
+#ifdef DEBUG_ALL
+#define DEBUG_ACCEL
+#define DEBUG_BITMAP
+#define DEBUG_CARET
+#define DEBUG_CDAUDIO
+#define DEBUG_CLASS
+#define DEBUG_CLIPBOARD
+#define DEBUG_CLIPPING
+#define DEBUG_COMBO
+#define DEBUG_COMM
+#define DEBUG_CURSOR
+#define DEBUG_DC
+#define DEBUG_DIALOG
+#define DEBUG_DLL
+#define DEBUG_DOSFS
+#define DEBUG_DRIVER
+#define DEBUG_EDIT
+#define DEBUG_ENUM
+#define DEBUG_EVENT
+#define DEBUG_EXEC
+#define DEBUG_FILE
+#define DEBUG_FIXUP
+#define DEBUG_FONT
+#define DEBUG_GDI
+#define DEBUG_GRAPHICS
+#define DEBUG_HEAP
+#define DEBUG_ICON
+#define DEBUG_INT
+#define DEBUG_KEY
+#define DEBUG_KEYBOARD
+#define DEBUG_LDT
+#define DEBUG_LISTBOX
+#define DEBUG_MCIWAVE
+#define DEBUG_MDI
+#define DEBUG_MENU
+#define DEBUG_MENUCALC
+#define DEBUG_MESSAGE
+#define DEBUG_METAFILE
+#define DEBUG_MODULE
+#define DEBUG_MSG
+#define DEBUG_NONCLIENT
+#define DEBUG_PALETTE
+#define DEBUG_REGION
+#define DEBUG_RESOURCE
+#define DEBUG_SCROLL
+#define DEBUG_SYSCOLOR
+#define DEBUG_TEXT
+#define DEBUG_TIMER
+#define DEBUG_UTILITY
+#define DEBUG_WIN
+#endif
diff --git a/include/win.h b/include/win.h
index 22290dd..2af959a 100644
--- a/include/win.h
+++ b/include/win.h
@@ -9,7 +9,7 @@
 
 #include <X11/Xlib.h>
 
-#include "windows.h"
+#include "class.h"
 
 #define WND_MAGIC     0x444e4957  /* 'WIND' */
 
@@ -38,7 +38,7 @@
     HRGN         hrgnUpdate;     /* Update region */
     HWND         hwndPrevActive; /* Previous active top-level window */
     HWND         hwndLastActive; /* Last active popup hwnd */
-    FARPROC      lpfnWndProc;    /* Window procedure */
+    WNDPROC      lpfnWndProc;    /* Window procedure */
     DWORD        dwStyle;        /* Window style (from CreateWindow) */
     DWORD        dwExStyle;      /* Extended style (from CreateWindowEx) */
     HANDLE       hdce;           /* Window DCE (if CS_OWNDC or CS_CLASSDC) */
@@ -48,10 +48,7 @@
     WORD         wIDmenu;        /* ID or hmenu (from CreateWindow) */
     HANDLE       hText;          /* Handle of window text */
     WORD         flags;          /* Misc. flags (see below) */
-    Window       window;         /* X window */
-    HICON        hIcon;          /* icon's MS-windows handle */
-    WORD	 iconWidth;	 /* width of icon */
-    WORD	 iconHeight;     /* height of icon */
+    Window       window;         /* X window (only for top-level windows) */
     RECT         rectClientSave; /* where client rect is saved when icon*/
     HMENU        hSysMenu;	 /* window's copy of System Menu */
     HANDLE       hProp;          /* Handle of Properties List */
@@ -63,14 +60,16 @@
 #define WIN_ERASE_UPDATERGN     0x01  /* Update region needs erasing */
 #define WIN_NEEDS_BEGINPAINT    0x02  /* WM_PAINT sent to window */
 #define WIN_GOT_SIZEMSG         0x04  /* WM_SIZE has been sent to the window */
-#define WIN_OWN_DC              0x08  /* Win class has style CS_OWNDC */
-#define WIN_CLASS_DC            0x10  /* Win class has style CS_CLASSDC */
-#define WIN_DOUBLE_CLICKS       0x20  /* Win class has style CS_DBLCLKS */
-#define WIN_RESTORE_MAX         0x40  /* Maximize when restoring */
-#define WIN_INTERNAL_PAINT      0x80  /* Internal WM_PAINT message pending */
+#define WIN_RESTORE_MAX         0x08  /* Maximize when restoring */
+#define WIN_INTERNAL_PAINT      0x10  /* Internal WM_PAINT message pending */
+#define WIN_NO_REDRAW           0x20  /* WM_SETREDRAW called for this window */
+
+#define WIN_CLASS_INFO(wndPtr)   (CLASS_FindClassPtr((wndPtr)->hClass)->wc)
+#define WIN_CLASS_STYLE(wndPtr)  (WIN_CLASS_INFO(wndPtr).style)
 
   /* Window functions */
 WND *WIN_FindWndPtr( HWND hwnd );
+Window WIN_GetXWindow( HWND hwnd );
 BOOL WIN_UnlinkWindow( HWND hwnd );
 BOOL WIN_LinkWindow( HWND hwnd, HWND hwndInsertAfter );
 HWND WIN_FindWinToRepaint( HWND hwnd );
diff --git a/include/windows.h b/include/windows.h
index 5443498..ee8fc6f 100644
--- a/include/windows.h
+++ b/include/windows.h
@@ -50,6 +50,7 @@
 DECLARE_HANDLE(HBRUSH);
 DECLARE_HANDLE(LOCALHANDLE);
 DECLARE_HANDLE(HMETAFILE);
+DECLARE_HANDLE(HDWP);
 
 #define TRUE 1
 #define FALSE 0
@@ -81,41 +82,6 @@
 #define min(a,b) (((a) < (b)) ? (a) : (b))
 #endif
 
-/*
-typedef long LONG;
-typedef WORD HANDLE;
-typedef HANDLE HWND;
-typedef HANDLE HDC;
-typedef HANDLE HCLASS;
-typedef HANDLE HCURSOR;
-typedef HANDLE HFONT;
-typedef HANDLE HPEN;
-typedef HANDLE HRGN;
-typedef HANDLE HPALETTE;
-typedef HANDLE HICON;
-typedef HANDLE HINSTANCE;
-typedef HANDLE HMENU;
-typedef HANDLE HBITMAP;
-typedef HANDLE HBRUSH;
-typedef HANDLE LOCALHANDLE;
-typedef char *LPSTR;
-typedef char *NPSTR;
-typedef short *LPINT;
-typedef void *LPVOID;
-typedef long (*FARPROC)();
-typedef int CATCHBUF[9];
-typedef int *LPCATCHBUF;
-
-#define TRUE 1
-#define FALSE 0
-#define CW_USEDEFAULT ((short)0x8000)
-#define FAR
-#define NEAR
-#define PASCAL
-#ifndef NULL
-#define NULL (void *)0
-#endif
-*/
 
 typedef struct { INT x, y; } POINT;
 typedef POINT *PPOINT;
@@ -158,19 +124,11 @@
 
   /* Window classes */
 
-#ifdef WINELIB
 typedef LONG (*WNDPROC)(HWND, UINT, WPARAM, LPARAM);
-#else
-typedef LONG	(* WNDPROC)();
-#endif
 
 typedef struct {
 	WORD	style;
-#ifdef WINELIB
-	WNDPROC lpfnWndProc;
-#else
-	LONG	(*lpfnWndProc)() WINE_PACKED;
-#endif
+	WNDPROC	lpfnWndProc WINE_PACKED;
 	INT	cbClsExtra, cbWndExtra;
 	HANDLE	hInstance;
 	HICON	hIcon;
@@ -763,18 +721,18 @@
     INT     tmAveCharWidth;
     INT     tmMaxCharWidth;
     INT     tmWeight;
-    BYTE      tmItalic;
-    BYTE      tmUnderlined;
-    BYTE      tmStruckOut;
-    BYTE      tmFirstChar;
-    BYTE      tmLastChar;
-    BYTE      tmDefaultChar;
-    BYTE      tmBreakChar;
-    BYTE      tmPitchAndFamily;
-    BYTE      tmCharSet;
-    INT     tmOverhang;
-    INT     tmDigitizedAspectX;
-    INT     tmDigitizedAspectY;
+    BYTE    tmItalic;
+    BYTE    tmUnderlined;
+    BYTE    tmStruckOut;
+    BYTE    tmFirstChar;
+    BYTE    tmLastChar;
+    BYTE    tmDefaultChar;
+    BYTE    tmBreakChar;
+    BYTE    tmPitchAndFamily;
+    BYTE    tmCharSet;
+    INT     tmOverhang WINE_PACKED;
+    INT     tmDigitizedAspectX WINE_PACKED;
+    INT     tmDigitizedAspectY WINE_PACKED;
 } TEXTMETRIC, *PTEXTMETRIC, *NPTEXTMETRIC, *LPTEXTMETRIC;
 
   /* tmPitchAndFamily values */
@@ -793,6 +751,10 @@
 #define TA_BOTTOM           0x08
 #define TA_BASELINE         0x18
 
+  /* ExtTextOut() parameters */
+#define ETO_GRAYED          0x01
+#define ETO_OPAQUE          0x02
+#define ETO_CLIPPED         0x04
 
 typedef struct tagPALETTEENTRY
 {
@@ -872,6 +834,10 @@
 #define ABSOLUTE          1
 #define RELATIVE          2
 
+  /* Flood fill modes */
+#define FLOODFILLBORDER   0
+#define FLOODFILLSURFACE  1
+
   /* Device parameters for GetDeviceCaps() */
 #define DRIVERVERSION     0
 #define TECHNOLOGY        2
@@ -1567,14 +1533,7 @@
 #define SW_PARENTOPENING    3
 #define SW_OTHERRESTORED    4
 
-/*
-enum { SW_HIDE, SW_SHOWNORMAL, SW_NORMAL, SW_SHOWMINIMIZED,
-	SW_SHOWMAXIMIZED, SW_MAXIMIZE, SW_SHOWNOACTIVATE, SW_SHOW,
-	SW_MINIMIZE, SW_SHOWMINNOACTIVE, SW_SHOWNA, SW_RESTORE,
-	SW_INTERNAL_HIDE, SW_INTERNAL_RESTORE };
-*/
-
-
+  /* ShowWindow() codes */
 #define SW_HIDE             0
 #define SW_SHOWNORMAL       1
 #define SW_NORMAL           1
@@ -1713,30 +1672,29 @@
 #define DT_INTERNAL 4096
 
 /* Window Styles */
-#define WS_OVERLAPPED 0x00000000L
-#define WS_POPUP 0x80000000L
-#define WS_CHILD 0x40000000L
-#define WS_MINIMIZE 0x20000000L
-#define WS_VISIBLE 0x10000000L
-#define WS_DISABLED 0x08000000L
-#define WS_CLIPSIBLINGS 0x04000000L
-#define WS_CLIPCHILDREN 0x02000000L
-#define WS_MAXIMIZE 0x01000000L
-#define WS_CAPTION 0x00C00000L
-#define WS_BORDER 0x00800000L
-#define WS_DLGFRAME 0x00400000L
-#define WS_VSCROLL 0x00200000L
-#define WS_HSCROLL 0x00100000L
-#define WS_SYSMENU 0x00080000L
-#define WS_THICKFRAME 0x00040000L
-#define WS_GROUP 0x00020000L
-#define WS_TABSTOP 0x00010000L
-#define WS_MINIMIZEBOX 0x00020000L
-#define WS_MINIMIZEBOX 0x00020000L
-#define WS_MAXIMIZEBOX 0x00010000L
-#define WS_TILED WS_OVERLAPPED
-#define WS_ICONIC WS_MINIMIZE
-#define WS_SIZEBOX WS_THICKFRAME
+#define WS_OVERLAPPED    0x00000000L
+#define WS_POPUP         0x80000000L
+#define WS_CHILD         0x40000000L
+#define WS_MINIMIZE      0x20000000L
+#define WS_VISIBLE       0x10000000L
+#define WS_DISABLED      0x08000000L
+#define WS_CLIPSIBLINGS  0x04000000L
+#define WS_CLIPCHILDREN  0x02000000L
+#define WS_MAXIMIZE      0x01000000L
+#define WS_CAPTION       0x00C00000L
+#define WS_BORDER        0x00800000L
+#define WS_DLGFRAME      0x00400000L
+#define WS_VSCROLL       0x00200000L
+#define WS_HSCROLL       0x00100000L
+#define WS_SYSMENU       0x00080000L
+#define WS_THICKFRAME    0x00040000L
+#define WS_GROUP         0x00020000L
+#define WS_TABSTOP       0x00010000L
+#define WS_MINIMIZEBOX   0x00020000L
+#define WS_MAXIMIZEBOX   0x00010000L
+#define WS_TILED         WS_OVERLAPPED
+#define WS_ICONIC        WS_MINIMIZE
+#define WS_SIZEBOX       WS_THICKFRAME
 #define WS_OVERLAPPEDWINDOW (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME| WS_MINIMIZEBOX | WS_MAXIMIZEBOX)
 #define WS_POPUPWINDOW (WS_POPUP | WS_BORDER | WS_SYSMENU)
 #define WS_CHILDWINDOW (WS_CHILD)
@@ -2069,8 +2027,8 @@
     UINT        itemState;
     HWND        hwndItem;
     HDC         hDC;
-    RECT        rcItem;
-    DWORD       itemData;
+    RECT        rcItem WINE_PACKED;
+    DWORD       itemData WINE_PACKED;
 } DRAWITEMSTRUCT;
 typedef DRAWITEMSTRUCT NEAR* PDRAWITEMSTRUCT;
 typedef DRAWITEMSTRUCT FAR* LPDRAWITEMSTRUCT;
@@ -2084,7 +2042,7 @@
     UINT        itemID;
     UINT        itemWidth;
     UINT        itemHeight;
-    DWORD       itemData;
+    DWORD       itemData WINE_PACKED;
 } MEASUREITEMSTRUCT;
 typedef MEASUREITEMSTRUCT NEAR* PMEASUREITEMSTRUCT;
 typedef MEASUREITEMSTRUCT FAR* LPMEASUREITEMSTRUCT;
@@ -2112,7 +2070,7 @@
     UINT        itemID1;
     DWORD       itemData1;
     UINT        itemID2;
-    DWORD       itemData2;
+    DWORD       itemData2 WINE_PACKED;
 } COMPAREITEMSTRUCT;
 typedef COMPAREITEMSTRUCT NEAR* PCOMPAREITEMSTRUCT;
 typedef COMPAREITEMSTRUCT FAR* LPCOMPAREITEMSTRUCT;
@@ -2269,9 +2227,9 @@
     WORD       mtType;
     WORD       mtHeaderSize;
     WORD       mtVersion;
-    DWORD      mtSize __attribute__ ((packed));
+    DWORD      mtSize WINE_PACKED;
     WORD       mtNoObjects;
-    DWORD      mtMaxRecord __attribute__ ((packed));
+    DWORD      mtMaxRecord WINE_PACKED;
     WORD       mtNoParameters;
 } METAHEADER;
 
@@ -2296,9 +2254,9 @@
 /* Clipboard metafile picture structure */
 typedef struct tagMETAFILEPICT
 {
-    int        mm;
-    int        xExt;
-    int        yExt;
+    INT        mm;
+    INT        xExt;
+    INT        yExt;
     HMETAFILE  hMF;
 } METAFILEPICT;
 typedef METAFILEPICT *LPMETAFILEPICT;
@@ -2488,6 +2446,7 @@
 Fa(BOOL,DestroyMenu,HMENU,a)
 Fa(BOOL,DestroyWindow,HWND,a)
 Fa(BOOL,EnableHardwareInput,BOOL,a)
+Fa(BOOL,EndDeferWindowPos,HDWP,hWinPosInfo)
 Fa(BOOL,FreeModule,HANDLE,a)
 Fa(BOOL,FreeResource,HANDLE,a)
 #ifndef GLOBAL_SOURCE
@@ -2534,7 +2493,7 @@
 #endif
 Fa(DWORD,OemKeyScan,WORD,a)
 Fa(FARPROC,LocalNotify,FARPROC,a)
-Fa(HANDLE,BeginDeferWindowPos,int,nNumWindows)
+Fa(HDWP,BeginDeferWindowPos,INT,nNumWindows)
 Fa(HMETAFILE,CloseMetaFile,HANDLE,a)
 Fa(HANDLE,CreateMetaFile,LPSTR,a)
 Fa(HANDLE,GetAtomHandle,ATOM,a)
@@ -2653,7 +2612,6 @@
 Fa(void,ClipCursor,LPRECT,a)
 Fa(void,CloseWindow,HWND,a)
 Fa(void,DrawMenuBar,HWND,a)
-Fa(void,EndDeferWindowPos,HANDLE,hWinPosInfo)
 Fa(void,FatalExit,int,a)
 Fa(void,FreeLibrary,HANDLE,a)
 Fa(void,FreeProcInstance,FARPROC,a)
@@ -2876,6 +2834,7 @@
 Fc(HRGN,CreatePolygonRgn,LPPOINT,a,short,b,short,c)
 Fc(HWND,GetNextDlgGroupItem,HWND,a,HWND,b,BOOL,c)
 Fc(HWND,GetNextDlgTabItem,HWND,a,HWND,b,BOOL,c)
+Fc(INT,GetTextFace,HDC,a,INT,b,LPSTR,c)
 Fc(LONG,GetBitmapBits,HBITMAP,a,LONG,b,LPSTR,c)
 Fc(LONG,SetBitmapBits,HBITMAP,a,LONG,b,LPSTR,c)
 Fc(LONG,SetClassLong,HWND,a,short,b,LONG,c)
@@ -2894,7 +2853,6 @@
 Fc(int,GetKeyNameText,LONG,a,LPSTR,b,int,c)
 Fc(int,GetModuleFileName,HANDLE,a,LPSTR,b,short,c)
 Fc(int,GetObject,HANDLE,a,int,b,LPSTR,c)
-Fc(int,GetTextFace,HDC,a,int,b,LPSTR,c)
 Fc(int,GetUpdateRgn,HWND,a,HRGN,b,BOOL,c)
 Fc(int,GetWindowText,HWND,a,LPSTR,b,int,c)
 Fc(int,MulDiv,int,a,int,b,int,c)
@@ -2929,7 +2887,7 @@
 Fd(BOOL,GetTextExtentPoint,HDC,a,LPSTR,b,short,c,LPSIZE,d)
 Fd(BOOL,DrawIcon,HDC,a,short,b,short,c,HICON,d)
 Fd(BOOL,EnumMetaFile,HDC,a,LOCALHANDLE,b,FARPROC,c,BYTE FAR*,d)
-Fd(BOOL,FloodFill,HDC,a,short,b,short,c,DWORD,d)
+Fd(BOOL,FloodFill,HDC,a,INT,b,INT,c,COLORREF,d)
 Fd(BOOL,GetCharWidth,HDC,a,WORD,b,WORD,c,LPINT,d)
 Fd(BOOL,HiliteMenuItem,HWND,a,HMENU,b,WORD,c,WORD,d)
 Fd(BOOL,MoveToEx,HDC,a,short,b,short,c,LPPOINT,d)
@@ -2948,8 +2906,8 @@
 Fd(HRGN,CreateEllipticRgn,short,a,short,b,short,c,short,d)
 Fd(HRGN,CreatePolyPolygonRgn,LPPOINT,a,LPINT,b,short,c,short,d)
 Fd(HRGN,CreateRectRgn,short,a,short,b,short,c,short,d)
-Fd(HWND,CreateDialog,HANDLE,a,LPCSTR,b,HWND,c,FARPROC,d)
-Fd(HWND,CreateDialogIndirect,HANDLE,a,LPCSTR,b,HWND,c,FARPROC,d)
+Fd(HWND,CreateDialog,HANDLE,a,LPCSTR,b,HWND,c,WNDPROC,d)
+Fd(HWND,CreateDialogIndirect,HANDLE,a,LPCSTR,b,HWND,c,WNDPROC,d)
 Fd(LONG,DefDlgProc,HWND,a,WORD,b,WORD,c,LONG,d)
 Fd(LONG,DefMDIChildProc,HWND,a,WORD,b,WORD,c,LONG,d)
 Fd(LONG,DefWindowProc,HWND,a,WORD,b,WORD,c,LONG,d)
@@ -2966,8 +2924,8 @@
 Fd(BOOL,OffsetViewportOrgEx,HDC,a,short,b,short,c,LPPOINT,d)
 Fd(BOOL,OffsetWindowOrgEx,HDC,a,short,b,short,c,LPPOINT,d)
 Fd(int,CombineRgn,HRGN,a,HRGN,b,HRGN,c,short,d)
-Fd(int,DialogBox,HINSTANCE,a,LPCSTR,b,HWND,c,FARPROC,d)
-Fd(int,DialogBoxIndirect,HANDLE,a,HANDLE,b,HWND,c,FARPROC,d)
+Fd(int,DialogBox,HINSTANCE,a,LPCSTR,b,HWND,c,WNDPROC,d)
+Fd(int,DialogBoxIndirect,HANDLE,a,HANDLE,b,HWND,c,WNDPROC,d)
 Fd(int,EnumFonts,HDC,a,LPSTR,b,FARPROC,c,LPSTR,d)
 Fd(int,EnumObjects,HDC,a,int,b,FARPROC,c,LPSTR,d)
 Fd(int,GetDlgItemText,HWND,a,WORD,b,LPSTR,c,WORD,d)
@@ -2989,10 +2947,10 @@
 Fe(BOOL,Rectangle,HDC,a,int,xLeft,int,yTop,int,xRight,int,yBottom)
 Fe(int,DrawText,HDC,a,LPSTR,str,int,c,LPRECT,d,WORD,flag)
 Fe(BOOL,PeekMessage,LPMSG,a,HWND,b,WORD,c,WORD,d,WORD,e)
-Fe(LONG,CallWindowProc,FARPROC,a,HWND,b,WORD,c,WORD,d,LONG,e)
+Fe(LONG,CallWindowProc,WNDPROC,a,HWND,b,WORD,c,WORD,d,LONG,e)
 Fe(BOOL,ChangeMenu,HMENU,a,WORD,b,LPSTR,c,WORD,d,WORD,e)
 Fe(BOOL,Ellipse,HDC,a,int,b,int,c,int,d,int,e)
-Fe(BOOL,ExtFloodFill,HDC,a,int,b,int,c,DWORD,d,WORD,e)
+Fe(BOOL,ExtFloodFill,HDC,a,INT,b,INT,c,COLORREF,d,WORD,e)
 Fe(BOOL,FrameRgn,HDC,a,HRGN,b,HBRUSH,e,int,c,int,d)
 Fe(BOOL,InsertMenu,HMENU,a,WORD,b,WORD,c,WORD,d,LPSTR,e)
 Fe(BOOL,ModifyMenu,HMENU,a,WORD,b,WORD,c,WORD,d,LPSTR,e)
@@ -3002,12 +2960,12 @@
 Fe(DWORD,ScaleViewportExt,HDC,a,short,b,short,c,short,d,short,e)
 Fe(DWORD,ScaleWindowExt,HDC,a,short,b,short,c,short,d,short,e)
 Fe(HBITMAP,CreateBitmap,short,a,short,b,BYTE,c,BYTE,d,LPSTR,e)
-Fe(HWND,CreateDialogIndirectParam,HANDLE,a,LPCSTR,b,HWND,c,FARPROC,d,LPARAM,e)
-Fe(HWND,CreateDialogParam,HANDLE,a,LPCSTR,b,HWND,c,FARPROC,d,LPARAM,e)
+Fe(HWND,CreateDialogIndirectParam,HANDLE,a,LPCSTR,b,HWND,c,WNDPROC,d,LPARAM,e)
+Fe(HWND,CreateDialogParam,HANDLE,a,LPCSTR,b,HWND,c,WNDPROC,d,LPARAM,e)
 Fe(LONG,DefFrameProc,HWND,a,HWND,b,WORD,c,WORD,d,LONG,e)
 Fe(LONG,SendDlgItemMessage,HWND,a,WORD,b,WORD,c,WORD,d,LONG,e)
-Fe(int,DialogBoxIndirectParam,HANDLE,a,HANDLE,b,HWND,c,FARPROC,d,LONG,e)
-Fe(int,DialogBoxParam,HANDLE,a,LPCSTR,b,HWND,c,FARPROC,d,LONG,e)
+Fe(int,DialogBoxIndirectParam,HANDLE,a,HANDLE,b,HWND,c,WNDPROC,d,LONG,e)
+Fe(int,DialogBoxParam,HANDLE,a,LPCSTR,b,HWND,c,WNDPROC,d,LONG,e)
 Fe(int,DlgDirList,HWND,a,LPSTR,b,int,c,int,d,WORD,e)
 Fe(int,DlgDirListComboBox,HWND,a,LPSTR,b,int,c,int,d,WORD,e)
 Fe(int,Escape,HDC,a,int,b,int,c,LPSTR,d,LPSTR,e)
@@ -3041,7 +2999,7 @@
 Fg(int,SetDIBits,HDC,a,HANDLE,a2,WORD,b,WORD,c,LPSTR,d,LPBITMAPINFO,e,WORD,f)
 Fg(BOOL,SetWindowPos,HWND,a,HWND,b,short,c,short,d,short,e,short,f,WORD,g)
 Fh(BOOL,ExtTextOut,HDC,a,short,b,short,c,WORD,d,LPRECT,e,LPSTR,f,WORD,g,LPINT,h)
-Fh(HANDLE,DeferWindowPos,HANDLE,hWinPosInfo,HWND,hWnd,HWND,hWndInsertAfter,int,x,int,y,int,cx,int,cy,WORD,wFlags)
+Fh(HDWP,DeferWindowPos,HDWP,hWinPosInfo,HWND,hWnd,HWND,hWndInsertAfter,INT,x,INT,y,INT,cx,INT,cy,WORD,wFlags)
 Fh(LONG,TabbedTextOut,HDC,a,short,b,short,c,LPSTR,d,short,e,short,f,LPINT,g,short,h)
 Fh(int,ScrollWindowEx,HWND,a,short,b,short,c,LPRECT,d,LPRECT,e,HRGN,f,LPRECT,g,WORD,h)
 Fi(BOOL,Arc,HDC,a,int,xLeft,int,yTop,int,xRight,int,yBottom,int,xStart,int,yStart,int,xEnd,int,yEnd)
diff --git a/include/winpos.h b/include/winpos.h
new file mode 100644
index 0000000..1353f92
--- /dev/null
+++ b/include/winpos.h
@@ -0,0 +1,21 @@
+/*
+ * *DeferWindowPos() structure and definitions
+ *
+ * Copyright 1994 Alexandre Julliard
+ */
+
+#ifndef WINPOS_H
+#define WINPOS_H
+
+#define DWP_MAGIC  0x5057  /* 'WP' */
+
+typedef struct
+{
+    WORD        actualCount;
+    WORD        suggestedCount;
+    WORD        valid;
+    WORD        wMagic;
+    WINDOWPOS   winPos[1];
+} DWP;
+
+#endif  /* WINPOS_H */
diff --git a/loader/Imakefile b/loader/Imakefile
index b778667..488f6e6 100644
--- a/loader/Imakefile
+++ b/loader/Imakefile
@@ -8,6 +8,9 @@
 	ldtlib.c \
 	main.c \
 	ne_image.c \
+	ne_resource.c \
+	pe_image.c \
+	pe_resource.c \
 	selector.c \
 	signal.c \
 	library.c \
@@ -18,7 +21,6 @@
 
 WineRelocatableTarget($(TOP)/$(MODULE),,$(OBJS))
 DependTarget()
-CleanTarget()
 
 includes::
 
diff --git a/loader/ldtlib.c b/loader/ldtlib.c
index 181c4b1..8266c7f 100644
--- a/loader/ldtlib.c
+++ b/loader/ldtlib.c
@@ -6,6 +6,10 @@
 #include <stdlib.h>
 #include <errno.h>
 #include "autoconf.h"
+#include "stddebug.h"
+/* #define DEBUG_LDT /* */
+/* #undef DEBUG_LDT  /* */
+#include "debug.h"
 
 #ifdef linux
 #include <linux/unistd.h>
@@ -76,12 +80,11 @@
     struct segment_descriptor *sd;
     int ret;
     
-#ifdef DEBUG_LDT
-    printf("set_ldt_entry: entry=%x base=%x limit=%x%s %s-bit contents=%d %s\n",
-           entry, base, limit, limit_in_pages_flag?"-pages":"",
-           seg_32bit_flag?"32":"16",
-           contents, read_only_flag?"read-only":"");
-#endif
+    dprintf_ldt(stddeb,
+	  "set_ldt_entry: entry=%x base=%x limit=%x%s %s-bit contents=%d %s\n",
+          entry, base, limit, limit_in_pages_flag?"-pages":"",
+          seg_32bit_flag?"32":"16",
+          contents, read_only_flag?"read-only":"");
 
     sd = make_sd(base, limit, contents, read_only_flag, seg_32bit_flag, limit_in_pages_flag);
     ret = i386_set_ldt(entry, (union descriptor *)sd, 1);
diff --git a/loader/library.c b/loader/library.c
index 2ceb59d..ea6f623 100644
--- a/loader/library.c
+++ b/loader/library.c
@@ -1,11 +1,8 @@
 /*
- *        Modules & Libraries functions
+ *        Module & Library functions
  */
-static char Copyright[] = "Copyright  Martin Ayotte, 1994";
+static char Copyright[] = "Copyright 1993, 1994 Martin Ayotte, Robert J. Amstadt, Erik Bos";
 
-/*
-#define DEBUG_MODULE
-*/
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -13,18 +10,31 @@
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <unistd.h>
+#include "neexe.h"
+#include "segmem.h"
+#include "dlls.h"
 #include "wine.h"
+#include "wineopts.h"
+#include "arch.h"
+#include "options.h"
 #include "prototypes.h"
 #include "windows.h"
-#include "dlls.h"
 #include "task.h"
 #include "toolhelp.h"
+#include "stddebug.h"
+/* #define DEBUG_MODULE /* */
+/* #undef DEBUG_MODULE  /* */
+#include "debug.h"
 
-extern struct  w_files *wine_files;
+extern char WindowsPath[256];
 extern struct dll_name_table_entry_s dll_builtin_table[];
+extern char *GetDosFileName(char *);
 
-struct w_files *GetFileInfo(HANDLE);
-char *GetDosFileName(char *);
+extern HANDLE hSysRes;
+
+struct w_files *wine_files = NULL;
+static char *DLL_Extensions[] = { "dll", NULL };
+static char *EXE_Extensions[] = { "exe", NULL };
 
 #define IS_BUILTIN_DLL(handle) ((handle >> 8) == 0xff) 
 
@@ -48,6 +58,196 @@
 	}
 }
 
+struct w_files *
+GetFileInfo(unsigned short instance)
+{
+    register struct w_files *w = wine_files;
+
+    while (w && w->hinstance != instance)
+	w = w->next;
+    
+    return w;
+}
+
+int IsDLLLoaded(char *name)
+{
+	struct w_files *wpnt;
+
+	if(FindDLLTable(name))
+		return 1;
+
+	for(wpnt = wine_files; wpnt; wpnt = wpnt->next)
+		if(strcmp(wpnt->name, name) == 0)
+			return 1;
+
+	return 0;
+}
+
+void InitDLL(struct w_files *wpnt)
+{
+	if (wpnt->ne) 
+		InitNEDLL(wpnt);
+	else
+		InitPEDLL(wpnt);
+}
+
+void InitializeLoadedDLLs(struct w_files *wpnt)
+{
+    static flagReadyToRun = 0;
+    struct w_files *final_wpnt;
+
+    printf("InitializeLoadedDLLs %08X\n", wpnt);
+
+    if (wpnt == NULL)
+    {
+	flagReadyToRun = 1;
+	fprintf(stderr, "Initializing DLLs\n");
+    }
+    
+    if (!flagReadyToRun)
+	return;
+
+#if 1
+    if (wpnt != NULL)
+	fprintf(stderr, "Initializing %s\n", wpnt->name);
+#endif
+
+    /*
+     * Initialize libraries
+     */
+    if (!wpnt)
+    {
+	wpnt = wine_files;
+	final_wpnt = NULL;
+    }
+    else
+    {
+	final_wpnt = wpnt->next;
+    }
+    
+    for( ; wpnt != final_wpnt; wpnt = wpnt->next)
+	InitDLL(wpnt);
+}
+
+/**********************************************************************
+ *			LoadImage
+ * Load one executable into memory
+ */
+HINSTANCE LoadImage(char *module, int filetype, int change_dir)
+{
+    HINSTANCE handle;
+    struct w_files *wpnt, *wpnt1;
+    char buffer[256], header[2], modulename[64], *fullname;
+
+    ExtractDLLName(module, modulename);
+    printf("LoadImage [%s]\n", module);
+    /* built-in one ? */
+    if (FindDLLTable(modulename)) {
+	return GetModuleHandle(modulename);
+    }
+    
+    /* already loaded ? */
+    for (wpnt = wine_files ; wpnt ; wpnt = wpnt->next)
+    	if (strcasecmp(wpnt->name, modulename) == 0)
+    		return wpnt->hinstance;
+
+    /*
+     * search file
+     */
+    fullname = FindFile(buffer, sizeof(buffer), module, 
+			(filetype == EXE ? EXE_Extensions : DLL_Extensions), 
+			WindowsPath);
+    if (fullname == NULL)
+    {
+    	fprintf(stderr, "LoadImage: I can't find %s.dll | %s.exe !\n",
+		module, module);
+	return 2;
+    }
+
+    fullname = GetDosFileName(fullname);
+    
+    fprintf(stderr,"LoadImage: loading %s (%s)\n           [%s]\n", 
+	    module, buffer, fullname);
+
+    if (change_dir && fullname)
+    {
+	char dirname[256];
+	char *p;
+
+	strcpy(dirname, fullname);
+	p = strrchr(dirname, '\\');
+	*p = '\0';
+
+	DOS_SetDefaultDrive(dirname[0] - 'A');
+	DOS_ChangeDir(dirname[0] - 'A', dirname + 2);
+    }
+
+    /* First allocate a spot to store the info we collect, and add it to
+     * our linked list if we could load the file.
+     */
+
+    wpnt = (struct w_files *) malloc(sizeof(struct w_files));
+
+    /*
+     * Open file for reading.
+     */
+    wpnt->fd = open(buffer, O_RDONLY);
+    if (wpnt->fd < 0)
+	return 2;
+
+    /* 
+     * Establish header pointers.
+     */
+    wpnt->filename = strdup(buffer);
+    wpnt->name = strdup(modulename);
+
+    /* read mz header */
+    wpnt->mz_header = (struct mz_header_s *) malloc(sizeof(struct mz_header_s));;
+    lseek(wpnt->fd, 0, SEEK_SET);
+    if (read(wpnt->fd, wpnt->mz_header, sizeof(struct mz_header_s)) !=
+	sizeof(struct mz_header_s))
+    {
+	myerror("Unable to read MZ header from file");
+    }
+    if (wpnt->mz_header->must_be_0x40 != 0x40)
+	myerror("This is not a Windows program");
+
+    /* read first two bytes to determine filetype */
+    lseek(wpnt->fd, wpnt->mz_header->ne_offset, SEEK_SET);
+    read(wpnt->fd, &header, sizeof(header));
+
+    handle = 0;
+    if (header[0] == 'N' && header[1] == 'E')
+    	handle = LoadNEImage(wpnt);
+    if (header[0] == 'P' && header[1] == 'E')
+	handle = LoadPEImage(wpnt);
+    wpnt->hinstance = handle;
+
+    if (handle > 32) {
+	/* ok, loaded, add to the end of the list */
+	if(wine_files == NULL)
+		wine_files = wpnt;
+	else {
+		wpnt1 = wine_files;
+		while(wpnt1->next)
+			wpnt1 =  wpnt1->next;
+		wpnt1->next  = wpnt;
+	}
+	wpnt->next = NULL;
+
+	return handle;
+    } else {
+	fprintf(stderr, "wine: (%s) unknown fileformat !\n", wpnt->filename);
+
+	close(wpnt->fd);
+	free(wpnt->filename);
+	free(wpnt->name);
+	free(wpnt);
+
+	return 14;
+    }
+}
+
 /**********************************************************************
  *				GetModuleHandle	[KERNEL.47]
  */
@@ -174,22 +374,27 @@
 	return h;
 }
 
-
 /**********************************************************************
  *				FreeLibrary	[KERNEL.96]
  */
 void FreeLibrary(HANDLE hLib)
 {
-    printf("FreeLibrary(%04X);\n", hLib);
+	struct w_files *wpnt;
+	printf("FreeLibrary(%04X);\n", hLib);
 
 	/* built-in dll ? */
-	if (IS_BUILTIN_DLL(hLib)) 
+	if (IS_BUILTIN_DLL(hLib) || hLib == 0 || hLib == hSysRes) 
 	    	return;
 
 /*
 	while (lpMod != NULL) {
 		if (lpMod->hInst == hLib) {
 			if (lpMod->Count == 1) {
+				wpnt = GetFileInfo(hLib);
+				if (wpnt->ne)
+					NEunloadImage(wpnt);
+				else
+					PEunloadImage(wpnt);
 				if (hLib != (HANDLE)NULL) GlobalFree(hLib);
 				if (lpMod->ModuleName != NULL) free(lpMod->ModuleName);
 				if (lpMod->FileName != NULL) free(lpMod->FileName);
@@ -215,7 +420,7 @@
 #ifdef WINELIB
     WINELIB_UNIMP ("GetProcAddress");
 #else
-    int		i, sel, addr, ret;
+    int		sel, addr, ret;
     register struct w_files *w = wine_files;
     int 	ordinal, len;
     char 	* cpnt;
@@ -275,11 +480,11 @@
     {
 	AnsiUpper(proc_name);
 	printf("GetProcAddress: %04X, '%s'\n", hModule, proc_name);
-	cpnt = w->nrname_table;
+	cpnt = w->ne->nrname_table;
 	while(TRUE) 
 	{
-	    if (((int) cpnt)  - ((int)w->nrname_table) >  
-		w->ne_header->nrname_tab_length)  return NULL;
+	    if (((int) cpnt)  - ((int)w->ne->nrname_table) >  
+		w->ne->ne_header->nrname_tab_length)  return NULL;
 	    len = *cpnt++;
 	    strncpy(C, cpnt, len);
 	    C[len] = '\0';
@@ -343,24 +548,24 @@
 }
 
 /**********************************************************************
- *		ModuleFirst [TOOHELP.59]
+ *		ModuleFirst [TOOLHELP.59]
  */
 BOOL ModuleFirst(MODULEENTRY *lpModule)
 {
-	printf("ModuleFirst(%08X)\n", lpModule);
+	printf("ModuleFirst(%08X)\n", (int) lpModule);
 	
 	FillModStructBuiltIn(lpModule, &dll_builtin_table[0]);
 	return TRUE;
 }
 
 /**********************************************************************
- *		ModuleNext [TOOHELP.60]
+ *		ModuleNext [TOOLHELP.60]
  */
 BOOL ModuleNext(MODULEENTRY *lpModule)
 {
 	struct w_files *w;
 
-	printf("ModuleNext(%08X)\n", lpModule);
+	printf("ModuleNext(%08X)\n", (int) lpModule);
 
 	if (IS_BUILTIN_DLL(lpModule->hModule)) {
 		/* last built-in ? */
@@ -383,13 +588,13 @@
 }
 
 /**********************************************************************
- *		ModuleFindHandle [TOOHELP.62]
+ *		ModuleFindHandle [TOOLHELP.62]
  */
 HMODULE ModuleFindHandle(MODULEENTRY *lpModule, HMODULE hModule)
 {
 	struct w_files *w;
 
-	printf("ModuleFindHandle(%08X, %04X)\n", lpModule, hModule);
+	printf("ModuleFindHandle(%08X, %04X)\n", (int) lpModule, (int)hModule);
 
 	/* built-in dll ? */
 	if (IS_BUILTIN_DLL(hModule)) {
@@ -406,7 +611,7 @@
 }
 
 /**********************************************************************
- *		ModuleFindName [TOOHELP.61]
+ *		ModuleFindName [TOOLHELP.61]
  */
 HMODULE ModuleFindName(MODULEENTRY *lpModule, LPCSTR lpstrName)
 {
diff --git a/loader/main.c b/loader/main.c
index c1991d0..eefa3c1 100644
--- a/loader/main.c
+++ b/loader/main.c
@@ -9,12 +9,6 @@
 #include <unistd.h>
 #include <string.h>
 #include <errno.h>
-#ifdef linux
-#include <linux/unistd.h>
-#include <linux/head.h>
-#include <linux/ldt.h>
-#include <linux/segment.h>
-#endif
 #include "neexe.h"
 #include "segmem.h"
 #include "prototypes.h"
@@ -23,32 +17,22 @@
 #include "windows.h"
 #include "wineopts.h"
 #include "arch.h"
+#include "task.h"
 #include "options.h"
+#include "stddebug.h"
+/* #define DEBUG_DLL /* */
+/* #undef  DEBUG_DLL /* */
+#include "debug.h"
 
-/* #define DEBUG_FIXUP */
-
-extern HANDLE CreateNewTask(HINSTANCE hInst);
-extern int CallToInit16(unsigned long csip, unsigned long sssp, 
-			unsigned short ds);
-extern void CallTo32();
 
 char *GetDosFileName(char *unixfilename);
-char *GetModuleName(struct w_files * wpnt, int index, char *buffer);
-extern unsigned char ran_out;
 extern char WindowsPath[256];
-char *WIN_ProgramName;
-
-unsigned short WIN_StackSize;
-unsigned short WIN_HeapSize;
-
-struct  w_files * wine_files = NULL;
 
 char **Argv;
 int Argc;
 HINSTANCE hSysRes;
-
-static char *DLL_Extensions[] = { "dll", NULL };
-static char *EXE_Extensions[] = { "exe", NULL };
+unsigned short WIN_StackSize;
+unsigned short WIN_HeapSize;
 
 /**********************************************************************
  *					myerror
@@ -64,195 +48,19 @@
     exit(1);
 }
 
-/**********************************************************************
- *					GetFilenameFromInstance
- */
-char *
-GetFilenameFromInstance(unsigned short instance)
-{
-    register struct w_files *w = wine_files;
-
-    while (w && w->hinstance != instance)
-	w = w->next;
-    
-    if (w)
-	return w->filename;
-    else
-	return NULL;
-}
-
-struct w_files *
-GetFileInfo(unsigned short instance)
-{
-    register struct w_files *w = wine_files;
-
-    while (w && w->hinstance != instance)
-	w = w->next;
-    
-    return w;
-}
-
-#ifndef WINELIB
-/**********************************************************************
- *
- * Load MZ Header
- */
-void load_mz_header(int fd, struct mz_header_s *mz_header)
-{
-    if (read(fd, mz_header, sizeof(struct mz_header_s)) !=
-	sizeof(struct mz_header_s))
-    {
-	myerror("Unable to read MZ header from file");
-    }
-}
-#endif
-
-int IsDLLLoaded(char *name)
-{
-	struct w_files *wpnt;
-
-	if(FindDLLTable(name))
-		return 1;
-
-	for(wpnt = wine_files; wpnt; wpnt = wpnt->next)
-		if(strcmp(wpnt->name, name) == 0)
-			return 1;
-
-	return 0;
-}
-
-/**********************************************************************
- *			LoadImage
- * Load one executable into memory
- */
-HINSTANCE LoadImage(char *module, int filetype, int change_dir)
-{
-    unsigned int read_size;
-    int i;
-    struct w_files * wpnt, *wpnt1;
-    unsigned int status;
-    char buffer[256], header[2], modulename[64], *fullname;
-
-    ExtractDLLName(module, modulename);
-    printf("%sLoadImage \n", module);
-    /* built-in one ? */
-    if (FindDLLTable(modulename)) {
-	return GetModuleHandle(modulename);
-    }
-    
-    /* already loaded ? */
-    for (wpnt = wine_files ; wpnt ; wpnt = wpnt->next)
-    	if (strcasecmp(wpnt->name, modulename) == 0)
-    		return wpnt->hinstance;
-
-    /*
-     * search file
-     */
-    fullname = FindFile(buffer, sizeof(buffer), module, 
-			(filetype == EXE ? EXE_Extensions : DLL_Extensions), 
-			WindowsPath);
-    if (fullname == NULL)
-    {
-    	fprintf(stderr, "LoadImage: I can't find %s.dll | %s.exe !\n",
-		module, module);
-	return 2;
-    }
-
-    fullname = GetDosFileName(fullname);
-    WIN_ProgramName = strdup(fullname);
-    
-    fprintf(stderr,"LoadImage: loading %s (%s)\n           [%s]\n", 
-	    module, buffer, WIN_ProgramName);
-
-    if (change_dir && fullname)
-    {
-	char dirname[256];
-	char *p;
-
-	strcpy(dirname, fullname);
-	p = strrchr(dirname, '\\');
-	*p = '\0';
-
-	DOS_SetDefaultDrive(dirname[0] - 'A');
-	DOS_ChangeDir(dirname[0] - 'A', dirname + 2);
-    }
-
-    /* First allocate a spot to store the info we collect, and add it to
-     * our linked list.
-     */
-
-    wpnt = (struct w_files *) malloc(sizeof(struct w_files));
-    if(wine_files == NULL)
-      wine_files = wpnt;
-    else {
-      wpnt1 = wine_files;
-      while(wpnt1->next) wpnt1 =  wpnt1->next;
-      wpnt1->next  = wpnt;
-    };
-    wpnt->next = NULL;
-    wpnt->resnamtab = (RESNAMTAB *) -1;
-
-    /*
-     * Open file for reading.
-     */
-    wpnt->fd = open(buffer, O_RDONLY);
-    if (wpnt->fd < 0)
-	return 2;
-
-    /* 
-     * Establish header pointers.
-     */
-    wpnt->filename = strdup(buffer);
-    wpnt->name = strdup(modulename);
-
-/*    if(module) {
-    	wpnt->name = strdup(module);
-	ToDos(wpnt->name);
-    }*/
-
-    /* read mz header */
-    wpnt->mz_header = (struct mz_header_s *) malloc(sizeof(struct mz_header_s));;
-    status = lseek(wpnt->fd, 0, SEEK_SET);
-    load_mz_header (wpnt->fd, wpnt->mz_header);
-    if (wpnt->mz_header->must_be_0x40 != 0x40 &&
-	wpnt->mz_header->must_be_0x40 != 0x1e)
-	myerror("This is not a Windows program");
-
-    /* read first two bytes to determine filetype */
-    status = lseek(wpnt->fd, wpnt->mz_header->ne_offset, SEEK_SET);
-    read(wpnt->fd, &header, sizeof(header));
-
-    if (header[0] == 'N' && header[1] == 'E')
-	return (LoadNEImage(wpnt));
-
-    if (header[0] == 'P' && header[1] == 'E') {
-      printf("win32 applications are not supported");
-      return 14;
-    }
-
-    fprintf(stderr, "wine: (%s) unknown fileformat !\n", wpnt->filename);
-
-    return 14;
-}
-
 #ifndef WINELIB
 /**********************************************************************
  *					main
  */
 int _WinMain(int argc, char **argv)
 {
-	int segment;
-	char *p;
-	char *sysresname;
-	char filename[256];
+	char *p, filename[256];
 	HANDLE		hTaskMain;
 	HINSTANCE	hInstMain;
+	struct w_files *wpnt;
 #ifdef WINESTAT
 	char * cp;
 #endif
-	struct w_files * wpnt;
-	int cs_reg, ds_reg, ss_reg, ip_reg, sp_reg;
-	int rv;
 
 	Argc = argc - 1;
 	Argv = argv + 1;
@@ -274,7 +82,7 @@
 		fprintf(stderr, "wine: can't load %s!.\n", Argv[0]);
 		exit(1);
 	}
-	hTaskMain = CreateNewTask(hInstMain);
+	hTaskMain = CreateNewTask(hInstMain, 0);
 	printf("_WinMain // hTaskMain=%04X hInstMain=%04X !\n", hTaskMain, hInstMain);
 
 	GetPrivateProfileString("wine", "SystemResources", "sysres.dll", 
@@ -285,18 +93,8 @@
 		fprintf(stderr, "wine: can't load %s!.\n", filename);
 		exit(1);
 	} else
- 	    printf("System Resources Loaded // hSysRes='%04X'\n", hSysRes);
+ 	    dprintf_dll(stddeb,"System Resources Loaded // hSysRes='%04X'\n", hSysRes);
 	
-    /*
-     * Fixup references.
-     */
-/*    wpnt = wine_files;
-    for(wpnt = wine_files; wpnt; wpnt = wpnt->next)
-	for (segment = 0; segment < wpnt->ne_header->n_segment_tab; segment++)
-	    if (FixupSegment(wpnt, segment) < 0)
-		myerror("fixup failed.");
-*/
-
 #ifdef WINESTAT
     cp = strrchr(argv[0], '/');
     if(!cp) cp = argv[0];
@@ -312,96 +110,14 @@
      */
     init_wine_signals();
 
-    /*
-     * Fixup stack and jump to start.
-     */
-    WIN_StackSize = wine_files->ne_header->stack_length;
-    WIN_HeapSize = wine_files->ne_header->local_heap_length;
+    wpnt = GetFileInfo(hInstMain);
+    if (Options.debug)
+	wine_debug(0, NULL);
 
-    ds_reg = (wine_files->
-	      selector_table[wine_files->ne_header->auto_data_seg-1].selector);
-    cs_reg = wine_files->selector_table[wine_files->ne_header->cs-1].selector;
-    ip_reg = wine_files->ne_header->ip;
-    ss_reg = wine_files->selector_table[wine_files->ne_header->ss-1].selector;
-    sp_reg = wine_files->ne_header->sp;
-
-    if (Options.debug) wine_debug(0, NULL);
-
-    rv = CallToInit16(cs_reg << 16 | ip_reg, ss_reg << 16 | sp_reg, ds_reg);
-    printf ("rv = %x\n", rv);
-}
-
-void InitDLL(struct w_files *wpnt)
-{
-	int cs_reg, ds_reg, ip_reg, rv;
-	/* 
-	 * Is this a library? 
-	 */
-	if (wpnt->ne_header->format_flags & 0x8000)
-	{
-	    if (!(wpnt->ne_header->format_flags & 0x0001))
-	    {
-		/* Not SINGLEDATA */
-		fprintf(stderr, "Library is not marked SINGLEDATA\n");
-		exit(1);
-	    }
-
-	    ds_reg = wpnt->selector_table[wpnt->
-					  ne_header->auto_data_seg-1].selector;
-	    cs_reg = wpnt->selector_table[wpnt->ne_header->cs-1].selector;
-	    ip_reg = wpnt->ne_header->ip;
-
-	    if (cs_reg) {
-		fprintf(stderr, "Initializing %s, cs:ip %04x:%04x, ds %04x\n", 
-		    wpnt->name, cs_reg, ip_reg, ds_reg);
-	    	    
-		rv = CallTo16(cs_reg << 16 | ip_reg, ds_reg);
-		printf ("rv = %x\n", rv);
-	    } else
-		printf("%s skipped\n", wpnt->name);
-	}
-}
-
-void InitializeLoadedDLLs(struct w_files *wpnt)
-{
-    static flagReadyToRun = 0;
-    struct w_files *final_wpnt;
-
-    printf("InitializeLoadedDLLs %08X\n", wpnt);
-
-    if (wpnt == NULL)
-    {
-	flagReadyToRun = 1;
-	fprintf(stderr, "Initializing DLLs\n");
-    }
-    
-    if (!flagReadyToRun)
-	return;
-
-#if 1
-    if (wpnt != NULL)
-	fprintf(stderr, "Initializing %s\n", wpnt->name);
-#endif
-
-    /*
-     * Initialize libraries
-     */
-    if (!wpnt)
-    {
-	wpnt = wine_files;
-	final_wpnt = NULL;
-    }
+    if (wpnt->ne)
+	StartNEprogram(wpnt);
     else
-    {
-	final_wpnt = wpnt->next;
-    }
-    
-    for( ; wpnt != final_wpnt; wpnt = wpnt->next)
-	InitDLL(wpnt);
-}
-#else /* #ifndef WINELIB */
-void InitDLL(struct w_files *wpnt)
-{
+	StartPEprogram(wpnt);
 }
 
 #endif /* #ifndef WINELIB */
diff --git a/loader/ne_image.c b/loader/ne_image.c
index 4247e6a..03d3b86 100644
--- a/loader/ne_image.c
+++ b/loader/ne_image.c
@@ -7,8 +7,8 @@
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <unistd.h>
+#include <ctype.h>
 #ifdef linux
-#include <linux/unistd.h>
 #include <linux/head.h>
 #include <linux/ldt.h>
 #include <linux/segment.h>
@@ -24,20 +24,23 @@
 #include "wineopts.h"
 #include "arch.h"
 #include "options.h"
-
+#include "stddebug.h"
 /* #define DEBUG_FIXUP /* */
+/* #undef DEBUG_FIXUP  /* */
+#include "debug.h"
 
 extern HANDLE CreateNewTask(HINSTANCE hInst);
+extern void InitializeLoadedDLLs(struct w_files *wpnt);
 extern int CallToInit16(unsigned long csip, unsigned long sssp, 
 			unsigned short ds);
-extern void InitializeLoadedDLLs(struct w_files *wpnt);
-extern void FixupFunctionPrologs(struct w_files * wpnt);
-
-char * GetModuleName(struct w_files * wpnt, int index, char *buffer);
+extern void CallTo32();
 extern char WindowsPath[256];
-char *WIN_ProgramName;
+extern unsigned short WIN_StackSize;
+extern unsigned short WIN_HeapSize;
 
-HINSTANCE hSysRes;
+int FixupSegment(struct w_files *, int);
+void FixupFunctionPrologs(struct w_files *);
+char *GetModuleName(struct w_files * wpnt, int index, char *buffer);
 
 #ifndef WINELIB
 
@@ -61,71 +64,61 @@
 {
     unsigned int read_size, status, segment;
     int i;
-    char buffer[256];
-    char *fullname;
-    HANDLE t;
 
-    wpnt->ne_header = (struct ne_header_s *) malloc(sizeof(struct ne_header_s));
-    status = lseek(wpnt->fd, wpnt->mz_header->ne_offset, SEEK_SET);
-    load_ne_header (wpnt->fd, wpnt->ne_header);
+    wpnt->ne = malloc(sizeof(struct ne_data));
+    wpnt->ne->resnamtab = NULL;
+    wpnt->ne->ne_header = malloc(sizeof(struct ne_header_s));
+    lseek(wpnt->fd, wpnt->mz_header->ne_offset, SEEK_SET);
+    load_ne_header(wpnt->fd, wpnt->ne->ne_header);
 
 #ifndef WINELIB
     /*
      * Create segment selectors.
      */
     status = lseek(wpnt->fd, wpnt->mz_header->ne_offset + 
-		   wpnt->ne_header->segment_tab_offset,
+		   wpnt->ne->ne_header->segment_tab_offset,
 		   SEEK_SET);
-    read_size  = wpnt->ne_header->n_segment_tab *
+    read_size  = wpnt->ne->ne_header->n_segment_tab *
 	sizeof(struct ne_segment_table_entry_s);
-    wpnt->seg_table = (struct ne_segment_table_entry_s *) malloc(read_size);
-    if (read(wpnt->fd, wpnt->seg_table, read_size) != read_size)
+    wpnt->ne->seg_table = (struct ne_segment_table_entry_s *) malloc(read_size);
+    if (read(wpnt->fd, wpnt->ne->seg_table, read_size) != read_size)
 	myerror("Unable to read segment table header from file");
-    wpnt->selector_table = CreateSelectors(wpnt);
-    wpnt->hinstance = (wpnt->
-		       selector_table[wpnt->ne_header->auto_data_seg-1].
+    wpnt->ne->selector_table = CreateSelectors(wpnt);
+    wpnt->hinstance = (wpnt->ne->
+		       selector_table[wpnt->ne->ne_header->auto_data_seg-1].
 		       selector);
 #endif
     /* Get the lookup  table.  This is used for looking up the addresses
        of functions that are exported */
 
-    read_size  = wpnt->ne_header->entry_tab_length;
-    wpnt->lookup_table = (char *) malloc(read_size);
+    read_size  = wpnt->ne->ne_header->entry_tab_length;
+    wpnt->ne->lookup_table = (char *) malloc(read_size);
     lseek(wpnt->fd, wpnt->mz_header->ne_offset + 
-	  wpnt->ne_header->entry_tab_offset, SEEK_SET);
-    if (read(wpnt->fd, wpnt->lookup_table, read_size) != read_size)
+	  wpnt->ne->ne_header->entry_tab_offset, SEEK_SET);
+    if (read(wpnt->fd, wpnt->ne->lookup_table, read_size) != read_size)
 	myerror("Unable to read lookup table header from file");
 
     /* Get the iname table.  This is used for looking up the names
        of functions that are exported */
 
-    status = lseek(wpnt->fd, wpnt->ne_header->nrname_tab_offset,  SEEK_SET);
-    read_size  = wpnt->ne_header->nrname_tab_length;
-    wpnt->nrname_table = (char *) malloc(read_size);
-    if (read(wpnt->fd, wpnt->nrname_table, read_size) != read_size)
+    status = lseek(wpnt->fd, wpnt->ne->ne_header->nrname_tab_offset,  SEEK_SET);
+    read_size  = wpnt->ne->ne_header->nrname_tab_length;
+    wpnt->ne->nrname_table = (char *) malloc(read_size);
+    if (read(wpnt->fd, wpnt->ne->nrname_table, read_size) != read_size)
 	myerror("Unable to read nrname table header from file");
 
     status = lseek(wpnt->fd, wpnt->mz_header->ne_offset + 
-		   wpnt->ne_header->rname_tab_offset,  SEEK_SET);
-    read_size  = wpnt->ne_header->moduleref_tab_offset - 
-	    wpnt->ne_header->rname_tab_offset;
-    wpnt->rname_table = (char *) malloc(read_size);
-    if (read(wpnt->fd, wpnt->rname_table, read_size) != read_size)
+		   wpnt->ne->ne_header->rname_tab_offset,  SEEK_SET);
+    read_size  = wpnt->ne->ne_header->moduleref_tab_offset - 
+	    wpnt->ne->ne_header->rname_tab_offset;
+    wpnt->ne->rname_table = (char *) malloc(read_size);
+    if (read(wpnt->fd, wpnt->ne->rname_table, read_size) != read_size)
 	myerror("Unable to read rname table header from file");
 
-    /* Now get the module name, if the current one is a filename */
-/* nope, name by which dll is loaded is used ! 
-
-    if (strchr(wpnt->name, '\\') || strchr(wpnt->name, '/') ) {
-	wpnt->name  = (char*) malloc(*wpnt->rname_table + 1);
-	memcpy(wpnt->name, wpnt->rname_table+1, *wpnt->rname_table);
-    }
-    wpnt->name[*wpnt->rname_table] =  0;
-*/
     /*
      * Now load any DLLs that  this module refers to.
      */
-    for(i=0; i<wpnt->ne_header->n_mod_ref_tab; i++)
+    for(i=0; i<wpnt->ne->ne_header->n_mod_ref_tab; i++)
     {
       char buff[14];
       GetModuleName(wpnt, i + 1, buff);
@@ -136,7 +129,7 @@
 #ifndef WINELIB
     /* fixup references */
 
-    for (segment = 0; segment < wpnt->ne_header->n_segment_tab; segment++)
+    for (segment = 0; segment < wpnt->ne->ne_header->n_segment_tab; segment++)
 	if (FixupSegment(wpnt, segment) < 0)
 		myerror("fixup failed.");
 
@@ -174,7 +167,7 @@
 {
     int fd = wpnt->fd;
     struct mz_header_s *mz_header = wpnt->mz_header; 
-    struct ne_header_s *ne_header = wpnt->ne_header;
+    struct ne_header_s *ne_header = wpnt->ne->ne_header;
     int length;
     WORD name_offset, status;
     int i;
@@ -194,7 +187,8 @@
 
     /* Module names  are always upper case */
     for(i=0; i<length; i++)
-	    if(buffer[i] >= 'a' && buffer[i] <= 'z')  buffer[i] &= ~0x20;
+    	if (islower(buffer[i]))
+    		buffer[i] = toupper(buffer[i]);
 
     return buffer;
 }
@@ -208,14 +202,13 @@
 FixupSegment(struct w_files * wpnt, int segment_num)
 {
     int fd =  wpnt->fd;
-    struct mz_header_s * mz_header = wpnt->mz_header;
-    struct ne_header_s *ne_header =  wpnt->ne_header;
-    struct ne_segment_table_entry_s *seg_table = wpnt->seg_table;
-    struct segment_descriptor_s *selector_table = wpnt->selector_table;
+    struct mz_header_s *mz_header = wpnt->mz_header;
+    struct ne_header_s *ne_header =  wpnt->ne->ne_header;
+    struct ne_segment_table_entry_s *seg_table = wpnt->ne->seg_table;
+    struct segment_descriptor_s *selector_table = wpnt->ne->selector_table;
     struct relocation_entry_s *rep, *rep1;
     struct ne_segment_table_entry_s *seg;
     struct segment_descriptor_s *sel;
-    struct dll_table_entry_s *dll_table;
     int status;
     unsigned short *sp;
     unsigned int selector, address;
@@ -229,10 +222,8 @@
     seg = &seg_table[segment_num];
     sel = &selector_table[segment_num];
 
-#ifdef DEBUG_FIXUP
-    printf("Segment fixups for %s, segment %d, selector %x\n", 
-	   wpnt->name, segment_num, (int) sel->base_addr >> 16);
-#endif
+    dprintf_fixup(stddeb, "Segment fixups for %s, segment %d, selector %x\n", 
+                  wpnt->name, segment_num, (int) sel->base_addr >> 16);
 
     if ((seg->seg_data_offset == 0) ||
 	!(seg->seg_flags & NE_SEGFLAGS_RELOC_DATA))
@@ -293,10 +284,8 @@
 		return -1;
 	    }
 
-#ifdef DEBUG_FIXUP
-	    printf("%d: %s.%d: %04.4x:%04.4x\n", i + 1, dll_name, ordinal,
-		   selector, address);
-#endif
+	    dprintf_fixup(stddeb,"%d: %s.%d: %04.4x:%04.4x\n", i + 1, 
+		   dll_name, ordinal, selector, address);
 	    break;
 	    
 	  case NE_RELTYPE_NAMEADD:
@@ -328,10 +317,8 @@
 		return -1;
 	    }
 
-#ifdef DEBUG_FIXUP
-	    printf("%d: %s %s.%d: %04.4x:%04.4x\n", i + 1, func_name,
-		   dll_name, ordinal, selector, address);
-#endif
+	    dprintf_fixup(stddeb,"%d: %s %s.%d: %04.4x:%04.4x\n", i + 1, 
+                   func_name, dll_name, ordinal, selector, address);
 	    break;
 	    
 	  case NE_RELTYPE_INTERNAL:
@@ -348,9 +335,8 @@
 		address  = rep->target2;
 	    }
 	    
-#ifdef DEBUG_FIXUP
-	    printf("%d: %04.4x:%04.4x\n", i + 1, selector, address);
-#endif
+	    dprintf_fixup(stddeb,"%d: %04.4x:%04.4x\n", 
+			  i + 1, selector, address);
 	    break;
 
 	  case 7:
@@ -362,19 +348,20 @@
 	     * successfully emulate the coprocessor if it doesn't
 	     * exist.
 	     */
-#ifdef DEBUG_FIXUP
-	    printf("%d: ADDR TYPE %d,  TYPE %d,  OFFSET %04.4x,  ",
+	    dprintf_fixup(stddeb,
+                   "%d: ADDR TYPE %d,  TYPE %d,  OFFSET %04.4x,  ",
 		   i + 1, rep->address_type, rep->relocation_type, 
 		   rep->offset);
-	    printf("TARGET %04.4x %04.4x\n", rep->target1, rep->target2);
-#endif
+	    dprintf_fixup(stddeb,"TARGET %04.4x %04.4x\n", 
+		   rep->target1, rep->target2);
 	    continue;
 	    
 	  default:
-	    fprintf(stderr,"%d: ADDR TYPE %d,  TYPE %d,  OFFSET %04.4x,  ",
+	    dprintf_fixup(stddeb,
+		   "%d: ADDR TYPE %d,  TYPE %d,  OFFSET %04.4x,  ",
 		   i + 1, rep->address_type, rep->relocation_type, 
 		   rep->offset);
-	    fprintf(stderr,"TARGET %04.4x %04.4x\n", 
+	    dprintf_fixup(stddeb,"TARGET %04.4x %04.4x\n", 
 		    rep->target1, rep->target2);
 	    free(rep1);
 	    return -1;
@@ -388,23 +375,21 @@
 	{
 	    if (FindDLLTable(dll_name) == NULL)
 		additive = 2;
-
-	    fprintf(stderr,"%d: ADDR TYPE %d,  TYPE %d,  OFFSET %04.4x,  ",
+	    dprintf_fixup(stddeb,
+		   "%d: ADDR TYPE %d,  TYPE %d,  OFFSET %04.4x,  ",
 		   i + 1, rep->address_type, rep->relocation_type, 
 		   rep->offset);
-	    fprintf(stderr,"TARGET %04.4x %04.4x\n", 
+	    dprintf_fixup(stddeb,"TARGET %04.4x %04.4x\n", 
 		    rep->target1, rep->target2);
-	    fprintf(stderr, "    Additive = %d\n", additive);
+	    dprintf_fixup(stddeb, "    Additive = %d\n", additive);
 	}
 	
 	switch (rep->address_type)
 	{
 	  case NE_RADDR_OFFSET16:
 	    do {
-#ifdef DEBUG_FIXUP
-		printf("    %04.4x:%04.4x:%04.4x OFFSET16\n",
+		dprintf_fixup(stddeb,"    %04.4x:%04.4x:%04.4x OFFSET16\n",
 		       (unsigned long) sp >> 16, (int) sp & 0xFFFF, *sp);
-#endif
 		next_addr = *sp;
 		*sp = (unsigned short) address;
 		if (additive == 2)
@@ -417,10 +402,8 @@
 	    
 	  case NE_RADDR_POINTER32:
 	    do {
-#ifdef DEBUG_FIXUP
-		printf("    %04.4x:%04.4x:%04.4x POINTER32\n",
+		dprintf_fixup(stddeb,"    %04.4x:%04.4x:%04.4x POINTER32\n",
 		       (unsigned long) sp >> 16, (int) sp & 0xFFFF, *sp);
-#endif
 		next_addr = *sp;
 		*sp     = (unsigned short) address;
 		if (additive == 2)
@@ -434,10 +417,8 @@
 	    
 	  case NE_RADDR_SELECTOR:
 	    do {
-#ifdef DEBUG_FIXUP
-		printf("    %04.4x:%04.4x:%04.4x SELECTOR\n",
+		dprintf_fixup(stddeb,"    %04.4x:%04.4x:%04.4x SELECTOR\n",
 		       (unsigned long) sp >> 16, (int) sp & 0xFFFF, *sp);
-#endif
 		next_addr = *sp;
 		*sp     = (unsigned short) selector;
 		sp = (unsigned short *) ((char *) sel->base_addr + next_addr);
@@ -449,10 +430,12 @@
 	    break;
 	    
 	  default:
-	    printf("%d: ADDR TYPE %d,  TYPE %d,  OFFSET %04.4x,  ",
+	    dprintf_fixup(stddeb,
+		   "%d: ADDR TYPE %d,  TYPE %d,  OFFSET %04.4x,  ",
 		   i + 1, rep->address_type, rep->relocation_type, 
 		   rep->offset);
-	    printf("TARGET %04.4x %04.4x\n", rep->target1, rep->target2);
+	    dprintf_fixup(stddeb,
+		   "TARGET %04.4x %04.4x\n", rep->target1, rep->target2);
 	    free(rep1);
 	    return -1;
 	}
@@ -462,4 +445,60 @@
     return 0;
 }
 
+int NEunloadImage(struct w_files *wpnt)
+{
+	printf("NEunloadImage() called!\n");
+	/* free resources, image */
+	return 1;
+}
+
+int StartNEprogram(struct w_files *wpnt)
+{
+    int cs_reg, ds_reg, ss_reg, ip_reg, sp_reg;
+    /*
+     * Fixup stack and jump to start. 
+     */
+    WIN_StackSize = wpnt->ne->ne_header->stack_length;
+    WIN_HeapSize = wpnt->ne->ne_header->local_heap_length;
+
+    ds_reg = wpnt->ne->selector_table[wpnt->ne->ne_header->auto_data_seg-1].selector;
+    cs_reg = wpnt->ne->selector_table[wpnt->ne->ne_header->cs-1].selector;
+    ip_reg = wpnt->ne->ne_header->ip;
+    ss_reg = wpnt->ne->selector_table[wpnt->ne->ne_header->ss-1].selector;
+    sp_reg = wpnt->ne->ne_header->sp;
+
+    return CallToInit16(cs_reg << 16 | ip_reg, ss_reg << 16 | sp_reg, ds_reg);
+}
+
+void InitNEDLL(struct w_files *wpnt)
+{
+	int cs_reg, ds_reg, ip_reg, rv;
+	/* 
+	 * Is this a library? 
+	 */
+	if (wpnt->ne->ne_header->format_flags & 0x8000)
+	{
+	    if (!(wpnt->ne->ne_header->format_flags & 0x0001))
+	    {
+		/* Not SINGLEDATA */
+		fprintf(stderr, "Library is not marked SINGLEDATA\n");
+		exit(1);
+	    }
+
+	    ds_reg = wpnt->ne->selector_table[wpnt->ne->
+					  ne_header->auto_data_seg-1].selector;
+	    cs_reg = wpnt->ne->selector_table[wpnt->ne->ne_header->cs-1].selector;
+	    ip_reg = wpnt->ne->ne_header->ip;
+
+	    if (cs_reg) {
+		fprintf(stderr, "Initializing %s, cs:ip %04x:%04x, ds %04x\n", 
+		    wpnt->name, cs_reg, ip_reg, ds_reg);
+	    	    
+		rv = CallTo16(cs_reg << 16 | ip_reg, ds_reg);
+		printf ("rv = %x\n", rv);
+	    } else
+		printf("%s skipped\n", wpnt->name);
+	}
+}
+
 #endif /* !WINELIB */
diff --git a/loader/ne_resource.c b/loader/ne_resource.c
new file mode 100644
index 0000000..25e0b4c
--- /dev/null
+++ b/loader/ne_resource.c
@@ -0,0 +1,499 @@
+static char RCSId[] = "$Id: ne_resource.c,v 1.4 1993/07/04 04:04:21 root Exp root $";
+static char Copyright[] = "Copyright  Robert J. Amstadt, 1993";
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include "windows.h"
+#include "neexe.h"
+#include "peexe.h"
+#include "arch.h"
+#include "dlls.h"
+#include "resource.h"
+
+/* #define DEBUG_RESOURCE */
+
+static int ResourceFd = -1;
+static HANDLE ResourceInst = 0;
+static struct w_files *ResourceFileInfo;
+
+/**********************************************************************
+ *			RSC_LoadNameTable
+ */
+void RSC_LoadNameTable(void)
+{
+    struct resource_typeinfo_s typeinfo;
+    struct resource_nameinfo_s nameinfo;
+    unsigned short             size_shift;
+    RESNAMTAB                 *top, *new;
+    char                       read_buf[1024];
+    char                      *p;
+    int                        i;
+    unsigned short             len;
+    off_t                      rtoff;
+    off_t		       saved_pos;
+    
+    top = NULL;
+
+    /*
+     * Move to beginning of resource table.
+     */
+    rtoff = (ResourceFileInfo->mz_header->ne_offset +
+	     ResourceFileInfo->ne->ne_header->resource_tab_offset);
+    lseek(ResourceFd, rtoff, SEEK_SET);
+    
+    /*
+     * Read block size.
+     */
+    if (read(ResourceFd, &size_shift, sizeof(size_shift)) != 
+	sizeof(size_shift))
+    {
+	return;
+    }
+    size_shift = CONV_SHORT(size_shift);
+
+    /*
+     * Find resource.
+     */
+    typeinfo.type_id = 0xffff;
+    while (typeinfo.type_id != 0) 
+    {
+	if (!load_typeinfo (ResourceFd, &typeinfo))
+	    break;
+
+	if (typeinfo.type_id == 0) 
+	    break;
+	if (typeinfo.type_id == 0x800f) 
+	{
+	    for (i = 0; i < typeinfo.count; i++) 
+	    {
+		if (read(ResourceFd, &nameinfo, sizeof(nameinfo)) != 
+		    sizeof(nameinfo))
+		{
+		    break;
+		}
+		
+		saved_pos = lseek(ResourceFd, 0, SEEK_CUR);
+		lseek(ResourceFd, (long) nameinfo.offset << size_shift, 
+		      SEEK_SET);
+		read(ResourceFd, &len, sizeof(len));
+		while (len)
+		{
+		    new = (RESNAMTAB *) GlobalQuickAlloc(sizeof(*new));
+		    new->next = top;
+		    top = new;
+
+		    read(ResourceFd, &new->type_ord, 2);
+		    read(ResourceFd, &new->id_ord, 2);
+		    read(ResourceFd, read_buf, len - 6);
+		    
+		    p = read_buf + strlen(read_buf) + 1;
+		    strncpy(new->id, p, MAX_NAME_LENGTH);
+		    new->id[MAX_NAME_LENGTH - 1] = '\0';
+
+		    read(ResourceFd, &len, sizeof(len));
+		}
+
+		lseek(ResourceFd, saved_pos, SEEK_SET);
+	    }
+	    break;
+	}
+	else 
+	{
+	    lseek(ResourceFd, (typeinfo.count * sizeof(nameinfo)), SEEK_CUR);
+	}
+    }
+    ResourceFileInfo->ne->resnamtab = top;
+}
+
+/**********************************************************************
+ *					OpenResourceFile
+ */
+int
+OpenResourceFile(HANDLE instance)
+{
+    struct w_files *w;
+    char   *res_file;
+    
+    if (ResourceInst == instance)
+	return ResourceFd;
+
+    w = GetFileInfo(instance);
+    if (w == NULL)
+	return -1;
+    ResourceFileInfo = w;
+    res_file = w->filename;
+    
+    if (ResourceFd >= 0)
+	close(ResourceFd);
+    
+    ResourceInst = instance;
+    ResourceFd   = open (res_file, O_RDONLY);
+#if 1
+#ifndef WINELIB
+    if (w->ne->resnamtab == (RESNAMTAB *) -1)
+    {
+	RSC_LoadNameTable();
+    }
+#endif
+#endif
+
+#ifdef DEBUG_RESOURCE
+    printf("OpenResourceFile(%04X) // file='%s' hFile=%04X !\n", 
+		instance, w->filename, ResourceFd);
+#endif
+    return ResourceFd;
+}
+
+int load_typeinfo (int fd, struct resource_typeinfo_s *typeinfo)
+{
+    return read (fd, typeinfo, sizeof (*typeinfo)) == sizeof (*typeinfo);
+}
+
+int type_match(int type_id1, int type_id2, int fd, off_t off)
+{
+	off_t old_pos;
+	unsigned char c;
+	size_t nbytes;
+	char name[256];
+
+	if (type_id1 == -1)
+		return 1;
+	if ((type_id1 & 0xffff0000) == 0) {
+		if ((type_id2 & 0x8000) == 0)
+			return 0;
+		return (type_id1 & 0x000f) == (type_id2 & 0x000f);
+	}
+	if ((type_id2 & 0x8000) != 0)
+		return 0;
+#ifdef DEBUG_RESOURCE
+	printf("type_compare: type_id2=%04X !\n", type_id2);
+#endif
+	old_pos = lseek(fd, 0, SEEK_CUR);
+	lseek(fd, off + type_id2, SEEK_SET);
+	read(fd, &c, 1);
+	nbytes = CONV_CHAR_TO_LONG (c);
+#ifdef DEBUG_RESOURCE
+	printf("type_compare: namesize=%d\n", nbytes);
+#endif
+	read(fd, name, nbytes);
+	lseek(fd, old_pos, SEEK_SET);
+	name[nbytes] = '\0';
+#ifdef DEBUG_RESOURCE
+	printf("type_compare: name=`%s'\n", name);
+#endif
+	return strcasecmp((char *) type_id1, name) == 0;
+}
+
+/**********************************************************************
+ *					FindResourceByNumber
+ */
+int
+FindResourceByNumber(struct resource_nameinfo_s *result_p,
+		     int type_id, int resource_id)
+{
+    struct resource_typeinfo_s typeinfo;
+    struct resource_nameinfo_s nameinfo;
+    unsigned short size_shift;
+    int i;
+    off_t rtoff;
+
+    /*
+     * Move to beginning of resource table.
+     */
+    rtoff = (ResourceFileInfo->mz_header->ne_offset +
+	     ResourceFileInfo->ne->ne_header->resource_tab_offset);
+    lseek(ResourceFd, rtoff, SEEK_SET);
+    
+    /*
+     * Read block size.
+     */
+    if (read(ResourceFd, &size_shift, sizeof(size_shift)) != 
+	sizeof(size_shift))
+    {
+    	printf("FindResourceByNumber (%d) bad block size !\n",(int) resource_id);
+	return -1;
+    }
+    size_shift = CONV_SHORT(size_shift);
+    /*
+     * Find resource.
+     */
+    for (;;) {
+	if (!load_typeinfo (ResourceFd, &typeinfo)){
+	    printf("FindResourceByNumber (%X) bad typeinfo size !\n", resource_id);
+	    return -1;
+	    }
+#ifdef DEBUG_RESOURCE
+	printf("FindResourceByNumber type=%X count=%d ?=%d searched=%08X\n", 
+		typeinfo.type_id, typeinfo.count, typeinfo.reserved, type_id);
+#endif
+	if (typeinfo.type_id == 0) break;
+	if (type_match(type_id, typeinfo.type_id, ResourceFd, rtoff)) {
+
+	    for (i = 0; i < typeinfo.count; i++) {
+#ifndef WINELIB
+		if (read(ResourceFd, &nameinfo, sizeof(nameinfo)) != 
+		    sizeof(nameinfo))
+#else
+		if (!load_nameinfo (ResourceFd, &nameinfo))
+#endif
+		{
+		    printf("FindResourceByNumber (%X) bad nameinfo size !\n", resource_id);
+		    return -1;
+		    }
+#ifdef DEBUG_RESOURCE
+		printf("FindResource: search type=%X id=%X // type=%X id=%X\n",
+			type_id, resource_id, typeinfo.type_id, nameinfo.id);
+#endif
+		if (nameinfo.id == resource_id) {
+		    memcpy(result_p, &nameinfo, sizeof(nameinfo));
+		    return size_shift;
+		    }
+	        }
+	    }
+	else {
+	    lseek(ResourceFd, (typeinfo.count * sizeof(nameinfo)), SEEK_CUR);
+	    }
+        }
+    return -1;
+}
+
+/**********************************************************************
+ *					FindResourceByName
+ */
+int
+FindResourceByName(struct resource_nameinfo_s *result_p,
+		     int type_id, char *resource_name)
+{
+    struct resource_typeinfo_s typeinfo;
+    struct resource_nameinfo_s nameinfo;
+    unsigned short size_shift;
+    off_t old_pos, new_pos;
+    unsigned char nbytes;
+    char name[256];
+    int i;
+    off_t rtoff;
+
+    /*
+     * Check for loaded name table.
+     */
+    if (ResourceFileInfo->ne->resnamtab != NULL)
+    {
+	RESNAMTAB *e;
+
+	for (e = ResourceFileInfo->ne->resnamtab; e != NULL; e = e->next)
+	{
+	    if (e->type_ord == (type_id & 0x000f) &&
+		strcasecmp(e->id, resource_name) == 0)
+	    {
+		return FindResourceByNumber(result_p, type_id, e->id_ord);
+	    }
+	}
+
+	return -1;
+    }
+
+    /*
+     * Move to beginning of resource table.
+     */
+    rtoff = (ResourceFileInfo->mz_header->ne_offset +
+	     ResourceFileInfo->ne->ne_header->resource_tab_offset);
+    lseek(ResourceFd, rtoff, SEEK_SET);
+    
+    /*
+     * Read block size.
+     */
+    if (read(ResourceFd, &size_shift, sizeof(size_shift)) != 
+	sizeof(size_shift))
+    {
+    	printf("FindResourceByName (%s) bad block size !\n", resource_name);
+	return -1;
+    }
+    size_shift = CONV_SHORT (size_shift);
+    
+    /*
+     * Find resource.
+     */
+    for (;;)
+    {
+	if (!load_typeinfo (ResourceFd, &typeinfo))
+	{
+	    printf("FindResourceByName (%s) bad typeinfo size !\n", resource_name);
+	    return -1;
+	}
+#ifdef DEBUG_RESOURCE
+	printf("FindResourceByName typeinfo.type_id=%X count=%d type_id=%X\n",
+			typeinfo.type_id, typeinfo.count, type_id);
+#endif
+	if (typeinfo.type_id == 0) break;
+	if (type_match(type_id, typeinfo.type_id, ResourceFd, rtoff))
+	{
+	    for (i = 0; i < typeinfo.count; i++)
+	    {
+#ifndef WINELIB
+		if (read(ResourceFd, &nameinfo, sizeof(nameinfo)) != 
+		    sizeof(nameinfo))
+#else
+		if (!load_nameinfo (ResourceFd, &nameinfo))
+#endif
+		{
+		    printf("FindResourceByName (%s) bad nameinfo size !\n", resource_name);
+		    return -1;
+		}
+/*
+		if ((nameinfo.id & 0x8000) != 0) continue;
+*/		
+#ifdef DEBUG_RESOURCE
+		printf("FindResourceByName // nameinfo.id=%04X !\n", nameinfo.id);
+#endif
+		old_pos = lseek(ResourceFd, 0, SEEK_CUR);
+		new_pos = rtoff + nameinfo.id;
+		lseek(ResourceFd, new_pos, SEEK_SET);
+		read(ResourceFd, &nbytes, 1);
+#ifdef DEBUG_RESOURCE
+		printf("FindResourceByName // namesize=%d !\n", nbytes);
+#endif
+ 		nbytes = CONV_CHAR_TO_LONG (nbytes);
+		read(ResourceFd, name, nbytes);
+		lseek(ResourceFd, old_pos, SEEK_SET);
+		name[nbytes] = '\0';
+#ifdef DEBUG_RESOURCE
+		printf("FindResourceByName type_id=%X (%d of %d) name='%s' resource_name='%s'\n", 
+			typeinfo.type_id, i + 1, typeinfo.count, 
+			name, resource_name);
+#endif
+		if (strcasecmp(name, resource_name) == 0)
+		{
+		    memcpy(result_p, &nameinfo, sizeof(nameinfo));
+		    return size_shift;
+		}
+	    }
+	}
+	else {
+	    lseek(ResourceFd, (typeinfo.count * sizeof(nameinfo)), SEEK_CUR);
+	    }
+    }
+    return -1;
+}
+
+
+/**********************************************************************
+ *					GetRsrcCount		[internal]
+ */
+int GetRsrcCount(HINSTANCE hInst, int type_id)
+{
+    struct resource_typeinfo_s typeinfo;
+    struct resource_nameinfo_s nameinfo;
+    unsigned short size_shift;
+    off_t rtoff;
+
+    if (hInst == 0) return 0;
+#ifdef DEBUG_RESOURCE
+    printf("GetRsrcCount hInst=%04X typename=%08X\n", hInst, type_id);
+#endif
+    if (OpenResourceFile(hInst) < 0)	return 0;
+
+    /*
+     * Move to beginning of resource table.
+     */
+    rtoff = (ResourceFileInfo->mz_header->ne_offset +
+	     ResourceFileInfo->ne->ne_header->resource_tab_offset);
+    lseek(ResourceFd, rtoff, SEEK_SET);
+    /*
+     * Read block size.
+     */
+    if (read(ResourceFd, &size_shift, sizeof(size_shift)) != sizeof(size_shift)) {
+		printf("GetRsrcCount // bad block size !\n");
+		return -1;
+		}
+    size_shift = CONV_SHORT (size_shift);
+    for (;;) {
+		if (!load_typeinfo (ResourceFd, &typeinfo))	{
+			printf("GetRsrcCount // bad typeinfo size !\n");
+			return 0;
+			}
+#ifdef DEBUG_RESOURCE
+		printf("GetRsrcCount // typeinfo.type_id=%X count=%d type_id=%X\n",
+				typeinfo.type_id, typeinfo.count, type_id);
+#endif
+		if (typeinfo.type_id == 0) break;
+		if (type_match(type_id, typeinfo.type_id, ResourceFd, rtoff)) {
+			return typeinfo.count;
+			}
+		else {
+			lseek(ResourceFd, (typeinfo.count * sizeof(nameinfo)), SEEK_CUR);
+			}
+		}
+    return 0;
+}
+
+/**********************************************************************
+ *			NE_FindResource	[KERNEL.60]
+ */
+int
+NE_FindResource(HANDLE instance, LPSTR resource_name, LPSTR type_name,
+		RESOURCE *r)
+{
+    int type;
+
+#ifdef DEBUG_RESOURCE
+    printf("NE_FindResource hInst=%04X typename=%08X resname=%08X\n", 
+			instance, type_name, resource_name);
+#endif
+
+    ResourceFd = r->fd;
+    ResourceFileInfo = r->wpnt;
+
+    /* nametable loaded ? */
+    if (r->wpnt->ne->resnamtab == NULL)
+	RSC_LoadNameTable();
+
+    if (((int) type_name & 0xffff0000) == 0)
+    {
+	type = (int) type_name;
+    }
+    else if (type_name[0] == '\0')
+    {
+	type = -1;
+    }
+    else if (type_name[0] == '#')
+    {
+	type = atoi(type_name + 1);
+    }
+    else
+    {
+	type = (int) type_name;
+    }
+    if (((int) resource_name & 0xffff0000) == 0)
+    {
+	r->size_shift = FindResourceByNumber(&r->nameinfo, type,
+					     (int) resource_name | 0x8000);
+    }
+    else if (resource_name[0] == '\0')
+    {
+	r->size_shift = FindResourceByNumber(&r->nameinfo, type, -1);
+    }
+    else if (resource_name[0] == '#')
+    {
+	r->size_shift = FindResourceByNumber(&r->nameinfo, type,
+					     atoi(resource_name + 1));
+    }
+    else
+    {
+	r->size_shift = FindResourceByName(&r->nameinfo, type, resource_name);
+    }
+
+    if (r->size_shift == -1)
+    {
+        printf("NE_FindResource hInst=%04X typename=%08X resname=%08X not found!\n", 
+		instance, (int) type_name, (int) resource_name);
+	return 0;
+    }
+    r->size = r->nameinfo.length << r->size_shift;
+    r->offset = r->nameinfo.offset << r->size_shift;
+    return 1;
+}
diff --git a/loader/pe_image.c b/loader/pe_image.c
new file mode 100644
index 0000000..948e8e6
--- /dev/null
+++ b/loader/pe_image.c
@@ -0,0 +1,213 @@
+/* 
+ *  Copyright	1994	Eric Youndale & Erik Bos
+ *
+ *	based on Eric Youndale's pe-test and:
+ *
+ *	ftp.microsoft.com:/pub/developer/MSDN/CD8/PEFILE.ZIP
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/mman.h>
+#include "windows.h"
+#include "dlls.h"
+#include "neexe.h"
+#include "peexe.h"
+
+#define MAP_ANONYMOUS	0x20
+
+unsigned int load_addr;
+
+void my_wcstombs(char * result, u_short * source, int len)
+{
+  while(len--) {
+    if(isascii(*source)) *result++ = *source++;
+    else {
+      printf("Unable to handle unicode right now\n");
+      exit(0);
+    }
+  };
+}
+
+char * xmmap(char * vaddr, unsigned int v_size, int prot, int flags, 
+	     int fd, unsigned int file_offset)
+{
+  char * result;
+  result = mmap(vaddr, v_size, prot, flags, fd, file_offset);
+  if((unsigned int) result != 0xffffffff) return result;
+
+  /* Sigh.  Alignment must be wrong for mmap.  Do this the hard way. */
+  if(!(flags & MAP_FIXED)) {
+    vaddr = 0x40000000;
+    flags |= MAP_FIXED;
+  };
+
+  mmap(vaddr, v_size, prot, MAP_ANONYMOUS | flags, 0, 0);
+  lseek(fd, file_offset, SEEK_SET);
+  read(fd, vaddr, v_size);
+  return vaddr;
+};
+
+dump_exports(struct PE_Export_Directory * pe_exports)
+{ 
+  char * Module;
+  int i;
+  u_short * ordinal;
+  u_long * function;
+  u_char ** name, *ename;
+
+  Module = ((char *) load_addr) + pe_exports->Name;
+  printf("\n*******EXPORT DATA*******\nModule name is %s, %d functions, %d names\n", 
+	 Module,
+	 pe_exports->Number_Of_Functions,
+	 pe_exports->Number_Of_Names);
+
+  ordinal = (u_short *) (((char *) load_addr) + (int) pe_exports->Address_Of_Name_Ordinals);
+  function = (u_long *)  (((char *) load_addr) + (int) pe_exports->AddressOfFunctions);
+  name = (u_char **)  (((char *) load_addr) + (int) pe_exports->AddressOfNames);
+
+  printf("%-32s Ordinal Virt Addr\n", "Function Name");
+  for(i=0; i< pe_exports->Number_Of_Functions; i++)
+    {
+      ename =  (char *) (((char *) load_addr) + (int) *name++);
+      printf("%-32s %4d    %8.8x\n", ename, *ordinal++, *function++);
+    }
+
+  return;
+}
+
+dump_imports(struct PE_Import_Directory *pe_imports)
+{ 
+  struct PE_Import_Directory * pe_imp;
+
+ /* OK, now dump the import list */
+  printf("\nDumping imports list\n");
+  pe_imp = pe_imports;
+  while (pe_imp->ModuleName)
+    {
+      char * Module, *Function;
+      struct pe_import_name * pe_name;
+      unsigned int * import_list;
+      char * c;
+
+      Module = ((char *) load_addr) + pe_imp->ModuleName;
+      printf("%s\n", Module);
+      c = strchr(Module, '.');
+      if (c) *c = 0;
+
+      import_list = (unsigned int *) 
+	(((unsigned int) load_addr) + pe_imp->Import_List);
+
+      while(*import_list)
+	{
+	  pe_name = (struct pe_import_name *) ((int) load_addr + *import_list);
+	  printf("--- %s %s.%d\n", pe_name->Name, Module, pe_name->Hint);
+	  import_list++;
+	}
+      pe_imp++;
+    };
+}
+
+static void dump_table(struct w_files *wpnt)
+{
+  int i;
+
+  printf("Dump of segment table\n");
+  printf("   Name    VSz  Vaddr     SzRaw   Fileadr  *Reloc *Lineum #Reloc #Linum Char\n");
+  for(i=0; i< wpnt->pe->pe_header->coff.NumberOfSections; i++)
+    {
+      printf("%8s: %4.4x %8.8x %8.8x %8.8x %8.8x %8.8x %4.4x %4.4x %8.8x\n", 
+	     wpnt->pe->pe_seg[i].Name, 
+	     wpnt->pe->pe_seg[i].Virtual_Size,
+	     wpnt->pe->pe_seg[i].Virtual_Address,
+	     wpnt->pe->pe_seg[i].Size_Of_Raw_Data,
+	     wpnt->pe->pe_seg[i].PointerToRawData,
+	     wpnt->pe->pe_seg[i].PointerToRelocations,
+	     wpnt->pe->pe_seg[i].PointerToLinenumbers,
+	     wpnt->pe->pe_seg[i].NumberOfRelocations,
+	     wpnt->pe->pe_seg[i].NumberOfLinenumbers,
+	     wpnt->pe->pe_seg[i].Characteristics);
+    }
+}
+
+/**********************************************************************
+ *			LoadPEImage
+ * Load one PE format executable into memory
+ */
+HINSTANCE LoadPEImage(struct w_files *wpnt)
+{
+	int i, result;
+
+	wpnt->pe = malloc(sizeof(struct pe_data));
+	wpnt->pe->pe_header = malloc(sizeof(struct pe_header_s));
+
+	/* read PE header */
+	lseek(wpnt->fd, wpnt->mz_header->ne_offset, SEEK_SET);
+	read(wpnt->fd, wpnt->pe->pe_header, sizeof(struct pe_header_s));
+
+	/* read sections */
+	wpnt->pe->pe_seg = malloc(sizeof(struct pe_segment_table) * 
+				wpnt->pe->pe_header->coff.NumberOfSections);
+	read(wpnt->fd, wpnt->pe->pe_seg, sizeof(struct pe_segment_table) * 
+			wpnt->pe->pe_header->coff.NumberOfSections);
+
+	load_addr = wpnt->pe->pe_header->opt_coff.BaseOfImage;
+	dump_table(wpnt);
+
+	for(i=0; i < wpnt->pe->pe_header->coff.NumberOfSections; i++)
+	{
+	if(!load_addr) {
+		result = xmmap(0, wpnt->pe->pe_seg[i].Size_Of_Raw_Data, 7, MAP_PRIVATE, 
+		      wpnt->fd, wpnt->pe->pe_seg[i].PointerToRawData);
+		load_addr = (unsigned int) result -  wpnt->pe->pe_seg[i].Virtual_Address;
+	} else {
+		result = xmmap((char *) load_addr + wpnt->pe->pe_seg[i].Virtual_Address, 
+		      wpnt->pe->pe_seg[i].Size_Of_Raw_Data, 7, MAP_PRIVATE | MAP_FIXED, 
+		      wpnt->fd, wpnt->pe->pe_seg[i].PointerToRawData);
+	}
+
+	if(strcmp(wpnt->pe->pe_seg[i].Name, ".idata") == 0)
+		wpnt->pe->pe_import = (struct PE_Import_Directory *) result;
+
+	if(strcmp(wpnt->pe->pe_seg[i].Name, ".edata") == 0)
+		wpnt->pe->pe_export = (struct PE_Export_Directory *) result;
+
+	if(strcmp(wpnt->pe->pe_seg[i].Name, ".rsrc") == 0) {
+	    wpnt->pe->pe_resource = (struct PE_Resource_Directory *) result;
+
+	    /* save offset for PE_FindResource */
+	    wpnt->pe->resource_offset = wpnt->pe->pe_seg[i].Virtual_Address - 
+					wpnt->pe->pe_seg[i].PointerToRawData;
+	    }
+	}
+
+	if(wpnt->pe->pe_import) dump_imports(wpnt->pe->pe_import);
+	if(wpnt->pe->pe_export) dump_exports(wpnt->pe->pe_export);
+  
+	wpnt->hinstance = 0x8000;
+	return (wpnt->hinstance);
+}
+
+int PEunloadImage(struct w_files *wpnt)
+{
+	printf("PEunloadImage() called!\n");
+	/* free resources, image, unmap */
+	return 1;
+}
+
+int StartPEprogram(struct w_files *wpnt)
+{
+	printf("StartPEprogram() called!\n");
+	return 0;
+}
+
+void InitPEDLL(struct w_files *wpnt)
+{
+	/* Is this a library? */
+	if (wpnt->pe->pe_header->coff.Characteristics & IMAGE_FILE_DLL) {
+		printf("InitPEDLL() called!\n");
+	}
+}
diff --git a/loader/pe_resource.c b/loader/pe_resource.c
new file mode 100644
index 0000000..d82789c
--- /dev/null
+++ b/loader/pe_resource.c
@@ -0,0 +1,151 @@
+/*
+ *	(c) 1994	Erik Bos	<erik@hacktic.nl>
+ *
+ *	based on Eric Youndale's pe-test and:
+ *
+ *	ftp.microsoft.com:/pub/developer/MSDN/CD8/PEFILE.ZIP
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include "windows.h"
+#include "neexe.h"
+#include "peexe.h"
+#include "dlls.h"
+#include "resource.h"
+
+#define DEBUG_RESOURCE
+
+static int
+find_lang(char *root, struct PE_Resource_Directory *resource, RESOURCE *r)
+{
+	int i;
+	struct PE_Directory_Entry *type_dir;
+	struct PE_Resource_Leaf_Entry *leaf;
+
+	type_dir = (struct PE_Directory_Entry *)(resource + 1);
+	type_dir += resource->NumberOfNamedEntries;
+
+	/* grab the 1st resource available */
+	leaf = (struct PE_Resource_Leaf_Entry *) (root + type_dir->OffsetToData);
+#ifdef DEBUG_RESOURCE
+		printf("\t\tPE_findlang: id %8x\n", (int) type_dir->Name);
+		printf("\t\taddress %d, size %d, language id %d\n", leaf->OffsetToData, leaf->Size, leaf->CodePage);
+#endif
+	r->offset = leaf->OffsetToData - r->wpnt->pe->resource_offset;
+	r->size = leaf->Size;
+	printf("\t\toffset %d, size %d\n", r->offset, r->size);
+	return 1;
+
+/*	for(i=0; i< resource->NumberOfIdEntries; i++) {
+		leaf = (root + (type_dir->OffsetToData & ~IMAGE_RESOURCE_DATA_IS_DIRECTORY));
+#ifdef DEBUG_RESOURCE
+		printf("\t\tPE_findlang: id %8x\n", (int) type_dir->Name);
+		printf("\t\t%x %x %x\n", leaf->OffsetToData, leaf->Size,
+						leaf->CodePage);
+#endif
+		type_dir++;
+	} */
+}
+
+static int 
+find_resource(char *root, struct PE_Resource_Directory *resource, 
+		LPSTR resource_name, RESOURCE *r)
+{
+	int i;
+	char res_name[256];
+	struct PE_Directory_Entry *type_dir;
+	struct PE_Directory_Name_String_U *name;
+	
+	type_dir = (struct PE_Directory_Entry *)(resource + 1);
+
+	if (HIWORD((DWORD)resource_name)) {
+		for(i=0; i< resource->NumberOfNamedEntries; i++) {
+			name = (struct PE_Directory_Name_String_U *)(root + (type_dir->Name & ~IMAGE_RESOURCE_NAME_IS_STRING));
+			memset(res_name, 0, sizeof(res_name));
+			my_wcstombs(res_name, name->NameString, name->Length);
+#ifdef DEBUG_RESOURCE
+			printf("\tPE_findresource: name %s\n", res_name);
+#endif
+			if (strcasecmp(res_name, resource_name) == 0) 
+				return find_lang(root, (struct PE_Resource_Directory *) (root + (type_dir->OffsetToData & ~IMAGE_RESOURCE_DATA_IS_DIRECTORY)), r);
+			type_dir++;
+		}
+	} else {
+		type_dir += resource->NumberOfNamedEntries;
+		for(i=0; i< resource->NumberOfIdEntries; i++) {
+#ifdef DEBUG_RESOURCE
+			printf("\tPE_findresource: name %8x\n", (int) type_dir->Name);
+#endif
+			if (type_dir->Name == ((int) resource_name & 0xff))
+				return find_lang(root, (struct PE_Resource_Directory *) (root + (type_dir->OffsetToData & ~IMAGE_RESOURCE_DATA_IS_DIRECTORY)), r);
+			type_dir++;
+		}
+	}
+	return 0;
+}
+
+static int 
+find_type(struct PE_Resource_Directory *resource, LPSTR resource_name,
+		LPSTR type_name, RESOURCE *r)
+{
+	int i;
+	char *root, res_name[256];
+	struct PE_Directory_Entry *type_dir;
+	struct PE_Directory_Name_String_U *name;
+	
+	root = (char *) resource;
+	type_dir = (struct PE_Directory_Entry *)(resource + 1);
+
+	if (HIWORD((DWORD)type_name)) {
+		for(i=0; i< resource->NumberOfNamedEntries; i++) {
+			name = (struct PE_Directory_Name_String_U *)(root + (type_dir->Name & ~IMAGE_RESOURCE_NAME_IS_STRING));
+			memset(res_name, 0, sizeof(res_name));
+			my_wcstombs(res_name, name->NameString, name->Length);
+#ifdef DEBUG_RESOURCE
+			printf("PE_findtype: type %s\n", res_name);
+#endif
+			if (strcasecmp(res_name, type_name) == 0) 
+				return find_resource(root, (struct PE_Resource_Directory *) (root + (type_dir->OffsetToData & ~IMAGE_RESOURCE_DATA_IS_DIRECTORY)), resource_name, r);
+			type_dir++;
+		}
+	} else {
+		type_dir += resource->NumberOfNamedEntries;
+		for(i=0; i< resource->NumberOfIdEntries; i++) {
+#ifdef DEBUG_RESOURCE
+			printf("PE_findtype: type %8x\n", (int) type_dir->Name);
+#endif
+			if (type_dir->Name == ((int) type_name & 0xff))
+				return find_resource(root, (struct PE_Resource_Directory *) (root + (type_dir->OffsetToData & ~IMAGE_RESOURCE_DATA_IS_DIRECTORY)), resource_name, r);
+			type_dir++;
+		}
+	}
+	return 0;
+}
+
+/**********************************************************************
+ *			PE_FindResource	[KERNEL.60]
+ */
+int
+PE_FindResource(HANDLE instance, LPSTR resource_name, LPSTR type_name,
+		RESOURCE *r)
+{
+#ifdef DEBUG_RESOURCE
+	printf("PE_FindResource hInst=%04X typename=%08X resname=%08X\n", 
+		instance, (int) type_name, (int) resource_name);
+#endif
+	if (HIWORD((DWORD)resource_name)) 
+		if (resource_name[0] == '#')
+			resource_name = (LPSTR) atoi(resource_name + 1);
+
+	if (HIWORD((DWORD)type_name)) 
+		if (type_name[0] == '#')
+			type_name = (LPSTR) atoi(type_name + 1);
+
+	return find_type(r->wpnt->pe->pe_resource, resource_name, type_name,r);
+}
diff --git a/loader/resource.c b/loader/resource.c
index b69c5f2..867c783 100644
--- a/loader/resource.c
+++ b/loader/resource.c
@@ -8,181 +8,262 @@
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <unistd.h>
-
 #include "arch.h"
 #include "prototypes.h"
 #include "windows.h"
 #include "gdi.h"
 #include "wine.h"
 #include "icon.h"
+#include "menu.h"
 #include "accel.h"
 #include "dlls.h"
-
-/* #define DEBUG_RESOURCE  */
+#include "resource.h"
+#include "stddebug.h"
+/* #define DEBUG_RESOURCE /* */
+/* #undef  DEBUG_RESOURCE /* */
+/* #define DEBUG_ACCEL    /* */
+/* #undef  DEBUG_ACCEL    /* */
+#include "debug.h"
 
 #define MIN(a,b)	((a) < (b) ? (a) : (b))
 
-typedef struct resource_s
-{
-    struct resource_s *next;
-    HANDLE info_mem;
-    int size_shift;
-    struct resource_nameinfo_s nameinfo;
-    HANDLE rsc_mem;
-} RESOURCE;
-
-static int ResourceFd = -1;
-static HANDLE ResourceInst = 0;
-static struct w_files *ResourceFileInfo = NULL;
-static RESOURCE *Top = NULL;
+RESOURCE *Top = NULL;
 extern HINSTANCE hSysRes;
 
+extern int NE_FindResource(HANDLE, LPSTR, LPSTR, RESOURCE *);
+extern int PE_FindResource(HANDLE, LPSTR, LPSTR, RESOURCE *);
 extern HBITMAP BITMAP_LoadOEMBitmap( WORD id );  /* objects/bitmap.c */
 
-HANDLE RSC_LoadResource(int instance, char *rsc_name, int type, 
-			int *image_size_ret);
-void RSC_LoadNameTable(void);
+#define PrintId(name) \
+	if (HIWORD((DWORD)name)) \
+		printf(", %s", name); \
+	else \
+		printf(", #%d", (int) name); 
 
-extern char *ProgramName;
-
-
 /**********************************************************************
- *					RSC_LoadNameTable
+ *			FindResource	[KERNEL.60]
  */
-#ifndef WINELIB
-void 
-RSC_LoadNameTable()
+HANDLE FindResource(HANDLE instance, LPSTR name, LPSTR type)
 {
-    struct resource_typeinfo_s typeinfo;
-    struct resource_nameinfo_s nameinfo;
-    unsigned short             size_shift;
-    RESNAMTAB                 *top, *new;
-    char                       read_buf[1024];
-    char                      *p;
-    int                        i;
-    unsigned short             len;
-    off_t                      rtoff;
-    off_t		       saved_pos;
-    
-    top = NULL;
+	int status;
+	RESOURCE *r;
+	HANDLE rh;
 
-    /*
-     * Move to beginning of resource table.
-     */
-    rtoff = (ResourceFileInfo->mz_header->ne_offset +
-	     ResourceFileInfo->ne_header->resource_tab_offset);
-    lseek(ResourceFd, rtoff, SEEK_SET);
-    
-    /*
-     * Read block size.
-     */
-    if (read(ResourceFd, &size_shift, sizeof(size_shift)) != 
-	sizeof(size_shift))
-    {
-	return;
-    }
-    size_shift = CONV_SHORT(size_shift);
+#ifdef DEBUG_RESOURCE 
+	printf("FindResource(%04X", instance);
+	PrintId(name);
+	PrintId(type);
+	printf(")\n");
+#endif
 
-    /*
-     * Find resource.
-     */
-    typeinfo.type_id = 0xffff;
-    while (typeinfo.type_id != 0) 
-    {
-	if (!load_typeinfo (ResourceFd, &typeinfo))
-	    break;
+	if (instance == (HANDLE)NULL)
+		instance = hSysRes;
 
-	if (typeinfo.type_id == 0) 
-	    break;
-	if (typeinfo.type_id == 0x800f) 
-	{
-	    for (i = 0; i < typeinfo.count; i++) 
-	    {
-		if (read(ResourceFd, &nameinfo, sizeof(nameinfo)) != 
-		    sizeof(nameinfo))
-		{
-		    break;
-		}
-		
-		saved_pos = lseek(ResourceFd, 0, SEEK_CUR);
-		lseek(ResourceFd, (long) nameinfo.offset << size_shift, 
-		      SEEK_SET);
-		read(ResourceFd, &len, sizeof(len));
-		while (len)
-		{
-		    new = (RESNAMTAB *) GlobalQuickAlloc(sizeof(*new));
-		    new->next = top;
-		    top = new;
+	/* FIXME: did we already find this one ? */
 
-		    read(ResourceFd, &new->type_ord, 2);
-		    read(ResourceFd, &new->id_ord, 2);
-		    read(ResourceFd, read_buf, len - 6);
-		    
-		    p = read_buf + strlen(read_buf) + 1;
-		    strncpy(new->id, p, MAX_NAME_LENGTH);
-		    new->id[MAX_NAME_LENGTH - 1] = '\0';
+	if ((rh = GlobalAlloc(GMEM_MOVEABLE, sizeof(RESOURCE))) == 0)
+		return 0;
 
-		    read(ResourceFd, &len, sizeof(len));
-		}
+	r = (RESOURCE *)GlobalLock(rh);
+	r->next = Top;
+	Top = r;
+	r->info_mem = rh;
+	r->rsc_mem = 0;
+	r->count = 0;
+	if (HIWORD((DWORD)name))
+		r->name = strdup(name);
+	else
+		r->name = name;
 
-		lseek(ResourceFd, saved_pos, SEEK_SET);
-	    }
-	    break;
-	}
-	else 
-	{
-	    lseek(ResourceFd, (typeinfo.count * sizeof(nameinfo)), SEEK_CUR);
-	}
-    }
+	if (HIWORD((DWORD)type))
+		r->type = strdup(type);
+	else
+		r->type = type;
 
-    ResourceFileInfo->resnamtab = top;
+	r->wpnt = GetFileInfo(instance);
+	r->fd = dup(r->wpnt->fd);
+	if (r->wpnt->ne)
+		status = NE_FindResource(instance, name, type, r);
+	else
+		status = PE_FindResource(instance, name, type, r);
+
+	if (!status) {
+		if (HIWORD((DWORD)r->name))
+			free(r->name);
+
+		if (HIWORD((DWORD)r->type))
+			free(r->type);
+		close(r->fd);
+
+		Top = r->next;
+		GlobalUnlock(rh);
+		return 0;
+	} else
+		return rh;
 }
-#endif /* WINELIB */
-
-/**********************************************************************
- *					OpenResourceFile
- */
-int
-OpenResourceFile(HANDLE instance)
-{
-    struct w_files *w;
-    char   *res_file;
-    
-    if (ResourceInst == instance)
-	return ResourceFd;
 
-    w = GetFileInfo(instance);
-    if (w == NULL)
-	return -1;
-    ResourceFileInfo = w;
-    res_file = w->filename;
-    
-    if (ResourceFd >= 0)
-	close(ResourceFd);
-    
-    ResourceInst = instance;
-    ResourceFd   = open (res_file, O_RDONLY);
-#if 1
-#ifndef WINELIB
-    if (w->resnamtab == (RESNAMTAB *) -1)
-    {
-	RSC_LoadNameTable();
-    }
-#endif
-#endif
+/**********************************************************************
+ *			AllocResource	[KERNEL.66]
+ */
+HANDLE AllocResource(HANDLE instance, HANDLE hResInfo, DWORD dwSize)
+{
+	RESOURCE *r;
+	int image_size;
 
 #ifdef DEBUG_RESOURCE
-    printf("OpenResourceFile(%04X) // file='%s' hFile=%04X !\n", 
-		instance, w->filename, ResourceFd);
-#endif
-    return ResourceFd;
+	printf("AllocResource(%04X, %04X, %08X);\n", instance, hResInfo, (int) dwSize);
+#endif 
+
+	if (instance == (HANDLE)NULL)
+		instance = hSysRes;
+
+	if ((r = (RESOURCE *)GlobalLock(hResInfo)) == NULL)
+		return 0;
+    
+	image_size = r->size;
+
+	if (dwSize == 0)
+		r->rsc_mem = GlobalAlloc(GMEM_MOVEABLE, image_size);
+	else
+		r->rsc_mem = GlobalAlloc(GMEM_MOVEABLE, dwSize);
+
+	GlobalUnlock(hResInfo);
+
+	return r->rsc_mem;
 }
 
 /**********************************************************************
- *					ConvertCoreBitmap
+ *				AccessResource	[KERNEL.64]
  */
-HBITMAP
-ConvertCoreBitmap( HDC hdc, BITMAPCOREHEADER * image )
+int AccessResource(HANDLE instance, HANDLE hResInfo)
+{
+	int fd;
+	RESOURCE *r;
+
+#ifdef DEBUG_RESOURCE
+	printf("AccessResource(%04X, %04X);\n", instance, hResInfo);
+#endif
+
+	if (instance == (HANDLE)NULL)
+		instance = hSysRes;
+
+	if ((r = (RESOURCE *)GlobalLock(hResInfo)) == NULL)
+		return -1;
+
+	fd = r->fd;
+	lseek(fd, r->offset, SEEK_SET);
+	GlobalUnlock(hResInfo);
+
+	return fd;
+}
+
+/**********************************************************************
+ *				SizeofResource	[KERNEL.65]
+ */
+WORD SizeofResource(HANDLE instance, HANDLE hResInfo)
+{
+	RESOURCE *r;
+	int size;
+	
+#ifdef DEBUG_RESOURCE
+	printf("SizeofResource(%04X, %04X);\n", instance, hResInfo);
+#endif
+
+	if (instance == (HANDLE)NULL)
+		instance = hSysRes;
+
+	if ((r = (RESOURCE *)GlobalLock(hResInfo)) == NULL)
+		return 0;
+
+	size = r->size;
+	GlobalUnlock(hResInfo);
+
+	return size;
+}
+
+/**********************************************************************
+ *			LoadResource	[KERNEL.61]
+ */
+HANDLE LoadResource(HANDLE instance, HANDLE hResInfo)
+{
+    RESOURCE *r;
+    int image_size, fd;
+    void *image;
+    HANDLE h;
+
+#ifdef DEBUG_RESOURCE
+	printf("LoadResource(%04X, %04X);\n", instance, hResInfo);
+#endif
+
+    if (instance == (HANDLE)NULL)
+	instance = hSysRes;
+
+    if ((r = (RESOURCE *)GlobalLock(hResInfo)) == NULL)
+	return 0;
+    
+    h = r->rsc_mem = AllocResource(instance, hResInfo, 0);
+    image = GlobalLinearLock(h);
+    image_size = r->size;
+    fd = AccessResource(instance, hResInfo);
+
+    if (image == NULL || read(fd, image, image_size) != image_size) {
+	GlobalFree(h);
+	GlobalUnlock(hResInfo);
+	return 0;
+    }
+    r->count++;
+    close(fd);
+    GlobalLinearUnlock(h);
+    GlobalUnlock(hResInfo);
+    return h;
+}
+
+/**********************************************************************
+ *				LockResource	[KERNEL.62]
+ */
+LPSTR LockResource(HANDLE hResData)
+{
+    return GlobalLock(hResData);
+}
+
+/**********************************************************************
+ *				FreeResource	[KERNEL.63]
+ */
+HANDLE FreeResource(HANDLE hResData)
+{
+    RESOURCE *r, *rp;
+
+#ifdef DEBUG_RESOURCE
+    printf("FreeResource: handle %04x\n", hResData);
+#endif
+
+    for (r = rp = Top; r ; r = r->next) {
+	if (r->rsc_mem == hResData) {
+	    if (r->count == 0) {
+		    if (rp != r)
+			rp->next = r->next;
+		    else
+			Top = r->next;
+
+		    if (HIWORD((DWORD)r->name))
+		    	free(r->name);
+                    if (HIWORD((DWORD)r->type))
+			free(r->type);
+		    GlobalFree(r->rsc_mem);
+		    GlobalFree(r->info_mem);
+		    return 0;
+	    } else
+	    	r->count--;
+	}
+	rp = r;
+    }
+    return hResData;
+}
+
+/**********************************************************************
+ *			ConvertCoreBitmap
+ */
+HBITMAP ConvertCoreBitmap( HDC hdc, BITMAPCOREHEADER * image )
 {
     BITMAPINFO * bmpInfo;
     HBITMAP hbitmap;
@@ -235,306 +316,44 @@
 }
 
 /**********************************************************************
- *					ConvertInfoBitmap
+ *			ConvertInfoBitmap
  */
-HBITMAP
-ConvertInfoBitmap( HDC hdc, BITMAPINFO * image )
+HBITMAP	ConvertInfoBitmap( HDC hdc, BITMAPINFO * image )
 {
     char * bits = ((char *)image) + DIB_BitmapInfoSize(image, DIB_RGB_COLORS);
     return CreateDIBitmap( hdc, &image->bmiHeader, CBM_INIT,
 			   bits, image, DIB_RGB_COLORS );
 } 
-
-#ifndef WINELIB
-load_typeinfo (int fd, struct resource_typeinfo_s *typeinfo)
-{
-    return read (fd, typeinfo, sizeof (*typeinfo)) == sizeof (*typeinfo);
-}
-#endif
-
-int
-type_match(int type_id1, int type_id2, int fd, off_t off)
-{
-	off_t old_pos;
-	unsigned char c;
-	size_t nbytes;
-	char name[256];
-
-	if (type_id1 == -1)
-		return 1;
-	if ((type_id1 & 0xffff0000) == 0) {
-		if ((type_id2 & 0x8000) == 0)
-			return 0;
-		return (type_id1 & 0x000f) == (type_id2 & 0x000f);
-	}
-	if ((type_id2 & 0x8000) != 0)
-		return 0;
-#ifdef DEBUG_RESOURCE
-	printf("type_compare: type_id2=%04X !\n", type_id2);
-#endif
-	old_pos = lseek(fd, 0, SEEK_CUR);
-	lseek(fd, off + type_id2, SEEK_SET);
-	read(fd, &c, 1);
-	nbytes = CONV_CHAR_TO_LONG (c);
-#ifdef DEBUG_RESOURCE
-	printf("type_compare: namesize=%d\n", nbytes);
-#endif
-	read(fd, name, nbytes);
-	lseek(fd, old_pos, SEEK_SET);
-	name[nbytes] = '\0';
-#ifdef DEBUG_RESOURCE
-	printf("type_compare: name=`%s'\n", name);
-#endif
-	return strcasecmp((char *) type_id1, name) == 0;
-}
 
 /**********************************************************************
- *					FindResourceByNumber
+ *			RSC_LoadResource
  */
-int
-FindResourceByNumber(struct resource_nameinfo_s *result_p,
-		     int type_id, int resource_id)
+HANDLE
+RSC_LoadResource(int instance, LPSTR rsc_name, LPSTR type, int *image_size_ret)
 {
-    struct resource_typeinfo_s typeinfo;
-    struct resource_nameinfo_s nameinfo;
-    unsigned short size_shift;
-    int i;
-    off_t rtoff;
+	HANDLE hResInfo;
+	RESOURCE *r;
 
-    /*
-     * Move to beginning of resource table.
-     */
-    rtoff = (ResourceFileInfo->mz_header->ne_offset +
-	     ResourceFileInfo->ne_header->resource_tab_offset);
-    lseek(ResourceFd, rtoff, SEEK_SET);
-    
-    /*
-     * Read block size.
-     */
-    if (read(ResourceFd, &size_shift, sizeof(size_shift)) != 
-	sizeof(size_shift))
-    {
-    	printf("FindResourceByNumber (%s) bad block size !\n", resource_id);
-	return -1;
-    }
-    size_shift = CONV_SHORT(size_shift);
-    /*
-     * Find resource.
-     */
-    for (;;) {
-	if (!load_typeinfo (ResourceFd, &typeinfo)){
-	    printf("FindResourceByNumber (%X) bad typeinfo size !\n", resource_id);
-	    return -1;
-	    }
-#ifdef DEBUG_RESOURCE
-	printf("FindResourceByNumber type=%X count=%d searched=%d \n", 
-			typeinfo.type_id, typeinfo.count, type_id);
-#endif
-	if (typeinfo.type_id == 0) break;
-	if (type_match(type_id, typeinfo.type_id, ResourceFd, rtoff)) {
+	if (instance == (HANDLE)NULL)
+		instance = hSysRes;
 
-	    for (i = 0; i < typeinfo.count; i++) {
-#ifndef WINELIB
-		if (read(ResourceFd, &nameinfo, sizeof(nameinfo)) != 
-		    sizeof(nameinfo))
-#else
-		if (!load_nameinfo (ResourceFd, &nameinfo))
-#endif
-		{
-		    printf("FindResourceByNumber (%X) bad nameinfo size !\n", resource_id);
-		    return -1;
-		    }
 #ifdef DEBUG_RESOURCE
-		printf("FindResource: search type=%X id=%X // type=%X id=%X\n",
-			type_id, resource_id, typeinfo.type_id, nameinfo.id);
+	printf("RSC_LoadResource: instance = %04x, name = %08x, type = %08x\n",
+	   instance, (int) rsc_name, (int) type);
 #endif
-		if (nameinfo.id == resource_id) {
-		    memcpy(result_p, &nameinfo, sizeof(nameinfo));
-		    return size_shift;
-		    }
-	        }
-	    }
-	else {
-	    lseek(ResourceFd, (typeinfo.count * sizeof(nameinfo)), SEEK_CUR);
-	    }
-        }
-    return -1;
+
+	if ((hResInfo = FindResource(instance, rsc_name, (LPSTR) type)) == (HANDLE) NULL) {
+		return (HANDLE)NULL;
+	}
+	r = (RESOURCE *)GlobalLock(hResInfo);
+	if (image_size_ret) 
+		*image_size_ret = r->size;
+	r->count++;
+	GlobalUnlock(hResInfo);
+	return LoadResource(instance, hResInfo);
 }
 
 /**********************************************************************
- *					FindResourceByName
- */
-int
-FindResourceByName(struct resource_nameinfo_s *result_p,
-		     int type_id, char *resource_name)
-{
-    struct resource_typeinfo_s typeinfo;
-    struct resource_nameinfo_s nameinfo;
-    unsigned short size_shift;
-    off_t old_pos, new_pos;
-    unsigned char nbytes;
-    char name[256];
-    int i;
-    off_t rtoff;
-
-    /*
-     * Check for loaded name table.
-     */
-    if (ResourceFileInfo->resnamtab != NULL)
-    {
-	RESNAMTAB *e;
-
-	for (e = ResourceFileInfo->resnamtab; e != NULL; e = e->next)
-	{
-	    if (e->type_ord == (type_id & 0x000f) &&
-		strcasecmp(e->id, resource_name) == 0)
-	    {
-		return FindResourceByNumber(result_p, type_id, e->id_ord);
-	    }
-	}
-
-	return -1;
-    }
-
-    /*
-     * Move to beginning of resource table.
-     */
-    rtoff = (ResourceFileInfo->mz_header->ne_offset +
-	     ResourceFileInfo->ne_header->resource_tab_offset);
-    lseek(ResourceFd, rtoff, SEEK_SET);
-    
-    /*
-     * Read block size.
-     */
-    if (read(ResourceFd, &size_shift, sizeof(size_shift)) != 
-	sizeof(size_shift))
-    {
-    	printf("FindResourceByName (%s) bad block size !\n", resource_name);
-	return -1;
-    }
-    size_shift = CONV_SHORT (size_shift);
-    
-    /*
-     * Find resource.
-     */
-    for (;;)
-    {
-	if (!load_typeinfo (ResourceFd, &typeinfo))
-	{
-	    printf("FindResourceByName (%s) bad typeinfo size !\n", resource_name);
-	    return -1;
-	}
-#ifdef DEBUG_RESOURCE
-	printf("FindResourceByName typeinfo.type_id=%X count=%d type_id=%X\n",
-			typeinfo.type_id, typeinfo.count, type_id);
-#endif
-	if (typeinfo.type_id == 0) break;
-	if (type_match(type_id, typeinfo.type_id, ResourceFd, rtoff))
-	{
-	    for (i = 0; i < typeinfo.count; i++)
-	    {
-#ifndef WINELIB
-		if (read(ResourceFd, &nameinfo, sizeof(nameinfo)) != 
-		    sizeof(nameinfo))
-#else
-		if (!load_nameinfo (ResourceFd, &nameinfo))
-#endif
-		{
-		    printf("FindResourceByName (%s) bad nameinfo size !\n", resource_name);
-		    return -1;
-		}
-/*
-		if ((nameinfo.id & 0x8000) != 0) continue;
-*/		
-#ifdef DEBUG_RESOURCE
-		printf("FindResourceByName // nameinfo.id=%04X !\n", nameinfo.id);
-#endif
-		old_pos = lseek(ResourceFd, 0, SEEK_CUR);
-		new_pos = rtoff + nameinfo.id;
-		lseek(ResourceFd, new_pos, SEEK_SET);
-		read(ResourceFd, &nbytes, 1);
-#ifdef DEBUG_RESOURCE
-		printf("FindResourceByName // namesize=%d !\n", nbytes);
-#endif
- 		nbytes = CONV_CHAR_TO_LONG (nbytes);
-		read(ResourceFd, name, nbytes);
-		lseek(ResourceFd, old_pos, SEEK_SET);
-		name[nbytes] = '\0';
-#ifdef DEBUG_RESOURCE
-		printf("FindResourceByName type_id=%X (%d of %d) name='%s' resource_name='%s'\n", 
-			typeinfo.type_id, i + 1, typeinfo.count, 
-			name, resource_name);
-#endif
-		if (strcasecmp(name, resource_name) == 0)
-		{
-		    memcpy(result_p, &nameinfo, sizeof(nameinfo));
-		    return size_shift;
-		}
-	    }
-	}
-	else {
-	    lseek(ResourceFd, (typeinfo.count * sizeof(nameinfo)), SEEK_CUR);
-	    }
-    }
-    return -1;
-}
-
-
-/**********************************************************************
- *					GetRsrcCount		[internal]
- */
-int GetRsrcCount(HINSTANCE hInst, int type_id)
-{
-    struct resource_typeinfo_s typeinfo;
-    struct resource_nameinfo_s nameinfo;
-    unsigned short size_shift;
-/*    off_t old_pos, new_pos;
-    unsigned char nbytes; 
-    char name[256]; */
-    int i;
-    off_t rtoff;
-    if (hInst == 0) return 0;
-#ifdef DEBUG_RESOURCE
-    printf("GetRsrcCount hInst=%04X typename=%08X\n", hInst, type_id);
-#endif
-    if (OpenResourceFile(hInst) < 0)	return 0;
-
-    /*
-     * Move to beginning of resource table.
-     */
-    rtoff = (ResourceFileInfo->mz_header->ne_offset +
-	     ResourceFileInfo->ne_header->resource_tab_offset);
-    lseek(ResourceFd, rtoff, SEEK_SET);
-    /*
-     * Read block size.
-     */
-    if (read(ResourceFd, &size_shift, sizeof(size_shift)) != sizeof(size_shift)) {
-		printf("GetRsrcCount // bad block size !\n");
-		return -1;
-		}
-    size_shift = CONV_SHORT (size_shift);
-    for (;;) {
-		if (!load_typeinfo (ResourceFd, &typeinfo))	{
-			printf("GetRsrcCount // bad typeinfo size !\n");
-			return 0;
-			}
-#ifdef DEBUG_RESOURCE
-		printf("GetRsrcCount // typeinfo.type_id=%X count=%d type_id=%X\n",
-				typeinfo.type_id, typeinfo.count, type_id);
-#endif
-		if (typeinfo.type_id == 0) break;
-		if (type_match(type_id, typeinfo.type_id, ResourceFd, rtoff)) {
-			return typeinfo.count;
-			}
-		else {
-			lseek(ResourceFd, (typeinfo.count * sizeof(nameinfo)), SEEK_CUR);
-			}
-		}
-    return 0;
-}
-
-
-/**********************************************************************
  *			LoadIcon [USER.174]
  */
 HICON LoadIcon(HANDLE instance, LPSTR icon_name)
@@ -548,22 +367,22 @@
     BITMAPINFO 	*bmi;
     BITMAPINFOHEADER 	*bih;
     RGBQUAD	*rgbq;
-    HBITMAP 	hBitMap;
     HDC 	hMemDC;
     HDC 	hMemDC2;
     HDC 	hdc;
-    int 	i, j, image_size;
+    int 	image_size;
+
 #ifdef DEBUG_RESOURCE
-    printf("LoadIcon: instance = %04x, name = %08x\n",
-	   instance, icon_name);
+	printf("LoadIcon(%04X", instance);
+	PrintId(icon_name);
+	printf(")\n");
 #endif
     
     if (!(hdc = GetDC(GetDesktopWindow()))) return 0;
-    if (instance == (HANDLE)NULL)  instance = hSysRes;
-    rsc_mem = RSC_LoadResource(instance, icon_name, NE_RSCTYPE_GROUP_ICON, 
+    rsc_mem = RSC_LoadResource(instance, icon_name, (LPSTR) NE_RSCTYPE_GROUP_ICON, 
 			       &image_size);
     if (rsc_mem == (HANDLE)NULL) {
-	printf("LoadIcon / Icon %04X not Found !\n", icon_name);
+	printf("LoadIcon / Icon %04X not Found !\n", (int) icon_name);
 	ReleaseDC(GetDesktopWindow(), hdc); 
 	return 0;
 	}
@@ -588,9 +407,9 @@
     GlobalFree(rsc_mem);
     rsc_mem = RSC_LoadResource(instance, 
     	MAKEINTRESOURCE(lpicodesc->icoDIBOffset), 
-    	NE_RSCTYPE_ICON, &image_size);
+    	(LPSTR) NE_RSCTYPE_ICON, &image_size);
     if (rsc_mem == (HANDLE)NULL) {
-	printf("LoadIcon / Icon %04X Bitmaps not Found !\n", icon_name);
+	printf("LoadIcon / Icon %04X Bitmaps not Found !\n", (int) icon_name);
 	ReleaseDC(GetDesktopWindow(), hdc); 
 	return 0;
 	}
@@ -624,7 +443,7 @@
     rgbq[1].rgbReserved = 0x00;
     if (bih->biSizeImage == 0) {
 	if (bih->biCompression != BI_RGB) {
-	    printf("Unknown size for compressed Icon bitmap.\n");
+	    fprintf(stderr,"Unknown size for compressed Icon bitmap.\n");
 	    GlobalFree(rsc_mem);
 	    ReleaseDC(GetDesktopWindow(), hdc); 
 	    return 0;
@@ -646,549 +465,9 @@
     DeleteDC(hMemDC2);
     ReleaseDC(GetDesktopWindow(), hdc);
     GlobalUnlock(hIcon);
-#ifdef DEBUG_RESOURCE
-    printf("LoadIcon Alloc hIcon=%X\n", hIcon);
-#endif
+    dprintf_resource(stddeb,"LoadIcon Alloc hIcon=%X\n", hIcon);
     return hIcon;
 }
-
-
-/**********************************************************************
- *			DestroyIcon [USER.457]
- */
-BOOL DestroyIcon(HICON hIcon)
-{
-    ICONALLOC	*lpico;
-    if (hIcon == (HICON)NULL) return FALSE;
-    lpico = (ICONALLOC *)GlobalLock(hIcon);
-    if (lpico->hBitmap != (HBITMAP)NULL) DeleteObject(lpico->hBitmap);
-    GlobalFree(hIcon);
-    return TRUE;
-}
-
-
-/**********************************************************************
- *			LoadAccelerators	[USER.177]
- */
-HANDLE LoadAccelerators(HANDLE instance, LPSTR lpTableName)
-{
-    HANDLE 	hAccel;
-    HANDLE 	rsc_mem;
-    BYTE 	*lp;
-    ACCELHEADER	*lpAccelTbl;
-    int 	i, image_size, n;
-#ifdef DEBUG_ACCEL
-    if (((LONG)lpTableName & 0xFFFF0000L) == 0L)
-	printf("LoadAccelerators: instance = %04X, name = %08X\n",
-			instance, lpTableName);
-    else
-	printf("LoadAccelerators: instance = %04X, name = '%s'\n",
-			instance, lpTableName);
-#endif
-    if (instance == (HANDLE)NULL)  instance = hSysRes;
-    rsc_mem = RSC_LoadResource(instance, lpTableName, NE_RSCTYPE_ACCELERATOR, 
-			       &image_size);
-    if (rsc_mem == (HANDLE)NULL) {
-	printf("LoadAccelerators / AccelTable %04X not Found !\n", lpTableName);
-	return 0;
-	}
-    lp = (BYTE *)GlobalLock(rsc_mem);
-    if (lp == NULL) {
-	GlobalFree(rsc_mem);
-	return 0;
-	}
-#ifdef DEBUG_ACCEL
-    printf("LoadAccelerators / image_size=%d\n", image_size);
-#endif
-    n = image_size/5;
-    hAccel = GlobalAlloc(GMEM_MOVEABLE, 
-    	sizeof(ACCELHEADER) + (n + 1)*sizeof(ACCELENTRY));
-    lpAccelTbl = (LPACCELHEADER)GlobalLock(hAccel);
-    lpAccelTbl->wCount = 0;
-    for (i = 0; i < n; i++) {
-	lpAccelTbl->tbl[i].type = *(lp++);
-	lpAccelTbl->tbl[i].wEvent = *((WORD *)lp);
-	lp += 2;
-	lpAccelTbl->tbl[i].wIDval = *((WORD *)lp);
-	lp += 2;
-    	if (lpAccelTbl->tbl[i].wEvent == 0) break;
-#ifdef DEBUG_ACCEL
-	printf("Accelerator #%u / event=%04X id=%04X type=%02X \n", 
-		i, lpAccelTbl->tbl[i].wEvent, lpAccelTbl->tbl[i].wIDval, 
-		lpAccelTbl->tbl[i].type);
-#endif
-	lpAccelTbl->wCount++;
- 	}
-    GlobalUnlock(hAccel);
-    GlobalUnlock(rsc_mem);
-    GlobalFree(rsc_mem);
-    return hAccel;
-}
-
-/**********************************************************************
- *			TranslateAccelerator 	[USER.178]
- */
-int TranslateAccelerator(HWND hWnd, HANDLE hAccel, LPMSG msg)
-{
-    ACCELHEADER	*lpAccelTbl;
-    int 	i, image_size;
-    if (hAccel == 0 || msg == NULL) return 0;
-    if (msg->message != WM_KEYDOWN &&
-    	msg->message != WM_KEYUP &&
-    	msg->message != WM_CHAR) return 0;
-#ifdef DEBUG_ACCEL
-    printf("TranslateAccelerators hAccel=%04X !\n", hAccel);
-#endif
-    lpAccelTbl = (LPACCELHEADER)GlobalLock(hAccel);
-    for (i = 0; i < lpAccelTbl->wCount; i++) {
-	if (lpAccelTbl->tbl[i].type & VIRTKEY_ACCEL) {
-	    if (msg->wParam == lpAccelTbl->tbl[i].wEvent &&
-		msg->message == WM_KEYDOWN) {
-		if ((lpAccelTbl->tbl[i].type & SHIFT_ACCEL) &&
-		    !(GetKeyState(VK_SHIFT) & 0xf)) {
-		    GlobalUnlock(hAccel);
-		    return 0;
-		}
-		if ((lpAccelTbl->tbl[i].type & CONTROL_ACCEL) &&
-		    !(GetKeyState(VK_CONTROL) & 0xf)) {
-		    GlobalUnlock(hAccel);
-		    return 0;
-		}
-		if ((lpAccelTbl->tbl[i].type & ALT_ACCEL) &&
-		    !(GetKeyState(VK_MENU) & 0xf)) {
-		    GlobalUnlock(hAccel);
-		    return 0;
-		}
-		SendMessage(hWnd, WM_COMMAND, lpAccelTbl->tbl[i].wIDval, 0x00010000L);
-		GlobalUnlock(hAccel);
-		return 1;
-		}
-	    if (msg->message == WM_KEYUP) return 1;
-	    }
-	else {
-	    if (msg->wParam == lpAccelTbl->tbl[i].wEvent &&
-		msg->message == WM_CHAR) {
-		SendMessage(hWnd, WM_COMMAND, lpAccelTbl->tbl[i].wIDval, 0x00010000L);
-		GlobalUnlock(hAccel);
-		return 1;
-		}
-	    }
-	}
-    GlobalUnlock(hAccel);
-    return 0;
-}
-
-/**********************************************************************
- *				FindResource	[KERNEL.60]
- */
-HANDLE FindResource(HANDLE instance, LPSTR resource_name, LPSTR type_name)
-{
-    RESOURCE *r;
-    HANDLE rh;
-    int type;
-
-    if (instance == 0)
-	return 0;
-    
-#ifdef DEBUG_RESOURCE
-    printf("FindResource hInst=%04X typename=%08X resname=%08X\n", 
-		instance, type_name, resource_name);
-#endif
-    if (OpenResourceFile(instance) < 0)
-	return 0;
-    
-    rh = GlobalAlloc(GMEM_MOVEABLE, sizeof(*r));
-    if (rh == 0)
-	return 0;
-    r = (RESOURCE *)GlobalLock(rh);
-
-    r->next = Top;
-    Top = r;
-    r->info_mem = rh;
-    r->rsc_mem = 0;
-
-    if (((int) type_name & 0xffff0000) == 0)
-    {
-	type = (int) type_name;
-    }
-    else if (type_name[0] == '\0')
-    {
-	type = -1;
-    }
-    else if (type_name[0] == '#')
-    {
-	type = atoi(type_name + 1);
-    }
-    else
-    {
-	type = (int) type_name;
-    }
-    if (((int) resource_name & 0xffff0000) == 0)
-    {
-	r->size_shift = FindResourceByNumber(&r->nameinfo, type,
-					     (int) resource_name | 0x8000);
-    }
-    else if (resource_name[0] == '\0')
-    {
-	r->size_shift = FindResourceByNumber(&r->nameinfo, type, -1);
-    }
-    else if (resource_name[0] == '#')
-    {
-	r->size_shift = FindResourceByNumber(&r->nameinfo, type,
-					     atoi(resource_name + 1));
-    }
-    else
-    {
-	r->size_shift = FindResourceByName(&r->nameinfo, type, resource_name);
-    }
-    
-    if (r->size_shift == -1)
-    {
-        printf("FindResource hInst=%04X typename=%08X resname=%08X not found!\n", 
-		instance, type_name, resource_name);
-	GlobalFree(rh);
-	return 0;
-    }
-
-    return rh;
-}
-
-/**********************************************************************
- *			AllocResource	[KERNEL.66]
- */
-HANDLE AllocResource(HANDLE instance, HANDLE hResInfo, DWORD dwSize)
-{
-    RESOURCE *r;
-    int image_size;
-
-    if (instance == 0)
-	return 0;
-    
-    if (OpenResourceFile(instance) < 0)
-	return 0;
-
-    r = (RESOURCE *)GlobalLock(hResInfo);
-    if (r == NULL)
-	return 0;
-    
-    image_size = r->nameinfo.length << r->size_shift;
-
-    if (dwSize == 0)
-	r->rsc_mem = GlobalAlloc(GMEM_MOVEABLE, image_size);
-    else
-	r->rsc_mem = GlobalAlloc(GMEM_MOVEABLE, dwSize);
-
-    GlobalUnlock(hResInfo);
-
-    return r->rsc_mem;
-}
-
-/**********************************************************************
- *				LoadResource	[KERNEL.61]
- */
-HANDLE LoadResource(HANDLE instance, HANDLE hResInfo)
-{
-    RESOURCE *r;
-    int image_size;
-    void *image;
-    HANDLE h;
-
-    if (instance == 0)
-	return 0;
-    
-    if (OpenResourceFile(instance) < 0)
-	return 0;
-
-    r = (RESOURCE *)GlobalLock(hResInfo);
-    if (r == NULL)
-	return 0;
-    
-    image_size = r->nameinfo.length << r->size_shift;
-
-    h = r->rsc_mem = GlobalAlloc(GMEM_MOVEABLE, image_size);
-    image = GlobalLock(h);
-
-    lseek(ResourceFd, ((int) r->nameinfo.offset << r->size_shift), SEEK_SET);
-
-    if (image == NULL || read(ResourceFd, image, image_size) != image_size)
-    {
-	GlobalFree(h);
-	GlobalUnlock(hResInfo);
-	return 0;
-    }
-
-    GlobalUnlock(h);
-    GlobalUnlock(hResInfo);
-    return h;
-}
-
-/**********************************************************************
- *				LockResource	[KERNEL.62]
- */
-LPSTR LockResource(HANDLE hResData)
-{
-    return GlobalLock(hResData);
-}
-
-/**********************************************************************
- *				FreeResource	[KERNEL.63]
- */
-HANDLE FreeResource(HANDLE hResData)
-{
-    RESOURCE *r, *rp;
-    
-    for (r = rp = Top; r != NULL; r = r->next)
-    {
-	if (r->info_mem == hResData)
-	{
-	    if (rp != NULL)
-		rp->next = r->next;
-	    else
-		Top = r->next;
-	    
-	    GlobalFree(r->rsc_mem);
-	    GlobalFree(r->info_mem);
-	    return 0;
-	}
-	rp = r;
-    }
-    
-    return hResData;
-}
-
-/**********************************************************************
- *				AccessResource	[KERNEL.64]
- */
-int AccessResource(HANDLE instance, HANDLE hResInfo)
-{
-    int	resfile, image_size;
-    RESOURCE *r;
-
-/* #ifdef DEBUG_RESOURCE */
-    printf("AccessResource(%04X, %04X);\n", instance, hResInfo);
-/* #endif */
-
-    if (instance == 0)
-	return -1;
-    
-    if ((resfile = OpenResourceFile(instance)) < 0)
-	return -1;
-
-    if ((r = (RESOURCE *)GlobalLock(hResInfo)) == NULL)
-	return -1;
-
-    lseek(resfile, ((int) r->nameinfo.offset << r->size_shift), SEEK_SET);
-    GlobalUnlock(hResInfo);
-
-    return dup(resfile);
-}
-
-/**********************************************************************
- *				SizeofResource	[KERNEL.65]
- */
-WORD SizeofResource(HANDLE instance, HANDLE hResInfo)
-{
-    int	image_size;
-    RESOURCE *r;
-
-/* #ifdef DEBUG_RESOURCE */
-    printf("SizeofResource(%04X, %04X);\n", instance, hResInfo);
-/* #endif */
-
-    if (instance == 0)
-	return 0;
-    
-    if ((r = (RESOURCE *)GlobalLock(hResInfo)) == NULL)
-	return 0;
-    
-    image_size = r->nameinfo.length << r->size_shift;
-
-    GlobalUnlock(hResInfo);
-
-/* #ifdef DEBUG_RESOURCE */
-    printf("SizeofResource return %d\n", image_size);
-/* #endif */
-
-    return image_size;
-}
-
-/**********************************************************************
- *					RSC_LoadResource
- */
-HANDLE
-RSC_LoadResource(int instance, char *rsc_name, int type, int *image_size_ret)
-{
-    struct resource_nameinfo_s nameinfo;
-    HANDLE hmem;
-    void *image;
-    int image_size;
-    int size_shift;
-    
-    /*
-     * Built-in resources
-     */
-    if (instance == 0)
-    {
-	return 0;
-    }
-    else if (OpenResourceFile(instance) < 0)
-	return 0;
-    
-    /*
-     * Get resource by ordinal
-     */
-    if (((int) rsc_name & 0xffff0000) == 0)
-    {
-	size_shift = FindResourceByNumber(&nameinfo, type,
-					  (int) rsc_name | 0x8000);
-    }
-    /*
-     * Get resource by name
-     */
-    else
-    {
-	size_shift = FindResourceByName(&nameinfo, type, rsc_name);
-    }
-    if (size_shift == -1) {
-    	if ((LONG)rsc_name >= 0x00010000L)
-	    printf("RSC_LoadResource inst (%x)/ Resource '%s' not Found !\n", instance, rsc_name);
-	else
-	    printf("RSC_LoadResource inst (%x)/ Resource '0x%X' not Found !\n", instance, rsc_name);
-	return 0;
-	}
-    /*
-     * Read resource.
-     */
-    lseek(ResourceFd, ((int) nameinfo.offset << size_shift), SEEK_SET);
-
-    image_size = nameinfo.length << size_shift;
-    if (image_size_ret != NULL)
-	*image_size_ret = image_size;
-    hmem = GlobalAlloc(GMEM_MOVEABLE, image_size);
-    image = GlobalLinearLock(hmem);
-    if (image == NULL || read(ResourceFd, image, image_size) != image_size)
-    {
-	GlobalFree(hmem);
-	return 0;
-    }
-
-    GlobalLinearUnlock(hmem);
-    return hmem;
-}
-
-/**********************************************************************
- *					LoadString
- */
-int
-LoadString(HANDLE instance, WORD resource_id, LPSTR buffer, int buflen)
-{
-    HANDLE hmem;
-    int rsc_size;
-    unsigned char *p;
-    int string_num;
-    int i;
-
-#ifdef DEBUG_RESOURCE
-    printf("LoadString: instance = %04x, id = %d, "
-	   "buffer = %08x, length = %d\n",
-	   instance, resource_id, buffer, buflen);
-#endif
-
-    hmem = RSC_LoadResource(instance, (char *) ((resource_id >> 4) + 1),
-			    NE_RSCTYPE_STRING, &rsc_size);
-    if (hmem == 0)
-	return 0;
-    
-    p = GlobalLock(hmem);
-    string_num = resource_id & 0x000f;
-    for (i = 0; i < string_num; i++)
-	p += *p + 1;
-    
-    i = MIN(buflen - 1, *p);
-	if (i > 0) {
-		memcpy(buffer, p + 1, i);
-		buffer[i] = '\0';
-		}
-	else {
-		if (buflen > 1) {
-			buffer[0] = '\0';
-			return 0;
-			}
-		printf("LoadString // I dont know why , but caller give buflen=%d *p=%d !\n", buflen, *p);
-		printf("LoadString // and try to obtain string '%s'\n", p + 1);
-		}
-    GlobalFree(hmem);
-
-#ifdef DEBUG_RESOURCE
-    printf("LoadString // '%s' copied !\n", buffer);
-#endif
-    return i;
-}
-
-/**********************************************************************
- *					RSC_LoadMenu
- */
-HANDLE
-RSC_LoadMenu(HANDLE instance, LPSTR menu_name)
-{
-#ifdef DEBUG_RESOURCE
-    printf("RSC_LoadMenu: instance = %04x, name = '%s'\n",
-	   instance, menu_name);
-#endif
-    return RSC_LoadResource(instance, menu_name, NE_RSCTYPE_MENU, NULL);
-}
-
-/**********************************************************************
- *					LoadBitmap
- */
-HBITMAP
-LoadBitmap(HANDLE instance, LPSTR bmp_name)
-{
-    HBITMAP hbitmap;
-    HANDLE rsc_mem;
-    HDC hdc;
-    long *lp;
-    int image_size;
-    int size;
-    
-#ifdef DEBUG_RESOURCE
-    printf("LoadBitmap: instance = %04x, name = %08x\n",
-	   instance, bmp_name);
-#endif
-    if (!instance)
-    {
-	  /* Try to create an OEM bitmap */
-	hbitmap = BITMAP_LoadOEMBitmap( ((int)bmp_name) & 0xffff );
-	if (hbitmap) return hbitmap;
-	  /* Failed -> load it from sysres.dll */
-	instance = hSysRes;
-    }
-
-    rsc_mem = RSC_LoadResource(instance, bmp_name, NE_RSCTYPE_BITMAP, 
-			       &image_size);
-    if (rsc_mem == (HANDLE)NULL) {
-	printf("LoadBitmap / BitMap %04X not Found !\n", bmp_name);
-	return 0;
-	}
-    lp = (long *) GlobalLinearLock(rsc_mem);
-    if (!(hdc = GetDC(0))) lp = NULL;
-    if (lp == NULL)
-    {
-	GlobalFree(rsc_mem);
-	return 0;
-    }
-    size = CONV_LONG (*lp);
-    if (size == sizeof(BITMAPCOREHEADER)){
-	CONV_BITMAPCOREHEADER (lp);
-	hbitmap = ConvertCoreBitmap( hdc, (BITMAPCOREHEADER *) lp );
-    } else if (size == sizeof(BITMAPINFOHEADER)){
-	CONV_BITMAPINFO (lp);
-	hbitmap = ConvertInfoBitmap( hdc, (BITMAPINFO *) lp );
-    } else hbitmap = 0;
-    GlobalFree(rsc_mem);
-    ReleaseDC( 0, hdc );
-    return hbitmap;
-}
 
 /**********************************************************************
  *			CreateIcon [USER.407]
@@ -1204,7 +483,8 @@
     printf("CreateIcon: hInstance = %04x, nWidth = %08x, nHeight = %08x \n",
 	    hInstance, nWidth, nHeight);
     printf("  nPlanes = %04x, nBitsPixel = %04x,",nPlanes, nBitsPixel);
-    printf(" lpANDbits= %04x, lpXORbits = %04x, \n",lpANDbits, lpXORbits);
+    printf(" lpANDbits= %04x, lpXORbits = %04x, \n", (int)lpANDbits,
+    		(int)lpXORbits);
 #endif
 
     if (hInstance == (HANDLE)NULL) { 
@@ -1247,3 +527,254 @@
 #endif
     return hIcon;
 }
+
+/**********************************************************************
+ *			DestroyIcon [USER.457]
+ */
+BOOL DestroyIcon(HICON hIcon)
+{
+    ICONALLOC	*lpico;
+    
+    if (hIcon == (HICON)NULL)
+    	return FALSE;
+    lpico = (ICONALLOC *)GlobalLock(hIcon);
+    if (lpico->hBitmap != (HBITMAP)NULL) 
+    	DeleteObject(lpico->hBitmap);
+    GlobalFree(hIcon);
+    return TRUE;
+}
+
+/**********************************************************************
+ *			LoadAccelerators	[USER.177]
+ */
+HANDLE LoadAccelerators(HANDLE instance, LPSTR lpTableName)
+{
+    HANDLE 	hAccel;
+    HANDLE 	rsc_mem;
+    BYTE 	*lp;
+    ACCELHEADER	*lpAccelTbl;
+    int 	i, image_size, n;
+
+#ifdef DEBUG_ACCEL
+	printf("LoadAccelerators(%04X", instance);
+	PrintId(lpTableName);
+	printf(")\n");
+#endif
+
+    rsc_mem = RSC_LoadResource(instance, lpTableName, (LPSTR) NE_RSCTYPE_ACCELERATOR, 
+			       &image_size);
+    if (rsc_mem == (HANDLE)NULL) {
+	printf("LoadAccelerators(%04X", instance);
+	PrintId(lpTableName);
+	printf(") not found !\n");
+	return 0;
+	}
+    lp = (BYTE *)GlobalLock(rsc_mem);
+    if (lp == NULL) {
+	GlobalFree(rsc_mem);
+	return 0;
+	}
+    dprintf_accel(stddeb,"LoadAccelerators / image_size=%d\n", image_size);
+    n = image_size/5;
+    hAccel = GlobalAlloc(GMEM_MOVEABLE, 
+    	sizeof(ACCELHEADER) + (n + 1)*sizeof(ACCELENTRY));
+    lpAccelTbl = (LPACCELHEADER)GlobalLock(hAccel);
+    lpAccelTbl->wCount = 0;
+    for (i = 0; i < n; i++) {
+	lpAccelTbl->tbl[i].type = *(lp++);
+	lpAccelTbl->tbl[i].wEvent = *((WORD *)lp);
+	lp += 2;
+	lpAccelTbl->tbl[i].wIDval = *((WORD *)lp);
+	lp += 2;
+    	if (lpAccelTbl->tbl[i].wEvent == 0) break;
+	dprintf_accel(stddeb,
+		"Accelerator #%u / event=%04X id=%04X type=%02X \n", 
+		i, lpAccelTbl->tbl[i].wEvent, lpAccelTbl->tbl[i].wIDval, 
+		lpAccelTbl->tbl[i].type);
+	lpAccelTbl->wCount++;
+ 	}
+    GlobalUnlock(hAccel);
+    GlobalUnlock(rsc_mem);
+    GlobalFree(rsc_mem);
+    return hAccel;
+}
+
+/**********************************************************************
+ *			TranslateAccelerator 	[USER.178]
+ */
+int TranslateAccelerator(HWND hWnd, HANDLE hAccel, LPMSG msg)
+{
+    ACCELHEADER	*lpAccelTbl;
+    int 	i;
+    
+    if (hAccel == 0 || msg == NULL) return 0;
+    if (msg->message != WM_KEYDOWN &&
+    	msg->message != WM_KEYUP &&
+    	msg->message != WM_CHAR) return 0;
+
+#ifdef DEBUG_ACCEL
+    printf("TranslateAccelerators hAccel=%04X !\n", hAccel);
+#endif
+
+    lpAccelTbl = (LPACCELHEADER)GlobalLock(hAccel);
+    for (i = 0; i < lpAccelTbl->wCount; i++) {
+	if (lpAccelTbl->tbl[i].type & VIRTKEY_ACCEL) {
+	    if (msg->wParam == lpAccelTbl->tbl[i].wEvent &&
+		msg->message == WM_KEYDOWN) {
+		if ((lpAccelTbl->tbl[i].type & SHIFT_ACCEL) &&
+		    !(GetKeyState(VK_SHIFT) & 0xf)) {
+		    GlobalUnlock(hAccel);
+		    return 0;
+		}
+		if ((lpAccelTbl->tbl[i].type & CONTROL_ACCEL) &&
+		    !(GetKeyState(VK_CONTROL) & 0xf)) {
+		    GlobalUnlock(hAccel);
+		    return 0;
+		}
+		if ((lpAccelTbl->tbl[i].type & ALT_ACCEL) &&
+		    !(GetKeyState(VK_MENU) & 0xf)) {
+		    GlobalUnlock(hAccel);
+		    return 0;
+		}
+		SendMessage(hWnd, WM_COMMAND, lpAccelTbl->tbl[i].wIDval, 0x00010000L);
+		GlobalUnlock(hAccel);
+		return 1;
+		}
+	    if (msg->message == WM_KEYUP) return 1;
+	    }
+	else {
+	    if (msg->wParam == lpAccelTbl->tbl[i].wEvent &&
+		msg->message == WM_CHAR) {
+		SendMessage(hWnd, WM_COMMAND, lpAccelTbl->tbl[i].wIDval, 0x00010000L);
+		GlobalUnlock(hAccel);
+		return 1;
+		}
+	    }
+	}
+    GlobalUnlock(hAccel);
+    return 0;
+}
+
+/**********************************************************************
+ *					LoadString
+ */
+int
+LoadString(HANDLE instance, WORD resource_id, LPSTR buffer, int buflen)
+{
+    HANDLE hmem;
+    int rsc_size;
+    unsigned char *p;
+    int string_num;
+    int i;
+
+#ifdef DEBUG_RESOURCE
+    printf("LoadString: instance = %04x, id = %d, buffer = %08x, "
+	   "length = %d\n", instance, resource_id, (int) buffer, buflen);
+#endif
+
+    hmem = RSC_LoadResource(instance, (char *) ((resource_id >> 4) + 1),
+			    (LPSTR) NE_RSCTYPE_STRING, &rsc_size);
+    if (hmem == 0)
+	return 0;
+    
+    p = GlobalLock(hmem);
+    string_num = resource_id & 0x000f;
+    for (i = 0; i < string_num; i++)
+	p += *p + 1;
+    
+    i = MIN(buflen - 1, *p);
+	if (i > 0) {
+		memcpy(buffer, p + 1, i);
+		buffer[i] = '\0';
+		}
+	else {
+		if (buflen > 1) {
+			buffer[0] = '\0';
+			return 0;
+			}
+		fprintf(stderr,"LoadString // I dont know why , but caller give buflen=%d *p=%d !\n", buflen, *p);
+		fprintf(stderr,"LoadString // and try to obtain string '%s'\n", p + 1);
+		}
+    GlobalFree(hmem);
+
+    dprintf_resource(stddeb,"LoadString // '%s' copied !\n", buffer);
+    return i;
+}
+
+/**********************************************************************
+ *			LoadMenu		[USER.150]
+ */
+HMENU LoadMenu(HINSTANCE instance, char *menu_name)
+{
+	HMENU     		hMenu;
+	HANDLE		hMenu_desc;
+	MENU_HEADER 	*menu_desc;
+
+#ifdef DEBUG_MENU
+	printf("LoadMenu(%04X", instance);
+	PrintId(menu_name);
+	printf(")\n");
+#endif
+	if (menu_name == NULL)
+		return 0;
+
+	if ((hMenu_desc = RSC_LoadResource(instance, menu_name, (LPSTR) NE_RSCTYPE_MENU, NULL)) == (HANDLE) NULL)
+		return 0;
+	
+	menu_desc = (MENU_HEADER *) GlobalLock(hMenu_desc);
+	hMenu = LoadMenuIndirect((LPSTR)menu_desc);
+	return hMenu;
+}
+
+/**********************************************************************
+ *					LoadBitmap
+ */
+HBITMAP 
+LoadBitmap(HANDLE instance, LPSTR bmp_name)
+{
+    HBITMAP hbitmap;
+    HANDLE rsc_mem;
+    HDC hdc;
+    long *lp;
+    int image_size;
+    int size;
+    
+#ifdef DEBUG_RESOURCE
+	printf("LoadBitmap(%04X", instance);
+	PrintId(bmp_name);
+	printf(")\n");
+#endif
+
+    if (!instance) {
+	hbitmap = BITMAP_LoadOEMBitmap(((int) bmp_name) & 0xffff);
+	if (hbitmap)
+		return hbitmap;
+    }
+
+    rsc_mem = RSC_LoadResource(instance, bmp_name, (LPSTR) NE_RSCTYPE_BITMAP, 
+			       &image_size);
+    if (rsc_mem == (HANDLE)NULL) {
+	printf("LoadBitmap(%04X", instance);
+	PrintId(bmp_name);
+	printf(") NOT found!\n");
+	return 0;
+	}
+    lp = (long *) GlobalLinearLock(rsc_mem);
+    if (!(hdc = GetDC(0))) lp == NULL;
+    if (lp == NULL)
+    {
+	GlobalFree(rsc_mem);
+	return 0;
+    }
+    size = CONV_LONG (*lp);
+    if (size == sizeof(BITMAPCOREHEADER)){
+	CONV_BITMAPCOREHEADER (lp);
+	hbitmap = ConvertCoreBitmap( hdc, (BITMAPCOREHEADER *) lp );
+    } else if (size == sizeof(BITMAPINFOHEADER)){
+	CONV_BITMAPINFO (lp);
+	hbitmap = ConvertInfoBitmap( hdc, (BITMAPINFO *) lp );
+    } else hbitmap = 0;
+    GlobalFree(rsc_mem);
+    ReleaseDC( 0, hdc );
+    return hbitmap;
+}
diff --git a/loader/selector.c b/loader/selector.c
index 03711aa..b38feeb 100644
--- a/loader/selector.c
+++ b/loader/selector.c
@@ -12,6 +12,7 @@
 #include <errno.h>
 
 #ifdef __linux__
+#include <sys/mman.h>
 #include <linux/unistd.h>
 #include <linux/head.h>
 #include <linux/mman.h>
@@ -28,8 +29,10 @@
 #include "wine.h"
 #include "windows.h"
 #include "prototypes.h"
+#include "debug.h"
 
 /* #define DEBUG_SELECTORS /* */
+/* #undef DEBUG_SELECTORS /* */
 
 #ifdef linux
 #define DEV_ZERO
@@ -60,7 +63,6 @@
 
 extern void KERNEL_Ordinal_102();
 extern void UNIXLIB_Ordinal_0();
-extern char *WIN_ProgramName;
 extern char WindowsPath[256];
 
 extern char **Argv;
@@ -505,8 +507,7 @@
     i = FindUnusedSelectors(n_segments);
 
 #ifdef DEBUG_SELECTORS    
-    fprintf(stderr, 
-	    "Using %d segments starting at index %d.\n", n_segments, i);
+    fprintf(stddeb, "Using %d segments starting at index %d.\n", n_segments, i);
 #endif
 
     /*
@@ -609,10 +610,10 @@
 	/* Not a builtin symbol, look to see what the file has for us */
 	for(wpnt = wine_files; wpnt; wpnt = wpnt->next){
 		if(strcasecmp(wpnt->name, dll_name)) continue;
-		cpnt  = wpnt->nrname_table;
+		cpnt  = wpnt->ne->nrname_table;
 		while(1==1){
-			if( ((int) cpnt)  - ((int)wpnt->nrname_table) >  
-			   wpnt->ne_header->nrname_tab_length)  return 1;
+			if( ((int) cpnt)  - ((int)wpnt->ne->nrname_table) >  
+			   wpnt->ne->ne_header->nrname_tab_length)  return 1;
 			len = *cpnt++;
 			if(strncmp(cpnt, function, len) ==  0) break;
 			cpnt += len + 2;
@@ -662,9 +663,8 @@
 {
    int fd =  wpnt->fd;
    struct mz_header_s *mz_header = wpnt->mz_header;   
-   struct ne_header_s *ne_header = wpnt->ne_header;   
+   struct ne_header_s *ne_header = wpnt->ne->ne_header;   
 
-   
     union lookup entry_tab_pointer;
     struct entry_tab_header_s *eth;
     struct entry_tab_movable_s *etm;
@@ -672,8 +672,7 @@
     int current_ordinal;
     int i;
     
-
-   entry_tab_pointer.cpnt = wpnt->lookup_table;
+   entry_tab_pointer.cpnt = wpnt->ne->lookup_table;
     /*
      * Let's walk through the table until we get to our entry.
      */
@@ -707,7 +706,7 @@
 		if (current_ordinal == ordinal)
 		{
 		    return ((unsigned int) 
-			    (wpnt->selector_table[etm->seg_number - 1].base_addr + 
+			    (wpnt->ne->selector_table[etm->seg_number - 1].base_addr + 
 			     etm->offset));
 		}
 	    }
@@ -718,7 +717,7 @@
 		if (current_ordinal == ordinal)
 		{
 		    return ((unsigned int) 
-			    (wpnt->selector_table[eth->seg_number - 1].base_addr + 
+			    (wpnt->ne->selector_table[eth->seg_number - 1].base_addr + 
 			     (int) etf->offset[0] + 
 			     ((int) etf->offset[1] << 8)));
 		}
@@ -728,73 +727,6 @@
 }
 
 /**********************************************************************
- */
-void
-FixupFunctionPrologs(struct w_files * wpnt)
-{
-    struct mz_header_s *mz_header = wpnt->mz_header;   
-    struct ne_header_s *ne_header = wpnt->ne_header;   
-    union lookup entry_tab_pointer;
-    struct entry_tab_header_s *eth;
-    struct entry_tab_movable_s *etm;
-    struct entry_tab_fixed_s *etf;
-    unsigned char *fixup_ptr;
-    int i;
-
-    if (!(ne_header->format_flags & 0x0001))
-	return;
-
-    entry_tab_pointer.cpnt = wpnt->lookup_table;
-    /*
-     * Let's walk through the table and fixup prologs as we go.
-     */
-    while (1)
-    {
-	/* Get bundle header */
-	eth = entry_tab_pointer.eth++;
-
-	/* Check for end of table */
-	if (eth->n_entries == 0)
-	    return;
-
-	/* Check for empty bundle */
-	if (eth->seg_number == 0)
-	    continue;
-
-	/* Examine each bundle */
-	for (i = 0; i < eth->n_entries; i++)
-	{
-	    /* Moveable segment */
-	    if (eth->seg_number >= 0xfe)
-	    {
-		etm = entry_tab_pointer.etm++;
-		fixup_ptr = (wpnt->selector_table[etm->seg_number-1].base_addr
-			     + etm->offset);
-	    }
-	    else
-	    {
-		etf = entry_tab_pointer.etf++;
-		fixup_ptr = (wpnt->selector_table[eth->seg_number-1].base_addr
-			     + (int) etf->offset[0] 
-			     + ((int) etf->offset[1] << 8));
-
-	    }
-
-	    /* Verify the signature */
-	    if (((fixup_ptr[0] == 0x1e && fixup_ptr[1] == 0x58)
-		 || (fixup_ptr[0] == 0x8c && fixup_ptr[1] == 0xd8))
-		&& fixup_ptr[2] == 0x90)
-	    {
-		fixup_ptr[0] = 0xb8;	/* MOV AX, */
-		fixup_ptr[1] = wpnt->hinstance;
-		fixup_ptr[2] = (wpnt->hinstance >> 8);
-	    }
-	}
-    }
-}
-
-
-/**********************************************************************
  *					GetDOSEnvironment
  */
 LPSTR GetDOSEnvironment(void)
@@ -810,7 +742,6 @@
 {
     char **e;
     char *p;
-    unsigned short *w;
     SEGDESC * s;
 
     s = CreateNewSegments(0, 0, PAGE_SIZE, 1);
@@ -836,18 +767,15 @@
     }
 
     *p++ = '\0';
-    w = (unsigned short *) p;
-    *w = strlen(WIN_ProgramName);
-    strcpy(p + 2, WIN_ProgramName);
 
     /*
      * Display environment
      */
-    fprintf(stderr, "Environment at %08.8x\n", s->base_addr);
+#ifdef DEBUG_SELECTORS
+    fprintf(stddeb, "Environment at %08.8x\n", s->base_addr);
     for (p = s->base_addr; *p; p += strlen(p) + 1)
-	fprintf(stderr, "    %s\n", p);
-    p += 3;
-    fprintf(stderr, "    Program: %s\n", p);
+	fprintf(stddeb, "    %s\n", p);
+#endif
 
     return  s;
 }
@@ -918,8 +846,8 @@
 CreateSelectors(struct  w_files * wpnt)
 {
     int fd = wpnt->fd;
-    struct ne_segment_table_entry_s *seg_table = wpnt->seg_table;
-    struct ne_header_s *ne_header = wpnt->ne_header;
+    struct ne_segment_table_entry_s *seg_table = wpnt->ne->seg_table;
+    struct ne_header_s *ne_header = wpnt->ne->ne_header;
     SEGDESC *selectors, *s, *stmp;
     unsigned short auto_data_sel;
     int contents, read_only;
@@ -1059,13 +987,78 @@
 
     return selectors;
 }
+/**********************************************************************
+ */
+void
+FixupFunctionPrologs(struct w_files * wpnt)
+{
+    struct mz_header_s *mz_header = wpnt->mz_header;   
+    struct ne_header_s *ne_header = wpnt->ne->ne_header;   
+    union lookup entry_tab_pointer;
+    struct entry_tab_header_s *eth;
+    struct entry_tab_movable_s *etm;
+    struct entry_tab_fixed_s *etf;
+    unsigned char *fixup_ptr;
+    int i;
+
+    if (!(ne_header->format_flags & 0x0001))
+	return;
+
+    entry_tab_pointer.cpnt = wpnt->ne->lookup_table;
+    /*
+     * Let's walk through the table and fixup prologs as we go.
+     */
+    while (1)
+    {
+	/* Get bundle header */
+	eth = entry_tab_pointer.eth++;
+
+	/* Check for end of table */
+	if (eth->n_entries == 0)
+	    return;
+
+	/* Check for empty bundle */
+	if (eth->seg_number == 0)
+	    continue;
+
+	/* Examine each bundle */
+	for (i = 0; i < eth->n_entries; i++)
+	{
+	    /* Moveable segment */
+	    if (eth->seg_number >= 0xfe)
+	    {
+		etm = entry_tab_pointer.etm++;
+		fixup_ptr = (wpnt->ne->selector_table[etm->seg_number-1].base_addr
+			     + etm->offset);
+	    }
+	    else
+	    {
+		etf = entry_tab_pointer.etf++;
+		fixup_ptr = (wpnt->ne->selector_table[eth->seg_number-1].base_addr
+			     + (int) etf->offset[0] 
+			     + ((int) etf->offset[1] << 8));
+
+	    }
+
+	    /* Verify the signature */
+	    if (((fixup_ptr[0] == 0x1e && fixup_ptr[1] == 0x58)
+		 || (fixup_ptr[0] == 0x8c && fixup_ptr[1] == 0xd8))
+		&& fixup_ptr[2] == 0x90)
+	    {
+		fixup_ptr[0] = 0xb8;	/* MOV AX, */
+		fixup_ptr[1] = wpnt->hinstance;
+		fixup_ptr[2] = (wpnt->hinstance >> 8);
+	    }
+	}
+    }
+}
 
 /***********************************************************************
  *	GetSelectorBase (KERNEL.186)
  */
 DWORD GetSelectorBase(WORD wSelector)
 {
-	fprintf(stderr, "GetSelectorBase(selector %4X) stub!\n", wSelector);
+	fprintf(stdnimp, "GetSelectorBase(selector %4X) stub!\n", wSelector);
 }
 
 /***********************************************************************
@@ -1073,7 +1066,7 @@
  */
 void SetSelectorBase(WORD wSelector, DWORD dwBase)
 {
-	fprintf(stderr, "SetSelectorBase(selector %4X, base %8X) stub!\n",
+	fprintf(stdnimp, "SetSelectorBase(selector %4X, base %8X) stub!\n",
 			wSelector, dwBase);
 }
 
@@ -1082,7 +1075,7 @@
  */
 DWORD GetSelectorLimit(WORD wSelector)
 {
-	fprintf(stderr, "GetSelectorLimit(selector %4X) stub!\n", wSelector);
+	fprintf(stdnimp, "GetSelectorLimit(selector %4X) stub!\n", wSelector);
 
 	return 0xffff;
 }
@@ -1092,7 +1085,7 @@
  */
 void SetSelectorLimit(WORD wSelector, DWORD dwLimit)
 {
-	fprintf(stderr, "SetSelectorLimit(selector %4X, base %8X) stub!\n", 
+	fprintf(stdnimp, "SetSelectorLimit(selector %4X, base %8X) stub!\n", 
 			wSelector, dwLimit);
 }
 
diff --git a/loader/signal.c b/loader/signal.c
index d9eb717..24256e4 100644
--- a/loader/signal.c
+++ b/loader/signal.c
@@ -12,14 +12,26 @@
 #include <syscall.h>
 #endif
 #ifdef linux
+#define inline __inline__  /* So we can compile with -ansi */
 #include <linux/sched.h>
 #include <asm/system.h>
+#undef inline
 #endif
 
 #include "wine.h"
 #include "segmem.h"
 #include "prototypes.h"
 #include "win.h"
+
+extern int do_int10(struct sigcontext_struct *);
+extern int do_int13(struct sigcontext_struct *);
+extern int do_int15(struct sigcontext_struct *);
+extern int do_int16(struct sigcontext_struct *);
+extern int do_int25(struct sigcontext_struct *);
+extern int do_int26(struct sigcontext_struct *);
+extern int do_int2a(struct sigcontext_struct *);
+extern int do_int2f(struct sigcontext_struct *);
+extern int do_int31(struct sigcontext_struct *);
  
 #if !defined(BSD4_4) || defined(linux)
 char * cstack[4096];
@@ -90,8 +102,6 @@
 {
 #endif
     unsigned char * instr;
-    unsigned int * dump;
-    int i;
 
 	/* First take care of a few preliminaries */
 #ifdef linux
diff --git a/loader/task.c b/loader/task.c
index d227640..d43e404 100644
--- a/loader/task.c
+++ b/loader/task.c
@@ -3,9 +3,6 @@
  */
 static char Copyright[] = "Copyright  Martin Ayotte, 1994";
 
-/*
-#define DEBUG_TASK
-*/
 
 #include <stdio.h>
 #include <stdlib.h>
@@ -15,6 +12,12 @@
 #include "windows.h"
 #include "wine.h"
 #include "task.h"
+#include "debug.h"
+
+
+/* #define DEBUG_TASK /* */
+/* #undef DEBUG_TASK /* */
+
 
 static LPWINETASKENTRY lpTaskList = NULL;
 static int nTaskCount = 0;
@@ -27,7 +30,7 @@
 	LPWINETASKENTRY lpTask = lpTaskList;
 	int pid = getpid();
 #ifdef DEBUG_TASK
-	printf("GetCurrentTask() // unix_pid=%08X !\n", pid);
+	fprintf(stddeb,"GetCurrentTask() // unix_pid=%08X !\n", pid);
 #endif
 	if (lpTask == NULL) return 0;
 	while (TRUE) {
@@ -36,7 +39,7 @@
 		lpTask = lpTask->lpNextTask;
 		}
 #ifdef DEBUG_TASK
-	printf("GetCurrentTask() returned hTask=%04X !\n", lpTask->te.hTask);
+	fprintf(stddeb,"GetCurrentTask() returned hTask=%04X !\n", lpTask->te.hTask);
 #endif
 	return lpTask->te.hTask;
 }
@@ -47,7 +50,9 @@
  */
 WORD GetNumTasks()
 {
-	printf("GetNumTasks() returned %d !\n", nTaskCount);
+#ifdef DEBUG_TASK
+	fprintf(stddeb,"GetNumTasks() returned %d !\n", nTaskCount);
+#endif
 	return nTaskCount;
 }
 
@@ -60,17 +65,23 @@
 	HWND 	*wptr;
 	int		count;
 	LPWINETASKENTRY lpTask = lpTaskList;
-	printf("GetWindowTask(%04X) !\n", hWnd);
+#ifdef DEBUG_TASK
+	fprintf(stddeb,"GetWindowTask(%04X) !\n", hWnd);
+#endif
 	while (lpTask != NULL) {
 		wptr = lpTask->lpWndList;
 		if (wptr != NULL) {
 			count = 0;
 			while (++count < MAXWIN_PER_TASK) {
-				printf("GetWindowTask // searching %04X %04X !\n",
+#ifdef DEBUG_TASK
+				fprintf(stddeb,"GetWindowTask // searching %04X %04X !\n",
 										lpTask->te.hTask, *(wptr));
+#endif
 				if (*(wptr) == hWnd) {
-					printf("GetWindowTask(%04X) found hTask=%04X !\n", 
+#ifdef DEBUG_TASK
+					fprintf(stddeb,"GetWindowTask(%04X) found hTask=%04X !\n", 
 												hWnd, lpTask->te.hTask);
+#endif
 					return lpTask->te.hTask;
 					}
 				wptr++;
@@ -91,22 +102,30 @@
 	BOOL	bRet;
 	int		count = 0;
 	LPWINETASKENTRY lpTask = lpTaskList;
-	printf("EnumTaskWindows(%04X, %08X, %08X) !\n", hTask, lpEnumFunc, lParam);
+#ifdef DEBUG_TASK
+	fprintf(stddeb,"EnumTaskWindows(%04X, %08X, %08X) !\n", hTask, lpEnumFunc, lParam);
+#endif
 	while (TRUE) {
 		if (lpTask->te.hTask == hTask) break;
 		if (lpTask == NULL) {
-			printf("EnumTaskWindows // hTask=%04X not found !\n", hTask);
+#ifdef DEBUG_TASK
+			fprintf(stddeb,"EnumTaskWindows // hTask=%04X not found !\n", hTask);
+#endif
 			return FALSE;
 			}
 		lpTask = lpTask->lpNextTask;
 		}
-	printf("EnumTaskWindows // found hTask=%04X !\n", hTask);
+#ifdef DEBUG_TASK
+	fprintf(stddeb,"EnumTaskWindows // found hTask=%04X !\n", hTask);
+#endif
 	wptr = lpTask->lpWndList;
 	if (wptr == NULL) return FALSE;
 	if (lpEnumFunc == NULL)	return FALSE;
 	while ((hWnd = *(wptr++)) != 0) {
 		if (++count >= MAXWIN_PER_TASK) return FALSE;
-		printf("EnumTaskWindows // hWnd=%04X count=%d !\n", hWnd, count);
+#ifdef DEBUG_TASK
+		fprintf(stddeb,"EnumTaskWindows // hWnd=%04X count=%d !\n", hWnd, count);
+#endif
 #ifdef WINELIB
 		bRet = (*lpEnumFunc)(hWnd, lParam); 
 #else
@@ -140,7 +159,7 @@
 	hTask = GlobalAlloc(GMEM_MOVEABLE, sizeof(WINETASKENTRY));
 	lpNewTask = (LPWINETASKENTRY) GlobalLock(hTask);
 #ifdef DEBUG_TASK
-    printf("CreateNewTask entry allocated %08X\n", lpNewTask);
+    fprintf(stddeb,"CreateNewTask entry allocated %08X\n", lpNewTask);
 #endif
 	if (lpNewTask == NULL) return 0;
 	if (lpTaskList == NULL) {
@@ -173,7 +192,7 @@
 	if (lpNewTask->lpWndList != NULL) 
 		memset((LPSTR)lpNewTask->lpWndList, 0, MAXWIN_PER_TASK * sizeof(HWND));
 #ifdef DEBUG_TASK
-    printf("CreateNewTask // unix_pid=%08X return hTask=%04X\n", 
+    fprintf(stddeb,"CreateNewTask // unix_pid=%08X return hTask=%04X\n", 
 									lpNewTask->unix_pid, hTask);
 #endif
 	GlobalUnlock(hTask);	
@@ -191,12 +210,12 @@
 	int		count = 0;
 	LPWINETASKENTRY lpTask = lpTaskList;
 #ifdef DEBUG_TASK
-	printf("AddWindowToTask(%04X, %04X); !\n", hTask, hWnd);
+	fprintf(stddeb,"AddWindowToTask(%04X, %04X); !\n", hTask, hWnd);
 #endif
 	while (TRUE) {
 		if (lpTask->te.hTask == hTask) break;
 		if (lpTask == NULL) {
-			printf("AddWindowToTask // hTask=%04X not found !\n", hTask);
+			fprintf(stderr,"AddWindowToTask // hTask=%04X not found !\n", hTask);
 			return FALSE;
 			}
 		lpTask = lpTask->lpNextTask;
@@ -209,7 +228,7 @@
 		}
 	*wptr = hWnd;
 #ifdef DEBUG_TASK
-	printf("AddWindowToTask // window added, count=%d !\n", count);
+	fprintf(stddeb,"AddWindowToTask // window added, count=%d !\n", count);
 #endif
 	return TRUE;
 }
@@ -224,12 +243,12 @@
 	int		count = 0;
 	LPWINETASKENTRY lpTask = lpTaskList;
 #ifdef DEBUG_TASK
-	printf("RemoveWindowToTask(%04X, %04X); !\n", hTask, hWnd);
+	fprintf(stddeb,"RemoveWindowToTask(%04X, %04X); !\n", hTask, hWnd);
 #endif
 	while (TRUE) {
 		if (lpTask->te.hTask == hTask) break;
 		if (lpTask == NULL) {
-			printf("RemoveWindowFromTask // hTask=%04X not found !\n", hTask);
+			fprintf(stderr,"RemoveWindowFromTask // hTask=%04X not found !\n", hTask);
 			return FALSE;
 			}
 		lpTask = lpTask->lpNextTask;
@@ -246,15 +265,16 @@
 		wptr++;
 		}
 #ifdef DEBUG_TASK
-	printf("RemoveWindowFromTask // window removed, count=%d !\n", --count);
+	fprintf(stddeb,"RemoveWindowFromTask // window removed, count=%d !\n", --count);
 #endif
 	return TRUE;
 }
 
 BOOL TaskFirst(LPTASKENTRY lpTask)
 {
-	printf("TaskFirst(%8x)\n", (int) lpTask);
-
+#ifdef DEBUG_TASK
+	fprintf(stddeb,"TaskFirst(%8x)\n", (int) lpTask);
+#endif
 	if (lpTaskList) {
 		memcpy(lpTask, &lpTaskList->te, lpTask->dwSize);
 		return TRUE;
@@ -265,9 +285,9 @@
 BOOL TaskNext(LPTASKENTRY lpTask)
 {
 	LPWINETASKENTRY list;
-	
-	printf("TaskNext(%8x)\n", (int) lpTask);
-
+#ifdef DEBUG_TASK	
+	fprintf(stddeb,"TaskNext(%8x)\n", (int) lpTask);
+#endif
 	list = lpTaskList;
 	while (list) {
 		if (list->te.hTask == lpTask->hTask) {
@@ -286,9 +306,9 @@
 BOOL TaskFindHandle(LPTASKENTRY lpTask, HTASK hTask)
 {
 	static LPWINETASKENTRY list;
-	
-	printf("TaskFindHandle(%8x,%4x)\n", (int) lpTask, hTask);
-
+#ifdef DEBUG_TASK	
+	fprintf(stddeb,"TaskFindHandle(%8x,%4x)\n", (int) lpTask, hTask);
+#endif
 	list = lpTaskList;
 	while (list) {
 		if (list->te.hTask == hTask) {
diff --git a/memory/Imakefile b/memory/Imakefile
index 57b61f2..d6586b9 100644
--- a/memory/Imakefile
+++ b/memory/Imakefile
@@ -11,7 +11,6 @@
 
 WineRelocatableTarget($(TOP)/$(MODULE),,$(OBJS))
 DependTarget()
-CleanTarget()
 
 includes::
 
diff --git a/memory/global.c b/memory/global.c
index 117c532..8ab7d2e 100644
--- a/memory/global.c
+++ b/memory/global.c
@@ -1,7 +1,6 @@
 static char RCSId[] = "$Id: global.c,v 1.2 1993/07/04 04:04:21 root Exp root $";
 static char Copyright[] = "Copyright  Robert J. Amstadt, 1993";
 
-/* #define DEBUG_HEAP /* */
 #define GLOBAL_SOURCE
 
 #include <stdio.h>
@@ -11,6 +10,11 @@
 #include "toolhelp.h"
 #include "heap.h"
 #include "segmem.h"
+#include "stddebug.h"
+/* #define DEBUG_HEAP /* */
+/* #undef  DEBUG_HEAP /* */
+#include "debug.h"
+
 
 GDESC *GlobalList = NULL;
 static unsigned short next_unused_handle = 1;
@@ -99,7 +103,7 @@
 	s = CreateNewSegments(0, 0, 0x10000, n_segments);
 	if (s == NULL) 
 	{
-	    printf("GlobalGetFreeSegments // bad CreateNewSegments !\n");
+	    fprintf(stderr,"GlobalGetFreeSegments // bad CreateNewSegments !\n");
 	    return NULL;
 	}
 	for (count = 0; count < n_segments; count++, s++)
@@ -107,7 +111,7 @@
 	    g = (GDESC *) malloc(sizeof(*g));
 	    if (g == NULL) 
 	    {
-		printf("GlobalGetFreeSegments // bad GDESC malloc !\n");
+		fprintf(stderr,"GlobalGetFreeSegments // bad GDESC malloc !\n");
 		return NULL;
 	    }
 	    g->prev         = g_prev;
@@ -145,7 +149,7 @@
     {
 	if (g == NULL) 
 	{
-	    printf("GlobalGetFreeSegments // bad Segments chain !\n");
+	    fprintf(stderr,"GlobalGetFreeSegments // bad Segments chain !\n");
 	    return NULL;
 	}
 	g->sequence     = i + 1;
@@ -178,9 +182,9 @@
     GDESC *g_prev;
     void *m;
 
-#ifdef DEBUG_HEAP
-	printf("GlobalAlloc flags %4X, size %d\n", flags, size);
-#endif
+    dprintf_heap(stddeb,"GlobalAlloc flags %4X, size %d\n", flags, size);
+
+    if (size == 0) size = 1;
 
     /*
      * If this block is fixed or very big we need to allocate entire
@@ -243,9 +247,7 @@
 	 * We have a new block.  Let's create a GDESC entry for it.
 	 */
 	g = malloc(sizeof(*g));
-#ifdef DEBUG_HEAP
-	printf("New GDESC %08x\n", g);
-#endif
+	dprintf_heap(stddeb,"New GDESC %08x\n", g);
 	if (g == NULL)
 	    return 0;
 
@@ -268,9 +270,7 @@
 	if ((next_unused_handle & 7) == 7)
 	    next_unused_handle++;
 	
-#ifdef DEBUG_HEAP
-	printf("GlobalAlloc: returning %04x\n", g->handle);
-#endif
+	dprintf_heap(stddeb,"GlobalAlloc: returning %04x\n", g->handle);
 	return g->handle;
     }
 }
@@ -344,9 +344,7 @@
 
     g->lock_count++;
 
-#ifdef DEBUG_HEAP
-    printf("GlobalLock: returning %08x\n", g->addr);
-#endif
+    dprintf_heap(stddeb,"GlobalLock: returning %08x\n", g->addr);
     return g->addr;
 }
 
@@ -804,8 +802,8 @@
     for (i = 0; i < 512; i++)
 	if (free_map[i] == 1)
 	    total_free++;
-    
-    printf("GetFreeSpace // return %ld !\n", total_free << 16);
+
+    dprintf_heap(stddeb,"GetFreeSpace // return %ld !\n", total_free << 16);
     return total_free << 16;
 }
 
@@ -816,3 +814,12 @@
 {
 	return 1;
 }
+
+/***********************************************************************
+ *           SetSwapAreaSize   (KERNEL.106)
+ */
+LONG SetSwapAreaSize( WORD size )
+{
+    printf( "STUB: SetSwapAreaSize(%d)\n", size );
+    return MAKELONG( size, 0xffff );
+}
diff --git a/memory/heap.c b/memory/heap.c
index be39fe0..fa2956b 100644
--- a/memory/heap.c
+++ b/memory/heap.c
@@ -8,8 +8,11 @@
 #include "segmem.h"
 #include "heap.h"
 #include "regfunc.h"
-
+#include "stddebug.h"
 /* #define DEBUG_HEAP /* */
+/* #undef  DEBUG_HEAP /* */
+#include "debug.h"
+
 
 LHEAP *LocalHeaps = NULL;
 
@@ -46,9 +49,9 @@
 {
     MDESC *m, *m_new;
     
-#ifdef DEBUG_HEAP
-    printf("HeapAlloc: free_list %08x, flags %x, bytes %d\n", 
+    dprintf_heap(stddeb,"HeapAlloc: free_list %08x, flags %x, bytes %d\n", 
 	   free_list, flags, bytes);
+#ifdef DEBUG_HEAP
     HEAP_CheckHeap(free_list);
 #endif
 
@@ -83,8 +86,8 @@
 	    m->flags = 0;
 	    if (flags & GLOBAL_FLAGS_ZEROINIT)
 		memset(m + 1, 0, bytes);
+	    dprintf_heap(stddeb,"HeapAlloc: returning %08x\n", (m + 1));
 #ifdef DEBUG_HEAP
-	    printf("HeapAlloc: returning %08x\n", (m + 1));
 	    HEAP_CheckHeap(free_list);
 #endif
 	    return (void *) (m + 1);
@@ -107,15 +110,15 @@
 	m->flags = 0;
 	if (flags & GLOBAL_FLAGS_ZEROINIT)
 	    memset(m + 1, 0, bytes);
+	dprintf_heap(stddeb,"HeapAlloc: returning %08x\n", (m + 1));
 #ifdef DEBUG_HEAP
-	printf("HeapAlloc: returning %08x\n", (m + 1));
 	HEAP_CheckHeap(free_list);
 #endif
 	return (void *) (m + 1);
     }
 
+    dprintf_heap(stddeb,"HeapAlloc: returning %08x\n", 0);
 #ifdef DEBUG_HEAP
-    printf("HeapAlloc: returning %08x\n", 0);
     HEAP_CheckHeap(free_list);
 #endif
     return 0;
@@ -140,40 +143,36 @@
      */
     m = (MDESC *) old_block - 1;
 
+    dprintf_heap(stddeb,"HEAP_ReAlloc new_size=%d !\n", new_size);
+    dprintf_heap(stddeb,"HEAP_ReAlloc old_block=%08X !\n", old_block);
+    dprintf_heap(stddeb,"HEAP_ReAlloc m=%08X free_list=%08X !\n", m,free_list);
+    dprintf_heap(stddeb,"HEAP_ReAlloc m->prev=%08X !\n", m->prev);
+    dprintf_heap(stddeb,"HEAP_ReAlloc m->next=%08X !\n", m->next);
+    dprintf_heap(stddeb,"HEAP_ReAlloc *free_list=%08X !\n", *free_list);
 #ifdef DEBUG_HEAP
-    printf("HEAP_ReAlloc new_size=%d !\n", new_size);
-    printf("HEAP_ReAlloc old_block=%08X !\n", old_block);
-    printf("HEAP_ReAlloc m=%08X free_list=%08X !\n", m, free_list);
-    printf("HEAP_ReAlloc m->prev=%08X !\n", m->prev);
-    printf("HEAP_ReAlloc m->next=%08X !\n", m->next);
-    printf("HEAP_ReAlloc *free_list=%08X !\n", *free_list);
     HEAP_CheckHeap(free_list);
 #endif
 
     if (m->prev != m || m->next != m || 
 	((int) m & 0xffff0000) != ((int) *free_list & 0xffff0000))
     {
-#ifdef DEBUG_HEAP
-	printf("Attempt to resize bad pointer, m = %08x, *free_list = %08x\n",
+	fprintf(stderr,"Attempt to resize bad pointer, m = %08x, *free_list = %08x\n",
 	       m, free_list);
 	HEAP_CheckHeap(free_list);
-#endif
 	return NULL;
     }
     
     /*
      * Check for grow block
      */
-#ifdef DEBUG_HEAP
-    printf("HEAP_ReAlloc Check for grow block !\n");
-#endif
 
+    dprintf_heap(stddeb,"HEAP_ReAlloc Check for grow block !\n");
     if (new_size > m->length)
     {
 	m_free = m + 1 + m->length / sizeof(MDESC);
 	if (m_free->next == m_free || 
 	    m_free->prev == m_free ||
-	    m_free->length + sizeof(MDESC) < new_size)
+	    m_free->length + 2*sizeof(MDESC) < new_size - m->length)
 	{
 	    void *new_p = HEAP_Alloc(free_list, flags, new_size);
 	    if (new_p ==NULL)
@@ -196,9 +195,7 @@
 	
 	m->length += sizeof(MDESC) + m_free->length;
 
-#ifdef DEBUG_HEAP
-	printf("HEAP_ReAlloc before GLOBAL_FLAGS_ZEROINIT !\n");
-#endif
+	dprintf_heap(stddeb,"HEAP_ReAlloc before GLOBAL_FLAGS_ZEROINIT !\n");
 	if (flags & GLOBAL_FLAGS_ZEROINIT)
 	    memset(m_free, '\0', sizeof(MDESC) + m_free->length);
     }
@@ -206,15 +203,13 @@
     /*
      * Check for shrink block.
      */
-#ifdef DEBUG_HEAP
-	printf("HEAP_ReAlloc Check for shrink block !\n");
-#endif
-    if (new_size < m->length - 4 * sizeof(MDESC))
+    dprintf_heap(stddeb,"HEAP_ReAlloc Check for shrink block !\n");
+    if (new_size + 4*sizeof(MDESC) < m->length)
     {
 	m_free = m + new_size / sizeof(MDESC) + 2;
 	m_free->next = m_free;
 	m_free->prev = m_free;
-	m_free->length = m->length - (int) m_free - (int) m;
+	m_free->length = m->length - ((int) m_free - (int) m);
 	m->length = (int) m_free - (int) (m + 1);
 	HEAP_Free(free_list, m_free + 1);
     }
@@ -236,9 +231,9 @@
     MDESC *m;
     MDESC *m_prev;
 
-#ifdef DEBUG_HEAP
-    printf("HeapFree: free_list %08x, block %08x\n", 
+    dprintf_heap(stddeb,"HeapFree: free_list %08x, block %08x\n", 
 	   free_list, block);
+#ifdef DEBUG_HEAP
     HEAP_CheckHeap(free_list);
 #endif
 
@@ -248,11 +243,9 @@
     m_free = (MDESC *) block - 1;
     if (m_free->prev != m_free || m_free->next != m_free)
     {
-#ifdef DEBUG_HEAP
-	printf("Attempt to free bad pointer,"
+	fprintf(stderr,"Attempt to free bad pointer,"
 	       "m_free = %08x, *free_list = %08x\n",
 	       m_free, free_list);
-#endif
 	return -1;
     }
 
@@ -265,11 +258,9 @@
     }
     else if (((int) m_free & 0xffff0000) != ((int) *free_list & 0xffff0000))
     {
-#ifdef DEBUG_HEAP
-	printf("Attempt to free bad pointer,"
+	fprintf(stderr,"Attempt to free bad pointer,"
 	       "m_free = %08x, *free_list = %08x\n",
 	       m_free, free_list);
-#endif
 	return -1;
     }
 
@@ -282,22 +273,18 @@
     
     if (m_prev != NULL && (int) m_prev + m_prev->length > (int) m_free)
     {
-#ifdef DEBUG_HEAP
-	printf("Attempt to free bad pointer,"
+	fprintf(stderr,"Attempt to free bad pointer,"
 	       "m_free = %08x, m_prev = %08x (length %x)\n",
 	       m_free, m_prev, m_prev->length);
-#endif
 	return -1;
     }
 	
     if ((m != NULL && (int) m_free + m_free->length > (int) m) ||
 	(int) m_free + m_free->length > ((int) m_free | 0xffff))
     {
-#ifdef DEBUG_HEAP
-	printf("Attempt to free bad pointer,"
+	fprintf(stderr,"Attempt to free bad pointer,"
 	       "m_free = %08x (length %x), m = %08x\n",
 	       m_free, m_free->length, m);
-#endif
 	return -1;
     }
 
@@ -359,9 +346,7 @@
 {
     LHEAP *lh;
     
-#ifdef DEBUG_HEAP
-    printf("HEAP_LocalFindHeap: owner %04x\n", owner);
-#endif
+    dprintf_heap(stddeb,"HEAP_LocalFindHeap: owner %04x\n", owner);
     
     for (lh = LocalHeaps; lh != NULL; lh = lh->next)
     {
@@ -380,10 +365,8 @@
 {
     LHEAP *lh;
 
-#ifdef DEBUG_HEAP
-    printf("HEAP_LocalInit: owner %04x, start %08x, length %04x\n",
-	   owner, start, length);
-#endif
+    dprintf_heap(stddeb,"HEAP_LocalInit: owner %04x, start %08x, length %04x\n"
+	   ,owner, start, length);
 
     if (length < 2 * sizeof(MDESC))
 	return;
@@ -424,16 +407,12 @@
 {
     void *m;
     
-#ifdef DEBUG_HEAP
-    printf("WIN16_LocalAlloc: flags %x, bytes %d\n", flags, bytes);
-    printf("    called from segment %04x\n", Stack16Frame[11]);
-#endif
+    dprintf_heap(stddeb,"WIN16_LocalAlloc: flags %x, bytes %d\n", flags,bytes);
+    dprintf_heap(stddeb,"    called from segment %04x\n", Stack16Frame[11]);
 
     m = HEAP_Alloc(LOCALHEAP(), flags, bytes);
 	
-#ifdef DEBUG_HEAP
-	printf("WIN16_LocalAlloc: returning %x\n", (int) m);
-#endif
+    dprintf_heap(stddeb,"WIN16_LocalAlloc: returning %x\n", (int) m);
     return m;
 }
 
@@ -461,7 +440,7 @@
 WIN16_LocalFlags(unsigned int handle)
 {
     MDESC *m;
-    
+
     m = (MDESC *) (((int) *LOCALHEAP() & 0xffff0000) | 
 		   (handle & 0xffff)) - 1;
     if (m->next != m || m->prev != m)
@@ -510,7 +489,7 @@
 	HEAP_Init(&lh->free_list,
 		  (void *) ((segment << 16) | start), end - start + 1);
     }
-	printf("WIN16_LocalInit // return segment=%04X !\n", segment);
+    dprintf_heap(stddeb,"WIN16_LocalInit // return segment=%04X !\n", segment);
     return segment;
 }
 
@@ -521,7 +500,7 @@
 WIN16_LocalLock(unsigned int handle)
 {
     MDESC *m;
-    
+
     m = (MDESC *) (((int) *LOCALHEAP() & 0xffff0000) | 
 		   (handle & 0xffff)) - 1;
     if (m->next != m || m->prev != m)
@@ -538,11 +517,12 @@
 WIN16_LocalReAlloc(unsigned int handle, int bytes, int flags)
 {
     void *m;
-#ifdef DEBUG_HEAP
-	printf("WIN16_LocalReAlloc(%04X, %d, %04X); !\n",	handle, bytes, flags);
-	printf("WIN16_LocalReAlloc // LOCALHEAP()=%08X !\n", LOCALHEAP());
-	printf("WIN16_LocalReAlloc // *LOCALHEAP()=%08X !\n", *LOCALHEAP());
-#endif
+    dprintf_heap(stddeb,"WIN16_LocalReAlloc(%04X, %d, %04X); !\n",	
+		 handle, bytes, flags);
+    dprintf_heap(stddeb,"WIN16_LocalReAlloc // LOCALHEAP()=%08X !\n", 
+		 LOCALHEAP());
+    dprintf_heap(stddeb,"WIN16_LocalReAlloc // *LOCALHEAP()=%08X !\n", 
+		 *LOCALHEAP());
     m = HEAP_ReAlloc(LOCALHEAP(), (void *)
 		     (((int) *LOCALHEAP() & 0xffff0000) | (handle & 0xffff)),
 		     bytes, flags);
@@ -557,7 +537,7 @@
 WIN16_LocalSize(unsigned int handle)
 {
     MDESC *m;
-    
+
     m = (MDESC *) (((int) *LOCALHEAP() & 0xffff0000) | 
 		   (handle & 0xffff)) - 1;
     if (m->next != m || m->prev != m)
@@ -619,9 +599,7 @@
   unsigned int UserFree=0,UserResult=0;
   unsigned int result=0;
   MDESC *m;
-
-  printf("GetFreeSystemResources(%u)\n",SystemResourceType);
-
+  dprintf_heap(stddeb,"GetFreeSystemResources(%u)\n",SystemResourceType);
   switch(SystemResourceType) {
     case(USERRESOURCES):
       for (m = USER_Heap; m != NULL; m = m->next) /* add up free area in heap */
diff --git a/misc/Imakefile b/misc/Imakefile
index 09d194c..3bd175fd 100644
--- a/misc/Imakefile
+++ b/misc/Imakefile
@@ -7,7 +7,6 @@
 	atom.c \
 	clipboard.c \
 	comm.c \
-	cursor.c \
 	dos_fs.c \
 	driver.c \
 	exec.c \
@@ -35,7 +34,6 @@
 
 WineRelocatableTarget($(TOP)/$(MODULE),,$(OBJS))
 DependTarget()
-CleanTarget()
 
 includes::
 
diff --git a/misc/audio.c b/misc/audio.c
index 2d81e37..1aad3cd 100644
--- a/misc/audio.c
+++ b/misc/audio.c
@@ -1,4 +1,4 @@
-/*
+/*

  * Sample Wine Driver for Linux
  *
  * Copyright 1994 Martin Ayotte
@@ -11,20 +11,25 @@
 
 #ifdef BUILTIN_MMSYSTEM
 
-#define DEBUG_MCIWAVE
-
-#include "stdio.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
 #include "win.h"
 #include "user.h"
 #include "driver.h"
 #include "mmsystem.h"
 
-#include <fcntl.h>
-#include <sys/ioctl.h>
 #ifdef linux
 #include <linux/soundcard.h>
 #endif
 
+#include "stddebug.h"
+/* #define DEBUG_MCIWAVE /* */
+/* #undef  DEBUG_MCIWAVE /* */
+#include "debug.h"
+
 #ifdef linux
 #define SOUND_DEV "/dev/dsp"
 
@@ -107,7 +112,7 @@
 		WInDev[wDevID].waveDesc.dwCallBack, WInDev[wDevID].wFlags, 
 		WInDev[wDevID].waveDesc.hWave, wMsg, 
 		WInDev[wDevID].waveDesc.dwInstance, dwParam1, dwParam2)) {
-		printf("WAVE_NotifyClient // can't notify client !\n");
+		fprintf(stderr,"WAVE_NotifyClient // can't notify client !\n");
 		return MMSYSERR_NOERROR;
 		}
 #else
@@ -191,9 +196,7 @@
 	DWORD		dwRet;
 	char		str[128];
 	LPSTR		ptr;
-#ifdef DEBUG_MCIWAVE
-	printf("WAVE_mciOpen(%08X, %08X)\n", dwFlags, lpParms);
-#endif
+	dprintf_mciwave(stddeb,"WAVE_mciOpen(%08X, %08X)\n", dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	wDevID = lpParms->wDeviceID;
 	if (MCIWavDev[wDevID].nUseCount > 0) {
@@ -210,7 +213,7 @@
 		MCIWavDev[wDevID].fShareable = dwFlags & MCI_OPEN_SHAREABLE;
 		}
     if (dwFlags & MCI_OPEN_ELEMENT) {
-		printf("WAVE_mciOpen // MCI_OPEN_ELEMENT '%s' !\n", 
+        dprintf_mciwave(stddeb,"WAVE_mciOpen // MCI_OPEN_ELEMENT '%s' !\n",
 								lpParms->lpstrElementName);
 /*		printf("WAVE_mciOpen // cdw='%s'\n", DOS_GetCurrentDir(DOS_GetDefaultDrive())); */
 		if (strlen(lpParms->lpstrElementName) > 0) {
@@ -219,14 +222,14 @@
 			MCIWavDev[wDevID].hFile = mmioOpen(str, NULL, 
 				MMIO_ALLOCBUF | MMIO_READWRITE | MMIO_EXCLUSIVE);
 			if (MCIWavDev[wDevID].hFile == 0) {
-				printf("WAVE_mciOpen // can't find file='%s' !\n", str);
+				fprintf(stderr,"WAVE_mciOpen // can't find file='%s' !\n", str);
 				return MCIERR_FILE_NOT_FOUND;
 				}
 			}
 		else 
 			MCIWavDev[wDevID].hFile = 0;
 		}
-	printf("WAVE_mciOpen // hFile=%u\n", MCIWavDev[wDevID].hFile);
+	dprintf_mciwave(stddeb,"WAVE_mciOpen // hFile=%u\n", MCIWavDev[wDevID].hFile);
 	memcpy(&MCIWavDev[wDevID].openParms, lpParms, sizeof(MCI_WAVE_OPEN_PARMS));
 	MCIWavDev[wDevID].wNotifyDeviceID = lpParms->wDeviceID;
 	lpWaveFormat = &MCIWavDev[wDevID].WaveFormat;
@@ -244,11 +247,10 @@
 		if (mmioDescend(MCIWavDev[wDevID].hFile, &ckMainRIFF, NULL, 0) != 0) {
 			return MCIERR_INTERNAL;
 			}
-#ifdef DEBUG_MCIWAVE
-		printf("WAVE_mciOpen // ParentChunk ckid=%.4s fccType=%.4s cksize=%08lX \n",
+		dprintf_mciwave(stddeb,
+				"WAVE_mciOpen // ParentChunk ckid=%.4s fccType=%.4s cksize=%08lX \n",
 				(LPSTR)&ckMainRIFF.ckid, (LPSTR)&ckMainRIFF.fccType,
 				ckMainRIFF.cksize);
-#endif
 		if ((ckMainRIFF.ckid != FOURCC_RIFF) ||
 		    (ckMainRIFF.fccType != mmioFOURCC('W', 'A', 'V', 'E'))) {
 			return MCIERR_INTERNAL;
@@ -257,11 +259,10 @@
 		if (mmioDescend(MCIWavDev[wDevID].hFile, &mmckInfo, &ckMainRIFF, MMIO_FINDCHUNK) != 0) {
 			return MCIERR_INTERNAL;
 			}
-#ifdef DEBUG_MCIWAVE
-		printf("WAVE_mciOpen // Chunk Found ckid=%.4s fccType=%.4s cksize=%08lX \n",
+		dprintf_mciwave(stddeb,
+				"WAVE_mciOpen // Chunk Found ckid=%.4s fccType=%.4s cksize=%08lX \n",
 				(LPSTR)&mmckInfo.ckid, (LPSTR)&mmckInfo.fccType,
 				mmckInfo.cksize);
-#endif
 		if (mmioRead(MCIWavDev[wDevID].hFile, (HPSTR) lpWaveFormat,
 		    (long) sizeof(PCMWAVEFORMAT)) != (long) sizeof(PCMWAVEFORMAT)) {
 			return MCIERR_INTERNAL;
@@ -270,13 +271,13 @@
 		if (mmioDescend(MCIWavDev[wDevID].hFile, &mmckInfo, &ckMainRIFF, MMIO_FINDCHUNK) != 0) {
 			return MCIERR_INTERNAL;
 			}
-#ifdef DEBUG_MCIWAVE
-		printf("WAVE_mciOpen // Chunk Found ckid=%.4s fccType=%.4s cksize=%08lX \n",
+		dprintf_mciwave(stddeb,
+				"WAVE_mciOpen // Chunk Found ckid=%.4s fccType=%.4s cksize=%08lX \n",
 				(LPSTR)&mmckInfo.ckid, (LPSTR)&mmckInfo.fccType,
 				mmckInfo.cksize);
-		printf("WAVE_mciOpen // nChannels=%d nSamplesPerSec=%d\n",
+		dprintf_mciwave(stddeb,
+			"WAVE_mciOpen // nChannels=%d nSamplesPerSec=%d\n",
 			lpWaveFormat->wf.nChannels, lpWaveFormat->wf.nSamplesPerSec);
-#endif
 		lpWaveFormat->wBitsPerSample = 0;
 		}
 	lpWaveFormat->wf.nAvgBytesPerSec = 
@@ -296,9 +297,8 @@
 {
 #ifdef linux
 	DWORD		dwRet;
-#ifdef DEBUG_MCIWAVE
-	printf("WAVE_mciClose(%u, %08X, %08X);\n", wDevID, dwParam, lpParms);
-#endif
+	dprintf_mciwave(stddeb,
+		"WAVE_mciClose(%u, %08X, %08X);\n", wDevID, dwParam, lpParms);
 	MCIWavDev[wDevID].nUseCount--;
 	if (MCIWavDev[wDevID].nUseCount == 0) {
 		if (MCIWavDev[wDevID].hFile != 0) {
@@ -327,34 +327,36 @@
 	int			start, end;
 	LPWAVEHDR		lpWaveHdr;
 	DWORD		dwRet;
-#ifdef DEBUG_MCIWAVE
-	printf("WAVE_mciPlay(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+	dprintf_mciwave(stddeb,
+		 "WAVE_mciPlay(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
 	if (MCIWavDev[wDevID].hFile == 0) {
-		printf("WAVE_mciPlay // can't find file='%s' !\n", 
+        fprintf(stderr,"WAVE_mciPlay // can't find file='%s' !\n",
 				MCIWavDev[wDevID].openParms.lpstrElementName);
 		return MCIERR_FILE_NOT_FOUND;
 		}
 	start = 1; 		end = 99999;
 	if (dwFlags & MCI_FROM) {
 		start = lpParms->dwFrom; 
-		printf("WAVE_mciPlay // MCI_FROM=%d \n", start);
+		dprintf_mciwave(stddeb,
+				"WAVE_mciPlay // MCI_FROM=%d \n", start);
 		}
 	if (dwFlags & MCI_TO) {
 		end = lpParms->dwTo;
-		printf("WAVE_mciPlay // MCI_TO=%d \n", end);
+		dprintf_mciwave(stddeb,"WAVE_mciPlay // MCI_TO=%d \n", end);
 		}
 /*
 	if (dwFlags & MCI_NOTIFY) {
-		printf("WAVE_mciPlay // MCI_NOTIFY %08X !\n", lpParms->dwCallback);
+        dprintf_mciwave(stddeb,
+	        "WAVE_mciPlay // MCI_NOTIFY %08X !\n", lpParms->dwCallback);
 		switch(fork()) {
 			case -1:
-				printf("WAVE_mciPlay // Can't 'fork' process !\n");
+				fprintf(stderr,
+				  "WAVE_mciPlay // Can't 'fork' process !\n");
 				break;
 			case 0:
 				break;         
 			default:
-				printf("WAVE_mciPlay // process started ! return to caller...\n");
+			dprintf_mciwave(stddeb,"WAVE_mciPlay // process started ! return to caller...\n");
 				return 0;
 			}
 		}
@@ -371,10 +373,8 @@
 		count = mmioRead(MCIWavDev[wDevID].hFile, lpWaveHdr->lpData, lpWaveHdr->dwBufferLength);
 		if (count < 1) break;
 		lpWaveHdr->dwBytesRecorded = count;
-#ifdef DEBUG_MCIWAVE
-		printf("WAVE_mciPlay // before WODM_WRITE lpWaveHdr=%08X dwBytesRecorded=%u\n",
+		dprintf_mciwave(stddeb,"WAVE_mciPlay // before WODM_WRITE lpWaveHdr=%08X dwBytesRecorded=%u\n",
 					lpWaveHdr, lpWaveHdr->dwBytesRecorded);
-#endif
 		dwRet = wodMessage(0, WODM_WRITE, 0, (DWORD)lpWaveHdr, sizeof(WAVEHDR));
 		}
 	dwRet = wodMessage(0, WODM_UNPREPARE, 0, (DWORD)lpWaveHdr, sizeof(WAVEHDR));
@@ -383,9 +383,7 @@
 		lpWaveHdr->lpData = NULL;
 		}
 	if (dwFlags & MCI_NOTIFY) {
-#ifdef DEBUG_MCIWAVE
-		printf("WAVE_mciPlay // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
-#endif
+	  dprintf_mciwave(stddeb,"WAVE_mciPlay // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
 		mciDriverNotify((HWND)LOWORD(lpParms->dwCallback), 
 			MCIWavDev[wDevID].wNotifyDeviceID, MCI_NOTIFY_SUCCESSFUL);
 		}
@@ -406,22 +404,22 @@
 	int			start, end;
 	LPWAVEHDR		lpWaveHdr;
 	DWORD		dwRet;
-#ifdef DEBUG_MCIWAVE
-	printf("WAVE_mciRecord(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+	dprintf_mciwave(stddeb,
+		"WAVE_mciRecord(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
 	if (MCIWavDev[wDevID].hFile == 0) {
-		printf("WAVE_mciRecord // can't find file='%s' !\n", 
+		fprintf(stderr,"WAVE_mciRecord // can't find file='%s' !\n", 
 				MCIWavDev[wDevID].openParms.lpstrElementName);
 		return MCIERR_FILE_NOT_FOUND;
 		}
 	start = 1; 		end = 99999;
 	if (dwFlags & MCI_FROM) {
 		start = lpParms->dwFrom; 
-		printf("WAVE_mciRecord // MCI_FROM=%d \n", start);
+		dprintf_mciwave(stddeb,
+				"WAVE_mciRecord // MCI_FROM=%d \n", start);
 		}
 	if (dwFlags & MCI_TO) {
 		end = lpParms->dwTo;
-		printf("WAVE_mciRecord // MCI_TO=%d \n", end);
+		dprintf_mciwave(stddeb,"WAVE_mciRecord // MCI_TO=%d \n", end);
 		}
 	lpWaveHdr = &MCIWavDev[wDevID].WaveHdr;
 	lpWaveHdr->lpData = (LPSTR) malloc(64000);
@@ -430,25 +428,24 @@
 	lpWaveHdr->dwFlags = 0L;
 	lpWaveHdr->dwLoops = 0L;
 	dwRet = widMessage(0, WIDM_PREPARE, 0, (DWORD)lpWaveHdr, sizeof(WAVEHDR));
-	printf("WAVE_mciRecord // after WIDM_PREPARE \n");
+    dprintf_mciwave(stddeb,"WAVE_mciRecord // after WIDM_PREPARE \n");
 	while(TRUE) {
 		lpWaveHdr->dwBytesRecorded = 0;
 		dwRet = widMessage(0, WIDM_START, 0, 0L, 0L);
-		printf("WAVE_mciRecord // after WIDM_START lpWaveHdr=%08X dwBytesRecorded=%u\n",
+		dprintf_mciwave(stddeb,
+                    "WAVE_mciRecord // after WIDM_START lpWaveHdr=%08X dwBytesRecorded=%u\n",
 					lpWaveHdr, lpWaveHdr->dwBytesRecorded);
 		if (lpWaveHdr->dwBytesRecorded == 0) break;
 		}
-	printf("WAVE_mciRecord // before WIDM_UNPREPARE \n");
+	dprintf_mciwave(stddeb,"WAVE_mciRecord // before WIDM_UNPREPARE \n");
 	dwRet = widMessage(0, WIDM_UNPREPARE, 0, (DWORD)lpWaveHdr, sizeof(WAVEHDR));
-	printf("WAVE_mciRecord // after WIDM_UNPREPARE \n");
+	dprintf_mciwave(stddeb,"WAVE_mciRecord // after WIDM_UNPREPARE \n");
 	if (lpWaveHdr->lpData != NULL) {
 		free(lpWaveHdr->lpData);
 		lpWaveHdr->lpData = NULL;
 		}
 	if (dwFlags & MCI_NOTIFY) {
-#ifdef DEBUG_MCIWAVE
-		printf("WAVE_mciRecord // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
-#endif
+	  dprintf_mciwave(stddeb,"WAVE_mciRecord // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
 		mciDriverNotify((HWND)LOWORD(lpParms->dwCallback), 
 			MCIWavDev[wDevID].wNotifyDeviceID, MCI_NOTIFY_SUCCESSFUL);
 		}
@@ -465,9 +462,8 @@
 DWORD WAVE_mciStop(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_MCIWAVE
-	printf("WAVE_mciStop(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+        dprintf_mciwave(stddeb,
+		 "WAVE_mciStop(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	return 0;
 #else
@@ -482,9 +478,8 @@
 DWORD WAVE_mciPause(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_MCIWAVE
-	printf("WAVE_mciPause(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+        dprintf_mciwave(stddeb,
+		"WAVE_mciPause(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	return 0;
 #else
@@ -499,9 +494,8 @@
 DWORD WAVE_mciResume(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_MCIWAVE
-	printf("WAVE_mciResume(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+        dprintf_mciwave(stddeb,
+		"WAVE_mciResume(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	return 0;
 #else
@@ -516,78 +510,70 @@
 DWORD WAVE_mciSet(UINT wDevID, DWORD dwFlags, LPMCI_SET_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_MCIWAVE
-	printf("WAVE_mciSet(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+        dprintf_mciwave(stddeb,
+		  "WAVE_mciSet(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
-#ifdef DEBUG_MCIWAVE
-	printf("WAVE_mciSet // dwTimeFormat=%08X\n", lpParms->dwTimeFormat);
-	printf("WAVE_mciSet // dwAudio=%08X\n", lpParms->dwAudio);
-#endif
+	dprintf_mciwave(stddeb,
+		 "WAVE_mciSet // dwTimeFormat=%08X\n", lpParms->dwTimeFormat);
+	dprintf_mciwave(stddeb,
+		 "WAVE_mciSet // dwAudio=%08X\n", lpParms->dwAudio);
 	if (dwFlags & MCI_SET_TIME_FORMAT) {
 		switch (lpParms->dwTimeFormat) {
 			case MCI_FORMAT_MILLISECONDS:
-				printf("WAVE_mciSet // MCI_FORMAT_MILLISECONDS !\n");
+		                dprintf_mciwave(stddeb,
+				 "WAVE_mciSet // MCI_FORMAT_MILLISECONDS !\n");
 				break;
 			case MCI_FORMAT_BYTES:
-				printf("WAVE_mciSet // MCI_FORMAT_BYTES !\n");
+				dprintf_mciwave(stddeb,
+				 "WAVE_mciSet // MCI_FORMAT_BYTES !\n");
 				break;
 			case MCI_FORMAT_SAMPLES:
-				printf("WAVE_mciSet // MCI_FORMAT_SAMPLES !\n");
+				dprintf_mciwave(stddeb,
+				 "WAVE_mciSet // MCI_FORMAT_SAMPLES !\n");
 				break;
 			default:
-				printf("WAVE_mciSet // bad time format !\n");
+				fprintf(stderr,
+				 "WAVE_mciSet // bad time format !\n");
 				return MCIERR_BAD_TIME_FORMAT;
 			}
 		}
 	if (dwFlags & MCI_SET_VIDEO) return MCIERR_UNSUPPORTED_FUNCTION;
 	if (dwFlags & MCI_SET_DOOR_OPEN) return MCIERR_UNSUPPORTED_FUNCTION;
 	if (dwFlags & MCI_SET_DOOR_CLOSED) return MCIERR_UNSUPPORTED_FUNCTION;
-	if (dwFlags & MCI_SET_AUDIO) {
-		printf("WAVE_mciSet // MCI_SET_AUDIO !\n");
-		}
+	if (dwFlags & MCI_SET_AUDIO) 
+	  dprintf_mciwave(stddeb,"WAVE_mciSet // MCI_SET_AUDIO !\n");
 	if (dwFlags && MCI_SET_ON) {
-		printf("WAVE_mciSet // MCI_SET_ON !\n");
-		if (dwFlags && MCI_SET_AUDIO_LEFT) {
-			printf("WAVE_mciSet // MCI_SET_AUDIO_LEFT !\n");
-			}
-		if (dwFlags && MCI_SET_AUDIO_RIGHT) {
-			printf("WAVE_mciSet // MCI_SET_AUDIO_RIGHT !\n");
-			}
-		}
-	if (dwFlags & MCI_SET_OFF) {
-		printf("WAVE_mciSet // MCI_SET_OFF !\n");
-		}
-	if (dwFlags & MCI_WAVE_INPUT) {
-		printf("WAVE_mciSet // MCI_WAVE_INPUT !\n");
-		}
-	if (dwFlags & MCI_WAVE_OUTPUT) {
-		printf("WAVE_mciSet // MCI_WAVE_OUTPUT !\n");
-		}
-	if (dwFlags & MCI_WAVE_SET_ANYINPUT) {
-		printf("WAVE_mciSet // MCI_WAVE_SET_ANYINPUT !\n");
-		}
-	if (dwFlags & MCI_WAVE_SET_ANYOUTPUT) {
-		printf("WAVE_mciSet // MCI_WAVE_SET_ANYOUTPUT !\n");
-		}
-	if (dwFlags & MCI_WAVE_SET_AVGBYTESPERSEC) {
-		printf("WAVE_mciSet // MCI_WAVE_SET_AVGBYTESPERSEC !\n");
-		}
-	if (dwFlags & MCI_WAVE_SET_BITSPERSAMPLE) {
-		printf("WAVE_mciSet // MCI_WAVE_SET_BITSPERSAMPLE !\n");
-		}
-	if (dwFlags & MCI_WAVE_SET_BLOCKALIGN) {
-		printf("WAVE_mciSet // MCI_WAVE_SET_BLOCKALIGN !\n");
-		}
-	if (dwFlags & MCI_WAVE_SET_CHANNELS) {
-		printf("WAVE_mciSet // MCI_WAVE_SET_CHANNELS !\n");
-		}
-	if (dwFlags & MCI_WAVE_SET_FORMATTAG) {
-		printf("WAVE_mciSet // MCI_WAVE_SET_FORMATTAG !\n");
-		}
-	if (dwFlags & MCI_WAVE_SET_SAMPLESPERSEC) {
-		printf("WAVE_mciSet // MCI_WAVE_SET_SAMPLESPERSEC !\n");
-		}
+	  dprintf_mciwave(stddeb,"WAVE_mciSet // MCI_SET_ON !\n");
+	  if (dwFlags && MCI_SET_AUDIO_LEFT) 
+	    dprintf_mciwave(stddeb,"WAVE_mciSet // MCI_SET_AUDIO_LEFT !\n");
+	  if (dwFlags && MCI_SET_AUDIO_RIGHT) 
+	    dprintf_mciwave(stddeb,"WAVE_mciSet // MCI_SET_AUDIO_RIGHT !\n");
+	}
+	if (dwFlags & MCI_SET_OFF) 
+	  dprintf_mciwave(stddeb,"WAVE_mciSet // MCI_SET_OFF !\n");
+	if (dwFlags & MCI_WAVE_INPUT) 
+	  dprintf_mciwave(stddeb,"WAVE_mciSet // MCI_WAVE_INPUT !\n");
+      	if (dwFlags & MCI_WAVE_OUTPUT) 
+	  dprintf_mciwave(stddeb,"WAVE_mciSet // MCI_WAVE_OUTPUT !\n");
+	if (dwFlags & MCI_WAVE_SET_ANYINPUT) 
+	  dprintf_mciwave(stddeb,"WAVE_mciSet // MCI_WAVE_SET_ANYINPUT !\n");
+	if (dwFlags & MCI_WAVE_SET_ANYOUTPUT) 
+	  dprintf_mciwave(stddeb,"WAVE_mciSet // MCI_WAVE_SET_ANYOUTPUT !\n");
+	if (dwFlags & MCI_WAVE_SET_AVGBYTESPERSEC) 
+	  dprintf_mciwave(stddeb,
+			  "WAVE_mciSet // MCI_WAVE_SET_AVGBYTESPERSEC !\n");
+	if (dwFlags & MCI_WAVE_SET_BITSPERSAMPLE) 
+	  dprintf_mciwave(stddeb,
+			  "WAVE_mciSet // MCI_WAVE_SET_BITSPERSAMPLE !\n");
+	if (dwFlags & MCI_WAVE_SET_BLOCKALIGN) 
+	  dprintf_mciwave(stddeb,"WAVE_mciSet // MCI_WAVE_SET_BLOCKALIGN !\n");
+	if (dwFlags & MCI_WAVE_SET_CHANNELS) 
+	  dprintf_mciwave(stddeb,"WAVE_mciSet // MCI_WAVE_SET_CHANNELS !\n");
+	if (dwFlags & MCI_WAVE_SET_FORMATTAG) 
+	  dprintf_mciwave(stddeb,"WAVE_mciSet // MCI_WAVE_SET_FORMATTAG !\n");
+	if (dwFlags & MCI_WAVE_SET_SAMPLESPERSEC) 
+	  dprintf_mciwave(stddeb,
+			  "WAVE_mciSet // MCI_WAVE_SET_SAMPLESPERSEC !\n");
  	return 0;
 #else
 	return MCIERR_INTERNAL;
@@ -601,9 +587,8 @@
 DWORD WAVE_mciStatus(UINT wDevID, DWORD dwFlags, LPMCI_STATUS_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_MCIWAVE
-	printf("WAVE_mciStatus(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+        dprintf_mciwave(stddeb,
+		"WAVE_mciStatus(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	if (dwFlags & MCI_STATUS_ITEM) {
 		switch(lpParms->dwItem) {
@@ -621,7 +606,7 @@
 				lpParms->dwReturn = MCI_MODE_STOP;
 				break;
 			case MCI_STATUS_MEDIA_PRESENT:
-				printf("WAVE_mciStatus // MCI_STATUS_MEDIA_PRESENT !\n");
+				dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_STATUS_MEDIA_PRESENT !\n");
 				lpParms->dwReturn = TRUE;
 				break;
 			case MCI_STATUS_NUMBER_OF_TRACKS:
@@ -638,56 +623,56 @@
 					}
 				break;
 			case MCI_STATUS_READY:
-				printf("WAVE_mciStatus // MCI_STATUS_READY !\n");
+				dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_STATUS_READY !\n");
 				lpParms->dwReturn = TRUE;
 				break;
 			case MCI_STATUS_TIME_FORMAT:
-				printf("WAVE_mciStatus // MCI_STATUS_TIME_FORMAT !\n");
+				dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_STATUS_TIME_FORMAT !\n");
 				lpParms->dwReturn = MCI_FORMAT_MILLISECONDS;
 				break;
 			case MCI_WAVE_INPUT:
-				printf("WAVE_mciStatus // MCI_WAVE_INPUT !\n");
+				dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_WAVE_INPUT !\n");
 				lpParms->dwReturn = 0;
 				break;
 			case MCI_WAVE_OUTPUT:
-				printf("WAVE_mciStatus // MCI_WAVE_OUTPUT !\n");
+				dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_WAVE_OUTPUT !\n");
 				lpParms->dwReturn = 0;
 				break;
 			case MCI_WAVE_STATUS_AVGBYTESPERSEC:
-				printf("WAVE_mciStatus // MCI_WAVE_STATUS_AVGBYTESPERSEC !\n");
+				dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_WAVE_STATUS_AVGBYTESPERSEC !\n");
 				lpParms->dwReturn = 22050;
 				break;
 			case MCI_WAVE_STATUS_BITSPERSAMPLE:
-				printf("WAVE_mciStatus // MCI_WAVE_STATUS_BITSPERSAMPLE !\n");
+				dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_WAVE_STATUS_BITSPERSAMPLE !\n");
 				lpParms->dwReturn = 8;
 				break;
 			case MCI_WAVE_STATUS_BLOCKALIGN:
-				printf("WAVE_mciStatus // MCI_WAVE_STATUS_BLOCKALIGN !\n");
+				dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_WAVE_STATUS_BLOCKALIGN !\n");
 				lpParms->dwReturn = 1;
 				break;
 			case MCI_WAVE_STATUS_CHANNELS:
-				printf("WAVE_mciStatus // MCI_WAVE_STATUS_CHANNELS !\n");
+				dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_WAVE_STATUS_CHANNELS !\n");
 				lpParms->dwReturn = 1;
 				break;
 			case MCI_WAVE_STATUS_FORMATTAG:
-				printf("WAVE_mciStatus // MCI_WAVE_FORMATTAG !\n");
+				dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_WAVE_FORMATTAG !\n");
 				lpParms->dwReturn = WAVE_FORMAT_PCM;
 				break;
 			case MCI_WAVE_STATUS_LEVEL:
-				printf("WAVE_mciStatus // MCI_WAVE_STATUS_LEVEL !\n");
+				dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_WAVE_STATUS_LEVEL !\n");
 				lpParms->dwReturn = 0xAAAA5555;
 				break;
 			case MCI_WAVE_STATUS_SAMPLESPERSEC:
-				printf("WAVE_mciStatus // MCI_WAVE_STATUS_SAMPLESPERSEC !\n");
+				dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_WAVE_STATUS_SAMPLESPERSEC !\n");
 				lpParms->dwReturn = 22050;
 				break;
 			default:
-				printf("WAVE_mciStatus // unknowm command %04X !\n", lpParms->dwItem);
+				fprintf(stderr,"WAVE_mciStatus // unknown command %04X !\n", lpParms->dwItem);
 				return MCIERR_UNRECOGNIZED_COMMAND;
 			}
 		}
 	if (dwFlags & MCI_NOTIFY) {
-		printf("WAVE_mciStatus // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
+  	        dprintf_mciwave(stddeb,"WAVE_mciStatus // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
 		mciDriverNotify((HWND)LOWORD(lpParms->dwCallback), 
 			MCIWavDev[wDevID].wNotifyDeviceID, MCI_NOTIFY_SUCCESSFUL);
 		}
@@ -704,7 +689,8 @@
 					LPMCI_GETDEVCAPS_PARMS lpParms)
 {
 #ifdef linux
-	printf("WAVE_mciGetDevCaps(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
+        dprintf_mciwave(stddeb,
+	    "WAVE_mciGetDevCaps(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	if (dwFlags & MCI_GETDEVCAPS_ITEM) {
 		switch(lpParms->dwItem) {
@@ -757,7 +743,8 @@
 DWORD WAVE_mciInfo(UINT wDevID, DWORD dwFlags, LPMCI_INFO_PARMS lpParms)
 {
 #ifdef linux
-	printf("WAVE_mciInfo(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
+        dprintf_mciwave(stddeb,
+		"WAVE_mciInfo(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	lpParms->lpstrReturn = NULL;
 	switch(dwFlags) {
@@ -801,7 +788,8 @@
 	int		samplesize = 16;
 	int		dsp_stereo = 1;
 	int		bytespersmpl;
-	printf("wodGetDevCaps(%u, %08X, %u);\n", wDevID, lpCaps, dwSize);
+	dprintf_mciwave(stddeb,
+		   "wodGetDevCaps(%u, %08X, %u);\n", wDevID, lpCaps, dwSize);
 	if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
 	audio = open (SOUND_DEV, O_WRONLY, 0);
 	if (audio == -1) return MMSYSERR_NOTENABLED;
@@ -840,7 +828,8 @@
 			}
 		}
 	close(audio);
-	printf("wodGetDevCaps // dwFormats = %08X\n", lpCaps->dwFormats);
+	dprintf_mciwave(stddeb,
+		"wodGetDevCaps // dwFormats = %08X\n", lpCaps->dwFormats);
 	return MMSYSERR_NOERROR;
 #else
 	return MMSYSERR_NOTENABLED;
@@ -859,42 +848,46 @@
 	int			smplrate;
 	int			samplesize;
 	int			dsp_stereo;
-	printf("wodOpen(%u, %08X, %08X);\n", wDevID, lpDesc, dwFlags);
+	dprintf_mciwave(stddeb,
+		     "wodOpen(%u, %08X, %08X);\n", wDevID, lpDesc, dwFlags);
 	if (lpDesc == NULL) {
-		printf("Linux 'wodOpen' // Invalid Parameter !\n");
+	        fprintf(stderr,"Linux 'wodOpen' // Invalid Parameter !\n");
 		return MMSYSERR_INVALPARAM;
 		}
 	if (wDevID >= MAX_WAVOUTDRV) {
-		printf("Linux 'wodOpen' // MAX_WAVOUTDRV reached !\n");
+	        fprintf(stderr,"Linux 'wodOpen' // MAX_WAVOUTDRV reached !\n");
 		return MMSYSERR_ALLOCATED;
 		}
 	WOutDev[wDevID].unixdev = 0;
 	audio = open (SOUND_DEV, O_WRONLY, 0);
 	if (audio == -1) {
-		printf("Linux 'wodOpen' // can't open !\n");
+                fprintf(stderr,"Linux 'wodOpen' // can't open !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	IOCTL(audio, SNDCTL_DSP_GETBLKSIZE, abuf_size);
 	if (abuf_size < 4096 || abuf_size > 65536) {
 		if (abuf_size == -1)
-			printf("Linux 'wodOpen' // IOCTL can't 'SNDCTL_DSP_GETBLKSIZE' !\n");
+		  fprintf(stderr,"Linux 'wodOpen' // IOCTL can't 'SNDCTL_DSP_GETBLKSIZE' !\n");
 		else
-			printf("Linux 'wodOpen' // SNDCTL_DSP_GETBLKSIZE Invalid bufsize !\n");
+		  fprintf(stderr,"Linux 'wodOpen' // SNDCTL_DSP_GETBLKSIZE Invalid bufsize !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	WOutDev[wDevID].wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
 	switch(WOutDev[wDevID].wFlags) {
 		case DCB_NULL:
-			printf("Linux 'wodOpen' // CALLBACK_NULL !\n");
+	                fprintf(stderr,"Linux 'wodOpen' // CALLBACK_NULL !\n");
 			break;
 		case DCB_WINDOW:
-			printf("Linux 'wodOpen' // CALLBACK_WINDOW !\n");
+			dprintf_mciwave(stddeb,
+				   "Linux 'wodOpen' // CALLBACK_WINDOW !\n");
 			break;
 		case DCB_TASK:
-			printf("Linux 'wodOpen' // CALLBACK_TASK !\n");
+			dprintf_mciwave(stddeb,
+				   "Linux 'wodOpen' // CALLBACK_TASK !\n");
 			break;
 		case DCB_FUNCTION:
-			printf("Linux 'wodOpen' // CALLBACK_FUNCTION !\n");
+			dprintf_mciwave(stddeb,
+				   "Linux 'wodOpen' // CALLBACK_FUNCTION !\n");
 			break;
 		}
 	WOutDev[wDevID].lpQueueHdr = NULL;
@@ -903,7 +896,7 @@
 	WOutDev[wDevID].bufsize = abuf_size;
 	memcpy(&WOutDev[wDevID].waveDesc, lpDesc, sizeof(WAVEOPENDESC));
 	if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM) {
-		printf("Linux 'wodOpen' // Bad format %04X !\n", 
+	        fprintf(stderr,"Linux 'wodOpen' // Bad format %04X !\n",
 						lpDesc->lpFormat->wFormatTag);
 		return WAVERR_BADFORMAT;
 		}
@@ -922,14 +915,14 @@
 	IOCTL(audio, SNDCTL_DSP_SPEED, smplrate);
 	IOCTL(audio, SNDCTL_DSP_SAMPLESIZE, samplesize);
 	IOCTL(audio, SNDCTL_DSP_STEREO, dsp_stereo);
-	printf("Linux 'wodOpen' // wBitsPerSample=%u !\n", 
+	dprintf_mciwave(stddeb,"Linux 'wodOpen' // wBitsPerSample=%u !\n",
 				WOutDev[wDevID].Format.wBitsPerSample);
-	printf("Linux 'wodOpen' // nSamplesPerSec=%u !\n", 
+	dprintf_mciwave(stddeb,"Linux 'wodOpen' // nSamplesPerSec=%u !\n",
 				WOutDev[wDevID].Format.wf.nSamplesPerSec);
-	printf("Linux 'wodOpen' // nChannels=%u !\n", 
+	dprintf_mciwave(stddeb,"Linux 'wodOpen' // nChannels=%u !\n",
 				WOutDev[wDevID].Format.wf.nChannels);
 	if (WAVE_NotifyClient(wDevID, WOM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
-		printf("Linux 'wodOpen' // can't notify client !\n");
+	        fprintf(stderr,"Linux 'wodOpen' // can't notify client !\n");
 		return MMSYSERR_INVALPARAM;
 		}
 	return MMSYSERR_NOERROR;
@@ -944,16 +937,16 @@
 DWORD wodClose(WORD wDevID)
 {
 #ifdef linux
-	printf("wodClose(%u);\n", wDevID);
+        dprintf_mciwave(stddeb,"wodClose(%u);\n", wDevID);
 	if (WOutDev[wDevID].unixdev == 0) {
-		printf("Linux 'wodClose' // can't close !\n");
+	        fprintf(stderr,"Linux 'wodClose' // can't close !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	close(WOutDev[wDevID].unixdev);
 	WOutDev[wDevID].unixdev = 0;
 	WOutDev[wDevID].bufsize = 0;
 	if (WAVE_NotifyClient(wDevID, WOM_CLOSE, 0L, 0L) != MMSYSERR_NOERROR) {
-		printf("Linux 'wodClose' // can't notify client !\n");
+                fprintf(stderr,"Linux 'wodClose' // can't notify client !\n");
 		return MMSYSERR_INVALPARAM;
 		}
 	return MMSYSERR_NOERROR;
@@ -968,9 +961,9 @@
 DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
 {
 #ifdef linux
-	printf("wodWrite(%u, %08X, %08X);\n", wDevID, lpWaveHdr, dwSize);
+        dprintf_mciwave(stddeb,"wodWrite(%u, %08X, %08X);\n", wDevID, lpWaveHdr, dwSize);
 	if (WOutDev[wDevID].unixdev == 0) {
-		printf("Linux 'wodWrite' // can't play !\n");
+        fprintf(stderr,"Linux 'wodWrite' // can't play !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	if (lpWaveHdr->lpData == NULL) return WAVERR_UNPREPARED;
@@ -978,7 +971,8 @@
 	if (lpWaveHdr->dwFlags & WHDR_INQUEUE) return WAVERR_STILLPLAYING;
 	lpWaveHdr->dwFlags &= ~WHDR_DONE;
 	lpWaveHdr->dwFlags |= WHDR_INQUEUE;
-	printf("wodWrite() // dwBytesRecorded %u !\n", lpWaveHdr->dwBytesRecorded);
+        dprintf_mciwave(stddeb,
+	   "wodWrite() // dwBytesRecorded %u !\n", lpWaveHdr->dwBytesRecorded);
 	if (write (WOutDev[wDevID].unixdev, lpWaveHdr->lpData, 
 		lpWaveHdr->dwBytesRecorded) != lpWaveHdr->dwBytesRecorded) {
 		return MMSYSERR_NOTENABLED;
@@ -986,7 +980,7 @@
 	lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
 	lpWaveHdr->dwFlags |= WHDR_DONE;
 	if (WAVE_NotifyClient(wDevID, WOM_DONE, 0L, 0L) != MMSYSERR_NOERROR) {
-		printf("Linux 'wodWrite' // can't notify client !\n");
+                fprintf(stderr,"Linux 'wodWrite' // can't notify client !\n");
 		return MMSYSERR_INVALPARAM;
 		}
 	return MMSYSERR_NOERROR;
@@ -1001,13 +995,14 @@
 DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
 {
 #ifdef linux
-	printf("wodPrepare(%u, %08X, %08X);\n", wDevID, lpWaveHdr, dwSize);
+        dprintf_mciwave(stddeb,
+		  "wodPrepare(%u, %08X, %08X);\n", wDevID, lpWaveHdr, dwSize);
 	if (WOutDev[wDevID].unixdev == 0) {
-		printf("Linux 'wodPrepare' // can't prepare !\n");
+                fprintf(stderr,"Linux 'wodPrepare' // can't prepare !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	if (WOutDev[wDevID].lpQueueHdr != NULL) {
-		printf("Linux 'wodPrepare' // already prepare !\n");
+                fprintf(stderr,"Linux 'wodPrepare' // already prepare !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	WOutDev[wDevID].dwTotalPlayed = 0;
@@ -1027,9 +1022,10 @@
 DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
 {
 #ifdef linux
-	printf("wodUnprepare(%u, %08X, %08X);\n", wDevID, lpWaveHdr, dwSize);
+        dprintf_mciwave(stddeb,
+		"wodUnprepare(%u, %08X, %08X);\n", wDevID, lpWaveHdr, dwSize);
 	if (WOutDev[wDevID].unixdev == 0) {
-		printf("Linux 'wodUnprepare' // can't unprepare !\n");
+        fprintf(stderr,"Linux 'wodUnprepare' // can't unprepare !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	return MMSYSERR_NOERROR;
@@ -1044,9 +1040,9 @@
 DWORD wodRestart(WORD wDevID)
 {
 #ifdef linux
-	printf("wodRestart(%u);\n", wDevID);
+        dprintf_mciwave(stddeb,"wodRestart(%u);\n", wDevID);
 	if (WOutDev[wDevID].unixdev == 0) {
-		printf("Linux 'wodRestart' // can't restart !\n");
+                fprintf(stderr,"Linux 'wodRestart' // can't restart !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	return MMSYSERR_NOERROR;
@@ -1061,9 +1057,9 @@
 DWORD wodReset(WORD wDevID)
 {
 #ifdef linux
-	printf("wodReset(%u);\n", wDevID);
+    dprintf_mciwave(stddeb,"wodReset(%u);\n", wDevID);
 	if (WOutDev[wDevID].unixdev == 0) {
-		printf("Linux 'wodReset' // can't reset !\n");
+                fprintf(stderr,"Linux 'wodReset' // can't reset !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	return MMSYSERR_NOERROR;
@@ -1080,9 +1076,9 @@
 {
 #ifdef linux
 	int		time;
-	printf("wodGetPosition(%u, %08X, %u);\n", wDevID, lpTime, uSize);
+	dprintf_mciwave(stddeb,"wodGetPosition(%u, %08X, %u);\n", wDevID, lpTime, uSize);
 	if (WOutDev[wDevID].unixdev == 0) {
-		printf("Linux 'wodGetPosition' // can't get pos !\n");
+                fprintf(stderr,"Linux 'wodGetPosition' // can't get pos !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	if (lpTime == NULL)	return MMSYSERR_INVALPARAM;
@@ -1090,17 +1086,17 @@
 	switch(lpTime->wType) {
 		case TIME_BYTES:
 			lpTime->u.cb = WOutDev[wDevID].dwTotalPlayed;
-			printf("wodGetPosition // TIME_BYTES=%u\n", lpTime->u.cb);
+			dprintf_mciwave(stddeb,"wodGetPosition // TIME_BYTES=%u\n", lpTime->u.cb);
 			break;
 		case TIME_SAMPLES:
 			lpTime->u.sample = WOutDev[wDevID].dwTotalPlayed * 8 /
 						WOutDev[wDevID].Format.wBitsPerSample;
-			printf("wodGetPosition // TIME_SAMPLES=%u\n", lpTime->u.sample);
+			dprintf_mciwave(stddeb,"wodGetPosition // TIME_SAMPLES=%u\n", lpTime->u.sample);
 			break;
 		case TIME_MS:
 			lpTime->u.ms = WOutDev[wDevID].dwTotalPlayed /
 					(WOutDev[wDevID].Format.wf.nAvgBytesPerSec / 1000);
-			printf("wodGetPosition // TIME_MS=%u\n", lpTime->u.ms);
+			dprintf_mciwave(stddeb,"wodGetPosition // TIME_MS=%u\n", lpTime->u.ms);
 			break;
 		case TIME_SMPTE:
 			time = WOutDev[wDevID].dwTotalPlayed /
@@ -1113,12 +1109,13 @@
 			time -= lpTime->u.smpte.sec * 30;
 			lpTime->u.smpte.frame = time;
 			lpTime->u.smpte.fps = 30;
-			printf("wodGetPosition // TIME_SMPTE=%02u:%02u:%02u:%02u\n", 
-					lpTime->u.smpte.hour, lpTime->u.smpte.min,
-					lpTime->u.smpte.sec, lpTime->u.smpte.frame);
+			dprintf_mciwave(stddeb,
+			  "wodGetPosition // TIME_SMPTE=%02u:%02u:%02u:%02u\n",
+			  lpTime->u.smpte.hour, lpTime->u.smpte.min,
+			  lpTime->u.smpte.sec, lpTime->u.smpte.frame);
 			break;
 		default:
-			printf("wodGetPosition() format not supported ! use TIME_MS !\n");
+			fprintf(stderr,"wodGetPosition() format not supported ! use TIME_MS !\n");
 			lpTime->wType = TIME_MS;
 			goto TryAGAIN;
 		}
@@ -1136,17 +1133,18 @@
 #ifdef linux
 	int 	mixer;
 	int		volume = 50;
-	printf("wodSetVolume(%u, %08X);\n", wDevID, dwParam);
+	dprintf_mciwave(stddeb,"wodSetVolume(%u, %08X);\n", wDevID, dwParam);
 	if (WOutDev[wDevID].unixdev == 0) {
-		printf("Linux 'wodSetVolume' // can't set volume !\n");
+                fprintf(stderr,"Linux 'wodSetVolume' // can't set volume !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	if ((mixer = open("/dev/mixer", O_RDWR)) < 0) {
-		printf("Linux 'wodSetVolume' // mixer device not available !\n");
+                fprintf(stderr,
+		   "Linux 'wodSetVolume' // mixer device not available !\n");
 		return MMSYSERR_NOTENABLED;
 		}
     if (ioctl(mixer, SOUND_MIXER_WRITE_PCM, &volume) == -1) {
-		printf("Linux 'wodSetVolume' // unable set mixer !\n");
+                fprintf(stderr,"Linux 'wodSetVolume' // unable set mixer !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	close(mixer);
@@ -1163,7 +1161,7 @@
 DWORD wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser, 
 					DWORD dwParam1, DWORD dwParam2)
 {
-	printf("wodMessage(%u, %04X, %08X, %08X, %08X);\n", 
+        dprintf_mciwave(stddeb,"wodMessage(%u, %04X, %08X, %08X, %08X);\n",
 			wDevID, wMsg, dwUser, dwParam1, dwParam2);
 	switch(wMsg) {
 		case WODM_OPEN:
@@ -1220,7 +1218,8 @@
 	int		samplesize = 16;
 	int		dsp_stereo = 1;
 	int		bytespersmpl;
-	printf("widGetDevCaps(%u, %08X, %u);\n", wDevID, lpCaps, dwSize);
+	dprintf_mciwave(stddeb,
+		  "widGetDevCaps(%u, %08X, %u);\n", wDevID, lpCaps, dwSize);
 	if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
 	audio = open (SOUND_DEV, O_RDONLY, 0);
 	if (audio == -1) return MMSYSERR_NOTENABLED;
@@ -1258,7 +1257,8 @@
 			}
 		}
 	close(audio);
-	printf("widGetDevCaps // dwFormats = %08X\n", lpCaps->dwFormats);
+	dprintf_mciwave(stddeb,
+		 "widGetDevCaps // dwFormats = %08X\n", lpCaps->dwFormats);
 	return MMSYSERR_NOERROR;
 #else
 	return MMSYSERR_NOTENABLED;
@@ -1277,42 +1277,47 @@
 	int			smplrate;
 	int			samplesize;
 	int			dsp_stereo;
-	printf("widOpen(%u, %08X, %08X);\n", wDevID, lpDesc, dwFlags);
+	dprintf_mciwave(stddeb,
+		 "widOpen(%u, %08X, %08X);\n", wDevID, lpDesc, dwFlags);
 	if (lpDesc == NULL) {
-		printf("Linux 'widOpen' // Invalid Parameter !\n");
+                fprintf(stderr,"Linux 'widOpen' // Invalid Parameter !\n");
 		return MMSYSERR_INVALPARAM;
 		}
 	if (wDevID >= MAX_WAVINDRV) {
-		printf("Linux 'widOpen' // MAX_WAVINDRV reached !\n");
+                fprintf(stderr,"Linux 'widOpen' // MAX_WAVINDRV reached !\n");
 		return MMSYSERR_ALLOCATED;
 		}
 	WInDev[wDevID].unixdev = 0;
 	audio = open (SOUND_DEV, O_RDONLY, 0);
 	if (audio == -1) {
-		printf("Linux 'widOpen' // can't open !\n");
+                fprintf(stderr,"Linux 'widOpen' // can't open !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	IOCTL(audio, SNDCTL_DSP_GETBLKSIZE, abuf_size);
 	if (abuf_size < 4096 || abuf_size > 65536) {
 		if (abuf_size == -1)
-			printf("Linux 'widOpen' // IOCTL can't 'SNDCTL_DSP_GETBLKSIZE' !\n");
+		  fprintf(stderr,"Linux 'widOpen' // IOCTL can't 'SNDCTL_DSP_GETBLKSIZE' !\n");
 		else
-			printf("Linux 'widOpen' // SNDCTL_DSP_GETBLKSIZE Invalid bufsize !\n");
+		  fprintf(stderr,"Linux 'widOpen' // SNDCTL_DSP_GETBLKSIZE Invalid bufsize !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	WInDev[wDevID].wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
 	switch(WInDev[wDevID].wFlags) {
 		case DCB_NULL:
-			printf("Linux 'widOpen' // CALLBACK_NULL !\n");
+	                dprintf_mciwave(stddeb,
+			      "Linux 'widOpen' // CALLBACK_NULL !\n");
 			break;
 		case DCB_WINDOW:
-			printf("Linux 'widOpen' // CALLBACK_WINDOW !\n");
+			dprintf_mciwave(stddeb,
+			      "Linux 'widOpen' // CALLBACK_WINDOW !\n");
 			break;
 		case DCB_TASK:
-			printf("Linux 'widOpen' // CALLBACK_TASK !\n");
+			dprintf_mciwave(stddeb,
+			      "Linux 'widOpen' // CALLBACK_TASK !\n");
 			break;
 		case DCB_FUNCTION:
-			printf("Linux 'widOpen' // CALLBACK_FUNCTION !\n");
+			dprintf_mciwave(stddeb,
+			      "Linux 'widOpen' // CALLBACK_FUNCTION !\n");
 			break;
 		}
 	WInDev[wDevID].lpQueueHdr = NULL;
@@ -1321,7 +1326,7 @@
 	WInDev[wDevID].dwTotalRecorded = 0;
 	memcpy(&WInDev[wDevID].waveDesc, lpDesc, sizeof(WAVEOPENDESC));
 	if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM) {
-		printf("Linux 'widOpen' // Bad format %04X !\n", 
+	        fprintf(stderr,"Linux 'widOpen' // Bad format %04X !\n",
 						lpDesc->lpFormat->wFormatTag);
 		return WAVERR_BADFORMAT;
 		}
@@ -1341,18 +1346,16 @@
 	IOCTL(audio, SNDCTL_DSP_SPEED, smplrate);
 	IOCTL(audio, SNDCTL_DSP_SAMPLESIZE, samplesize);
 	IOCTL(audio, SNDCTL_DSP_STEREO, dsp_stereo);
-#ifdef DEBUG_MCIWAVE
-	printf("Linux 'widOpen' // wBitsPerSample=%u !\n", 
+	dprintf_mciwave(stddeb,"Linux 'widOpen' // wBitsPerSample=%u !\n",
 				WInDev[wDevID].Format.wBitsPerSample);
-	printf("Linux 'widOpen' // nSamplesPerSec=%u !\n", 
+	dprintf_mciwave(stddeb,"Linux 'widOpen' // nSamplesPerSec=%u !\n",
 				WInDev[wDevID].Format.wf.nSamplesPerSec);
-	printf("Linux 'widOpen' // nChannels=%u !\n", 
+	dprintf_mciwave(stddeb,"Linux 'widOpen' // nChannels=%u !\n",
 				WInDev[wDevID].Format.wf.nChannels);
-	printf("Linux 'widOpen' // nAvgBytesPerSec=%u\n",
+	dprintf_mciwave(stddeb,"Linux 'widOpen' // nAvgBytesPerSec=%u\n",
 			WInDev[wDevID].Format.wf.nAvgBytesPerSec); 
-#endif
 	if (WAVE_NotifyClient(wDevID, WIM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
-		printf("Linux 'widOpen' // can't notify client !\n");
+	        fprintf(stderr,"Linux 'widOpen' // can't notify client !\n");
 		return MMSYSERR_INVALPARAM;
 		}
 	return MMSYSERR_NOERROR;
@@ -1367,16 +1370,16 @@
 DWORD widClose(WORD wDevID)
 {
 #ifdef linux
-	printf("widClose(%u);\n", wDevID);
+        dprintf_mciwave(stddeb,"widClose(%u);\n", wDevID);
 	if (WInDev[wDevID].unixdev == 0) {
-		printf("Linux 'widClose' // can't close !\n");
+                fprintf(stderr,"Linux 'widClose' // can't close !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	close(WInDev[wDevID].unixdev);
 	WInDev[wDevID].unixdev = 0;
 	WInDev[wDevID].bufsize = 0;
 	if (WAVE_NotifyClient(wDevID, WIM_CLOSE, 0L, 0L) != MMSYSERR_NOERROR) {
-		printf("Linux 'widClose' // can't notify client !\n");
+                fprintf(stderr,"Linux 'widClose' // can't notify client !\n");
 		return MMSYSERR_INVALPARAM;
 		}
 	return MMSYSERR_NOERROR;
@@ -1393,20 +1396,23 @@
 #ifdef linux
 	int			count	= 1;
 	LPWAVEHDR 	lpWIHdr;
-	printf("widAddBuffer(%u, %08X, %08X);\n", wDevID, lpWaveHdr, dwSize);
+	dprintf_mciwave(stddeb,
+	       "widAddBuffer(%u, %08X, %08X);\n", wDevID, lpWaveHdr, dwSize);
 	if (WInDev[wDevID].unixdev == 0) {
-		printf("Linux 'widAddBuffer' // can't do it !\n");
+	        fprintf(stderr,"Linux 'widAddBuffer' // can't do it !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	if (WInDev[wDevID].lpQueueHdr == NULL || 
 		!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
-		printf("Linux 'widAddBuffer' // never been prepared !\n");
+	        fprintf(stderr,
+		       "Linux 'widAddBuffer' // never been prepared !\n");
 		return WAVERR_UNPREPARED;
 		}
 	if ((lpWaveHdr->dwFlags & WHDR_INQUEUE) &&
 		(WInDev[wDevID].lpQueueHdr != lpWaveHdr)) {
 		/* except if it's the one just prepared ... */
-		printf("Linux 'widAddBuffer' // header already in use !\n");
+	        fprintf(stderr,
+			"Linux 'widAddBuffer' // header already in use !\n");
 		return WAVERR_STILLPLAYING;
 		}
 	lpWaveHdr->dwFlags |= WHDR_PREPARED;
@@ -1423,7 +1429,8 @@
 		lpWIHdr->lpNext = lpWaveHdr;
 		count++;
 		}
-	printf("widAddBuffer // buffer added ! (now %u in queue)\n", count);
+	dprintf_mciwave(stddeb,
+	      "widAddBuffer // buffer added ! (now %u in queue)\n", count);
 	return MMSYSERR_NOERROR;
 #else
 	return MMSYSERR_NOTENABLED;
@@ -1436,13 +1443,14 @@
 DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
 {
 #ifdef linux
-	printf("widPrepare(%u, %08X, %08X);\n", wDevID, lpWaveHdr, dwSize);
+        dprintf_mciwave(stddeb,
+	      "widPrepare(%u, %08X, %08X);\n", wDevID, lpWaveHdr, dwSize);
 	if (WInDev[wDevID].unixdev == 0) {
-		printf("Linux 'widPrepare' // can't prepare !\n");
+	        fprintf(stderr,"Linux 'widPrepare' // can't prepare !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	if (WInDev[wDevID].lpQueueHdr != NULL) {
-		printf("Linux 'widPrepare' // already prepare !\n");
+                fprintf(stderr,"Linux 'widPrepare' // already prepare !\n");
 		return WAVERR_BADFORMAT;
 		}
 	WInDev[wDevID].dwTotalRecorded = 0;
@@ -1452,7 +1460,7 @@
 	lpWaveHdr->dwFlags |= WHDR_INQUEUE;
 	lpWaveHdr->dwFlags &= ~WHDR_DONE;
 	lpWaveHdr->dwBytesRecorded = 0;
-	printf("Linux 'widPrepare' // header prepared !\n");
+	dprintf_mciwave(stddeb,"Linux 'widPrepare' // header prepared !\n");
 	return MMSYSERR_NOERROR;
 #else
 	return MMSYSERR_NOTENABLED;
@@ -1465,16 +1473,18 @@
 DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
 {
 #ifdef linux
-	printf("widUnprepare(%u, %08X, %08X);\n", wDevID, lpWaveHdr, dwSize);
+        dprintf_mciwave(stddeb,
+	    "widUnprepare(%u, %08X, %08X);\n", wDevID, lpWaveHdr, dwSize);
 	if (WInDev[wDevID].unixdev == 0) {
-		printf("Linux 'widUnprepare' // can't unprepare !\n");
+                fprintf(stderr,"Linux 'widUnprepare' // can't unprepare !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
 	lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
 	lpWaveHdr->dwFlags |= WHDR_DONE;
 	WInDev[wDevID].lpQueueHdr = NULL;
-	printf("Linux 'widUnprepare' // all headers unprepared !\n");
+	dprintf_mciwave(stddeb,
+		  "Linux 'widUnprepare' // all headers unprepared !\n");
 	return MMSYSERR_NOERROR;
 #else
 	return MMSYSERR_NOTENABLED;
@@ -1489,37 +1499,40 @@
 #ifdef linux
 	int			count	= 1;
 	LPWAVEHDR 	lpWIHdr;
-	printf("widStart(%u);\n", wDevID);
+	dprintf_mciwave(stddeb,"widStart(%u);\n", wDevID);
 	if (WInDev[wDevID].unixdev == 0) {
-		printf("Linux 'widStart' // can't start recording !\n");
+	        fprintf(stderr,
+		       "Linux 'widStart' // can't start recording !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	if (WInDev[wDevID].lpQueueHdr == NULL || 
 		WInDev[wDevID].lpQueueHdr->lpData == NULL) {
-		printf("Linux 'widStart' // never been prepared !\n");
+	        fprintf(stderr,"Linux 'widStart' // never been prepared !\n");
 		return WAVERR_UNPREPARED;
 		}
 	lpWIHdr = WInDev[wDevID].lpQueueHdr;
 	while(lpWIHdr != NULL) {
 		lpWIHdr->dwBufferLength &= 0xFFFF;
-		printf("widStart // recording buf#%u=%08X size=%u \n", 
+                dprintf_mciwave(stddeb,
+		        "widStart // recording buf#%u=%08X size=%u \n",
 			count, lpWIHdr->lpData, lpWIHdr->dwBufferLength);
-		fflush(stdout);
+		fflush(stddeb);
 		read (WInDev[wDevID].unixdev, lpWIHdr->lpData,
-							lpWIHdr->dwBufferLength);
+						      lpWIHdr->dwBufferLength);
 		lpWIHdr->dwBytesRecorded = lpWIHdr->dwBufferLength;
 		WInDev[wDevID].dwTotalRecorded += lpWIHdr->dwBytesRecorded;
 		lpWIHdr->dwFlags &= ~WHDR_INQUEUE;
 		lpWIHdr->dwFlags |= WHDR_DONE;
 		if (WAVE_NotifyClient(wDevID, WIM_DATA, (DWORD)lpWIHdr, 0L) != 
 			MMSYSERR_NOERROR) {
-			printf("Linux 'widStart' // can't notify client !\n");
+		        fprintf(stderr,
+			     "Linux 'widStart' // can't notify client !\n");
 			return MMSYSERR_INVALPARAM;
 			}
 		lpWIHdr = lpWIHdr->lpNext;
 		count++;
 		}
-	printf("widStart // end of recording !\n");
+	dprintf_mciwave(stddeb,"widStart // end of recording !\n");
 	fflush(stdout);
 	return MMSYSERR_NOERROR;
 #else
@@ -1533,9 +1546,9 @@
 DWORD widStop(WORD wDevID)
 {
 #ifdef linux
-	printf("widStop(%u);\n", wDevID);
+        dprintf_mciwave(stddeb,"widStop(%u);\n", wDevID);
 	if (WInDev[wDevID].unixdev == 0) {
-		printf("Linux 'widStop' // can't stop !\n");
+                fprintf(stderr,"Linux 'widStop' // can't stop !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	return MMSYSERR_NOERROR;
@@ -1550,9 +1563,9 @@
 DWORD widReset(WORD wDevID)
 {
 #ifdef linux
-	printf("widReset(%u);\n", wDevID);
+        dprintf_mciwave(stddeb,"widReset(%u);\n", wDevID);
 	if (WInDev[wDevID].unixdev == 0) {
-		printf("Linux 'widReset' // can't reset !\n");
+                fprintf(stderr,"Linux 'widReset' // can't reset !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	return MMSYSERR_NOERROR;
@@ -1568,41 +1581,43 @@
 {
 #ifdef linux
 	int		time;
-#ifdef DEBUG_MCIWAVE
-	printf("widGetPosition(%u, %08X, %u);\n", wDevID, lpTime, uSize);
-#endif
+        dprintf_mciwave(stddeb,
+		"widGetPosition(%u, %08X, %u);\n", wDevID, lpTime, uSize);
 	if (WInDev[wDevID].unixdev == 0) {
-		printf("Linux 'widGetPosition' // can't get pos !\n");
+                fprintf(stderr,"Linux 'widGetPosition' // can't get pos !\n");
 		return MMSYSERR_NOTENABLED;
 		}
 	if (lpTime == NULL)	return MMSYSERR_INVALPARAM;
 TryAGAIN:
-#ifdef DEBUG_MCIWAVE
-	printf("widGetPosition // wType=%04X !\n", lpTime->wType);
-	printf("widGetPosition // wBitsPerSample=%u\n",
+	dprintf_mciwave(stddeb,"widGetPosition // wType=%04X !\n", 
+			lpTime->wType);
+	dprintf_mciwave(stddeb,"widGetPosition // wBitsPerSample=%u\n",
 			WInDev[wDevID].Format.wBitsPerSample); 
-	printf("widGetPosition // nSamplesPerSec=%u\n",
+	dprintf_mciwave(stddeb,"widGetPosition // nSamplesPerSec=%u\n",
 			WInDev[wDevID].Format.wf.nSamplesPerSec); 
-	printf("widGetPosition // nChannels=%u\n",
+	dprintf_mciwave(stddeb,"widGetPosition // nChannels=%u\n",
 			WInDev[wDevID].Format.wf.nChannels); 
-	printf("widGetPosition // nAvgBytesPerSec=%u\n",
+	dprintf_mciwave(stddeb,"widGetPosition // nAvgBytesPerSec=%u\n",
 			WInDev[wDevID].Format.wf.nAvgBytesPerSec); 
- 	fflush(stdout);
-#endif
+	fflush(stddeb);
 	switch(lpTime->wType) {
 		case TIME_BYTES:
 			lpTime->u.cb = WInDev[wDevID].dwTotalRecorded;
-			printf("widGetPosition // TIME_BYTES=%u\n", lpTime->u.cb);
+			dprintf_mciwave(stddeb,
+			    "widGetPosition // TIME_BYTES=%u\n", lpTime->u.cb);
 			break;
 		case TIME_SAMPLES:
 			lpTime->u.sample = WInDev[wDevID].dwTotalRecorded * 8 /
-						WInDev[wDevID].Format.wBitsPerSample;
-			printf("widGetPosition // TIME_SAMPLES=%u\n", lpTime->u.sample);
+					  WInDev[wDevID].Format.wBitsPerSample;
+			dprintf_mciwave(stddeb,
+					"widGetPosition // TIME_SAMPLES=%u\n", 
+					lpTime->u.sample);
 			break;
 		case TIME_MS:
 			lpTime->u.ms = WInDev[wDevID].dwTotalRecorded /
 					(WInDev[wDevID].Format.wf.nAvgBytesPerSec / 1000);
-			printf("widGetPosition // TIME_MS=%u\n", lpTime->u.ms);
+			dprintf_mciwave(stddeb,
+			      "widGetPosition // TIME_MS=%u\n", lpTime->u.ms);
 			break;
 		case TIME_SMPTE:
 			time = WInDev[wDevID].dwTotalRecorded /
@@ -1615,12 +1630,12 @@
 			time -= lpTime->u.smpte.sec * 30;
 			lpTime->u.smpte.frame = time;
 			lpTime->u.smpte.fps = 30;
-			printf("widGetPosition // TIME_SMPTE=%02u:%02u:%02u:%02u\n", 
+            dprintf_mciwave(stddeb,"widGetPosition // TIME_SMPTE=%02u:%02u:%02u:%02u\n",
 					lpTime->u.smpte.hour, lpTime->u.smpte.min,
 					lpTime->u.smpte.sec, lpTime->u.smpte.frame);
 			break;
 		default:
-			printf("widGetPosition() format not supported ! use TIME_MS !\n");
+			fprintf(stderr,"widGetPosition() format not supported ! use TIME_MS !\n");
 			lpTime->wType = TIME_MS;
 			goto TryAGAIN;
 		}
@@ -1636,7 +1651,7 @@
 DWORD widMessage(WORD wDevID, WORD wMsg, DWORD dwUser, 
 					DWORD dwParam1, DWORD dwParam2)
 {
-	printf("widMessage(%u, %04X, %08X, %08X, %08X);\n", 
+        dprintf_mciwave(stddeb,"widMessage(%u, %04X, %08X, %08X, %08X);\n",
 			wDevID, wMsg, dwUser, dwParam1, dwParam2);
 	switch(wMsg) {
 		case WIDM_OPEN:
diff --git a/misc/clipboard.c b/misc/clipboard.c
index 17cca79..ad2d99a 100644
--- a/misc/clipboard.c
+++ b/misc/clipboard.c
@@ -6,10 +6,6 @@
 
 static char Copyright[] = "Copyright Martin Ayotte, 1994";
 
-/*
-#define DEBUG_CLIPBOARD
-*/
-
 #include <stdlib.h>
 #include <stdio.h>
 #include <windows.h>
@@ -20,6 +16,10 @@
 #include "prototypes.h"
 #include "heap.h"
 #include "win.h"
+#include "stddebug.h"
+/* #define DEBUG_CLIPBOARD /* */
+/* #undef  DEBUG_CLIPBOARD /* */
+#include "debug.h"
 
 typedef struct tagCLIPFORMAT {
     WORD	wFormatID;
@@ -58,9 +58,7 @@
 {
     if (hWndClipboardOwner != 0) return FALSE;
     hWndClipboardOwner = hWnd;
-#ifdef DEBUG_CLIPBOARD
-    printf("OpenClipboard(%04X); !\n", hWnd);
-#endif
+    dprintf_clipboard(stddeb,"OpenClipboard(%04X); !\n", hWnd);
     return TRUE;
 }
 
@@ -72,9 +70,7 @@
 {
     if (hWndClipboardOwner == 0) return FALSE;
     hWndClipboardOwner = 0;
-#ifdef DEBUG_CLIPBOARD
-    printf("CloseClipboard(); !\n");
-#endif
+    dprintf_clipboard(stddeb,"CloseClipboard(); !\n");
     return TRUE;
 }
 
@@ -86,9 +82,7 @@
 {
     LPCLIPFORMAT lpFormat = ClipFormats; 
     if (hWndClipboardOwner == 0) return FALSE;
-#ifdef DEBUG_CLIPBOARD
-    printf("EmptyClipboard(); !\n");
-#endif
+    dprintf_clipboard(stddeb,"EmptyClipboard(); !\n");
     while(TRUE) {
 	if (lpFormat == NULL) break;
 	if (lpFormat->hData != 0) {
@@ -106,9 +100,8 @@
  */
 HWND GetClipboardOwner()
 {
-#ifdef DEBUG_CLIPBOARD
-    printf("GetClipboardOwner() = %04X !\n", hWndClipboardOwner);
-#endif
+    dprintf_clipboard(stddeb,
+		"GetClipboardOwner() = %04X !\n", hWndClipboardOwner);
     return hWndClipboardOwner;
 }
 
@@ -119,9 +112,8 @@
 HANDLE SetClipboardData(WORD wFormat, HANDLE hData)
 {
     LPCLIPFORMAT lpFormat = ClipFormats; 
-#ifdef DEBUG_CLIPBOARD
-    printf("SetClipboardDate(%04X, %04X) !\n", wFormat, hData);
-#endif
+    dprintf_clipboard(stddeb,
+		"SetClipboardDate(%04X, %04X) !\n", wFormat, hData);
     while(TRUE) {
 	if (lpFormat == NULL) return 0;
 	if (lpFormat->wFormatID == wFormat) break;
@@ -139,9 +131,7 @@
 HANDLE GetClipboardData(WORD wFormat)
 {
     LPCLIPFORMAT lpFormat = ClipFormats; 
-#ifdef DEBUG_CLIPBOARD
-    printf("GetClipboardData(%04X) !\n", wFormat);
-#endif
+    dprintf_clipboard(stddeb,"GetClipboardData(%04X) !\n", wFormat);
     while(TRUE) {
 	if (lpFormat == NULL) return 0;
 	if (lpFormat->wFormatID == wFormat) break;
@@ -161,17 +151,14 @@
     while(TRUE) {
 	if (lpFormat == NULL) break;
 	if (lpFormat->hData != 0) {
-#ifdef DEBUG_CLIPBOARD
-	    printf("CountClipboardFormats // Find Not Empty (%04X) !\n", 
+        dprintf_clipboard(stddeb,
+		"CountClipboardFormats // Find Not Empty (%04X) !\n",
 					lpFormat->hData);
-#endif
 	    FormatCount++;
 	    }
 	lpFormat = lpFormat->NextFormat;
 	}
-#ifdef DEBUG_CLIPBOARD
-    printf("CountClipboardFormats() = %d !\n", FormatCount);
-#endif
+    dprintf_clipboard(stddeb,"CountClipboardFormats() = %d !\n", FormatCount);
     return FormatCount;
 }
 
@@ -182,9 +169,7 @@
 WORD EnumClipboardFormats(WORD wFormat)
 {
     LPCLIPFORMAT lpFormat = ClipFormats; 
-#ifdef DEBUG_CLIPBOARD
-    printf("EnumClipboardFormats(%04X) !\n", wFormat);
-#endif
+    dprintf_clipboard(stddeb,"EnumClipboardFormats(%04X) !\n", wFormat);
     if (wFormat == 0) {
 	if (lpFormat->hData != 0) 
 	    return lpFormat->wFormatID;
@@ -196,20 +181,17 @@
 	if (lpFormat->wFormatID == wFormat) break;
 	lpFormat = lpFormat->NextFormat;
 	}
-#ifdef DEBUG_CLIPBOARD
-    printf("EnumClipboardFormats // Find Last (%04X) !\n", 
+    dprintf_clipboard(stddeb,"EnumClipboardFormats // Find Last (%04X) !\n",
 				lpFormat->wFormatID);
-#endif
     lpFormat = lpFormat->NextFormat;
     while(TRUE) {
 	if (lpFormat == NULL) return 0;
 	if (lpFormat->hData != 0) break;
 	lpFormat = lpFormat->NextFormat;
 	}
-#ifdef DEBUG_CLIPBOARD
-    printf("EnumClipboardFormats // Find Not Empty Id=%04X hData=%04X !\n",
+    dprintf_clipboard(stddeb,
+		"EnumClipboardFormats // Find Not Empty Id=%04X hData=%04X !\n",
 				lpFormat->wFormatID, lpFormat->hData);
-#endif
     return lpFormat->wFormatID;
 }
 
@@ -229,9 +211,7 @@
     lpNewFormat = (LPCLIPFORMAT)malloc(sizeof(CLIPFORMAT));
     if (lpNewFormat == NULL) return 0;
     lpFormat->NextFormat = lpNewFormat;
-#ifdef DEBUG_CLIPBOARD
-    printf("RegisterClipboardFormat('%s') !\n", FormatName);
-#endif
+    dprintf_clipboard(stddeb,"RegisterClipboardFormat('%s') !\n", FormatName);
     lpNewFormat->wFormatID = LastRegFormat;
     lpNewFormat->wRefCount = 1;
     lpNewFormat->Name = (LPSTR)malloc(strlen(FormatName) + 1);
@@ -254,20 +234,18 @@
 int GetClipboardFormatName(WORD wFormat, LPSTR retStr, short maxlen)
 {
     LPCLIPFORMAT lpFormat = ClipFormats; 
-#ifdef DEBUG_CLIPBOARD
-    printf("GetClipboardFormat(%04X, %08X, %d) !\n", wFormat, retStr, maxlen);
-#endif
+    dprintf_clipboard(stddeb,
+	"GetClipboardFormat(%04X, %08X, %d) !\n", wFormat, retStr, maxlen);
     while(TRUE) {
 	if (lpFormat == NULL) return 0;
 	if (lpFormat->wFormatID == wFormat) break;
 	lpFormat = lpFormat->NextFormat;
 	}
     if (lpFormat->Name == NULL) return 0;
-#ifdef DEBUG_CLIPBOARD
-    printf("GetClipboardFormat // Name='%s' !\n", lpFormat->Name);
-#endif
+    dprintf_clipboard(stddeb,
+		"GetClipboardFormat // Name='%s' !\n", lpFormat->Name);
     maxlen = min(maxlen - 1, strlen(lpFormat->Name));
-    printf("GetClipboardFormat // maxlen=%d !\n", maxlen);
+    dprintf_clipboard(stddeb,"GetClipboardFormat // maxlen=%d !\n", maxlen);
     memcpy(retStr, lpFormat->Name, maxlen);
     retStr[maxlen] = 0;
     return maxlen;
@@ -279,9 +257,7 @@
  */
 HWND SetClipboardViewer(HWND hWnd)
 {
-#ifdef DEBUG_CLIPBOARD
-    printf("SetClipboardFormat(%04X) !\n", hWnd);
-#endif
+    dprintf_clipboard(stddeb,"SetClipboardFormat(%04X) !\n", hWnd);
     hWndViewer = hWnd;
 }
 
@@ -291,9 +267,8 @@
  */
 HWND GetClipboardViewer()
 {
-#ifdef DEBUG_CLIPBOARD
-    printf("GetClipboardFormat() = %04X !\n", hWndViewer);
-#endif
+    dprintf_clipboard(stddeb,"GetClipboardFormat() = %04X !\n", hWndViewer);
+    return hWndViewer;
 }
 
 
@@ -302,9 +277,8 @@
  */
 BOOL ChangeClipboardChain(HWND hWnd, HWND hWndNext)
 {
-#ifdef DEBUG_CLIPBOARD
-    printf("ChangeClipboardChain(%04X, %04X) !\n", hWnd, hWndNext);
-#endif
+    dprintf_clipboard(stdnimp,
+		"ChangeClipboardChain(%04X, %04X) !\n", hWnd, hWndNext);
 }
 
 
@@ -314,9 +288,7 @@
 BOOL IsClipboardFormatAvailable(WORD wFormat)
 {
     LPCLIPFORMAT lpFormat = ClipFormats; 
-#ifdef DEBUG_CLIPBOARD
-    printf("IsClipboardFormatAvailable(%04X) !\n", wFormat);
-#endif
+    dprintf_clipboard(stddeb,"IsClipboardFormatAvailable(%04X) !\n", wFormat);
     while(TRUE) {
 	if (lpFormat == NULL) return FALSE;
 	if (lpFormat->wFormatID == wFormat) break;
@@ -331,9 +303,8 @@
  */
 HWND GetOpenClipboardWindow()
 {
-#ifdef DEBUG_CLIPBOARD
-    printf("GetOpenClipboardWindow() = %04X !\n", hWndClipboardOwner);
-#endif
+    dprintf_clipboard(stddeb,
+		"GetOpenClipboardWindow() = %04X !\n", hWndClipboardOwner);
     return hWndClipboardOwner;
 }
 
@@ -343,9 +314,8 @@
  */
 int GetPriorityClipboardFormat(WORD FAR *lpPriorityList, short nCount)
 {
-#ifdef DEBUG_CLIPBOARD
-    printf("GetPriorityClipboardFormat(%08X, %d) !\n", lpPriorityList, nCount);
-#endif
+    dprintf_clipboard(stdnimp,
+	"GetPriorityClipboardFormat(%08X, %d) !\n", lpPriorityList, nCount);
 }
 
 
diff --git a/misc/comm.c b/misc/comm.c
index 4c6edfb..930a5f1 100644
--- a/misc/comm.c
+++ b/misc/comm.c
@@ -19,8 +19,10 @@
 #include "wine.h"
 #include "windows.h"
 #include "comm.h"
-
+#include "stddebug.h"
 /* #define DEBUG_COMM /* */
+/* #undef  DEBUG_COMM /* */
+#include "debug.h"
 
 int commerror = 0, eventmask = 0;
 
@@ -141,9 +143,8 @@
 	int port;
 	char *ptr, temp[256];
 
-#ifdef DEBUG_COMM
-fprintf(stderr,"BuildCommDCB: (%s), ptr %d\n", device, (long) lpdcb);
-#endif
+	dprintf_comm(stddeb,
+		"BuildCommDCB: (%s), ptr %d\n", device, (long) lpdcb);
 	commerror = 0;
 
 	if (!strncasecmp(device,"COM",3)) {
@@ -174,14 +175,14 @@
 		strcpy(temp,device+5);
 		ptr = strtok(temp, ","); 
 
-		fprintf(stderr,"BuildCommDCB: baudrate (%s)\n", ptr);
+        	dprintf_comm(stddeb,"BuildCommDCB: baudrate (%s)\n", ptr);
 		lpdcb->BaudRate = atoi(ptr);
 
 		ptr = strtok(NULL, ",");
 		if (islower(*ptr))
 			*ptr = toupper(*ptr);
 
-		fprintf(stderr,"BuildCommDCB: parity (%c)\n", *ptr);
+        	dprintf_comm(stddeb,"BuildCommDCB: parity (%c)\n", *ptr);
 		switch (*ptr) {
 			case 'N':
 				lpdcb->Parity = NOPARITY;
@@ -205,11 +206,11 @@
 		}
 
 		ptr = strtok(NULL, ","); 
-		fprintf(stderr, "BuildCommDCB: charsize (%c)\n", *ptr);
+         	dprintf_comm(stddeb, "BuildCommDCB: charsize (%c)\n", *ptr);
 		lpdcb->ByteSize = *ptr - '0';
 
 		ptr = strtok(NULL, ",");
-		fprintf(stderr, "BuildCommDCB: stopbits (%c)\n", *ptr);
+        	dprintf_comm(stddeb, "BuildCommDCB: stopbits (%c)\n", *ptr);
 		switch (*ptr) {
 			case '1':
 				lpdcb->StopBits = ONESTOPBIT;
@@ -230,10 +231,8 @@
 {
 	int port, fd;
 
-#ifdef DEBUG_COMM
-fprintf(stderr,"OpenComm: %s, %d, %d\n", device, cbInQueue, cbOutQueue);
-#endif	
-	
+    	dprintf_comm(stddeb,
+		"OpenComm: %s, %d, %d\n", device, cbInQueue, cbOutQueue);
 	commerror = 0;
 
 	if (!strncasecmp(device,"COM",3)) {
@@ -288,10 +287,7 @@
 
 int CloseComm(int fd)
 {
-#ifdef DEBUG_COMM
-fprintf(stderr,"CloseComm: fd %d\n", fd);
-#endif	
-
+    	dprintf_comm(stddeb,"CloseComm: fd %d\n", fd);
 	if (close(fd) == -1) {
 		commerror = WinError();
 		return -1;
@@ -305,10 +301,7 @@
 {
 	struct DosDeviceStruct *ptr;
 
-#ifdef DEBUG_COMM
-fprintf(stderr,"SetCommBreak: fd: %d\n", fd);
-#endif	
-
+	dprintf_comm(stddeb,"SetCommBreak: fd: %d\n", fd);
 	if ((ptr = GetDeviceStruct(fd)) == NULL) {
 		commerror = IE_BADID;
 		return -1;
@@ -323,10 +316,7 @@
 {
 	struct DosDeviceStruct *ptr;
 
-#ifdef DEBUG_COMM
-fprintf(stderr,"ClearCommBreak: fd: %d\n", fd);
-#endif	
-
+    	dprintf_comm(stddeb,"ClearCommBreak: fd: %d\n", fd);
 	if ((ptr = GetDeviceStruct(fd)) == NULL) {
 		commerror = IE_BADID;
 		return -1;
@@ -342,10 +332,8 @@
 	int max;
 	struct termios port;
 
-#ifdef DEBUG_COMM
-fprintf(stderr,"EscapeCommFunction fd: %d, function: %d\n", fd, nFunction);
-#endif
-
+    	dprintf_comm(stddeb,
+		"EscapeCommFunction fd: %d, function: %d\n", fd, nFunction);
 	if (tcgetattr(fd, &port) == -1) {
 		commerror = WinError();	
 		return -1;
@@ -392,7 +380,9 @@
 			break;
 
 		default:
-			fprintf(stderr,"EscapeCommFunction fd: %d, unknown function: %d\n", fd, nFunction);
+			fprintf(stderr,
+			"EscapeCommFunction fd: %d, unknown function: %d\n", 
+			fd, nFunction);
 			break;				
 	}
 	
@@ -409,10 +399,7 @@
 {
 	int queue;
 
-#ifdef DEBUG_COMM
-fprintf(stderr,"FlushComm fd: %d, queue: %d\n", fd, fnQueue);
-#endif	
-
+    	dprintf_comm(stddeb,"FlushComm fd: %d, queue: %d\n", fd, fnQueue);
 	switch (fnQueue) {
 		case 0:
 			queue = TCOFLUSH;
@@ -421,7 +408,9 @@
 			queue = TCIFLUSH;
 			break;
 		default:
-			fprintf(stderr,"FlushComm fd: %d, UNKNOWN queue: %d\n", fd, fnQueue);
+			fprintf(stderr,
+				"FlushComm fd: %d, UNKNOWN queue: %d\n", 
+				fd, fnQueue);
 			return -1;
 		}
 	
@@ -436,28 +425,23 @@
 
 int GetCommError(int fd, COMSTAT FAR *lpStat)
 {
-#ifdef DEBUG_COMM
-fprintf(stderr,"GetCommError: fd %d (current error %d)\n", fd, commerror);
-#endif	
-
+    	dprintf_comm(stddeb,
+		"GetCommError: fd %d (current error %d)\n", fd, commerror);
 	return(commerror);
 }
 
 UINT FAR* SetCommEventMask(int fd, UINT fuEvtMask)
 {
-#ifdef DEBUG_COMM
-fprintf(stderr,"SetCommEventMask: fd %d, mask %d\n", fd, fuEvtMask);
-#endif	
-	
+    	dprintf_comm(stddeb,
+		"SetCommEventMask: fd %d, mask %d\n", fd, fuEvtMask);
 	eventmask |= fuEvtMask;
 	return (UINT *)&eventmask;
 }
 
 UINT GetCommEventMask(int fd, int fnEvtClear)
 {
-#ifdef DEBUG_COMM
-fprintf(stderr,"GetCommEventMask: fd %d, mask %d\n", fd, fnEvtClear);
-#endif	
+    	dprintf_comm(stddeb,
+		"GetCommEventMask: fd %d, mask %d\n", fd, fnEvtClear);
 	eventmask &= ~fnEvtClear;
 	return eventmask;
 }
@@ -466,10 +450,8 @@
 {
 	struct termios port;
 
-#ifdef DEBUG_COMM
-fprintf(stderr,"SetCommState: fd %d, ptr %d\n", lpdcb->Id, (long) lpdcb);
-#endif	
-
+    	dprintf_comm(stddeb,
+		"SetCommState: fd %d, ptr %d\n", lpdcb->Id, (long) lpdcb);
 	if (tcgetattr(lpdcb->Id, &port) == -1) {
 		commerror = WinError();	
 		return -1;
@@ -489,7 +471,7 @@
 	port.c_lflag &= ~(ICANON|ECHO|ISIG);
 	port.c_lflag |= NOFLSH;
 
-	fprintf(stderr,"SetCommState: baudrate %d\n",lpdcb->BaudRate);
+    	dprintf_comm(stddeb,"SetCommState: baudrate %d\n",lpdcb->BaudRate);
 #ifdef CBAUD
 	port.c_cflag &= ~CBAUD;
 	switch (lpdcb->BaudRate) {
@@ -577,7 +559,7 @@
         }
         port.c_ispeed = port.c_ospeed;
 #endif
-	fprintf(stderr,"SetCommState: bytesize %d\n",lpdcb->ByteSize);
+    	dprintf_comm(stddeb,"SetCommState: bytesize %d\n",lpdcb->ByteSize);
 	port.c_cflag &= ~CSIZE;
 	switch (lpdcb->ByteSize) {
 		case 5:
@@ -597,7 +579,7 @@
 			return -1;
 	}
 
-	fprintf(stderr,"SetCommState: parity %d\n",lpdcb->Parity);
+    	dprintf_comm(stddeb,"SetCommState: parity %d\n",lpdcb->Parity);
 	port.c_cflag &= ~(PARENB | PARODD);
 	if (lpdcb->fParity)
 		switch (lpdcb->Parity) {
@@ -618,7 +600,7 @@
 		}
 	
 
-	fprintf(stderr,"SetCommState: stopbits %d\n",lpdcb->StopBits);
+    	dprintf_comm(stddeb,"SetCommState: stopbits %d\n",lpdcb->StopBits);
 	switch (lpdcb->StopBits) {
 		case ONESTOPBIT:
 				port.c_cflag &= ~CSTOPB;
@@ -655,10 +637,7 @@
 {
 	struct termios port;
 
-#ifdef DEBUG_COMM
-fprintf(stderr,"GetCommState: fd %d, ptr %d\n", fd, (long) lpdcb);
-#endif
-
+    	dprintf_comm(stddeb,"GetCommState: fd %d, ptr %d\n", fd, (long) lpdcb);
 	if (tcgetattr(fd, &port) == -1) {
 		commerror = WinError();	
 		return -1;
@@ -772,10 +751,8 @@
 {
 	struct DosDeviceStruct *ptr;
 
-#ifdef DEBUG_COMM
-fprintf(stderr,"TransmitCommChar: fd %d, data %d \n", fd, chTransmit);
-#endif	
-
+    	dprintf_comm(stddeb,
+		"TransmitCommChar: fd %d, data %d \n", fd, chTransmit);
 	if ((ptr = GetDeviceStruct(fd)) == NULL) {
 		commerror = IE_BADID;
 		return -1;
@@ -799,10 +776,7 @@
 {
 	struct DosDeviceStruct *ptr;
 
-#ifdef DEBUG_COMM
-fprintf(stderr,"UngetCommChar: fd %d (char %d)\n", fd, chUnget);
-#endif	
-
+    	dprintf_comm(stddeb,"UngetCommChar: fd %d (char %d)\n", fd, chUnget);
 	if ((ptr = GetDeviceStruct(fd)) == NULL) {
 		commerror = IE_BADID;
 		return -1;
@@ -825,10 +799,8 @@
 	int status, length;
 	struct DosDeviceStruct *ptr;
 
-#ifdef DEBUG_COMM
-fprintf(stderr,"ReadComm: fd %d, ptr %d, length %d\n", fd, (long) lpvBuf, cbRead);
-#endif	
-
+    	dprintf_comm(stddeb,
+	    "ReadComm: fd %d, ptr %d, length %d\n", fd, (long) lpvBuf, cbRead);
 	if ((ptr = GetDeviceStruct(fd)) == NULL) {
 		commerror = IE_BADID;
 		return -1;
@@ -864,10 +836,8 @@
 	int x, length;
 	struct DosDeviceStruct *ptr;
 
-#ifdef DEBUG_COMM
-fprintf(stderr,"WriteComm: fd %d, ptr %d, length %d\n", fd, (long) lpvBuf, cbWrite);
-#endif
-	
+    	dprintf_comm(stddeb,"WriteComm: fd %d, ptr %d, length %d\n", 
+		fd, (long) lpvBuf, cbWrite);
 	if ((ptr = GetDeviceStruct(fd)) == NULL) {
 		commerror = IE_BADID;
 		return -1;
@@ -878,10 +848,8 @@
 		return -1;
 	}	
 	
-#ifdef DEBUG_COMM
 	for (x=0; x != cbWrite ; x++)
-		fprintf(stderr,"%c", *(lpvBuf + x) );
-#endif
+        dprintf_comm(stddeb,"%c", *(lpvBuf + x) );
 
 	length = write(fd, (void *) lpvBuf, cbWrite);
 	
diff --git a/misc/cursor.c b/misc/cursor.c
deleted file mode 100644
index 91e88ef..0000000
--- a/misc/cursor.c
+++ /dev/null
@@ -1,464 +0,0 @@
-/*
- *    WINE
-*/
-static char Copyright[] = "Copyright  Martin Ayotte, 1993";
-
-/*
-#define DEBUG_CURSOR
-*/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <X11/cursorfont.h>
-#include <X11/Xlib.h>
-#include "prototypes.h"
-#include "windows.h"
-#include "win.h"
-#include "gdi.h"
-#include "wine.h"
-#include "cursor.h"
-
-static int ShowCursCount = 0;
-static HCURSOR hActiveCursor;
-static HCURSOR hEmptyCursor = 0;
-RECT	ClipCursorRect;
-extern HINSTANCE hSysRes;
-extern Window winHasCursor;
-extern int desktopX, desktopY;   /* misc/main.c */
-
-static struct { LPSTR name; HCURSOR cursor; } system_cursor[] =
-{
-    { IDC_ARROW, 0 },
-    { IDC_IBEAM, 0 },
-    { IDC_WAIT, 0 },
-    { IDC_CROSS, 0 },
-    { IDC_UPARROW, 0 },
-    { IDC_SIZE, 0 },
-    { IDC_ICON, 0 },
-    { IDC_SIZENWSE, 0 },
-    { IDC_SIZENESW, 0 },
-    { IDC_SIZEWE, 0 },
-    { IDC_SIZENS, 0 }
-};
-
-#define NB_SYS_CURSORS  (sizeof(system_cursor)/sizeof(system_cursor[0]))
-
-
-/**********************************************************************
- *			LoadCursor [USER.173]
- */
-HCURSOR LoadCursor(HANDLE instance, LPSTR cursor_name)
-{
-    XColor	bkcolor;
-    XColor	fgcolor;
-    HCURSOR 	hCursor;
-    HANDLE 	rsc_mem;
-    WORD 	*lp;
-    CURSORDESCRIP *lpcurdesc;
-    CURSORALLOC	  *lpcur;
-    BITMAP 	BitMap;
-    HBITMAP 	hBitMap;
-    HDC 	hMemDC;
-    HDC 	hdc;
-    int i, j, image_size;
-#ifdef DEBUG_RESOURCE
-    printf("LoadCursor: instance = %04x, name = %08x\n",
-	   instance, cursor_name);
-#endif    
-
-    if (!instance)
-    {
-	for (i = 0; i < NB_SYS_CURSORS; i++)
-	    if (system_cursor[i].name == cursor_name)
-	    {
-		hCursor = system_cursor[i].cursor;
-		break;
-	    }
-	if (i == NB_SYS_CURSORS) return 0;
-	if (hCursor) return hCursor;
-    }
-    hCursor = GlobalAlloc(GMEM_MOVEABLE, sizeof(CURSORALLOC) + 1024L); 
-    if (hCursor == (HCURSOR)NULL) return 0;
-    if (!instance) system_cursor[i].cursor = hCursor;
-
-#ifdef DEBUG_CURSOR
-    printf("LoadCursor Alloc hCursor=%X\n", hCursor);
-#endif    
-    lpcur = (CURSORALLOC *)GlobalLock(hCursor);
-    memset(lpcur, 0, sizeof(CURSORALLOC));
-    if (instance == (HANDLE)NULL) {
-	instance = hSysRes;
-	switch((LONG)cursor_name) {
-	    case IDC_ARROW:
-		lpcur->xcursor = XCreateFontCursor(XT_display, XC_top_left_arrow);
-		GlobalUnlock(hCursor);
-	    	return hCursor;
-	    case IDC_CROSS:
-		lpcur->xcursor = XCreateFontCursor(XT_display, XC_crosshair);
-		GlobalUnlock(hCursor);
-	    	return hCursor;
-	    case IDC_IBEAM:
-		lpcur->xcursor = XCreateFontCursor(XT_display, XC_xterm);
-		GlobalUnlock(hCursor);
-	    	return hCursor;
-	    case IDC_WAIT:
-		lpcur->xcursor = XCreateFontCursor(XT_display, XC_watch);
-		GlobalUnlock(hCursor);
-	    	return hCursor;
-	    case IDC_SIZENS:
-		lpcur->xcursor = XCreateFontCursor(XT_display, XC_sb_v_double_arrow);
-		GlobalUnlock(hCursor);
-	    	return hCursor;
-	    case IDC_SIZEWE:
-		lpcur->xcursor = XCreateFontCursor(XT_display, XC_sb_h_double_arrow);
-		GlobalUnlock(hCursor);
-	    	return hCursor;
-            case IDC_SIZENWSE:
-            case IDC_SIZENESW:
-                lpcur->xcursor = XCreateFontCursor(XT_display, XC_fleur);
-                GlobalUnlock(hCursor);
-                return hCursor;
-	    default:
-		break;
-	    }
-	}
-
-#if 1
-    lpcur->xcursor = XCreateFontCursor(XT_display, XC_top_left_arrow);
-    GlobalUnlock(hCursor);
-    return hCursor;
-#endif
-
-    if (!(hdc = GetDC(GetDesktopWindow()))) return 0;
-    rsc_mem = RSC_LoadResource(instance, cursor_name, NE_RSCTYPE_GROUP_CURSOR, 
-			       &image_size);
-    if (rsc_mem == (HANDLE)NULL) {
-	printf("LoadCursor / Cursor %08X not Found !\n", cursor_name);
-	ReleaseDC(GetDesktopWindow(), hdc); 
-	return 0;
-	}
-    lp = (WORD *)GlobalLock(rsc_mem);
-    if (lp == NULL) {
-	GlobalFree(rsc_mem);
-	ReleaseDC(GetDesktopWindow(), hdc); 
-	return 0;
-	}
-    lpcurdesc = (CURSORDESCRIP *)(lp + 3);
-#ifdef DEBUG_CURSOR
-    printf("LoadCursor / image_size=%d\n", image_size);
-    printf("LoadCursor / curReserved=%X\n", *lp);
-    printf("LoadCursor / curResourceType=%X\n", *(lp + 1));
-    printf("LoadCursor / curResourceCount=%X\n", *(lp + 2));
-    printf("LoadCursor / cursor Width=%d\n", (int)lpcurdesc->Width);
-    printf("LoadCursor / cursor Height=%d\n", (int)lpcurdesc->Height);
-    printf("LoadCursor / cursor curXHotspot=%d\n", (int)lpcurdesc->curXHotspot);
-    printf("LoadCursor / cursor curYHotspot=%d\n", (int)lpcurdesc->curYHotspot);
-    printf("LoadCursor / cursor curDIBSize=%lX\n", (DWORD)lpcurdesc->curDIBSize);
-    printf("LoadCursor / cursor curDIBOffset=%lX\n", (DWORD)lpcurdesc->curDIBOffset);
-#endif
-    lpcur->descriptor = *lpcurdesc;
-    GlobalUnlock(rsc_mem);
-    GlobalFree(rsc_mem);
-    rsc_mem = RSC_LoadResource(instance, 
-    	MAKEINTRESOURCE(lpcurdesc->curDIBOffset), 
-    	NE_RSCTYPE_CURSOR, &image_size);
-    if (rsc_mem == (HANDLE)NULL) {
-	printf("LoadCursor / Cursor %08X Bitmap not Found !\n", cursor_name);
-	ReleaseDC(GetDesktopWindow(), hdc); 
-	return 0;
-	}
-    lp = (WORD *)GlobalLock(rsc_mem);
-    if (lp == NULL) {
-	GlobalFree(rsc_mem);
-	ReleaseDC(GetDesktopWindow(), hdc); 
-	return 0;
- 	}
-	lp++;
-    for (j = 0; j < 16; j++)
-    	printf("%04X ", *(lp + j));
-/*
-    if (*lp == sizeof(BITMAPINFOHEADER))
-	lpcur->hBitmap = ConvertInfoBitmap(hdc, (BITMAPINFO *)lp);
-    else
-*/
-        lpcur->hBitmap = 0;
-/*     lp += sizeof(BITMAP); */
-    for (i = 0; i < 81; i++) {
-	char temp = *((char *)lp + 162 + i);
-	*((char *)lp + 162 + i) = *((char *)lp + 324 - i);
-	*((char *)lp + 324 - i) = temp;
-	}
-    lpcur->pixshape = XCreatePixmapFromBitmapData(
-    	XT_display, DefaultRootWindow(XT_display), 
-        ((char *)lp + 211), 32, 32,
-/*
-        lpcurdesc->Width / 2, lpcurdesc->Height / 4, 
-*/
-        WhitePixel(XT_display, DefaultScreen(XT_display)), 
-        BlackPixel(XT_display, DefaultScreen(XT_display)), 1);
-    lpcur->pixmask = XCreatePixmapFromBitmapData(
-    	XT_display, DefaultRootWindow(XT_display), 
-        ((char *)lp + 211), 32, 32,
-        WhitePixel(XT_display, DefaultScreen(XT_display)), 
-        BlackPixel(XT_display, DefaultScreen(XT_display)), 1);
-    memset(&bkcolor, 0, sizeof(XColor));
-    memset(&fgcolor, 0, sizeof(XColor));
-    bkcolor.pixel = WhitePixel(XT_display, DefaultScreen(XT_display)); 
-    fgcolor.pixel = BlackPixel(XT_display, DefaultScreen(XT_display));
-printf("LoadCursor / before XCreatePixmapCursor !\n");
-    lpcur->xcursor = XCreatePixmapCursor(XT_display,
- 	lpcur->pixshape, lpcur->pixmask, 
- 	&fgcolor, &bkcolor, lpcur->descriptor.curXHotspot, 
- 	lpcur->descriptor.curYHotspot);
-    GlobalUnlock(rsc_mem);
-    GlobalFree(rsc_mem);
-/*
-    hCursor = CreateCursor(instance, lpcur->descriptor.curXHotspot, 
- 	lpcur->descriptor.curYHotspot, 32, 32,
-	(LPSTR)lp + 211, , (LPSTR)lp + 211);
-*/
-    XFreePixmap(XT_display, lpcur->pixshape);
-    XFreePixmap(XT_display, lpcur->pixmask);
-    ReleaseDC(GetDesktopWindow(), hdc); 
-    GlobalUnlock(hCursor);
-    return hCursor;
-}
-
-
-
-/**********************************************************************
- *			CreateCursor [USER.406]
- */
-HCURSOR CreateCursor(HANDLE instance, short nXhotspot, short nYhotspot, 
-	short nWidth, short nHeight, LPSTR lpANDbitPlane, LPSTR lpXORbitPlane)
-{
-    XColor	bkcolor;
-    XColor	fgcolor;
-    HCURSOR 	hCursor;
-    CURSORALLOC	  *lpcur;
-    BITMAP 	BitMap;
-    HBITMAP 	hBitMap;
-    HDC 	hMemDC;
-    HDC 	hdc;
-    int i, j;
-#ifdef DEBUG_RESOURCE
-    printf("CreateCursor: inst=%04x nXhotspot=%d  nYhotspot=%d nWidth=%d nHeight=%d\n",  
-       instance, nXhotspot, nYhotspot, nWidth, nHeight);
-    printf("CreateCursor: inst=%04x lpANDbitPlane=%08X lpXORbitPlane=%08X\n",
-	instance, lpANDbitPlane, lpXORbitPlane);
-#endif    
-    if (!(hdc = GetDC(GetDesktopWindow()))) return 0;
-    hCursor = GlobalAlloc(GMEM_MOVEABLE, sizeof(CURSORALLOC) + 1024L); 
-    if (hCursor == (HCURSOR)NULL) {
-	ReleaseDC(GetDesktopWindow(), hdc); 
-	return 0;
-	}
-    printf("CreateCursor Alloc hCursor=%X\n", hCursor);
-    lpcur = (CURSORALLOC *)GlobalLock(hCursor);
-    memset(lpcur, 0, sizeof(CURSORALLOC));
-    lpcur->descriptor.curXHotspot = nXhotspot;
-    lpcur->descriptor.curYHotspot = nYhotspot;
-    lpcur->pixshape = XCreatePixmapFromBitmapData(
-    	XT_display, DefaultRootWindow(XT_display), 
-        lpXORbitPlane, nWidth, nHeight,
-        WhitePixel(XT_display, DefaultScreen(XT_display)), 
-        BlackPixel(XT_display, DefaultScreen(XT_display)), 1);
-    lpcur->pixmask = XCreatePixmapFromBitmapData(
-    	XT_display, DefaultRootWindow(XT_display), 
-        lpANDbitPlane, nWidth, nHeight,
-        WhitePixel(XT_display, DefaultScreen(XT_display)), 
-        BlackPixel(XT_display, DefaultScreen(XT_display)), 1);
-    memset(&bkcolor, 0, sizeof(XColor));
-    memset(&fgcolor, 0, sizeof(XColor));
-    bkcolor.pixel = WhitePixel(XT_display, DefaultScreen(XT_display)); 
-    fgcolor.pixel = BlackPixel(XT_display, DefaultScreen(XT_display));
-    lpcur->xcursor = XCreatePixmapCursor(XT_display,
- 	lpcur->pixshape, lpcur->pixmask, 
- 	&fgcolor, &bkcolor, lpcur->descriptor.curXHotspot, 
- 	lpcur->descriptor.curYHotspot);
-    XFreePixmap(XT_display, lpcur->pixshape);
-    XFreePixmap(XT_display, lpcur->pixmask);
-    ReleaseDC(GetDesktopWindow(), hdc); 
-    GlobalUnlock(hCursor);
-    return hCursor;
-}
-
-
-
-/**********************************************************************
- *			DestroyCursor [USER.458]
- */
-BOOL DestroyCursor(HCURSOR hCursor)
-{
-    CURSORALLOC	*lpcur;
-    if (hCursor == (HCURSOR)NULL) return FALSE;
-    lpcur = (CURSORALLOC *)GlobalLock(hCursor);
-    if (lpcur->hBitmap != (HBITMAP)NULL) DeleteObject(lpcur->hBitmap);
-    GlobalUnlock(hCursor);
-    GlobalFree(hCursor);
-    return TRUE;
-}
-
-
-/**********************************************************************
- *			CURSOR_SetWinCursor
- *
- * Set the cursor for a given window. To be used instead of SetCursor()
- * wherever possible.
- */
-HCURSOR CURSOR_SetWinCursor( HWND hwnd, HCURSOR hCursor )
-{
-    CURSORALLOC	*lpcur;
-    HCURSOR	hOldCursor;
-    WND * wndPtr = WIN_FindWndPtr( hwnd );
-
-    if (!wndPtr || !hCursor) return 0;
-    lpcur = (CURSORALLOC *)GlobalLock(hCursor);
-    hOldCursor = hActiveCursor;
-    if (hActiveCursor != hCursor) ShowCursCount = 0;
-    if (ShowCursCount >= 0)
-	XDefineCursor( display, wndPtr->window, lpcur->xcursor );
-    GlobalUnlock(hCursor);
-    hActiveCursor = hCursor;
-    return hOldCursor;
-}
-
-
-/**********************************************************************
- *			SetCursor [USER.69]
- */
-HCURSOR SetCursor(HCURSOR hCursor)
-{
-    HDC		hDC;
-    HDC		hMemDC;
-    BITMAP	bm;
-    CURSORALLOC	*lpcur;
-    HCURSOR	hOldCursor;
-    Window 	root, child;
-    int		rootX, rootY;
-    int		childX, childY;
-    unsigned int mousebut;
-#ifdef DEBUG_CURSOR
-    printf("SetCursor / hCursor=%04X !\n", hCursor);
-#endif
-    if (hCursor == (HCURSOR)NULL) return FALSE;
-    lpcur = (CURSORALLOC *)GlobalLock(hCursor);
-    hOldCursor = hActiveCursor;
-#ifdef DEBUG_CURSOR
-    printf("SetCursor / lpcur->xcursor=%08X !\n", &lpcur->xcursor);
-    XQueryPointer(XT_display, DefaultRootWindow(XT_display),
-	&root, &child, &rootX, &rootY, &childX, &childY, &mousebut);
-    printf("SetCursor / winHasCursor=%08X !\n", winHasCursor);
-    printf("SetCursor / child=%08X !\n", child);
-#endif
-    if (hActiveCursor != hCursor) ShowCursCount = 0;
-    if ((ShowCursCount >= 0) & (winHasCursor != 0)) {
-/*	XUndefineCursor(XT_display, winHasCursor); */
-	XDefineCursor(XT_display, winHasCursor, lpcur->xcursor);
-	}
-    GlobalUnlock(hCursor);
-    hActiveCursor = hCursor;
-    return hOldCursor;
-}
-
-/**********************************************************************
- *			GetCursor [USER.247]
- */
-HCURSOR GetCursor(void)
-{
-	return hActiveCursor;
-}
-
-/**********************************************************************
- *                        SetCursorPos [USER.70]
- */
-void SetCursorPos(short x, short y)
-{
-#ifdef DEBUG_CURSOR
-    printf("SetCursorPos // x=%d y=%d\n", x, y);
-#endif
-    XWarpPointer( display, None, rootWindow, 0, 0, 0, 0, x, y );
-}
-
-
-/**********************************************************************
- *                        GetCursorPos [USER.17]
- */
-void GetCursorPos(LPPOINT lpRetPoint)
-{
-    Window 	root, child;
-    int		rootX, rootY;
-    int		childX, childY;
-    unsigned int mousebut;
-
-    if (!lpRetPoint) return;
-    if (!XQueryPointer( display, rootWindow, &root, &child,
-		        &rootX, &rootY, &childX, &childY, &mousebut ))
-	lpRetPoint->x = lpRetPoint->y = 0;
-    else
-    {
-	lpRetPoint->x = rootX + desktopX;
-	lpRetPoint->y = rootY + desktopY;
-    }
-#ifdef DEBUG_CURSOR
-	printf("GetCursorPos // x=%d y=%d\n", lpRetPoint->x, lpRetPoint->y);
-#endif
-}
-
-
-/**********************************************************************
- *			ShowCursor [USER.71]
- */
-int ShowCursor(BOOL bShow)
-{
-    HCURSOR	hCursor;
-#ifdef DEBUG_CURSOR
-	printf("ShowCursor bShow=%d ShowCount=%d !\n", bShow, ShowCursCount);
-#endif
-    if (bShow)
-	ShowCursCount++;
-    else
-	ShowCursCount--;
-    if (ShowCursCount >= 0) {
-/*    	if (hCursor == (HCURSOR)NULL) */
-    	    hCursor = LoadCursor((HINSTANCE)NULL, IDC_ARROW);
-	SetCursor(hCursor);
-	}
-    else {
-/*	XUndefineCursor(XT_display, winHasCursor); */
-	if (hEmptyCursor == (HCURSOR)NULL)
-	    hEmptyCursor = CreateCursor((HINSTANCE)NULL, 1, 1, 1, 1, 
-	    				"\xFF\xFF", "\xFF\xFF");
-	hCursor = SetCursor(hEmptyCursor);
-	hActiveCursor = hCursor;
-	}
-    return 0;
-}
-
-
-/**********************************************************************
- *                        ClipCursor [USER.16]
- */
-void ClipCursor(LPRECT lpNewClipRect)
-{
-    CopyRect(&ClipCursorRect, lpNewClipRect);
-}
-
-
-/**********************************************************************
- *                        GetClipCursor [USER.309]
- */
-void GetClipCursor(LPRECT lpRetClipRect)
-{
-    if (lpRetClipRect != NULL)
-	CopyRect(lpRetClipRect, &ClipCursorRect);
-}
-
-
-
-
diff --git a/misc/dos_fs.c b/misc/dos_fs.c
index bb1d3e5..29a68ed 100644
--- a/misc/dos_fs.c
+++ b/misc/dos_fs.c
@@ -3,6 +3,8 @@
  * NOV 1993 Erik Bos (erik@(trashcan.)hacktic.nl)
  *
  * FindFile by Bob, hacked for dos & unixpaths by Erik.
+ *
+ * Bugfix by dash@ifi.uio.no: ToUnix() was called to often
  */
 
 #include <ctype.h>
@@ -28,8 +30,10 @@
 #include "prototypes.h"
 #include "autoconf.h"
 #include "comm.h"
-
-/* #define DEBUG /* */
+#include "stddebug.h"
+/* #define DEBUG_DOSFS /* */
+/* #undef  DEBIG_DOSFS /* */
+#include "debug.h"
 
 #define WINE_INI_USER "~/.winerc"
 #define MAX_OPEN_DIRS 16
@@ -141,8 +145,7 @@
 
 	for (x=0; x!=MAX_DOS_DRIVES; x++) {
 		if (DosDrives[x].rootdir != NULL) {
-#ifdef DEBUG
-			fprintf(stderr, "DOSFS: %c: => %-40s %s %s %X %d\n",
+            dprintf_dosfs(stddeb, "DOSFS: %c: => %-40s %s %s %X %d\n",
 			'A'+x,
 			DosDrives[x].rootdir,
 			DosDrives[x].cwd,
@@ -150,21 +153,18 @@
 			DosDrives[x].serialnumber,
 			DosDrives[x].disabled
 			);	
-#endif
 		}
 	}
 
 	for (x=0; x!=MAX_OPEN_DIRS ; x++)
 		DosDirs[x].inuse = 0;
 
-#ifdef DEBUG
-	fprintf(stderr,"wine.ini = %s\n",WINE_INI);
-	fprintf(stderr,"win.ini = %s\n",WIN_INI);
-	fprintf(stderr,"windir = %s\n",WindowsDirectory);
-	fprintf(stderr,"sysdir = %s\n",SystemDirectory);
-	fprintf(stderr,"tempdir = %s\n",TempDirectory);
-	fprintf(stderr,"path = %s\n",WindowsPath);
-#endif
+    dprintf_dosfs(stddeb,"wine.ini = %s\n",WINE_INI);
+    dprintf_dosfs(stddeb,"win.ini = %s\n",WIN_INI);
+    dprintf_dosfs(stddeb,"windir = %s\n",WindowsDirectory);
+    dprintf_dosfs(stddeb,"sysdir = %s\n",SystemDirectory);
+    dprintf_dosfs(stddeb,"tempdir = %s\n",TempDirectory);
+    dprintf_dosfs(stddeb,"path = %s\n",WindowsPath);
 }
 
 WORD DOS_GetEquipment(void)
@@ -224,23 +224,17 @@
 	equipment = (diskdrives << 6) | (serialports << 9) | 
 		    (parallelports << 14) | 0x02;
 
-#ifdef DEBUG
-	fprintf(stderr, "DOS_GetEquipment : diskdrives = %d serialports = %d "
+    dprintf_dosfs(stddeb, "DOS_GetEquipment : diskdrives = %d serialports = %d "
 			"parallelports = %d\n"
 			"DOS_GetEquipment : equipment = %d\n",
 			diskdrives, serialports, parallelports, equipment);
-#endif
 
 	return (equipment);
 }
 
 int DOS_ValidDrive(int drive)
 {
-/*
-#ifdef DEBUG
-	fprintf(stderr,"ValidDrive %c (%d)\n",'A'+drive,drive);
-#endif
-*/
+    dprintf_dosfs(stddeb,"ValidDrive %c (%d)\n",'A'+drive,drive);
 	if (drive >= MAX_DOS_DRIVES)
 		return 0;
 	if (DosDrives[drive].rootdir == NULL)
@@ -251,21 +245,31 @@
 	return 1;
 }
 
+
+int DOS_ValidDirectory(char *name)
+{
+	char *dirname;
+	struct stat s;
+	if ((dirname = GetUnixFileName(name)) == NULL)
+		return 0;
+	if (stat(dirname,&s))
+		return 0;
+	if (!S_ISDIR(s.st_mode))
+		return 0;
+	return 1;
+}
+
+
+
 int DOS_GetDefaultDrive(void)
 {
-#ifdef DEBUG
-	fprintf(stderr,"GetDefaultDrive (%c)\n",'A'+CurrentDrive);
-#endif
-
+    dprintf_dosfs(stddeb,"GetDefaultDrive (%c)\n",'A'+CurrentDrive);
 	return( CurrentDrive);
 }
 
 void DOS_SetDefaultDrive(int drive)
 {
-#ifdef DEBUG
-	fprintf(stderr,"SetDefaultDrive to %c:\n",'A'+drive);
-#endif
-
+    dprintf_dosfs(stddeb,"SetDefaultDrive to %c:\n",'A'+drive);
 	if (DOS_ValidDrive(drive))
 		CurrentDrive = drive;
 }
@@ -336,11 +340,9 @@
 	
 	cwdptr = rootdir + strlen(rootdir);
 	nameptr = name;
-/*
-#ifdef DEBUG
-	fprintf(stderr,"GetUnixDirName: %s <=> %s => ",rootdir, name);
-#endif
-*/	
+
+	dprintf_dosfs(stddeb,"GetUnixDirName: %s <=> %s => ",rootdir, name);
+
 	while (*nameptr) {
 		if (*nameptr == '.' & !filename) {
 			nameptr++;
@@ -379,11 +381,11 @@
 	*cwdptr = '\0';
 
 	ToUnix(rootdir);
-/*
+
 #ifdef DEBUG
 	fprintf(stderr,"%s\n", rootdir);
 #endif
-*/
+
 }
 
 char *GetUnixFileName(char *dosfilename)
@@ -408,12 +410,7 @@
 	strcat(temp, DosDrives[drive].cwd);
 	GetUnixDirName(temp + strlen(DosDrives[drive].rootdir), dosfilename);
 
-	ToUnix(temp);
-
-#ifdef DEBUG
-	fprintf(stderr,"GetUnixFileName: %s => %s\n", dosfilename, temp);
-#endif
-
+	dprintf_dosfs(stddeb,"GetUnixFileName: %s => %s\n", dosfilename, temp);
 	return(temp);
 }
 
@@ -427,7 +424,6 @@
 		if (DosDrives[i].rootdir != NULL) {
  			strcpy(rootdir, DosDrives[i].rootdir);
  			strcat(rootdir, "/");
-                	ToUnix(rootdir);
  			if (strncmp(rootdir, unixfilename, strlen(rootdir)) == 0) {
  				sprintf(temp, "%c:\\%s", 'A' + i, unixfilename + strlen(rootdir));
 				ToDos(temp);
@@ -451,30 +447,34 @@
 	
 	strcpy(temp, DosDrives[drive].cwd);
 	ToDos(temp);
-	fprintf(stderr, "2 %s\n", temp);
 	ChopOffSlash(temp);
 
-#ifdef DEBUG
-	fprintf(stderr,"DOS_GetCWD: %c: %s\n",'A'+drive, temp + 1);
-#endif
+    	dprintf_dosfs(stddeb,"DOS_GetCWD: %c: %s\n",'A'+drive, temp + 1);
 	return (temp + 1);
 }
 
 int DOS_ChangeDir(int drive, char *dirname)
 {
-	char temp[256];
+	char temp[256],old[256];
 
 	if (!DOS_ValidDrive(drive)) 
 		return 0;
 
 	strcpy(temp, dirname);
 	ToUnix(temp);
+	strcpy(old, DosDrives[drive].cwd);
 	
 	GetUnixDirName(DosDrives[drive].cwd, temp);
 	strcat(DosDrives[drive].cwd,"/");
-#ifdef DEBUG
-	fprintf(stderr,"DOS_SetCWD: %c: %s\n",'A'+drive, DosDrives[drive].cwd);
-#endif
+
+	dprintf_dosfs(stddeb,"DOS_SetCWD: %c: %s\n",'A'+drive,
+                      DosDrives[drive].cwd);
+
+	if (!DOS_ValidDirectory(DosDrives[drive].cwd))
+	{
+		strcpy(DosDrives[drive].cwd, old);
+		return 0;
+	}
 	return 1;
 }
 
@@ -489,12 +489,11 @@
 	GetUnixDirName(temp, dirname);
 	strcat(DosDrives[drive].cwd,"/");
 
-	ToUnix(temp);
+	ToUnix(temp + strlen(DosDrives[drive].cwd));
 	mkdir(temp,0);	
 
-#ifdef DEBUG
-	fprintf(stderr,"DOS_MakeDir: %c:\%s => %s",'A'+drive, dirname, temp);
-#endif
+    	dprintf_dosfs(stddeb,
+		"DOS_MakeDir: %c:\%s => %s",'A'+drive, dirname, temp);
 	return 1;
 }
 
@@ -541,7 +540,8 @@
 		return 0;
 
 	if (statfs(DosDrives[drive].rootdir, &info) < 0) {
-		fprintf(stderr,"dosfs: cannot do statfs(%s)\n",DosDrives[drive].rootdir);
+		fprintf(stderr,"dosfs: cannot do statfs(%s)\n",
+			DosDrives[drive].rootdir);
 		return 0;
 	}
 
@@ -563,7 +563,6 @@
     if (strchr(filename, '\\') != NULL)
     {
 	strncpy(buffer, GetUnixFileName(filename), buflen);
-	ToUnix(buffer);
 	stat( buffer, &filestat);
 	if (S_ISREG(filestat.st_mode))
 	    return buffer;
@@ -577,10 +576,7 @@
 	return buffer;
     }
 
-#ifdef DEBUG
-fprintf(stderr,"FindFile: looking for %s\n", filename);
-#endif
-
+    dprintf_dosfs(stddeb,"FindFile: looking for %s\n", filename);
     rootnamelen = strlen(filename);
     if ((rootname = malloc(rootnamelen + 1)) == NULL)
     	return NULL;
@@ -600,10 +596,7 @@
 	else
 		d = opendir( dirname );
 
-#ifdef DEBUG
-	fprintf(stderr,"in %s\n",dirname);
-#endif
-	
+    	dprintf_dosfs(stddeb,"in %s\n",dirname);
 	if (d != NULL)
 	{
 	    while ((f = readdir(d)) != NULL)
@@ -637,7 +630,6 @@
 			if (S_ISREG(filestat.st_mode)) {
 				closedir(d);
 				free(rootname);
-				ToUnix(buffer);
 				return buffer;
 		    	} else 
 		    		found = 0; 
@@ -693,7 +685,6 @@
 	strcpy(name, GetUnixFileName(WindowsDirectory));
 	strcat(name, "/");
 	strcat(name, "win.ini");
-	ToUnix(name);
 
 	name = realloc(name, strlen(name) + 1);
 	
@@ -704,10 +695,7 @@
 {
 	int x, masklength = strlen(filemask);
 
-#ifdef DEBUG
-	fprintf(stderr, "match: %s, %s\n", filename, filemask);
-#endif
-
+    	dprintf_dosfs(stddeb, "match: %s, %s\n", filename, filemask);
 	for (x = 0; x != masklength ; x++) {
 /*		printf("(%c%c) ", *filename, filemask[x]); 
 */
@@ -763,9 +751,7 @@
 		}
 	}
 
-#ifdef DEBUG
-	fprintf(stderr,"DOS_opendir: %s -> %s\n", unixdirname, temp);
-#endif
+    	dprintf_dosfs(stddeb,"DOS_opendir: %s -> %s\n", unixdirname, temp);
 
 	DosDirs[x].inuse = 1;
 	strcpy(DosDirs[x].unixpath, temp);
@@ -800,7 +786,7 @@
 	strcpy(temp,de->unixpath);
 	strcat(temp,"/");
 	strcat(temp,de->filename);
-	ToUnix(temp);
+	ToUnix(temp + strlen(de->unixpath));
 
 	stat (temp, &st);
 	de->attribute = 0x0;
diff --git a/misc/driver.c b/misc/driver.c
index 436daf7..7e1b9fc 100644
--- a/misc/driver.c
+++ b/misc/driver.c
@@ -12,6 +12,10 @@
 #include "user.h"
 #include "dlls.h"
 #include "driver.h"
+#include "stddebug.h"
+/* #define DEBUG_DRIVER /* */
+/* #undef  DEBUG_DRIVER /* */
+#include "debug.h"
 
 LPDRIVERITEM lpDrvItemList = NULL;
 
@@ -23,16 +27,19 @@
 	LPSTR	file = "SYSTEM.INI";
 	if (GetPrivateProfileString("drivers", NULL, 
 		"", str, sizeof(str), file) < 2) {
-		printf("LoadStartupDrivers // can't find drivers section in '%s'\n", file);
+        	fprintf(stderr,
+		"LoadStartupDrivers // can't find drivers section in '%s'\n", 
+		file);
 		return;
 		}
 	while(strlen(ptr) != 0) {
-		printf("LoadStartupDrivers // str='%s'\n", ptr);
+        	dprintf_driver(stddeb,"LoadStartupDrivers // str='%s'\n", ptr);
 		hDrv = OpenDriver(ptr, "drivers", 0L);
-		printf("LoadStartupDrivers // hDrv=%04X\n", hDrv);
+        	dprintf_driver(stddeb,
+			"LoadStartupDrivers // hDrv=%04X\n", hDrv);
 		ptr += strlen(ptr) + 1;
 		}
-	printf("LoadStartupDrivers // end of list !\n");
+    	dprintf_driver(stddeb,"LoadStartupDrivers // end of list !\n");
 }
 
 /**************************************************************************
@@ -40,12 +47,12 @@
  */
 LRESULT WINAPI SendDriverMessage(HDRVR hDriver, WORD msg, LPARAM lParam1, LPARAM lParam2)
 {
-	printf("SendDriverMessage(%04X, %04X, %08X, %08X);\n",
+	dprintf_driver(stdnimp,"SendDriverMessage(%04X, %04X, %08X, %08X);\n",
 						hDriver, msg, lParam1, lParam2);
 }
 
 /**************************************************************************
- *				OpenDriver				[USER.252]
+ *				OpenDriver		        [USER.252]
  */
 HDRVR OpenDriver(LPSTR lpDriverName, LPSTR lpSectionName, LPARAM lParam)
 {
@@ -53,12 +60,12 @@
 	LPDRIVERITEM	lpnewdrv;
 	LPDRIVERITEM	lpdrv = lpDrvItemList;
 	char			DrvName[128];
-	printf("OpenDriver('%s', '%s', %08X);\n",
+    	dprintf_driver(stddeb,"OpenDriver('%s', '%s', %08X);\n",
 		lpDriverName, lpSectionName, lParam);
 	if (lpSectionName == NULL) lpSectionName = "drivers";
 	GetPrivateProfileString(lpSectionName, lpDriverName,
 		"", DrvName, sizeof(DrvName), "SYSTEM.INI");
-	printf("OpenDriver // DrvName='%s'\n", DrvName);
+    	dprintf_driver(stddeb,"OpenDriver // DrvName='%s'\n", DrvName);
 	if (strlen(DrvName) < 1) return 0;
 	while (lpdrv != NULL) {
 		if (lpdrv->lpNextItem == NULL) break;
@@ -88,7 +95,7 @@
 		lpnewdrv->lpPrevItem = lpdrv;
 		}
 	lpnewdrv->lpDrvProc = NULL;
-	printf("OpenDriver // hDrvr=%04X loaded !\n", hDrvr);
+    	dprintf_driver(stddeb,"OpenDriver // hDrvr=%04X loaded !\n", hDrvr);
 	return hDrvr;
 }
 
@@ -98,7 +105,8 @@
 LRESULT CloseDriver(HDRVR hDrvr, LPARAM lParam1, LPARAM lParam2)
 {
 	LPDRIVERITEM	lpdrv;
-	printf("CloseDriver(%04X, %08X, %08X);\n", hDrvr, lParam1, lParam2);
+    	dprintf_driver(stddeb,
+		"CloseDriver(%04X, %08X, %08X);\n", hDrvr, lParam1, lParam2);
 	lpdrv = (LPDRIVERITEM) GlobalLock(hDrvr);
 	if (lpdrv != NULL && lpdrv->dis.hDriver == hDrvr) {
 		if (lpdrv->lpPrevItem)
@@ -107,7 +115,7 @@
 			((LPDRIVERITEM)lpdrv->lpNextItem)->lpPrevItem = lpdrv->lpPrevItem;
 		GlobalUnlock(hDrvr);
 		GlobalFree(hDrvr);
-		printf("CloseDriver // hDrvr=%04X closed !\n", hDrvr);
+        dprintf_driver(stddeb,"CloseDriver // hDrvr=%04X closed !\n", hDrvr);
 		return TRUE;
 		}
 	return FALSE;
@@ -120,7 +128,7 @@
 {
 	LPDRIVERITEM	lpdrv;
 	HANDLE			hModule = 0;
-	printf("GetDriverModuleHandle(%04X);\n", hDrvr);
+    	dprintf_driver(stddeb,"GetDriverModuleHandle(%04X);\n", hDrvr);
 	lpdrv = (LPDRIVERITEM) GlobalLock(hDrvr);
 	if (lpdrv != NULL) {
 		hModule = lpdrv->dis.hModule;
@@ -169,7 +177,7 @@
 BOOL GetDriverInfo(HDRVR hDrvr, LPDRIVERINFOSTRUCT lpDrvInfo)
 {
 	LPDRIVERITEM	lpdrv;
-	printf("GetDriverInfo(%04X, %08X);\n", hDrvr, lpDrvInfo);
+    	dprintf_driver(stddeb,"GetDriverInfo(%04X, %08X);\n", hDrvr, lpDrvInfo);
 	if (lpDrvInfo == NULL) return FALSE;
 	lpdrv = (LPDRIVERITEM) GlobalLock(hDrvr);
 	if (lpdrv == NULL) return FALSE;
@@ -185,15 +193,16 @@
 {
 	LPDRIVERITEM	lpdrv;
 	HDRVR			hRetDrv = 0;
-	printf("GetNextDriver(%04X, %08X);\n", hDrvr, dwFlags);
+    	dprintf_driver(stddeb,"GetNextDriver(%04X, %08X);\n", hDrvr, dwFlags);
 	if (hDrvr == 0) {
 		if (lpDrvItemList == NULL) {
-			printf("GetNextDriver // drivers list empty !\n");
+            		dprintf_driver(stddeb,
+				"GetNextDriver // drivers list empty !\n");
 			LoadStartupDrivers();
 			if (lpDrvItemList == NULL) return 0;
 			}
-		printf("GetNextDriver // return first %04X !\n", 
-							lpDrvItemList->dis.hDriver);
+        	dprintf_driver(stddeb,"GetNextDriver // return first %04X !\n",
+					lpDrvItemList->dis.hDriver);
 		return lpDrvItemList->dis.hDriver;
 		}
 	lpdrv = (LPDRIVERITEM) GlobalLock(hDrvr);
@@ -208,7 +217,7 @@
 			}
 		GlobalUnlock(hDrvr);
 		}
-	printf("GetNextDriver // return %04X !\n", hRetDrv);
+    	dprintf_driver(stddeb,"GetNextDriver // return %04X !\n", hRetDrv);
 	return hRetDrv;
 }
 
diff --git a/misc/exec.c b/misc/exec.c
index a53550e..31d3570 100644
--- a/misc/exec.c
+++ b/misc/exec.c
@@ -13,6 +13,10 @@
 #include "dlls.h"
 #include "wine.h"
 #include "windows.h"
+#include "stddebug.h"
+/* #define DEBUG_EXEC /* */
+/* #undef  DEBUG_EXEC /* */
+#include "debug.h"
 
 #define HELP_CONTEXT      0x0001
 #define HELP_QUIT         0x0002
@@ -53,40 +57,41 @@
     int cs_reg, ds_reg, ip_reg;
     int rv;
 
-    fprintf(stderr, "Initializing New DLLs\n");
+    dprintf_exec(stddeb, "Initializing New DLLs\n");
 
     /*
      * Initialize libraries
      */
-	printf("InitializeLoadedNewDLLs() before searching hInst=%04X !\n", hInst);
+    dprintf_exec(stddeb,
+	"InitializeLoadedNewDLLs() before searching hInst=%04X !\n", hInst);
 	w = wine_files;
 	while (w && w->hinstance != hInst) w = w->next;
 	if (w == NULL) return;
-	printf("InitializeLoadedNewDLLs() // before InitLoop !\n");
+    dprintf_exec(stddeb,"InitializeLoadedNewDLLs() // before InitLoop !\n");
     for(wpnt = w; wpnt; wpnt = wpnt->next)
     {
 	/* 
 	 * Is this a library? 
 	 */
-	if (wpnt->ne_header->format_flags & 0x8000)
+	if (wpnt->ne->ne_header->format_flags & 0x8000)
 	{
-	    if (!(wpnt->ne_header->format_flags & 0x0001))
+	    if (!(wpnt->ne->ne_header->format_flags & 0x0001))
 	    {
 		/* Not SINGLEDATA */
 		fprintf(stderr, "Library is not marked SINGLEDATA\n");
 		exit(1);
 	    }
 
-	    ds_reg = wpnt->selector_table[wpnt->
+	    ds_reg = wpnt->ne->selector_table[wpnt->ne->
 					  ne_header->auto_data_seg-1].selector;
-	    cs_reg = wpnt->selector_table[wpnt->ne_header->cs-1].selector;
-	    ip_reg = wpnt->ne_header->ip;
+	    cs_reg = wpnt->ne->selector_table[wpnt->ne->ne_header->cs-1].selector;
+	    ip_reg = wpnt->ne->ne_header->ip;
 
-	    fprintf(stderr, "Initializing %s, cs:ip %04x:%04x, ds %04x\n", 
+        dprintf_exec(stddeb, "Initializing %s, cs:ip %04x:%04x, ds %04x\n",
 		    wpnt->name, cs_reg, ip_reg, ds_reg);
 
 	    rv = CallTo16(cs_reg << 16 | ip_reg, ds_reg);
-	    printf ("rv = %x\n", rv);
+        dprintf_exec(stddeb,"rv = %x\n", rv);
 	}
     }
 }
@@ -100,28 +105,29 @@
 	int rv;
 	int segment;
 
-	printf("StartNewTask() before searching hInst=%04X !\n", hInst);
+    	dprintf_exec(stddeb,
+		"StartNewTask() before searching hInst=%04X !\n", hInst);
 	wpnt = wine_files;
 	while (wpnt && wpnt->hinstance != hInst) wpnt = wpnt->next;
 	if (wpnt == NULL) return;
-	printf("StartNewTask() // before FixupSegment !\n");
+    	dprintf_exec(stddeb,"StartNewTask() // before FixupSegment !\n");
 	for(w = wpnt; w; w = w->next)	{
-		for (segment = 0; segment < w->ne_header->n_segment_tab; segment++) {
+		for (segment = 0; segment < w->ne->ne_header->n_segment_tab; segment++) {
 			if (FixupSegment(w, segment) < 0) {
 				myerror("fixup failed.");
 				}
 			}
 		}
-	printf("StartNewTask() before InitializeLoadedNewDLLs !\n");
+	dprintf_exec(stddeb,"StartNewTask() before InitializeLoadedNewDLLs !\n");
 	InitializeLoadedNewDLLs(hInst);
-	printf("StartNewTask() before setup register !\n");
-    ds_reg = (wpnt->selector_table[wpnt->ne_header->auto_data_seg-1].selector);
-    cs_reg = wpnt->selector_table[wpnt->ne_header->cs-1].selector;
-    ip_reg = wpnt->ne_header->ip;
-    ss_reg = wpnt->selector_table[wpnt->ne_header->ss-1].selector;
-    sp_reg = wpnt->ne_header->sp;
+	dprintf_exec(stddeb,"StartNewTask() before setup register !\n");
+    ds_reg = (wpnt->ne->selector_table[wpnt->ne->ne_header->auto_data_seg-1].selector);
+    cs_reg = wpnt->ne->selector_table[wpnt->ne->ne_header->cs-1].selector;
+    ip_reg = wpnt->ne->ne_header->ip;
+    ss_reg = wpnt->ne->selector_table[wpnt->ne->ne_header->ss-1].selector;
+    sp_reg = wpnt->ne->ne_header->sp;
 
-	printf("StartNewTask() before CallToInit16() !\n");
+	dprintf_exec(stddeb,"StartNewTask() before CallToInit16() !\n");
     rv = CallToInit16(cs_reg << 16 | ip_reg, ss_reg << 16 | sp_reg, ds_reg);
     printf ("rv = %x\n", rv);
 
@@ -141,7 +147,7 @@
 {
 	PARAMBLOCK  *pblk = lpParamBlk;
 	WORD 	*lpCmdShow;
-    printf("LoadModule '%s' %08X\n", modulefile, lpParamBlk);
+    	dprintf_exec(stddeb,"LoadModule '%s' %08X\n", modulefile, lpParamBlk);
 	if (lpParamBlk == NULL) return 0;
 	lpCmdShow = (WORD *)pblk->lpCmdShow;
 	return WinExec(pblk->lpCmdLine, lpCmdShow[1]);
@@ -159,7 +165,7 @@
 	LPFNWINMAIN lpfnMain;
 	HINSTANCE	hInst = 0;
 	HANDLE		hTask = 0;
-	printf("WinExec('%s', %04X)\n", lpCmdLine, nCmdShow);
+    	dprintf_exec(stddeb,"WinExec('%s', %04X)\n", lpCmdLine, nCmdShow);
 /*	ArgV[0] = "wine";
 	c = 1; */
 	for (x = x2 = 0; x < strlen(lpCmdLine) + 1; x++) {
@@ -171,36 +177,43 @@
 			}							  
 		}  
 	ArgV[c] = NULL;
-	for (c = 0; ArgV[c] != NULL; c++) printf("--> '%s' \n", ArgV[c]);
+    for (c = 0; ArgV[c] != NULL; c++) 
+	dprintf_exec(stddeb,"--> '%s' \n", ArgV[c]);
 	switch(fork()) {
 		case -1:
-			printf("Can't 'fork' process !\n");
+            fprintf(stderr,"Can't 'fork' process !\n");
 			break;
 		case 0:
 			if ((hInst = LoadImage(ArgV[0], EXE, 1)) == (HINSTANCE) NULL ) {
 				fprintf(stderr, "wine: can't find %s!.\n", ArgV[0]);
-				printf("Child process died !\n");
+                		fprintf(stderr,"Child process died !\n");
 				exit(1);
 				}
 			hTask = CreateNewTask(hInst);
-			printf("WinExec // hTask=%04X hInst=%04X !\n", hTask, hInst);
+            		dprintf_exec(stddeb,
+			"WinExec // hTask=%04X hInst=%04X !\n", hTask, hInst);
 			StartNewTask(hInst); 
 /*
 			lpfnMain = (LPFNWINMAIN)GetProcAddress(hInst, (LPSTR)0L);
-			printf("WineExec() // lpfnMain=%08X\n", (LONG)lpfnMain);
+            		dprintf_exec(stddeb,
+			"WineExec() // lpfnMain=%08X\n", (LONG)lpfnMain);
 			if (lpfnMain != NULL) {
 				(lpfnMain)(hInst, 0, lpCmdLine, nCmdShow);
-				printf("WineExec() // after lpfnMain\n");
+                		dprintf_exec(stddeb,
+					"WineExec() // after lpfnMain\n");
 				}
 */
 /*			hTask = CreateNewTask(0);
-			printf("WinExec // New Task hTask=%04X !\n", hTask);
+            		dprintf_exec(stddeb,
+				"WinExec // New Task hTask=%04X !\n", hTask);
 			execvp(ArgV[0], ArgV); */
 
-			printf("Child process died !\n");
+            		fprintf(stderr,"Child process died !\n");
 			exit(1);
 		default:
-			printf("WinExec (Main process stay alive) hTask=%04X !\n", hTask);
+            		dprintf_exec(stddeb,
+			"WinExec (Main process stay alive) hTask=%04X !\n", 
+			hTask);
 			break;         
 		}
 	for (c = 0; ArgV[c] != NULL; c++) 	free(ArgV[c]);
@@ -213,7 +226,8 @@
  */
 BOOL ExitWindows(DWORD dwReserved, WORD wRetCode)
 {
-	printf("EMPTY STUB !!! ExitWindows(%08X, %04X) !\n", dwReserved, wRetCode);
+    dprintf_exec(stdnimp,"EMPTY STUB !!! ExitWindows(%08X, %04X) !\n", 
+		dwReserved, wRetCode);
 }
 
 
@@ -223,18 +237,19 @@
 BOOL WinHelp(HWND hWnd, LPSTR lpHelpFile, WORD wCommand, DWORD dwData)
 {
 	char	str[256];
-	printf("WinHelp(%s, %u, %lu)\n", lpHelpFile, wCommand, dwData);
+    	dprintf_exec(stddeb,"WinHelp(%s, %u, %lu)\n", 
+		lpHelpFile, wCommand, dwData);
 	switch(wCommand) {
 	case 0:
 	case HELP_HELPONHELP:
 		GetWindowsDirectory(str, sizeof(str));
 		strcat(str, "\\winhelp.exe");
-		printf("'%s'\n", str);
+        dprintf_exec(stddeb,"'%s'\n", str);
 		break;
 	case HELP_INDEX:
 		GetWindowsDirectory(str, sizeof(str));
 		strcat(str, "\\winhelp.exe");
-		printf("'%s'\n", str);
+        dprintf_exec(stddeb,"'%s'\n", str);
 		break;
 	default:
 		return FALSE;
diff --git a/misc/file.c b/misc/file.c
index 0551a6a..5a9d86a 100644
--- a/misc/file.c
+++ b/misc/file.c
@@ -22,8 +22,8 @@
 #include <limits.h>
 #include <unistd.h>
 #include <time.h>
-#include <windows.h>
 #include <sys/stat.h>
+#include <string.h>
 #include "prototypes.h"
 #include "regfunc.h"
 #include "windows.h"
@@ -31,11 +31,13 @@
 #include "msdos.h"
 #include "registers.h"
 #include "options.h"
+#include "stddebug.h"
+/* #define DEBUG_FILE /* */
+/* #undef  DEBUG_FILE /* */
+#include "debug.h"
 
 #define MAX_PATH 255
 
-/* #define DEBUG_FILE /* */
-
 char WindowsDirectory[256], SystemDirectory[256], TempDirectory[256];
 extern char WindowsPath[256];
 
@@ -55,18 +57,13 @@
   int  handle;
   char *UnixFileName;
 
-#ifdef DEBUG_FILE
-  fprintf (stderr, "_lopen: open('%s', %X);\n", lpPathName, iReadWrite);
-#endif
-
+  dprintf_file(stddeb, "_lopen: open('%s', %X);\n", lpPathName, iReadWrite);
   if ((UnixFileName = GetUnixFileName(lpPathName)) == NULL)
   	return HFILE_ERROR;
   iReadWrite &= 0x000F;
   handle =  open (UnixFileName, iReadWrite);
 
-#ifdef DEBUG_FILE
-  fprintf (stderr, "_lopen: open: %s (handle %d)\n", UnixFileName, handle);
-#endif
+  dprintf_file(stddeb, "_lopen: open: %s (handle %d)\n", UnixFileName, handle);
 
   if (handle == -1)
   	return HFILE_ERROR;
@@ -81,10 +78,8 @@
 {
   int result;
 
-#ifdef DEBUG_FILE
-  fprintf(stderr, "_lread: handle %d, buffer = %ld, length = %d\n",
+  dprintf_file(stddeb, "_lread: handle %d, buffer = %ld, length = %d\n",
 	  		hFile, (int) lpBuffer, wBytes);
-#endif
   
   result = read (hFile, lpBuffer, wBytes);
 
@@ -101,13 +96,10 @@
 {
 	int result;
 
-#if 0
-#ifdef DEBUG_FILE
-  fprintf(stderr, "_lwrite: handle %d, buffer = %ld, length = %d\n",
+  dprintf_file(stddeb, "_lwrite: handle %d, buffer = %ld, length = %d\n",
 	  		hFile, (int) lpBuffer, wBytes);
-#endif
-#endif
-	result = write (hFile, lpBuffer, wBytes);
+
+    result = write (hFile, lpBuffer, wBytes);
 
 	if (result == -1)
   		return HFILE_ERROR;
@@ -120,9 +112,7 @@
  ***************************************************************************/
 INT _lclose (INT hFile)
 {
-#ifdef DEBUG_FILE
-	fprintf(stderr, "_lclose: handle %d\n", hFile);
-#endif
+    	dprintf_file(stddeb, "_lclose: handle %d\n", hFile);
 	if (close (hFile))
   		return HFILE_ERROR;
   	else
@@ -135,9 +125,11 @@
 INT OpenFile (LPSTR lpFileName, LPOFSTRUCT ofs, WORD wStyle)
 {
     int		              handle;
+#ifndef PROCEMU
     struct sigcontext_struct  ccontext;
                               /* To make macros like EAX happy */
     struct sigcontext_struct *context=&ccontext; 
+#endif
     char                      filename[MAX_PATH+1];
     int                       action;
     struct stat               s;
@@ -145,9 +137,7 @@
     int                       res;
     int                       verify_time;
   
-  #ifdef DEBUG_FILE
-      fprintf(stderr,"Openfile(%s,<struct>,%d) ",lpFileName,wStyle);
-  #endif
+    dprintf_file(stddeb,"Openfile(%s,<struct>,%d) ",lpFileName,wStyle);
   
     action = wStyle & 0xff00;
   
@@ -196,14 +186,12 @@
 	  if ( (!stat(GetUnixFileName(filename), &s)) && (S_ISREG(s.st_mode)) )
 	    break;
 	  GetWindowsDirectory (filename,MAX_PATH);
-	  if (filename[1] != ':')
-	    strcat(filename,'\\');
+	  if (filename[1] != ':') strcat(filename,"\\");
 	  strcat (filename, lpFileName);
 	  if ( (!stat(GetUnixFileName(filename), &s)) && (S_ISREG(s.st_mode)) )
 	    break;
 	  GetSystemDirectory (filename,MAX_PATH);
-	  if (filename[1] != ':')
-	    strcat(filename,'\\');
+	  if (filename[1] != ':') strcat(filename,"\\");
 	  strcat (filename, lpFileName);
 	  if ( (!stat(GetUnixFileName(filename), &s)) && (S_ISREG(s.st_mode)) )
 	    break;
@@ -263,17 +251,17 @@
    /* Now we are actually going to open the file. According to Microsoft's
        Knowledge Basis, this is done by calling int 21h, ax=3dh. */    
 
-    EAX = 0x00003d00;
-    EAX = (EAX & 0xffffff0f) | (wStyle & 0x0070); /* Handle OF_SHARE_xxx etc. */
-    EAX = (EAX & 0xfffffff0) | (wStyle & 0x0003); /* Handle OF_READ etc. */
+    AX = 0x3d00;
+    AL = (AL & 0x0f) | (wStyle & 0x70); /* Handle OF_SHARE_xxx etc. */
+    AL = (AL & 0xf0) | (wStyle & 0x03); /* Handle OF_READ etc. */
     DS = segment (ofs->szPathName);
-    EDX = (EDX & 0xffff0000) | offset (ofs->szPathName);
+    DX = offset (ofs->szPathName);
   
     OpenExistingFile (context);
 
     if (EFL & 0x00000001)     /* Cflag */
     {
-      ofs->nErrCode = (AX & 0x00ff);
+      ofs->nErrCode = AL;
       return -1;
       }
 
@@ -293,7 +281,7 @@
 #endif
 WORD SetHandleCount (WORD wNumber)
 {
-  printf("SetHandleCount(%d)\n",wNumber);
+  dprintf_file(stddeb,"SetHandleCount(%d)\n",wNumber);
   return((wNumber<OPEN_MAX) ? wNumber : OPEN_MAX);
 }
 
@@ -304,9 +292,8 @@
 {
 	int origin;
 	
-#ifdef DEBUG_FILE
-  fprintf(stderr, "_llseek: handle %d, offset %ld, origin %d\n", hFile, lOffset, nOrigin);
-#endif
+  	dprintf_file(stddeb, "_llseek: handle %d, offset %ld, origin %d\n", 
+		hFile, lOffset, nOrigin);
 
 	switch (nOrigin) {
 		case 1: origin = SEEK_CUR;
@@ -328,10 +315,8 @@
 	int handle;
 	char *UnixFileName;
 
-#ifdef DEBUG_FILE
-	fprintf(stderr, "_lcreat: filename %s, attributes %d\n",lpszFilename, 
-  			fnAttribute);
-#endif
+    	dprintf_file(stddeb, "_lcreat: filename %s, attributes %d\n",
+		lpszFilename, fnAttribute);
 	if ((UnixFileName = GetUnixFileName(lpszFilename)) == NULL)
   		return HFILE_ERROR;
 	handle =  open (UnixFileName, O_CREAT | O_TRUNC | O_WRONLY, 426);
@@ -348,9 +333,7 @@
 UINT GetDriveType(INT drive)
 {
 
-#ifdef DEBUG_FILE
-	fprintf(stderr,"GetDriveType %c:\n",'A'+drive);
-#endif
+    	dprintf_file(stddeb,"GetDriveType %c:\n",'A'+drive);
 
 	if (!DOS_ValidDrive(drive))
 		return DRIVE_DOESNOTEXIST;
@@ -366,9 +349,7 @@
  ***************************************************************************/
 BYTE GetTempDrive(BYTE chDriveLetter)
 {
-#ifdef DEBUG_FILE
-	fprintf(stderr,"GetTempDrive (%d)\n",chDriveLetter);
-#endif
+    dprintf_file(stddeb,"GetTempDrive (%d)\n",chDriveLetter);
 	return('C');
 }
 
@@ -382,9 +363,7 @@
 	else
 		strcpy(lpszSysPath, WindowsDirectory);
 	
-#ifdef DEBUG_FILE
-	fprintf(stderr,"GetWindowsDirectory (%s)\n",lpszSysPath);
-#endif
+    	dprintf_file(stddeb,"GetWindowsDirectory (%s)\n",lpszSysPath);
 
 	ChopOffSlash(lpszSysPath);
 	return(strlen(lpszSysPath));
@@ -399,9 +378,7 @@
 	else
 		strcpy(lpszSysPath, SystemDirectory);
 
-#ifdef DEBUG_FILE
-	fprintf(stderr,"GetSystemDirectory (%s)\n",lpszSysPath);
-#endif
+    	dprintf_file(stddeb,"GetSystemDirectory (%s)\n",lpszSysPath);
 
 	ChopOffSlash(lpszSysPath);
 	return(strlen(lpszSysPath));
@@ -428,10 +405,8 @@
 
 	ToDos(lpszTempFileName);
 
-#ifdef DEBUG_FILE
-	fprintf(stderr,"GetTempFilename: %c %s %d => %s\n",bDriveLetter,
+    	dprintf_file(stddeb,"GetTempFilename: %c %s %d => %s\n",bDriveLetter,
 		lpszPrefixString,uUnique,lpszTempFileName);
-#endif
 	if ((handle = _lcreat (lpszTempFileName, 0x0000)) == -1) {
 		fprintf(stderr,"GetTempFilename: can't create temp file '%s' !\n", lpszTempFileName);
 		}
@@ -446,7 +421,7 @@
  ***************************************************************************/
 WORD SetErrorMode(WORD x)
 {
-	fprintf(stderr,"wine: SetErrorMode %4x (ignored)\n",x);
+    dprintf_file(stdnimp,"wine: SetErrorMode %4x (ignored)\n",x);
 }
 
 /***************************************************************************
diff --git a/misc/keyboard.c b/misc/keyboard.c
index d7c9ce2..a42cb04 100644
--- a/misc/keyboard.c
+++ b/misc/keyboard.c
@@ -3,16 +3,21 @@
 
 #include <stdlib.h>
 #include <stdio.h>
+#include <string.h>
 #include "prototypes.h"
 #include "windows.h"
 #include "keyboard.h"
+#include "stddebug.h"
+/* #define DEBUG_KEYBOARD /* */
+/* #undef  DEBUG_KEYBOARD /* */
+#include "debug.h"
 
 int ToAscii(WORD wVirtKey, WORD wScanCode, LPSTR lpKeyState, 
 	LPVOID lpChar, WORD wFlags) 
 {
 	int i;
 
-	printf("ToAscii (%d,%d)\n",wVirtKey, wScanCode);
+    	dprintf_keyboard(stddeb,"ToAscii (%d,%d)\n",wVirtKey, wScanCode);
 
 	/* FIXME: this is not sufficient but better than returing -1 */
 
@@ -29,7 +34,7 @@
 
 DWORD OemKeyScan(WORD wOemChar)
 {
-	printf("*OemKeyScan (%d)\n",wOemChar);
+    dprintf_keyboard(stddeb,"*OemKeyScan (%d)\n",wOemChar);
 
 	return wOemChar;
 }
@@ -41,7 +46,7 @@
 {
 	int i;
 	
-	printf("VkKeyScan (%d)\n",cChar);
+    	dprintf_keyboard(stddeb,"VkKeyScan (%d)\n",cChar);
 	
 	for (i = 0 ; i != KeyTableSize ; i++) 
 		if (KeyTable[i].ASCII == cChar)
@@ -52,7 +57,7 @@
 
 int GetKeyboardType(int nTypeFlag)
 {
-  printf("GetKeyboardType(%d)\n",nTypeFlag);
+  dprintf_keyboard(stddeb,"GetKeyboardType(%d)\n",nTypeFlag);
   switch(nTypeFlag)
     {
     case 0:      /* Keyboard type */
@@ -104,7 +109,7 @@
 
 int GetKbCodePage(void)
 {
-	printf("GetKbCodePage()\n");
+    	dprintf_keyboard(stddeb,"GetKbCodePage()\n");
 	return 850;
 }
 
@@ -112,7 +117,7 @@
 {
 	int i;
 	
-	printf("GetKeyNameText(%d,<ptr>, %d)\n",lParam,nSize);
+    	dprintf_keyboard(stddeb,"GetKeyNameText(%d,<ptr>, %d)\n",lParam,nSize);
 
 	lParam >>= 16;
 	lParam &= 0xff;
diff --git a/misc/lstr.c b/misc/lstr.c
index 28ec8c4..41174f3 100644
--- a/misc/lstr.c
+++ b/misc/lstr.c
@@ -100,8 +100,8 @@
 		}
 		return strOrChar;
 	} else
-		if (IsCharLower((char) strOrChar))
-			return (LPSTR) ToUpper(strOrChar);
+		if (IsCharLower((int)strOrChar))
+			return (LPSTR) ToUpper((int)strOrChar);
 		else 
 			return (LPSTR) strOrChar;
 }
@@ -133,8 +133,8 @@
 		}
 		return strOrChar;
 	} else
-		if (IsCharUpper((char) strOrChar))
-			return (LPSTR) ToLower(strOrChar);
+		if (IsCharUpper((int)strOrChar))
+			return (LPSTR) ToLower((int)strOrChar);
 		else 
 			return (LPSTR) strOrChar;
 }
diff --git a/misc/main.c b/misc/main.c
index 623c6ed..5c2a1a4 100644
--- a/misc/main.c
+++ b/misc/main.c
@@ -9,6 +9,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <ctype.h>
 #include <locale.h>
 #include <X11/Xlib.h>
 #include <X11/Xresource.h>
@@ -19,6 +20,9 @@
 #include "options.h"
 #include "prototypes.h"
 #include "texts.h"
+#define DEBUG_DEFINE_VARIABLES
+#include "stddebug.h"
+#include "debug.h"
 
 #define WINE_CLASS    "Wine"    /* Class name for resources */
 
@@ -33,8 +37,6 @@
 
 LPENVENTRY	lpEnvList = NULL;
 
-Display * XT_display;  /* To be removed */
-
 Display *display;
 Screen *screen;
 Window rootWindow;
@@ -42,7 +44,6 @@
 int screenDepth = 0;  /* Screen depth to use */
 int desktopX = 0, desktopY = 0;  /* Desktop window position (if any) */
 
-char *ProgramName;		/* Used by resource.c with WINELIB */
 extern ButtonTexts ButtonText;
 
 struct options Options =
@@ -70,7 +71,8 @@
     { "-synchronous",   ".synchronous",     XrmoptionNoArg,  (caddr_t)"on" },
     { "-spy",           ".spy",             XrmoptionSepArg, (caddr_t)NULL },
     { "-debug",         ".debug",           XrmoptionNoArg,  (caddr_t)"on" },
-    { "-relaydbg",      ".relaydbg",        XrmoptionNoArg,  (caddr_t)"on" }
+    { "-relaydbg",      ".relaydbg",        XrmoptionNoArg,  (caddr_t)"on" },
+    { "-debugmsg",      ".debugmsg",        XrmoptionSepArg, (caddr_t)NULL }
 };
 
 #define NB_OPTIONS  (sizeof(optionsTable) / sizeof(optionsTable[0]))
@@ -89,7 +91,8 @@
   "    -synchronous    Turn on synchronous display mode\n" \
   "    -backingstore   Turn on backing store\n" \
   "    -spy file       Turn on message spying to the specified file\n" \
-  "    -relaydbg       Display call relay information\n"
+  "    -relaydbg       Display call relay information\n" \
+  "    -debugmsg name  Turn debugging-messages on or off\n"
 
 
 /***********************************************************************
@@ -232,9 +235,6 @@
 	exit(1);
     }
 
-      /* Use app-defaults */
-    display->db = db;
-
       /* Get all options */
     if (MAIN_GetResource( db, ".iconic", &value ))
 	Options.cmdShow = SW_SHOWMINIMIZED;
@@ -254,6 +254,49 @@
 	screenDepth = atoi( value.addr );
     if (MAIN_GetResource( db, ".desktop", &value))
 	Options.desktopGeometry = value.addr;
+    if (MAIN_GetResource( db, ".debugmsg", &value))
+      {
+#ifndef DEBUG_RUNTIME
+	fprintf(stderr,"%s: Option \"-debugmsg\" not implemented.\n" \
+          "    Recompile with DEBUG_RUNTIME in include/stddebug.h defined.\n",
+	  argv[0]);
+	exit(1);
+#else
+	char *p=(char*)value.addr;
+	if (strlen(p)<3)
+	  goto msgerror;
+	if ((*p!='+')&&(*p!='-'))
+	  goto msgerror;
+	if (!strcasecmp(p+1,"all"))
+	  {
+	    int i;
+	    for (i=0;i<sizeof(debug_msg_enabled)/sizeof(short);i++)
+	      debug_msg_enabled[i]=(*p=='+');
+	  }
+	else
+	  {
+	    int i;
+	    for (i=0;i<sizeof(debug_msg_enabled)/sizeof(short);i++)
+	      if (debug_msg_name && (!strcasecmp(p+1,debug_msg_name[i])))
+		{
+		  debug_msg_enabled[i]=(*p=='+');
+		  break;
+		}
+	    if (i==sizeof(debug_msg_enabled)/sizeof(short))
+	      {
+	      msgerror:
+		fprintf(stderr,"%s: Syntax: -debugmsg +xxx  or -debugmsg -xxx  with xxx one of\n",argv[0]);
+		fprintf(stderr,"%-9s ","all");
+		for(i=0;i<sizeof(debug_msg_enabled)/sizeof(short);i++)
+		  if(debug_msg_name[i])
+		      fprintf(stderr,"%-9s%c",debug_msg_name[i],
+			(((i+2)%8==0)?'\n':' '));
+		fprintf(stderr,"\n\n");
+		exit(1);
+	      }
+	  }
+#endif
+      }
 
 /*    MAIN_GetAllButtonTexts(db); */
  
@@ -371,7 +414,6 @@
     screen       = DefaultScreenOfDisplay( display );
     screenWidth  = WidthOfScreen( screen );
     screenHeight = HeightOfScreen( screen );
-    XT_display   = display;
     if (screenDepth)  /* -depth option specified */
     {
 	depth_list = XListDepths(display,DefaultScreen(display),&depth_count);
@@ -390,7 +432,6 @@
     if (Options.desktopGeometry) MAIN_CreateDesktop( argc, argv );
     else rootWindow = DefaultRootWindow( display );
 
-    ProgramName = argv [0];
     MAIN_SaveSetup();
     DOS_InitFS();
     Comm_Init();
@@ -690,3 +731,11 @@
 	   
 	return FALSE;
 }
+
+/***********************************************************************
+*	FileCDR (KERNEL.130)
+*/
+void FileCDR(FARPROC x)
+{
+	printf("FileCDR(%8x)\n", (int) x);
+}
diff --git a/misc/mcicda.c b/misc/mcicda.c
index 93096f2..213ebff 100644
--- a/misc/mcicda.c
+++ b/misc/mcicda.c
@@ -11,18 +11,21 @@
 
 #ifdef BUILTIN_MMSYSTEM
 
-/*
-#define DEBUG_CDAUDIO
-*/
-
-#include "stdio.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
 #include "win.h"
 #include "user.h"
 #include "driver.h"
 #include "mmsystem.h"
+#include "stddebug.h"
+/* #define DEBUG_CDAUDIO /* */
+/* #undef  DEBUG_CDAUDIO /* */
+#include "debug.h"
 
-#include <fcntl.h>
-#include <sys/ioctl.h>
 #ifdef linux
 #include <linux/soundcard.h>
 #include <linux/cdrom.h>
@@ -84,9 +87,8 @@
 #ifdef linux
 	UINT	wDevID;
 	int		cdrom;
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_mciOpen(%08X, %08X);\n", dwFlags, lpParms);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_mciOpen(%08X, %08X);\n", 
+		dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	wDevID = lpParms->wDeviceID;
 	if (CDADev[wDevID].nUseCount > 0) {
@@ -103,14 +105,14 @@
 		CDADev[wDevID].fShareable = dwFlags & MCI_OPEN_SHAREABLE;
 		}
     if (dwFlags & MCI_OPEN_ELEMENT) {
-		printf("CDAUDIO_mciOpen // MCI_OPEN_ELEMENT !\n");
+        dprintf_cdaudio(stddeb,"CDAUDIO_mciOpen // MCI_OPEN_ELEMENT !\n");
 /*		return MCIERR_NO_ELEMENT_ALLOWED; */
 		}
 	memcpy(&CDADev[wDevID].openParms, lpParms, sizeof(MCI_OPEN_PARMS));
 	CDADev[wDevID].wNotifyDeviceID = lpParms->wDeviceID;
 	CDADev[wDevID].unixdev = open (CDAUDIO_DEV, O_RDONLY, 0);
 	if (CDADev[wDevID].unixdev == -1) {
-		printf("CDAUDIO_mciOpen // can't open '%s' !\n", CDAUDIO_DEV);
+        fprintf(stderr,"CDAUDIO_mciOpen // can't open '%s' !\n", CDAUDIO_DEV);
 		return MCIERR_HARDWARE;
 		}
 	CDADev[wDevID].mode = 0;
@@ -122,11 +124,13 @@
 	CDADev[wDevID].lpdwTrackLen = NULL;
 	CDADev[wDevID].lpdwTrackPos = NULL;
 	if (!CDAUDIO_GetTracksInfo(wDevID)) {
-		printf("CDAUDIO_mciOpen // error reading TracksInfo !\n");
+        fprintf(stderr,"CDAUDIO_mciOpen // error reading TracksInfo !\n");
 /*		return MCIERR_INTERNAL; */
 		}
 	if (dwFlags & MCI_NOTIFY) {
-		printf("CDAUDIO_mciOpen // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
+        	dprintf_cdaudio(stddeb,
+			"CDAUDIO_mciOpen // MCI_NOTIFY_SUCCESSFUL %08X !\n", 
+			lpParms->dwCallback);
 		mciDriverNotify((HWND)LOWORD(lpParms->dwCallback), 
 			CDADev[wDevID].wNotifyDeviceID, MCI_NOTIFY_SUCCESSFUL);
 		}
@@ -142,9 +146,8 @@
 DWORD CDAUDIO_mciClose(UINT wDevID, DWORD dwParam, LPMCI_GENERIC_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_mciClose(%u, %08X, %08X);\n", wDevID, dwParam, lpParms);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_mciClose(%u, %08X, %08X);\n", 
+		wDevID, dwParam, lpParms);
 	if (CDADev[wDevID].lpdwTrackLen != NULL) free(CDADev[wDevID].lpdwTrackLen);
 	if (CDADev[wDevID].lpdwTrackPos != NULL) free(CDADev[wDevID].lpdwTrackPos);
 	close(CDADev[wDevID].unixdev);
@@ -158,12 +161,12 @@
 						LPMCI_GETDEVCAPS_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_mciGetDevCaps(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_mciGetDevCaps(%u, %08X, %08X);\n", 
+		wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	if (dwFlags & MCI_GETDEVCAPS_ITEM) {
-		printf("CDAUDIO_mciGetDevCaps // MCI_GETDEVCAPS_ITEM dwItem=%08X;\n", 
+        	dprintf_cdaudio(stddeb,
+		"CDAUDIO_mciGetDevCaps // MCI_GETDEVCAPS_ITEM dwItem=%08X;\n",
 				lpParms->dwItem);
 		switch(lpParms->dwItem) {
 			case MCI_GETDEVCAPS_CAN_RECORD:
@@ -197,7 +200,9 @@
 				return MCIERR_UNRECOGNIZED_COMMAND;
 			}
 		}
-	printf("CDAUDIO_mciGetDevCaps // lpParms->dwReturn=%08X;\n", lpParms->dwReturn);
+    	dprintf_cdaudio(stddeb,
+		"CDAUDIO_mciGetDevCaps // lpParms->dwReturn=%08X;\n", 
+		lpParms->dwReturn);
  	return 0;
 #else
 	return MCIERR_INTERNAL;
@@ -210,9 +215,8 @@
 DWORD CDAUDIO_mciInfo(UINT wDevID, DWORD dwFlags, LPMCI_INFO_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_mciInfo(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_mciInfo(%u, %08X, %08X);\n", 
+		wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	lpParms->lpstrReturn = NULL;
 	switch(dwFlags) {
@@ -238,15 +242,14 @@
 DWORD CDAUDIO_mciStatus(UINT wDevID, DWORD dwFlags, LPMCI_STATUS_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_mciStatus(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_mciStatus(%u, %08X, %08X);\n", 
+		wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	if (CDADev[wDevID].unixdev == 0) return MMSYSERR_NOTENABLED;
 	if (dwFlags & MCI_NOTIFY) {
-#ifdef DEBUG_CDAUDIO
-		printf("CDAUDIO_mciStatus // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
-#endif
+        	dprintf_cdaudio(stddeb,
+			"CDAUDIO_mciStatus // MCI_NOTIFY_SUCCESSFUL %08X !\n", 
+			lpParms->dwCallback);
 		mciDriverNotify((HWND)LOWORD(lpParms->dwCallback), 
 			CDADev[wDevID].wNotifyDeviceID, MCI_NOTIFY_SUCCESSFUL);
 		}
@@ -255,19 +258,17 @@
 			case MCI_STATUS_CURRENT_TRACK:
 				if (!CDAUDIO_GetCDStatus(wDevID)) return MCIERR_INTERNAL;
 				lpParms->dwReturn = CDADev[wDevID].nCurTrack;
-#ifdef DEBUG_CDAUDIO
-				printf("CDAUDIO_mciStatus // CURRENT_TRACK=%u!\n", lpParms->dwReturn);
-#endif
+                		dprintf_cdaudio(stddeb,"CDAUDIO_mciStatus // CURRENT_TRACK=%u!\n", lpParms->dwReturn);
 			 	return 0;
 			case MCI_STATUS_LENGTH:
 				if (CDADev[wDevID].nTracks == 0) {
 					if (!CDAUDIO_GetTracksInfo(wDevID)) {
-						printf("CDAUDIO_mciStatus // error reading TracksInfo !\n");
+                        			fprintf(stderr,"CDAUDIO_mciStatus // error reading TracksInfo !\n");
 						return MCIERR_INTERNAL;
 						}
 					}
 				if (dwFlags & MCI_TRACK) {
-					printf("CDAUDIO_mciStatus // MCI_TRACK #%u LENGTH=??? !\n", 
+                    			dprintf_cdaudio(stddeb,"CDAUDIO_mciStatus // MCI_TRACK #%u LENGTH=??? !\n",
 														lpParms->dwTrack);
 					if (lpParms->dwTrack > CDADev[wDevID].nTracks)
 						return MCIERR_OUTOFRANGE;
@@ -277,26 +278,24 @@
 					lpParms->dwReturn = CDADev[wDevID].dwTotalLen;
 				lpParms->dwReturn = CDAUDIO_CalcTime(wDevID, 
 					CDADev[wDevID].dwTimeFormat, lpParms->dwReturn);
-				printf("CDAUDIO_mciStatus // LENGTH=%u !\n", lpParms->dwReturn);
+                		dprintf_cdaudio(stddeb,"CDAUDIO_mciStatus // LENGTH=%u !\n", lpParms->dwReturn);
 			 	return 0;
 			case MCI_STATUS_MODE:
 				if (!CDAUDIO_GetCDStatus(wDevID)) return MCIERR_INTERNAL;
 				lpParms->dwReturn = CDADev[wDevID].mode;
-#ifdef DEBUG_CDAUDIO
-				printf("CDAUDIO_mciStatus // MCI_STATUS_MODE=%08X !\n", 
+                		dprintf_cdaudio(stddeb,"CDAUDIO_mciStatus // MCI_STATUS_MODE=%08X !\n",
 												lpParms->dwReturn);
-#endif
 			 	return 0;
 			case MCI_STATUS_MEDIA_PRESENT:
 				lpParms->dwReturn = (CDADev[wDevID].nTracks > 0) ? TRUE : FALSE;
 				if (lpParms->dwReturn == FALSE)
-					printf("CDAUDIO_mciStatus // MEDIA_NOT_PRESENT !\n");
+                    			fprintf(stderr,"CDAUDIO_mciStatus // MEDIA_NOT_PRESENT !\n");
 				else
-					printf("CDAUDIO_mciStatus // MCI_STATUS_MEDIA_PRESENT !\n");
+                    			dprintf_cdaudio(stddeb,"CDAUDIO_mciStatus // MCI_STATUS_MEDIA_PRESENT !\n");
 			 	return 0;
 			case MCI_STATUS_NUMBER_OF_TRACKS:
 				lpParms->dwReturn = CDAUDIO_GetNumberOfTracks(wDevID);
-				printf("CDAUDIO_mciStatus // MCI_STATUS_NUMBER_OF_TRACKS = %u !\n",
+                		dprintf_cdaudio(stddeb,"CDAUDIO_mciStatus // MCI_STATUS_NUMBER_OF_TRACKS = %u !\n",
 													lpParms->dwReturn);
 				if (lpParms->dwReturn == (WORD)-1) return MCIERR_INTERNAL;
 			 	return 0;
@@ -305,39 +304,33 @@
 				lpParms->dwReturn = CDADev[wDevID].dwCurFrame;
 				if (dwFlags & MCI_STATUS_START) {
 					lpParms->dwReturn = CDADev[wDevID].dwFirstOffset;
-#ifdef DEBUG_CDAUDIO
-					printf("CDAUDIO_mciStatus // get MCI_STATUS_START !\n");
-#endif
+                    			dprintf_cdaudio(stddeb,"CDAUDIO_mciStatus // get MCI_STATUS_START !\n");
 					}
 				if (dwFlags & MCI_TRACK) {
 					if (lpParms->dwTrack > CDADev[wDevID].nTracks)
 						return MCIERR_OUTOFRANGE;
 					lpParms->dwReturn = CDADev[wDevID].lpdwTrackPos[lpParms->dwTrack - 1];
-#ifdef DEBUG_CDAUDIO
-					printf("CDAUDIO_mciStatus // get MCI_TRACK #%u !\n", lpParms->dwTrack);
-#endif
+                    			dprintf_cdaudio(stddeb,"CDAUDIO_mciStatus // get MCI_TRACK #%u !\n", lpParms->dwTrack);
 					}
 				lpParms->dwReturn = CDAUDIO_CalcTime(wDevID, 
 					CDADev[wDevID].dwTimeFormat, lpParms->dwReturn);
-#ifdef DEBUG_CDAUDIO
-				printf("CDAUDIO_mciStatus // MCI_STATUS_POSITION=%08X !\n",
+                			dprintf_cdaudio(stddeb,"CDAUDIO_mciStatus // MCI_STATUS_POSITION=%08X !\n",
 														lpParms->dwReturn);
-#endif
 			 	return 0;
 			case MCI_STATUS_READY:
-				printf("CDAUDIO_mciStatus // MCI_STATUS_READY !\n");
+                		dprintf_cdaudio(stddeb,"CDAUDIO_mciStatus // MCI_STATUS_READY !\n");
 				lpParms->dwReturn = TRUE;
 			 	return 0;
 			case MCI_STATUS_TIME_FORMAT:
-				printf("CDAUDIO_mciStatus // MCI_STATUS_TIME_FORMAT !\n");
+                		dprintf_cdaudio(stddeb,"CDAUDIO_mciStatus // MCI_STATUS_TIME_FORMAT !\n");
 				lpParms->dwReturn = MCI_FORMAT_MILLISECONDS;
 			 	return 0;
 			default:
-				printf("CDAUDIO_mciStatus // unknowm command %04X !\n", lpParms->dwItem);
+                		fprintf(stderr,"CDAUDIO_mciStatus // unknown command %04X !\n", lpParms->dwItem);
 				return MCIERR_UNRECOGNIZED_COMMAND;
 			}
 		}
-	printf("CDAUDIO_mciStatus // not MCI_STATUS_ITEM !\n");
+    fprintf(stderr,"CDAUDIO_mciStatus // not MCI_STATUS_ITEM !\n");
  	return 0;
 #else
 	return MMSYSERR_NOTENABLED;
@@ -356,16 +349,15 @@
 	UINT	wMinutes;
 	UINT	wSeconds;
 	UINT	wFrames;
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_CalcTime(%u, %08X, %lu);\n", wDevID, dwFormatType, dwFrame);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_CalcTime(%u, %08X, %lu);\n", 
+		wDevID, dwFormatType, dwFrame);
 TryAGAIN:
 	switch (dwFormatType) {
 		case MCI_FORMAT_MILLISECONDS:
 			dwTime = dwFrame / CDFRAMES_PERSEC * 1000;
-#ifdef DEBUG_CDAUDIO
-			printf("CDAUDIO_CalcTime // MILLISECONDS %u\n", dwTime);
-#endif
+            		dprintf_cdaudio(stddeb,
+				"CDAUDIO_CalcTime // MILLISECONDS %u\n", 
+				dwTime);
 			break;
 		case MCI_FORMAT_MSF:
 			wMinutes = dwFrame / CDFRAMES_PERMIN;
@@ -373,10 +365,8 @@
 			wFrames = dwFrame - CDFRAMES_PERMIN * wMinutes - 
 								CDFRAMES_PERSEC * wSeconds;
 			dwTime = MCI_MAKE_MSF(wMinutes, wSeconds, wFrames);
-#ifdef DEBUG_CDAUDIO
-			printf("CDAUDIO_CalcTime // MSF %02u:%02u:%02u -> dwTime=%u\n", 
+            		dprintf_cdaudio(stddeb,"CDAUDIO_CalcTime // MSF %02u:%02u:%02u -> dwTime=%u\n",
 								wMinutes, wSeconds, wFrames, dwTime);
-#endif
 			break;
 		case MCI_FORMAT_TMSF:
 			for (wTrack = 0; wTrack < CDADev[wDevID].nTracks; wTrack++) {
@@ -390,10 +380,9 @@
 			wFrames = dwFrame - CDFRAMES_PERMIN * wMinutes - 
 								CDFRAMES_PERSEC * wSeconds;
 			dwTime = MCI_MAKE_TMSF(wTrack, wMinutes, wSeconds, wFrames);
-#ifdef DEBUG_CDAUDIO
-			printf("CDAUDIO_CalcTime // %02u-%02u:%02u:%02u\n", 
+            		dprintf_cdaudio(stddeb,
+				"CDAUDIO_CalcTime // %02u-%02u:%02u:%02u\n",
 					wTrack, wMinutes, wSeconds, wFrames);
-#endif
 			break;
 		default:
 			/* unknown format ! force TMSF ! ... */
@@ -413,36 +402,34 @@
 	DWORD	dwFrame = 0;
 #ifdef linux
 	UINT	wTrack;
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_CalcFrame(%u, %08X, %lu);\n", wDevID, dwFormatType, dwTime);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_CalcFrame(%u, %08X, %lu);\n", 
+		wDevID, dwFormatType, dwTime);
 TryAGAIN:
 	switch (dwFormatType) {
 		case MCI_FORMAT_MILLISECONDS:
 			dwFrame = dwTime * CDFRAMES_PERSEC / 1000;
-#ifdef DEBUG_CDAUDIO
-			printf("CDAUDIO_CalcFrame // MILLISECONDS %u\n", dwFrame);
-#endif
+            		dprintf_cdaudio(stddeb,
+				"CDAUDIO_CalcFrame // MILLISECONDS %u\n", 
+				dwFrame);
 			break;
 		case MCI_FORMAT_MSF:
-#ifdef DEBUG_CDAUDIO
-			printf("CDAUDIO_CalcFrame // MSF %02u:%02u:%02u\n", 
+            		dprintf_cdaudio(stddeb,
+				"CDAUDIO_CalcFrame // MSF %02u:%02u:%02u\n",
 				MCI_MSF_MINUTE(dwTime), MCI_MSF_SECOND(dwTime), 
 				MCI_MSF_FRAME(dwTime));
-#endif
 			dwFrame += CDFRAMES_PERMIN * MCI_MSF_MINUTE(dwTime);
 			dwFrame += CDFRAMES_PERSEC * MCI_MSF_SECOND(dwTime);
 			dwFrame += MCI_MSF_FRAME(dwTime);
 			break;
 		case MCI_FORMAT_TMSF:
 			wTrack = MCI_TMSF_TRACK(dwTime);
-#ifdef DEBUG_CDAUDIO
-			printf("CDAUDIO_CalcFrame // TMSF %02u-%02u:%02u:%02u\n", 
+            		dprintf_cdaudio(stddeb,
+			"CDAUDIO_CalcFrame // TMSF %02u-%02u:%02u:%02u\n",
 					MCI_TMSF_TRACK(dwTime), MCI_TMSF_MINUTE(dwTime), 
 					MCI_TMSF_SECOND(dwTime), MCI_TMSF_FRAME(dwTime));
-			printf("CDAUDIO_CalcFrame // TMSF trackpos[%u]=%u\n",
+            		dprintf_cdaudio(stddeb,
+				"CDAUDIO_CalcFrame // TMSF trackpos[%u]=%u\n",
 				wTrack, CDADev[wDevID].lpdwTrackPos[wTrack - 1]);
-#endif
 			dwFrame = CDADev[wDevID].lpdwTrackPos[wTrack - 1];
 			dwFrame += CDFRAMES_PERMIN * MCI_TMSF_MINUTE(dwTime);
 			dwFrame += CDFRAMES_PERSEC * MCI_TMSF_SECOND(dwTime);
@@ -467,7 +454,9 @@
 	struct cdrom_tochdr	hdr;
 	if (CDADev[wDevID].nTracks == 0) {
 		if (ioctl(CDADev[wDevID].unixdev, CDROMREADTOCHDR, &hdr)) {
-			printf("GetNumberOfTracks(%u) // Error occured !\n", wDevID);
+            		fprintf(stderr,
+				"GetNumberOfTracks(%u) // Error occured !\n", 
+				wDevID);
 			return (WORD)-1;
 			}
 		CDADev[wDevID].nTracks = hdr.cdth_trk1;
@@ -491,7 +480,8 @@
 	if (CDADev[wDevID].nTracks == 0) {
 		if (CDAUDIO_GetNumberOfTracks(wDevID) == (WORD)-1) return FALSE;
 		}
-	printf("CDAUDIO_GetTracksInfo // nTracks=%u\n", CDADev[wDevID].nTracks);
+    	dprintf_cdaudio(stddeb,"CDAUDIO_GetTracksInfo // nTracks=%u\n", 
+		CDADev[wDevID].nTracks);
 	if (CDADev[wDevID].lpdwTrackLen != NULL) 
 		free(CDADev[wDevID].lpdwTrackLen);
 	CDADev[wDevID].lpdwTrackLen = (LPDWORD)malloc(
@@ -502,7 +492,8 @@
 		(CDADev[wDevID].nTracks + 1) * sizeof(DWORD));
 	if (CDADev[wDevID].lpdwTrackLen == NULL ||
 		CDADev[wDevID].lpdwTrackPos == NULL) {
-		printf("CDAUDIO_GetTracksInfo // error allocating track table !\n");
+        		fprintf(stderr,
+				"CDAUDIO_GetTracksInfo // error allocating track table !\n");
 		return FALSE;
 		}
 	memset(CDADev[wDevID].lpdwTrackLen, 0, 
@@ -516,7 +507,8 @@
 			entry.cdte_track = i + 1;
 		entry.cdte_format = CDROM_MSF;
 		if (ioctl(CDADev[wDevID].unixdev, CDROMREADTOCENTRY, &entry)) {
-			printf("CDAUDIO_GetTracksInfo // error read entry\n");
+            		fprintf(stderr,
+				"CDAUDIO_GetTracksInfo // error read entry\n");
 			return FALSE;
 			}
 		start = CDFRAMES_PERSEC * (SECONDS_PERMIN * 
@@ -524,7 +516,9 @@
 			entry.cdte_addr.msf.frame;
 		if (i == 0) {
 			CDADev[wDevID].dwFirstOffset = last_start = start;
-			printf("CDAUDIO_GetTracksInfo // dwFirstOffset=%u\n", start);
+            		dprintf_cdaudio(stddeb,
+				"CDAUDIO_GetTracksInfo // dwFirstOffset=%u\n", 
+				start);
 			}
 		else {
 			length = start - last_start;
@@ -533,12 +527,14 @@
 			total_length += length;
 			CDADev[wDevID].lpdwTrackLen[i - 1] = length;
 			CDADev[wDevID].lpdwTrackPos[i - 1] = start;
-			printf("CDAUDIO_GetTracksInfo // track #%u start=%u len=%u\n", 
-													i, start, length);
+            		dprintf_cdaudio(stddeb,
+			"CDAUDIO_GetTracksInfo // track #%u start=%u len=%u\n",
+				i, start, length);
 			}
 		}
 	CDADev[wDevID].dwTotalLen = total_length;
-	printf("CDAUDIO_GetTracksInfo // total_len=%u\n", total_length);
+    	dprintf_cdaudio(stddeb,"CDAUDIO_GetTracksInfo // total_len=%u\n", 
+		total_length);
 	fflush(stdout);
 	return TRUE;
 #else
@@ -556,36 +552,28 @@
 	int		oldmode = CDADev[wDevID].mode;
 	CDADev[wDevID].sc.cdsc_format = CDROM_MSF;
 	if (ioctl(CDADev[wDevID].unixdev, CDROMSUBCHNL, &CDADev[wDevID].sc)) {
-#ifdef DEBUG_CDAUDIO
-		printf("CDAUDIO_GetCDStatus // opened or no_media !\n");
-#endif
+        	fprintf(stderr,"CDAUDIO_GetCDStatus // opened or no_media !\n");
 		CDADev[wDevID].mode = MCI_MODE_NOT_READY;
 		return TRUE;
 		}
 	switch (CDADev[wDevID].sc.cdsc_audiostatus) {
 		case CDROM_AUDIO_INVALID:
-			printf("CDAUDIO_GetCDStatus // device doesn't support status !\n");
+            		fprintf(stderr,"CDAUDIO_GetCDStatus // device doesn't support status !\n");
 			return FALSE;
 		case CDROM_AUDIO_NO_STATUS: 
 			CDADev[wDevID].mode = MCI_MODE_STOP;
-#ifdef DEBUG_CDAUDIO
-			printf("CDAUDIO_GetCDStatus // MCI_MODE_STOP !\n");
-#endif
+            		dprintf_cdaudio(stddeb,"CDAUDIO_GetCDStatus // MCI_MODE_STOP !\n");
 			break;
 		case CDROM_AUDIO_PLAY: 
 			CDADev[wDevID].mode = MCI_MODE_PLAY;
-#ifdef DEBUG_CDAUDIO
-			printf("CDAUDIO_GetCDStatus // MCI_MODE_PLAY !\n");
-#endif
+            		dprintf_cdaudio(stddeb,"CDAUDIO_GetCDStatus // MCI_MODE_PLAY !\n");
 			break;
 		case CDROM_AUDIO_PAUSED:
 			CDADev[wDevID].mode = MCI_MODE_PAUSE;
-#ifdef DEBUG_CDAUDIO
-			printf("CDAUDIO_GetCDStatus // MCI_MODE_PAUSE !\n");
-#endif
+            		dprintf_cdaudio(stddeb,"CDAUDIO_GetCDStatus // MCI_MODE_PAUSE !\n");
 			break;
 		default:
-			printf("CDAUDIO_GetCDStatus // status=%02X !\n", 
+            		dprintf_cdaudio(stddeb,"CDAUDIO_GetCDStatus // status=%02X !\n",
 					CDADev[wDevID].sc.cdsc_audiostatus);
 		}
 	CDADev[wDevID].nCurTrack = CDADev[wDevID].sc.cdsc_trk;
@@ -593,16 +581,14 @@
 		CDFRAMES_PERMIN * CDADev[wDevID].sc.cdsc_absaddr.msf.minute +
 		CDFRAMES_PERSEC * CDADev[wDevID].sc.cdsc_absaddr.msf.second +
 		CDADev[wDevID].sc.cdsc_absaddr.msf.frame;
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_GetCDStatus // %02u-%02u:%02u:%02u \n", 
+    	dprintf_cdaudio(stddeb,"CDAUDIO_GetCDStatus // %02u-%02u:%02u:%02u \n",
 		CDADev[wDevID].sc.cdsc_trk,
 		CDADev[wDevID].sc.cdsc_absaddr.msf.minute,
 		CDADev[wDevID].sc.cdsc_absaddr.msf.second,
 		CDADev[wDevID].sc.cdsc_absaddr.msf.frame);
-#endif
 	if (oldmode != CDADev[wDevID].mode && oldmode == MCI_MODE_OPEN) {
 		if (!CDAUDIO_GetTracksInfo(wDevID)) {
-			printf("CDAUDIO_GetCDStatus // error updating TracksInfo !\n");
+            fprintf(stderr,"CDAUDIO_GetCDStatus // error updating TracksInfo !\n");
 			return MCIERR_INTERNAL;
 			}
 		}
@@ -620,9 +606,8 @@
 #ifdef linux
 	int 	start, end;
 	struct 	cdrom_msf	msf;
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_mciPlay(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_mciPlay(%u, %08X, %08X);\n", 
+		wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	if (CDADev[wDevID].unixdev == 0) return MMSYSERR_NOTENABLED;
 	start = 0; 		end = CDADev[wDevID].dwTotalLen;
@@ -630,18 +615,15 @@
 	if (dwFlags & MCI_FROM) {
 		start = CDAUDIO_CalcFrame(wDevID, 
 			CDADev[wDevID].dwTimeFormat, lpParms->dwFrom); 
-#ifdef DEBUG_CDAUDIO
-		printf("CDAUDIO_mciPlay // MCI_FROM=%08X -> %u \n", 
-								lpParms->dwFrom, start);
-#endif
+        dprintf_cdaudio(stddeb,"CDAUDIO_mciPlay // MCI_FROM=%08X -> %u \n",
+				lpParms->dwFrom, start);
 		}
 	if (dwFlags & MCI_TO) {
 		end = CDAUDIO_CalcFrame(wDevID, 
 			CDADev[wDevID].dwTimeFormat, lpParms->dwTo);
-#ifdef DEBUG_CDAUDIO
-		printf("CDAUDIO_mciPlay // MCI_TO=%08X -> %u \n", 
-								lpParms->dwTo, end);
-#endif
+        	dprintf_cdaudio(stddeb,
+			"CDAUDIO_mciPlay // MCI_TO=%08X -> %u \n",
+			lpParms->dwTo, end);
 		}
 	start += CDADev[wDevID].dwFirstOffset;	
 	end += CDADev[wDevID].dwFirstOffset;
@@ -652,21 +634,21 @@
 	msf.cdmsf_sec1 = (end % CDFRAMES_PERMIN) / CDFRAMES_PERSEC;
 	msf.cdmsf_frame1 = end % CDFRAMES_PERSEC;
 	if (ioctl(CDADev[wDevID].unixdev, CDROMSTART)) {
-		printf("CDAUDIO_mciPlay // motor doesn't start !\n");
+        	fprintf(stderr,"CDAUDIO_mciPlay // motor doesn't start !\n");
 		return MCIERR_HARDWARE;
 		}
 	if (ioctl(CDADev[wDevID].unixdev, CDROMPLAYMSF, &msf)) {
-		printf("CDAUDIO_mciPlay // device doesn't play !\n");
+        	fprintf(stderr,"CDAUDIO_mciPlay // device doesn't play !\n");
 		return MCIERR_HARDWARE;
 		}
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_mciPlay // msf = %d:%d:%d %d:%d:%d\n",
+    	dprintf_cdaudio(stddeb,"CDAUDIO_mciPlay // msf = %d:%d:%d %d:%d:%d\n",
 		msf.cdmsf_min0, msf.cdmsf_sec0, msf.cdmsf_frame0,
 		msf.cdmsf_min1, msf.cdmsf_sec1, msf.cdmsf_frame1);
-#endif
 	CDADev[wDevID].mode = MCI_MODE_PLAY;
 	if (dwFlags & MCI_NOTIFY) {
-		printf("CDAUDIO_mciPlay // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
+        	dprintf_cdaudio(stddeb,
+			"CDAUDIO_mciPlay // MCI_NOTIFY_SUCCESSFUL %08X !\n", 
+			lpParms->dwCallback);
 		mciDriverNotify((HWND)LOWORD(lpParms->dwCallback), 
 			CDADev[wDevID].wNotifyDeviceID, MCI_NOTIFY_SUCCESSFUL);
 		}
@@ -682,14 +664,15 @@
 DWORD CDAUDIO_mciStop(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_mciStop(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_mciStop(%u, %08X, %08X);\n", 
+		wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	if (ioctl(CDADev[wDevID].unixdev, CDROMSTOP)) return MCIERR_HARDWARE;
 	CDADev[wDevID].mode = MCI_MODE_STOP;
 	if (dwFlags & MCI_NOTIFY) {
-		printf("CDAUDIO_mciStop // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
+        	dprintf_cdaudio(stddeb,
+			"CDAUDIO_mciStop // MCI_NOTIFY_SUCCESSFUL %08X !\n", 
+			lpParms->dwCallback);
 		mciDriverNotify((HWND)LOWORD(lpParms->dwCallback), 
 			CDADev[wDevID].wNotifyDeviceID, MCI_NOTIFY_SUCCESSFUL);
 		}
@@ -705,14 +688,15 @@
 DWORD CDAUDIO_mciPause(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_mciPause(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_mciPause(%u, %08X, %08X);\n", 
+		wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	if (ioctl(CDADev[wDevID].unixdev, CDROMPAUSE)) return MCIERR_HARDWARE;
 	CDADev[wDevID].mode = MCI_MODE_PAUSE;
 	if (dwFlags & MCI_NOTIFY) {
-		printf("CDAUDIO_mciPause // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
+        dprintf_cdaudio(stddeb,
+		"CDAUDIO_mciPause // MCI_NOTIFY_SUCCESSFUL %08X !\n", 
+		lpParms->dwCallback);
 		mciDriverNotify((HWND)LOWORD(lpParms->dwCallback), 
 			CDADev[wDevID].wNotifyDeviceID, MCI_NOTIFY_SUCCESSFUL);
 		}
@@ -728,14 +712,15 @@
 DWORD CDAUDIO_mciResume(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_mciResume(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_mciResume(%u, %08X, %08X);\n", 
+		wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	if (ioctl(CDADev[wDevID].unixdev, CDROMRESUME)) return MCIERR_HARDWARE;
 	CDADev[wDevID].mode = MCI_MODE_STOP;
 	if (dwFlags & MCI_NOTIFY) {
-		printf("CDAUDIO_mciResume // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
+        	dprintf_cdaudio(stddeb,
+			"CDAUDIO_mciResume // MCI_NOTIFY_SUCCESSFUL %08X !\n", 
+			lpParms->dwCallback);
 		mciDriverNotify((HWND)LOWORD(lpParms->dwCallback), 
 			CDADev[wDevID].wNotifyDeviceID, MCI_NOTIFY_SUCCESSFUL);
 		}
@@ -753,9 +738,8 @@
 #ifdef linux
 	DWORD	dwRet;
 	MCI_PLAY_PARMS PlayParms;
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_mciSeek(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_mciSeek(%u, %08X, %08X);\n", 
+		wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 	if (ioctl(CDADev[wDevID].unixdev, CDROMRESUME)) return MCIERR_HARDWARE;
 	CDADev[wDevID].mode = MCI_MODE_SEEK;
@@ -774,7 +758,9 @@
 	if (dwRet != 0) return dwRet;
 	dwRet = CDAUDIO_mciStop(wDevID, MCI_WAIT, (LPMCI_GENERIC_PARMS)&PlayParms);
 	if (dwFlags & MCI_NOTIFY) {
-		printf("CDAUDIO_mciSeek // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
+        	dprintf_cdaudio(stddeb,
+			"CDAUDIO_mciSeek // MCI_NOTIFY_SUCCESSFUL %08X !\n", 
+			lpParms->dwCallback);
 		mciDriverNotify((HWND)LOWORD(lpParms->dwCallback), 
 			CDADev[wDevID].wNotifyDeviceID, MCI_NOTIFY_SUCCESSFUL);
 		}
@@ -791,9 +777,8 @@
 DWORD CDAUDIO_mciSet(UINT wDevID, DWORD dwFlags, LPMCI_SET_PARMS lpParms)
 {
 #ifdef linux
-#ifdef DEBUG_CDAUDIO
-	printf("CDAUDIO_mciSet(%u, %08X, %08X);\n", wDevID, dwFlags, lpParms);
-#endif
+    	dprintf_cdaudio(stddeb,"CDAUDIO_mciSet(%u, %08X, %08X);\n", 
+		wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 /*
 	printf("CDAUDIO_mciSet // dwTimeFormat=%08X\n", lpParms->dwTimeFormat);
@@ -802,33 +787,30 @@
 	if (dwFlags & MCI_SET_TIME_FORMAT) {
 		switch (lpParms->dwTimeFormat) {
 			case MCI_FORMAT_MILLISECONDS:
-#ifdef DEBUG_CDAUDIO
-				printf("CDAUDIO_mciSet // MCI_FORMAT_MILLISECONDS !\n");
-#endif
+                		dprintf_cdaudio(stddeb,
+				"CDAUDIO_mciSet // MCI_FORMAT_MILLISECONDS !\n");
 				break;
 			case MCI_FORMAT_MSF:
-#ifdef DEBUG_CDAUDIO
-				printf("CDAUDIO_mciSet // MCI_FORMAT_MSF !\n");
-#endif
+                		dprintf_cdaudio(stddeb,"CDAUDIO_mciSet // MCI_FORMAT_MSF !\n");
 				break;
 			case MCI_FORMAT_TMSF:
-#ifdef DEBUG_CDAUDIO
-				printf("CDAUDIO_mciSet // MCI_FORMAT_TMSF !\n");
-#endif
+                		dprintf_cdaudio(stddeb,"CDAUDIO_mciSet // MCI_FORMAT_TMSF !\n");
 				break;
 			default:
-				printf("CDAUDIO_mciSet // bad time format !\n");
+                		fprintf(stderr,"CDAUDIO_mciSet // bad time format !\n");
 				return MCIERR_BAD_TIME_FORMAT;
 			}
 		CDADev[wDevID].dwTimeFormat = lpParms->dwTimeFormat;
 		}
 	if (dwFlags & MCI_SET_DOOR_OPEN) {
-		printf("CDAUDIO_mciSet // MCI_SET_DOOR_OPEN !\n");
+        	dprintf_cdaudio(stddeb,
+			"CDAUDIO_mciSet // MCI_SET_DOOR_OPEN !\n");
 		if (ioctl(CDADev[wDevID].unixdev, CDROMEJECT)) return MCIERR_HARDWARE;
 		CDADev[wDevID].nTracks = 0;
 		}
 	if (dwFlags & MCI_SET_DOOR_CLOSED) {
-		printf("CDAUDIO_mciSet // MCI_SET_DOOR_CLOSED !\n");
+        	dprintf_cdaudio(stddeb,
+			"CDAUDIO_mciSet // MCI_SET_DOOR_CLOSED !\n");
 		if (ioctl(CDADev[wDevID].unixdev, CDROMEJECT)) return MCIERR_HARDWARE;
 		CDADev[wDevID].nTracks = 0;
 		}
@@ -836,7 +818,9 @@
 	if (dwFlags & MCI_SET_ON) return MCIERR_UNSUPPORTED_FUNCTION;
 	if (dwFlags & MCI_SET_OFF) return MCIERR_UNSUPPORTED_FUNCTION;
 	if (dwFlags & MCI_NOTIFY) {
-		printf("CDAUDIO_mciSet // MCI_NOTIFY_SUCCESSFUL %08X !\n", lpParms->dwCallback);
+        	dprintf_cdaudio(stddeb,
+			"CDAUDIO_mciSet // MCI_NOTIFY_SUCCESSFUL %08X !\n", 
+			lpParms->dwCallback);
 		mciDriverNotify((HWND)LOWORD(lpParms->dwCallback), 
 			CDADev[wDevID].wNotifyDeviceID, MCI_NOTIFY_SUCCESSFUL);
 		}
@@ -910,12 +894,13 @@
 			return CDAUDIO_mciSeek(dwDevID, dwParam1, 
 					(LPMCI_SEEK_PARMS)dwParam2);
 		case MCI_SET_DOOR_OPEN:
-			printf("CDAUDIO_DriverProc // MCI_SET_DOOR_OPEN !\n");
+            		dprintf_cdaudio(stddeb,
+				"CDAUDIO_DriverProc // MCI_SET_DOOR_OPEN !\n");
 			if (ioctl(CDADev[dwDevID].unixdev, CDROMEJECT)) return MCIERR_HARDWARE;
 			CDADev[dwDevID].nTracks = 0;
 			return 0;
 		case MCI_SET_DOOR_CLOSED:
-			printf("CDAUDIO_DriverProc // MCI_SET_DOOR_CLOSED !\n");
+            		dprintf_cdaudio(stddeb,"CDAUDIO_DriverProc // MCI_SET_DOOR_CLOSED !\n");
 			if (ioctl(CDADev[dwDevID].unixdev, CDROMEJECT, 1)) return MCIERR_HARDWARE;
 			CDADev[dwDevID].nTracks = 0;
 			return 0;
diff --git a/misc/message.c b/misc/message.c
index 825e224..3f766df 100644
--- a/misc/message.c
+++ b/misc/message.c
@@ -14,6 +14,7 @@
 #include <windows.h>
 #include <sys/types.h>
 #include <sys/stat.h>
+#include <ctype.h>
 #include <fcntl.h>
 #include <unistd.h>
 #include "prototypes.h"
@@ -93,8 +94,16 @@
 	lpmb->Title = (LPSTR) malloc(strlen(title) + 1);
 	strcpy(lpmb->Title, title);
 /*	lpmb->Str = str;*/
-	lpmb->Str = (LPSTR) malloc(strlen(str) + 1);
-	strcpy(lpmb->Str, str);
+	if (str && *str)
+	{
+		lpmb->Str = (LPSTR) malloc(strlen(str) + 1);
+		strcpy(lpmb->Str, str);
+	}
+	else
+	{
+		lpmb->Str = (LPSTR) malloc(8);
+		strcpy(lpmb->Str, "Message");
+	}
 	lpmb->wType = type;
 	lpmb->ActiveFlg = TRUE;
 	wndClass.style           = CS_HREDRAW | CS_VREDRAW ;
diff --git a/misc/mmaux.c b/misc/mmaux.c
index 36a2d74..80ed111 100644
--- a/misc/mmaux.c
+++ b/misc/mmaux.c
@@ -11,14 +11,16 @@
 
 #ifdef BUILTIN_MMSYSTEM
 
-#include "stdio.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
 #include "win.h"
 #include "user.h"
 #include "driver.h"
 #include "mmsystem.h"
 
-#include <fcntl.h>
-#include <sys/ioctl.h>
 #ifdef linux
 #include <linux/soundcard.h>
 #endif
diff --git a/misc/mmsystem.c b/misc/mmsystem.c
index ef8d5ca..4da49f9 100644
--- a/misc/mmsystem.c
+++ b/misc/mmsystem.c
@@ -7,7 +7,9 @@
 
 #ifndef WINELIB
 
-#include "stdio.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 #include <fcntl.h>
 #include <sys/ioctl.h>
 #include "win.h"
diff --git a/misc/shell.c b/misc/shell.c
index 0b6e552..6682100 100644
--- a/misc/shell.c
+++ b/misc/shell.c
@@ -359,10 +359,17 @@
  */
 INT ShellAbout(HWND hWnd, LPCSTR szApp, LPCSTR szOtherStuff, HICON hIcon)
 {
-	fprintf(stderr, "ShellAbout ! (%s, %s)\n", szApp, szOtherStuff);
+/*	fprintf(stderr, "ShellAbout ! (%s, %s)\n", szApp, szOtherStuff);*/
 
-	strcpy(AppName, szApp);
-	strcpy(AppMisc, szOtherStuff);
+	if (szApp)
+		strcpy(AppName, szApp);
+	else
+		*AppName = 0;
+
+	if (szOtherStuff)
+		strcpy(AppMisc, szOtherStuff);
+	else
+		*AppMisc = 0;
 
 	return DialogBox(hSysRes, "SHELL_ABOUT_MSGBOX", hWnd, (FARPROC)AboutDlgProc);
 }
diff --git a/misc/spy.c b/misc/spy.c
index efb2210..2598711 100644
--- a/misc/spy.c
+++ b/misc/spy.c
@@ -241,8 +241,8 @@
     "WM_EXITSIZEMOVE"		/* 0x0232 */
 };
 
-char SpyFilters[256];
-char SpyIncludes[256];
+char SpyFilters[256+1];
+char SpyIncludes[256+1];
 
 #endif /* NOSPY */
 
@@ -303,7 +303,14 @@
     }
     
     GetPrivateProfileString("spy", "exclude", "", SpyFilters, 
-			    sizeof(SpyFilters), WINE_INI);
+			    sizeof(SpyFilters)-1, WINE_INI);
     GetPrivateProfileString("spy", "include", "", SpyIncludes, 
-			    sizeof(SpyIncludes), WINE_INI);
+			    sizeof(SpyIncludes)-1, WINE_INI);
+
+    if (*SpyIncludes != 0) {
+      strcat(SpyIncludes, ";");
+    }
+    if (*SpyFilters != 0) {
+      strcat(SpyFilters, ";");
+    }
 }
diff --git a/miscemu/Imakefile b/miscemu/Imakefile
index 7caac55..f44c876 100644
--- a/miscemu/Imakefile
+++ b/miscemu/Imakefile
@@ -22,7 +22,6 @@
 
 WineRelocatableTarget($(TOP)/$(MODULE),,$(OBJS))
 DependTarget()
-CleanTarget()
 
 includes::
 
diff --git a/miscemu/emulate.c b/miscemu/emulate.c
index 78b49a9..bf2c868 100644
--- a/miscemu/emulate.c
+++ b/miscemu/emulate.c
@@ -2,6 +2,10 @@
 #include <stdio.h>
 #include "prototypes.h"
 #include "regfunc.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
 
 struct Win87EmInfoStruct {
   unsigned short Version;
@@ -15,8 +19,8 @@
 int
 WIN87_fpmath()
 {
-  printf( "_fpmath: (%x:%x %x %x)\n",_CONTEXT->sc_cs, _CONTEXT->sc_eip, 
-	 _CONTEXT->sc_es, _BX & 0xffff);
+  dprintf_int(stddeb, "_fpmath: (%x:%x %x %x)\n",_CONTEXT->sc_cs, 
+	 _CONTEXT->sc_eip, _CONTEXT->sc_es, _BX & 0xffff);
 
   switch(_BX & 0xffff)
     {
@@ -31,17 +35,19 @@
 void
 WIN87_WinEm87Info(struct Win87EmInfoStruct *pWIS, int cbWin87EmInfoStruct)
 {
-  printf( "__WinEm87Info(%p,%d)\n",pWIS,cbWin87EmInfoStruct);
+  dprintf_int(stddeb, "__WinEm87Info(%p,%d)\n",pWIS,cbWin87EmInfoStruct);
 }
 
 void
 WIN87_WinEm87Restore(void *pWin87EmSaveArea, int cbWin87EmSaveArea)
 {
-  printf( "__WinEm87Restore(%p,%d)\n",pWin87EmSaveArea,cbWin87EmSaveArea);
+  dprintf_int(stddeb, "__WinEm87Restore(%p,%d)\n",
+	pWin87EmSaveArea,cbWin87EmSaveArea);
 }
 
 void
 WIN87_WinEm87Save(void *pWin87EmSaveArea, int cbWin87EmSaveArea)
 {
-  printf( "__WinEm87Save(%p,%d)\n",pWin87EmSaveArea,cbWin87EmSaveArea);
+  dprintf_int(stddeb, "__WinEm87Save(%p,%d)\n",
+	pWin87EmSaveArea,cbWin87EmSaveArea);
 }
diff --git a/miscemu/int10.c b/miscemu/int10.c
index 632f279..2260fff 100644
--- a/miscemu/int10.c
+++ b/miscemu/int10.c
@@ -2,6 +2,10 @@
 #include <stdlib.h>
 #include "registers.h"
 #include "wine.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
 
 void IntBarf(int i, struct sigcontext_struct *context)
 {
diff --git a/miscemu/int13.c b/miscemu/int13.c
index 8fb128e..1c08233 100644
--- a/miscemu/int13.c
+++ b/miscemu/int13.c
@@ -2,6 +2,12 @@
 #include <stdlib.h>
 #include "registers.h"
 #include "wine.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
+
+void IntBarf(int i, struct sigcontext_struct *context);
 
 int do_int13(struct sigcontext_struct *context)
 {
diff --git a/miscemu/int15.c b/miscemu/int15.c
index 67a0b7a..3858e8f 100644
--- a/miscemu/int15.c
+++ b/miscemu/int15.c
@@ -2,6 +2,12 @@
 #include <stdlib.h>
 #include "registers.h"
 #include "wine.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
+
+void IntBarf(int i, struct sigcontext_struct *context);
 
 int do_int15(struct sigcontext_struct *context)
 {
diff --git a/miscemu/int16.c b/miscemu/int16.c
index 33ecef5..c1294f8 100644
--- a/miscemu/int16.c
+++ b/miscemu/int16.c
@@ -2,6 +2,12 @@
 #include <stdlib.h>
 #include "registers.h"
 #include "wine.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
+
+void IntBarf(int i, struct sigcontext_struct *context);
 
 int do_int16(struct sigcontext_struct *context)
 {
diff --git a/miscemu/int1a.c b/miscemu/int1a.c
index f43fef3..0e0a9fa 100644
--- a/miscemu/int1a.c
+++ b/miscemu/int1a.c
@@ -4,21 +4,29 @@
 #include "registers.h"
 #include "wine.h"
 #include "options.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
 
 #ifdef linux
+#define inline __inline__  /* So we can compile with -ansi */
 #include <linux/sched.h> /* needed for HZ */
+#undef inline
 #endif
 
 #define	BCD_TO_BIN(x) ((x&15) + (x>>4)*10)
 #define BIN_TO_BCD(x) ((x%10) + ((x/10)<<4))
 
+void IntBarf(int i, struct sigcontext_struct *context);
+
 int do_int1A(struct sigcontext_struct * context){
 	time_t ltime;
 	struct tm *bdtime;
 	int ticks;
 
     if (Options.relay_debug) {
-	printf("int1A: AX %04x, BX %04x, CX %04x, DX %04x, "
+	fprintf(stddeb,"int1A: AX %04x, BX %04x, CX %04x, DX %04x, "
 	       "SI %04x, DI %04x, DS %04x, ES %04x\n",
 	       AX, BX, CX, DX, SI, DI, DS, ES);
     }
@@ -30,7 +38,8 @@
 		CX = ticks >> 16;
 		DX = ticks & 0x0000FFFF;
 		AX = 0;  /* No midnight rollover */
-		printf("int1a_00 // ltime=%ld ticks=%ld\n", ltime, ticks);
+		dprintf_int(stddeb,"int1a_00 // ltime=%ld ticks=%ld\n",
+			ltime, ticks);
 		break;
 		
 	case 2: 
diff --git a/miscemu/int21.c b/miscemu/int21.c
index 7596aa4..84cb953 100644
--- a/miscemu/int21.c
+++ b/miscemu/int21.c
@@ -22,6 +22,10 @@
 #include "msdos.h"
 #include "registers.h"
 #include "options.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
 
 WORD ExtendedError, CodePage = 437;
 BYTE ErrorClass, Action, ErrorLocus;
@@ -38,6 +42,7 @@
 WORD sharing_pause = 1;        /* pause between retries */
 
 extern char TempDirectory[];
+void IntBarf(int i, struct sigcontext_struct *context);
 
 static int Error(int e, int class, int el)
 {
@@ -89,6 +94,7 @@
 	}
 }
 
+/*
 static void Barf(struct sigcontext_struct *context)
 {
 	fprintf(stderr, "int21: unknown/not implemented parameters:\n");
@@ -96,6 +102,7 @@
 	       "SI %04x, DI %04x, DS %04x, ES %04x\n",
 	       AX, BX, CX, DX, SI, DI, DS, ES);
 }
+*/
 
 void ChopOffWhiteSpace(char *string)
 {
@@ -265,9 +272,9 @@
 
 	if (BX < 3) {
 		for (x = 0;x != CX;x++) {
-			fprintf(stderr, "%c", *ptr++);
+			dprintf_int(stddeb, "%c", *ptr++);
 		}
-		fflush(stderr);
+		fflush(stddeb);
 
 		Error (0,0,0);
 		AL = CX;
@@ -356,6 +363,12 @@
 	else
 		drive = BL - 1;
 
+	if (!DOS_ValidDrive(drive)) {
+		AX = 0x02;				
+		SetCflag;
+		return;
+	}
+
 	if (CH != 0x08) {
 		IntBarf(0x21, context);
 		return;
@@ -363,6 +376,7 @@
 	switch (CL) {
 		case 0x60: /* get device parameters */
 			   /* used by w4wgrp's winfile */
+			memset(dataptr, 0, 0x26);
 			dataptr[0] = 0x04;
 			dataptr[6] = 0; /* media type */
 			if (drive > 1) 
@@ -378,7 +392,6 @@
 				setword(&dataptr[4], 80); /* # of cylinders */
 			}
 			CreateBPB(drive, &dataptr[7]);			
-			AL = 0;
 			ResetCflag;
 			return;
 		default:
@@ -450,7 +463,7 @@
 	  case 1:
 	    mode = O_WRONLY;
 	    break;
-	    
+
 	  default:
 	    mode = O_RDWR;
 	    break;
@@ -471,7 +484,7 @@
 	    break;
 
 	  case 0x30:    /* DENYREAD */
-	    fprintf(stderr,
+	    dprintf_int(stdnimp,
 	      "OpenExistingFile (%s): DENYREAD changed to DENYALL\n",
 	      pointer(DS,DX));
 	  case 0x10:    /* DENYALL */  
@@ -536,7 +549,7 @@
 {
 	char *newname, *oldname;
 
-	fprintf(stderr,"int21: renaming %s to %s\n", 
+	dprintf_int(stddeb,"int21: renaming %s to %s\n",
 			pointer(DS,DX), pointer(ES,DI) );
 	
 	oldname = GetUnixFileName( pointer(DS,DX) );
@@ -551,7 +564,7 @@
 {
 	char *dirname;
 
-	fprintf(stderr,"int21: makedir %s\n", pointer(DS,DX) );
+	dprintf_int(stddeb,"int21: makedir %s\n", pointer(DS,DX) );
 	
 	if ((dirname = GetUnixFileName( pointer(DS,DX) ))== NULL) {
 		AL = CanNotMakeDir;
@@ -572,19 +585,23 @@
 	int drive;
 	char *dirname = pointer(DS,DX);
 	drive = DOS_GetDefaultDrive();
-	fprintf(stderr,"int21: changedir %s\n", dirname);
+	dprintf_int(stddeb,"int21: changedir %s\n", dirname);
 	if (dirname != NULL && dirname[1] == ':') {
 		drive = toupper(dirname[0]) - 'A';
 		dirname += 2;
 		}
-	DOS_ChangeDir(drive, dirname);
+	if (!DOS_ChangeDir(drive, dirname))
+	{
+		SetCflag;
+		AX=0x03;
+	}
 }
 
 static void RemoveDir(struct sigcontext_struct *context)
 {
 	char *dirname;
 
-	fprintf(stderr,"int21: removedir %s\n", pointer(DS,DX) );
+	dprintf_int(stddeb,"int21: removedir %s\n", pointer(DS,DX) );
 
 	if ((dirname = GetUnixFileName( pointer(DS,DX) ))== NULL) {
 		AL = CanNotMakeDir;
@@ -623,14 +640,16 @@
 			SetCflag;
 			return;
 		}
-	} while (*(dta + 0x0c) != dp->attribute);
+	} /* while (*(dta + 0x0c) != dp->attribute);*/
+       while ( ( dp->search_attribute & dp->attribute) != dp->attribute);
 	
+  	*(dta + 0x15) = dp->attribute;
 	setword(&dta[0x16], 0x1234); /* time */
 	setword(&dta[0x18], 0x1234); /* date */
 	setdword(&dta[0x1a], dp->filesize);
 	strncpy(dta + 0x1e, dp->filename, 13);
 
-	AL;
+	AL = 0;
 	ResetCflag;
 	return;
 }
@@ -640,7 +659,7 @@
 	BYTE drive, *path = pointer(DS, DX);
 	struct dosdirent *dp;
 
-	if (path[1] == ':') {
+	if ((*path)&&(path[1] == ':')) {
 		drive = (islower(*path) ? toupper(*path) : *path) - 'A';
 
 		if (!DOS_ValidDrive(drive)) {
@@ -674,6 +693,7 @@
 		return;
 	}
 
+	dp->search_attribute = ECX & (FA_LABEL | FA_DIREC);
 	memcpy(dta + 0x0d, &dp, sizeof(dp));
 	FindNext(context);
 }
@@ -720,7 +740,7 @@
 	
 	sprintf(temp,"%s\\win%d.tmp",TempDirectory,(int) getpid());
 
-	fprintf(stderr,"CreateTempFile %s\n",temp);
+	dprintf_int(stddeb,"CreateTempFile %s\n",temp);
 
 	handle = open(GetUnixFileName(temp), O_CREAT | O_TRUNC | O_RDWR);
 
@@ -793,7 +813,7 @@
 	strncpy(dataptr + 6, DOS_GetVolumeLabel(drive), 8);
 	strncpy(dataptr + 0x11, "FAT16   ", 8);
 	
-	AL;
+	AL = 0;
 	ResetCflag;
 }
 
@@ -830,8 +850,8 @@
 
 	for (y = 0; y !=2 ; y++) {
 		for (x = 0; x!=15;x++)
-			fprintf(stderr, "%02x ", *fcb++);
-		fprintf(stderr,"\n");
+			dprintf_int(stddeb, "%02x ", *fcb++);
+		dprintf_int(stddeb,"\n");
 	}
 }
 
@@ -850,14 +870,14 @@
 	
 	if ((*fcb) == 0xff)
 	  {
-	    standard_fcb = fcb + 7;
-	    output_fcb = dta + 7;
+	    standard_fcb = (struct fcb *)(fcb + 7);
+	    output_fcb = (struct fcb *)(dta + 7);
 	    *dta = 0xff;
 	  }
 	else
 	  {
-	    standard_fcb = fcb;
-	    output_fcb = dta;
+	    standard_fcb = (struct fcb *)fcb;
+	    output_fcb = (struct fcb *)dta;
 	  }
 
 	if (standard_fcb->drive)
@@ -875,7 +895,7 @@
 
 	output_fcb->drive = drive;
 
-	if (*(fcb) == 0xff) 
+	if (*(fcb) == 0xff)
 	  {
 	    if (*(fcb+6) & FA_LABEL)      /* return volume label */
 	      {
@@ -883,14 +903,14 @@
 		memset(&output_fcb->name, ' ', 11);
 		if (DOS_GetVolumeLabel(drive) != NULL) 
 		  {
-		    strncpy(&output_fcb->name, DOS_GetVolumeLabel(drive), 11);
+		    strncpy(output_fcb->name, DOS_GetVolumeLabel(drive), 11);
 		    AL = 0x00;
 		    return;
 		  }
 	      }
 	  }
 
-	strncpy(&(output_fcb->name),&(standard_fcb->name),11);
+	strncpy(output_fcb->name, standard_fcb->name, 11);
 	if (*fcb == 0xff)
 	  *(dta+6) = ( *(fcb+6) & (!FA_DIREC));
 
@@ -940,11 +960,11 @@
 	while (DOS_readdir(dp) != NULL)
 	{
 		strcpy(ptr, dp->filename);
-		fprintf(stderr, "int21: delete file %s\n", temp);
+		dprintf_int(stddeb, "int21: delete file %s\n", temp);
 		/* unlink(GetUnixFileName(temp)); */
 	}
 	DOS_closedir(dp);
-	AL;
+	AL = 0;
 }
 
 static void RenameFileFCB(struct sigcontext_struct *context)
@@ -986,10 +1006,11 @@
 	{
 		strcpy(oldnameptr, dp->filename);
 		strcpy(newnameptr, fcb + 1);
-		fprintf(stderr, "int21: renamefile %s -> %s\n", oldname, newname);
+		dprintf_int(stddeb, "int21: renamefile %s -> %s\n",
+			oldname, newname);
 	}
 	DOS_closedir(dp);
-	AL;
+	AL = 0;
 }
 
 
@@ -1080,7 +1101,7 @@
 {
     if (Options.relay_debug)
     {
-	printf("int21: AX %04x, BX %04x, CX %04x, DX %04x, "
+	fprintf(stddeb,"int21: AX %04x, BX %04x, CX %04x, DX %04x, "
 	       "SI %04x, DI %04x, DS %04x, ES %04x\n",
 	       AX, BX, CX, DX, SI, DI, DS, ES);
     }
@@ -1178,7 +1199,7 @@
 		AL = DOS_GetDefaultDrive();
 		Error (0,0,0);
 	    break;
-	    
+
 	  case 0x1a: /* SET DISK TRANSFER AREA ADDRESS */
             dta = pointer(DS, DX);
             break;
@@ -1197,7 +1218,9 @@
 		
 	  case 0x25: /* SET INTERRUPT VECTOR */
 	    /* Ignore any attempt to set a segment vector */
- 		fprintf(stderr, "int21: set interrupt vector %2x (%04x:%04x)\n", AL, DS, DX);
+ 		dprintf_int(stdnimp,
+			"int21: set interrupt vector %2x (%04x:%04x)\n",
+			AL, DS, DX);
             break;
 
 	  case 0x2a: /* GET SYSTEM DATE */
@@ -1265,7 +1288,8 @@
 	  case 0x35: /* GET INTERRUPT VECTOR */
 	    /* Return a NULL segment selector - this will bomb, 
 	    		if anyone ever tries to use it */
-	    fprintf(stderr, "int21: get interrupt vector %2x\n", AX & 0xff);
+	    dprintf_int(stdnimp, "int21: get interrupt vector %2x\n",
+		AX & 0xff);
 	    ES = 0;
 	    BX = 0;
 	    break;
@@ -1379,7 +1403,7 @@
 		ResetCflag;
 	    break;
 
-	  case 0x47: /* "CWD" - GET CURRENT DIRECTORY */	
+	  case 0x47: /* "CWD" - GET CURRENT DIRECTORY */
 	    GetCurrentDirectory(context);
 	    AX = 0x0100; 
 	    /* intlist: many Microsoft products for Windows rely on this */
@@ -1398,7 +1422,7 @@
 	  case 0x4c: /* "EXIT" - TERMINATE WITH RETURN CODE */
 	    exit(AL);
 	    break;
-		
+
 	  case 0x4d: /* GET RETURN CODE */
 	    AL = NoError; /* normal exit */
 	    break;
@@ -1474,7 +1498,7 @@
 		    AL = InvalidDrive;
 		    SetCflag;
 		    break;
-		} 
+		}
 		else 
 		{
 		    ResetCflag;
diff --git a/miscemu/int25.c b/miscemu/int25.c
index af79ec4..7f95717 100644
--- a/miscemu/int25.c
+++ b/miscemu/int25.c
@@ -3,6 +3,10 @@
 #include "registers.h"
 #include "msdos.h"
 #include "wine.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
 
 int do_int25(struct sigcontext_struct *context)
 {
@@ -18,7 +22,7 @@
 		begin = DX;
 		length = CX;
 	}
-	fprintf(stderr, "int25: abs diskread, drive %d, sector %d, "
+	dprintf_int(stdnimp, "int25: abs diskread, drive %d, sector %d, "
 	"count %d, buffer %d\n", EAX & 0xff, begin, length, (int) dataptr);
 
 	memset(dataptr, 0, length * 512);
diff --git a/miscemu/int26.c b/miscemu/int26.c
index ff145b1..6abe988 100644
--- a/miscemu/int26.c
+++ b/miscemu/int26.c
@@ -3,6 +3,12 @@
 #include "registers.h"
 #include "msdos.h"
 #include "wine.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
+
+void IntBarf(int i, struct sigcontext_struct *context);
 
 int do_int26(struct sigcontext_struct *context)
 {
@@ -19,7 +25,7 @@
 		length = CX;
 	}
 		
-	fprintf(stderr,"int26: abs diskwrite, drive %d, sector %d, count %d,"
+	dprintf_int(stdnimp,"int26: abs diskwrite, drive %d, sector %d, count %d,"
 		" buffer %d\n", EAX & 0xff, begin, length, (int) dataptr);
 
 	ResetCflag;
diff --git a/miscemu/int2a.c b/miscemu/int2a.c
index ba25c2f..74ed60f 100644
--- a/miscemu/int2a.c
+++ b/miscemu/int2a.c
@@ -2,6 +2,12 @@
 #include <stdlib.h>
 #include "msdos.h"
 #include "wine.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
+
+void IntBarf(int i, struct sigcontext_struct *context);
 
 int do_int2a(struct sigcontext_struct *context)
 {
diff --git a/miscemu/int2f.c b/miscemu/int2f.c
index e1a6195..e41fd5b 100644
--- a/miscemu/int2f.c
+++ b/miscemu/int2f.c
@@ -2,10 +2,14 @@
 #include <stdlib.h>
 #include "registers.h"
 #include "wine.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
 
+void IntBarf(int i, struct sigcontext_struct *context);
 int do_int2f_16(struct sigcontext_struct *context);
 
-
 int do_int2f(struct sigcontext_struct *context)
 {
 	switch((context->sc_eax >> 8) & 0xff)
@@ -33,16 +37,16 @@
 	switch(context->sc_eax & 0xff) {
 		case 0x00: 
 			/* return 'major/minor' for MSWin 3.1 */
-			printf("do_int2f_16 // return 'major/minor' for MSWin 3.1 !\n");
+			dprintf_int(stddeb,"do_int2f_16 // return 'major/minor' for MSWin 3.1 !\n");
 			context->sc_eax = 0x0310;
 			return 1;
-		case 0x86: 
+		case 0x86:
 			/* operating in protected mode under DPMI */
-			printf("do_int2f_16 // operating in protected mode under DPMI !\n");
+			dprintf_int(stddeb,"do_int2f_16 // operating in protected mode under DPMI !\n");
 			context->sc_eax = 0x0000;
 			return 1;
-		case 0x87: 
-			printf("do_int2f_16 // return DPMI flags !\n");
+		case 0x87:
+			dprintf_int(stddeb,"do_int2f_16 // return DPMI flags !\n");
 			context->sc_eax = 0x0000;		/* DPMI Installed */
 			context->sc_ebx = 0x0001;		/* 32bits available */
 			context->sc_ecx = 0x04;			/* processor 486 */
diff --git a/miscemu/int31.c b/miscemu/int31.c
index d738772..6bdef30 100644
--- a/miscemu/int31.c
+++ b/miscemu/int31.c
@@ -2,6 +2,10 @@
 #include <stdlib.h>
 #include "registers.h"
 #include "wine.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
 
 typedef struct {
 	WORD	accessed    : 1;
@@ -33,7 +37,8 @@
 int do_int31(struct sigcontext_struct *context)
 {
 	LPDESCRIPTOR lpDesc;
-	printf("do_int31 // context->sc_eax=%04X\n", context->sc_eax);
+	dprintf_int(stddeb,"do_int31 // context->sc_eax=%04X\n",
+		context->sc_eax);
 	switch(context->sc_eax)
 	{
 	case 0x0000:
@@ -60,35 +65,43 @@
 {
 	LPSTR	ptr;
 	HANDLE 	pmSel;
-	printf("DPMI_GetNewSelector(%d); !\n", selcount);
+	dprintf_int(stddeb,"DPMI_GetNewSelector(%d); !\n", selcount);
 	pmSel = GlobalAlloc(GMEM_FIXED, 4096);
 	ptr = GlobalLock(pmSel);
-	printf("DPMI_GetNewSelector() return %04X !\n", pmSel);
+	dprintf_int(stddeb,"DPMI_GetNewSelector() return %04X !\n", pmSel);
 	return pmSel;
 }
 
 
 BOOL DPMI_FreeSelector(HANDLE pmSel)
 {
-	printf("DPMI_FreeSelector(%04X); !\n", pmSel);
+	dprintf_int(stddeb,"DPMI_FreeSelector(%04X); !\n", pmSel);
 	GlobalFree(pmSel);
 	return 0;
 }
 
 BOOL DPMI_SetDescriptor(HANDLE pmSel, LPDESCRIPTOR lpDesc)
 {
-	printf("DPMI_SetDescriptor(%04X, %08X); !\n", pmSel, lpDesc);
-	printf("DPMI lpDesc->Limit=%u \n", lpDesc->Limit);
-	printf("DPMI lpDesc->addr_lo=%04X \n", lpDesc->addr_lo);
-	printf("DPMI lpDesc->addr_hi=%02X \n", lpDesc->addr_hi);
-	printf("DPMI lpDesc->access.accessed=%u \n", lpDesc->access.accessed);
-	printf("DPMI lpDesc->access.read_write=%u \n", lpDesc->access.read_write);
-	printf("DPMI lpDesc->access.conf_exp=%u \n", lpDesc->access.conf_exp);
-	printf("DPMI lpDesc->access.code=%u \n", lpDesc->access.code);
-	printf("DPMI lpDesc->access.xsystem=%u \n", lpDesc->access.xsystem);
-	printf("DPMI lpDesc->access.dpl=%u \n", lpDesc->access.dpl);
-	printf("DPMI lpDesc->access.present=%u \n", lpDesc->access.present);
-	printf("DPMI lpDesc->reserved=%04X \n", lpDesc->reserved);
+	dprintf_int(stdnimp,"DPMI_SetDescriptor(%04X, %08X); !\n", 
+		pmSel, lpDesc);
+	dprintf_int(stdnimp,"DPMI lpDesc->Limit=%u \n", lpDesc->Limit);
+	dprintf_int(stdnimp,"DPMI lpDesc->addr_lo=%04X \n", lpDesc->addr_lo);
+	dprintf_int(stdnimp,"DPMI lpDesc->addr_hi=%02X \n", lpDesc->addr_hi);
+	dprintf_int(stdnimp,"DPMI lpDesc->access.accessed=%u \n", 
+		lpDesc->access.accessed);
+	dprintf_int(stdnimp,"DPMI lpDesc->access.read_write=%u \n", 
+		lpDesc->access.read_write);
+	dprintf_int(stdnimp,"DPMI lpDesc->access.conf_exp=%u \n", 
+		lpDesc->access.conf_exp);
+	dprintf_int(stdnimp,"DPMI lpDesc->access.code=%u \n", 
+		lpDesc->access.code);
+	dprintf_int(stdnimp,"DPMI lpDesc->access.xsystem=%u \n", 
+		lpDesc->access.xsystem);
+	dprintf_int(stdnimp,"DPMI lpDesc->access.dpl=%u \n", 
+		lpDesc->access.dpl);
+	dprintf_int(stdnimp,"DPMI lpDesc->access.present=%u \n", 
+		lpDesc->access.present);
+	dprintf_int(stdnimp,"DPMI lpDesc->reserved=%04X \n", lpDesc->reserved);
 	return FALSE;
 }
 
diff --git a/miscemu/ioports.c b/miscemu/ioports.c
index 07d6af3..d8b09f3 100644
--- a/miscemu/ioports.c
+++ b/miscemu/ioports.c
@@ -3,6 +3,10 @@
 #include <time.h>
 #include "registers.h"
 #include "wine.h"
+#include "stddebug.h"
+/* #define DEBUG_INT */
+/* #undef  DEBUG_INT */
+#include "debug.h"
 
 static BYTE cmosaddress;
 
@@ -18,7 +22,7 @@
 
 void inportb(struct sigcontext_struct *context)
 {
-	fprintf(stderr, "IO: inb (%x)\n", DX);
+	dprintf_int(stddeb, "IO: inb (%x)\n", DX);
 
 	switch(DX) {
 		case 0x70:
@@ -33,14 +37,14 @@
 
 void inport(struct sigcontext_struct *context)
 {
-	fprintf(stderr, "IO: in (%x)\n", DX);
+	dprintf_int(stdnimp, "IO: in (%x)\n", DX);
 
 	AX = 0xffff;
 }
 
 void outportb(struct sigcontext_struct *context)
 {
-	fprintf(stderr, "IO: outb (%x), %x\n", DX, AX);
+	dprintf_int(stdnimp, "IO: outb (%x), %x\n", DX, AX);
 
 	switch (EDX & 0xffff)
 	{
@@ -56,5 +60,5 @@
 
 void outport(struct sigcontext_struct *context)
 {
-	fprintf(stderr, "IO: out (%x), %x\n", DX, AX);
+	dprintf_int(stdnimp, "IO: out (%x), %x\n", DX, AX);
 }
diff --git a/miscemu/kernel.c b/miscemu/kernel.c
index d257b16..a2a559f 100644
--- a/miscemu/kernel.c
+++ b/miscemu/kernel.c
@@ -6,6 +6,8 @@
 #include "prototypes.h"
 #include "regfunc.h"
 #include "options.h"
+#include "stddebug.h"
+#include "debug.h"
 
 extern unsigned short WIN_StackSize;
 
@@ -18,9 +20,8 @@
     if (segment == -1)
 	segment = *(Stack16Frame + 6);
 
-#ifdef RELAY_DEBUG
-    printf("LockSegment: segment %x\n", segment);
-#endif
+    if (Options.relay_debug)
+	fprintf(stddeb,"LockSegment: segment %x\n", segment);
 
     return segment;
 }
@@ -34,9 +35,8 @@
     if (segment == -1)
 	segment = *(Stack16Frame + 6);
 
-#ifdef RELAY_DEBUG
-    printf("UnlockSegment: segment %x\n", segment);
-#endif
+    if (Options.relay_debug)
+    	fprintf(stddeb,"UnlockSegment: segment %x\n", segment);
 
     return segment;
 }
@@ -50,6 +50,11 @@
     _AX = 1;
     _CX = WIN_StackSize;
     _DX = Options.cmdShow;
+    _DI = _DS;
+
+/* FIXME: DI should contain the instance handle of the caller, _DS doesn't
+          always work as the caller might have changed it. */
+
     _SI = 0;
     ReturnFromRegisterFunc();
     /* Function does not return */
@@ -61,8 +66,7 @@
 int
 KERNEL_WaitEvent(int task)
 {
-#ifdef RELAY_DEBUG
-    printf("WaitEvent: task %d\n", task);
-#endif
+    if (Options.relay_debug)
+    	fprintf(stddeb,"WaitEvent: task %d\n", task);
     return 0;
 }
diff --git a/objects/Imakefile b/objects/Imakefile
index b39ccd2..81e345a 100644
--- a/objects/Imakefile
+++ b/objects/Imakefile
@@ -3,44 +3,28 @@
 MODULE = objects
 
 SRCS = \
+	bitblt.c \
 	bitmap.c \
 	brush.c \
+	clipping.c \
+	color.c \
+	dc.c \
+	dcvalues.c \
+	dib.c \
+	dither.c \
 	font.c \
 	gdiobj.c \
+	linedda.c \
+	metafile.c \
 	palette.c \
 	pen.c \
-	dib.c \
 	region.c \
-	text.c \
-	dcvalues.c \
-	clipping.c \
-	bitblt.c \
-	linedda.c \
-	color.c \
-	dither.c \
-	metafile.c
+	text.c
 
-OBJS = \
-	bitmap.o \
-	brush.o \
-	font.o \
-	gdiobj.o \
-	palette.o \
-	pen.o \
-	dib.o \
-	region.o \
-	text.o \
-	dcvalues.o \
-	clipping.o \
-	bitblt.o \
-	linedda.o \
-	color.o \
-	dither.o \
-	metafile.o
+OBJS = $(SRCS:.c=.o)
 
 WineRelocatableTarget($(TOP)/$(MODULE),,$(OBJS))
 DependTarget()
-CleanTarget()
 
 includes::
 
diff --git a/objects/bitblt.c b/objects/bitblt.c
index bb83f99..47aa35c 100644
--- a/objects/bitblt.c
+++ b/objects/bitblt.c
@@ -13,6 +13,11 @@
 
 #include "gdi.h"
 #include "metafile.h"
+#include "options.h"
+#include "stddebug.h"
+/* #define DEBUG_GDI /* */
+/* #undef  DEBUG_GDI /* */
+#include "debug.h"
 
 extern const int DC_XROPfunction[];
 
@@ -26,8 +31,6 @@
 BOOL PatBlt( HDC hdc, short left, short top,
 	     short width, short height, DWORD rop)
 {
-    int x1, x2, y1, y2;
-    
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) 
     {
@@ -38,22 +41,42 @@
 	return TRUE;
     }
 
-#ifdef DEBUG_GDI
-    printf( "PatBlt: %d %d,%d %dx%d %06x\n",
+    dprintf_gdi(stddeb, "PatBlt: %d %d,%d %dx%d %06x\n",
 	    hdc, left, top, width, height, rop );
-#endif
 
+      /* Convert ROP3 code to ROP2 code */
     rop >>= 16;
     if (!DC_SetupGCForBrush( dc )) rop &= 0x0f;
     else rop = (rop & 0x03) | ((rop >> 4) & 0x0c);
-    XSetFunction( XT_display, dc->u.x.gc, DC_XROPfunction[rop] );
 
-    x1 = dc->w.DCOrgX + XLPTODP( dc, left );
-    x2 = dc->w.DCOrgX + XLPTODP( dc, left + width );
-    y1 = dc->w.DCOrgY + YLPTODP( dc, top );
-    y2 = dc->w.DCOrgY + YLPTODP( dc, top + height );
-    XFillRectangle( XT_display, dc->u.x.drawable, dc->u.x.gc,
-		   MIN(x1,x2), MIN(y1,y2), abs(x2-x1), abs(y2-y1) );
+      /* Special case for BLACKNESS and WHITENESS */
+    if (!Options.usePrivateMap && ((rop == R2_BLACK-1) || (rop == R2_WHITE-1)))
+    {
+        XSetForeground( display, dc->u.x.gc, (rop == R2_BLACK-1) ?
+                      BlackPixelOfScreen(screen) : WhitePixelOfScreen(screen));
+        XSetFillStyle( display, dc->u.x.gc, FillSolid );
+        rop = R2_COPYPEN;
+    }
+
+    XSetFunction( display, dc->u.x.gc, DC_XROPfunction[rop] );
+
+    left = dc->w.DCOrgX + XLPTODP( dc, left );
+    top  = dc->w.DCOrgY + YLPTODP( dc, top );
+
+      /* Convert dimensions to device coords */
+    if ((width = (width * dc->w.VportExtX) / dc->w.WndExtX) < 0)
+    {
+        width = -width;
+        left -= width;
+    }
+    if ((height = (height * dc->w.VportExtY) / dc->w.WndExtY) < 0)
+    {
+        height = -height;
+        top -= height;
+    }
+
+    XFillRectangle( display, dc->u.x.drawable, dc->u.x.gc,
+                    left, top, width, height );
     return TRUE;
 }
 
@@ -69,18 +92,17 @@
     DWORD saverop = rop;
     DC *dcDest, *dcSrc;
 
-#ifdef DEBUG_GDI    
-    printf( "BitBlt: %d %d,%d %dx%d %d %d,%d %08x\n",
-	   hdcDest, xDest, yDest, width, height, hdcSrc, xSrc, ySrc, rop );
-#endif
-	if (width == 0 || height == 0) return FALSE;
+    dprintf_gdi(stddeb, "BitBlt: %04x %d,%d %dx%d %04x %d,%d %08x\n",
+                hdcDest, xDest, yDest, width, height, hdcSrc, xSrc, ySrc, rop);
+
+    if (width == 0 || height == 0) return FALSE;
     if ((rop & 0xcc0000) == ((rop & 0x330000) << 2))
 	return PatBlt( hdcDest, xDest, yDest, width, height, rop );
 
     rop >>= 16;
     if ((rop & 0x0f) != (rop >> 4))
     {
-	printf( "BitBlt: Unimplemented ROP %02x\n", rop );
+	dprintf_gdi(stdnimp, "BitBlt: Unimplemented ROP %02x\n", rop );
 	return FALSE;
     }
     
@@ -109,21 +131,21 @@
 	return FALSE;  /* Should call StretchBlt here */
     
     DC_SetupGCForText( dcDest );
-    XSetFunction( XT_display, dcDest->u.x.gc, DC_XROPfunction[rop & 0x0f] );
+    XSetFunction( display, dcDest->u.x.gc, DC_XROPfunction[rop & 0x0f] );
     if (dcSrc->w.bitsPerPixel == dcDest->w.bitsPerPixel)
     {
-	XCopyArea( XT_display, dcSrc->u.x.drawable,
+	XCopyArea( display, dcSrc->u.x.drawable,
 		   dcDest->u.x.drawable, dcDest->u.x.gc,
-		   MIN(xs1,xs2), MIN(ys1,ys2), abs(xs2-xs1), abs(ys2-ys1),
-		   MIN(xd1,xd2), MIN(yd1,yd2) );
+		   min(xs1,xs2), min(ys1,ys2), abs(xs2-xs1), abs(ys2-ys1),
+		   min(xd1,xd2), min(yd1,yd2) );
     }
     else
     {
 	if (dcSrc->w.bitsPerPixel != 1) return FALSE;
-	XCopyPlane( XT_display, dcSrc->u.x.drawable,
+	XCopyPlane( display, dcSrc->u.x.drawable,
 		    dcDest->u.x.drawable, dcDest->u.x.gc,
-		    MIN(xs1,xs2), MIN(ys1,ys2), abs(xs2-xs1), abs(ys2-ys1),
-		    MIN(xd1,xd2), MIN(yd1,yd2), 1 );
+		    min(xs1,xs2), min(ys1,ys2), abs(xs2-xs1), abs(ys2-ys1),
+		    min(xd1,xd2), min(yd1,yd2), 1 );
     }
     return TRUE;
 }
@@ -248,7 +270,7 @@
 /* scaling without having to worry about overflows. */
 
 /* ##### muldiv64() borrowed from svgalib 1.03 ##### */
-static inline int muldiv64( int m1, int m2, int d ) 
+static __inline__ int muldiv64( int m1, int m2, int d ) 
 {
 	/* int32 * int32 -> int64 / int32 -> int32 */
 #ifdef i386	
@@ -331,13 +353,11 @@
     WORD stretchmode;
 	BOOL	flg;
 
-#ifdef DEBUG_GDI     
-    fprintf(stderr, "StretchBlt: %d %d,%d %dx%d %d %d,%d %dx%d %08x\n",
+    dprintf_gdi(stddeb, "StretchBlt: %d %d,%d %dx%d %d %d,%d %dx%d %08x\n",
            hdcDest, xDest, yDest, widthDest, heightDest, hdcSrc, xSrc, 
            ySrc, widthSrc, heightSrc, rop );
-    printf("StretchMode is %x\n", 
+    dprintf_gdi(stddeb, "StretchMode is %x\n", 
            ((DC *)GDI_GetObjPtr(hdcDest, DC_MAGIC))->w.stretchBltMode);	
-#endif 
 
 	if (widthDest == 0 || heightDest == 0) return FALSE;
 	if (widthSrc == 0 || heightSrc == 0) return FALSE;
@@ -356,7 +376,7 @@
     rop >>= 16;
     if ((rop & 0x0f) != (rop >> 4))
     {
-        printf( "StretchBlt: Unimplemented ROP %02x\n", rop );
+        dprintf_gdi(stdnimp, "StretchBlt: Unimplemented ROP %02x\n", rop );
         return FALSE;
     }
 
@@ -427,7 +447,7 @@
     DC_SetupGCForText(dcDest);
     XSetFunction(display, dcDest->u.x.gc, DC_XROPfunction[rop & 0x0f]);
     XPutImage(display, dcDest->u.x.drawable, dcDest->u.x.gc,
-	 	dxi, 0, 0, MIN(xd1,xd2), MIN(yd1,yd2), 
+	 	dxi, 0, 0, min(xd1,xd2), min(yd1,yd2), 
 		widthDest, heightDest);
 
     /* now free the images we created */
diff --git a/objects/bitmap.c b/objects/bitmap.c
index 93b0e4a..0785559 100644
--- a/objects/bitmap.c
+++ b/objects/bitmap.c
@@ -6,23 +6,28 @@
 
 static char Copyright[] = "Copyright  Alexandre Julliard, 1993";
 
+#include <stdio.h>
 #include <stdlib.h>
 #include <X11/Xlib.h>
 #include <X11/Xutil.h>
 #include "gdi.h"
 #include "bitmap.h"
+#include "stddebug.h"
+/* #define DEBUG_GDI    /* */
+/* #undef  DEBUG_GDI    /* */
+/* #define DEBUG_BITMAP /* */
+/* #define DEBUG_BITMAP /* */
+#include "debug.h"
 
   /* Include OEM bitmaps */
 #include "bitmaps/check_boxes"
 #include "bitmaps/check_mark"
 #include "bitmaps/menu_arrow"
 
-  /* Handle of the bitmap selected by default in a memory DC */
-HBITMAP BITMAP_hbitmapMemDC = 0;
-
   /* GCs used for B&W and color bitmap operations */
 GC BITMAP_monoGC = 0, BITMAP_colorGC = 0;
 
+extern void DC_InitDC( HDC hdc );  /* dc.c */
 
 /***********************************************************************
  *           BITMAP_Init
@@ -49,9 +54,7 @@
 	    XFreePixmap( display, tmpPixmap );
 	}
     }
-
-    BITMAP_hbitmapMemDC = CreateBitmap( 1, 1, 1, 1, NULL );
-    return (BITMAP_hbitmapMemDC != 0);
+    return TRUE;
 }
 
 
@@ -143,10 +146,8 @@
 		      BYTE planes, BYTE bpp, LPSTR bits )
 {
     BITMAP bitmap = { 0, width, height, 0, planes, bpp, bits };
-#ifdef DEBUG_GDI
-    printf( "CreateBitmap: %dx%d, %d colors\n", 
+    dprintf_gdi(stddeb, "CreateBitmap: %dx%d, %d colors\n", 
 	     width, height, 1 << (planes*bpp) );
-#endif
     return CreateBitmapIndirect( &bitmap );
 }
 
@@ -157,9 +158,8 @@
 HBITMAP CreateCompatibleBitmap( HDC hdc, short width, short height )
 {
     DC * dc;
-#ifdef DEBUG_GDI
-    printf( "CreateCompatibleBitmap: %d %dx%d\n", hdc, width, height );
-#endif
+    dprintf_gdi(stddeb, "CreateCompatibleBitmap: %d %dx%d\n", 
+		hdc, width, height );
     if (!(dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC ))) return 0;
     return CreateBitmap( width, height, 1, dc->w.bitsPerPixel, NULL );
 }
@@ -222,11 +222,9 @@
     bmp = (BITMAPOBJ *) GDI_GetObjPtr( hbitmap, BITMAP_MAGIC );
     if (!bmp) return 0;
 
-#ifdef DEBUG_BITMAP
-    printf( "GetBitmapBits: %dx%d %d colors %p\n",
+    dprintf_bitmap(stddeb, "GetBitmapBits: %dx%d %d colors %p\n",
 	    bmp->bitmap.bmWidth, bmp->bitmap.bmHeight,
 	    1 << bmp->bitmap.bmBitsPixel, buffer );
-#endif
       /* Only get entire lines */
     height = count / bmp->bitmap.bmWidthBytes;
     if (height > bmp->bitmap.bmHeight) height = bmp->bitmap.bmHeight;
@@ -253,11 +251,10 @@
     bmp = (BITMAPOBJ *) GDI_GetObjPtr( hbitmap, BITMAP_MAGIC );
     if (!bmp) return 0;
 
-#ifdef DEBUG_BITMAP
-    printf( "SetBitmapBits: %dx%d %d colors %p\n",
+    dprintf_bitmap(stddeb, "SetBitmapBits: %dx%d %d colors %p\n",
 	    bmp->bitmap.bmWidth, bmp->bitmap.bmHeight,
 	    1 << bmp->bitmap.bmBitsPixel, buffer );
-#endif
+
       /* Only set entire lines */
     height = count / bmp->bitmap.bmWidthBytes;
     if (height > bmp->bitmap.bmHeight) height = bmp->bitmap.bmHeight;
@@ -314,9 +311,7 @@
 	XFreeGC( display, dc->u.x.gc );
 	dc->u.x.gc = XCreateGC( display, dc->u.x.drawable, 0, NULL );
 	dc->w.bitsPerPixel = bmp->bitmap.bmBitsPixel;
-	  /* Re-select objects with changed depth */
-	SelectObject( hdc, dc->w.hPen );
-	SelectObject( hdc, dc->w.hBrush );
+        DC_InitDC( hdc );
     }
     return prevHandle;
 }
@@ -326,7 +321,7 @@
  */
 HBITMAP CreateDiscardableBitmap(HDC hdc, short width, short height)
 {
-    printf("CreateDiscardableBitmap(%04X, %d, %d); "
+    dprintf_bitmap(stddeb,"CreateDiscardableBitmap(%04X, %d, %d); "
 	   "// call CreateCompatibleBitmap() for now!\n",
 	   hdc, width, height);
     return CreateCompatibleBitmap(hdc, width, height);
diff --git a/objects/brush.c b/objects/brush.c
index 3979836..1a4ff72 100644
--- a/objects/brush.c
+++ b/objects/brush.c
@@ -10,7 +10,10 @@
 #include "bitmap.h"
 #include "prototypes.h"
 #include "metafile.h"
-
+#include "stddebug.h"
+/* #define DEBUG_GDI /* */
+/* #undef  DEBUG_GDI /* */
+#include "debug.h"
 
 #define NB_HATCH_STYLES  6
 
@@ -47,9 +50,7 @@
 HBRUSH CreateHatchBrush( short style, COLORREF color )
 {
     LOGBRUSH logbrush = { BS_HATCHED, color, style };
-#ifdef DEBUG_GDI
-    printf( "CreateHatchBrush: %d %06x\n", style, color );
-#endif
+    dprintf_gdi(stddeb, "CreateHatchBrush: %d %06x\n", style, color );
     if ((style < 0) || (style >= NB_HATCH_STYLES)) return 0;
     return CreateBrushIndirect( &logbrush );
 }
@@ -63,9 +64,7 @@
     LOGBRUSH logbrush = { BS_PATTERN, 0, 0 };
     BITMAPOBJ *bmp, *newbmp;
 
-#ifdef DEBUG_GDI
-    printf( "CreatePatternBrush: %d\n", hbitmap );
-#endif
+    dprintf_gdi(stddeb, "CreatePatternBrush: %d\n", hbitmap );
 
       /* Make a copy of the bitmap */
 
@@ -89,9 +88,7 @@
     BITMAPINFO *info, *newInfo;
     int size;
     
-#ifdef DEBUG_GDI
-    printf( "CreateDIBPatternBrush: %d\n", hbitmap );
-#endif
+    dprintf_gdi(stddeb, "CreateDIBPatternBrush: %d\n", hbitmap );
 
       /* Make a copy of the bitmap */
 
@@ -122,9 +119,7 @@
 HBRUSH CreateSolidBrush( COLORREF color )
 {
     LOGBRUSH logbrush = { BS_SOLID, color, 0 };
-#ifdef DEBUG_GDI
-    printf( "CreateSolidBrush: %06x\n", color );
-#endif
+    dprintf_gdi(stddeb, "CreateSolidBrush: %06x\n", color );
     return CreateBrushIndirect( &logbrush );
 }
 
diff --git a/objects/clipping.c b/objects/clipping.c
index 9675b9c..26019dc 100644
--- a/objects/clipping.c
+++ b/objects/clipping.c
@@ -9,7 +9,10 @@
 #include <stdio.h>
 #include "gdi.h"
 #include "metafile.h"
-
+#include "stddebug.h"
+/* #define DEBUG_CLIPPING /* */
+/* #undef  DEBUG_CLIPPING /* */
+#include "debug.h"
 
 /***********************************************************************
  *           CLIPPING_SetDeviceClipping
@@ -109,9 +112,7 @@
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) return ERROR;
     
-#ifdef DEBUG_CLIPPING
-    printf( "SelectClipRgn: %d %d\n", hdc, hrgn );
-#endif
+    dprintf_clipping(stddeb, "SelectClipRgn: %d %d\n", hdc, hrgn );
     return CLIPPING_SelectRgn( dc, &dc->w.hClipRgn, hrgn );
 }
 
@@ -124,9 +125,7 @@
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) return ERROR;
     
-#ifdef DEBUG_CLIPPING
-    printf( "SelectVisRgn: %d %d\n", hdc, hrgn );
-#endif
+    dprintf_clipping(stddeb, "SelectVisRgn: %d %d\n", hdc, hrgn );
     return CLIPPING_SelectRgn( dc, &dc->w.hVisRgn, hrgn );
 }
 
@@ -145,9 +144,7 @@
 	return NULLREGION;   /* ?? */
     }
 
-#ifdef DEBUG_CLIPPING
-    printf( "OffsetClipRgn: %d %d,%d\n", hdc, x, y );
-#endif
+    dprintf_clipping(stddeb, "OffsetClipRgn: %d %d,%d\n", hdc, x, y );
 
     if (dc->w.hClipRgn)
     {
@@ -166,9 +163,7 @@
 {
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) return ERROR;    
-#ifdef DEBUG_CLIPPING
-    printf( "OffsetVisRgn: %d %d,%d\n", hdc, x, y );
-#endif
+    dprintf_clipping(stddeb, "OffsetVisRgn: %d %d,%d\n", hdc, x, y );
 
     if (dc->w.hVisRgn)
     {
@@ -240,10 +235,8 @@
 	return NULLREGION;   /* ?? */
     }
 
-#ifdef DEBUG_CLIPPING
-    printf( "ExcludeClipRect: %d %dx%d,%dx%d\n",
+    dprintf_clipping(stddeb, "ExcludeClipRect: %d %dx%d,%dx%d\n",
 	    hdc, left, top, right, bottom );
-#endif
     return CLIPPING_IntersectRect( dc, &dc->w.hClipRgn, left, top,
 				   right, bottom, 1 );
 }
@@ -264,10 +257,8 @@
 	return NULLREGION;   /* ?? */
     }
 
-#ifdef DEBUG_CLIPPING
-    printf( "IntersectClipRect: %d %dx%d,%dx%d\n",
+    dprintf_clipping(stddeb, "IntersectClipRect: %d %dx%d,%dx%d\n",
 	    hdc, left, top, right, bottom );
-#endif
     return CLIPPING_IntersectRect( dc, &dc->w.hClipRgn, left, top,
 				   right, bottom, 0 );
 }
@@ -281,10 +272,8 @@
 {
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) return ERROR;    
-#ifdef DEBUG_CLIPPING
-    printf( "ExcludeVisRect: %d %dx%d,%dx%d\n",
+    dprintf_clipping(stddeb, "ExcludeVisRect: %d %dx%d,%dx%d\n",
 	    hdc, left, top, right, bottom );
-#endif
     return CLIPPING_IntersectRect( dc, &dc->w.hVisRgn, left, top,
 				   right, bottom, 1 );
 }
@@ -298,10 +287,8 @@
 {
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) return ERROR;    
-#ifdef DEBUG_CLIPPING
-    printf( "IntersectVisRect: %d %dx%d,%dx%d\n",
+    dprintf_clipping(stddeb, "IntersectVisRect: %d %dx%d,%dx%d\n",
 	    hdc, left, top, right, bottom );
-#endif
     return CLIPPING_IntersectRect( dc, &dc->w.hVisRgn, left, top,
 				   right, bottom, 0 );
 }
@@ -314,11 +301,10 @@
 {
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) return ERROR;    
-#ifdef DEBUG_CLIPPING
-    printf( "PtVisible: %d %d,%d\n", hdc, x, y );
-#endif
-    if (!dc->w.hClipRgn) return FALSE;
-    return PtInRegion( dc->w.hClipRgn, x, y );
+
+    dprintf_clipping(stddeb, "PtVisible: %d %d,%d\n", hdc, x, y );
+    if (!dc->w.hGCClipRgn) return FALSE;
+    return PtInRegion( dc->w.hGCClipRgn, XLPTODP(dc,x), YLPTODP(dc,y) );
 }
 
 
@@ -327,13 +313,16 @@
  */
 BOOL RectVisible( HDC hdc, LPRECT rect )
 {
+    RECT tmpRect;
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
-    if (!dc) return ERROR;    
-#ifdef DEBUG_CLIPPING
-    printf( "RectVisible: %d %p\n", hdc, rect );
-#endif
-    if (!dc->w.hClipRgn) return FALSE;
-    return RectInRegion( dc->w.hClipRgn, rect );
+    if (!dc) return FALSE;
+    dprintf_clipping(stddeb,"RectVisible: %d %p\n", hdc, rect );
+    if (!dc->w.hGCClipRgn) return FALSE;
+    tmpRect.left   = XLPTODP(dc, rect->left);
+    tmpRect.top    = YLPTODP(dc, rect->top);
+    tmpRect.right  = XLPTODP(dc, rect->right);
+    tmpRect.bottom = YLPTODP(dc, rect->bottom);
+    return RectInRegion( dc->w.hGCClipRgn, &tmpRect );
 }
 
 
@@ -344,9 +333,7 @@
 {
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) return ERROR;    
-#ifdef DEBUG_CLIPPING
-    printf( "GetClipBox: %d %p\n", hdc, rect );
-#endif
+    dprintf_clipping(stddeb, "GetClipBox: %d %p\n", hdc, rect );
 
     if (dc->w.hGCClipRgn) return GetRgnBox( dc->w.hGCClipRgn, rect );
     else
@@ -368,9 +355,7 @@
     RGNOBJ *obj, *copyObj;
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) return 0;
-#ifdef DEBUG_CLIPPING
-    printf( "SaveVisRgn: %d\n", hdc );
-#endif
+    dprintf_clipping(stddeb, "SaveVisRgn: %d\n", hdc );
     if (!dc->w.hVisRgn) return 0;
     if (!(obj = (RGNOBJ *) GDI_GetObjPtr( dc->w.hVisRgn, REGION_MAGIC )))
 	return 0;
@@ -393,9 +378,7 @@
     RGNOBJ *obj, *savedObj;
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) return ERROR;    
-#ifdef DEBUG_CLIPPING
-    printf( "RestoreVisRgn: %d\n", hdc );
-#endif
+    dprintf_clipping(stddeb, "RestoreVisRgn: %d\n", hdc );
     if (!dc->w.hVisRgn) return ERROR;
     if (!(obj = (RGNOBJ *) GDI_GetObjPtr( dc->w.hVisRgn, REGION_MAGIC )))
 	return ERROR;
diff --git a/objects/color.c b/objects/color.c
index c6cbddc..acd145f 100644
--- a/objects/color.c
+++ b/objects/color.c
@@ -8,7 +8,7 @@
 
 #include <stdlib.h>
 #include <X11/Xlib.h>
-
+#include <stdio.h>
 #include "windows.h"
 #include "options.h"
 #include "gdi.h"
@@ -128,7 +128,7 @@
 	}
 	else if (!XAllocColor( display, COLOR_WinColormap, &color ))
 	{
-	    printf( "Warning: Not enough free colors. Try using the -privatemap option.\n" );
+	    fprintf(stderr, "Warning: Not enough free colors. Try using the -privatemap option.\n" );
 	    color.pixel = color.red = color.green = color.blue = 0;
 	}
 	colorTranslation[i] = color.pixel;
diff --git a/windows/dc.c b/objects/dc.c
similarity index 92%
rename from windows/dc.c
rename to objects/dc.c
index 9c8a274..5365efb 100644
--- a/windows/dc.c
+++ b/objects/dc.c
@@ -11,6 +11,11 @@
 #include "gdi.h"
 #include "bitmap.h"
 #include "metafile.h"
+#include "stddebug.h"
+/* #define DEBUG_DC /* */
+/* #undef  DEBUG_DC /* */
+#include "debug.h"
+
 
 static DeviceCaps * displayDevCaps = NULL;
 
@@ -94,7 +99,7 @@
  *
  * Setup device-specific DC values for a newly created DC.
  */
-static void DC_InitDC( HDC hdc )
+void DC_InitDC( HDC hdc )
 {
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     RealizeDefaultPalette( hdc );
@@ -103,7 +108,8 @@
     SelectObject( hdc, dc->w.hPen );
     SelectObject( hdc, dc->w.hBrush );
     SelectObject( hdc, dc->w.hFont );
-    XSetGraphicsExposures( XT_display, dc->u.x.gc, False );
+    XSetGraphicsExposures( display, dc->u.x.gc, False );
+    XSetSubwindowMode( display, dc->u.x.gc, IncludeInferiors );
     CLIPPING_SetDeviceClipping( dc );
 }
 
@@ -192,7 +198,7 @@
 
 
 /***********************************************************************
- *           DC_SetupDCForText
+ *           DC_SetupGCForText
  *
  * Setup dc->u.x.gc for text drawing operations.
  * Return 0 if the font is null, 1 otherwise.
@@ -205,7 +211,7 @@
     {
 	FONT_SelectObject(dc, STOCK_SYSTEM_FONT, NULL);
     }
-    val.function   = DC_XROPfunction[dc->w.ROPmode-1];
+    val.function   = GXcopy;  /* Text is always GXcopy */
     val.foreground = dc->w.textPixel;
     val.background = dc->w.backgroundPixel;
     val.fill_style = FillSolid;
@@ -229,9 +235,7 @@
     if (!(handle = GDI_AllocObject( sizeof(DC), DC_MAGIC ))) return 0;
     newdc = (DC *) GDI_HEAP_ADDR( handle );
 
-#ifdef DEBUG_DC
-    printf( "GetDCState(%d): returning %d\n", hdc, handle );
-#endif
+    dprintf_dc(stddeb, "GetDCState(%d): returning %d\n", hdc, handle );
 
     memcpy( &newdc->w, &dc->w, sizeof(dc->w) );
     memcpy( &newdc->u.x.pen, &dc->u.x.pen, sizeof(dc->u.x.pen) );
@@ -264,9 +268,7 @@
     if (!(dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC ))) return;
     if (!(dcs = (DC *) GDI_GetObjPtr( hdcs, DC_MAGIC ))) return;
     if (!dcs->w.flags & DC_SAVED) return;
-#ifdef DEBUG_DC
-    printf( "SetDCState: %d %d\n", hdc, hdcs );
-#endif
+    dprintf_dc(stddeb, "SetDCState: %d %d\n", hdc, hdcs );
     if (dc->w.hClipRgn)	DeleteObject( dc->w.hClipRgn );
     if (dc->w.hVisRgn) DeleteObject( dc->w.hVisRgn );
     if (dc->w.hGCClipRgn) DeleteObject( dc->w.hGCClipRgn );
@@ -305,9 +307,7 @@
     dcs = (DC *) GDI_HEAP_ADDR( hdcs );
     dcs->header.hNext = dc->header.hNext;
     dc->header.hNext = hdcs;
-#ifdef DEBUG_DC
-    printf( "SaveDC(%d): returning %d\n", hdc, dc->saveLevel+1 );
-#endif    
+    dprintf_dc(stddeb, "SaveDC(%d): returning %d\n", hdc, dc->saveLevel+1 );
     return ++dc->saveLevel;
 }
 
@@ -319,9 +319,7 @@
 {
     DC * dc, * dcs;
 
-#ifdef DEBUG_DC
-    printf( "RestoreDC: %d %d\n", hdc, level );
-#endif    
+    dprintf_dc(stddeb, "RestoreDC: %d %d\n", hdc, level );
     dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) 
     {
@@ -358,9 +356,8 @@
     if (!handle) return 0;
     dc = (DC *) GDI_HEAP_ADDR( handle );
 
-#ifdef DEBUG_DC
-    printf( "CreateDC(%s %s %s): returning %d\n", driver, device, output, handle );
-#endif
+    dprintf_dc(stddeb, "CreateDC(%s %s %s): returning %d\n", 
+	    driver, device, output, handle );
 
     if (!displayDevCaps)
     {
@@ -403,28 +400,36 @@
 {
     DC * dc;
     HANDLE handle;
-    
+    HBITMAP hbitmap;
+    BITMAPOBJ *bmp;
+
     handle = GDI_AllocObject( sizeof(DC), DC_MAGIC );
     if (!handle) return 0;
     dc = (DC *) GDI_HEAP_ADDR( handle );
 
-#ifdef DEBUG_DC
-    printf( "CreateCompatibleDC(%d): returning %d\n", hdc, handle );
-#endif
+    dprintf_dc(stddeb, "CreateCompatibleDC(%d): returning %d\n", hdc, handle );
 
+      /* Create default bitmap */
+    if (!(hbitmap = CreateBitmap( 1, 1, 1, 1, NULL )))
+    {
+	GDI_HEAP_FREE( handle );
+	return 0;
+    }
+    bmp = (BITMAPOBJ *) GDI_GetObjPtr( hbitmap, BITMAP_MAGIC );
+    
     dc->saveLevel = 0;
     memcpy( &dc->w, &DCVAL_defaultValues, sizeof(DCVAL_defaultValues) );
     memset( &dc->u.x, 0, sizeof(dc->u.x) );
 
-    dc->u.x.drawable   = XCreatePixmap( display, rootWindow, 1, 1, 1 );
+    dc->u.x.drawable   = bmp->pixmap;
     dc->u.x.gc         = XCreateGC( display, dc->u.x.drawable, 0, NULL );
     dc->w.flags        = DC_MEMORY;
     dc->w.bitsPerPixel = 1;
     dc->w.devCaps      = displayDevCaps;
     dc->w.DCSizeX      = 1;
     dc->w.DCSizeY      = 1;
+    dc->w.hBitmap      = hbitmap;
 
-    SelectObject( handle, BITMAP_hbitmapMemDC );
     DC_InitDC( handle );
 
     return handle;
@@ -439,9 +444,7 @@
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) return FALSE;
 
-#ifdef DEBUG_DC
-    printf( "DeleteDC: %d\n", hdc );
-#endif
+    dprintf_dc(stddeb, "DeleteDC: %d\n", hdc );
 
     while (dc->saveLevel)
     {
@@ -460,7 +463,9 @@
 	SelectObject( hdc, STOCK_SYSTEM_FONT );
 	XFreeGC( display, dc->u.x.gc );
     }
-    
+
+    if (dc->w.flags & DC_MEMORY) DeleteObject( dc->w.hBitmap );
+
     if (dc->w.hClipRgn) DeleteObject( dc->w.hClipRgn );
     if (dc->w.hVisRgn) DeleteObject( dc->w.hVisRgn );
     if (dc->w.hGCClipRgn) DeleteObject( dc->w.hGCClipRgn );
@@ -479,10 +484,8 @@
 
     if (cap > sizeof(DeviceCaps)-sizeof(WORD)) return 0;
     
-#ifdef DEBUG_DC
-    printf( "GetDeviceCaps(%d,%d): returning %d\n",
+    dprintf_dc(stddeb, "GetDeviceCaps(%d,%d): returning %d\n",
 	    hdc, cap, *(WORD *)(((char *)dc->w.devCaps) + cap) );
-#endif
     return *(WORD *)(((char *)dc->w.devCaps) + cap);
 }
 
diff --git a/objects/dib.c b/objects/dib.c
index 6042cb2..a37509b 100644
--- a/objects/dib.c
+++ b/objects/dib.c
@@ -13,6 +13,12 @@
 #include "gdi.h"
 #include "bitmap.h"
 #include "icon.h"
+#include "stddebug.h"
+/* #define DEBUG_ICON /* */
+/* #undef  DEBUG_ICON /* */
+#include "debug.h"
+
+extern const int DC_XROPfunction[];
 
 extern WORD COLOR_ToPhysical( DC *dc, COLORREF color );  /* color.c */
 
@@ -424,7 +430,8 @@
     if (xSrc+cx >= info->bmiHeader.biWidth) cx = info->bmiHeader.biWidth-xSrc;
     if (!cx || !cy) return 0;
 
-    DC_SetupGCForText( dc );  /* To have the correct ROP */
+    DC_SetupGCForText( dc );  /* To have the correct colors */
+    XSetFunction( display, dc->u.x.gc, DC_XROPfunction[dc->w.ROPmode-1] );
     return DIB_SetImageBits( dc, lines, dc->w.bitsPerPixel,
 			     bits, info, coloruse,
 			     dc->u.x.drawable, dc->u.x.gc,
@@ -521,33 +528,36 @@
     HBITMAP	hBitTemp;
     HDC		hMemDC;
     HDC		hMemDC2;
-#ifdef DEBUG_ICON
-    printf("DrawIcon(%04X, %d, %d, %04X) \n", hDC, x, y, hIcon);
-#endif
+    dprintf_icon(stddeb,"DrawIcon(%04X, %d, %d, %04X) \n", hDC, x, y, hIcon);
     if (hIcon == (HICON)NULL) return FALSE;
     lpico = (ICONALLOC *)GlobalLock(hIcon);
     GetObject(lpico->hBitmap, sizeof(BITMAP), (LPSTR)&bm);
-#ifdef DEBUG_ICON
-    printf("DrawIcon / x=%d y=%d\n", x, y);
-    printf("DrawIcon / icon Width=%d\n", (int)lpico->descriptor.Width);
-    printf("DrawIcon / icon Height=%d\n", (int)lpico->descriptor.Height);
-    printf("DrawIcon / icon ColorCount=%d\n", (int)lpico->descriptor.ColorCount);
-    printf("DrawIcon / icon icoDIBSize=%lX\n", (DWORD)lpico->descriptor.icoDIBSize);
-    printf("DrawIcon / icon icoDIBOffset=%lX\n", (DWORD)lpico->descriptor.icoDIBOffset);
-    printf("DrawIcon / bitmap bmWidth=%d bmHeight=%d\n", bm.bmWidth, bm.bmHeight);
-#endif
+    dprintf_icon(stddeb,"DrawIcon / x=%d y=%d\n", x, y);
+    dprintf_icon(stddeb,"DrawIcon / icon Width=%d\n", 
+		 (int)lpico->descriptor.Width);
+    dprintf_icon(stddeb,"DrawIcon / icon Height=%d\n", 
+		 (int)lpico->descriptor.Height);
+    dprintf_icon(stddeb,"DrawIcon / icon ColorCount=%d\n", 
+		 (int)lpico->descriptor.ColorCount);
+    dprintf_icon(stddeb,"DrawIcon / icon icoDIBSize=%lX\n", 
+		 (DWORD)lpico->descriptor.icoDIBSize);
+    dprintf_icon(stddeb,"DrawIcon / icon icoDIBOffset=%lX\n", 
+		 (DWORD)lpico->descriptor.icoDIBOffset);
+    dprintf_icon(stddeb,"DrawIcon / bitmap bmWidth=%d bmHeight=%d\n", 
+		 bm.bmWidth, bm.bmHeight);
     hMemDC = CreateCompatibleDC(hDC);
 #ifdef DEBUG_ICON
-    SelectObject(hMemDC, lpico->hBitmap);
+    hBitTemp = SelectObject(hMemDC, lpico->hBitmap);
     BitBlt(hDC, x, y, bm.bmWidth, bm.bmHeight, hMemDC, 0, 0, SRCCOPY);
     SelectObject(hMemDC, lpico->hBitMask);
     BitBlt(hDC, x, y + bm.bmHeight, bm.bmWidth, bm.bmHeight, hMemDC, 0, 0, SRCCOPY);
 #else
-    SelectObject(hMemDC, lpico->hBitMask);
+    hBitTemp = SelectObject(hMemDC, lpico->hBitMask);
     BitBlt(hDC, x, y, bm.bmWidth, bm.bmHeight, hMemDC, 0, 0, SRCAND);
     SelectObject(hMemDC, lpico->hBitmap);
     BitBlt(hDC, x, y, bm.bmWidth, bm.bmHeight, hMemDC, 0, 0, SRCPAINT);
 #endif
+    SelectObject( hMemDC, hBitTemp );
     DeleteDC(hMemDC);
     return TRUE;
 }
diff --git a/objects/font.c b/objects/font.c
index 3f3b4cb..1a28d6c 100644
--- a/objects/font.c
+++ b/objects/font.c
@@ -12,6 +12,10 @@
 #include <X11/Xatom.h>
 #include "user.h"
 #include "gdi.h"
+#include "stddebug.h"
+/* #define DEBUG_FONT /* */
+/* #undef  DEBUG_FONT /* */
+#include "debug.h"
 
 #define MAX_FONTS	256
 static LPLOGFONT lpLogFontList[MAX_FONTS] = { NULL };
@@ -44,6 +48,38 @@
 #define CI_GET_DEFAULT_INFO(fs,cs) \
   CI_GET_CHAR_INFO(fs, fs->default_char, NULL, cs)
 
+
+/***********************************************************************
+ *           FONT_TranslateName
+ *
+ * Translate a Windows face name to its X11 equivalent.
+ * This will probably have to be customizable.
+ */
+static const char *FONT_TranslateName( char *winFaceName )
+{
+    int i;
+    static const char *mappings[] =
+    {
+        /*Windows name*/  /*X11 name*/
+        "system",         "helvetica",
+        "ms sans serif",  "helvetica",
+        "ms serif",       "times",
+        "fixedsys",       "fixed",
+        "arial",          "helvetica",
+        "helv",           "helvetica",
+        "roman",          "times"
+    };
+
+    for (i = 0; i < sizeof(mappings)/sizeof(mappings[0]); i += 2)
+        if (!strcmp( winFaceName, mappings[i] ))
+        {
+            dprintf_font(stddeb, "---- Mapped %s to %s\n", winFaceName, mappings[i+1] );
+            return mappings[i+1];
+        }
+    return winFaceName;
+}
+
+
 /***********************************************************************
  *           FONT_MatchFont
  *
@@ -52,7 +88,7 @@
 static XFontStruct * FONT_MatchFont( LOGFONT * font )
 {
     char pattern[100];
-    char *family, *weight, *charset;
+    const char *family, *weight, *charset;
     char **names;
     char slant, spacing;
     int width, height, count;
@@ -60,13 +96,13 @@
     
     weight = (font->lfWeight > 550) ? "bold" : "medium";
     slant = font->lfItalic ? 'i' : 'r';
-    height = font->lfHeight * 10;
+    height = abs(font->lfHeight * 10);
     width = font->lfWidth * 10;
     spacing = (font->lfPitchAndFamily & FIXED_PITCH) ? 'm' :
 	      (font->lfPitchAndFamily & VARIABLE_PITCH) ? 'p' : '*';
     charset = (font->lfCharSet == ANSI_CHARSET) ? "iso8859-1" : "*";
-    family = font->lfFaceName;
-    if (!*family) switch(font->lfPitchAndFamily & 0xf0)
+    if (*font->lfFaceName) family = FONT_TranslateName( font->lfFaceName );
+    else switch(font->lfPitchAndFamily & 0xf0)
     {
       case FF_ROMAN:      family = "times"; break;
       case FF_SWISS:      family = "helvetica"; break;
@@ -75,36 +111,28 @@
       case FF_DECORATIVE: family = "*"; break;
       default:            family = "*"; break;
     }
-    else 
-	AnsiLower(family);
     
 	while (TRUE) {
 	    /* Width==0 seems not to be a valid wildcard on SGI's, using * instead */
 	    if ( width == 0 )
-	      sprintf( pattern, "-*-%s-%s-%c-normal--*-%d-*-*-%c-*-%s",
+	      sprintf( pattern, "-*-%s-%s-%c-normal-*-*-%d-*-*-%c-*-%s",
 		      family, weight, slant, height, spacing, charset);
 	    else
-	      sprintf( pattern, "-*-%s-%s-%c-normal--*-%d-*-*-%c-%d-%s",
+	      sprintf( pattern, "-*-%s-%s-%c-normal-*-*-%d-*-*-%c-%d-%s",
 		      family, weight, slant, height, spacing, width, charset);
-#ifdef DEBUG_FONT
-	    printf( "FONT_MatchFont: '%s'\n", pattern );
-#endif
-	    names = XListFonts( XT_display, pattern, 1, &count );
+	    dprintf_font(stddeb, "FONT_MatchFont: '%s'\n", pattern );
+	    names = XListFonts( display, pattern, 1, &count );
 	    if (count > 0) break;
-		height -= 10;		
-		if (height < 10) {
-#ifdef DEBUG_FONT
-			printf( "        No matching font found\n" );	
-#endif
-			return NULL;
-		    }
-		}
-#ifdef DEBUG_FONT
-	printf( "        Found '%s'\n", *names );
-#endif
-	fontStruct = XLoadQueryFont( XT_display, *names );
-	XFreeFontNames( names );
-	return fontStruct;
+            height -= 10;		
+            if (height < 10) {
+                dprintf_font(stddeb,"*** No match for %s\n", pattern );
+                return NULL;
+            }
+        }
+    dprintf_font(stddeb,"        Found '%s'\n", *names );
+    fontStruct = XLoadQueryFont( display, *names );
+    XFreeFontNames( names );
+    return fontStruct;
 }
 
 
@@ -170,9 +198,8 @@
     if (!hfont) return 0;
     fontPtr = (FONTOBJ *) GDI_HEAP_ADDR( hfont );
     memcpy( &fontPtr->logfont, font, sizeof(LOGFONT) );
-#ifdef DEBUG_FONT
-	printf("CreateFontIndirect(%08X); return %04X !\n", font, hfont);
-#endif
+    AnsiLower( fontPtr->logfont.lfFaceName );
+    dprintf_font(stddeb,"CreateFontIndirect(%08X); return %04X\n",font,hfont);
     return hfont;
 }
 
@@ -212,9 +239,8 @@
     X_PHYSFONT * stockPtr;
     HFONT prevHandle = dc->w.hFont;
     XFontStruct * fontStruct;
-#ifdef DEBUG_FONT
-	printf("FONT_SelectObject(%04X, %04X, %08X); !\n", dc, hfont, font);
-#endif
+    dprintf_font(stddeb,"FONT_SelectObject(%04X, %04X, %08X); !\n", 
+		     dc, hfont, font);
       /* Load font if necessary */
 
     if (!font)
@@ -242,10 +268,9 @@
     else
     {
 	fontStruct = stockPtr->fstruct;
-#ifdef DEBUG_FONT
-	printf( "FONT_SelectObject: Loaded font from cache %x %p\n",
-	        hfont, fontStruct );
-#endif
+	dprintf_font(stddeb, 
+		     "FONT_SelectObject: Loaded font from cache %x %p\n",
+		     hfont, fontStruct );
     }	
     if (!fontStruct) return 0;
 
@@ -254,7 +279,7 @@
     if ((prevHandle < FIRST_STOCK_FONT) || (prevHandle > LAST_STOCK_FONT))
     {
 	if (dc->u.x.font.fstruct)
-	    XFreeFont( XT_display, dc->u.x.font.fstruct );
+	    XFreeFont( display, dc->u.x.font.fstruct );
     }
 
       /* Store font */
@@ -332,6 +357,23 @@
 
 
 /***********************************************************************
+ *           GetTextFace    (GDI.92)
+ */
+INT GetTextFace( HDC hdc, INT count, LPSTR name )
+{
+    FONTOBJ *font;
+
+    DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
+    if (!dc) return 0;
+    if (!(font = (FONTOBJ *) GDI_GetObjPtr( dc->w.hFont, FONT_MAGIC )))
+        return 0;
+    strncpy( name, font->logfont.lfFaceName, count );
+    name[count-1] = '\0';
+    return strlen(name);
+}
+
+
+/***********************************************************************
  *           GetTextExtent    (GDI.91)
  */
 DWORD GetTextExtent( HDC hdc, LPSTR str, short count )
@@ -359,10 +401,8 @@
     size->cy = abs((dc->u.x.font.fstruct->ascent+dc->u.x.font.fstruct->descent)
 		    * dc->w.WndExtY / dc->w.VportExtY);
 
-#ifdef DEBUG_FONT
-    printf( "GetTextExtentPoint(%d '%s' %d %p): returning %d,%d\n",
+    dprintf_font(stddeb,"GetTextExtentPoint(%d '%s' %d %p): returning %d,%d\n",
 	    hdc, str, count, size, size->cx, size->cy );
-#endif
     return TRUE;
 }
 
@@ -398,7 +438,8 @@
  */
 DWORD SetMapperFlags(HDC hDC, DWORD dwFlag)
 {
-    printf("SetmapperFlags(%04X, %08X) // Empty Stub !\n", hDC, dwFlag); 
+    dprintf_font(stdnimp,"SetmapperFlags(%04X, %08X) // Empty Stub !\n", 
+		 hDC, dwFlag); 
     return 0L;
 }
 
@@ -445,10 +486,8 @@
 int ParseFontParms(LPSTR lpFont, WORD wParmsNo, LPSTR lpRetStr, WORD wMaxSiz)
 {
 	int 	i, j;
-#ifdef DEBUG_FONT
-	printf("ParseFontParms('%s', %d, %08X, %d);\n", 
+	dprintf_font(stddeb,"ParseFontParms('%s', %d, %08X, %d);\n", 
 			lpFont, wParmsNo, lpRetStr, wMaxSiz);
-#endif
 	if (lpFont == NULL) return 0;
 	if (lpRetStr == NULL) return 0;
 	for (i = 0; (*lpFont != '\0' && i != wParmsNo); ) {
@@ -461,9 +500,7 @@
 		for (i = 0; (*lpFont != '\0' && *lpFont != '-' && i < wMaxSiz); i++)
 			*(lpRetStr + i) = *lpFont++;
 		*(lpRetStr + i) = '\0';
-#ifdef DEBUG_FONT
-		printf("ParseFontParms // '%s'\n", lpRetStr);
-#endif
+		dprintf_font(stddeb,"ParseFontParms // '%s'\n", lpRetStr);
 		return i;
 		}
 	else
@@ -489,22 +526,18 @@
     spacing = '*';
     charset = "*";
     family = "*";
-	printf("InitFontsList !\n");
-    sprintf( pattern, "-*-%s-%s-%c-normal--*-*-*-*-%c-*-%s",
+    dprintf_font(stddeb,"InitFontsList !\n");
+    sprintf( pattern, "-*-%s-%s-%c-normal-*-*-*-*-*-%c-*-%s",
 	      family, weight, slant, spacing, charset);
-    names = XListFonts( XT_display, pattern, MAX_FONTS, &count );
-#ifdef DEBUG_FONT
-	printf("InitFontsList // count=%d \n", count);
-#endif
+    names = XListFonts( display, pattern, MAX_FONTS, &count );
+    dprintf_font(stddeb,"InitFontsList // count=%d \n", count);
 	for (i = 0; i < count; i++) {
 		lpNewFont = malloc(sizeof(LOGFONT) + LF_FACESIZE);
 		if (lpNewFont == NULL) {
-			printf("InitFontsList // Error alloc new font structure !\n");
+			dprintf_font(stddeb, "InitFontsList // Error alloc new font structure !\n");
 			break;
 			}
-#ifdef DEBUG_FONT
-		printf("InitFontsList // names[%d]='%s' \n", i, names[i]);
-#endif
+		dprintf_font(stddeb,"InitFontsList // names[%d]='%s' \n", i, names[i]);
 		ParseFontParms(names[i], 2, str, sizeof(str));
 		if (strcmp(str, "fixed") == 0) strcat(str, "sys");
 		AnsiUpper(str);
@@ -539,11 +572,9 @@
 				lpNewFont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
 				break;
 			}
-#ifdef DEBUG_FONT
-		printf("InitFontsList // lpNewFont->lfHeight=%d \n", lpNewFont->lfHeight);
-		printf("InitFontsList // lpNewFont->lfWidth=%d \n", lpNewFont->lfWidth);
-		printf("InitFontsList // lfFaceName='%s' \n", lpNewFont->lfFaceName);
-#endif
+		dprintf_font(stddeb,"InitFontsList // lpNewFont->lfHeight=%d \n", lpNewFont->lfHeight);
+		dprintf_font(stddeb,"InitFontsList // lpNewFont->lfWidth=%d \n", lpNewFont->lfWidth);
+		dprintf_font(stddeb,"InitFontsList // lfFaceName='%s' \n", lpNewFont->lfFaceName);
 		lpLogFontList[i] = lpNewFont;
 		lpLogFontList[i+1] = NULL;
 		}
@@ -566,20 +597,21 @@
 	char			FaceName[LF_FACESIZE];
 	int				nRet;
 	int				j, i = 0;
-	printf("EnumFonts(%04X, %08X='%s', %08X, %08X)\n", 
+
+	dprintf_font(stddeb,"EnumFonts(%04X, %08X='%s', %08X, %08X)\n", 
 		hDC, lpFaceName, lpFaceName, lpEnumFunc, lpData);
 	if (lpEnumFunc == NULL) return 0;
 	hLog = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(LOGFONT) + LF_FACESIZE);
 	lpLogFont = (LPLOGFONT) USER_HEAP_ADDR(hLog);
 	if (lpLogFont == NULL) {
-		printf("EnumFonts // can't alloc LOGFONT struct !\n");
+		dprintf_font(stddeb,"EnumFonts // can't alloc LOGFONT struct !\n");
 		return 0;
 		}
 	hMet = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(TEXTMETRIC));
 	lptm = (LPTEXTMETRIC) USER_HEAP_ADDR(hMet);
 	if (lptm == NULL) {
 		USER_HEAP_FREE(hLog);
-		printf("EnumFonts // can't alloc TEXTMETRIC struct !\n");
+		dprintf_font(stddeb, "EnumFonts // can't alloc TEXTMETRIC struct !\n");
 		return 0;
 		}
 	if (lpFaceName != NULL) {
@@ -600,7 +632,7 @@
 				}
 			if (lpLogFontList[i] == NULL) break;
 			lpFaceList[j] = lpLogFontList[i]->lfFaceName;
-			printf("EnumFonts // enum all 'lpFaceName' '%s' !\n", lpFaceList[j]);
+			dprintf_font(stddeb,"EnumFonts // enum all 'lpFaceName' '%s' !\n", lpFaceList[j]);
 			}
 		else {
 			while(lpLogFontList[i] != NULL) {
@@ -615,7 +647,8 @@
 		GetTextMetrics(hDC, lptm);
 		SelectObject(hDC, hOldFont);
 		DeleteObject(hFont);
-		printf("EnumFonts // i=%d lpLogFont=%08X lptm=%08X\n", i, lpLogFont, lptm);
+		dprintf_font(stddeb,"EnumFonts // i=%d lpLogFont=%08X lptm=%08X\n", i, lpLogFont, lptm);
+
 #ifdef WINELIB
 		nRet = (*lpEnumFunc)(lpLogFont, lptm, 0, lpData);
 #else
@@ -623,7 +656,7 @@
 					2, (int)lptm, 0, (int)0, 2, (int)lpData);
 #endif
 		if (nRet == 0) {
-			printf("EnumFonts // EnumEnd requested by application !\n");
+			dprintf_font(stddeb,"EnumFonts // EnumEnd requested by application !\n");
 			break;
 			}
 		}
@@ -648,20 +681,21 @@
 	char			FaceName[LF_FACESIZE];
 	int				nRet;
 	int				j, i = 0;
-	printf("EnumFontFamilies(%04X, %08X, %08X, %08X)\n", 
+
+	dprintf_font(stddeb,"EnumFontFamilies(%04X, %08X, %08X, %08X)\n", 
 					hDC, lpszFamily, lpEnumFunc, lpData);
 	if (lpEnumFunc == NULL) return 0;
 	hLog = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(LOGFONT) + LF_FACESIZE);
 	lpLogFont = (LPLOGFONT) USER_HEAP_ADDR(hLog);
 	if (lpLogFont == NULL) {
-		printf("EnumFontFamilies // can't alloc LOGFONT struct !\n");
+		dprintf_font(stddeb,"EnumFontFamilies // can't alloc LOGFONT struct !\n");
 		return 0;
 		}
 	hMet = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(TEXTMETRIC));
 	lptm = (LPTEXTMETRIC) USER_HEAP_ADDR(hMet);
 	if (lptm == NULL) {
 		USER_HEAP_FREE(hLog);
-		printf("EnumFontFamilies // can't alloc TEXTMETRIC struct !\n");
+		dprintf_font(stddeb,"EnumFontFamilies // can't alloc TEXTMETRIC struct !\n");
 		return 0;
 		}
 	if (lpszFamily != NULL) {
@@ -683,7 +717,7 @@
 				}
 			if (lpLogFontList[i] == NULL) break;
 			lpFaceList[j] = lpLogFontList[i]->lfFaceName;
-			printf("EnumFontFamilies // enum all 'lpszFamily' '%s' !\n", lpFaceList[j]);
+			dprintf_font(stddeb,"EnumFontFamilies // enum all 'lpszFamily' '%s' !\n", lpFaceList[j]);
 			}
 		else {
 			while(lpLogFontList[i] != NULL) {
@@ -698,7 +732,8 @@
 		GetTextMetrics(hDC, lptm);
 		SelectObject(hDC, hOldFont);
 		DeleteObject(hFont);
-		printf("EnumFontFamilies // i=%d lpLogFont=%08X lptm=%08X\n", i, lpLogFont, lptm);
+		dprintf_font(stddeb, "EnumFontFamilies // i=%d lpLogFont=%08X lptm=%08X\n", i, lpLogFont, lptm);
+
 #ifdef WINELIB
 		nRet = (*lpEnumFunc)(lpLogFont, lptm, 0, lpData);
 #else
@@ -706,7 +741,7 @@
 					2, (int)lptm, 0, (int)0, 2, (int)lpData);
 #endif
 		if (nRet == 0) {
-			printf("EnumFontFamilies // EnumEnd requested by application !\n");
+			dprintf_font(stddeb,"EnumFontFamilies // EnumEnd requested by application !\n");
 			break;
 			}
 		}
diff --git a/objects/gdiobj.c b/objects/gdiobj.c
index 7937282..e521619 100644
--- a/objects/gdiobj.c
+++ b/objects/gdiobj.c
@@ -11,6 +11,10 @@
 #include "user.h"
 #include "gdi.h"
 #include "prototypes.h"
+#include "stddebug.h"
+/* #define DEBUG_GDI /* */
+/* #undef  DEBUG_GDI /* */
+#include "debug.h"
 
 MDESC *GDI_Heap = NULL;
 
@@ -196,17 +200,13 @@
 	if (lpPenBrushList == NULL) {
 		lpPenBrushList = malloc(MAX_OBJ * sizeof(HANDLE));
 		lpPenBrushList[0] = 0;
-#ifdef DEBUG_GDI
-		printf("GDI_AppendToPenBrushList() lpPenBrushList allocated !\n");
-#endif
+		dprintf_gdi(stddeb,"GDI_AppendToPenBrushList() lpPenBrushList allocated !\n");
 		}
 	for (lphObj = lpPenBrushList; i < MAX_OBJ; i++) {
 		if (*lphObj == 0) {
 			*lphObj = hNewObj;
 			*(lphObj + 1) = 0;
-#ifdef DEBUG_GDI
-			printf("GDI_AppendToPenBrushList(%04X) appended (count=%d)\n", hNewObj, i);
-#endif
+			dprintf_gdi(stddeb,"GDI_AppendToPenBrushList(%04X) appended (count=%d)\n", hNewObj, i);
 			return TRUE;
 			}
 		lphObj++;
@@ -244,7 +244,7 @@
     if (!handle) return 0;
     obj = (GDIOBJHDR *) GDI_HEAP_ADDR( handle );
     if (obj == NULL) {
-    	printf("GDI_AllocObject // Error trying to get GDI_HEAD_ADDR !\n");
+    	fprintf(stderr,"GDI_AllocObject // Error trying to get GDI_HEAD_ADDR !\n");
     	return 0;
     	}
     obj->hNext   = 0;
@@ -265,10 +265,11 @@
     GDIOBJHDR * object;
 
       /* Can't free stock objects */
-    if (handle >= FIRST_STOCK_HANDLE) return FALSE;
+    if (handle >= FIRST_STOCK_HANDLE) return TRUE;
     
     object = (GDIOBJHDR *) GDI_HEAP_ADDR( handle );
     if (!object) return FALSE;
+    object->wMagic = 0;  /* Mark it as invalid */
 
       /* Free object */
     
@@ -308,9 +309,7 @@
     GDIOBJHDR * header = (GDIOBJHDR *) GDI_HEAP_ADDR( obj );
     if (!header) return FALSE;
 
-#ifdef DEBUG_GDI
-    printf( "DeleteObject: %d\n", obj );
-#endif
+    dprintf_gdi(stddeb, "DeleteObject: %d\n", obj );
 
       /* Delete object */
 
@@ -334,9 +333,8 @@
 {
     if ((obj < 0) || (obj >= NB_STOCK_OBJECTS)) return 0;
     if (!StockObjects[obj]) return 0;
-#ifdef DEBUG_GDI
-    printf( "GetStockObject: returning %04x\n", FIRST_STOCK_HANDLE + obj );
-#endif
+    dprintf_gdi(stddeb, "GetStockObject: returning %04x\n", 
+		FIRST_STOCK_HANDLE + obj );
     return FIRST_STOCK_HANDLE + obj;
 }
 
@@ -347,9 +345,7 @@
 int GetObject( HANDLE handle, int count, LPSTR buffer )
 {
     GDIOBJHDR * ptr = NULL;
-#ifdef DEBUG_GDI
-    printf( "GetObject: %04x %d %08x\n", handle, count, buffer );
-#endif
+    dprintf_gdi(stddeb, "GetObject: %04x %d %08x\n", handle, count, buffer );
     if (!count) return 0;
 
     if (handle >= FIRST_STOCK_HANDLE)
@@ -385,9 +381,7 @@
     GDIOBJHDR * ptr = NULL;
     DC * dc;
     
-#ifdef DEBUG_GDI
-    printf( "SelectObject: %d %04x\n", hdc, handle );
-#endif
+    dprintf_gdi(stddeb, "SelectObject: %d %04x\n", hdc, handle );
     if (handle >= FIRST_STOCK_HANDLE)
     {
 	if (handle < FIRST_STOCK_HANDLE + NB_STOCK_OBJECTS)
@@ -425,9 +419,7 @@
  */
 BOOL UnrealizeObject( HANDLE handle )
 {
-#ifdef DEBUG_GDI
-    printf( "UnrealizeObject: %04x\n", handle );
-#endif
+    dprintf_gdi(stdnimp, "UnrealizeObject: %04x\n", handle );
     return TRUE;
 }
 
@@ -446,53 +438,53 @@
 	HANDLE 		hLog;
 	int			i, nRet;
 	if (lpEnumFunc == NULL) {
-		printf("EnumObjects // Bad EnumProc callback address !\n");
+		fprintf(stderr,"EnumObjects // Bad EnumProc callback address !\n");
 		return 0;
 		}
 	switch (nObjType) {
 		case OBJ_PEN:
 			wMagic = PEN_MAGIC;
-			printf("EnumObjects(%04X, OBJ_PEN, %08X, %08X);\n", 
+			dprintf_gdi(stddeb,"EnumObjects(%04X, OBJ_PEN, %08X, %08X);\n", 
 									hDC, lpEnumFunc, lpData);
 			hLog = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(LOGPEN));
 			lpLog = (LPSTR) USER_HEAP_ADDR(hLog);
 			if (lpLog == NULL) {
-				printf("EnumObjects // Unable to alloc LOGPEN struct !\n");
+				fprintf(stderr,"EnumObjects // Unable to alloc LOGPEN struct !\n");
 				return 0;
 				}
 			break;
 		case OBJ_BRUSH:
 			wMagic = BRUSH_MAGIC;
-			printf("EnumObjects(%04X, OBJ_BRUSH, %08X, %08X);\n", 
+			dprintf_gdi(stddeb,"EnumObjects(%04X, OBJ_BRUSH, %08X, %08X);\n", 
 									hDC, lpEnumFunc, lpData);
 			hLog = USER_HEAP_ALLOC(GMEM_MOVEABLE, sizeof(LOGBRUSH));
 			lpLog = (LPSTR) USER_HEAP_ADDR(hLog);
 			if (lpLog == NULL) {
-				printf("EnumObjects // Unable to alloc LOGBRUSH struct !\n");
+				fprintf(stderr,"EnumObjects // Unable to alloc LOGBRUSH struct !\n");
 				return 0;
 				}
 			break;
 		default:
-			printf("EnumObjects(%04X, %04X, %08X, %08X); // Unknown OBJ type !\n", 
+			fprintf(stderr,"EnumObjects(%04X, %04X, %08X, %08X); // Unknown OBJ type !\n", 
 						hDC, nObjType, lpEnumFunc, lpData);
 			return 0;
 		}
-	printf("EnumObjects // Stock Objects first !\n");
+	dprintf_gdi(stddeb,"EnumObjects // Stock Objects first !\n");
 	for (i = 0; i < NB_STOCK_OBJECTS; i++) {
 		header = StockObjects[i];
 		if (header->wMagic == wMagic) {
 			PEN_GetObject( (PENOBJ *)header, sizeof(LOGPEN), (LPLOGPEN)lpLog);
 			BRUSH_GetObject( (BRUSHOBJ *)header, sizeof(LOGBRUSH), (LPLOGBRUSH)lpLog);
-			printf("EnumObjects // StockObj lpLog=%08X lpData=%08X\n", lpLog, lpData);
+			dprintf_gdi(stddeb,"EnumObjects // StockObj lpLog=%08X lpData=%08X\n", lpLog, lpData);
 			if (header->wMagic == BRUSH_MAGIC) {
-				printf("EnumObjects // StockBrush lbStyle=%04X\n", ((LPLOGBRUSH)lpLog)->lbStyle);
-				printf("EnumObjects // StockBrush lbColor=%08X\n", ((LPLOGBRUSH)lpLog)->lbColor);
-				printf("EnumObjects // StockBrush lbHatch=%04X\n", ((LPLOGBRUSH)lpLog)->lbHatch);
+				dprintf_gdi(stddeb,"EnumObjects // StockBrush lbStyle=%04X\n", ((LPLOGBRUSH)lpLog)->lbStyle);
+				dprintf_gdi(stddeb,"EnumObjects // StockBrush lbColor=%08X\n", ((LPLOGBRUSH)lpLog)->lbColor);
+				dprintf_gdi(stddeb,"EnumObjects // StockBrush lbHatch=%04X\n", ((LPLOGBRUSH)lpLog)->lbHatch);
 				}
 			if (header->wMagic == PEN_MAGIC) {
-				printf("EnumObjects // StockPen lopnStyle=%04X\n", ((LPLOGPEN)lpLog)->lopnStyle);
-				printf("EnumObjects // StockPen lopnWidth=%08X\n", ((LPLOGPEN)lpLog)->lopnWidth);
-				printf("EnumObjects // StockPen lopnColor=%08X\n", ((LPLOGPEN)lpLog)->lopnColor);
+				dprintf_gdi(stddeb,"EnumObjects // StockPen lopnStyle=%04X\n", ((LPLOGPEN)lpLog)->lopnStyle);
+				dprintf_gdi(stddeb,"EnumObjects // StockPen lopnWidth=%08X\n", ((LPLOGPEN)lpLog)->lopnWidth);
+				dprintf_gdi(stddeb,"EnumObjects // StockPen lopnColor=%08X\n", ((LPLOGPEN)lpLog)->lopnColor);
 				}
 			nRet = 1;
 /*
@@ -502,36 +494,32 @@
 			nRet = CallBack16(lpEnumFunc, 4, 2, (int)lpLog,	2, (int)lpData);
 #endif
 */
-			printf("EnumObjects // after CallBack16 !\n");
+			dprintf_gdi(stddeb,"EnumObjects // after CallBack16 !\n");
 			if (nRet == 0) {
 				USER_HEAP_FREE(hLog);
-				printf("EnumObjects // EnumEnd requested by application !\n");
+				dprintf_gdi(stddeb,"EnumObjects // EnumEnd requested by application !\n");
 				return 0;
 				}
 			}
 		}
 	if (lpPenBrushList == NULL) return 0;
-	printf("EnumObjects // Now DC owned objects %08X !\n", header);
+	dprintf_gdi(stddeb,"EnumObjects // Now DC owned objects %08X !\n", header);
 	for (lphObj = lpPenBrushList; *lphObj != 0; ) {
-#ifdef DEBUG_GDI
-		printf("EnumObjects // *lphObj=%04X\n", *lphObj);
-#endif
+		dprintf_gdi(stddeb,"EnumObjects // *lphObj=%04X\n", *lphObj);
 		header = (GDIOBJHDR *) GDI_HEAP_ADDR(*lphObj++);
 		if (header->wMagic == wMagic) {
-#ifdef DEBUG_GDI
-			printf("EnumObjects // DC_Obj lpLog=%08X lpData=%08X\n", lpLog, lpData);
-#endif
+			dprintf_gdi(stddeb,"EnumObjects // DC_Obj lpLog=%08X lpData=%08X\n", lpLog, lpData);
 			if (header->wMagic == BRUSH_MAGIC) {
 				BRUSH_GetObject( (BRUSHOBJ *)header, sizeof(LOGBRUSH), (LPLOGBRUSH)lpLog);
-				printf("EnumObjects // DC_Brush lbStyle=%04X\n", ((LPLOGBRUSH)lpLog)->lbStyle);
-				printf("EnumObjects // DC_Brush lbColor=%08X\n", ((LPLOGBRUSH)lpLog)->lbColor);
-				printf("EnumObjects // DC_Brush lbHatch=%04X\n", ((LPLOGBRUSH)lpLog)->lbHatch);
+				dprintf_gdi(stddeb,"EnumObjects // DC_Brush lbStyle=%04X\n", ((LPLOGBRUSH)lpLog)->lbStyle);
+				dprintf_gdi(stddeb,"EnumObjects // DC_Brush lbColor=%08X\n", ((LPLOGBRUSH)lpLog)->lbColor);
+				dprintf_gdi(stddeb,"EnumObjects // DC_Brush lbHatch=%04X\n", ((LPLOGBRUSH)lpLog)->lbHatch);
 				}
 			if (header->wMagic == PEN_MAGIC) {
 				PEN_GetObject( (PENOBJ *)header, sizeof(LOGPEN), (LPLOGPEN)lpLog);
-				printf("EnumObjects // DC_Pen lopnStyle=%04X\n", ((LPLOGPEN)lpLog)->lopnStyle);
-				printf("EnumObjects // DC_Pen lopnWidth=%08X\n", ((LPLOGPEN)lpLog)->lopnWidth);
-				printf("EnumObjects // DC_Pen lopnColor=%08X\n", ((LPLOGPEN)lpLog)->lopnColor);
+				dprintf_gdi(stddeb,"EnumObjects // DC_Pen lopnStyle=%04X\n", ((LPLOGPEN)lpLog)->lopnStyle);
+				dprintf_gdi(stddeb,"EnumObjects // DC_Pen lopnWidth=%08X\n", ((LPLOGPEN)lpLog)->lopnWidth);
+				dprintf_gdi(stddeb,"EnumObjects // DC_Pen lopnColor=%08X\n", ((LPLOGPEN)lpLog)->lopnColor);
 				}
 /*
 #ifdef WINELIB
@@ -541,16 +529,16 @@
 #endif
 */
 			nRet = 1;
-			printf("EnumObjects // after CallBack16 !\n");
+			dprintf_gdi(stddeb,"EnumObjects // after CallBack16 !\n");
 			if (nRet == 0) {
 				USER_HEAP_FREE(hLog);
-				printf("EnumObjects // EnumEnd requested by application !\n");
+				dprintf_gdi(stddeb,"EnumObjects // EnumEnd requested by application !\n");
 				return 0;
 				}
 			}
 		}
 	USER_HEAP_FREE(hLog);
-	printf("EnumObjects // End of enumeration !\n");
+	dprintf_gdi(stddeb,"EnumObjects // End of enumeration !\n");
 	return 0;
 }
 
diff --git a/objects/metafile.c b/objects/metafile.c
index fd9c3ae..83cf4c4 100644
--- a/objects/metafile.c
+++ b/objects/metafile.c
@@ -6,12 +6,15 @@
 
 static char Copyright[] = "Copyright  David W. Metcalfe, 1994";
 
+#include <string.h>
 #include "windows.h"
 #include "gdi.h"
 #include "metafile.h"
 #include "prototypes.h"
-
-#define DEBUG_METAFILE
+#include "stddebug.h"
+/* #define DEBUG_METAFILE /* */
+/* #undef  DEBUG_METAFILE /* */
+#include "debug.h"
 
 #define HTINCR  10      /* handle table allocation size increment */
 
@@ -29,9 +32,7 @@
     METAHEADER *mh;
     HANDLETABLE *ht;
 
-#ifdef DEBUG_METAFILE
-    printf("CreateMetaFile: %s\n", lpFilename);
-#endif
+    dprintf_metafile(stddeb,"CreateMetaFile: %s\n", lpFilename);
 
     handle = GDI_AllocObject(sizeof(DC), METAFILE_DC_MAGIC);
     if (!handle) return 0;
@@ -94,9 +95,7 @@
     char buffer[15];
     METARECORD *mr = (METARECORD *)&buffer;
 
-#ifdef DEBUG_METAFILE
-    printf("CloseMetaFile\n");
-#endif
+    dprintf_metafile(stddeb,"CloseMetaFile\n");
 
     dc = (DC *)GDI_GetObjPtr(hdc, METAFILE_DC_MAGIC);
     if (!dc) return 0;
@@ -442,7 +441,7 @@
 	break;
 
     default:
-	printf("PlayMetaFileRecord: Unknown record type %x\n",
+	fprintf(stderr,"PlayMetaFileRecord: Unknown record type %x\n",
 	                                      mr->rdFunction);
     }
 }
@@ -898,7 +897,7 @@
 BOOL MF_BitBlt(DC *dcDest, short xDest, short yDest, short width,
 	       short height, HDC hdcSrc, short xSrc, short ySrc, DWORD rop)
 {
-    printf("MF_BitBlt: not implemented yet\n");
+    dprintf_metafile(stdnimp,"MF_BitBlt: not implemented yet\n");
 }
 
 
@@ -909,5 +908,5 @@
 		   short heightDest, HDC hdcSrc, short xSrc, short ySrc, 
 		   short widthSrc, short heightSrc, DWORD rop)
 {
-    printf("MF_StretchBlt: not implemented yet\n");
+    dprintf_metafile(stdnimp,"MF_StretchBlt: not implemented yet\n");
 }
diff --git a/objects/palette.c b/objects/palette.c
index dc52635..7761c2e 100644
--- a/objects/palette.c
+++ b/objects/palette.c
@@ -22,6 +22,10 @@
 
 #include <X11/Xlib.h>
 #include "gdi.h"
+#include "stddebug.h"
+/* #define DEBUG_PALETTE /* */
+/* #undef  DEBUG_PALETTE /* */
+#include "debug.h"
 
 extern void COLOR_SetMapping( DC *dc, HANDLE map, WORD size );  /* color.c */
 
@@ -156,10 +160,8 @@
 	}
 	entry++;
     }
-#ifdef DEBUG_GDI
-    printf( "GetNearestPaletteIndex(%x,%06x) : returning %d\n", 
+    dprintf_palette(stddeb,"GetNearestPaletteIndex(%x,%06x) : returning %d\n", 
 	     hpalette, color, index );
-#endif
     return index;
 }
 
@@ -183,9 +185,7 @@
     HPALETTE prev;
     DC *dc;
 
-#ifdef DEBUG_PALETTE
-    printf( "GDISelectPalette: %d %d\n", hdc, hpal );
-#endif
+    dprintf_palette(stddeb, "GDISelectPalette: %d %d\n", hdc, hpal );
     if (!(dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC ))) return 0;
     prev = dc->w.hPalette;
     dc->w.hPalette = hpal;
@@ -200,9 +200,7 @@
  */
 UINT GDIRealizePalette( HDC hdc )
 {
-#ifdef DEBUG_PALETTE
-    printf( "GDIRealizePalette: %d\n", hdc );
-#endif
+    dprintf_palette(stdnimp, "GDIRealizePalette: %d\n", hdc );
     return 0;
 }
 
diff --git a/objects/pen.c b/objects/pen.c
index 61e1f16..00eba87 100644
--- a/objects/pen.c
+++ b/objects/pen.c
@@ -8,6 +8,10 @@
 
 #include "gdi.h"
 #include "metafile.h"
+#include "stddebug.h"
+/* #define DEBUG_GDI /* */
+/* #undef  DEBUG_GDI /* */
+#include "debug.h"
 
 extern WORD COLOR_ToPhysical( DC *dc, COLORREF color );
 
@@ -17,9 +21,7 @@
 HPEN CreatePen( short style, short width, COLORREF color )
 {
     LOGPEN logpen = { style, { width, 0 }, color };
-#ifdef DEBUG_GDI
-    printf( "CreatePen: %d %d %06x\n", style, width, color );
-#endif
+    dprintf_gdi(stddeb, "CreatePen: %d %d %06x\n", style, width, color );
     return CreatePenIndirect( &logpen );
 }
 
diff --git a/objects/region.c b/objects/region.c
index 74ec57b..ad3379b 100644
--- a/objects/region.c
+++ b/objects/region.c
@@ -10,6 +10,10 @@
 #include <stdio.h>
 
 #include "gdi.h"
+#include "stddebug.h"
+/* #define DEBUG_REGION /* */
+/* #undef  DEBUG_REGION /* */
+#include "debug.h"
 
   /* GC used for region operations */
 static GC regionGC = 0;
@@ -50,8 +54,8 @@
     region->pixmap = XCreatePixmap( display, rootWindow, width, height, 1 );
     if (!region->pixmap) return FALSE;
     XSetRegion( display, regionGC, region->xrgn );
-    XSetClipOrigin( display, regionGC, region->box.left, region->box.top );
-    XSetFunction( display, regionGC, GXcopy );
+    XSetClipOrigin( display, regionGC, -region->box.left, -region->box.top );
+    XSetFunction( display, regionGC, GXset );
     XFillRectangle( display, region->pixmap, regionGC, 0, 0, width, height );
     XSetClipMask( display, regionGC, None );  /* Clear clip region */
     return TRUE;
@@ -91,14 +95,9 @@
 
     if (createXrgn)  /* Create and set the X region */
     {
-	Region tmprgn;
 	XRectangle xrect = { region->box.left, region->box.top, width, height};
-
-	if (!(tmprgn = XCreateRegion())) return FALSE;
-	if ((region->xrgn = XCreateRegion()))
-	    XUnionRectWithRegion( &xrect, tmprgn, region->xrgn );
-	XDestroyRegion( tmprgn );
-	if (!region->xrgn) return FALSE;
+	if (!(region->xrgn = XCreateRegion())) return FALSE;
+        XUnionRectWithRegion( &xrect, region->xrgn, region->xrgn );
     }
     else  /* Create the pixmap */
     {
@@ -130,9 +129,7 @@
 {
     RGNOBJ * obj = (RGNOBJ *) GDI_GetObjPtr( hrgn, REGION_MAGIC );
     if (!obj) return ERROR;
-#ifdef DEBUG_REGION
-    printf( "OffsetRgn: %d %d,%d\n", hrgn, x, y );
-#endif
+    dprintf_region(stddeb, "OffsetRgn: %d %d,%d\n", hrgn, x, y );
     OffsetRect( &obj->region.box, x, y );
     if (obj->region.xrgn) XOffsetRegion( obj->region.xrgn, x, y );
     return obj->region.type;
@@ -146,9 +143,7 @@
 {
     RGNOBJ * obj = (RGNOBJ *) GDI_GetObjPtr( hrgn, REGION_MAGIC );
     if (!obj) return ERROR;
-#ifdef DEBUG_REGION
-    printf( "GetRgnBox: %d\n", hrgn );
-#endif
+    dprintf_region(stddeb, "GetRgnBox: %d\n", hrgn );
     *rect = obj->region.box;
     return obj->region.type;
 }
@@ -171,10 +166,8 @@
 {
     HRGN hrgn;
 
-#ifdef DEBUG_REGION
-    printf( "CreateRectRgnIndirect: %d,%d-%d,%d\n",
+    dprintf_region(stddeb, "CreateRectRgnIndirect: %d,%d-%d,%d\n",
 	    rect->left, rect->top, rect->right, rect->bottom );
-#endif
     
       /* Create region */
 
@@ -198,10 +191,8 @@
     RGNOBJ * rgnObj;
     HRGN hrgn;
 
-#ifdef DEBUG_REGION
-    printf( "CreateRoundRectRgn: %d,%d-%d,%d %dx%d\n",
+    dprintf_region(stddeb, "CreateRoundRectRgn: %d,%d-%d,%d %dx%d\n",
 	    left, top, right, bottom, ellipse_width, ellipse_height );
-#endif
     
       /* Create region */
 
@@ -252,9 +243,8 @@
     RECT rect = { left, top, right, bottom };    
     RGNOBJ * rgnObj;
 
-#ifdef DEBUG_REGION
-    printf( "SetRectRgn: %d %d,%d-%d,%d\n", hrgn, left, top, right, bottom );
-#endif
+    dprintf_region(stddeb, "SetRectRgn: %d %d,%d-%d,%d\n", 
+		   hrgn, left, top, right, bottom );
     
       /* Free previous pixmap */
 
@@ -283,10 +273,8 @@
     RGNOBJ * rgnObj;
     HRGN hrgn;
 
-#ifdef DEBUG_REGION
-    printf( "CreateEllipticRgnIndirect: %d,%d-%d,%d\n",
+    dprintf_region(stddeb, "CreateEllipticRgnIndirect: %d,%d-%d,%d\n",
 	    rect->left, rect->top, rect->right, rect->bottom );
-#endif
     
       /* Create region */
 
@@ -335,9 +323,7 @@
     XRectangle rect;
     Region xrgn;
 
-#ifdef DEBUG_REGION
-    printf( "CreatePolyPolygonRgn: %d polygons\n", nbpolygons );
-#endif
+    dprintf_region(stddeb, "CreatePolyPolygonRgn: %d polygons\n", nbpolygons );
 
       /* Allocate points array */
 
@@ -541,6 +527,47 @@
 
 
 /***********************************************************************
+ *           REGION_CopyRegion
+ *
+ * Copy region src into dest.
+ */
+static int REGION_CopyRegion( RGNOBJ *src, RGNOBJ *dest )
+{
+    if (dest->region.pixmap) XFreePixmap( display, dest->region.pixmap );
+    dest->region.type   = src->region.type;
+    dest->region.box    = src->region.box;
+    dest->region.pixmap = 0;
+    if (src->region.xrgn)  /* Copy only the X region */
+    {
+        Region tmprgn = XCreateRegion();
+        if (!dest->region.xrgn) dest->region.xrgn = XCreateRegion();
+        XUnionRegion( tmprgn, src->region.xrgn, dest->region.xrgn );
+        XDestroyRegion( tmprgn );
+    }
+    else  /* Copy the pixmap (if any) */
+    {
+        if (dest->region.xrgn)
+        {
+            XDestroyRegion( dest->region.xrgn );
+            dest->region.xrgn = 0;
+        }
+        if (src->region.pixmap)
+        {
+            int width = src->region.box.right - src->region.box.left;
+            int height = src->region.box.bottom - src->region.box.top;
+            
+            dest->region.pixmap = XCreatePixmap( display, rootWindow,
+                                                 width, height, 1 );
+            XSetFunction( display, regionGC, GXcopy );
+            XCopyArea( display, src->region.pixmap, dest->region.pixmap,
+                       regionGC, 0, 0, width, height, 0, 0 );
+        }
+    }
+    return dest->region.type;
+}
+
+
+/***********************************************************************
  *           CombineRgn    (GDI.451)
  */
 int CombineRgn( HRGN hDest, HRGN hSrc1, HRGN hSrc2, short mode )
@@ -550,20 +577,20 @@
     int width, height;
     BOOL res;
     
-#ifdef DEBUG_REGION
-    printf( "CombineRgn: %d %d %d %d\n", hDest, hSrc1, hSrc2, mode );
-#endif
+    dprintf_region(stddeb, "CombineRgn: %d %d %d %d\n", 
+		   hDest, hSrc1, hSrc2, mode );
     
     if (!(destObj = (RGNOBJ *) GDI_GetObjPtr( hDest, REGION_MAGIC )))
 	return ERROR;
     if (!(src1Obj = (RGNOBJ *) GDI_GetObjPtr( hSrc1, REGION_MAGIC )))
 	return ERROR;
-    if (mode != RGN_COPY)
-	if (!(src2Obj = (RGNOBJ *) GDI_GetObjPtr( hSrc2, REGION_MAGIC )))
-	    return ERROR;
+    if (mode == RGN_COPY) return REGION_CopyRegion( src1Obj, destObj );
+
+    if (!(src2Obj = (RGNOBJ *) GDI_GetObjPtr( hSrc2, REGION_MAGIC )))
+        return ERROR;
     region = &destObj->region;
 
-    if (src1Obj->region.xrgn && ((mode == RGN_COPY) || src2Obj->region.xrgn))
+    if (src1Obj->region.xrgn && src2Obj->region.xrgn)
     {
 	/* Perform the operation with X regions */
 
@@ -588,18 +615,12 @@
 	    XSubtractRegion( src1Obj->region.xrgn, src2Obj->region.xrgn,
 			     region->xrgn );
 	    break;
-	case RGN_COPY:
-	    {
-		Region tmprgn = XCreateRegion();
-		XUnionRegion( tmprgn, src1Obj->region.xrgn, region->xrgn );
-		XDestroyRegion( tmprgn );
-	    }
-	    break;
 	default:
 	    return ERROR;
 	}
 	if (XEmptyRegion(region->xrgn))
 	{
+            XDestroyRegion( region->xrgn );
 	    region->type = NULLREGION;
 	    region->xrgn = 0;
 	    return NULLREGION;
@@ -620,7 +641,7 @@
     {
 	if (!src1Obj->region.pixmap)
 	    if (!REGION_MakePixmap( &src1Obj->region )) return ERROR;
-	if ((mode != RGN_COPY) && !src2Obj->region.pixmap)
+	if (!src2Obj->region.pixmap)
 	    if (!REGION_MakePixmap( &src2Obj->region )) return ERROR;
     }
     
@@ -646,12 +667,6 @@
 	region->type = COMPLEXREGION;
 	break;
 
-      case RGN_COPY:
-	region->box  = src1Obj->region.box;
-	region->type = src1Obj->region.type;
-	res = (region->type != NULLREGION);
-	break;
-
       default:
 	return ERROR;
     }
@@ -670,8 +685,8 @@
     height = region->box.bottom - region->box.top;
     if (!width || !height)
     {
-	printf( "CombineRgn: width or height is 0. Please report this.\n" );
-	printf( "src1=%d,%d-%d,%d  src2=%d,%d-%d,%d  dst=%d,%d-%d,%d  op=%d\n",
+	fprintf(stderr, "CombineRgn: width or height is 0. Please report this.\n" );
+	fprintf(stderr, "src1=%d,%d-%d,%d  src2=%d,%d-%d,%d  dst=%d,%d-%d,%d  op=%d\n",
 	        src1Obj->region.box.left, src1Obj->region.box.top,
 	        src1Obj->region.box.right, src1Obj->region.box.bottom,
 	        src2Obj->region.box.left, src2Obj->region.box.top,
@@ -711,12 +726,6 @@
 	  XSetFunction( display, regionGC, GXandInverted );
 	  REGION_CopyIntersection( region, &src2Obj->region );
 	  break;
-	  
-      case RGN_COPY:
-	  XSetFunction( display, regionGC, GXcopy );
-	  XCopyArea( display, src1Obj->region.pixmap, region->pixmap,
-		     regionGC, 0, 0, width, height, 0, 0 );
-	  break;
     }
     return region->type;
 }
diff --git a/objects/text.c b/objects/text.c
index 10a6a75..95b2eb7 100644
--- a/objects/text.c
+++ b/objects/text.c
@@ -1,15 +1,20 @@
 /*
  * text functions
  *
- * Copyright 1993 Alexandre Julliard
+ * Copyright 1993, 1994 Alexandre Julliard
  */
 
-static char Copyright[] = "Copyright  Alexandre Julliard, 1993";
+static char Copyright[] = "Copyright  Alexandre Julliard, 1993, 1994";
 
+#include <stdlib.h>
 #include <X11/Xatom.h>
 #include "windows.h"
 #include "gdi.h"
 #include "metafile.h"
+#include "stddebug.h"
+/* #define DEBUG_TEXT /* */
+/* #undef  DEBUG_TEXT /* */
+#include "debug.h"
 
 #define TAB     9
 #define LF     10
@@ -17,6 +22,8 @@
 #define SPACE  32
 #define PREFIX 38
 
+#define SWAP_INT(a,b)  { int t = a; a = b; b = t; }
+
 static int tabstop = 8;
 static int tabwidth;
 static int spacewidth;
@@ -182,10 +189,8 @@
     int x = rect->left, y = rect->top;
     int width = rect->right - rect->left;
 
-#ifdef DEBUG_TEXT
-    printf( "DrawText: '%s', %d , [(%d,%d),(%d,%d)]\n", str, count,
+    dprintf_text(stddeb,"DrawText: '%s', %d , [(%d,%d),(%d,%d)]\n", str, count,
 	   rect->left, rect->top, rect->right, rect->bottom);
-#endif
 
     if (count == -1) count = strlen(str);
     strPtr = str;
@@ -232,7 +237,9 @@
 	    else if (flags & DT_BOTTOM) y = rect->bottom - size.cy;
 	}
 	if (!(flags & DT_CALCRECT))
-	    if (!TextOut(hdc, x, y, line, len)) return 0;
+	    if (!ExtTextOut( hdc, x, y, (flags & DT_NOCLIP) ? 0 : ETO_CLIPPED,
+                             rect, line, len, NULL )) return 0;
+
 	if (prefix_offset != -1)
 	{
 	    HPEN hpen = CreatePen( PS_SOLID, 1, GetTextColor(hdc) );
@@ -260,41 +267,67 @@
 
 
 /***********************************************************************
- *           TextOut    (GDI.33)
+ *           ExtTextOut    (GDI.351)
  */
-BOOL TextOut( HDC hdc, short x, short y, LPSTR str, short count )
+BOOL ExtTextOut( HDC hdc, short x, short y, WORD flags, LPRECT lprect,
+                 LPSTR str, WORD count, LPINT lpDx )
 {
     int dir, ascent, descent, i;
     XCharStruct info;
     XFontStruct *font;
+    RECT rect;
 
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
     if (!dc) 
     {
-	dc = (DC *)GDI_GetObjPtr(hdc, METAFILE_DC_MAGIC);
+	dc = (DC *)GDI_GetObjPtr( hdc, METAFILE_DC_MAGIC );
 	if (!dc) return FALSE;
-	MF_TextOut(dc, x, y, str, count);
+	MF_TextOut( dc, x, y, str, count );
 	return TRUE;
     }
 
     if (!DC_SetupGCForText( dc )) return TRUE;
     font = dc->u.x.font.fstruct;
 
+    dprintf_text(stddeb,"ExtTextOut: %d,%d '%s', %d  flags=%d rect=%d,%d,%d,%d\n",
+            x, y, str, count, flags,
+            lprect->left, lprect->top, lprect->right, lprect->bottom );
+
+      /* Setup coordinates */
+
     if (dc->w.textAlign & TA_UPDATECP)
     {
 	x = dc->w.CursPosX;
 	y = dc->w.CursPosY;
     }
-#ifdef DEBUG_TEXT
-    printf( "TextOut: %d,%d '%s', %d\n", x, y, str, count );
-#endif
     x = XLPTODP( dc, x );
     y = YLPTODP( dc, y );
+    if (flags & (ETO_OPAQUE | ETO_CLIPPED))  /* There's a rectangle */
+    {
+        rect.left   = XLPTODP( dc, lprect->left );
+        rect.right  = XLPTODP( dc, lprect->right );
+        rect.top    = YLPTODP( dc, lprect->top );
+        rect.bottom = YLPTODP( dc, lprect->bottom );
+        if (rect.right < rect.left) SWAP_INT( rect.left, rect.right );
+        if (rect.bottom < rect.top) SWAP_INT( rect.top, rect.bottom );
+    }
+
+      /* Draw the rectangle */
+
+    if (flags & ETO_OPAQUE)
+    {
+        XSetForeground( display, dc->u.x.gc, dc->w.backgroundPixel );
+        XFillRectangle( display, dc->u.x.drawable, dc->u.x.gc,
+                        dc->w.DCOrgX + rect.left, dc->w.DCOrgY + rect.top,
+                        rect.right-rect.left, rect.bottom-rect.top );
+    }
+    if (!count) return TRUE;  /* Nothing more to do */
+
+      /* Compute text starting position */
 
     XTextExtents( font, str, count, &dir, &ascent, &descent, &info );
     info.width += count*dc->w.charExtra + dc->w.breakExtra*dc->w.breakCount;
-
-      /* Compute starting position */
+    if (lpDx) for (i = 0; i < count; i++) info.width += lpDx[i];
 
     switch( dc->w.textAlign & (TA_LEFT | TA_RIGHT | TA_CENTER) )
     {
@@ -322,52 +355,75 @@
 	  break;
     }
 
-      /* Draw text */
+      /* Set the clip region */
 
-    if (!dc->w.charExtra && !dc->w.breakExtra)
+    if (flags & ETO_CLIPPED)
     {
-	if (dc->w.backgroundMode == TRANSPARENT)
-	    XDrawString( XT_display, dc->u.x.drawable, dc->u.x.gc, 
-			 dc->w.DCOrgX + x, dc->w.DCOrgY + y, str, count );
-	else
-	    XDrawImageString( XT_display, dc->u.x.drawable, dc->u.x.gc,
-			      dc->w.DCOrgX + x, dc->w.DCOrgY + y, str, count );
+        SaveVisRgn( hdc );
+        IntersectVisRect( hdc, rect.left, rect.top, rect.right, rect.bottom );
     }
-    else
+
+      /* Draw the text background if necessary */
+
+    if (dc->w.backgroundMode != TRANSPARENT)
     {
-	char * p = str;
-	int xchar = x;
-	for (i = 0; i < count; i++, p++)
-	{
-	    XCharStruct * charStr;
-	    unsigned char ch = *p;
-	    int extraWidth;
-	    
-	    if ((ch < font->min_char_or_byte2)||(ch > font->max_char_or_byte2))
-		ch = font->default_char;
-	    if (!font->per_char) charStr = &font->min_bounds;
-	    else charStr = font->per_char + ch - font->min_char_or_byte2;
+          /* If rectangle is opaque and clipped, do nothing */
+        if (!(flags & ETO_CLIPPED) || !(flags & ETO_OPAQUE))
+        {
+              /* Only draw if rectangle is not opaque or if some */
+              /* text is outside the rectangle */
+            if (!(flags & ETO_OPAQUE) ||
+                (x < rect.left) ||
+                (x + info.width >= rect.right) ||
+                (y-font->ascent < rect.top) ||
+                (y+font->descent >= rect.bottom))
+            {
+                XSetForeground( display, dc->u.x.gc, dc->w.backgroundPixel );
+                XFillRectangle( display, dc->u.x.drawable, dc->u.x.gc,
+                                dc->w.DCOrgX + x,
+                                dc->w.DCOrgY + y - font->ascent,
+                                info.width,
+                                font->ascent + font->descent );
+            }
+        }
+    }
+    
+      /* Draw the text */
 
-	    extraWidth = dc->w.charExtra;
-	    if (ch == dc->u.x.font.metrics.tmBreakChar)
-		extraWidth += dc->w.breakExtra;
+    XSetForeground( display, dc->u.x.gc, dc->w.textPixel );
+    if (!dc->w.charExtra && !dc->w.breakExtra && !lpDx)
+    {
+        XDrawString( display, dc->u.x.drawable, dc->u.x.gc, 
+                     dc->w.DCOrgX + x, dc->w.DCOrgY + y, str, count );
+    }
+    else  /* Now the fun begins... */
+    {
+        XTextItem *items, *pitem;
 
-	    if (dc->w.backgroundMode == TRANSPARENT)
-		XDrawString( XT_display, dc->u.x.drawable, dc->u.x.gc,
-			     dc->w.DCOrgX + xchar, dc->w.DCOrgY + y, p, 1 );
-	    else
-	    {
-		XDrawImageString( XT_display, dc->u.x.drawable, dc->u.x.gc,
-				  dc->w.DCOrgX + xchar, dc->w.DCOrgY + y, p, 1 );
-		XSetForeground( XT_display, dc->u.x.gc, dc->w.backgroundPixel);
-		XFillRectangle( XT_display, dc->u.x.drawable, dc->u.x.gc,
-			        dc->w.DCOrgX + xchar + charStr->width,
-			        dc->w.DCOrgY + y - font->ascent,
-			        extraWidth, font->ascent + font->descent );
-		XSetForeground( XT_display, dc->u.x.gc, dc->w.textPixel );
-	    }
-	    xchar += charStr->width + extraWidth;
-	}
+        items = malloc( count * sizeof(XTextItem) );
+        for (i = 0, pitem = items; i < count; i++, pitem++)
+        {
+            pitem->chars  = str + i;
+            pitem->nchars = 1;
+            pitem->font   = None;
+            if (i == 0)
+            {
+                pitem->delta = 0;
+                continue;  /* First iteration -> no delta */
+            }
+            pitem->delta = dc->w.charExtra;
+            if (str[i] == dc->u.x.font.metrics.tmBreakChar)
+                pitem->delta += dc->w.breakExtra;
+            if (lpDx)
+            {
+                INT width;
+                GetCharWidth( hdc, str[i], str[i], &width );
+                pitem->delta += lpDx[i-1] - width;
+            }
+        }
+        XDrawText( display, dc->u.x.drawable, dc->u.x.gc,
+                   dc->w.DCOrgX + x, dc->w.DCOrgY + y, items, count );
+        free( items );
     }
 
       /* Draw underline and strike-out if needed */
@@ -380,9 +436,9 @@
 	if (!XGetFontProperty( font, XA_UNDERLINE_THICKNESS, &lineWidth ))
 	    lineWidth = 0;
 	else if (lineWidth == 1) lineWidth = 0;
-	XSetLineAttributes( XT_display, dc->u.x.gc, lineWidth,
+	XSetLineAttributes( display, dc->u.x.gc, lineWidth,
 			    LineSolid, CapRound, JoinBevel ); 
-	XDrawLine( XT_display, dc->u.x.drawable, dc->u.x.gc,
+        XDrawLine( display, dc->u.x.drawable, dc->u.x.gc,
 		   dc->w.DCOrgX + x, dc->w.DCOrgY + y + linePos,
 		   dc->w.DCOrgX + x + info.width, dc->w.DCOrgY + y + linePos );
     }
@@ -393,16 +449,26 @@
 	    lineAscent = font->ascent / 3;
 	if (!XGetFontProperty( font, XA_STRIKEOUT_DESCENT, &lineDescent ))
 	    lineDescent = -lineAscent;
-	XSetLineAttributes( XT_display, dc->u.x.gc, lineAscent + lineDescent,
+	XSetLineAttributes( display, dc->u.x.gc, lineAscent + lineDescent,
 			    LineSolid, CapRound, JoinBevel ); 
-	XDrawLine( XT_display, dc->u.x.drawable, dc->u.x.gc,
+	XDrawLine( display, dc->u.x.drawable, dc->u.x.gc,
 		   dc->w.DCOrgX + x, dc->w.DCOrgY + y - lineAscent,
 		   dc->w.DCOrgX + x + info.width, dc->w.DCOrgY + y - lineAscent );
     }
-    
+    if (flags & ETO_CLIPPED) RestoreVisRgn( hdc );
     return TRUE;
 }
 
+
+/***********************************************************************
+ *           TextOut    (GDI.33)
+ */
+BOOL TextOut( HDC hdc, short x, short y, LPSTR str, short count )
+{
+    return ExtTextOut( hdc, x, y, 0, NULL, str, count, NULL );
+}
+
+
 /***********************************************************************
  *		GrayString (USER.185)
  */
@@ -425,6 +491,7 @@
 	}
 }
 
+
 /***********************************************************************
  *			TabbedTextOut		[USER.196]
  */
@@ -432,7 +499,7 @@
 		short nTabCount, LPINT lpTabPos, short nTabOrg)
 {
 	WORD 	width, height;
-	printf("EMPTY STUB !!! TabbedTextOut(); ! call TextOut() for now !\n");
+	dprintf_text(stdnimp,"EMPTY STUB !!! TabbedTextOut(); ! call TextOut() for now !\n");
 	height = HIWORD(GetTextExtent(hDC, lpStr, nCount));
 	width = LOWORD(GetTextExtent(hDC, lpStr, nCount));
 	TextOut(hDC, x, y, lpStr, nCount);
@@ -441,23 +508,12 @@
 
 
 /***********************************************************************
- *			ExtTextOut			[GDI.351]
- */
-BOOL ExtTextOut(HDC hDC, short x, short y, WORD wOptions, LPRECT lprect,
-			LPSTR str, WORD count, LPINT lpDx)
-{
-	printf("EMPTY STUB !!! ExtTextOut(); ! call TextOut() for now !\n");
-	TextOut(hDC, x, y, str, count);
-	return FALSE;
-}
-
-/***********************************************************************
  *			GetTabbedTextExtent		[USER.197]
  */
 DWORD GetTabbedTextExtent(HDC hDC, LPSTR lpString, int nCount, 
 	int nTabPositions, LPINT lpnTabStopPositions)
 {
-	printf("EMPTY STUB !!! GetTabbedTextExtent(); !\n");
+	dprintf_text(stdnimp,"EMPTY STUB !!! GetTabbedTextExtent(); !\n");
 
 	return (18 << 16) | (nCount * 18);
 }
diff --git a/toolkit/Imakefile b/toolkit/Imakefile
index 5ddccc8..0ecfb4f 100644
--- a/toolkit/Imakefile
+++ b/toolkit/Imakefile
@@ -12,7 +12,6 @@
 
 WineRelocatableTarget($(TOP)/$(MODULE),,$(OBJS))
 DependTarget()
-CleanTarget()
 
 includes::
 
diff --git a/tools/make_debug b/tools/make_debug
new file mode 100755
index 0000000..09a63f9
--- /dev/null
+++ b/tools/make_debug
@@ -0,0 +1,120 @@
+#!/bin/sh
+#
+# This script scans the whole source code for symbols of the form dprintf_xxx,
+# generates the necessary macro definitions and puts them into the files
+# include/stddebug.h and include/debug.h . This script must be started with 
+# cwd = rootdir of the Wine-distribution.
+#
+# Michael Patra  <micky@marie.physik.tu-berlin.de>
+#
+makedepend -s"# /* Do not remove this line or change anything below this line */" -finclude/debug.h
+echo " " >> include/debug.h
+grep -h dprintf_ */*.c | tr -d '[:blank:]' | cut -d"(" -f1 | sort | uniq | \
+	cut -d"_" -f2 > temp.$$
+echo " " >> include/debug.h
+echo "#ifdef DEBUG_NONE_EXT" >> include/debug.h
+cat temp.$$ |
+{
+while read x
+do
+	y=`echo $x | tr a-z A-Z`
+	echo "#undef DEBUG_$y" >> include/debug.h
+done
+}
+echo "#endif" >> include/debug.h
+echo " " >> include/debug.h
+echo " " >> include/debug.h
+echo "#ifdef DEBUG_ALL_EXT" >> include/debug.h
+cat temp.$$ |
+{
+while read x
+do
+	y=`echo $x | tr a-z A-Z`
+	echo "#define DEBUG_$y" >> include/debug.h
+done
+}
+echo "#endif" >> include/debug.h
+echo " " >> include/debug.h
+echo " " >> include/debug.h
+echo "#ifdef DEBUG_RUNTIME" >> include/debug.h
+echo "#ifdef DEBUG_DEFINE_VARIABLES" >> include/debug.h
+echo "short debug_msg_enabled[]={" >> include/debug.h
+i=0;
+cat temp.$$ |
+{
+while read x
+do
+	y=`echo $x | tr a-z A-Z`
+	echo "#ifdef DEBUG_$y" >> include/debug.h
+	echo "1," >> include/debug.h
+	echo "#else" >> include/debug.h
+	echo "0," >> include/debug.h
+	echo "#endif" >> include/debug.h
+done
+}
+echo "0};" >> include/debug.h
+echo "#else" >> include/debug.h 
+echo "extern short debug_msg_enabled[];" >> include/debug.h
+echo "#endif" >> include/debug.h
+echo "#endif" >> include/debug.h
+echo " " >> include/debug.h
+echo " " >> include/debug.h
+i=0
+cat temp.$$ |
+{
+while read x 
+do
+	y=`echo $x | tr a-z A-Z`
+	echo "#ifdef DEBUG_RUNTIME" >> include/debug.h
+	echo "#define dprintf_$x if(debug_msg_enabled[$i]) fprintf" >> include/debug.h
+	echo "#else" >> include/debug.h
+	echo "#ifdef DEBUG_$y" >> include/debug.h
+	echo "#define dprintf_$x fprintf" >> include/debug.h
+	echo "#else" >> include/debug.h
+	echo "#define dprintf_$x" >> include/debug.h
+	echo "#endif" >> include/debug.h
+	echo "#endif" >> include/debug.h
+	echo " " >> include/debug.h
+	let i=$i+1
+done
+}
+makedepend -s"# /* Do not remove this line or change anything below this line */" -finclude/stddebug.h
+echo " " >> include/stddebug.h
+echo "#ifdef DEBUG_NONE" >> include/stddebug.h
+cat temp.$$ |
+{
+while read x
+do
+	y=`echo $x | tr a-z A-Z`
+	echo "#undef DEBUG_$y" >> include/stddebug.h
+done
+}
+echo "#endif" >> include/stddebug.h
+echo " " >> include/stddebug.h
+echo " " >> include/stddebug.h
+echo "#ifdef DEBUG_ALL" >> include/stddebug.h
+cat temp.$$ |
+{
+while read x
+do
+	y=`echo $x | tr a-z A-Z`
+	echo "#define DEBUG_$y" >> include/stddebug.h
+done
+}
+echo "#endif" >> include/stddebug.h
+echo " " >> include/debug.h
+echo " " >> include/debug.h
+echo "#ifdef DEBUG_RUNTIME" >> include/debug.h
+echo "#ifdef DEBUG_DEFINE_VARIABLES" >> include/debug.h
+echo "static char *debug_msg_name[] = {" >> include/debug.h
+cat temp.$$ |
+{
+while read x
+do
+	echo "\"$x\"," >> include/debug.h
+done
+} 
+echo "\"\"};" >> include/debug.h
+echo "#endif" >> include/debug.h
+echo "#endif" >> include/debug.h
+rm temp.$$
diff --git a/windows/Imakefile b/windows/Imakefile
index 53412bc..237c777 100644
--- a/windows/Imakefile
+++ b/windows/Imakefile
@@ -5,7 +5,7 @@
 SRCS = \
 	caret.c \
 	class.c \
-	dc.c \
+	cursor.c \
 	dce.c \
 	defdlg.c \
 	defwnd.c \
@@ -33,7 +33,6 @@
 
 WineRelocatableTarget($(TOP)/$(MODULE),,$(OBJS))
 DependTarget()
-CleanTarget()
 
 includes::
 
diff --git a/windows/caret.c b/windows/caret.c
index c3ed202..ae835b4 100644
--- a/windows/caret.c
+++ b/windows/caret.c
@@ -7,6 +7,11 @@
 static char Copyright[] = "Copyright  David Metcalfe, 1993";
 
 #include "windows.h"
+#include "stddebug.h"
+/* #define DEBUG_CARET /* */
+/* #undef  DEBUG_CARET /* */
+#include "debug.h"
+
 
 typedef struct
 {
@@ -40,10 +45,8 @@
     HBRUSH hBrush;
     HRGN rgn;
 
-#ifdef DEBUG_CARET
-    printf("CARET_Callback: id=%d: LockCaret=%d, hidden=%d, on=%d\n",
+    dprintf_caret(stddeb,"CARET_Callback: id=%d: LockCaret=%d, hidden=%d, on=%d\n",
 	   timerid, LockCaret, Caret.hidden, Caret.on);
-#endif
     if (!LockCaret && (!Caret.hidden || Caret.on))
     {
 	Caret.on = (Caret.on ? FALSE : TRUE);
@@ -134,9 +137,8 @@
 
     Caret.timerid = SetSystemTimer(NULL, 0, Caret.timeout, CARET_Callback);
 
-#ifdef DEBUG_CARET
-    printf("CreateCaret: hwnd=%d, timerid=%d\n", hwnd, Caret.timerid);
-#endif
+    dprintf_caret(stddeb,"CreateCaret: hwnd=%d, timerid=%d\n", 
+		  hwnd, Caret.timerid);
 }
    
 
@@ -148,9 +150,7 @@
 {
 /*    if (!Caret.hwnd) return;
 */
-#ifdef DEBUG_CARET
-    printf("DestroyCaret: timerid=%d\n", Caret.timerid);
-#endif
+    dprintf_caret(stddeb,"DestroyCaret: timerid=%d\n", Caret.timerid);
 
     KillSystemTimer(NULL, Caret.timerid);
 
@@ -173,9 +173,7 @@
 
     if (!Caret.hwnd) return;
 
-#ifdef DEBUG_CARET
-    printf("SetCaretPos: x=%d, y=%d\n", x, y);
-#endif
+    dprintf_caret(stddeb,"SetCaretPos: x=%d, y=%d\n", x, y);
 
     LockCaret = TRUE;
     if (Caret.on)
@@ -213,9 +211,7 @@
     if (!Caret.hwnd) return;
     if (hwnd && (Caret.hwnd != hwnd)) return;
 
-#ifdef DEBUG_CARET
-    printf("ShowCaret: hidden=%d\n", Caret.hidden);
-#endif
+    dprintf_caret(stddeb,"ShowCaret: hidden=%d\n", Caret.hidden);
     if (Caret.hidden)
 	--Caret.hidden;
 }
diff --git a/windows/class.c b/windows/class.c
index 622afe1..639d2da 100644
--- a/windows/class.c
+++ b/windows/class.c
@@ -13,8 +13,10 @@
 #include "user.h"
 #include "win.h"
 #include "dce.h"
-
+#include "stddebug.h"
 /* #define DEBUG_CLASS /* */
+/* #undef  DEBUG_CLASS /* */
+#include "debug.h"
 
 
 static HCLASS firstClass = 0;
@@ -93,11 +95,9 @@
     HCLASS handle, prevClass;
     int classExtra;
 
-#ifdef DEBUG_CLASS
-    printf( "RegisterClass: wndproc=%08x hinst=%d name='%s' background %x\n", 
+    dprintf_class(stddeb, "RegisterClass: wndproc=%08x hinst=%d name='%s' background %x\n", 
 	    class->lpfnWndProc, class->hInstance, class->lpszClassName,
 	    class->hbrBackground );
-#endif
 
       /* Check if a class with this name already exists */
 
@@ -177,7 +177,7 @@
 	}
 	if (!prevClass)
 	{
-	    printf( "ERROR: Class list corrupted\n" );
+	    fprintf(stderr, "ERROR: Class list corrupted\n" );
 	    return FALSE;
 	}
 	prevClassPtr->hNext = classPtr->hNext;
diff --git a/windows/cursor.c b/windows/cursor.c
new file mode 100644
index 0000000..1c866d1
--- /dev/null
+++ b/windows/cursor.c
@@ -0,0 +1,443 @@
+/*
+ *    WINE
+*/
+static char Copyright[] = "Copyright  Martin Ayotte, 1993";
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <X11/cursorfont.h>
+#include <X11/Xlib.h>
+#include "prototypes.h"
+#include "windows.h"
+#include "win.h"
+#include "gdi.h"
+#include "wine.h"
+#include "cursor.h"
+#include "stddebug.h"
+/* #define DEBUG_CURSOR   /* */
+/* #undef  DEBUG_CURSOR   /* */
+/* #define DEBUG_RESOURCE /* */
+/* #undef  DEBUG_RESOURCE /* */
+#include "debug.h"
+
+static int ShowCursCount = 0;
+static HCURSOR hActiveCursor;
+static HCURSOR hEmptyCursor = 0;
+RECT	ClipCursorRect;
+extern HINSTANCE hSysRes;
+extern int desktopX, desktopY;   /* misc/main.c */
+
+static struct { LPSTR name; HCURSOR cursor; } system_cursor[] =
+{
+    { IDC_ARROW, 0 },
+    { IDC_IBEAM, 0 },
+    { IDC_WAIT, 0 },
+    { IDC_CROSS, 0 },
+    { IDC_UPARROW, 0 },
+    { IDC_SIZE, 0 },
+    { IDC_ICON, 0 },
+    { IDC_SIZENWSE, 0 },
+    { IDC_SIZENESW, 0 },
+    { IDC_SIZEWE, 0 },
+    { IDC_SIZENS, 0 }
+};
+
+#define NB_SYS_CURSORS  (sizeof(system_cursor)/sizeof(system_cursor[0]))
+
+
+/**********************************************************************
+ *			LoadCursor [USER.173]
+ */
+HCURSOR LoadCursor(HANDLE instance, LPSTR cursor_name)
+{
+    XColor	bkcolor;
+    XColor	fgcolor;
+    HCURSOR 	hCursor;
+    HANDLE 	rsc_mem;
+    WORD 	*lp;
+    CURSORDESCRIP *lpcurdesc;
+    CURSORALLOC	  *lpcur;
+    HDC 	hdc;
+    int i, j, image_size;
+
+    dprintf_resource(stddeb,"LoadCursor: instance = %04x, name = %08x\n",
+	   instance, cursor_name);
+    if (!instance)
+    {
+	for (i = 0; i < NB_SYS_CURSORS; i++)
+	    if (system_cursor[i].name == cursor_name)
+	    {
+		hCursor = system_cursor[i].cursor;
+		break;
+	    }
+	if (i == NB_SYS_CURSORS) return 0;
+	if (hCursor) return hCursor;
+    }
+    hCursor = GlobalAlloc(GMEM_MOVEABLE, sizeof(CURSORALLOC) + 1024L); 
+    if (hCursor == (HCURSOR)NULL) return 0;
+    if (!instance) system_cursor[i].cursor = hCursor;
+
+    dprintf_cursor(stddeb,"LoadCursor Alloc hCursor=%X\n", hCursor);
+    lpcur = (CURSORALLOC *)GlobalLock(hCursor);
+    memset(lpcur, 0, sizeof(CURSORALLOC));
+    if (instance == (HANDLE)NULL) {
+	instance = hSysRes;
+	switch((LONG)cursor_name) {
+	    case IDC_ARROW:
+		lpcur->xcursor = XCreateFontCursor(display, XC_top_left_arrow);
+		GlobalUnlock(hCursor);
+	    	return hCursor;
+	    case IDC_CROSS:
+		lpcur->xcursor = XCreateFontCursor(display, XC_crosshair);
+		GlobalUnlock(hCursor);
+	    	return hCursor;
+	    case IDC_IBEAM:
+		lpcur->xcursor = XCreateFontCursor(display, XC_xterm);
+		GlobalUnlock(hCursor);
+	    	return hCursor;
+	    case IDC_WAIT:
+		lpcur->xcursor = XCreateFontCursor(display, XC_watch);
+		GlobalUnlock(hCursor);
+	    	return hCursor;
+	    case IDC_SIZENS:
+		lpcur->xcursor = XCreateFontCursor(display, XC_sb_v_double_arrow);
+		GlobalUnlock(hCursor);
+	    	return hCursor;
+	    case IDC_SIZEWE:
+		lpcur->xcursor = XCreateFontCursor(display, XC_sb_h_double_arrow);
+		GlobalUnlock(hCursor);
+	    	return hCursor;
+            case IDC_SIZENWSE:
+            case IDC_SIZENESW:
+                lpcur->xcursor = XCreateFontCursor(display, XC_fleur);
+                GlobalUnlock(hCursor);
+                return hCursor;
+	    default:
+		break;
+	    }
+	}
+
+#if 1
+    lpcur->xcursor = XCreateFontCursor(display, XC_top_left_arrow);
+    GlobalUnlock(hCursor);
+    return hCursor;
+#endif
+
+    if (!(hdc = GetDC(GetDesktopWindow()))) return 0;
+    rsc_mem = RSC_LoadResource(instance, cursor_name, NE_RSCTYPE_GROUP_CURSOR, 
+			       &image_size);
+    if (rsc_mem == (HANDLE)NULL) {
+    fprintf(stderr,"LoadCursor / Cursor %08X not Found !\n", cursor_name);
+	ReleaseDC(GetDesktopWindow(), hdc); 
+	return 0;
+	}
+    lp = (WORD *)GlobalLock(rsc_mem);
+    if (lp == NULL) {
+	GlobalFree(rsc_mem);
+	ReleaseDC(GetDesktopWindow(), hdc); 
+	return 0;
+	}
+    lpcurdesc = (CURSORDESCRIP *)(lp + 3);
+    dprintf_cursor(stddeb,"LoadCursor / image_size=%d\n", image_size);
+    dprintf_cursor(stddeb,"LoadCursor / curReserved=%X\n", *lp);
+    dprintf_cursor(stddeb,"LoadCursor / curResourceType=%X\n", *(lp + 1));
+    dprintf_cursor(stddeb,"LoadCursor / curResourceCount=%X\n", *(lp + 2));
+    dprintf_cursor(stddeb,"LoadCursor / cursor Width=%d\n", 
+		(int)lpcurdesc->Width);
+    dprintf_cursor(stddeb,"LoadCursor / cursor Height=%d\n", 
+		(int)lpcurdesc->Height);
+    dprintf_cursor(stddeb,"LoadCursor / cursor curXHotspot=%d\n", 
+		(int)lpcurdesc->curXHotspot);
+    dprintf_cursor(stddeb,"LoadCursor / cursor curYHotspot=%d\n", 
+		(int)lpcurdesc->curYHotspot);
+    dprintf_cursor(stddeb,"LoadCursor / cursor curDIBSize=%lX\n", 
+		(DWORD)lpcurdesc->curDIBSize);
+    dprintf_cursor(stddeb,"LoadCursor / cursor curDIBOffset=%lX\n", 
+		(DWORD)lpcurdesc->curDIBOffset);
+    lpcur->descriptor = *lpcurdesc;
+    GlobalUnlock(rsc_mem);
+    GlobalFree(rsc_mem);
+    rsc_mem = RSC_LoadResource(instance, 
+    	MAKEINTRESOURCE(lpcurdesc->curDIBOffset), 
+    	NE_RSCTYPE_CURSOR, &image_size);
+    if (rsc_mem == (HANDLE)NULL) {
+    	fprintf(stderr,
+		"LoadCursor / Cursor %08X Bitmap not Found !\n", cursor_name);
+	ReleaseDC(GetDesktopWindow(), hdc); 
+	return 0;
+	}
+    lp = (WORD *)GlobalLock(rsc_mem);
+    if (lp == NULL) {
+	GlobalFree(rsc_mem);
+	ReleaseDC(GetDesktopWindow(), hdc); 
+	return 0;
+ 	}
+	lp++;
+    for (j = 0; j < 16; j++)
+        dprintf_cursor(stddeb,"%04X ", *(lp + j));
+/*
+    if (*lp == sizeof(BITMAPINFOHEADER))
+	lpcur->hBitmap = ConvertInfoBitmap(hdc, (BITMAPINFO *)lp);
+    else
+*/
+        lpcur->hBitmap = 0;
+/*     lp += sizeof(BITMAP); */
+    for (i = 0; i < 81; i++) {
+	char temp = *((char *)lp + 162 + i);
+	*((char *)lp + 162 + i) = *((char *)lp + 324 - i);
+	*((char *)lp + 324 - i) = temp;
+	}
+    lpcur->pixshape = XCreatePixmapFromBitmapData(
+    	display, DefaultRootWindow(display), 
+        ((char *)lp + 211), 32, 32,
+/*
+        lpcurdesc->Width / 2, lpcurdesc->Height / 4, 
+*/
+        WhitePixel(display, DefaultScreen(display)), 
+        BlackPixel(display, DefaultScreen(display)), 1);
+    lpcur->pixmask = XCreatePixmapFromBitmapData(
+    	display, DefaultRootWindow(display), 
+        ((char *)lp + 211), 32, 32,
+        WhitePixel(display, DefaultScreen(display)), 
+        BlackPixel(display, DefaultScreen(display)), 1);
+    memset(&bkcolor, 0, sizeof(XColor));
+    memset(&fgcolor, 0, sizeof(XColor));
+    bkcolor.pixel = WhitePixel(display, DefaultScreen(display)); 
+    fgcolor.pixel = BlackPixel(display, DefaultScreen(display));
+    dprintf_cursor(stddeb,"LoadCursor / before XCreatePixmapCursor !\n");
+    lpcur->xcursor = XCreatePixmapCursor(display,
+ 	lpcur->pixshape, lpcur->pixmask, 
+ 	&fgcolor, &bkcolor, lpcur->descriptor.curXHotspot, 
+ 	lpcur->descriptor.curYHotspot);
+    GlobalUnlock(rsc_mem);
+    GlobalFree(rsc_mem);
+/*
+    hCursor = CreateCursor(instance, lpcur->descriptor.curXHotspot, 
+ 	lpcur->descriptor.curYHotspot, 32, 32,
+	(LPSTR)lp + 211, , (LPSTR)lp + 211);
+*/
+    XFreePixmap(display, lpcur->pixshape);
+    XFreePixmap(display, lpcur->pixmask);
+    ReleaseDC(GetDesktopWindow(), hdc); 
+    GlobalUnlock(hCursor);
+    return hCursor;
+}
+
+
+
+/**********************************************************************
+ *			CreateCursor [USER.406]
+ */
+HCURSOR CreateCursor(HANDLE instance, short nXhotspot, short nYhotspot, 
+	short nWidth, short nHeight, LPSTR lpANDbitPlane, LPSTR lpXORbitPlane)
+{
+    XColor	bkcolor;
+    XColor	fgcolor;
+    HCURSOR 	hCursor;
+    CURSORALLOC	  *lpcur;
+    BITMAP 	BitMap;
+    HBITMAP 	hBitMap;
+    HDC 	hMemDC;
+    HDC 	hdc;
+
+    dprintf_resource(stddeb,"CreateCursor: inst=%04x nXhotspot=%d  nYhotspot=%d nWidth=%d nHeight=%d\n",  
+       instance, nXhotspot, nYhotspot, nWidth, nHeight);
+    dprintf_resource(stddeb,"CreateCursor: inst=%04x lpANDbitPlane=%08X lpXORbitPlane=%08X\n",
+	instance, lpANDbitPlane, lpXORbitPlane);
+
+    if (!(hdc = GetDC(GetDesktopWindow()))) return 0;
+    hCursor = GlobalAlloc(GMEM_MOVEABLE, sizeof(CURSORALLOC) + 1024L); 
+    if (hCursor == (HCURSOR)NULL) {
+	ReleaseDC(GetDesktopWindow(), hdc); 
+	return 0;
+	}
+    dprintf_cursor(stddeb,"CreateCursor Alloc hCursor=%X\n", hCursor);
+    lpcur = (CURSORALLOC *)GlobalLock(hCursor);
+    memset(lpcur, 0, sizeof(CURSORALLOC));
+    lpcur->descriptor.curXHotspot = nXhotspot;
+    lpcur->descriptor.curYHotspot = nYhotspot;
+    lpcur->pixshape = XCreatePixmapFromBitmapData(
+    	display, DefaultRootWindow(display), 
+        lpXORbitPlane, nWidth, nHeight,
+        WhitePixel(display, DefaultScreen(display)), 
+        BlackPixel(display, DefaultScreen(display)), 1);
+    lpcur->pixmask = XCreatePixmapFromBitmapData(
+    	display, DefaultRootWindow(display), 
+        lpANDbitPlane, nWidth, nHeight,
+        WhitePixel(display, DefaultScreen(display)), 
+        BlackPixel(display, DefaultScreen(display)), 1);
+    memset(&bkcolor, 0, sizeof(XColor));
+    memset(&fgcolor, 0, sizeof(XColor));
+    bkcolor.pixel = WhitePixel(display, DefaultScreen(display)); 
+    fgcolor.pixel = BlackPixel(display, DefaultScreen(display));
+    lpcur->xcursor = XCreatePixmapCursor(display,
+ 	lpcur->pixshape, lpcur->pixmask, 
+ 	&fgcolor, &bkcolor, lpcur->descriptor.curXHotspot, 
+ 	lpcur->descriptor.curYHotspot);
+    XFreePixmap(display, lpcur->pixshape);
+    XFreePixmap(display, lpcur->pixmask);
+    ReleaseDC(GetDesktopWindow(), hdc); 
+    GlobalUnlock(hCursor);
+    return hCursor;
+}
+
+
+
+/**********************************************************************
+ *			DestroyCursor [USER.458]
+ */
+BOOL DestroyCursor(HCURSOR hCursor)
+{
+    CURSORALLOC	*lpcur;
+    if (hCursor == (HCURSOR)NULL) return FALSE;
+    lpcur = (CURSORALLOC *)GlobalLock(hCursor);
+    if (lpcur->hBitmap != (HBITMAP)NULL) DeleteObject(lpcur->hBitmap);
+    GlobalUnlock(hCursor);
+    GlobalFree(hCursor);
+    return TRUE;
+}
+
+
+/**********************************************************************
+ *         CURSOR_SetCursor
+ *
+ * Internal helper function for SetCursor() and ShowCursor().
+ */
+static BOOL CURSOR_SetCursor( HCURSOR hCursor )
+{
+    CURSORALLOC	*lpcur;
+
+    if (!(lpcur = (CURSORALLOC *)GlobalLock(hCursor))) return FALSE;
+    if (rootWindow != DefaultRootWindow(display))
+    {
+        XDefineCursor( display, rootWindow, lpcur->xcursor );
+    }
+    else
+    {
+        HWND hwnd = GetWindow( GetDesktopWindow(), GW_CHILD );
+        while(hwnd)
+        {
+            Window win = WIN_GetXWindow( hwnd );
+            if (win) XDefineCursor( display, win, lpcur->xcursor );
+            hwnd = GetWindow( hwnd, GW_HWNDNEXT );
+        }
+    }
+    GlobalUnlock( hCursor );
+}
+
+/**********************************************************************
+ *			SetCursor [USER.69]
+ */
+HCURSOR SetCursor(HCURSOR hCursor)
+{
+    HCURSOR hOldCursor;
+
+    dprintf_cursor(stddeb,"SetCursor / hCursor=%04X !\n", hCursor);
+    hOldCursor = hActiveCursor;
+    hActiveCursor = hCursor;
+    if ((hCursor != hOldCursor) || (ShowCursCount < 0))
+    {
+        CURSOR_SetCursor( hCursor );
+    }
+    ShowCursCount = 0;
+    return hOldCursor;
+}
+
+
+/**********************************************************************
+ *			GetCursor [USER.247]
+ */
+HCURSOR GetCursor(void)
+{
+    return hActiveCursor;
+}
+
+
+/**********************************************************************
+ *                        SetCursorPos [USER.70]
+ */
+void SetCursorPos(short x, short y)
+{
+    dprintf_cursor(stddeb,"SetCursorPos // x=%d y=%d\n", x, y);
+    XWarpPointer( display, None, rootWindow, 0, 0, 0, 0, x, y );
+}
+
+
+/**********************************************************************
+ *                        GetCursorPos [USER.17]
+ */
+void GetCursorPos(LPPOINT lpRetPoint)
+{
+    Window 	root, child;
+    int		rootX, rootY;
+    int		childX, childY;
+    unsigned int mousebut;
+
+    if (!lpRetPoint) return;
+    if (!XQueryPointer( display, rootWindow, &root, &child,
+		        &rootX, &rootY, &childX, &childY, &mousebut ))
+	lpRetPoint->x = lpRetPoint->y = 0;
+    else
+    {
+	lpRetPoint->x = rootX + desktopX;
+	lpRetPoint->y = rootY + desktopY;
+    }
+    dprintf_cursor(stddeb,
+		"GetCursorPos // x=%d y=%d\n", lpRetPoint->x, lpRetPoint->y);
+}
+
+
+/**********************************************************************
+ *			ShowCursor [USER.71]
+ */
+int ShowCursor(BOOL bShow)
+{
+    HCURSOR	hCursor;
+
+    dprintf_cursor(stddeb, "ShowCursor(%d), count=%d\n", bShow, ShowCursCount);
+
+    if (bShow)
+    {
+        if (++ShowCursCount == 0)  /* Time to show it */
+            CURSOR_SetCursor( hActiveCursor );
+    }
+    else  /* Hide it */
+    {
+        if (--ShowCursCount == -1)  /* Time to hide it */
+        {
+            if (!hEmptyCursor)
+                hEmptyCursor = CreateCursor( 0, 1, 1, 1, 1,
+                                             "\xFF\xFF", "\xFF\xFF" );
+            CURSOR_SetCursor( hEmptyCursor );
+        }
+    }
+    return 0;
+}
+
+
+/**********************************************************************
+ *                        ClipCursor [USER.16]
+ */
+void ClipCursor(LPRECT lpNewClipRect)
+{
+    CopyRect(&ClipCursorRect, lpNewClipRect);
+}
+
+
+/**********************************************************************
+ *                        GetClipCursor [USER.309]
+ */
+void GetClipCursor(LPRECT lpRetClipRect)
+{
+    if (lpRetClipRect != NULL)
+	CopyRect(lpRetClipRect, &ClipCursorRect);
+}
+
+
+
+
diff --git a/windows/dce.c b/windows/dce.c
index 2148af1..4508fcb 100644
--- a/windows/dce.c
+++ b/windows/dce.c
@@ -11,7 +11,11 @@
 #include "win.h"
 #include "gdi.h"
 #include "user.h"
-#include "icon.h"
+#include "sysmetrics.h"
+#include "stddebug.h"
+/* #define DEBUG_DC /* */
+/* #undef  DEBUG_DC /* */
+#include "debug.h"
 
 
 #define NB_DCE    5  /* Number of DCEs created at startup */
@@ -90,10 +94,11 @@
 /***********************************************************************
  *           DCE_GetVisRect
  *
- * Return the visible rectangle of a window, i.e. the client or
+ * Calc the visible rectangle of a window, i.e. the client or
  * window area clipped by the client area of all ancestors.
+ * Return FALSE if the visible region is empty.
  */
-static void DCE_GetVisRect( WND *wndPtr, BOOL clientArea, RECT *lprect )
+static BOOL DCE_GetVisRect( WND *wndPtr, BOOL clientArea, RECT *lprect )
 {
     int xoffset, yoffset;
 
@@ -101,9 +106,22 @@
     xoffset = lprect->left;
     yoffset = lprect->top;
 
-    while (wndPtr->dwStyle & WS_CHILD)
+    if (!(wndPtr->dwStyle & WS_VISIBLE) || (wndPtr->flags & WIN_NO_REDRAW))
+    {
+        SetRectEmpty( lprect );  /* Clip everything */
+        return FALSE;
+    }
+
+    while (wndPtr->hwndParent)
     {
 	WND *parentPtr = WIN_FindWndPtr( wndPtr->hwndParent );
+        if (!(parentPtr->dwStyle & WS_VISIBLE) ||
+            (parentPtr->flags & WIN_NO_REDRAW) ||
+            (parentPtr->dwStyle & WS_ICONIC))
+        {
+            SetRectEmpty( lprect );  /* Clip everything */
+            return FALSE;
+        }
 	xoffset += parentPtr->rectClient.left;
 	yoffset += parentPtr->rectClient.top;
 	OffsetRect( lprect, parentPtr->rectClient.left,
@@ -111,27 +129,188 @@
 
 	  /* Warning!! we assume that IntersectRect() handles the case */
 	  /* where the destination is the same as one of the sources.  */
-	IntersectRect( lprect, lprect, &parentPtr->rectClient );
+	if (!IntersectRect( lprect, lprect, &parentPtr->rectClient ))
+            return FALSE;  /* Visible rectangle is empty */
 	wndPtr = parentPtr;
     }
     OffsetRect( lprect, -xoffset, -yoffset );
+    return TRUE;
+}
+
+
+/***********************************************************************
+ *           DCE_ClipWindows
+ *
+ * Go through the linked list of windows from hwndStart to hwndEnd,
+ * removing from the given region the rectangle of each window offset
+ * by a given amount.  The new region is returned, and the original one
+ * is destroyed.  Used to implement DCX_CLIPSIBLINGS and
+ * DCX_CLIPCHILDREN styles.
+ */
+static HRGN DCE_ClipWindows( HWND hwndStart, HWND hwndEnd,
+                             HRGN hrgn, int xoffset, int yoffset )
+{
+    HRGN hrgnTmp, hrgnNew;
+    WND *wndPtr;
+
+    if (!hwndStart) return hrgn;
+    for (; hwndStart != hwndEnd; hwndStart = wndPtr->hwndNext)
+    {
+        hrgnTmp = hrgnNew = 0;
+        wndPtr = WIN_FindWndPtr( hwndStart );
+        if (!(wndPtr->dwStyle & WS_VISIBLE)) continue;
+        if (!(hrgnTmp = CreateRectRgn( 0, 0, 0, 0 ))) break;
+        if (!(hrgnNew = CreateRectRgn( wndPtr->rectWindow.left + xoffset,
+                                       wndPtr->rectWindow.top + yoffset,
+                                       wndPtr->rectWindow.right + xoffset,
+                                       wndPtr->rectWindow.bottom + yoffset )))
+            break;
+        if (!CombineRgn( hrgnTmp, hrgn, hrgnNew, RGN_DIFF )) break;
+        DeleteObject( hrgn );
+        DeleteObject( hrgnNew );
+        hrgn = hrgnTmp;
+    }
+    if (hwndStart != hwndEnd)  /* something went wrong */
+    {
+        if (hrgnTmp) DeleteObject( hrgnTmp );
+        if (hrgnNew) DeleteObject( hrgnNew );
+        if (hrgn) DeleteObject( hrgn );
+        return 0;
+    }
+    return hrgn;
+}
+
+
+/***********************************************************************
+ *           DCE_GetVisRgn
+ *
+ * Return the visible region of a window, i.e. the client or window area
+ * clipped by the client area of all ancestors, and then optionally
+ * by siblings and children.
+ */
+static HRGN DCE_GetVisRgn( HWND hwnd, WORD flags )
+{
+    RECT rect;
+    HRGN hrgn;
+    int xoffset, yoffset;
+    WND *wndPtr = WIN_FindWndPtr( hwnd );
+
+      /* Get visible rectangle and create a region with it */
+
+    if (!DCE_GetVisRect( wndPtr, !(flags & DCX_WINDOW), &rect ))
+    {
+        return CreateRectRgn( 0, 0, 0, 0 );  /* Visible region is empty */
+    }
+    if (!(hrgn = CreateRectRgnIndirect( &rect ))) return 0;
+
+      /* Clip all children from the visible region */
+
+    if (flags & DCX_CLIPCHILDREN)
+    {
+        if (flags & DCX_WINDOW)
+        {
+            xoffset = wndPtr->rectClient.left - wndPtr->rectWindow.left;
+            yoffset = wndPtr->rectClient.top - wndPtr->rectWindow.top;
+        }
+        else xoffset = yoffset = 0;
+        hrgn = DCE_ClipWindows( wndPtr->hwndChild, 0, hrgn, xoffset, yoffset );
+        if (!hrgn) return 0;
+    }
+
+      /* Clip siblings placed above this window */
+
+    if (flags & DCX_WINDOW)
+    {
+        xoffset = -wndPtr->rectWindow.left;
+        yoffset = -wndPtr->rectWindow.top;
+    }
+    else
+    {
+        xoffset = -wndPtr->rectClient.left;
+        yoffset = -wndPtr->rectClient.top;
+    }
+    if (flags & DCX_CLIPSIBLINGS)
+    {
+        hrgn = DCE_ClipWindows( GetWindow( wndPtr->hwndParent, GW_CHILD ),
+                                hwnd, hrgn, xoffset, yoffset );
+        if (!hrgn) return 0;
+    }
+
+      /* Clip siblings of all ancestors that have the WS_CLIPSIBLINGS style */
+
+    while (wndPtr->dwStyle & WS_CHILD)
+    {
+        hwnd = wndPtr->hwndParent;
+        wndPtr = WIN_FindWndPtr( hwnd );
+        xoffset -= wndPtr->rectClient.left;
+        yoffset -= wndPtr->rectClient.top;
+        hrgn = DCE_ClipWindows( GetWindow( wndPtr->hwndParent, GW_CHILD ),
+                                hwnd, hrgn, xoffset, yoffset );
+        if (!hrgn) return 0;
+    }
+    return hrgn;
+}
+
+
+/***********************************************************************
+ *           DCE_SetDrawable
+ *
+ * Set the drawable, origin and dimensions for the DC associated to
+ * a given window.
+ */
+static void DCE_SetDrawable( WND *wndPtr, DC *dc, WORD flags )
+{
+    if (!wndPtr)  /* Get a DC for the whole screen */
+    {
+        dc->w.DCOrgX = 0;
+        dc->w.DCOrgY = 0;
+        dc->w.DCSizeX = SYSMETRICS_CXSCREEN;
+        dc->w.DCSizeY = SYSMETRICS_CYSCREEN;
+        dc->u.x.drawable = rootWindow;
+        XSetSubwindowMode( display, dc->u.x.gc, IncludeInferiors );
+    }
+    else
+    {
+        if (flags & DCX_WINDOW)
+        {
+            dc->w.DCOrgX  = wndPtr->rectWindow.left;
+            dc->w.DCOrgY  = wndPtr->rectWindow.top;
+            dc->w.DCSizeX = wndPtr->rectWindow.right - wndPtr->rectWindow.left;
+            dc->w.DCSizeY = wndPtr->rectWindow.bottom - wndPtr->rectWindow.top;
+        }
+        else
+        {
+            dc->w.DCOrgX  = wndPtr->rectClient.left;
+            dc->w.DCOrgY  = wndPtr->rectClient.top;
+            dc->w.DCSizeX = wndPtr->rectClient.right - wndPtr->rectClient.left;
+            dc->w.DCSizeY = wndPtr->rectClient.bottom - wndPtr->rectClient.top;
+        }
+        while (!wndPtr->window)
+        {
+            wndPtr = WIN_FindWndPtr( wndPtr->hwndParent );
+            dc->w.DCOrgX += wndPtr->rectClient.left;
+            dc->w.DCOrgY += wndPtr->rectClient.top;
+        }
+        dc->w.DCOrgX -= wndPtr->rectWindow.left;
+        dc->w.DCOrgY -= wndPtr->rectWindow.top;
+        dc->u.x.drawable = wndPtr->window;
+    }
 }
 
 
 /***********************************************************************
  *           GetDCEx    (USER.359)
  */
-/* Unimplemented flags: DCX_CLIPSIBLINGS, DCX_LOCKWINDOWUPDATE, DCX_PARENTCLIP
+/* Unimplemented flags: DCX_LOCKWINDOWUPDATE
  */
 HDC GetDCEx( HWND hwnd, HRGN hrgnClip, DWORD flags )
 {
     HANDLE hdce;
-    RECT clipRect;
+    HRGN hrgnVisible;
     HDC hdc = 0;
     DCE * dce;
     DC * dc;
     WND * wndPtr;
-    ICONALLOC   *lpico;
     
     if (hwnd)
     {
@@ -141,18 +320,27 @@
 
     if (flags & DCX_USESTYLE)
     {
+        /* Set the flags according to the window style. */
 	/* Not sure if this is the real meaning of the DCX_USESTYLE flag... */
-	flags &= ~(DCX_CACHE | DCX_CLIPCHILDREN | DCX_CLIPSIBLINGS);
+	flags &= ~(DCX_CACHE | DCX_CLIPCHILDREN |
+                   DCX_CLIPSIBLINGS | DCX_PARENTCLIP);
 	if (wndPtr)
 	{
-	    if (!(wndPtr->flags & (WIN_CLASS_DC | WIN_OWN_DC)))
+            if (!(WIN_CLASS_STYLE(wndPtr) & (CS_OWNDC | CS_CLASSDC)))
 		flags |= DCX_CACHE;
+            if (WIN_CLASS_STYLE(wndPtr) & CS_PARENTDC) flags |= DCX_PARENTCLIP;
 	    if (wndPtr->dwStyle & WS_CLIPCHILDREN) flags |= DCX_CLIPCHILDREN;
 	    if (wndPtr->dwStyle & WS_CLIPSIBLINGS) flags |= DCX_CLIPSIBLINGS;
 	}
 	else flags |= DCX_CACHE;
     }
 
+      /* Can only use PARENTCLIP on child windows */
+    if (!wndPtr || !(wndPtr->dwStyle & WS_CHILD)) flags &= ~DCX_PARENTCLIP;
+
+      /* Whole window DC implies children are not clipped */
+    if (flags & DCX_WINDOW) flags &= ~DCX_CLIPCHILDREN;
+
     if (flags & DCX_CACHE)
     {
 	for (hdce = firstDCE; (hdce); hdce = dce->hNext)
@@ -173,50 +361,49 @@
     
     if (!(dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC ))) return 0;
 
-    if (wndPtr)
+    DCE_SetDrawable( wndPtr, dc, flags );
+    if (hwnd)
     {
-	dc->u.x.drawable = wndPtr->window;
-	if (flags & DCX_WINDOW)
-	{
-	    dc->w.DCOrgX  = 0;
-	    dc->w.DCOrgY  = 0;
-	    dc->w.DCSizeX = wndPtr->rectWindow.right - wndPtr->rectWindow.left;
-	    dc->w.DCSizeY = wndPtr->rectWindow.bottom - wndPtr->rectWindow.top;
-	}
-	else
-	{
-	    dc->w.DCOrgX  = wndPtr->rectClient.left - wndPtr->rectWindow.left;
-	    dc->w.DCOrgY  = wndPtr->rectClient.top - wndPtr->rectWindow.top;
-	    dc->w.DCSizeX = wndPtr->rectClient.right - wndPtr->rectClient.left;
-	    dc->w.DCSizeY = wndPtr->rectClient.bottom - wndPtr->rectClient.top;
-	}	
-
-	DCE_GetVisRect( wndPtr, !(flags & DCX_WINDOW), &clipRect );
-	IntersectVisRect( hdc, clipRect.left, clipRect.top,
-			  clipRect.right, clipRect.bottom );
+        if (flags & DCX_PARENTCLIP)  /* Get a VisRgn for the parent */
+        {
+            WND *parentPtr = WIN_FindWndPtr( wndPtr->hwndParent );
+            DWORD newflags = flags & ~(DCX_CLIPSIBLINGS | DCX_CLIPCHILDREN |
+                                       DCX_WINDOW);
+            if (parentPtr->dwStyle & WS_CLIPSIBLINGS)
+                newflags |= DCX_CLIPSIBLINGS;
+            hrgnVisible = DCE_GetVisRgn( wndPtr->hwndParent, newflags );
+            if (flags & DCX_WINDOW)
+                OffsetRgn( hrgnVisible, -wndPtr->rectWindow.left,
+                                        -wndPtr->rectWindow.top );
+            else OffsetRgn( hrgnVisible, -wndPtr->rectClient.left,
+                                         -wndPtr->rectClient.top );
+        }
+        else hrgnVisible = DCE_GetVisRgn( hwnd, flags );
     }
-    else dc->u.x.drawable = rootWindow;
+    else  /* Get a VisRgn for the whole screen */
+    {
+        hrgnVisible = CreateRectRgn( 0, 0, SYSMETRICS_CXSCREEN,
+                                     SYSMETRICS_CYSCREEN);
+    }
 
-    if (flags & DCX_CLIPCHILDREN)
-	XSetSubwindowMode( display, dc->u.x.gc, ClipByChildren );
-    else XSetSubwindowMode( display, dc->u.x.gc, IncludeInferiors);
+      /* Intersect VisRgn with the given region */
 
     if ((flags & DCX_INTERSECTRGN) || (flags & DCX_EXCLUDERGN))
     {
 	HRGN hrgn = CreateRectRgn( 0, 0, 0, 0 );
 	if (hrgn)
 	{
-	    if (CombineRgn( hrgn, InquireVisRgn(hdc), hrgnClip,
-			    (flags & DCX_INTERSECTRGN) ? RGN_AND : RGN_DIFF )) {
-		SelectVisRgn( hdc, hrgn );
-	    }
-	    DeleteObject( hrgn );
+            CombineRgn( hrgn, hrgnVisible, hrgnClip,
+                       (flags & DCX_INTERSECTRGN) ? RGN_AND : RGN_DIFF );
+	    DeleteObject( hrgnVisible );
+            hrgnVisible = hrgn;
 	}
     }
+    SelectVisRgn( hdc, hrgnVisible );
+    DeleteObject( hrgnVisible );
 
-#ifdef DEBUG_DC
-    printf( "GetDCEx(%d,%d,0x%x): returning %d\n", hwnd, hrgnClip, flags, hdc);
-#endif
+    dprintf_dc(stddeb, "GetDCEx(%d,%d,0x%x): returning %d\n", 
+	       hwnd, hrgnClip, flags, hdc);
     return hdc;
 }
 
@@ -240,7 +427,7 @@
     {
 	WND * wndPtr;
 	if (!(wndPtr = WIN_FindWndPtr( hwnd ))) return 0;
-	if (wndPtr->dwStyle & WS_CLIPCHILDREN) flags |= DCX_CLIPCHILDREN;
+/*	if (wndPtr->dwStyle & WS_CLIPCHILDREN) flags |= DCX_CLIPCHILDREN; */
 	if (wndPtr->dwStyle & WS_CLIPSIBLINGS) flags |= DCX_CLIPSIBLINGS;
     }
     return GetDCEx( hwnd, 0, flags );
@@ -255,9 +442,7 @@
     HANDLE hdce;
     DCE * dce = NULL;
     
-#ifdef DEBUG_DC
-    printf( "ReleaseDC: %d %d\n", hwnd, hdc );
-#endif
+    dprintf_dc(stddeb, "ReleaseDC: %d %d\n", hwnd, hdc );
         
     for (hdce = firstDCE; (hdce); hdce = dce->hNext)
     {
diff --git a/windows/defdlg.c b/windows/defdlg.c
index 2e5607d..c223035 100644
--- a/windows/defdlg.c
+++ b/windows/defdlg.c
@@ -9,6 +9,109 @@
 #include "windows.h"
 #include "dialog.h"
 #include "win.h"
+#include "stddebug.h"
+/* #define DEBUG_DIALOG /* */
+/* #undef  DEBUG_DIALOG /* */
+#include "debug.h"
+
+
+extern HWND DIALOG_GetFirstTabItem( HWND hwndDlg );  /* windows/dialog.c */
+
+
+/***********************************************************************
+ *           DEFDLG_SetFocus
+ *
+ * Set the focus to a control of the dialog, selecting the text if
+ * the control is an edit dialog.
+ */
+static void DEFDLG_SetFocus( HWND hwndDlg, HWND hwndCtrl )
+{
+    int dlgCode;
+    HWND hwndPrev = GetFocus();
+
+    if (IsChild( hwndDlg, hwndPrev ))
+    {
+        if (SendMessage( hwndPrev, WM_GETDLGCODE, 0, 0 ) & DLGC_HASSETSEL)
+            SendMessage( hwndPrev, EM_SETSEL, TRUE, MAKELONG( -1, 0 ) );
+    }
+    if (SendMessage( hwndCtrl, WM_GETDLGCODE, 0, 0 ) & DLGC_HASSETSEL)
+        SendMessage( hwndCtrl, EM_SETSEL, FALSE, MAKELONG( 0, -1 ) );
+    SetFocus( hwndCtrl );
+}
+
+
+/***********************************************************************
+ *           DEFDLG_SaveFocus
+ */
+static BOOL DEFDLG_SaveFocus( HWND hwnd, DIALOGINFO *infoPtr )
+{
+    HWND hwndFocus = GetFocus();
+
+    if (!hwndFocus || !IsChild( hwnd, hwndFocus )) return FALSE;
+    if (!infoPtr->hwndFocus) return FALSE;  /* Already saved */
+    infoPtr->hwndFocus = hwndFocus;
+      /* Remove default button */
+    return TRUE;
+}
+
+
+/***********************************************************************
+ *           DEFDLG_RestoreFocus
+ */
+static BOOL DEFDLG_RestoreFocus( HWND hwnd, DIALOGINFO *infoPtr )
+{
+    if (!infoPtr->hwndFocus || IsIconic(hwnd)) return FALSE;
+    if (!IsWindow( infoPtr->hwndFocus )) return FALSE;
+    DEFDLG_SetFocus( hwnd, infoPtr->hwndFocus );
+    infoPtr->hwndFocus = 0;
+    return TRUE;
+}
+
+
+/***********************************************************************
+ *           DEFDLG_FindDefButton
+ *
+ * Find the current default push-button.
+ */
+static HWND DEFDLG_FindDefButton( HWND hwndDlg )
+{
+    HWND hwndChild = GetWindow( hwndDlg, GW_CHILD );
+    while (hwndChild)
+    {
+        if (SendMessage( hwndChild, WM_GETDLGCODE, 0, 0 ) & DLGC_DEFPUSHBUTTON)
+            break;
+        hwndChild = GetWindow( hwndChild, GW_HWNDNEXT );
+    }
+    return hwndChild;
+}
+
+
+/***********************************************************************
+ *           DEFDLG_SetDefButton
+ *
+ * Set the new default button to be hwndNew.
+ */
+static BOOL DEFDLG_SetDefButton( HWND hwndDlg, DIALOGINFO *dlgInfo,
+                                 HWND hwndNew )
+{
+    if (hwndNew &&
+        !(SendMessage( hwndNew, WM_GETDLGCODE, 0, 0 ) & DLGC_UNDEFPUSHBUTTON))
+        return FALSE;  /* Destination is not a push button */
+    
+    if (dlgInfo->msgResult)  /* There's already a default pushbutton */
+    {
+        HWND hwndOld = GetDlgItem( hwndDlg, dlgInfo->msgResult );
+        if (SendMessage( hwndOld, WM_GETDLGCODE, 0, 0 ) & DLGC_DEFPUSHBUTTON)
+            SendMessage( hwndOld, BM_SETSTYLE, BS_PUSHBUTTON, TRUE );
+    }
+    if (hwndNew)
+    {
+        SendMessage( hwndNew, BM_SETSTYLE, BS_DEFPUSHBUTTON, TRUE );
+        dlgInfo->msgResult = GetDlgCtrlID( hwndNew );
+    }
+    else dlgInfo->msgResult = 0;
+    return TRUE;
+}
 
 
 /***********************************************************************
@@ -23,9 +126,8 @@
     if (!wndPtr) return 0;
     dlgInfo = (DIALOGINFO *)&wndPtr->wExtra;
 
-#ifdef DEBUG_DIALOG
-    printf( "DefDlgProc: %d %04x %d %08x\n", hwnd, msg, wParam, lParam );
-#endif
+    dprintf_dialog(stddeb, "DefDlgProc: %d %04x %d %08x\n", 
+		   hwnd, msg, wParam, lParam );
 
     dlgInfo->msgResult = 0;
     if (dlgInfo->dlgProc)
@@ -75,7 +177,46 @@
 	      /* Window clean-up */
 	    DefWindowProc( hwnd, msg, wParam, lParam );
 	    break;
-	    
+
+	case WM_SHOWWINDOW:
+	    if (!wParam) DEFDLG_SaveFocus( hwnd, dlgInfo );
+	    return DefWindowProc( hwnd, msg, wParam, lParam );
+
+	case WM_ACTIVATE:
+	    if (wParam) DEFDLG_RestoreFocus( hwnd, dlgInfo );
+	    else DEFDLG_SaveFocus( hwnd, dlgInfo );
+	    break;
+
+	case WM_SETFOCUS:
+	    DEFDLG_RestoreFocus( hwnd, dlgInfo );
+	    break;
+
+        case DM_SETDEFID:
+            if (dlgInfo->fEnd) return TRUE;
+            DEFDLG_SetDefButton( hwnd, dlgInfo,
+                                 wParam ? GetDlgItem( hwnd, wParam ) : 0 );
+            return TRUE;
+
+        case DM_GETDEFID:
+            if (dlgInfo->fEnd || !dlgInfo->msgResult) return 0;
+            return MAKELONG( dlgInfo->msgResult, DC_HASDEFID );
+
+	case WM_NEXTDLGCTL:
+	    {
+                HWND hwndDest = wParam;
+                if (!lParam)
+                {
+                    HWND hwndPrev = GetFocus();
+                    if (!hwndPrev)  /* Set focus to the first item */
+                        hwndDest = DIALOG_GetFirstTabItem( hwnd );
+                    else
+                        hwndDest = GetNextDlgTabItem( hwnd, hwndPrev, wParam );
+                }
+                if (hwndDest) DEFDLG_SetFocus( hwnd, hwndDest );
+                DEFDLG_SetDefButton( hwnd, dlgInfo, hwndDest );
+            }
+            break;
+
 	default:
 	    return DefWindowProc( hwnd, msg, wParam, lParam );
     }
diff --git a/windows/defwnd.c b/windows/defwnd.c
index 071e681..501ad78 100644
--- a/windows/defwnd.c
+++ b/windows/defwnd.c
@@ -13,6 +13,11 @@
 #include "class.h"
 #include "user.h"
 #include "syscolor.h"
+#include "stddebug.h"
+/* #define DEBUG_MESSAGE /* */
+/* #undef  DEBUG_MESSAGE /* */
+#include "debug.h"
+
 
   /* Last COLOR id */
 #define COLOR_MAX   COLOR_BTNHIGHLIGHT
@@ -57,9 +62,8 @@
 	int len;
 	WND * wndPtr = WIN_FindWndPtr( hwnd );
     
-#ifdef DEBUG_MESSAGE
-    printf( "DefWindowProc: %d %d %d %08x\n", hwnd, msg, wParam, lParam );
-#endif
+    dprintf_message(stddeb, "DefWindowProc: %d %d %d %08x\n", 
+		    hwnd, msg, wParam, lParam );
 
     switch(msg)
     {
@@ -109,6 +113,15 @@
 	    return 0;
 	}
 
+    case WM_SETREDRAW:
+        if (wParam)
+        {
+            ValidateRect( hwnd, NULL );
+            wndPtr->flags |= WIN_NO_REDRAW;
+        }
+        else wndPtr->flags &= ~WIN_NO_REDRAW;
+        return 0;
+
     case WM_CLOSE:
 	DestroyWindow( hwnd );
 	return 0;
diff --git a/windows/dialog.c b/windows/dialog.c
index eeb5311..fed61e0 100644
--- a/windows/dialog.c
+++ b/windows/dialog.c
@@ -1,12 +1,11 @@
 /*
  * Dialog functions
  *
- * Copyright 1993 Alexandre Julliard
+ * Copyright 1993, 1994 Alexandre Julliard
  */
 
-/* #define DEBUG_DIALOG /* */
 
-static char Copyright[] = "Copyright  Alexandre Julliard, 1993";
+static char Copyright[] = "Copyright  Alexandre Julliard, 1993, 1994";
 
 #include <stdlib.h>
 #include <stdio.h>
@@ -17,6 +16,10 @@
 #include "user.h"
 #include "message.h"
 #include "heap.h"
+#include "stddebug.h"
+/* #define DEBUG_DIALOG /* */
+/* #undef  DEBUG_DIALOG /* */
+#include "debug.h"
 
 
   /* Dialog base units */
@@ -40,14 +43,32 @@
     ReleaseDC( 0, hdc );
     xBaseUnit = tm.tmAveCharWidth;
     yBaseUnit = tm.tmHeight;
-#ifdef DEBUG_DIALOG
-    printf( "DIALOG_Init: base units = %d,%d\n", xBaseUnit, yBaseUnit );
-#endif    
+    dprintf_dialog(stddeb, "DIALOG_Init: base units = %d,%d\n", xBaseUnit, yBaseUnit );
     return TRUE;
 }
 
 
 /***********************************************************************
+ *           DIALOG_GetFirstTabItem
+ *
+ * Return the first item of the dialog that has the WS_TABSTOP style.
+ */
+HWND DIALOG_GetFirstTabItem( HWND hwndDlg )
+{
+    HWND hwnd;
+    WND *wndPtr = WIN_FindWndPtr( hwndDlg );
+    hwnd = wndPtr->hwndChild;
+    while(hwnd)
+    {
+        wndPtr = WIN_FindWndPtr( hwnd );
+        if (wndPtr->dwStyle & WS_TABSTOP) break;
+        hwnd = wndPtr->hwndNext;
+    }
+    return hwnd;
+}
+
+
+/***********************************************************************
  *           DIALOG_GetControl
  *
  * Return the class and text of the control pointed to by ptr,
@@ -56,7 +77,6 @@
 static DLGCONTROLHEADER * DIALOG_GetControl( DLGCONTROLHEADER * ptr,
 					     char ** class, char ** text )
 {
-    int i;
     unsigned char * p = (unsigned char *)ptr;
     p += 14;  /* size of control header */
 
@@ -134,16 +154,17 @@
 #ifdef DEBUG_DIALOG
 static void DIALOG_DisplayTemplate( DLGTEMPLATE * result )
 {
-    printf( "DIALOG %d, %d, %d, %d\n", result->header->x, result->header->y,
+    dprintf_dialog(stddeb, "DIALOG %d, %d, %d, %d\n", result->header->x, result->header->y,
 	    result->header->cx, result->header->cy );
-    printf( " STYLE %08x\n", result->header->style );
-    printf( " CAPTION '%s'\n", result->caption );
-    printf( " CLASS '%s'\n", result->className );
+    dprintf_dialog(stddeb, " STYLE %08x\n", result->header->style );
+    dprintf_dialog(stddeb, " CAPTION '%s'\n", result->caption );
+    dprintf_dialog(stddeb, " CLASS '%s'\n", result->className );
     if (result->menuName[0] == 0xff)
-	printf( " MENU %d\n", result->menuName[1] + 256*result->menuName[2] );
-    else printf( " MENU '%s'\n", result->menuName );
+	dprintf_dialog(stddeb, " MENU %d\n", result->menuName[1] + 256*result->menuName[2] );
+    else 
+        dprintf_dialog(stddeb, " MENU '%s'\n", result->menuName );
     if (result->header->style & DS_SETFONT)
-	printf( " FONT %d,'%s'\n", result->pointSize, result->faceName );
+	dprintf_dialog(stddeb, " FONT %d,'%s'\n", result->pointSize, result->faceName );
 }
 #endif  /* DEBUG_DIALOG */
 
@@ -152,7 +173,7 @@
  *           CreateDialog   (USER.89)
  */
 HWND CreateDialog( HINSTANCE hInst, LPCSTR dlgTemplate,
-		   HWND owner, FARPROC dlgProc )
+		   HWND owner, WNDPROC dlgProc )
 {
     return CreateDialogParam( hInst, dlgTemplate, owner, dlgProc, 0 );
 }
@@ -162,16 +183,14 @@
  *           CreateDialogParam   (USER.241)
  */
 HWND CreateDialogParam( HINSTANCE hInst, LPCSTR dlgTemplate,
-		        HWND owner, FARPROC dlgProc, LPARAM param )
+		        HWND owner, WNDPROC dlgProc, LPARAM param )
 {
     HWND hwnd = 0;
     HANDLE hres, hmem;
     LPCSTR data;
 
-#ifdef DEBUG_DIALOG
-    printf( "CreateDialogParam: %d,'%x',%d,%p,%d\n",
+    dprintf_dialog(stddeb, "CreateDialogParam: %d,'%x',%d,%p,%d\n",
 	    hInst, dlgTemplate, owner, dlgProc, param );
-#endif
      
       /* FIXME: MAKEINTRESOURCE should be replaced by RT_DIALOG */
     if (!(hres = FindResource( hInst, dlgTemplate, MAKEINTRESOURCE(0x8005) )))
@@ -188,7 +207,7 @@
  *           CreateDialogIndirect   (USER.219)
  */
 HWND CreateDialogIndirect( HINSTANCE hInst, LPCSTR dlgTemplate,
-			   HWND owner, FARPROC dlgProc )
+			   HWND owner, WNDPROC dlgProc )
 {
     return CreateDialogIndirectParam( hInst, dlgTemplate, owner, dlgProc, 0 );
 }
@@ -198,11 +217,11 @@
  *           CreateDialogIndirectParam   (USER.242)
  */
 HWND CreateDialogIndirectParam( HINSTANCE hInst, LPCSTR dlgTemplate,
-			        HWND owner, FARPROC dlgProc, LPARAM param )
+			        HWND owner, WNDPROC dlgProc, LPARAM param )
 {
     HMENU hMenu;
     HFONT hFont = 0;
-    HWND hwnd;
+    HWND hwnd, hwndCtrl;
     RECT rect;
     WND * wndPtr;
     int i;
@@ -288,61 +307,72 @@
 
       /* Create control windows */
 
-#ifdef DEBUG_DIALOG
-    printf( " BEGIN\n" );
-#endif	
+    dprintf_dialog(stddeb, " BEGIN\n" );
 
     wndPtr = WIN_FindWndPtr( hwnd );
     dlgInfo = (DIALOGINFO *)wndPtr->wExtra;
+    dlgInfo->msgResult = 0;  /* This is used to store the default button id */
     dlgInfo->hDialogHeap = 0;
 
     for (i = 0; i < template.header->nbItems; i++)
     {
 	DLGCONTROLHEADER * next_header;
 	LPSTR class, text;
+        HWND hwndDefButton = 0;
 	next_header = DIALOG_GetControl( header, &class, &text );
 
-#ifdef DEBUG_DIALOG
-	printf( "   %s ", class);
-	if ((int)text & 0xffff0000) printf("'%s'", text);
-	else printf("%4X", (int)text & 0xffff);
-	printf(" %d, %d, %d, %d, %d, %08x\n", header->id, header->x, header->y, 
+	dprintf_dialog(stddeb, "   %s ", class);
+	if ((int)text & 0xffff0000) 
+	  dprintf_dialog(stddeb,"'%s'", text);
+	else 
+	  dprintf_dialog(stddeb,"%4X", (int)text & 0xffff);
+	dprintf_dialog(stddeb," %d, %d, %d, %d, %d, %08x\n", 
+		header->id, header->x, header->y, 
 		header->cx, header->cy, header->style );
-#endif
 
 	if ((strcmp(class, "EDIT") == 0) &&
 	            ((header->style & DS_LOCALEDIT) != DS_LOCALEDIT)) {
 	    if (!dlgInfo->hDialogHeap) {
 		dlgInfo->hDialogHeap = GlobalAlloc(GMEM_FIXED, 0x10000);
 		if (!dlgInfo->hDialogHeap) {
-		    printf("CreateDialogIndirectParam: Insufficient memory ",
+		    fprintf(stderr,"CreateDialogIndirectParam: Insufficient memory ",
 			   "to create heap for edit control\n");
 		    continue;
 		}
 		dlgHeapBase = GlobalLock(dlgInfo->hDialogHeap);
-		HEAP_Init(&dlgHeap, dlgHeapBase, 0x10000);
+		HEAP_Init(dlgHeapBase,dlgHeapBase+sizeof(char*), 0x10000-sizeof(char*));
 	    }
 	    header->style |= WS_CHILD;
-	    CreateWindowEx( WS_EX_NOPARENTNOTIFY, 
-			   class, text, header->style,
-			   header->x * xUnit / 4, header->y * yUnit / 8,
-			   header->cx * xUnit / 4, header->cy * yUnit / 8,
-			   hwnd, header->id, HIWORD((LONG)dlgHeapBase), NULL );
+	    hwndCtrl = CreateWindowEx( WS_EX_NOPARENTNOTIFY, 
+                           class, text, header->style,
+                           header->x * xUnit / 4, header->y * yUnit / 8,
+                           header->cx * xUnit / 4, header->cy * yUnit / 8,
+                           hwnd, header->id, dlgInfo->hDialogHeap, NULL );
 	}
-	else {
+	else
+        {
 	    header->style |= WS_CHILD;
-	    CreateWindowEx( WS_EX_NOPARENTNOTIFY, 
-			   class, text, header->style,
-			   header->x * xUnit / 4, header->y * yUnit / 8,
-			   header->cx * xUnit / 4, header->cy * yUnit / 8,
-			   hwnd, header->id, hInst, NULL );
+	    hwndCtrl = CreateWindowEx( WS_EX_NOPARENTNOTIFY, 
+                                class, text, header->style,
+                                header->x * xUnit / 4, header->y * yUnit / 8,
+                                header->cx * xUnit / 4, header->cy * yUnit / 8,
+                                hwnd, header->id, hInst, NULL );
 	}
+            /* Send initialisation messages to the control */
+        if (hFont) SendMessage( hwndCtrl, WM_SETFONT, hFont, 0 );
+        if (SendMessage( hwndCtrl, WM_GETDLGCODE, 0, 0 ) & DLGC_DEFPUSHBUTTON)
+        {
+              /* If there's already a default push-button, set it back */
+              /* to normal and use this one instead. */
+            if (hwndDefButton)
+                SendMessage( hwndDefButton, BM_SETSTYLE, BS_PUSHBUTTON, FALSE);
+            hwndDefButton = hwndCtrl;
+            dlgInfo->msgResult = header->id;
+        }
 	header = next_header;
     }    
 
-#ifdef DEBUG_DIALOG
-    printf( " END\n" );
-#endif	
+    dprintf_dialog(stddeb, " END\n" );
     
       /* Initialise dialog extra data */
 
@@ -351,8 +381,7 @@
     dlgInfo->hMenu     = hMenu;
     dlgInfo->xBaseUnit = xUnit;
     dlgInfo->yBaseUnit = yUnit;
-    dlgInfo->hwndFocus = GetNextDlgTabItem( hwnd,
-			    GetWindow(wndPtr->hwndChild, GW_HWNDLAST), FALSE );
+    dlgInfo->hwndFocus = DIALOG_GetFirstTabItem( hwnd );
 
       /* Send initialisation messages and set focus */
 
@@ -376,14 +405,18 @@
     MSG* lpmsg;
     int retval;
 
+      /* Owner must be a top-level window */
+    while (owner && GetParent(owner)) owner = GetParent(owner);
     if (!(wndPtr = WIN_FindWndPtr( hwnd ))) return -1;
     if (!(msgHandle = USER_HEAP_ALLOC( GMEM_MOVEABLE, sizeof(MSG)))) return -1;
     lpmsg = (MSG *) USER_HEAP_ADDR( msgHandle );
     dlgInfo = (DIALOGINFO *)wndPtr->wExtra;
+    EnableWindow( owner, FALSE );
     ShowWindow( hwnd, SW_SHOW );
 
-    while (MSG_InternalGetMessage( lpmsg, hwnd, owner, MSGF_DIALOGBOX,
-				   PM_REMOVE, TRUE ))
+    while (MSG_InternalGetMessage( lpmsg, hwnd, owner,
+                                   MSGF_DIALOGBOX, PM_REMOVE,
+                                   !(wndPtr->dwStyle & DS_NOIDLEMSG) ))
     {
 	if (!IsDialogMessage( hwnd, lpmsg))
 	{
@@ -395,6 +428,7 @@
     retval = dlgInfo->msgResult;
     DestroyWindow( hwnd );
     USER_HEAP_FREE( msgHandle );
+    EnableWindow( owner, TRUE );
     return retval;
 }
 
@@ -403,7 +437,7 @@
  *           DialogBox   (USER.87)
  */
 int DialogBox( HINSTANCE hInst, LPCSTR dlgTemplate,
-	       HWND owner, FARPROC dlgProc )
+	       HWND owner, WNDPROC dlgProc )
 {
     return DialogBoxParam( hInst, dlgTemplate, owner, dlgProc, 0 );
 }
@@ -413,14 +447,12 @@
  *           DialogBoxParam   (USER.239)
  */
 int DialogBoxParam( HINSTANCE hInst, LPCSTR dlgTemplate,
-		    HWND owner, FARPROC dlgProc, LPARAM param )
+		    HWND owner, WNDPROC dlgProc, LPARAM param )
 {
     HWND hwnd;
     
-#ifdef DEBUG_DIALOG
-    printf( "DialogBoxParam: %d,'%x',%d,%p,%d\n",
+    dprintf_dialog(stddeb, "DialogBoxParam: %d,'%x',%d,%p,%d\n",
 	    hInst, dlgTemplate, owner, dlgProc, param );
-#endif
     hwnd = CreateDialogParam( hInst, dlgTemplate, owner, dlgProc, param );
     if (hwnd) return DIALOG_DoDialogBox( hwnd, owner );
     return -1;
@@ -431,7 +463,7 @@
  *           DialogBoxIndirect   (USER.218)
  */
 int DialogBoxIndirect( HINSTANCE hInst, HANDLE dlgTemplate,
-		       HWND owner, FARPROC dlgProc )
+		       HWND owner, WNDPROC dlgProc )
 {
     return DialogBoxIndirectParam( hInst, dlgTemplate, owner, dlgProc, 0 );
 }
@@ -441,7 +473,7 @@
  *           DialogBoxIndirectParam   (USER.240)
  */
 int DialogBoxIndirectParam( HINSTANCE hInst, HANDLE dlgTemplate,
-			    HWND owner, FARPROC dlgProc, LPARAM param )
+			    HWND owner, WNDPROC dlgProc, LPARAM param )
 {
     HWND hwnd;
     LPCSTR ptr;
@@ -463,9 +495,7 @@
     DIALOGINFO * dlgInfo = (DIALOGINFO *)wndPtr->wExtra;
     dlgInfo->msgResult = retval;
     dlgInfo->fEnd = TRUE;
-#ifdef DEBUG_DIALOG
-    printf( "EndDialog: %d %d\n", hwnd, retval );
-#endif    
+    dprintf_dialog(stddeb, "EndDialog: %d %d\n", hwnd, retval );
 }
 
 
@@ -475,21 +505,90 @@
 BOOL IsDialogMessage( HWND hwndDlg, LPMSG msg )
 {
     WND * wndPtr;
-    
+    int dlgCode;
+
     if (!(wndPtr = WIN_FindWndPtr( hwndDlg ))) return FALSE;
     if ((hwndDlg != msg->hwnd) && !IsChild( hwndDlg, msg->hwnd )) return FALSE;
 
-    if (msg->message != WM_KEYDOWN)
+      /* Only the key messages get special processing */
+    if ((msg->message == WM_KEYDOWN) ||
+        (msg->message == WM_SYSCHAR) ||
+	(msg->message == WM_CHAR))
     {
-	SendMessage( msg->hwnd, msg->message, msg->wParam, msg->lParam );
+	dlgCode = SendMessage( msg->hwnd, WM_GETDLGCODE, 0, 0 );
+        if (dlgCode & DLGC_WANTMESSAGE)
+        {
+            DispatchMessage( msg );
+            return TRUE;
+        }
     }
-    else
+
+    switch(msg->message)
     {
-	int dlgCode = SendMessage( msg->hwnd, WM_GETDLGCODE, 0, 0 );
-	/* Process key message */
-	/* .... */
-	SendMessage( msg->hwnd, msg->message, msg->wParam, msg->lParam );
+    case WM_KEYDOWN:
+        if (dlgCode & DLGC_WANTALLKEYS) break;
+        switch(msg->wParam)
+        {
+        case VK_TAB:
+            if (!(dlgCode & DLGC_WANTTAB))
+            {
+                SendMessage( hwndDlg, WM_NEXTDLGCTL,
+                             !(GetKeyState(VK_SHIFT) & 0x80), 0 );
+                return TRUE;
+            }
+            break;
+            
+        case VK_RIGHT:
+        case VK_DOWN:
+            if (!(dlgCode & DLGC_WANTARROWS))
+            {
+                SetFocus(GetNextDlgGroupItem(hwndDlg,GetFocus(),TRUE));
+                return TRUE;
+            }
+            break;
+
+        case VK_LEFT:
+        case VK_UP:
+            if (!(dlgCode & DLGC_WANTARROWS))
+            {
+                SetFocus(GetNextDlgGroupItem(hwndDlg,GetFocus(),FALSE));
+                return TRUE;
+            }
+            break;
+
+        case VK_ESCAPE:
+            SendMessage( hwndDlg, WM_COMMAND, IDCANCEL,
+                         MAKELPARAM( GetDlgItem(hwndDlg,IDCANCEL), 0 ));
+            break;
+
+        case VK_RETURN:
+            {
+                DWORD dw = SendMessage( hwndDlg, DM_GETDEFID, 0, 0 );
+                if (HIWORD(dw) == DC_HASDEFID)
+                    SendMessage( hwndDlg, WM_COMMAND, LOWORD(dw),
+                                 MAKELPARAM( GetDlgItem( hwndDlg, LOWORD(dw) ),
+                                             BN_CLICKED ));
+                else
+                    SendMessage( hwndDlg, WM_COMMAND, IDOK,
+                                 MAKELPARAM( GetDlgItem(hwndDlg,IDOK), 0 ));
+            }
+            break;
+        }
+        break;  /* case WM_KEYDOWN */
+
+        
+    case WM_CHAR:
+        if (dlgCode & (DLGC_WANTALLKEYS | DLGC_WANTCHARS)) break;
+        break;
+
+    case WM_SYSCHAR:
+        if (dlgCode & DLGC_WANTALLKEYS) break;
+        break;
     }
+
+      /* If we get here, the message has not been treated specially */
+      /* and can be sent to its destination window. */
+    DispatchMessage( msg );
     return TRUE;
 }
 
@@ -674,29 +773,57 @@
  */
 HWND GetNextDlgGroupItem( HWND hwndDlg, HWND hwndCtrl, BOOL fPrevious )
 {
-    HWND hwnd, hwndLast;
+    HWND hwnd, hwndStart;
     WND * dlgPtr, * ctrlPtr, * wndPtr;
 
     if (!(dlgPtr = WIN_FindWndPtr( hwndDlg ))) return 0;
     if (!(ctrlPtr = WIN_FindWndPtr( hwndCtrl ))) return 0;
     if (ctrlPtr->hwndParent != hwndDlg) return 0;
 
-    hwndLast = hwndCtrl;
-    hwnd = ctrlPtr->hwndNext;
-    while (1)
+    if (!fPrevious && ctrlPtr->hwndNext)  /*Check if next control is in group*/
     {
-	if (!hwnd) hwnd = dlgPtr->hwndChild;
-	if (hwnd == hwndCtrl) break;
+	wndPtr = WIN_FindWndPtr( ctrlPtr->hwndNext );
+        if (!(wndPtr->dwStyle & WS_GROUP)) return ctrlPtr->hwndNext;
+    }
+
+    if (ctrlPtr->dwStyle & WS_GROUP)  /* Control is the first of the group */
+    {
+        if (!fPrevious) return hwndCtrl;  /* Control is alone in his group */
+        hwnd = ctrlPtr->hwndNext;
+        while(hwnd)  /* Find last control of the group */
+        {
+            wndPtr = WIN_FindWndPtr( hwnd );
+            if (wndPtr->dwStyle & WS_GROUP) break;
+            hwndCtrl = hwnd;
+            hwnd = wndPtr->hwndNext;
+        }
+        return hwndCtrl;
+    }
+    
+      /* Now we will have to find the start of the group */
+
+    hwndStart = 0;
+    hwnd = dlgPtr->hwndChild;
+    while (hwnd)
+    {
 	wndPtr = WIN_FindWndPtr( hwnd );
-	if (wndPtr->dwStyle & WS_TABSTOP)
-	{
-	    hwndLast = hwnd;
-	    if (!fPrevious) break;
-	}
+        if (wndPtr->dwStyle & WS_GROUP) hwndStart = hwnd;  /*Start of a group*/
+        if (hwnd == hwndCtrl)
+        {
+            /* We found the control -> hwndStart is the first of the group */
+            if (!fPrevious) return hwndStart;
+
+            while(hwndStart)  /* Find the control placed before hwndCtrl */
+            {
+                wndPtr = WIN_FindWndPtr( hwndStart );
+                if (wndPtr->hwndNext == hwndCtrl) return hwndStart;
+                hwndStart = wndPtr->hwndNext;
+            }
+            break;
+        }
 	hwnd = wndPtr->hwndNext;
     }
-    return hwndLast;
-    return 0;
+    return hwndCtrl;  /* Not found -> return original control */
 }
 
 
diff --git a/windows/event.c b/windows/event.c
index a1dd581..9da6617 100644
--- a/windows/event.c
+++ b/windows/event.c
@@ -16,6 +16,13 @@
 #include "win.h"
 #include "class.h"
 #include "message.h"
+#include "stddebug.h"
+/* #define DEBUG_EVENT /* */
+/* #undef  DEBUG_EVENT /* */
+/* #define DEBUG_KEY   /* */
+/* #undef  DEBUG_KEY   /* */
+#include "debug.h"
+
 
 #ifdef ndef
 #ifndef FamilyAmoeba
@@ -45,7 +52,6 @@
 static WORD ALTKeyState;
 static HWND captureWnd = 0;
 static BOOL	InputEnabled = TRUE;
-Window winHasCursor = 0;
 
 /* Keyboard translation tables */
 static int special_key[] =
@@ -114,7 +120,6 @@
 static BOOL KeyDown = FALSE;
 
 
-#ifdef DEBUG_EVENT
 static char *event_names[] =
 {
     "", "", "KeyPress", "KeyRelease", "ButtonPress", "ButtonRelease",
@@ -126,14 +131,12 @@
     "SelectionClear", "SelectionRequest", "SelectionNotify", "ColormapNotify",
     "ClientMessage", "MappingNotify"
 };
-#endif
 
   /* Event handlers */
-static void EVENT_key( HWND hwnd, XKeyEvent *event );
+static void EVENT_key( XKeyEvent *event );
 static void EVENT_ButtonPress( XButtonEvent *event );
 static void EVENT_ButtonRelease( XButtonEvent *event );
 static void EVENT_MotionNotify( XMotionEvent *event );
-static void EVENT_EnterNotify( XCrossingEvent *event );
 static void EVENT_FocusOut( HWND hwnd, XFocusChangeEvent *event );
 static void EVENT_Expose( HWND hwnd, XExposeEvent *event );
 static void EVENT_ConfigureNotify( HWND hwnd, XConfigureEvent *event );
@@ -152,15 +155,14 @@
     XFindContext( display, ((XAnyEvent *)event)->window, winContext, &ptr );
     hwnd = (HWND) (int)ptr;
 
-#ifdef DEBUG_EVENT
-    printf( "Got event %s for hwnd %d\n", event_names[event->type], hwnd );
-#endif
+    dprintf_event(stddeb, "Got event %s for hwnd %d\n", 
+		  event_names[event->type], hwnd );
 
     switch(event->type)
     {
     case KeyPress:
     case KeyRelease:
-	EVENT_key( hwnd, (XKeyEvent*)event );
+	EVENT_key( (XKeyEvent*)event );
 	break;
 	
     case ButtonPress:
@@ -185,10 +187,6 @@
 	EVENT_MotionNotify( (XMotionEvent*)event );
 	break;
 
-    case EnterNotify:
-	EVENT_EnterNotify( (XCrossingEvent*)event );
-	break;
-
     case FocusOut:
 	EVENT_FocusOut( hwnd, (XFocusChangeEvent*)event );
 	break;
@@ -201,12 +199,10 @@
 	EVENT_ConfigureNotify( hwnd, (XConfigureEvent*)event );
 	break;
 
-#ifdef DEBUG_EVENT
     default:    
-	printf( "Unprocessed event %s for hwnd %d\n",
+	dprintf_event(stddeb, "Unprocessed event %s for hwnd %d\n",
 	        event_names[event->type], hwnd );
 	break;
-#endif	
     }
 }
 
@@ -257,11 +253,10 @@
     rect.top  = event->y - (wndPtr->rectClient.top - wndPtr->rectWindow.top);
     rect.right  = rect.left + event->width;
     rect.bottom = rect.top + event->height;
-    winHasCursor = event->window;
 
-    flags = RDW_INVALIDATE | RDW_ERASE | RDW_FRAME;
+    flags = RDW_INVALIDATE | RDW_ERASE | RDW_FRAME | RDW_ALLCHILDREN;
       /* Erase desktop background synchronously */
-    if (event->window == rootWindow) flags |= RDW_ERASENOW | RDW_NOCHILDREN;
+/*     if (event->window == rootWindow) flags |= RDW_ERASENOW | RDW_NOCHILDREN; */
     RedrawWindow( hwnd, &rect, 0, flags );
 }
 
@@ -271,7 +266,7 @@
  *
  * Handle a X key event
  */
-static void EVENT_key( HWND hwnd, XKeyEvent *event )
+static void EVENT_key( XKeyEvent *event )
 {
     char Str[24]; 
     XComposeStatus cs; 
@@ -282,17 +277,13 @@
 
     int count = XLookupString(event, Str, 1, &keysym, &cs);
     Str[count] = '\0';
-#ifdef DEBUG_KEY
-    printf("WM_KEY??? : keysym=%lX, count=%u / %X / '%s'\n", 
+    dprintf_key(stddeb,"WM_KEY??? : keysym=%lX, count=%u / %X / '%s'\n", 
 	   keysym, count, Str[0], Str);
-#endif
 
     xkey = LOWORD(keysym);
     key_type = HIBYTE(xkey);
     key = LOBYTE(xkey);
-#ifdef DEBUG_KEY
-    printf("            key_type=%X, key=%X\n", key_type, key);
-#endif
+    dprintf_key(stddeb,"            key_type=%X, key=%X\n", key_type, key);
 
     if (key_type == 0xFF)                          /* non-character key */
     {
@@ -337,10 +328,9 @@
 	keylp.lp1.context = (event->state & Mod1Mask ? 1 : 0);
 	keylp.lp1.previous = (KeyDown ? 0 : 1);
 	keylp.lp1.transition = 0;
-#ifdef DEBUG_KEY
-	printf("            wParam=%X, lParam=%lX\n", vkey, keylp.lp2 );
-	printf("            KeyState=%X\n", KeyStateTable[vkey]);
-#endif
+	dprintf_key(stddeb,"            wParam=%X, lParam=%lX\n", 
+		    vkey, keylp.lp2 );
+	dprintf_key(stddeb,"            KeyState=%X\n", KeyStateTable[vkey]);
 	hardware_event( ALTKeyState ? WM_SYSKEYDOWN : WM_KEYDOWN, 
 		        vkey, keylp.lp2,
 		        event->x_root - desktopX, event->y_root - desktopY,
@@ -354,9 +344,7 @@
 	 */
 	if (count == 1)                /* key has an ASCII representation */
 	{
-#ifdef DEBUG_KEY
-	    printf("WM_CHAR :   wParam=%X\n", (WORD)Str[0] );
-#endif
+	    dprintf_key(stddeb,"WM_CHAR :   wParam=%X\n", (WORD)Str[0] );
 	    PostMessage( GetFocus(), WM_CHAR, (WORD)Str[0], keylp.lp2 );
 	}
     }
@@ -370,10 +358,9 @@
 	keylp.lp1.context = (event->state & Mod1Mask ? 1 : 0);
 	keylp.lp1.previous = 1;
 	keylp.lp1.transition = 1;
-#ifdef DEBUG_KEY
-	printf("            wParam=%X, lParam=%lX\n", vkey, keylp.lp2 );
-	printf("            KeyState=%X\n", KeyStateTable[vkey]);
-#endif
+	dprintf_key(stddeb,"            wParam=%X, lParam=%lX\n", 
+		    vkey, keylp.lp2 );
+	dprintf_key(stddeb,"            KeyState=%X\n", KeyStateTable[vkey]);
 	hardware_event( ((ALTKeyState || vkey == VK_MENU) ? 
 			 WM_SYSKEYUP : WM_KEYUP), 
 		        vkey, keylp.lp2,
@@ -407,7 +394,6 @@
     if (buttonNum >= NB_BUTTONS) return;
     MouseButtonsStates[buttonNum] = TRUE;
     AsyncMouseButtonsStates[buttonNum] = TRUE;
-    winHasCursor = event->window;
     hardware_event( messages[buttonNum],
 		    EVENT_XStateToKeyState( event->state ), 0L,
 		    event->x_root - desktopX, event->y_root - desktopY,
@@ -426,7 +412,6 @@
 
     if (buttonNum >= NB_BUTTONS) return;    
     MouseButtonsStates[buttonNum] = FALSE;
-    winHasCursor = event->window;
     hardware_event( messages[buttonNum],
 		    EVENT_XStateToKeyState( event->state ), 0L,
 		    event->x_root - desktopX, event->y_root - desktopY,
@@ -448,16 +433,6 @@
 
 
 /**********************************************************************
- *              EVENT_EnterNotify
- */
-static void EVENT_EnterNotify( XCrossingEvent *event )
-{
-    if (captureWnd != 0) return;
-    winHasCursor = event->window;
-}
-
-
-/**********************************************************************
  *              EVENT_ConfigureNotify
  *
  * The ConfigureNotify event is only selected on the desktop window.
@@ -472,28 +447,24 @@
 /**********************************************************************
  *		SetCapture 	(USER.18)
  */
-HWND SetCapture(HWND wnd)
+HWND SetCapture( HWND hwnd )
 {
-    int rv;
+    Window win;
     HWND old_capture_wnd = captureWnd;
-    WND *wnd_p = WIN_FindWndPtr(wnd);
-    if (wnd_p == NULL)
-	return 0;
-    
-    rv = XGrabPointer(display, wnd_p->window, False, 
-		      ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
-		      GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
 
-    if (rv == GrabSuccess)
+    if (!(win = WIN_GetXWindow( hwnd ))) return 0;
+    if (XGrabPointer(display, win, False, 
+                     ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
+                     GrabModeAsync, GrabModeAsync,
+                     None, None, CurrentTime ) == GrabSuccess)
     {
-	winHasCursor = wnd_p->window;
-	captureWnd = wnd;
+	captureWnd   = hwnd;
 	return old_capture_wnd;
     }
-    else
-	return 0;
+    else return 0;
 }
 
+
 /**********************************************************************
  *		ReleaseCapture	(USER.19)
  */
@@ -518,9 +489,9 @@
  */
 BOOL EnableHardwareInput(BOOL bEnable)
 {
-	BOOL bOldState = InputEnabled;
-	printf("EMPTY STUB !!! EnableHardwareInput(%d);\n", bEnable);
-	InputEnabled = bEnable;
-    return (bOldState && !bEnable);
+  BOOL bOldState = InputEnabled;
+  dprintf_event(stdnimp,"EMPTY STUB !!! EnableHardwareInput(%d);\n", bEnable);
+  InputEnabled = bEnable;
+  return (bOldState && !bEnable);
 }
 
diff --git a/windows/focus.c b/windows/focus.c
index 8850af0..0418ad9 100644
--- a/windows/focus.c
+++ b/windows/focus.c
@@ -22,8 +22,8 @@
  */
 static void FOCUS_SetXFocus( HWND hwnd )
 {
-    WND *wndPtr;
     XWindowAttributes win_attr;
+    Window win;
 
       /* Only mess with the X focus if there's no desktop window */
     if (rootWindow != DefaultRootWindow(display)) return;
@@ -35,20 +35,13 @@
 	return;
     }
 
-      /* Set X focus on the top-level ancestor. */
-	
-      /* Find ancestor */
-    wndPtr = WIN_FindWndPtr( hWndFocus );
-    while (wndPtr && (wndPtr->dwStyle & WS_CHILD))
-	wndPtr = WIN_FindWndPtr( wndPtr->hwndParent );
-    if (!wndPtr) return;
-
-      /* Make sure window is viewable */
-    if (!XGetWindowAttributes( display, wndPtr->window, &win_attr ) ||
-	(win_attr.map_state != IsViewable)) return;
-
       /* Set X focus and install colormap */
-    XSetInputFocus( display, wndPtr->window, RevertToParent, CurrentTime );
+
+    if (!(win = WIN_GetXWindow( hwnd ))) return;
+    if (!XGetWindowAttributes( display, win, &win_attr ) ||
+        (win_attr.map_state != IsViewable))
+        return;  /* If window is not viewable, don't change anything */
+    XSetInputFocus( display, win, RevertToParent, CurrentTime );
     if (COLOR_WinColormap != DefaultColormapOfScreen(screen))
 	XInstallColormap( display, COLOR_WinColormap );
 }
diff --git a/windows/graphics.c b/windows/graphics.c
index b3c9307..4f69b02 100644
--- a/windows/graphics.c
+++ b/windows/graphics.c
@@ -1,10 +1,10 @@
 /*
  * GDI graphics operations
  *
- * Copyright 1993 Alexandre Julliard
+ * Copyright 1993, 1994 Alexandre Julliard
  */
 
-static char Copyright[] = "Copyright  Alexandre Julliard, 1993";
+static char Copyright[] = "Copyright  Alexandre Julliard, 1993, 1994";
 
 #include <math.h>
 #include <stdlib.h>
@@ -17,12 +17,17 @@
 
 #include "gdi.h"
 #include "syscolor.h"
+#include "stddebug.h"
+/* #define DEBUG_GRAPHICS /* */
+/* #undef  DEBUG_GRAPHICS /* */
+#include "debug.h"
+
 
 extern const int DC_XROPfunction[];
 
 extern int COLOR_ToPhysical( DC *dc, COLORREF color );
 
-static inline swap_int(int *a, int *b)
+static __inline__ void swap_int(int *a, int *b)
 {
 	int c;
 	
@@ -641,9 +646,9 @@
 
 
 /**********************************************************************
- *          DrawReliefRect  (Not a MSWin Call)
+ *          GRAPH_DrawReliefRect  (Not a MSWin Call)
  */
-void DrawReliefRect( HDC hdc, RECT rect, int thickness, BOOL pressed )
+void GRAPH_DrawReliefRect( HDC hdc, RECT *rect, int thickness, BOOL pressed )
 {
     HBRUSH hbrushOld;
     int i;
@@ -652,20 +657,20 @@
 			                  sysColorObjects.hbrushBtnHighlight );
     for (i = 0; i < thickness; i++)
     {
-	PatBlt( hdc, rect.left + i, rect.top,
-	        1, rect.bottom - rect.top - i, PATCOPY );
-	PatBlt( hdc, rect.left, rect.top + i,
-	        rect.right - rect.left - i, 1, PATCOPY );
+	PatBlt( hdc, rect->left + i, rect->top,
+	        1, rect->bottom - rect->top - i, PATCOPY );
+	PatBlt( hdc, rect->left, rect->top + i,
+	        rect->right - rect->left - i, 1, PATCOPY );
     }
 
     SelectObject( hdc, pressed ? sysColorObjects.hbrushBtnHighlight :
 		                 sysColorObjects.hbrushBtnShadow );
     for (i = 0; i < thickness; i++)
     {
-	PatBlt( hdc, rect.right - i - 1, rect.top + i,
-	        1, rect.bottom - rect.top - i, PATCOPY );
-	PatBlt( hdc, rect.left + i, rect.bottom - i - 1,
-	        rect.right - rect.left - i, 1, PATCOPY );
+	PatBlt( hdc, rect->right - i - 1, rect->top + i,
+	        1, rect->bottom - rect->top - i, PATCOPY );
+	PatBlt( hdc, rect->left + i, rect->bottom - i - 1,
+	        rect->right - rect->left - i, 1, PATCOPY );
     }
 
     SelectObject( hdc, hbrushOld );
@@ -748,7 +753,6 @@
  */
 BOOL PolyPolygon( HDC hdc, LPPOINT pt, LPINT counts, WORD polygons )
 {
-    int i;
     HRGN hrgn;
     DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
 
@@ -796,106 +800,127 @@
 
 
 /**********************************************************************
- *          FloodFill_rec -- FloodFill helper function
+ *          GRAPH_InternalFloodFill
  *
- * Just does a recursive flood fill:
- * this is /not/ efficent -- a better way would be to draw
- * an entire line at a time, but this will do for now.
+ * Internal helper function for flood fill.
+ * (xorg,yorg) is the origin of the X image relative to the drawable.
+ * (x,y) is relative to the origin of the X image.
  */
-static BOOL FloodFill_rec(XImage *image, int x, int y, 
-		int orgx, int orgy, int endx, int endy, 
-		Pixel borderp, Pixel fillp)
+static void GRAPH_InternalFloodFill( XImage *image, DC *dc,
+                                     int x, int y,
+                                     int xOrg, int yOrg,
+                                     Pixel pixel, WORD fillType )
 {
-	Pixel testp;
+    int left, right;
 
-	if (x > endx || x < orgx || y > endy || y < orgy)
-		return FALSE;
-	XPutPixel(image, x, y, fillp);
-	
-	if ((x+1 <= endx) && (y+1 <= endy)) {
-	  testp = XGetPixel(image, x+1, y+1);
-	  if (testp != borderp && testp != fillp)
-	    FloodFill_rec(image, x+1, y+1, orgx, orgy, 
-			  endx, endy, borderp, fillp);
-	}
-	if ((x+1 <= endx) && (y-1 >= orgy)) {
-	  testp = XGetPixel(image, x+1, y-1);
-	  if (testp != borderp && testp != fillp)
-		FloodFill_rec(image, x+1, y-1, orgx, orgy, 
-				endx, endy, borderp, fillp);
-	}
-	if ((x-1 >= orgx) && (y+1 <= endy)) {
-	  testp = XGetPixel(image, x-1, y+1); 
-	  if (testp != borderp && testp != fillp)
-	    FloodFill_rec(image, x-1, y+1, orgx, orgy,
-			  endx, endy, borderp, fillp);
-	}
-	if ((x-1 >= orgx) && (y-1 >= orgy)) {
-	  testp = XGetPixel(image, x-1, y-1);
-	  if (testp != borderp && testp != fillp) 
-	    FloodFill_rec(image, x-1, y-1, orgx, orgy, 
-			  endx, endy, borderp, fillp);
-	}
-	return TRUE;
+#define TO_FLOOD(x,y)  ((fillType == FLOODFILLBORDER) ? \
+                        (XGetPixel(image,x,y) != pixel) : \
+                        (XGetPixel(image,x,y) == pixel))
+
+    if (!TO_FLOOD(x,y)) return;
+
+      /* Find left and right boundaries */
+
+    left = right = x;
+    while ((left > 0) && TO_FLOOD( left-1, y )) left--;
+    while ((right < image->width) && TO_FLOOD( right, y )) right++;
+    XFillRectangle( display, dc->u.x.drawable, dc->u.x.gc,
+                    xOrg + left, yOrg + y, right-left, 1 );
+
+      /* Set the pixels of this line so we don't fill it again */
+
+    for (x = left; x < right; x++)
+    {
+        if (fillType == FLOODFILLBORDER) XPutPixel( image, x, y, pixel );
+        else XPutPixel( image, x, y, ~pixel );
+    }
+
+      /* Fill the line above */
+
+    if (--y >= 0)
+    {
+        x = left;
+        while (x < right)
+        {
+            while ((x < right) && !TO_FLOOD(x,y)) x++;
+            if (x >= right) break;
+            while ((x < right) && TO_FLOOD(x,y)) x++;
+            GRAPH_InternalFloodFill( image, dc, x-1, y,
+                                     xOrg, yOrg, pixel, fillType );
+        }
+    }
+
+      /* Fill the line below */
+
+    if ((y += 2) < image->height)
+    {
+        x = left;
+        while (x < right)
+        {
+            while ((x < right) && !TO_FLOOD(x,y)) x++;
+            if (x >= right) break;
+            while ((x < right) && TO_FLOOD(x,y)) x++;
+            GRAPH_InternalFloodFill( image, dc, x-1, y,
+                                     xOrg, yOrg, pixel, fillType );
+        }
+    }
+#undef TO_FLOOD    
 }
 
- 
+
 /**********************************************************************
- *          FloodFill (GDI.25)
+ *          ExtFloodFill  (GDI.372)
  */
-BOOL FloodFill(HDC hdc, short x, short y, DWORD crColor)
+BOOL ExtFloodFill( HDC hdc, INT x, INT y, COLORREF color, WORD fillType )
 {
-    Pixel boundrypixel;
-    int imagex, imagey;
+    RECT rect;
+    Pixel pixel;
     XImage *image;
     DC *dc;
 
-#ifdef DEBUG_GRAPHICS
-    printf("FloodFill %x %d,%d %x\n", hdc, x, y, crColor);
-#endif
+    dprintf_graphics( stddeb, "ExtFloodFill %x %d,%d %06x %d\n",
+                      hdc, x, y, color, fillType );
     dc = (DC *) GDI_GetObjPtr(hdc, DC_MAGIC);
     if (!dc) 
     {
 	dc = (DC *)GDI_GetObjPtr(hdc, METAFILE_DC_MAGIC);
 	if (!dc) return FALSE;
-	MF_MetaParam4(dc, META_FLOODFILL, x, y, HIWORD(crColor), 
-		      LOWORD(crColor)); 
+	MF_MetaParam4(dc, META_FLOODFILL, x, y, HIWORD(color), 
+		      LOWORD(color)); 
 	return TRUE;
     }
 
-    x = dc->w.DCOrgX + XLPTODP(dc, x);
-    y = dc->w.DCOrgY + YLPTODP(dc, y);
+    if (!PtVisible( hdc, x, y )) return FALSE;
+    if (GetClipBox( hdc, &rect ) == ERROR) return FALSE;
+    pixel = COLOR_ToPhysical( dc, color );
 
-    if (x < dc->w.DCOrgX || x > dc->w.DCOrgX + dc->w.DCSizeX ||
-	y < dc->w.DCOrgY || y > dc->w.DCOrgY + dc->w.DCSizeY)
-	return FALSE;
+    if (!(image = XGetImage( display, dc->u.x.drawable,
+                             dc->w.DCOrgX + rect.left, dc->w.DCOrgY + rect.top,
+                             rect.right - rect.left, rect.bottom - rect.top,
+                             AllPlanes, ZPixmap ))) return FALSE;
 
-    if (!DC_SetupGCForBrush(dc)) 
-	return FALSE;
-
-    boundrypixel = GetNearestPaletteIndex( dc->w.hPalette, crColor );	
-
-    image = XGetImage(display, dc->u.x.drawable,  
-		      dc->w.DCOrgX, dc->w.DCOrgY,
-		      dc->w.DCSizeX, dc->w.DCSizeY, AllPlanes, ZPixmap);
-    if (XGetPixel(image, x, y) == boundrypixel) 
-	return FALSE;
-    if (!FloodFill_rec(image, x, y, 
-		       0, 0, 
-		       dc->w.DCSizeX-1, 
-		       dc->w.DCSizeY-1, 
-		       boundrypixel, dc->u.x.brush.pixel)) {
-	XDestroyImage(image);
-	return FALSE;
+    if (DC_SetupGCForBrush( dc ))
+    {
+          /* ROP mode is always GXcopy for flood-fill */
+        XSetFunction( display, dc->u.x.gc, GXcopy );
+          /* We can pass anything except 0 as a region */
+        GRAPH_InternalFloodFill( image, dc,
+                                 XLPTODP(dc,x) - rect.left,
+                                 YLPTODP(dc,y) - rect.top,
+                                 dc->w.DCOrgX + rect.left,
+                                 dc->w.DCOrgY + rect.top,
+                                 pixel, fillType );
     }
 
-    XPutImage(display, dc->u.x.drawable, dc->u.x.gc, image,
-	      0, 0,
-	      dc->w.DCOrgX, dc->w.DCOrgY,
-	      dc->w.DCSizeX, dc->w.DCSizeY);
-    XDestroyImage(image);
-
+    XDestroyImage( image );
     return TRUE;
 }
 
 
+/**********************************************************************
+ *          FloodFill  (GDI.25)
+ */
+BOOL FloodFill( HDC hdc, INT x, INT y, COLORREF color )
+{
+    return ExtFloodFill( hdc, x, y, color, FLOODFILLBORDER );
+}
diff --git a/windows/keyboard.c b/windows/keyboard.c
index e8181cb..ab15b9d 100644
--- a/windows/keyboard.c
+++ b/windows/keyboard.c
@@ -6,6 +6,7 @@
 
 static char Copyright[] = "Copyright  Bob Amstadt, 1993";
 
+#include <string.h>
 #include "win.h"
 #include "windows.h"
 
diff --git a/windows/mapping.c b/windows/mapping.c
index f1b9d37..07e4bbc 100644
--- a/windows/mapping.c
+++ b/windows/mapping.c
@@ -8,6 +8,10 @@
 
 #include "gdi.h"
 #include "metafile.h"
+#include "stddebug.h"
+/* #define DEBUG_GDI /* */
+/* #undef  DEBUG_GDI /* */
+#include "debug.h"
 
 
 /***********************************************************************
@@ -84,9 +88,7 @@
 	return 1;
     }
 
-#ifdef DEBUG_GDI
-    printf( "SetMapMode: %d %d\n", hdc, mode );
-#endif
+    dprintf_gdi(stddeb, "SetMapMode: %d %d\n", hdc, mode );
     
     prevMode = dc->w.MapMode;
     switch(mode)
diff --git a/windows/mdi.c b/windows/mdi.c
index 66a511e..d2d956f 100644
--- a/windows/mdi.c
+++ b/windows/mdi.c
@@ -12,8 +12,11 @@
 #include "mdi.h"
 #include "user.h"
 #include "sysmetrics.h"
+#include "stddebug.h"
+/* #define DEBUG_MDI /* */
+/* #undef  DEBUG_MDI /* */
+#include "debug.h"
 
-#define DEBUG_MDI /* */
 
 extern WORD MENU_DrawMenuBar( HDC hDC, LPRECT lprect,
 			      HWND hwnd, BOOL suppress_draw );  /* menu.c */
@@ -28,19 +31,15 @@
     char buffer[128];
     int id, n, index;
 
-#ifdef DEBUG_MDI
-    fprintf(stderr, "MDIRecreateMenuList: hWindowMenu %04.4x\n", 
+    dprintf_mdi(stddeb, "MDIRecreateMenuList: hWindowMenu %04.4x\n", 
 	    ci->hWindowMenu);
-#endif
     
     id = ci->idFirstChild; 
     while (DeleteMenu(ci->hWindowMenu, id, MF_BYCOMMAND))
 	id++;
 
-#ifdef DEBUG_MDI
-    fprintf(stderr, "MDIRecreateMenuList: id %04.4x, idFirstChild %04.4x\n", 
+    dprintf_mdi(stddeb, "MDIRecreateMenuList: id %04.4x, idFirstChild %04.4x\n", 
 	    id, ci->idFirstChild);
-#endif
 
     if (!ci->flagMenuAltered)
     {
@@ -55,10 +54,8 @@
 	n = sprintf(buffer, "%d ", index++);
 	GetWindowText(chi->hwnd, buffer + n, sizeof(buffer) - n - 1);
 
-#ifdef DEBUG_MDI
-	fprintf(stderr, "MDIRecreateMenuList: id %04.4x, '%s'\n", 
+	dprintf_mdi(stddeb, "MDIRecreateMenuList: id %04.4x, '%s'\n", 
 		id, buffer);
-#endif
 
 	AppendMenu(ci->hWindowMenu, MF_STRING, id++, buffer);
     }
@@ -160,9 +157,7 @@
     w  = WIN_FindWndPtr(parent);
     ci = (MDICLIENTINFO *) w->wExtra;
     
-#ifdef DEBUG_MDI
-    fprintf(stderr, "MDIBringToTop: id %04.4x, by_id %d\n", id, by_id);
-#endif
+    dprintf_mdi(stddeb, "MDIBringToTop: id %04.4x, by_id %d\n", id, by_id);
 
     if (by_id)
 	id -= ci->idFirstChild;
@@ -184,9 +179,7 @@
 	if (!chi)
 	    return;
 
-#ifdef DEBUG_MDI
-	fprintf(stderr, "MDIBringToTop: child %04.4x\n", chi->hwnd);
-#endif
+	dprintf_mdi(stddeb, "MDIBringToTop: child %04.4x\n", chi->hwnd);
 	if (chi != ci->infoActiveChildren)
 	{
 	    if (ci->flagChildMaximized)
@@ -248,10 +241,8 @@
 	    SendMessage(parent, WM_CHILDACTIVATE, 0, 0);
 	}
 	
-#ifdef DEBUG_MDI
-	fprintf(stderr, "MDIBringToTop: pos %04.4x, hwnd %04.4x\n", 
+	dprintf_mdi(stddeb, "MDIBringToTop: pos %04.4x, hwnd %04.4x\n", 
 		id, chi->hwnd);
-#endif
     }
 }
 
@@ -298,7 +289,7 @@
     WND    *w      = WIN_FindWndPtr(child);
     LPRECT  lprect = &ci->rectRestore;
 
-    printf("restoring mdi child\n");
+    dprintf_mdi(stddeb,"restoring mdi child\n");
 
     child = ci->hwndActiveChild;
     
@@ -327,9 +318,7 @@
     HWND          act_hwnd;
     LONG          lParam;
 
-#ifdef DEBUG_MDI
-    fprintf(stderr, "MDIChildActivate: top %04.4x\n", w->hwndChild);
-#endif
+    dprintf_mdi(stddeb, "MDIChildActivate: top %04.4x\n", w->hwndChild);
 
     chi = ci->infoActiveChildren;
     if (chi)
@@ -338,10 +327,8 @@
 	act_hwnd   = chi->hwnd;
 	lParam     = ((LONG) deact_hwnd << 16) | act_hwnd;
 
-#ifdef DEBUG_MDI
-	fprintf(stderr, "MDIChildActivate: deact %04.4x, act %04.4x\n",
+	dprintf_mdi(stddeb, "MDIChildActivate: deact %04.4x, act %04.4x\n",
 	       deact_hwnd, act_hwnd);
-#endif
 
 	ci->hwndActiveChild = act_hwnd;
 
@@ -383,26 +370,20 @@
     ysize   = rect.bottom - 8 * spacing;
     xsize   = rect.right  - 8 * spacing;
     
-#ifdef DEBUG_MDI
-    fprintf(stderr, 
+    dprintf_mdi(stddeb, 
 	    "MDICascade: Client wnd at (%d,%d) - (%d,%d), spacing %d\n", 
 	    rect.left, rect.top, rect.right, rect.bottom, spacing);
-    fprintf(stderr, "MDICascade: searching for last child\n");
-#endif
+    dprintf_mdi(stddeb, "MDICascade: searching for last child\n");
     for (chi = ci->infoActiveChildren; chi->next != NULL; chi = chi->next)
 	;
     
-#ifdef DEBUG_MDI
-    fprintf(stderr, "MDICascade: last child is %04.4x\n", chi->hwnd);
-#endif
+    dprintf_mdi(stddeb, "MDICascade: last child is %04.4x\n", chi->hwnd);
     x = 0;
     y = 0;
     for ( ; chi != NULL; chi = chi->prev)
     {
-#ifdef DEBUG_MDI
-	fprintf(stderr, "MDICascade: move %04.4x to (%d,%d) size [%d,%d]\n", 
+	dprintf_mdi(stddeb, "MDICascade: move %04.4x to (%d,%d) size [%d,%d]\n", 
 		chi->hwnd, x, y, xsize, ysize);
-#endif
 	SetWindowPos(chi->hwnd, 0, x, y, xsize, ysize, 
 		     SWP_DRAWFRAME | SWP_NOACTIVATE | SWP_NOZORDER);
 
@@ -517,13 +498,11 @@
     w  = WIN_FindWndPtr(hwndClient);
     ci = (MDICLIENTINFO *) w->wExtra;
 
-#ifdef DEBUG_MDI
-	fprintf(stderr, 
+    dprintf_mdi(stddeb, 
 		"MDIPaintMaximized: frame %04x,  client %04x"
 		",  max flag %d,  menu %04x\n", 
 		hwndFrame, hwndClient, 
 		ci->flagChildMaximized, wndPtr ? wndPtr->wIDmenu : 0);
-#endif
 
     if (ci->flagChildMaximized && wndPtr && wndPtr->wIDmenu != 0)
     {
@@ -541,12 +520,10 @@
 	    hbitmapMaximized = LoadBitmap(0, MAKEINTRESOURCE(OBM_RESTORE));
 	}
 
-#ifdef DEBUG_MDI
-	fprintf(stderr, 
+	dprintf_mdi(stddeb, 
 		"MDIPaintMaximized: hdcMem %04x, close bitmap %04x, "
 		"maximized bitmap %04x\n",
 		hdcMem, hbitmapClose, hbitmapMaximized);
-#endif
 
 	NC_GetInsideRect(hwndFrame, &rect);
 	rect.top   += ((wndPtr->dwStyle & WS_CAPTION) ? 
diff --git a/windows/message.c b/windows/message.c
index 6d7a21a..137ffe0 100644
--- a/windows/message.c
+++ b/windows/message.c
@@ -1,7 +1,7 @@
 /*
  * Message queues related functions
  *
- * Copyright 1993 Alexandre Julliard
+ * Copyright 1993, 1994 Alexandre Julliard
  */
 
 /*
@@ -9,7 +9,7 @@
  * one message queue).
  */
 
-static char Copyright[] = "Copyright  Alexandre Julliard, 1993";
+static char Copyright[] = "Copyright  Alexandre Julliard, 1993, 1994";
 
 #include <stdlib.h>
 #include <sys/time.h>
@@ -20,6 +20,11 @@
 #include "wineopts.h"
 #include "sysmetrics.h"
 #include "hook.h"
+#include "stddebug.h"
+/* #define DEBUG_MSG /* */
+/* #undef  DEBUG_MSG /* */
+#include "debug.h"
+
 
 #define HWND_BROADCAST  ((HWND)0xffff)
 
@@ -118,7 +123,7 @@
 
       /* Check if queue is full */
     if ((pos == msgQueue->nextMessage) && (msgQueue->msgCount > 0)) {
-		printf("MSG_AddMsg // queue is full !\n");
+		fprintf(stderr,"MSG_AddMsg // queue is full !\n");
 		return FALSE;
 		}
 
@@ -290,8 +295,8 @@
 	{
 	    /* Check whether window wants the double click message. */
 	    WND * wndPtr = WIN_FindWndPtr( msg->hwnd );
-	    if (!wndPtr || !(wndPtr->flags & WIN_DOUBLE_CLICKS))
-		dbl_click = FALSE;
+            if (!wndPtr || !(WIN_CLASS_STYLE(wndPtr) & CS_DBLCLKS))
+                dbl_click = FALSE;
 	}
 
 	if (dbl_click) switch(msg->message)
@@ -349,6 +354,44 @@
 }
 
 
+/***********************************************************************
+ *           MSG_PeekHardwareMsg
+ *
+ * Peek for a hardware message matching the hwnd and message filters.
+ */
+static BOOL MSG_PeekHardwareMsg( MSG *msg, HWND hwnd, WORD first, WORD last,
+                                 BOOL remove )
+{
+    int i, pos = sysMsgQueue->nextMessage;
+
+    for (i = 0; i < sysMsgQueue->msgCount; i++, pos++)
+    {
+	*msg = sysMsgQueue->messages[pos].msg;
+
+          /* Translate message */
+
+        if ((msg->message >= WM_MOUSEFIRST) && (msg->message <= WM_MOUSELAST))
+        {
+            if (!MSG_TranslateMouseMsg( msg, remove )) continue;
+        }
+        else if ((msg->message >= WM_KEYFIRST) && (msg->message <= WM_KEYLAST))
+        {
+            if (!MSG_TranslateKeyboardMsg( msg )) continue;
+        }
+        else continue;  /* Should never happen */
+
+          /* Check message against filters */
+
+        if (hwnd && (msg->hwnd != hwnd)) continue;
+        if ((first || last) && 
+            ((msg->message < first) || (msg->message > last))) continue;
+        if (remove) MSG_RemoveMsg( sysMsgQueue, pos );
+        return TRUE;
+    }
+    return FALSE;
+}
+
+
 /**********************************************************************
  *		SetDoubleClickTime  (USER.20)
  */
@@ -425,30 +468,49 @@
 void hardware_event( WORD message, WORD wParam, LONG lParam,
 		     int xPos, int yPos, DWORD time, DWORD extraInfo )
 {
-    MSG msg;
-
-    msg.hwnd    = 0;
-    msg.message = message;
-    msg.wParam  = wParam;
-    msg.lParam  = lParam;
-    msg.time    = time;
-    msg.pt.x    = xPos & 0xffff;
-    msg.pt.y    = yPos & 0xffff;
+    MSG *msg;
+    int pos;
+  
+    if (!sysMsgQueue) return;
+    pos = sysMsgQueue->nextFreeMessage;
 
       /* Merge with previous event if possible */
 
-    if (sysMsgQueue->msgCount && (message == WM_MOUSEMOVE))
+    if ((message == WM_MOUSEMOVE) && sysMsgQueue->msgCount)
     {
-	MSG *prevMsg = &sysMsgQueue->messages[sysMsgQueue->nextMessage].msg;
-	if ((prevMsg->message == message) && (prevMsg->wParam == wParam))
-	{
-	    *prevMsg = msg;  /* Overwrite previous message */
-	    return;
-	}
+        if (pos > 0) pos--;
+        else pos = sysMsgQueue->queueSize - 1;
+	msg = &sysMsgQueue->messages[pos].msg;
+	if ((msg->message == message) && (msg->wParam == wParam))
+            sysMsgQueue->msgCount--;  /* Merge events */
+        else
+            pos = sysMsgQueue->nextFreeMessage;  /* Don't merge */
     }
 
-    if (!MSG_AddMsg( sysMsgQueue, &msg, extraInfo ))
-	printf( "hardware_event: Queue is full\n" );
+      /* Check if queue is full */
+
+    if ((pos == sysMsgQueue->nextMessage) && sysMsgQueue->msgCount)
+    {
+        /* Queue is full, beep (but not on every mouse motion...) */
+        if (message != WM_MOUSEMOVE) MessageBeep(0);
+        return;
+    }
+
+      /* Store message */
+
+    msg = &sysMsgQueue->messages[pos].msg;
+    msg->hwnd    = 0;
+    msg->message = message;
+    msg->wParam  = wParam;
+    msg->lParam  = lParam;
+    msg->time    = time;
+    msg->pt.x    = xPos & 0xffff;
+    msg->pt.y    = yPos & 0xffff;
+    sysMsgQueue->messages[pos].extraInfo = extraInfo;
+    if (pos < sysMsgQueue->queueSize - 1) pos++;
+    else pos = 0;
+    sysMsgQueue->nextFreeMessage = pos;
+    sysMsgQueue->msgCount++;
 }
 
 		    
@@ -573,6 +635,41 @@
 
 
 /***********************************************************************
+ *           MSG_WaitXEvent
+ *
+ * Wait for an X event, but at most maxWait milliseconds (-1 for no timeout).
+ * Return TRUE if an event is pending, FALSE on timeout or error
+ * (for instance lost connection with the server).
+ */
+static BOOL MSG_WaitXEvent( LONG maxWait )
+{
+    fd_set read_set;
+    struct timeval timeout;
+    XEvent event;
+    int fd = ConnectionNumber(display);
+
+    if (!XPending(display) && (maxWait != -1))
+    {
+        FD_ZERO( &read_set );
+        FD_SET( fd, &read_set );
+        timeout.tv_sec = maxWait / 1000;
+        timeout.tv_usec = (maxWait % 1000) * 1000;
+        if (select( fd+1, &read_set, NULL, NULL, &timeout ) != 1)
+            return FALSE;  /* Timeout or error */
+    }
+
+    /* Process the event (and possibly others that occurred in the meantime) */
+    do
+    {
+        XNextEvent( display, &event );
+        EVENT_ProcessEvent( &event );
+    }
+    while (XPending( display ));
+    return TRUE;
+}
+
+
+/***********************************************************************
  *           MSG_PeekMessage
  */
 static BOOL MSG_PeekMessage( MESSAGEQUEUE * msgQueue, LPMSG msg, HWND hwnd,
@@ -580,10 +677,6 @@
 {
     int pos, mask;
     LONG nextExp;  /* Next timer expiration time */
-    XEvent event;
-    fd_set read_set;
-    struct timeval timeout;
-    int fd = ConnectionNumber(display);
 
     if (first || last)
     {
@@ -631,32 +724,14 @@
 	}
 
 	  /* Now find a hardware event */
-	pos = MSG_FindMsg( sysMsgQueue, 0, first, last );
-	if (pos != -1)
-	{
-	    QMSG *qmsg = &sysMsgQueue->messages[pos];
-	    *msg = qmsg->msg;
+        if (MSG_PeekHardwareMsg( msg, hwnd, first, last, flags & PM_REMOVE ))
+        {
+            /* Got one */
 	    msgQueue->GetMessageTimeVal      = msg->time;
 	    msgQueue->GetMessagePosVal       = *(DWORD *)&msg->pt;
-	    msgQueue->GetMessageExtraInfoVal = qmsg->extraInfo;
-
-	    if ((msg->message >= WM_MOUSEFIRST) &&
-		(msg->message <= WM_MOUSELAST))
-		if (!MSG_TranslateMouseMsg( msg, flags & PM_REMOVE )) 
-		{
-		    MSG_RemoveMsg( sysMsgQueue, pos );
-		    continue;
-		}
-	    else if ((msg->message >= WM_KEYFIRST) &&
-		     (msg->message <= WM_KEYLAST))
-		if (!MSG_TranslateKeyboardMsg( msg )) 
-		{
-		    MSG_RemoveMsg( sysMsgQueue, pos );
-		    continue;
-		}
-	    if (flags & PM_REMOVE) MSG_RemoveMsg( sysMsgQueue, pos );
-	    break;
-	}
+	    msgQueue->GetMessageExtraInfoVal = 0;  /* Always 0 for now */
+            break;
+        }
 
 	  /* Now handle a WM_QUIT message */
 	if (msgQueue->wPostQMsg)
@@ -687,27 +762,12 @@
 	else nextExp = -1;  /* No timeout needed */
 
 	  /* Wait until something happens */
-	FD_ZERO( &read_set );
-	FD_SET( fd, &read_set );
-	if (peek)
-	{
-	    timeout.tv_sec = 0;
-	    timeout.tv_usec = 0;
-	    if (select( fd+1, &read_set, NULL, NULL, &timeout ) != 1)
-		return FALSE;  /* No data waiting to be read */
-	}
-	else if (!XPending( display ) && (nextExp != -1))
-	{
-	    timeout.tv_sec = nextExp / 1000;
-	    timeout.tv_usec = (nextExp % 1000) * 1000;
-	    if (select( fd+1, &read_set, NULL, NULL, &timeout ) != 1)
-		continue;  /* On timeout or error, restart from the start */
-	}
-	while (XPending( display ))
-	{
-	    XNextEvent( display, &event );
-	    EVENT_ProcessEvent( &event );
-	}
+        if (peek)
+        {
+            if (!MSG_WaitXEvent( 0 )) return FALSE;  /* No pending event */
+        }
+        else  /* Wait for an event, then restart the loop */
+            MSG_WaitXEvent( nextExp );
     }
 
       /* We got a message */
@@ -782,17 +842,13 @@
     WND 	*wndPtr;
 
 	if (hwnd == HWND_BROADCAST) {
-#ifdef DEBUG_MSG
-		printf("PostMessage // HWND_BROADCAST !\n");
-#endif
+	    dprintf_msg(stddeb,"PostMessage // HWND_BROADCAST !\n");
 	    hwnd = GetTopWindow(GetDesktopWindow());
 	    while (hwnd) {
 	        if (!(wndPtr = WIN_FindWndPtr(hwnd))) break;
 			if (wndPtr->dwStyle & WS_POPUP || wndPtr->dwStyle & WS_CAPTION) {
-#ifdef DEBUG_MSG
-				printf("BROADCAST Message to hWnd=%04X m=%04X w=%04X l=%08X !\n", 
+				dprintf_msg(stddeb,"BROADCAST Message to hWnd=%04X m=%04X w=%04X l=%08X !\n", 
 							hwnd, message, wParam, lParam);
-#endif
 				PostMessage(hwnd, message, wParam, lParam);
 				}
 /*				{
@@ -802,9 +858,7 @@
 				}*/
 			hwnd = wndPtr->hwndNext;
 			}
-#ifdef DEBUG_MSG
-		printf("PostMessage // End of HWND_BROADCAST !\n");
-#endif
+		dprintf_msg(stddeb,"PostMessage // End of HWND_BROADCAST !\n");
 		return TRUE;
 		}
 
@@ -841,41 +895,16 @@
 void WaitMessage( void )
 {
     MSG msg;
-    LONG nextExp;  /* Next timer expiration time */
-    XEvent event;
+    LONG nextExp = -1;  /* Next timer expiration time */
 
-    while (XPending( display ))
-    {
-        XNextEvent( display, &event );
-        EVENT_ProcessEvent( &event );
-    }    
-
-    while(1)
-    {
-        if ((appMsgQueue->wPostQMsg) || 
-            (appMsgQueue->status & (QS_SENDMESSAGE | QS_PAINT)) ||
-            (appMsgQueue->msgCount) || (sysMsgQueue->msgCount) )
-            break;
-	nextExp = -1;
-        if ((appMsgQueue->status & QS_TIMER) && 
-            TIMER_CheckTimer( &nextExp, &msg, 0, FALSE))
-            break;
-
-        if (!XPending( display ) && (nextExp != -1))
-        {
-            fd_set read_set;
-            struct timeval timeout;
-            int fd = ConnectionNumber(display);
-            FD_ZERO( &read_set );
-            FD_SET( fd, &read_set );
-            timeout.tv_sec = nextExp / 1000;
-            timeout.tv_usec = (nextExp % 1000) * 1000;
-            if (select( fd+1, &read_set, NULL, NULL, &timeout ) != 1)
-                continue;  /* On timeout or error, restart from the start */
-        }
-        XNextEvent( display, &event );
-        EVENT_ProcessEvent( &event );
-    }
+    if ((appMsgQueue->wPostQMsg) || 
+        (appMsgQueue->status & (QS_SENDMESSAGE | QS_PAINT)) ||
+        (appMsgQueue->msgCount) || (sysMsgQueue->msgCount) )
+        return;
+    if ((appMsgQueue->status & QS_TIMER) && 
+        TIMER_CheckTimer( &nextExp, &msg, 0, FALSE))
+        return;
+    MSG_WaitXEvent( nextExp );
 }
 
 
@@ -889,9 +918,7 @@
     if ((message == WM_KEYDOWN) || (message == WM_KEYUP) ||
 	(message == WM_SYSKEYDOWN) || (message == WM_SYSKEYUP))
     {
-#ifdef DEBUG_MSG
-	printf( "Translating key message\n" );
-#endif
+	dprintf_msg(stddeb, "Translating key message\n" );
 	return TRUE;
     }
     return FALSE;
@@ -907,17 +934,15 @@
     LONG retval;
     int painting;
     
-#ifdef DEBUG_MSG
-    printf( "Dispatch message hwnd=%08x msg=0x%x w=%d l=%d time=%u pt=%d,%d\n",
+    dprintf_msg(stddeb, "Dispatch message hwnd=%08x msg=0x%x w=%d l=%d time=%u pt=%d,%d\n",
 	    msg->hwnd, msg->message, msg->wParam, msg->lParam, 
 	    msg->time, msg->pt.x, msg->pt.y );
-#endif
 
       /* Process timer messages */
     if ((msg->message == WM_TIMER) || (msg->message == WM_SYSTIMER))
     {
 	if (msg->lParam)
-	    return CallWindowProc( (FARPROC)msg->lParam, msg->hwnd,
+	    return CallWindowProc( (WNDPROC)msg->lParam, msg->hwnd,
 				   msg->message, msg->wParam, GetTickCount() );
     }
 
@@ -928,11 +953,11 @@
     if (painting) wndPtr->flags |= WIN_NEEDS_BEGINPAINT;
     retval = CallWindowProc( wndPtr->lpfnWndProc, msg->hwnd, msg->message,
 			     msg->wParam, msg->lParam );
-    if (painting && (wndPtr->flags & WIN_NEEDS_BEGINPAINT))
+    if (painting && IsWindow(msg->hwnd) &&
+        (wndPtr->flags & WIN_NEEDS_BEGINPAINT))
     {
-#ifdef DEBUG_WIN
-	printf( "BeginPaint not called on WM_PAINT for hwnd %d!\n", msg->hwnd);
-#endif
+	fprintf(stderr, "BeginPaint not called on WM_PAINT for hwnd %d!\n", 
+		msg->hwnd);
 	wndPtr->flags &= ~WIN_NEEDS_BEGINPAINT;
     }
     return retval;
@@ -972,9 +997,7 @@
 WORD RegisterWindowMessage( LPCSTR str )
 {
 	WORD	wRet;
-#ifdef DEBUG_MSG
-    printf( "RegisterWindowMessage: '%s'\n", str );
-#endif
+    dprintf_msg(stddeb, "RegisterWindowMessage: '%s'\n", str );
 	wRet = GlobalAddAtom( str );
     return wRet;
 }
diff --git a/windows/nonclient.c b/windows/nonclient.c
index 5909530..b0c71ef 100644
--- a/windows/nonclient.c
+++ b/windows/nonclient.c
@@ -13,6 +13,11 @@
 #include "user.h"
 #include "scroll.h"
 #include "syscolor.h"
+#include "stddebug.h"
+/* #define DEBUG_NONCLIENT /* */
+/* #undef  DEBUG_NONCLIENT /* */
+#include "debug.h"
+
 
 static HBITMAP hbitmapClose = 0;
 static HBITMAP hbitmapMDIClose = 0;
@@ -29,7 +34,6 @@
 
 extern void WINPOS_GetMinMaxInfo( HWND hwnd, POINT *maxSize, POINT *maxPos,
 			    POINT *minTrack, POINT *maxTrack );  /* winpos.c */
-extern void CURSOR_SetWinCursor( HWND hwnd, HCURSOR hcursor );   /* cursor.c */
 extern BOOL GRAPH_DrawBitmap( HDC hdc, HBITMAP hbitmap, int xdest, int ydest,
 			      int xsrc, int ysrc, int width, int height,
 			      int rop );                     /* graphics.c */
@@ -108,10 +112,8 @@
 	style |= WS_CAPTION;
     if (exStyle & WS_EX_DLGMODALFRAME) style &= ~WS_THICKFRAME;
 
-#ifdef DEBUG_NONCLIENT
-    printf( "AdjustWindowRectEx: (%d,%d)-(%d,%d) %08x %d %08x\n",
+    dprintf_nonclient(stddeb, "AdjustWindowRectEx: (%d,%d)-(%d,%d) %08x %d %08x\n",
       rect->left, rect->top, rect->right, rect->bottom, style, menu, exStyle );
-#endif
 
     NC_AdjustRect( rect, style, menu, exStyle );
 }
@@ -193,9 +195,8 @@
     WND *wndPtr = WIN_FindWndPtr( hwnd );
     if (!wndPtr) return HTERROR;
 
-#ifdef DEBUG_NONCLIENT
-    printf( "NC_HandleNCHitTest: hwnd=%x pt=%d,%d\n", hwnd, pt.x, pt.y );
-#endif
+    dprintf_nonclient(stddeb, "NC_HandleNCHitTest: hwnd=%x pt=%d,%d\n", 
+		      hwnd, pt.x, pt.y );
 
     GetWindowRect( hwnd, &rect );
     if (!PtInRect( &rect, pt )) return HTNOWHERE;
@@ -372,9 +373,9 @@
  *           NC_DrawFrame
  *
  * Draw a window frame inside the given rectangle, and update the rectangle.
- * The correct pen and brush must be selected in the DC.
+ * The correct pen for the frame must be selected in the DC.
  */
-static void NC_DrawFrame( HDC hdc, RECT *rect, BOOL dlgFrame )
+static void NC_DrawFrame( HDC hdc, RECT *rect, BOOL dlgFrame, BOOL active )
 {
     short width, height, tmp;
 
@@ -382,11 +383,15 @@
     {
 	width = SYSMETRICS_CXDLGFRAME - 1;
 	height = SYSMETRICS_CYDLGFRAME - 1;
+        SelectObject( hdc, active ? sysColorObjects.hbrushActiveCaption :
+                                    sysColorObjects.hbrushInactiveCaption );
     }
     else
     {
 	width = SYSMETRICS_CXFRAME - 1;
 	height = SYSMETRICS_CYFRAME - 1;
+        SelectObject( hdc, active ? sysColorObjects.hbrushActiveBorder :
+                                    sysColorObjects.hbrushInactiveBorder );
     }
 
       /* Draw frame */
@@ -552,22 +557,20 @@
 
     WND *wndPtr = WIN_FindWndPtr( hwnd );
 
-#ifdef DEBUG_NONCLIENT
-    printf( "NC_DoNCPaint: %d %d\n", hwnd, hrgn );
-#endif
+    dprintf_nonclient(stddeb, "NC_DoNCPaint: %d %d\n", hwnd, hrgn );
     if (!wndPtr || !hrgn) return;
     if ((!(wndPtr->dwStyle & (WS_BORDER | WS_DLGFRAME | WS_THICKFRAME))) ||
 	(!(wndPtr->dwStyle & WS_VISIBLE)))
 	return;  /* Nothing to do! */
 
-    if (hrgn == 1) hdc = GetDCEx( hwnd, 0, DCX_CACHE | DCX_WINDOW );
+    if (hrgn == 1) hdc = GetDCEx( hwnd, 0, DCX_USESTYLE | DCX_WINDOW );
     else
     {
 	  /* Make region relative to window area */
 	int xoffset = wndPtr->rectWindow.left - wndPtr->rectClient.left;
 	int yoffset = wndPtr->rectWindow.top - wndPtr->rectClient.top;
 	OffsetRgn( hrgn, -xoffset, -yoffset );
-	hdc = GetDCEx( hwnd, hrgn, DCX_CACHE | DCX_WINDOW | DCX_INTERSECTRGN);
+	hdc = GetDCEx( hwnd, hrgn, DCX_USESTYLE|DCX_WINDOW|DCX_INTERSECTRGN );
 	OffsetRgn( hrgn, xoffset, yoffset );  /* Restore region */
     }
     if (!hdc) return;
@@ -580,16 +583,16 @@
      */
     if (IsIconic(hwnd))
     {
-        if (wndPtr->hIcon)  
+        HICON hIcon = WIN_CLASS_INFO(wndPtr).hIcon;
+        if (hIcon)  
         {
             SendMessage(hwnd, WM_ICONERASEBKGND, hdc, 0);
             Rectangle(hdc, wndPtr->rectWindow.left, wndPtr->rectWindow.top,
                      wndPtr->rectWindow.right, wndPtr->rectWindow.bottom);
-            DrawIcon(hdc, 0, 0, wndPtr->hIcon);
+            DrawIcon(hdc, 0, 0, hIcon);
         }
-      ReleaseDC(hwnd, hdc);
-	
-      return;
+        ReleaseDC(hwnd, hdc);
+        return;
     }
 
     if (ExcludeVisRect( hdc, wndPtr->rectClient.left-wndPtr->rectWindow.left,
@@ -607,8 +610,6 @@
     rect.bottom = wndPtr->rectWindow.bottom - wndPtr->rectWindow.top;
 
     SelectObject( hdc, sysColorObjects.hpenWindowFrame );
-    SelectObject( hdc, active ? sysColorObjects.hbrushActiveBorder :
-		                sysColorObjects.hbrushInactiveBorder );
 
     if ((wndPtr->dwStyle & WS_BORDER) || (wndPtr->dwStyle & WS_DLGFRAME))
     {
@@ -621,9 +622,9 @@
     }
 
     if (HAS_DLGFRAME( wndPtr->dwStyle, wndPtr->dwExStyle )) 
-	NC_DrawFrame( hdc, &rect, TRUE );
+	NC_DrawFrame( hdc, &rect, TRUE, active );
     else if (wndPtr->dwStyle & WS_THICKFRAME)
-	NC_DrawFrame(hdc, &rect, FALSE);
+	NC_DrawFrame(hdc, &rect, FALSE, active );
 
     if ((wndPtr->dwStyle & WS_CAPTION) == WS_CAPTION)
     {
@@ -726,7 +727,7 @@
 	    if (!(classPtr = CLASS_FindClassPtr( wndPtr->hClass ))) break;
 	    if (classPtr->wc.hCursor)
 	    {
-		CURSOR_SetWinCursor( hwnd, classPtr->wc.hCursor );
+		SetCursor( classPtr->wc.hCursor );
 		return TRUE;
 	    }
 	    else return FALSE;
@@ -734,28 +735,23 @@
 
     case HTLEFT:
     case HTRIGHT:
-	CURSOR_SetWinCursor( hwnd, LoadCursor( 0, IDC_SIZEWE ) );
-	return TRUE;
+	return SetCursor( LoadCursor( 0, IDC_SIZEWE ) );
 
     case HTTOP:
     case HTBOTTOM:
-	CURSOR_SetWinCursor( hwnd, LoadCursor( 0, IDC_SIZENS ) );
-	return TRUE;
+	return SetCursor( LoadCursor( 0, IDC_SIZENS ) );
 
     case HTTOPLEFT:
     case HTBOTTOMRIGHT:	
-	CURSOR_SetWinCursor( hwnd, LoadCursor( 0, IDC_SIZENWSE ) );
-	return TRUE;
+	return SetCursor( LoadCursor( 0, IDC_SIZENWSE ) );
 
     case HTTOPRIGHT:
     case HTBOTTOMLEFT:
-	CURSOR_SetWinCursor( hwnd, LoadCursor( 0, IDC_SIZENESW ) );
-	return TRUE;
+	return SetCursor( LoadCursor( 0, IDC_SIZENESW ) );
     }
 
     /* Default cursor: arrow */
-    CURSOR_SetWinCursor( hwnd, LoadCursor( 0, IDC_ARROW ) );
-    return TRUE;
+    return SetCursor( LoadCursor( 0, IDC_ARROW ) );
 }
 
 
@@ -1211,9 +1207,8 @@
 {
     WND *wndPtr = WIN_FindWndPtr( hwnd );
 
-#ifdef DEBUG_NONCLIENT
-    printf( "Handling WM_SYSCOMMAND %x %d,%d\n", wParam, pt.x, pt.y );
-#endif
+    dprintf_nonclient(stddeb, "Handling WM_SYSCOMMAND %x %d,%d\n", 
+		      wParam, pt.x, pt.y );
 
     if (wndPtr->dwStyle & WS_CHILD) ScreenToClient( wndPtr->hwndParent, &pt );
 
diff --git a/windows/painting.c b/windows/painting.c
index 8c5658c..878e9d8 100644
--- a/windows/painting.c
+++ b/windows/painting.c
@@ -97,6 +97,8 @@
 
     if (!hwnd) hwnd = GetDesktopWindow();
     if (!(wndPtr = WIN_FindWndPtr( hwnd ))) return FALSE;
+    if (!(wndPtr->dwStyle & WS_VISIBLE) || (wndPtr->flags & WIN_NO_REDRAW))
+        return TRUE;  /* No redraw needed */
 
     /* 
      *	I can't help but feel that this belongs somewhere upstream...
@@ -104,7 +106,7 @@
      *  Don't redraw the window if it is iconified and we have an
      *  icon to draw for it
      */
-    if (IsIconic(hwnd) && wndPtr->hIcon) return FALSE;
+/*    if (IsIconic(hwnd) && wndPtr->hIcon) return FALSE; */
 
     GetClientRect( hwnd, &rectClient );
     rectWindow = wndPtr->rectWindow;
@@ -247,7 +249,7 @@
       /* Recursively process children */
 
     if (!(flags & RDW_NOCHILDREN) &&
-	((flags && RDW_ALLCHILDREN) || (wndPtr->dwStyle & WS_CLIPCHILDREN)))
+	((flags && RDW_ALLCHILDREN) || !(wndPtr->dwStyle & WS_CLIPCHILDREN)))
     {
 	if (hrgnUpdate)
 	{
diff --git a/windows/scroll.c b/windows/scroll.c
index 29dbe7c..5afef8e 100644
--- a/windows/scroll.c
+++ b/windows/scroll.c
@@ -10,6 +10,11 @@
 #include <stdlib.h>
 #include "windows.h"
 #include "gdi.h"
+#include "stddebug.h"
+/* #define DEBUG_SCROLL /* */
+/* #undef  DEBUG_SCROLL /* */
+#include "debug.h"
+
 
 static int RgnType;
 
@@ -24,10 +29,8 @@
     HRGN hrgnUpdate;
     RECT rc, cliprc;
 
-#ifdef DEBUG_SCROLL
-    printf("ScrollWindow: dx=%d, dy=%d, rect=%d,%d,%d,%d\n", dx, dy,
-	   rect->left, rect->top, rect->right, rect->bottom);
-#endif
+    dprintf_scroll(stddeb,"ScrollWindow: dx=%d, dy=%d, rect=%d,%d,%d,%d\n", 
+	   dx, dy, rect->left, rect->top, rect->right, rect->bottom);
 
     hdc = GetDC(hwnd);
 
@@ -59,10 +62,8 @@
     short width, height;
     DC *dc = (DC *)GDI_GetObjPtr(hdc, DC_MAGIC);
 
-#ifdef DEBUG_SCROLL
-    printf("ScrollDC: dx=%d, dy=%d, rc=%d,%d,%d,%d\n", dx, dy,
+    dprintf_scroll(stddeb, "ScrollDC: dx=%d, dy=%d, rc=%d,%d,%d,%d\n", dx, dy,
 	   rc->left, rc->top, rc->right, rc->bottom);
-#endif
 
     if (rc == NULL)
 	return;
@@ -122,11 +123,7 @@
 	RgnType = CombineRgn(hrgnUpdate, hrgn1, hrgn2, RGN_OR);
     }
 
-    if (rcUpdate)
-    {
-	SelectClipRgn(hdc, hrgnUpdate);
-	GetClipBox(hdc, rcUpdate);
-    }
+    if (rcUpdate) GetRgnBox( hrgnUpdate, rcUpdate );
 }
 
 
@@ -140,10 +137,8 @@
     HDC hdc;
     RECT rc, cliprc;
 
-#ifdef DEBUG_SCROLL
-    printf("ScrollWindowEx: dx=%d, dy=%d, rect=%d,%d,%d,%d\n", dx, dy,
-	   rect->left, rect->top, rect->right, rect->bottom);
-#endif
+    dprintf_scroll(stddeb,"ScrollWindowEx: dx=%d, dy=%d, rect=%d,%d,%d,%d\n", 
+	   dx, dy, rect->left, rect->top, rect->right, rect->bottom);
 
     hdc = GetDC(hwnd);
 
diff --git a/windows/syscolor.c b/windows/syscolor.c
index 8d0cda3..de92afc 100644
--- a/windows/syscolor.c
+++ b/windows/syscolor.c
@@ -9,10 +9,15 @@
 static char Copyright[] = "Copyright  David W. Metcalfe, 1993";
 static char Copyright2[] = "Copyright  Alexandre Julliard, 1994";
 
+#include <stdio.h>
 #include <stdlib.h>
-
 #include "windows.h"
 #include "syscolor.h"
+#include "stddebug.h"
+/* #define DEBUG_SYSCOLOR /* */
+/* #undef  DEBUG_SYSCOLOR /* */
+#include "debug.h"
+
 
 struct SysColorObjects sysColorObjects = { 0, };
 
@@ -150,9 +155,8 @@
 
 COLORREF GetSysColor(short nIndex)
 {
-#ifdef DEBUG_SYSCOLOR
-    printf("System Color %d = %6x\n", nIndex, SysColors[nIndex]);
-#endif
+    dprintf_syscolor(stddeb,"System Color %d = %6x\n", 
+		    nIndex, SysColors[nIndex]);
     return SysColors[nIndex];
 }
 
diff --git a/windows/timer.c b/windows/timer.c
index 6aad7ac..b95b99b 100644
--- a/windows/timer.c
+++ b/windows/timer.c
@@ -8,6 +8,10 @@
 
 #include "windows.h"
 #include "message.h"
+#include "stddebug.h"
+/* #define DEBUG_TIMER /* */
+/* #undef  DEBUG_TIMER /* */
+#include "debug.h"
 
 
 typedef struct tagTIMER
@@ -133,25 +137,22 @@
     TIMER * pTimer;
 
     if (!timeout) return 0;
-    if (!hwnd && !proc) return 0;
+/*    if (!hwnd && !proc) return 0; */
 
       /* Check if there's already a timer with the same hwnd and id */
 
-    if (hwnd)
-    {
-	for (i = 0, pTimer = TimersArray; i < NB_TIMERS; i++, pTimer++)
-	    if ((pTimer->hwnd == hwnd) && (pTimer->id == id) &&
-		(pTimer->timeout != 0))
-	    {
-		  /* Got one: set new values and return */
-		pTimer->timeout = timeout;
-		pTimer->expires = GetTickCount() + timeout;
-		pTimer->proc    = proc;
-		TIMER_RemoveTimer( pTimer );
-		TIMER_InsertTimer( pTimer );
-		return id;
-	    }
-    }
+    for (i = 0, pTimer = TimersArray; i < NB_TIMERS; i++, pTimer++)
+        if ((pTimer->hwnd == hwnd) && (pTimer->id == id) &&
+            (pTimer->timeout != 0))
+        {
+              /* Got one: set new values and return */
+            pTimer->timeout = timeout;
+            pTimer->expires = GetTickCount() + timeout;
+            pTimer->proc    = proc;
+            TIMER_RemoveTimer( pTimer );
+            TIMER_InsertTimer( pTimer );
+            return id;
+        }
 
       /* Find a free timer */
     
@@ -215,9 +216,7 @@
  */
 WORD SetTimer( HWND hwnd, WORD id, WORD timeout, FARPROC proc )
 {
-#ifdef DEBUG_TIMER    
-    printf( "SetTimer: %d %d %d %p\n", hwnd, id, timeout, proc );
-#endif
+    dprintf_timer(stddeb, "SetTimer: %d %d %d %p\n", hwnd, id, timeout, proc );
     return TIMER_SetTimer( hwnd, id, timeout, proc, FALSE );
 }
 
@@ -227,9 +226,8 @@
  */
 WORD SetSystemTimer( HWND hwnd, WORD id, WORD timeout, FARPROC proc )
 {
-#ifdef DEBUG_TIMER    
-    printf( "SetSystemTimer: %d %d %d %p\n", hwnd, id, timeout, proc );
-#endif
+    dprintf_timer(stddeb, "SetSystemTimer: %d %d %d %p\n", 
+		  hwnd, id, timeout, proc );
     return TIMER_SetTimer( hwnd, id, timeout, proc, TRUE );
 }
 
@@ -239,9 +237,7 @@
  */
 BOOL KillTimer( HWND hwnd, WORD id )
 {
-#ifdef DEBUG_TIMER
-    printf( "KillTimer: %d %d\n", hwnd, id );
-#endif
+    dprintf_timer(stddeb, "KillTimer: %d %d\n", hwnd, id );
     return TIMER_KillTimer( hwnd, id, FALSE );
 }
 
@@ -251,8 +247,6 @@
  */
 BOOL KillSystemTimer( HWND hwnd, WORD id )
 {
-#ifdef DEBUG_TIMER
-    printf( "KillSystemTimer: %d %d\n", hwnd, id );
-#endif
+    dprintf_timer(stddeb, "KillSystemTimer: %d %d\n", hwnd, id );
     return TIMER_KillTimer( hwnd, id, TRUE );
 }
diff --git a/windows/utility.c b/windows/utility.c
index afec604..5f9fcad 100644
--- a/windows/utility.c
+++ b/windows/utility.c
@@ -13,10 +13,14 @@
 #include <ctype.h>
 #include <stdlib.h>
 #include "windows.h"
+#include "stddebug.h"
+/* #define DEBUG_UTILITY /* */
+/* #undef  DEBUG_UTILITY /* */
+#include "debug.h"
+
 
 static char Copyright[] = "Copyright Andrew C. Bulhak, 1993";
 
-/*#define debug_utility*/
 
 /*	MulDiv is a simple function that may as well have been
  *	implemented as a macro; however Microsoft, in their infinite
@@ -77,9 +81,8 @@
 
 static void UTILITY_qualify(const char *source, char *dest)
 {
-#ifdef debug_utility
-	fprintf(stderr, "UTILITY_qualify(\"%s\", \"%s\");\n", source, dest);
-#endif
+	dprintf_utility(stddeb, "UTILITY_qualify(\"%s\", \"%s\");\n", 
+			source, dest);
 	if(!source) return;	/* Dumbass attack! */
 	while(*source) {
 		/* Find next format code. */
@@ -129,49 +132,35 @@
 		while((*format) && (*format != '%')) format++;	/* skip ahead */
 		if(*format) {
 			char modifier = ' ';
-#ifdef debug_utility
-			fprintf(stderr, "found:\t\"%%");
-#endif
+			dprintf_utility(stddeb, "found:\t\"%%");
 			format++;		/* skip past '%' */
 			/* First skip the flags, field width, etc. */
 			/* First the flags */
 			if ((*format == '#') || (*format == '-') || (*format == '+')
 				|| (*format == ' ')) {
-#ifdef debug_utility
-				fprintf(stderr, "%c", *format);
-#endif
+				dprintf_utility(stddeb, "%c", *format);
 				format++;
 			}
 			/* Now the field width, etc. */
 			while(isdigit(*format)) {
-#ifdef debug_utility
-				fprintf(stderr, "%c", *format);
-#endif
+				dprintf_utility(stddeb, "%c", *format);
 				format++;
 			}
 			if(*format == '.') {
-#ifdef debug_utility
-				fprintf(stderr, "%c", *format);
-#endif
+				dprintf_utility(stddeb, "%c", *format);
 				format++;
 			}
 			while(isdigit(*format)) {
-#ifdef debug_utility
-				fprintf(stderr, "%c", *format);
-#endif
+				dprintf_utility(stddeb, "%c", *format);
 				format++;
 			}
 			/* Now we handle the rest */
 			if((*format == 'h') || (*format == 'l') || (*format == 'L')) {
-#ifdef debug_utility
-				fprintf(stderr, "%c", modifier);
-#endif
+				dprintf_utility(stddeb, "%c", modifier);
 				modifier = *(format++);
 			}
 			/* Handle the actual type. */
-#ifdef debug_utility
-				fprintf(stderr, "%c\"\n", *format);
-#endif
+				dprintf_utility(stddeb, "%c\"\n", *format);
 			switch(*format) {
 				case 'd':
 				case 'i':
@@ -199,9 +188,7 @@
 		};
 	};
 #undef INT_SIZE
-#ifdef debug_utility
-	fprintf(stderr, "UTILITY_argsize: returning %i\n", size);
-#endif
+	dprintf_utility(stddeb, "UTILITY_argsize: returning %i\n", size);
 	return size;
 };
 
@@ -227,9 +214,7 @@
 		while((*format) && (*format != '%')) format++;	/* skip ahead */
 		if(*format) {
 			char modifier = ' ';
-#ifdef debug_utility
-			fprintf(stderr, "found:\t\"%%");
-#endif
+			dprintf_utility(stddeb, "found:\t\"%%");
 			format++;		/* skip past '%' */
 			/* First skip the flags, field width, etc. */
 			/* First the flags */
@@ -243,9 +228,7 @@
 			if((*format == 'h') || (*format == 'l') || (*format == 'L'))
 				modifier = *(format++);
 			/* Handle the actual type. */
-#ifdef debug_utility
-				fprintf(stderr, "%c\"\n", *format);
-#endif
+			dprintf_utility(stddeb, "%c\"\n", *format);
 			switch(*format) {
 				case 'd':
 				case 'i':
diff --git a/windows/win.c b/windows/win.c
index 2c27a76..9e90dcc 100644
--- a/windows/win.c
+++ b/windows/win.c
@@ -1,10 +1,10 @@
 /*
  * Window related functions
  *
- * Copyright 1993 Alexandre Julliard
+ * Copyright 1993, 1994 Alexandre Julliard
  */
 
-static char Copyright[] = "Copyright  Alexandre Julliard, 1993";
+static char Copyright[] = "Copyright  Alexandre Julliard, 1993, 1994";
 
 #include <stdlib.h>
 #include <stdio.h>
@@ -18,11 +18,17 @@
 #include "sysmetrics.h"
 #include "scroll.h"
 #include "icon.h"
+#include "cursor.h"
+#include "stddebug.h"
+/* #define DEBUG_WIN  /* */ 
+/* #undef  DEBUG_WIN  /* */
+/* #define DEBUG_MENU /* */
+/* #undef  DEBUG_MENU /* */
+#include "debug.h"
 
 extern Colormap COLOR_WinColormap;
 
 extern void EVENT_RegisterWindow( Window w, HWND hwnd );  /* event.c */
-extern void CURSOR_SetWinCursor( HWND hwnd, HCURSOR hcursor );  /* cursor.c */
 extern void WINPOS_ChangeActiveWindow( HWND hwnd, BOOL mouseMsg ); /*winpos.c*/
 extern LONG WINPOS_SendNCCalcSize( HWND hwnd, BOOL calcValidRect,
 				   RECT *newWindowRect, RECT *oldWindowRect,
@@ -54,6 +60,22 @@
 
 
 /***********************************************************************
+ *           WIN_GetXWindow
+ *
+ * Return the X window associated to a window.
+ */
+Window WIN_GetXWindow( HWND hwnd )
+{
+    WND *wndPtr = WIN_FindWndPtr( hwnd );
+    while (wndPtr && !wndPtr->window)
+    {
+        wndPtr = WIN_FindWndPtr( wndPtr->hwndParent );
+    }
+    return wndPtr ? wndPtr->window : 0;
+}
+
+
+/***********************************************************************
  *           WIN_UnlinkWindow
  *
  * Remove a window from the siblings linked list.
@@ -129,6 +151,8 @@
     for ( ; hwnd != 0; hwnd = wndPtr->hwndNext )
     {
 	if (!(wndPtr = WIN_FindWndPtr( hwnd ))) return 0;
+        if (!(wndPtr->dwStyle & WS_VISIBLE) || (wndPtr->flags & WIN_NO_REDRAW))
+            continue;
 	if (wndPtr->hrgnUpdate || (wndPtr->flags & WIN_INTERNAL_PAINT))
 	    return hwnd;
 	if (wndPtr->hwndChild)
@@ -163,6 +187,35 @@
 
 
 /***********************************************************************
+ *           WIN_DestroyWindow
+ *
+ * Destroy storage associated to a window
+ */
+static void WIN_DestroyWindow( HWND hwnd )
+{
+    WND *wndPtr = WIN_FindWndPtr( hwnd );
+    CLASS *classPtr = CLASS_FindClassPtr( wndPtr->hClass );
+
+    if (!wndPtr || !classPtr) return;
+    wndPtr->dwMagic = 0;  /* Mark it as invalid */
+    if ((wndPtr->hrgnUpdate) || (wndPtr->flags & WIN_INTERNAL_PAINT))
+    {
+        if (wndPtr->hrgnUpdate) DeleteObject( wndPtr->hrgnUpdate );
+        MSG_DecPaintCount( wndPtr->hmemTaskQ );
+    }
+    if (!(wndPtr->dwStyle & WS_CHILD))
+    {
+        if (wndPtr->wIDmenu) DestroyMenu( wndPtr->wIDmenu );
+    }
+    if (wndPtr->hSysMenu) DestroyMenu( wndPtr->hSysMenu );
+    if (wndPtr->window) XDestroyWindow( display, wndPtr->window );
+    if (classPtr->wc.style & CS_OWNDC) DCE_FreeDCE( wndPtr->hdce );
+    classPtr->cWindows--;
+    USER_HEAP_FREE( hwnd );
+}
+
+
+/***********************************************************************
  *           WIN_CreateDesktopWindow
  *
  * Create the desktop window.
@@ -246,18 +299,16 @@
 {
     HANDLE class, hwnd;
     CLASS *classPtr;
-    WND *wndPtr, *parentPtr = NULL;
+    WND *wndPtr;
     POINT maxSize, maxPos, minTrack, maxTrack;
     CREATESTRUCT *createStruct;
     HANDLE hcreateStruct;
     int wmcreate;
     XSetWindowAttributes win_attr;
 
-#ifdef DEBUG_WIN
-    printf( "CreateWindowEx: %04X '%s' '%s' %04X %d,%d %dx%d %04X %04X %04X %08X\n",
+    dprintf_win(stddeb, "CreateWindowEx: %04X '%s' '%s' %04X %d,%d %dx%d %04X %04X %04X %08X\n",
 				exStyle, className, windowName, style, x, y, width, height, 
 				parent, menu, instance, data);
-#endif
 	/* 'soundrec.exe' has negative position ! 
 	Why ? For now, here a patch : */
         if (!strcmp(className, "SoundRec"))
@@ -278,13 +329,13 @@
 
     if (parent)
     {
-	  /* Check if parent is valid */
-	if (!(parentPtr = WIN_FindWndPtr( parent ))) return 0;
+	  /* Make sure parent is valid */
+        if (!IsWindow( parent )) return 0;
     }
     else if (style & WS_CHILD) return 0;  /* WS_CHILD needs a parent */
 
     if (!(class = CLASS_FindClassByName( className, &classPtr ))) {
-	printf("CreateWindow BAD CLASSNAME '%s' !\n", className);
+	fprintf(stderr,"CreateWindow BAD CLASSNAME '%s' !\n", className);
 	return 0;
 	}    
 
@@ -304,7 +355,7 @@
     wndPtr = (WND *) USER_HEAP_ADDR( hwnd );
     wndPtr->hwndNext   = 0;
     wndPtr->hwndChild  = 0;
-	wndPtr->window 	   = 0;
+    wndPtr->window     = 0;
     wndPtr->dwMagic    = WND_MAGIC;
     wndPtr->hwndParent = (style & WS_CHILD) ? parent : hwndDesktop;
     wndPtr->hwndOwner  = (style & WS_CHILD) ? 0 : parent;
@@ -339,41 +390,27 @@
 
     if (classPtr->wc.cbWndExtra)
 	memset( wndPtr->wExtra, 0, classPtr->wc.cbWndExtra );
-    if (classPtr->wc.style & CS_DBLCLKS) wndPtr->flags |= WIN_DOUBLE_CLICKS;
     classPtr->cWindows++;
 
+      /* Make sure owner is a top-level window */
+
+    while (wndPtr->hwndOwner && GetParent(wndPtr->hwndOwner))
+        wndPtr->hwndOwner = GetParent(wndPtr->hwndOwner);
+
       /* Get class or window DC if needed */
+
     if (classPtr->wc.style & CS_OWNDC)
-    {
-	wndPtr->flags |= WIN_OWN_DC;
-	wndPtr->hdce = DCE_AllocDCE( DCE_WINDOW_DC );
-    }
+        wndPtr->hdce = DCE_AllocDCE( DCE_WINDOW_DC );
     else if (classPtr->wc.style & CS_CLASSDC)
-    {
-	wndPtr->flags |= WIN_CLASS_DC;
-	wndPtr->hdce = classPtr->hdce;
-    }
-    else wndPtr->hdce = 0;
+        wndPtr->hdce = classPtr->hdce;
+    else
+        wndPtr->hdce = 0;
 
       /* Insert the window in the linked list */
 
     WIN_LinkWindow( hwnd, HWND_TOP );
 
-      /* Create the X window */
-
-    win_attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask |
-	                 PointerMotionMask | ButtonPressMask |
-			 ButtonReleaseMask | EnterWindowMask;
-    win_attr.override_redirect = (rootWindow == DefaultRootWindow(display));
-    win_attr.colormap          = COLOR_WinColormap;
-    if (!(style & WS_CHILD))
-    {
-	parentPtr = WIN_FindWndPtr( hwndDesktop );
-	  /* Only select focus events on top-level override-redirect windows */
-	if (win_attr.override_redirect) win_attr.event_mask |= FocusChangeMask;
-    }
-    win_attr.backing_store = Options.backingstore ? WhenMapped : NotUseful;
-    win_attr.save_under = ((classPtr->wc.style & CS_SAVEBITS) != 0);
+      /* Send the WM_GETMINMAXINFO message and fix the size if needed */
 
     WINPOS_GetMinMaxInfo( hwnd, &maxSize, &maxPos, &minTrack, &maxTrack );
 
@@ -388,36 +425,38 @@
 	wndPtr->rectWindow.bottom = y + height;
       }
 
-    wndPtr->window = XCreateWindow( display, parentPtr->window,
-		   x + parentPtr->rectClient.left - parentPtr->rectWindow.left,
-		   y + parentPtr->rectClient.top - parentPtr->rectWindow.top,
-		   width, height, 0,
-		   CopyFromParent, InputOutput, CopyFromParent,
-		   CWEventMask | CWOverrideRedirect | CWColormap |
-		   CWSaveUnder | CWBackingStore, &win_attr );
-    XStoreName( display, wndPtr->window, windowName );
+      /* Create the X window (only for top-level windows, and then only */
+      /* when there's no desktop window) */
 
+    if (!(style & WS_CHILD) && (rootWindow == DefaultRootWindow(display)))
+    {
+        CURSORALLOC *cursor;
+        HCURSOR hCursor = classPtr->wc.hCursor;
+        if (!hCursor) hCursor = LoadCursor( 0, IDC_ARROW );
+        cursor = (CURSORALLOC *) GlobalLock(hCursor);
 
-    /* 
-     * store icon handle, icon handle is kept in class.  If we
-     * have an icon, make the icon size the size of the icon,
-     * if we don't have an icon, just give it 64x64
-     */
-    wndPtr->hIcon = classPtr->wc.hIcon;
-    if (wndPtr->hIcon != (HICON)NULL) {
-      ICONALLOC   *lpico;
-      lpico = (ICONALLOC *)GlobalLock(wndPtr->hIcon);
-      wndPtr->iconWidth = (int)lpico->descriptor.Width;
-      wndPtr->iconHeight = (int)lpico->descriptor.Height;
-    } else {
-      wndPtr->iconWidth = 64;
-      wndPtr->iconHeight = 64;
+        win_attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask |
+                              PointerMotionMask | ButtonPressMask |
+                              ButtonReleaseMask | FocusChangeMask;
+        win_attr.override_redirect = TRUE;
+        win_attr.colormap      = COLOR_WinColormap;
+        win_attr.backing_store = Options.backingstore ? WhenMapped : NotUseful;
+        win_attr.save_under    = ((classPtr->wc.style & CS_SAVEBITS) != 0);
+        win_attr.cursor        = cursor ? cursor->xcursor : None;
+        wndPtr->window = XCreateWindow( display, rootWindow, x, y,
+                                        width, height, 0, CopyFromParent,
+                                        InputOutput, CopyFromParent,
+                                        CWEventMask | CWOverrideRedirect |
+                                        CWColormap | CWCursor | CWSaveUnder |
+                                        CWBackingStore, &win_attr );
+        XStoreName( display, wndPtr->window, windowName );
+        EVENT_RegisterWindow( wndPtr->window, hwnd );
+        GlobalUnlock( hCursor );
     }
+    
+    dprintf_menu(stddeb,"CreateWindowEx // menu=%04X instance=%04X classmenu=%08X !\n", 
+    	menu, instance, classPtr->wc.lpszMenuName);
 
-#ifdef DEBUG_MENU
-    printf("CreateWindowEx // menu=%04X instance=%04X classmenu=%08X !\n", 
-    	menu, instance, classPtr->wc.lpszMenuName); 
-#endif
 	if ((style & WS_CAPTION) && (style & WS_CHILD) == 0) {
 		if (menu != 0)
 			SetMenu(hwnd, menu);
@@ -460,35 +499,22 @@
     if (wmcreate == -1)
     {
 	  /* Abort window creation */
-
-	WIN_UnlinkWindow( hwnd );
-	XDestroyWindow( display, wndPtr->window );
-	if (wndPtr->flags & WIN_OWN_DC) DCE_FreeDCE( wndPtr->hdce );
-	classPtr->cWindows--;
-	USER_HEAP_FREE( hwnd );
+        WIN_DestroyWindow( hwnd );
 	return 0;
     }
 
       /* Create a copy of SysMenu */
     if (style & WS_SYSMENU) wndPtr->hSysMenu = CopySysMenu();
 
-	/* Register window in current task windows list */
-	AddWindowToTask(GetCurrentTask(), hwnd);
-
-      /* Set window cursor */
-    if (classPtr->wc.hCursor) CURSOR_SetWinCursor( hwnd, classPtr->wc.hCursor);
-    else CURSOR_SetWinCursor( hwnd, LoadCursor( 0, IDC_ARROW ));
-
-    EVENT_RegisterWindow( wndPtr->window, hwnd );
+      /* Register window in current task windows list */
+    AddWindowToTask(GetCurrentTask(), hwnd);
 
     WIN_SendParentNotify( hwnd, WM_CREATE, MAKELONG( hwnd, wndPtr->wIDmenu ) );
     
     if (style & WS_VISIBLE) ShowWindow( hwnd, SW_SHOW );
 /*    if (style & WS_MINIMIZE) ShowWindow( hwnd, SW_MINIMIZE ); */
 
-#ifdef DEBUG_WIN
-    printf( "CreateWindowEx: return %04X \n", hwnd);
-#endif
+    dprintf_win(stddeb, "CreateWindowEx: return %04X \n", hwnd);
     return hwnd;
 }
 
@@ -531,11 +557,7 @@
 
       /* Destroy the window */
 
-    wndPtr->dwMagic = 0;  /* Mark it as invalid */
-    XDestroyWindow( display, wndPtr->window );
-    if (wndPtr->flags & WIN_OWN_DC) DCE_FreeDCE( wndPtr->hdce );
-    classPtr->cWindows--;
-    USER_HEAP_FREE( hwnd );
+    WIN_DestroyWindow( hwnd );
     return TRUE;
 }
 
@@ -933,9 +955,7 @@
     WND *wndPtr;
     int result;
 
-#ifdef DEBUG_ENUM
-    printf("EnumWindows\n");
-#endif 
+    dprintf_enum(stddeb,"EnumWindows\n");
 
     while (hwnd) {
       char *ptr;
@@ -943,12 +963,6 @@
         if ( !(wndPtr=WIN_FindWndPtr(hwnd)) ) {
               return 0;
       }
-#ifdef DEBUG_ENUM
-      if (XFetchName(display, wndPtr->window, &ptr) && ptr)
-              printf("found a window (%s)\n", ptr);
-      else 
-              printf("found nameless parent window\n");
-#endif
 #ifdef WINELIB
       (*wndenumprc)(hwnd, lParam);
 #else
@@ -984,19 +998,8 @@
       if ( !(wndPtr=WIN_FindWndPtr(hwnd)) ) {
             return 0;
         }
-#ifdef DEBUG_ENUM
-      if (XFetchName(display, wndPtr->window, &ptr) && ptr)
-              printf("EnumChild: found a child window (%s)\n", ptr);
-      else 
-              printf("EnumChild: nameless child\n");
-      
-        if (!(wndPtr->dwStyle & WS_CHILD)) {
-           printf("this is not a child window!  What is it doing here?\n");
-           return 0;
-      }
-#endif
 #ifdef WINELIB
-        if (!(*wndenumprc, 2, lParam, (int) hwnd)) {
+        if (!(*wndenumprc)( 2, lParam, (int) hwnd)) {
 #else
         if (!CallBack16(wndenumprc, 2, lParam, (int) hwnd)) {
 #endif
@@ -1021,9 +1024,7 @@
 {
     WND *wndPtr;
 
-#ifdef DEBUG_ENUM
-    printf("EnumChildWindows\n");
-#endif
+    dprintf_enum(stddeb,"EnumChildWindows\n");
 
     if (hwnd == 0) return 0;
     if (!(wndPtr = WIN_FindWndPtr(hwnd))) return 0;
@@ -1036,7 +1037,7 @@
  */
 BOOL AnyPopup()
 {
-	printf("EMPTY STUB !! AnyPopup !\n");
+	dprintf_win(stdnimp,"EMPTY STUB !! AnyPopup !\n");
 	return FALSE;
 }
 
@@ -1045,7 +1046,7 @@
  */
 BOOL FlashWindow(HWND hWnd, BOOL bInvert)
 {
-	printf("EMPTY STUB !! FlashWindow !\n");
+	dprintf_win(stdnimp,"EMPTY STUB !! FlashWindow !\n");
 	return FALSE;
 }
 
@@ -1057,7 +1058,7 @@
 {
 	HWND hWndOldModal = hWndSysModal;
 	hWndSysModal = hWnd;
-	printf("EMPTY STUB !! SetSysModalWindow(%04X) !\n", hWnd);
+	dprintf_win(stdnimp,"EMPTY STUB !! SetSysModalWindow(%04X) !\n", hWnd);
 	return hWndOldModal;
 }
 
diff --git a/windows/winpos.c b/windows/winpos.c
index a9415cd..f9b274d 100644
--- a/windows/winpos.c
+++ b/windows/winpos.c
@@ -10,12 +10,14 @@
 #include "user.h"
 #include "win.h"
 #include "message.h"
-#include <assert.h>
+#include "winpos.h"
+#include "stddebug.h"
+/* #define DEBUG_WIN /* */
+/* #undef  DEBUG_WIN /* */
+#include "debug.h"
 
 static HWND hwndActive = 0;  /* Currently active window */
 
-/* #define DEBUG_WIN /**/
-
 
 /***********************************************************************
  *           GetWindowRect   (USER.32)
@@ -216,13 +218,13 @@
 {    
     int flags = SWP_NOZORDER | SWP_NOACTIVATE;
     if (!repaint) flags |= SWP_NOREDRAW;
-#ifdef DEBUG_WIN    
-    printf( "MoveWindow: %d %d,%d %dx%d %d\n", hwnd, x, y, cx, cy, repaint );
-#endif
+    dprintf_win(stddeb, "MoveWindow: %d %d,%d %dx%d %d\n", 
+	    hwnd, x, y, cx, cy, repaint );
     return SetWindowPos( hwnd, 0, x, y, cx, cy, flags );
 }
 
 
+#if 0
 /*
  * hwnd is the handle to the first child window to hide
  */
@@ -261,6 +263,7 @@
 	hwnd = wndPtr->hwndNext;
     }
 }
+#endif
 
 /***********************************************************************
  *           ShowWindow   (USER.42)
@@ -274,9 +277,7 @@
 
     if (!wndPtr) return FALSE;
 
-#ifdef DEBUG_WIN
-    printf("ShowWindow: hwnd=%04X, cmd=%d\n", hwnd, cmd);
-#endif
+    dprintf_win(stddeb,"ShowWindow: hwnd=%04X, cmd=%d\n", hwnd, cmd);
 
     /*
      *  wasVisible is true if user has not made window invisible 
@@ -304,10 +305,12 @@
 	    swpflags |= SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE | 
 		        SWP_NOACTIVATE | SWP_NOZORDER;
 
+#if 0
 	    /*
 	     *	tell children that they are getting hidden
 	     */
 	    WINPOS_hideChildren(wndPtr->hwndChild);
+#endif
 
 	    /* store the size and position of the window, so we can
 	     *	deiconify it to the same size and position	
@@ -319,7 +322,7 @@
 	     * tell it that it is going to have to be painted
 	     */
             MoveWindow(hwnd, wndPtr->ptIconPos.x, wndPtr->ptIconPos.y,
-                        wndPtr->iconWidth, wndPtr->iconHeight, FALSE);
+                       SYSMETRICS_CXICON, SYSMETRICS_CYICON, FALSE);
             SendMessage(hwnd, WM_PAINTICON, 0, 0);
 	    break;
 
@@ -350,7 +353,9 @@
 			   wndPtr->rectNormal.bottom - wndPtr->rectNormal.top, 
 			   FALSE);
 	    }
+#if 0
 	    WINPOS_ChildrenComeOutToPlay(wndPtr->hwndChild);
+#endif
 	    break;
     }
 
@@ -575,6 +580,81 @@
 
 
 /***********************************************************************
+ *           WINPOS_MoveWindowZOrder
+ *
+ * Move a window in Z order, invalidating everything that needs it.
+ * Only necessary for windows without associated X window.
+ */
+static void WINPOS_MoveWindowZOrder( HWND hwnd, HWND hwndAfter, BOOL erase )
+{
+    BOOL movingUp;
+    HWND hwndCur;
+    WND *wndPtr = WIN_FindWndPtr( hwnd );
+
+    /* We have two possible cases:
+     * - The window is moving up: we have to invalidate all areas
+     *   of the window that were covered by other windows
+     * - The window is moving down: we have to invalidate areas
+     *   of other windows covered by this one.
+     */
+
+    if (hwndAfter == HWND_TOP)
+    {
+        movingUp = TRUE;
+    }
+    else if (hwndAfter == HWND_BOTTOM)
+    {
+        if (!wndPtr->hwndNext) return;  /* Already at the bottom */
+        movingUp = FALSE;
+    }
+    else
+    {
+        if (wndPtr->hwndNext == hwndAfter) return;  /* Already placed right */
+
+          /* Determine which window we encounter first in Z-order */
+        hwndCur = GetWindow( wndPtr->hwndParent, GW_CHILD );
+        while ((hwndCur != hwnd) && (hwndCur != hwndAfter))
+            hwndCur = GetWindow( hwndCur, GW_HWNDNEXT );
+        movingUp = (hwndCur == hwndAfter);
+    }
+
+    if (movingUp)
+    {
+        HWND hwndPrevAfter = wndPtr->hwndNext;
+        WIN_UnlinkWindow( hwnd );
+        WIN_LinkWindow( hwnd, hwndAfter );
+        hwndCur = wndPtr->hwndNext;
+        while (hwndCur != hwndPrevAfter)
+        {
+            WND *curPtr = WIN_FindWndPtr( hwndCur );
+            RECT rect = curPtr->rectWindow;
+            OffsetRect( &rect, -wndPtr->rectClient.left,
+                        -wndPtr->rectClient.top );
+            RedrawWindow( hwnd, &rect, 0, RDW_INVALIDATE | RDW_ALLCHILDREN |
+                          RDW_FRAME | (erase ? RDW_ERASENOW : RDW_ERASE) );
+            hwndCur = curPtr->hwndNext;
+        }
+    }
+    else  /* Moving down */
+    {
+        hwndCur = wndPtr->hwndNext;
+        WIN_UnlinkWindow( hwnd );
+        WIN_LinkWindow( hwnd, hwndAfter );
+        while (hwndCur != hwnd)
+        {
+            WND *curPtr = WIN_FindWndPtr( hwndCur );
+            RECT rect = wndPtr->rectWindow;
+            OffsetRect( &rect, -curPtr->rectClient.left,
+                        -curPtr->rectClient.top );
+            RedrawWindow( hwndCur, &rect, 0, RDW_INVALIDATE | RDW_ALLCHILDREN |
+                          RDW_FRAME | (erase ? RDW_ERASENOW : RDW_ERASE) );
+            hwndCur = curPtr->hwndNext;
+        }
+    }
+}
+
+
+/***********************************************************************
  *           WINPOS_InternalSetWindowPos
  *
  * Helper function for SetWindowPos.
@@ -606,8 +686,6 @@
       /* Check flags */
 
     flags = winpos->flags;
-    if (flags & (SWP_SHOWWINDOW | SWP_HIDEWINDOW))
-	flags |= SWP_NOMOVE | SWP_NOSIZE;
     if (winpos->hwnd == hwndActive) flags |= SWP_NOACTIVATE; /*Already active*/
 
       /* Check hwndAfter */
@@ -666,17 +744,22 @@
 
     if (!(flags & SWP_NOZORDER))
     {
-	WIN_UnlinkWindow( winpos->hwnd );
-	WIN_LinkWindow( winpos->hwnd, hwndAfter );
-	if (hwndAfter == HWND_TOP) winChanges.stack_mode = Above;
-	else winChanges.stack_mode = Below;
-	if ((hwndAfter != HWND_TOP) && (hwndAfter != HWND_BOTTOM))
-	{
-	    WND * insertPtr = WIN_FindWndPtr( hwndAfter );
-	    winChanges.sibling = insertPtr->window;
-	    changeMask |= CWSibling;
-	}
-	changeMask |= CWStackMode;
+        if (wndPtr->window)
+        {
+            WIN_UnlinkWindow( winpos->hwnd );
+            WIN_LinkWindow( winpos->hwnd, hwndAfter );
+            if (hwndAfter == HWND_TOP) winChanges.stack_mode = Above;
+            else winChanges.stack_mode = Below;
+            if ((hwndAfter != HWND_TOP) && (hwndAfter != HWND_BOTTOM))
+            {
+                WND * insertPtr = WIN_FindWndPtr( hwndAfter );
+                winChanges.sibling = insertPtr->window;
+                changeMask |= CWSibling;
+            }
+            changeMask |= CWStackMode;
+        }
+        else WINPOS_MoveWindowZOrder( winpos->hwnd, hwndAfter,
+                                      !(flags & SWP_DEFERERASE) );
     }
 
       /* Send WM_NCCALCSIZE message to get new client area */
@@ -688,25 +771,66 @@
 
       /* Perform the moving and resizing */
 
-    if (changeMask) XConfigureWindow( display, wndPtr->window,
-				      changeMask, &winChanges );
-    wndPtr->rectWindow = newWindowRect;
-    wndPtr->rectClient = newClientRect;
+    if (wndPtr->window)
+    {
+        if (changeMask) XConfigureWindow( display, wndPtr->window,
+                                          changeMask, &winChanges );
+        wndPtr->rectWindow = newWindowRect;
+        wndPtr->rectClient = newClientRect;
+    }
+    else
+    {
+        RECT oldWindowRect = wndPtr->rectWindow;
+
+        wndPtr->rectWindow = newWindowRect;
+        wndPtr->rectClient = newClientRect;
+
+        if (changeMask)
+        {
+            HRGN hrgn1 = CreateRectRgnIndirect( &oldWindowRect );
+            HRGN hrgn2 = CreateRectRgnIndirect( &wndPtr->rectWindow );
+            HRGN hrgn3 = CreateRectRgn( 0, 0, 0, 0 );
+            CombineRgn( hrgn3, hrgn1, hrgn2, RGN_DIFF );
+            RedrawWindow( wndPtr->hwndParent, NULL, hrgn3,
+                          RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_ERASENOW );
+            if ((oldWindowRect.left != wndPtr->rectWindow.left) ||
+                (oldWindowRect.top != wndPtr->rectWindow.top))
+            {
+                RedrawWindow( winpos->hwnd, NULL, 0, RDW_INVALIDATE |
+                              RDW_FRAME | RDW_ALLCHILDREN | RDW_ERASENOW );
+            }
+            DeleteObject( hrgn1 );
+            DeleteObject( hrgn2 );
+            DeleteObject( hrgn3 );
+        }
+    }
 
     if (flags & SWP_SHOWWINDOW)
     {
 	wndPtr->dwStyle |= WS_VISIBLE;
-	XMapWindow( display, wndPtr->window );
-	MSG_Synchronize();
-	if (flags & SWP_NOREDRAW)  /* Validate the whole window */
-	    RedrawWindow( winpos->hwnd, NULL, 0, RDW_VALIDATE );
+        if (wndPtr->window)
+        {
+            XMapWindow( display, wndPtr->window );
+            MSG_Synchronize();
+            if (flags & SWP_NOREDRAW)  /* Validate the whole window */
+                RedrawWindow( winpos->hwnd, NULL, 0, RDW_VALIDATE );
+        }
     }
     else if (flags & SWP_HIDEWINDOW)
     {
 	wndPtr->dwStyle &= ~WS_VISIBLE;
-	XUnmapWindow( display, wndPtr->window );
-	if ((winpos->hwnd == GetFocus()) || IsChild(winpos->hwnd, GetFocus()))
-	    SetFocus( GetParent(winpos->hwnd) );  /* Revert focus to parent */
+        if (wndPtr->window)
+        {
+            XUnmapWindow( display, wndPtr->window );
+        }
+        else
+        {
+            RedrawWindow( wndPtr->hwndParent, &wndPtr->rectWindow, 0,
+                          RDW_INVALIDATE | RDW_FRAME |
+                          RDW_ALLCHILDREN | RDW_ERASENOW );
+        }
+        if ((winpos->hwnd == GetFocus()) || IsChild(winpos->hwnd, GetFocus()))
+            SetFocus( GetParent(winpos->hwnd) );  /* Revert focus to parent */
 	if (winpos->hwnd == hwndActive)
 	{
 	      /* Activate previously active window if possible */
@@ -754,37 +878,120 @@
 
 					
 /***********************************************************************
+ *           BeginDeferWindowPos   (USER.259)
+ */
+HDWP BeginDeferWindowPos( INT count )
+{
+    HDWP handle;
+    DWP *pDWP;
+
+    if (count <= 0) return 0;
+    handle = USER_HEAP_ALLOC( GMEM_MOVEABLE,
+                              sizeof(DWP) + (count-1)*sizeof(WINDOWPOS) );
+    if (!handle) return 0;
+    pDWP = (DWP *) USER_HEAP_ADDR( handle );
+    pDWP->actualCount    = 0;
+    pDWP->suggestedCount = count;
+    pDWP->valid          = TRUE;
+    pDWP->wMagic         = DWP_MAGIC;
+    return handle;
+}
+
+
+/***********************************************************************
+ *           DeferWindowPos   (USER.260)
+ */
+HDWP DeferWindowPos( HDWP hdwp, HWND hwnd, HWND hwndAfter, INT x, INT y,
+                     INT cx, INT cy, WORD flags )
+{
+    DWP *pDWP;
+    int i;
+    HDWP newhdwp = hdwp;
+
+    pDWP = (DWP *) USER_HEAP_ADDR( hdwp );
+    if (!pDWP) return 0;
+    for (i = 0; i < pDWP->actualCount; i++)
+    {
+        if (pDWP->winPos[i].hwnd == hwnd)
+        {
+              /* Merge with the other changes */
+            if (!(flags & SWP_NOZORDER))
+            {
+                pDWP->winPos[i].hwndInsertAfter = hwndAfter;
+            }
+            if (!(flags & SWP_NOMOVE))
+            {
+                pDWP->winPos[i].x = x;
+                pDWP->winPos[i].y = y;
+            }                
+            if (!(flags & SWP_NOSIZE))
+            {
+                pDWP->winPos[i].cx = cx;
+                pDWP->winPos[i].cy = cy;
+            }
+            pDWP->winPos[i].flags &= flags & (SWP_NOSIZE | SWP_NOMOVE |
+                                              SWP_NOZORDER | SWP_NOREDRAW |
+                                              SWP_NOACTIVATE | SWP_NOCOPYBITS |
+                                              SWP_NOOWNERZORDER);
+            pDWP->winPos[i].flags |= flags & (SWP_SHOWWINDOW | SWP_HIDEWINDOW |
+                                              SWP_FRAMECHANGED);
+            return hdwp;
+        }
+    }
+    if (pDWP->actualCount >= pDWP->suggestedCount)
+    {
+        newhdwp = USER_HEAP_REALLOC( hdwp,
+                      sizeof(DWP) + pDWP->suggestedCount*sizeof(WINDOWPOS), 0);
+        if (!newhdwp) return 0;
+        pDWP = (DWP *) USER_HEAP_ADDR( newhdwp );
+        pDWP->suggestedCount++;
+    }
+    pDWP->winPos[pDWP->actualCount].hwnd = hwnd;
+    pDWP->winPos[pDWP->actualCount].hwndInsertAfter = hwndAfter;
+    pDWP->winPos[pDWP->actualCount].x = x;
+    pDWP->winPos[pDWP->actualCount].y = y;
+    pDWP->winPos[pDWP->actualCount].cx = cx;
+    pDWP->winPos[pDWP->actualCount].cy = cy;
+    pDWP->winPos[pDWP->actualCount].flags = flags;
+    pDWP->actualCount++;
+    return newhdwp;
+}
+
+
+/***********************************************************************
+ *           EndDeferWindowPos   (USER.261)
+ */
+BOOL EndDeferWindowPos( HDWP hdwp )
+{
+    DWP *pDWP;
+    BOOL res = TRUE;
+    int i;
+
+    pDWP = (DWP *) USER_HEAP_ADDR( hdwp );
+    if (!pDWP) return FALSE;
+    for (i = 0; i < pDWP->actualCount; i++)
+    {
+        if (!(res = WINPOS_InternalSetWindowPos( &pDWP->winPos[i] ))) break;
+    }
+    USER_HEAP_FREE( hdwp );
+    return res;
+}
+
+
+/***********************************************************************
  *           SetWindowPos   (USER.232)
  */
-/* Note: all this code should be in the DeferWindowPos() routines,
- * and SetWindowPos() should simply call them.  This will be implemented
- * some day...
- */
-BOOL SetWindowPos( HWND hwnd, HWND hwndInsertAfter, short x, short y,
-		   short cx, short cy, WORD flags )
+BOOL SetWindowPos( HWND hwnd, HWND hwndInsertAfter, INT x, INT y,
+		   INT cx, INT cy, WORD flags )
 {
-    WINDOWPOS *winPos;
-    HANDLE hmem = 0;
-    BOOL res;
+    HDWP hdwp;
 
 #ifdef DEBUG_WIN
     printf( "SetWindowPos: %04X %d %d,%d %dx%d 0x%x\n",
-	    hwnd, hwndInsertAfter, x, y, cx, cy, flags );
+            hwnd, hwndInsertAfter, x, y, cx, cy, flags );
 #endif
-
-    if (!(hmem = USER_HEAP_ALLOC( GMEM_MOVEABLE, sizeof(WINDOWPOS) )))
-	return FALSE;
-    winPos = (WINDOWPOS *)USER_HEAP_ADDR( hmem );
-    winPos->hwnd = hwnd;
-    winPos->hwndInsertAfter = hwndInsertAfter;
-    winPos->x = x;
-    winPos->y = y;
-    winPos->cx = cx;
-    winPos->cy = cy;
-    winPos->flags = flags;
-
-    res = WINPOS_InternalSetWindowPos( winPos );
-
-    USER_HEAP_FREE( hmem );
-    return res;
+    if (!(hdwp = BeginDeferWindowPos( 1 ))) return FALSE;
+    if (!(hdwp = DeferWindowPos( hdwp, hwnd, hwndInsertAfter,
+                                 x, y, cx, cy, flags ))) return FALSE;
+    return EndDeferWindowPos( hdwp );
 }