Release 970120

Sun Jan 19 11:46:48 1997  Alexandre Julliard  <julliard@lrc.epfl.ch>

	* [loader/module.c]
	Fixed LoadModule() to always call the DLL initialization code.

	* [windows/event.c]
	Moved all the keyboard stuff to windows/keyboard.c

	* [tools/build.c]
	Fixed Win32 register functions.

Sat Jan 18 22:24:41 1997  David Makepeace  <D.Makepeace@mailbox.uq.oz.au>

        * [tools/makedep.c]
        Fixed bug which causes SEGV on Solaris x86.

Fri Jan 17 18:32:27 1997  Frans van Dorsselaer <dorssel@rulhmpc49.LeidenUniv.nl>

	* [controls/edit.c]
	Implemented WM_UNDO, WM_CONTEXTMENU (temporary using WM_RBUTTONUP),
	WM_COMMAND, WM_INITPOPUPMENU, WM_SYSKEYDOWN.
	Fixed EM_SETSEL and some minor bugs (features).
	Hence: fully functional undo and a win95 menu with the right mouse
		button.

	* [include/resources.h] [resources/TODO] [resources/sysres_??.rc]
	Added a context menu for the edit control.
	Translations, please ...

Fri Jan	17 08:29:52 1997  David Faure <david.faure@ifhamy.insa-lyon.fr>

	* [windows/event.c]
	Move EVENT_ToAscii to windows/keyboard.c (where name ToAscii)
	Fixed Keypad keys 0-9 and . in EVENT_event_to_vkey.
	Added 3-state handling of toggle keys (CapsLock, NumLock) in order
	to make them work with any X server.
	Toggle keys now generate WM_KEYDOWN and WM_KEYUP on each pressing.

	* [include/keyboard.h]
	Totally replaced the file (formerly containing the vkcase definitions)
	by the declaration of 'extern' variables contained by event.c and used
	by keyboard.c
	
	* [windows/keyboard.c]
	Started to rewrite VkKeyScan and MapVirtualKey, to make them use the 
	table keyc2vkey or X functions only.
	ToAscii : added keypad 0-9 and . special case.
	Changed toggle keys active mask from 0x80 to 0x1.

	* [misc/keyboard.c]
	File deleted. Contents moved to windows/keyboard.c.

	* [misc/main.c]
	Added putenv XKB_DISABLE to disable XKB extension (which, when
	present, causes AltGr to change keyboard group instead of being a
	modifier).

Tue Jan 14 22:56:43 1997  Philippe De Muyter  <phdm@info.ucl.ac.be>

	* [windows/event.c]
	Do not assume NumLockMask is Mod2Mask, but compute it by scanning
	output of XGetModifierMapping for XK_Num_Lock.

Tue Jan 14 15:49:49 1997  Marcus Meissner <msmeissn@cip.informatik.uni-erlangen.de>

	* [loader/pe_*.c] [include/peexe.h] [include/resource32.h]
	  [debugger/*.c]
	General clean up.
	Changed defines/structures to match Windows NT SDK.

	* [loader/main.c]
	Don't crash on empty command-line.

	* [windows/winpos.c]
	winpos.c made win32 clean.

	* [misc/ntdll.c]
	Some string conversion additions.

	* [files/file.c]
	GetFileAttributes/GetTempFileName fixed.

	* [misc/ver.c]
	VerInstallFile implemented.

Mon Jan 13 15:03:11 1997  Philippe De Muyter  <phdm@info.ucl.ac.be>

	* [tools/build.c]: Use PREFIX also in stabs messages.

Mon Jan 13 10:40:33 1997  John Harvey <john@division.co.uk>

	* [graphics/win16drv/*] [include/win16drv.h]
	Many fixes and some new features.

	* [graphics/x11drv/font.c] [graphics/x11drv/init.c]
	  [include/x11drv.h] [objects/font.c]
	GetTextMetrics() moved to graphics driver.

	* [if1632/gdi.spec] [misc/fontengine.c] [misc/Makefile.in]
	New dummy EngineEnumerateFont, EngineRealizeFont functions.

	* [include/windows.h]
	TEXTFORM16 and FONTINFO16 structure definitions moved here from
	include/win16drv.h
diff --git a/ANNOUNCE b/ANNOUNCE
index 669aa02..50c7bc3 100644
--- a/ANNOUNCE
+++ b/ANNOUNCE
@@ -1,15 +1,15 @@
-This is release 970112 of Wine, the MS Windows emulator.  This is still a
+This is release 970120 of Wine, the MS Windows emulator.  This is still a
 developer's only release.  There are many bugs and many unimplemented API
 features.  Most applications still do not work correctly.
 
 Patches should be submitted to "julliard@lrc.epfl.ch".  Please don't
 forget to include a ChangeLog entry.
 
-WHAT'S NEW with Wine-970112: (see ChangeLog for details)
-	- Better support for non-US keyboards.
-	- Support for VFAT filesystem short names.
-	- Many improvements to the built-in debugger.
-	- More Win32 stuff.
+WHAT'S NEW with Wine-970120: (see ChangeLog for details)
+	- More keyboard improvements.
+	- Some new printer driver functions.
+	- Many fixes to Win32 loader.
+	- Better edit control.
 	- Lots of bug fixes.
 
 See the README file in the distribution for installation instructions.
@@ -18,10 +18,10 @@
 the release is available at the ftp sites.  The sources will be available
 from the following locations:
 
-  ftp://sunsite.unc.edu/pub/Linux/ALPHA/wine/development/Wine-970112.tar.gz
-  ftp://tsx-11.mit.edu/pub/linux/ALPHA/Wine/development/Wine-970112.tar.gz
-  ftp://ftp.infomagic.com/pub/mirrors/linux/wine/development/Wine-970112.tar.gz
-  ftp://aris.com/pub/linux/ALPHA/Wine/development/Wine-970112.tar.gz
+  ftp://sunsite.unc.edu/pub/Linux/ALPHA/wine/development/Wine-970120.tar.gz
+  ftp://tsx-11.mit.edu/pub/linux/ALPHA/Wine/development/Wine-970120.tar.gz
+  ftp://ftp.infomagic.com/pub/mirrors/linux/wine/development/Wine-970120.tar.gz
+  ftp://aris.com/pub/linux/ALPHA/Wine/development/Wine-970120.tar.gz
 
 It should also be available from any site that mirrors tsx-11 or sunsite.
 
diff --git a/ChangeLog b/ChangeLog
index bf0c55d..27134ae 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,4 +1,110 @@
 ----------------------------------------------------------------------
+Sun Jan 19 11:46:48 1997  Alexandre Julliard  <julliard@lrc.epfl.ch>
+
+	* [loader/module.c]
+	Fixed LoadModule() to always call the DLL initialization code.
+
+	* [windows/event.c]
+	Moved all the keyboard stuff to windows/keyboard.c
+
+	* [tools/build.c]
+	Fixed Win32 register functions.
+
+Sat Jan 18 22:24:41 1997  David Makepeace  <D.Makepeace@mailbox.uq.oz.au>
+
+        * [tools/makedep.c]
+        Fixed bug which causes SEGV on Solaris x86.
+
+Fri Jan 17 18:32:27 1997  Frans van Dorsselaer <dorssel@rulhmpc49.LeidenUniv.nl>
+
+	* [controls/edit.c]
+	Implemented WM_UNDO, WM_CONTEXTMENU (temporary using WM_RBUTTONUP),
+	WM_COMMAND, WM_INITPOPUPMENU, WM_SYSKEYDOWN.
+	Fixed EM_SETSEL and some minor bugs (features).
+	Hence: fully functional undo and a win95 menu with the right mouse
+		button.
+
+	* [include/resources.h] [resources/TODO] [resources/sysres_??.rc]
+	Added a context menu for the edit control.
+	Translations, please ...
+
+Fri Jan	17 08:29:52 1997  David Faure <david.faure@ifhamy.insa-lyon.fr>
+
+	* [windows/event.c]
+	Move EVENT_ToAscii to windows/keyboard.c (where name ToAscii)
+	Fixed Keypad keys 0-9 and . in EVENT_event_to_vkey.
+	Added 3-state handling of toggle keys (CapsLock, NumLock) in order
+	to make them work with any X server.
+	Toggle keys now generate WM_KEYDOWN and WM_KEYUP on each pressing.
+
+	* [include/keyboard.h]
+	Totally replaced the file (formerly containing the vkcase definitions)
+	by the declaration of 'extern' variables contained by event.c and used
+	by keyboard.c
+	
+	* [windows/keyboard.c]
+	Started to rewrite VkKeyScan and MapVirtualKey, to make them use the 
+	table keyc2vkey or X functions only.
+	ToAscii : added keypad 0-9 and . special case.
+	Changed toggle keys active mask from 0x80 to 0x1.
+
+	* [misc/keyboard.c]
+	File deleted. Contents moved to windows/keyboard.c.
+
+	* [misc/main.c]
+	Added putenv XKB_DISABLE to disable XKB extension (which, when
+	present, causes AltGr to change keyboard group instead of being a
+	modifier).
+
+Tue Jan 14 22:56:43 1997  Philippe De Muyter  <phdm@info.ucl.ac.be>
+
+	* [windows/event.c]
+	Do not assume NumLockMask is Mod2Mask, but compute it by scanning
+	output of XGetModifierMapping for XK_Num_Lock.
+
+Tue Jan 14 15:49:49 1997  Marcus Meissner <msmeissn@cip.informatik.uni-erlangen.de>
+
+	* [loader/pe_*.c] [include/peexe.h] [include/resource32.h]
+	  [debugger/*.c]
+	General clean up.
+	Changed defines/structures to match Windows NT SDK.
+
+	* [loader/main.c]
+	Don't crash on empty command-line.
+
+	* [windows/winpos.c]
+	winpos.c made win32 clean.
+
+	* [misc/ntdll.c]
+	Some string conversion additions.
+
+	* [files/file.c]
+	GetFileAttributes/GetTempFileName fixed.
+
+	* [misc/ver.c]
+	VerInstallFile implemented.
+
+Mon Jan 13 15:03:11 1997  Philippe De Muyter  <phdm@info.ucl.ac.be>
+
+	* [tools/build.c]: Use PREFIX also in stabs messages.
+
+Mon Jan 13 10:40:33 1997  John Harvey <john@division.co.uk>
+
+	* [graphics/win16drv/*] [include/win16drv.h]
+	Many fixes and some new features.
+
+	* [graphics/x11drv/font.c] [graphics/x11drv/init.c]
+	  [include/x11drv.h] [objects/font.c]
+	GetTextMetrics() moved to graphics driver.
+
+	* [if1632/gdi.spec] [misc/fontengine.c] [misc/Makefile.in]
+	New dummy EngineEnumerateFont, EngineRealizeFont functions.
+
+	* [include/windows.h]
+	TEXTFORM16 and FONTINFO16 structure definitions moved here from
+	include/win16drv.h
+
+----------------------------------------------------------------------
 Sat Jan 11 18:17:59 1997  Alexandre Julliard  <julliard@lrc.epfl.ch>
 
 	* [controls/menu.c]
diff --git a/controls/combo.c b/controls/combo.c
index dacc760..7259aec 100644
--- a/controls/combo.c
+++ b/controls/combo.c
@@ -159,7 +159,7 @@
      lphc->RectButton = rect;
      lphc->RectButton.left = lphc->RectButton.right - 6 - CBitWidth;
      lphc->RectButton.bottom = lphc->RectButton.top + lphl->StdItemHeight;
-     SetWindowPos(hwnd, 0, 0, 0, rect.right -rect.left + 2*SYSMETRICS_CXBORDER,
+     SetWindowPos32(hwnd, 0, 0, 0, rect.right -rect.left + 2*SYSMETRICS_CXBORDER,
 		 lphl->StdItemHeight + 2*SYSMETRICS_CYBORDER,
 		 SWP_NOMOVE | SWP_NOZORDER | SWP_NOSENDCHANGING | SWP_NOACTIVATE);
      dprintf_combo(stddeb,(cstyle & 3)==CBS_DROPDOWN ? "CBS_DROPDOWN\n": "CBS_DROPDOWNLIST\n");
@@ -209,8 +209,8 @@
 {
   LPHEADCOMBO lphc = ComboGetStorageHeader(hwnd);
 
-  if (lphc->hWndEdit) DestroyWindow( lphc->hWndEdit );
-  if (lphc->hWndLBox) DestroyWindow( lphc->hWndLBox );
+  if (lphc->hWndEdit) DestroyWindow32( lphc->hWndEdit );
+  if (lphc->hWndLBox) DestroyWindow32( lphc->hWndLBox );
   return 0;
 }
 
@@ -248,7 +248,7 @@
 		     lphc->RectButton.left + 2,lphc->RectButton.top + 2,
 		     0, 0, CBitWidth, CBitHeight );
   }
-  if (!IsWindowVisible(hwnd) || !lphl->bRedrawFlag 
+  if (!IsWindowVisible16(hwnd) || !lphl->bRedrawFlag 
       || (lphc->dwStyle & 3) != CBS_DROPDOWNLIST) 
   {
     /* we don't want to draw an entry when there is an edit control */
@@ -616,7 +616,7 @@
   if (wParam != lphc->DropDownVisible) {
     lphc->DropDownVisible = wParam;
     GetWindowRect32(hwnd,&rect);
-    SetWindowPos(lphc->hWndLBox, 0, rect.left, rect.top+lphc->LBoxTop, 0, 0,
+    SetWindowPos32(lphc->hWndLBox, 0, rect.left, rect.top+lphc->LBoxTop, 0, 0,
 		 SWP_NOSIZE | SWP_NOACTIVATE |
                  (wParam ? SWP_SHOWWINDOW : SWP_HIDEWINDOW));
     if (!wParam) SetFocus32(hwnd);
@@ -648,7 +648,7 @@
 
   if ((cRect.bottom - cRect.top) >
       (lphl->StdItemHeight + 2*SYSMETRICS_CYBORDER)) {
-    SetWindowPos(hwnd, 0, 0, 0, 
+    SetWindowPos32(hwnd, 0, 0, 0, 
 		 cRect.right-cRect.left,
 		 lphl->StdItemHeight+2*SYSMETRICS_CYBORDER, 
 		 SWP_NOMOVE | SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE );
@@ -673,12 +673,12 @@
     }
     /* otherwise we need to make the client include the button */
     else
-      SetWindowPos(hwnd, 0, 0, 0, lphc->RectButton.right,
+      SetWindowPos32(hwnd, 0, 0, 0, lphc->RectButton.right,
 		   lphl->StdItemHeight+2*SYSMETRICS_CYBORDER,
 		   SWP_NOMOVE | SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE);
 
       if ((lphc->dwStyle & 3) != CBS_DROPDOWNLIST)
-        SetWindowPos(lphc->hWndEdit, 0, 0, 0, lphc->RectButton.left,
+        SetWindowPos32(lphc->hWndEdit, 0, 0, 0, lphc->RectButton.left,
 		     lphl->StdItemHeight,
 		     SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER );
   }
@@ -934,7 +934,7 @@
   top = 0;
   hdc = BeginPaint16( hwnd, &ps );
 
-  if (!IsWindowVisible(hwnd) || !lphl->bRedrawFlag) {
+  if (!IsWindowVisible16(hwnd) || !lphl->bRedrawFlag) {
     EndPaint16(hwnd, &ps);
     return 0;
   }
@@ -1202,7 +1202,7 @@
   if ((lRect.bottom-lRect.top < 3*lphl->StdItemHeight) || dw) {
     dprintf_combo(stddeb,"    Changing; totHeight %d  StdItemHght %d  dw %d\n",
 		  totheight,lphl->StdItemHeight,dw);
-    SetWindowPos(hWndLBox, 0, lRect.left, lRect.top, 
+    SetWindowPos32(hWndLBox, 0, lRect.left, lRect.top, 
 		 lwRect.right-lwRect.left+dw, totheight+2*SYSMETRICS_CYBORDER, 
 		 SWP_NOMOVE | SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE );
   }
diff --git a/controls/edit.c b/controls/edit.c
index e53103e..c8b241d 100644
--- a/controls/edit.c
+++ b/controls/edit.c
@@ -21,6 +21,7 @@
 #include "windows.h"
 #include "win.h"
 #include "local.h"
+#include "resource.h"
 #include "stddebug.h"
 #include "debug.h"
 #include "xmalloc.h"
@@ -88,7 +89,11 @@
 	INT32 BufLimit;
 	INT32 BufSize;
 	BOOL32 TextChanged;
-	BOOL32 CanUndo;
+	INT32 UndoInsertLen;
+	INT32 UndoPos;
+	INT32 UndoBufSize;
+	HLOCAL32 hUndoBuf;
+	LPSTR UndoText;
 	BOOL32 Redraw;
 	INT32 SelStart;		/* offset of selection start, == SelEnd if no selection */
 	INT32 SelEnd;		/* offset of selection end == current caret position */
@@ -135,7 +140,7 @@
 		    (LPARAM)(wndPtr)->hwndSelf ))
 #define DPRINTF_EDIT_MSG16(str) \
     dprintf_edit(stddeb, \
-		 "edit: 16 bit : " str ": hwnd=%08x, wParam=%08x, lParam=%08x\n  ", \
+		 "edit: 16 bit : " str ": hwnd=%08x, wParam=%08x, lParam=%08x\n", \
 		 (UINT32)hwnd, (UINT32)wParam, (UINT32)lParam)
 #define DPRINTF_EDIT_MSG32(str) \
     dprintf_edit(stddeb, \
@@ -166,12 +171,14 @@
 static BOOL32  EDIT_GetRedraw(WND *wndPtr);
 static void    EDIT_GetSel(WND *wndPtr, LPINT32 s, LPINT32 e);
 static INT32   EDIT_GetTextWidth(WND *wndPtr);
+static LPSTR   EDIT_GetUndoPointer(WND *wndPtr);
 static INT32   EDIT_GetVisibleLineCount(WND *wndPtr);
 static INT32   EDIT_GetWndWidth(WND *wndPtr);
 static INT32   EDIT_GetXOffset(WND *wndPtr);
 static void    EDIT_InvalidateText(WND *wndPtr, INT32 start, INT32 end);
 static INT32   EDIT_LineFromWndY(WND *wndPtr, INT32 y);
 static BOOL32  EDIT_MakeFit(WND *wndPtr, INT32 size);
+static BOOL32  EDIT_MakeUndoFit(WND *wndPtr, INT32 size);
 static void    EDIT_MoveBackward(WND *wndPtr, BOOL32 extend);
 static void    EDIT_MoveDownward(WND *wndPtr, BOOL32 extend);
 static void    EDIT_MoveEnd(WND *wndPtr, BOOL32 extend);
@@ -185,6 +192,8 @@
 static void    EDIT_PaintLine(WND *wndPtr, HDC32 hdc, INT32 line, BOOL32 rev);
 static INT32   EDIT_PaintText(WND *wndPtr, HDC32 hdc, INT32 x, INT32 y, INT32 line, INT32 col, INT32 count, BOOL32 rev);
 static void    EDIT_ReleasePointer(WND *wndPtr);
+static void    EDIT_ReleaseUndoPointer(WND *wndPtr);
+static void    EDIT_SetSel(WND *wndPtr, INT32 ns, INT32 ne);
 static INT32   EDIT_WndXFromCol(WND *wndPtr, INT32 line, INT32 col);
 static INT32   EDIT_WndYFromLine(WND *wndPtr, INT32 line);
 static INT32   EDIT_WordBreakProc(LPSTR s, INT32 index, INT32 count, INT32 action);
@@ -233,6 +242,8 @@
 
 static LRESULT EDIT_WM_Char(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 static LRESULT EDIT_WM_Clear(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
+static LRESULT EDIT_WM_Command(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
+static LRESULT EDIT_WM_ContextMenu(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 static LRESULT EDIT_WM_Copy(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 static LRESULT EDIT_WM_Cut(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 static LRESULT EDIT_WM_Create(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
@@ -244,6 +255,7 @@
 static LRESULT EDIT_WM_GetText(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 static LRESULT EDIT_WM_GetTextLength(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 static LRESULT EDIT_WM_HScroll(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
+static LRESULT EDIT_WM_InitMenuPopup(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 static LRESULT EDIT_WM_KeyDown(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 static LRESULT EDIT_WM_KillFocus(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 static LRESULT EDIT_WM_LButtonDblClk(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
@@ -258,6 +270,8 @@
 static LRESULT EDIT_WM_SetRedraw(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 static LRESULT EDIT_WM_SetText(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 static LRESULT EDIT_WM_Size(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
+static LRESULT EDIT_WM_SysKeyDown(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
+static LRESULT EDIT_WM_Timer(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 static LRESULT EDIT_WM_VScroll(WND *wndPtr, WPARAM32 wParam, LPARAM lParam);
 
 
@@ -648,6 +662,23 @@
 		lResult = EDIT_WM_Clear(wndPtr, wParam, lParam);
 		break;
 
+	case WM_COMMAND:
+		DPRINTF_EDIT_MSG32("WM_COMMAND");
+		lResult = EDIT_WM_Command(wndPtr, wParam, lParam);
+		break;
+
+/*
+ *	FIXME: when this one is added to WINE, change RBUTTONUP to CONTEXTMENU
+ *	Furthermore, coordinate conversion should no longer be required
+ *
+ *	case WM_CONTEXTMENU:
+ */
+ 	case WM_RBUTTONUP:
+		DPRINTF_EDIT_MSG32("WM_RBUTTONUP");
+		ClientToScreen16(wndPtr->hwndSelf, (LPPOINT16)&lParam);
+		lResult = EDIT_WM_ContextMenu(wndPtr, wParam, lParam);
+		break;
+
 	case WM_COPY:
 		DPRINTF_EDIT_MSG32("WM_COPY");
 		lResult = EDIT_WM_Copy(wndPtr, wParam, lParam);
@@ -698,6 +729,11 @@
 		lResult = EDIT_WM_HScroll(wndPtr, wParam, lParam);
 		break;
 
+	case WM_INITMENUPOPUP:
+		DPRINTF_EDIT_MSG32("WM_INITMENUPOPUP");
+		lResult = EDIT_WM_InitMenuPopup(wndPtr, wParam, lParam);
+		break;
+
 	case WM_KEYDOWN:
 		DPRINTF_EDIT_MSG32("WM_KEYDOWN");
 		lResult = EDIT_WM_KeyDown(wndPtr, wParam, lParam);
@@ -772,6 +808,16 @@
 		lResult = EDIT_WM_Size(wndPtr, wParam, lParam);
 		break;
 
+	case WM_SYSKEYDOWN:
+		DPRINTF_EDIT_MSG32("WM_SYSKEYDOWN");
+		lResult = EDIT_WM_SysKeyDown(wndPtr, wParam, lParam);
+		break;
+
+	case WM_TIMER:
+		DPRINTF_EDIT_MSG32("WM_TIMER");
+		lResult = EDIT_WM_Timer(wndPtr, wParam, lParam);
+		break;
+
 	case WM_VSCROLL:
 		DPRINTF_EDIT_MSG32("WM_VSCROLL");
 		lResult = EDIT_WM_VScroll(wndPtr, wParam, lParam);
@@ -1105,7 +1151,8 @@
  *	EDIT_GetSel
  *
  *	Beware: This is not the function called on EM_GETSEL.
- *	(because s can be greater than e).
+ *		This is the unordered version used internally
+ *		(s can be > e).  No return value either.
  *
  */
 static void EDIT_GetSel(WND *wndPtr, LPINT32 s, LPINT32 e)
@@ -1134,6 +1181,24 @@
 
 /*********************************************************************
  *
+ *	EDIT_GetUndoPointer
+ *
+ *	This acts as a LocalLock32(), but it locks only once.  This way
+ *	you can call it whenever you like, without unlocking.
+ *
+ */
+static LPSTR EDIT_GetUndoPointer(WND *wndPtr)
+{
+	EDITSTATE *es = EDITSTATEPTR(wndPtr);
+
+	if (!es->UndoText && es->hUndoBuf)
+		es->UndoText = (LPSTR)LocalLock32(es->hUndoBuf);
+	return es->UndoText;
+}
+
+
+/*********************************************************************
+ *
  *	EDIT_GetVisibleLineCount
  *
  */
@@ -1197,7 +1262,7 @@
 	RECT32 rcUpdate;
 	INT32 l;
 
-	if (end == start )
+	if (end == start)
 		return;
 
 	if (end == -1)
@@ -1278,8 +1343,11 @@
 
 	if (size <= es->BufSize)
 		return TRUE;
-	if (size > es->BufLimit)
+	if (size > es->BufLimit) {
+		dprintf_edit(stddeb, "edit: notification EN_MAXTEXT sent\n");
+		EDIT_NOTIFY_PARENT(wndPtr, EN_MAXTEXT);
 		return FALSE;
+	}
 	size = ((size / GROWLENGTH) + 1) * GROWLENGTH;
 	if (size > es->BufLimit)
 		size = es->BufLimit;
@@ -1294,6 +1362,8 @@
 			es->BufSize = MIN(LocalSize32(es->hBuf32) - 1, es->BufLimit);
 			if (es->BufSize < size) {
 				dprintf_edit(stddeb, "edit: EDIT_MakeFit: FAILED !  We now have %d+1\n", es->BufSize);
+				dprintf_edit(stddeb, "edit: notification EN_ERRSPACE sent\n");
+				EDIT_NOTIFY_PARENT(wndPtr, EN_ERRSPACE);
 				return FALSE;
 			}
 			dprintf_edit(stddeb, "edit: EDIT_MakeFit: We now have %d+1\n", es->BufSize);
@@ -1306,12 +1376,51 @@
 			es->BufSize = MIN(LOCAL_Size(wndPtr->hInstance, es->hBuf16) - 1, es->BufLimit);
 			if (es->BufSize < size) {
 				dprintf_edit(stddeb, "edit: EDIT_MakeFit: FAILED !  We now have %d+1\n", es->BufSize);
+				dprintf_edit(stddeb, "edit: notification EN_ERRSPACE sent\n");
+				EDIT_NOTIFY_PARENT(wndPtr, EN_ERRSPACE);
 				return FALSE;
 			}
 			dprintf_edit(stddeb, "edit: EDIT_MakeFit: We now have %d+1\n", es->BufSize);
 			return TRUE;
 		}
 	}
+	dprintf_edit(stddeb, "edit: EDIT_MakeFit: Reallocation failed\n");
+	dprintf_edit(stddeb, "edit: notification EN_ERRSPACE sent\n");
+	EDIT_NOTIFY_PARENT(wndPtr, EN_ERRSPACE);
+	return FALSE;
+}
+
+
+/*********************************************************************
+ *
+ *	EDIT_MakeUndoFit
+ *
+ *	Try to fit size + 1 bytes in the undo buffer.
+ *
+ */
+static BOOL32 EDIT_MakeUndoFit(WND *wndPtr, INT32 size)
+{
+	EDITSTATE *es = EDITSTATEPTR(wndPtr);
+	HLOCAL32 hNew;
+
+	if (size <= es->UndoBufSize)
+		return TRUE;
+	size = ((size / GROWLENGTH) + 1) * GROWLENGTH;
+
+	dprintf_edit(stddeb, "edit: EDIT_MakeUndoFit: trying to ReAlloc to %d+1\n", size);
+
+	EDIT_ReleaseUndoPointer(wndPtr);
+	if ((hNew = LocalReAlloc32(es->hUndoBuf, size + 1, 0))) {
+		dprintf_edit(stddeb, "edit: EDIT_MakeUndoFit: Old handle %08x, new handle %08x\n", es->hUndoBuf, hNew);
+		es->hUndoBuf = hNew;
+		es->UndoBufSize = LocalSize32(es->hUndoBuf) - 1;
+		if (es->UndoBufSize < size) {
+			dprintf_edit(stddeb, "edit: EDIT_MakeUndoFit: FAILED !  We now have %d+1\n", es->UndoBufSize);
+			return FALSE;
+		}
+		dprintf_edit(stddeb, "edit: EDIT_MakeUndoFit: We now have %d+1\n", es->UndoBufSize);
+		return TRUE;
+	}
 	return FALSE;
 }
 
@@ -1340,7 +1449,7 @@
 		e--;
 	if (!extend)
 		s = e;
-	EDIT_EM_SetSel(wndPtr, s, e);
+	EDIT_SetSel(wndPtr, s, e);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
 }
 
@@ -1371,7 +1480,7 @@
 	}
 	if (!extend)
 		s = e;
-	EDIT_EM_SetSel(wndPtr, s, e);
+	EDIT_SetSel(wndPtr, s, e);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
 }
 
@@ -1396,7 +1505,7 @@
 	e = li + ll;
 	if (!extend)
 		s = e;
-	EDIT_EM_SetSel(wndPtr, s, e);
+	EDIT_SetSel(wndPtr, s, e);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
 }
 
@@ -1427,7 +1536,7 @@
 		e++;
 	if (!extend)
 		s = e;
-	EDIT_EM_SetSel(wndPtr, s, e);
+	EDIT_SetSel(wndPtr, s, e);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
 }
 
@@ -1452,7 +1561,7 @@
 	e = li;
 	if (!extend)
 		s = e;
-	EDIT_EM_SetSel(wndPtr, s, e);
+	EDIT_SetSel(wndPtr, s, e);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
 }
 
@@ -1483,7 +1592,7 @@
 	}
 	if (!extend)
 		s = e;
-	EDIT_EM_SetSel(wndPtr, s, e);
+	EDIT_SetSel(wndPtr, s, e);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
 }
 
@@ -1512,7 +1621,7 @@
 	}
 	if (!extend)
 		s = e;
-	EDIT_EM_SetSel(wndPtr, s, e);
+	EDIT_SetSel(wndPtr, s, e);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
 }
 
@@ -1541,7 +1650,7 @@
 	}
 	if (!extend)
 		s = e;
-	EDIT_EM_SetSel(wndPtr, s, e);
+	EDIT_SetSel(wndPtr, s, e);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
 }
 
@@ -1576,7 +1685,7 @@
 	}
 	if (!extend)
 		s = e;
-	EDIT_EM_SetSel(wndPtr, s, e);
+	EDIT_SetSel(wndPtr, s, e);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
 }
 
@@ -1611,7 +1720,7 @@
 	}
 	if (!extend)
 		s = e;
-	EDIT_EM_SetSel(wndPtr, s, e);
+	EDIT_SetSel(wndPtr, s, e);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
 }
 
@@ -1708,19 +1817,77 @@
 
 	if (!es)
 		return;
-	if (es->text && (es->hBuf32 || es->hBuf16))
-        {
+	if (es->text && (es->hBuf32 || es->hBuf16)) {
 		if (es->hBuf32)
 			LocalUnlock32(es->hBuf32);
 		else
 			LOCAL_Unlock(wndPtr->hInstance, es->hBuf16);
-        }
+	}
 	es->text = NULL;
 }
 
 
 /*********************************************************************
  *
+ *	EDIT_ReleaseUndoPointer
+ *
+ *	This is the only helper function that can be called with es = NULL.
+ *	It is called at the end of EditWndProc() to unlock the buffer.
+ *
+ */
+static void EDIT_ReleaseUndoPointer(WND *wndPtr)
+{
+	EDITSTATE *es = EDITSTATEPTR(wndPtr);
+
+	if (!es)
+		return;
+	if (es->UndoText && es->hUndoBuf)
+		LocalUnlock32(es->hUndoBuf);
+	es->UndoText = NULL;
+}
+
+
+/*********************************************************************
+ *
+ *	EDIT_SetSel
+ *
+ *	Beware: This is not the function called on EM_SETSEL.
+ *		This is the unordered version used internally
+ *		(s can be > e).  Doesn't accept -1 parameters either.
+ *		No range checking.
+ *
+ */
+static void EDIT_SetSel(WND *wndPtr, INT32 ns, INT32 ne)
+{
+	EDITSTATE *es = EDITSTATEPTR(wndPtr);
+	LRESULT pos;
+	INT32 s;
+	INT32 e;
+
+	EDIT_EM_GetSel(wndPtr, (WPARAM32)&s, (LPARAM)&e);
+	es->SelStart = ns;
+	es->SelEnd = ne;
+	if (EDIT_GetRedraw(wndPtr)) {
+		if (wndPtr->hwndSelf == GetFocus32()) {
+			pos = EDIT_EM_PosFromChar(wndPtr, ne, 0);
+			SetCaretPos((INT16)LOWORD(pos), (INT16)HIWORD(pos));
+		}
+		ORDER_INT32(s, ns);
+		ORDER_INT32(s, ne);
+		ORDER_INT32(e, ns);
+		ORDER_INT32(e, ne);
+		ORDER_INT32(ns, ne);
+		if (e != ns) {
+			EDIT_InvalidateText(wndPtr, s, e);
+			EDIT_InvalidateText(wndPtr, ns, ne);
+		} else
+			EDIT_InvalidateText(wndPtr, s, ne);
+	}
+}
+
+
+/*********************************************************************
+ *
  *	EDIT_WndXFromCol
  *
  *	Calculates, for a given line and column, the X-coordinate on the screen.
@@ -1845,7 +2012,7 @@
 {
 	EDITSTATE *es = EDITSTATEPTR(wndPtr);
 
-	return (LRESULT)es->CanUndo;
+	return (LRESULT)(es->UndoInsertLen || lstrlen32A(EDIT_GetUndoPointer(wndPtr)));
 }
 
 
@@ -1887,7 +2054,8 @@
 {
 	EDITSTATE *es = EDITSTATEPTR(wndPtr);
 
-	es->CanUndo = FALSE;
+	es->UndoInsertLen = 0;
+	*EDIT_GetUndoPointer(wndPtr) = '\0';
 	return 0;
 }
 
@@ -2277,7 +2445,6 @@
 	INT32 tw = EDIT_GetTextWidth(wndPtr);
 	INT32 dx;
 	INT32 dy;
-	POINT32 pos;
 
 	if (nfv >= lc)
 		nfv = lc - 1;
@@ -2287,8 +2454,6 @@
 	dx = xoff - nxoff;
 	dy = EDIT_WndYFromLine(wndPtr, fv) - EDIT_WndYFromLine(wndPtr, nfv);
 	if (dx || dy) {
-		if (wndPtr->hwndSelf == GetFocus32())
-			HideCaret(wndPtr->hwndSelf);
 		if (EDIT_GetRedraw(wndPtr))
 			ScrollWindow32(wndPtr->hwndSelf, dx, dy, NULL, NULL);
 		es->FirstVisibleLine = nfv;
@@ -2299,11 +2464,6 @@
 		if (IsHScrollBar(wndPtr))
 			SetScrollPos32(wndPtr->hwndSelf, SB_HORZ,
 				EDIT_WM_HScroll(wndPtr, EM_GETTHUMB16, 0), TRUE);
-		if (wndPtr->hwndSelf == GetFocus32()) {
-			GetCaretPos32(&pos);
-			SetCaretPos(pos.x + dx, pos.y + dy);
-			ShowCaret(wndPtr->hwndSelf);
-		}
 	}
 	if (IsMultiLine(wndPtr))
 		return TRUE;
@@ -2335,46 +2495,101 @@
  *
  *	EM_REPLACESEL
  *
- *	FIXME: wParam indicates whether we should maintain an undo buffer
- *	for this operation.
- *
  */
 static LRESULT EDIT_EM_ReplaceSel(WND *wndPtr, WPARAM32 wParam, LPARAM lParam)
 {
+	EDITSTATE *es = EDITSTATEPTR(wndPtr);
 	LPCSTR str = (LPCSTR)lParam;
 	INT32 strl = lstrlen32A(str);
 	INT32 tl = (INT32)EDIT_WM_GetTextLength(wndPtr, 0, 0);
+	INT32 utl;
 	INT32 s;
 	INT32 e;
 	INT32 i;
 	LPSTR p;
 	LPSTR text;
+	LPSTR utext;
 	BOOL32 redraw;
 
-	EDIT_GetSel(wndPtr, &s, &e);
-	ORDER_INT32(s,e);
-	if (!EDIT_MakeFit(wndPtr, tl - (e - s) + strl)) {
-		dprintf_edit(stddeb, "edit: notification EN_MAXTEXT sent\n");
-		EDIT_NOTIFY_PARENT(wndPtr, EN_MAXTEXT);
+	EDIT_EM_GetSel(wndPtr, (WPARAM32)&s, (LPARAM)&e);
+
+	if ((s == e) && !strl)
 		return 0;
+
+	if (!EDIT_MakeFit(wndPtr, tl - (e - s) + strl))
+		return 0;
+
+	text = EDIT_GetPointer(wndPtr);
+	utext = EDIT_GetUndoPointer(wndPtr);
+	if (e != s) {
+		/* there is something to be deleted */
+		if ((BOOL32)wParam) {
+			/* we have to be able to undo */
+			utl = lstrlen32A(utext);
+			if (!es->UndoInsertLen && (*utext && (s == es->UndoPos))) {
+				/* undo-buffer is extended to the right */
+				EDIT_MakeUndoFit(wndPtr, utl + e - s);
+				lstrcpyn32A(utext + utl, text + s, e - s + 1);
+			} else if (!es->UndoInsertLen && (*utext && (e == es->UndoPos))) {
+				/* undo-buffer is extended to the left */
+				EDIT_MakeUndoFit(wndPtr, utl + e - s);
+				for (p = utext + utl ; p >= utext ; p--)
+					p[e - s] = p[0];
+				for (i = 0 , p = utext ; i < e - s ; i++)
+					p[i] = (text + s)[i];
+				es->UndoPos = s;
+			} else {
+				/* new undo-buffer */
+				EDIT_MakeUndoFit(wndPtr, e - s);
+				lstrcpyn32A(utext, text + s, e - s + 1);
+				es->UndoPos = s;
+			}
+			/* any deletion makes the old insertion-undo invalid */
+			es->UndoInsertLen = 0;
+		} else
+			EDIT_EM_EmptyUndoBuffer(wndPtr, 0, 0);
+
+		/* now delete */
+		lstrcpy32A(text + s, text + e);
+	}
+	if (strl) {
+		/* there is an insertion */
+		if ((BOOL32)wParam) {
+			/* we have to be able to undo */
+			if ((s == es->UndoPos) ||
+					((es->UndoInsertLen) &&
+					(s == es->UndoPos + es->UndoInsertLen)))
+				/*
+				 * insertion is new and at delete position or
+				 * an extension to either left or right
+				 */
+				es->UndoInsertLen += strl;
+			else {
+				/* new insertion undo */
+				es->UndoPos = s;
+				es->UndoInsertLen = strl;
+				/* new insertion makes old delete-buffer invalid */
+				*utext = '\0';
+			}
+		} else
+			EDIT_EM_EmptyUndoBuffer(wndPtr, 0, 0);
+
+		/* now insert */
+		tl = lstrlen32A(text);
+		for (p = text + tl ; p >= text + s ; p--)
+			p[strl] = p[0];
+		for (i = 0 , p = text + s ; i < strl ; i++)
+			p[i] = str[i];
+		if(IsUpper(wndPtr))
+			CharUpperBuff32A(p, strl);
+		else if(IsLower(wndPtr))
+			CharLowerBuff32A(p, strl);
+		s += strl;
 	}
 	redraw = EDIT_GetRedraw(wndPtr);
 	EDIT_WM_SetRedraw(wndPtr, FALSE, 0);
-	EDIT_WM_Clear(wndPtr, 0, 0);
-	tl = EDIT_WM_GetTextLength(wndPtr, 0, 0);
-	EDIT_GetSel(wndPtr, NULL, &e);
-	text = EDIT_GetPointer(wndPtr);
-	for (p = text + tl ; p >= text + e ; p--)
-		p[strl] = p[0];
-	for (i = 0 , p = text + e ; i < strl ; i++)
-		p[i] = str[i];
-	if(IsUpper(wndPtr))
-		CharUpperBuff32A(p, strl);
-	else if(IsLower(wndPtr))
-		CharLowerBuff32A(p, strl);
 	EDIT_BuildLineDefs(wndPtr);
-	e += strl;
-	EDIT_EM_SetSel(wndPtr, e, e);
+	EDIT_EM_SetSel(wndPtr, s, s);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
 	EDIT_EM_SetModify(wndPtr, TRUE, 0);
 	dprintf_edit(stddeb, "edit: notification EN_UPDATE sent\n");
@@ -2518,6 +2733,9 @@
  *
  *	EM_SETLIMITTEXT
  *
+ *	FIXME: in WinNT maxsize is 0x7FFFFFFF / 0xFFFFFFFF
+ *	However, the windows version is not complied to yet in all of edit.c
+ *
  */
 static LRESULT EDIT_EM_SetLimitText(WND *wndPtr, WPARAM32 wParam, LPARAM lParam)
 {
@@ -2641,54 +2859,24 @@
  *
  *	EM_SETSEL
  *
- *	FIXME: specs state that we should order start and end.
- *		However, we use internally that this is not the case.
- *
  */
 static LRESULT EDIT_EM_SetSel(WND *wndPtr, WPARAM32 wParam, LPARAM lParam)
 {
-	EDITSTATE *es = EDITSTATEPTR(wndPtr);
 	INT32 ns = (INT32)wParam;
 	INT32 ne = (INT32)lParam;
-	INT32 s;
-	INT32 e;
-	INT32 el;
-	INT32 eli;
 	INT32 tl = (INT32)EDIT_WM_GetTextLength(wndPtr, 0, 0);
 
-	EDIT_GetSel(wndPtr, &s, &e);
 	if (ns == -1) {
-		ns = e;
-		ne = e;
-	}
-	if (ne == -1)
-		ne = e;
-/*
-	ORDER_INT32(ns, ne);
-*/
-	ns = MIN(ns, tl);
-	ne = MIN(ne, tl);
-	es->SelStart = ns;
-	es->SelEnd = ne;
-	if (wndPtr->hwndSelf == GetFocus32()) {
-		el = (INT32)EDIT_EM_LineFromChar(wndPtr, ne, 0);
-		eli = (INT32)EDIT_EM_LineIndex(wndPtr, el, 0);
-		SetCaretPos(EDIT_WndXFromCol(wndPtr, el, ne - eli),
-				EDIT_WndYFromLine(wndPtr, el));
-	}
-	if (EDIT_GetRedraw(wndPtr)) {
-		ORDER_INT32(s, e);
-		ORDER_INT32(s, ns);
-		ORDER_INT32(s, ne);
-		ORDER_INT32(e, ns);
-		ORDER_INT32(e, ne);
+		EDIT_GetSel(wndPtr, NULL, &ne);
+		ns = ne;
+	} else if ((!ns) && (ne == -1))
+		ne = tl;
+	else {
+		ns = MAX(0, MIN(ns, tl));
+		ne = MAX(0, MIN(ne, tl));
 		ORDER_INT32(ns, ne);
-		if (e != ns) {
-			EDIT_InvalidateText(wndPtr, s, e);
-			EDIT_InvalidateText(wndPtr, ns, ne);
-		} else
-			EDIT_InvalidateText(wndPtr, s, ne);
 	}
+	EDIT_SetSel(wndPtr, ns, ne);
 	return -1;
 }
 
@@ -2705,7 +2893,7 @@
 
 	if ((INT16)LOWORD(lParam) == -1)
 		ns = -1;
-	if ((INT16)HIWORD(lParam) == -1)
+	if ((!ns) && ((INT16)HIWORD(lParam) == -1))
 		ne = -1;
 	EDIT_EM_SetSel(wndPtr, ns, ne);
 	if (!wParam)
@@ -2783,16 +2971,27 @@
 
 /*********************************************************************
  *
- *	EM_UNDO
+ *	EM_UNDO / WM_UNDO
  *
  */
 static LRESULT EDIT_EM_Undo(WND *wndPtr, WPARAM32 wParam, LPARAM lParam)
 {
-	fprintf(stdnimp,"edit: EM_UNDO: message not implemented\n");
-	if (IsMultiLine(wndPtr))
-		return FALSE;
-	else
-		return TRUE;
+	EDITSTATE *es = EDITSTATEPTR(wndPtr);
+	LPSTR utext = xstrdup(EDIT_GetUndoPointer(wndPtr));
+
+	dprintf_edit(stddeb, "edit: before UNDO:insertion length = %d, deletion buffer = %s\n",
+			es->UndoInsertLen, utext);
+
+	EDIT_EM_SetSel(wndPtr, es->UndoPos, es->UndoPos + es->UndoInsertLen);
+	EDIT_EM_EmptyUndoBuffer(wndPtr, 0, 0);
+	EDIT_EM_ReplaceSel(wndPtr, TRUE, (LPARAM)utext);
+	EDIT_EM_SetSel(wndPtr, es->UndoPos, es->UndoPos + es->UndoInsertLen);
+	free(utext);
+
+	dprintf_edit(stddeb, "edit: after UNDO: insertion length = %d, deletion buffer = %s\n",
+			es->UndoInsertLen, EDIT_GetUndoPointer(wndPtr));
+
+	return TRUE;
 }
 
 
@@ -2814,18 +3013,18 @@
 				EDIT_MoveHome(wndPtr, FALSE);
 				EDIT_MoveDownward(wndPtr, FALSE);
 			} else
-				EDIT_EM_ReplaceSel(wndPtr, 0, (LPARAM)"\r\n");
+				EDIT_EM_ReplaceSel(wndPtr, (WPARAM32)TRUE, (LPARAM)"\r\n");
 		}
 		break;
 	case '\t':
 		if (IsMultiLine(wndPtr) && !IsReadOnly(wndPtr))
-			EDIT_EM_ReplaceSel(wndPtr, 0, (LPARAM)"\t");
+			EDIT_EM_ReplaceSel(wndPtr, (WPARAM32)TRUE, (LPARAM)"\t");
 		break;
 	default:
 		if (!IsReadOnly(wndPtr) && (c >= ' ') && (c != 127)) {
  			str[0] = c;
  			str[1] = '\0';
- 			EDIT_EM_ReplaceSel(wndPtr, 0, (LPARAM)str);
+ 			EDIT_EM_ReplaceSel(wndPtr, (WPARAM32)TRUE, (LPARAM)str);
  		}
 		break;
 	}
@@ -2840,30 +3039,45 @@
  */
 static LRESULT EDIT_WM_Clear(WND *wndPtr, WPARAM32 wParam, LPARAM lParam)
 {
-	INT32 s;
-	INT32 e;
-	LPSTR text;
-	BOOL32 redraw;
+	EDIT_EM_ReplaceSel(wndPtr, TRUE, (LPARAM)"");
 
-	EDIT_GetSel(wndPtr, &s, &e);
-	if (s != e) {
-		redraw = EDIT_GetRedraw(wndPtr);
-		EDIT_WM_SetRedraw(wndPtr, FALSE, 0);
-		ORDER_INT32(s, e);
-		text = EDIT_GetPointer(wndPtr);
-		lstrcpy32A(text + s, text + e);
-		EDIT_BuildLineDefs(wndPtr);
-		EDIT_EM_SetSel(wndPtr, s, s);
-		EDIT_EM_ScrollCaret(wndPtr, 0, 0);
-		EDIT_EM_SetModify(wndPtr, TRUE, 0);
-		dprintf_edit(stddeb, "edit: notification EN_UPDATE sent\n");
-		EDIT_NOTIFY_PARENT(wndPtr, EN_UPDATE);
-		EDIT_WM_SetRedraw(wndPtr, redraw, 0);
-		if (redraw) {
-			InvalidateRect32( wndPtr->hwndSelf, NULL, TRUE );
-			dprintf_edit(stddeb, "edit: notification EN_CHANGE sent\n");
-			EDIT_NOTIFY_PARENT(wndPtr, EN_CHANGE);
-		}
+	return -1;
+}
+
+
+/*********************************************************************
+ *
+ *	WM_COMMAND
+ *
+ */
+static LRESULT EDIT_WM_Command(WND *wndPtr, WPARAM32 wParam, LPARAM lParam)
+{
+	if (HIWORD(wParam))
+		return 0;
+
+	switch (LOWORD(wParam)) {
+		case EM_UNDO32:	
+			EDIT_EM_Undo(wndPtr, 0, 0);
+			break;
+		case WM_CUT:
+			EDIT_WM_Cut(wndPtr, 0, 0);
+			break;
+		case WM_COPY:
+			EDIT_WM_Copy(wndPtr, 0, 0);
+			break;
+		case WM_PASTE:
+			EDIT_WM_Paste(wndPtr, 0, 0);
+			break;
+		case WM_CLEAR:
+			EDIT_WM_Clear(wndPtr, 0, 0);
+			break;
+		case EM_SETSEL32:
+			EDIT_EM_SetSel(wndPtr, 0, -1);
+			EDIT_EM_ScrollCaret(wndPtr, 0, 0);
+			break;
+		default:
+			dprintf_edit(stddeb, "edit: unknown menu item, please report\n");
+			break;
 	}
 	return -1;
 }
@@ -2871,6 +3085,27 @@
 
 /*********************************************************************
  *
+ *	WM_CONTEXTMENU
+ *
+ *	Note: the resource files resource/sysres_??.rc cannot define a
+ *		single popup menu.  Hence we use a (dummy) menubar
+ *		containing the single popup menu as its first item.
+ *
+ */
+static LRESULT EDIT_WM_ContextMenu(WND *wndPtr, WPARAM32 wParam, LPARAM lParam)
+{
+	HMENU32 hMenu = LoadMenuIndirect32A(SYSRES_GetResPtr(SYSRES_MENU_EDITMENU));
+	HMENU32 hPopup = GetSubMenu32(hMenu, 0);
+
+	TrackPopupMenu32(hPopup, TPM_LEFTALIGN | TPM_RIGHTBUTTON, LOWORD(lParam),
+			HIWORD(lParam), 0, wndPtr->hwndSelf, NULL);
+	DestroyMenu32(hMenu);
+	return 0;
+}
+
+
+/*********************************************************************
+ *
  *	WM_COPY
  *
  */
@@ -2881,8 +3116,6 @@
 	HGLOBAL16 hdst;
 	LPSTR text;
 	LPSTR dst;
-	LPSTR src;
-	INT32 i;
 
 	EDIT_GetSel(wndPtr, &s, &e);
 	if (e == s)
@@ -2891,10 +3124,7 @@
 	hdst = GlobalAlloc16(GMEM_MOVEABLE, (DWORD)(e - s + 1));
 	dst = GlobalLock16(hdst);
 	text = EDIT_GetPointer(wndPtr);
-	src = text + s;
-	for (i = 0 ; i < e - s ; i++)
-		*dst++ = *src++;
-	*dst = '\0';
+	lstrcpyn32A(dst, text + s, e - s + 1);
 	GlobalUnlock16(hdst);
 	OpenClipboard(wndPtr->hwndSelf);
 	EmptyClipboard();
@@ -2942,13 +3172,21 @@
 		fprintf(stderr, "edit: WM_CREATE: unable to allocate buffer\n");
 		return -1;
 	}
+	if (!(es->hUndoBuf = LocalAlloc32(LMEM_MOVEABLE, es->BufSize + 1))) {
+		fprintf(stderr, "edit: WM_CREATE: unable to allocate undo buffer\n");
+		LocalFree32(es->hBuf32);
+		es->hBuf32 = (HLOCAL32)NULL;
+		return -1;
+	}
 	es->BufSize = LocalSize32(es->hBuf32) - 1;
+	es->UndoBufSize = LocalSize32(es->hUndoBuf) - 1;
+	EDIT_EM_EmptyUndoBuffer(wndPtr, 0, 0);
 	text = EDIT_GetPointer(wndPtr);
 	*text = '\0';
 	EDIT_BuildLineDefs(wndPtr);
 	EDIT_WM_SetFont(wndPtr, 0, 0);
 	if (cs->lpszName && *(cs->lpszName) != '\0')
-		EDIT_EM_ReplaceSel(wndPtr, FALSE, (LPARAM)cs->lpszName);
+		EDIT_EM_ReplaceSel(wndPtr, (WPARAM32)FALSE, (LPARAM)cs->lpszName);
 	EDIT_WM_SetRedraw(wndPtr, TRUE, 0);
 	return 0;
 }
@@ -2979,6 +3217,8 @@
 	free(es->LineDefs);
 	if (es->TabStops)
 		free(es->TabStops);
+	EDIT_ReleaseUndoPointer(wndPtr);
+	LocalFree32(es->hUndoBuf);
 	EDIT_ReleasePointer(wndPtr);
 	if (es->hBuf32)
 		LocalFree32(es->hBuf32);
@@ -3154,6 +3394,49 @@
 
 /*********************************************************************
  *
+ *	WM_INITMENUPOPUP
+ *
+ *	FIXME: the message identifiers have been chosen arbitrarily,
+ *		hence we use MF_BYPOSITION.
+ *		We might as well use the "real" values (anybody knows ?)
+ *		The menu definition is in resources/sysres_??.rc.
+ *		Once these are OK, we better use MF_BYCOMMAND here
+ *		(as we do in EDIT_WM_Command()).
+ *
+ */
+static LRESULT EDIT_WM_InitMenuPopup(WND *wndPtr, WPARAM32 wParam, LPARAM lParam)
+{
+	HMENU32 hPopup = (HMENU32)wParam;
+	INT32 s;
+	INT32 e;
+
+	EDIT_EM_GetSel(wndPtr, (WPARAM32)&s, (LPARAM)&e);
+
+	/* undo */
+	EnableMenuItem32(hPopup, 0, MF_BYPOSITION |
+		(EDIT_EM_CanUndo(wndPtr, 0, 0) ? MF_ENABLED : MF_GRAYED));
+	/* cut */
+	EnableMenuItem32(hPopup, 2, MF_BYPOSITION |
+		((e - s) && !IsPassword(wndPtr) ? MF_ENABLED : MF_GRAYED));
+	/* copy */
+	EnableMenuItem32(hPopup, 3, MF_BYPOSITION |
+		((e - s) && !IsPassword(wndPtr) ? MF_ENABLED : MF_GRAYED));
+	/* paste */
+	EnableMenuItem32(hPopup, 4, MF_BYPOSITION |
+		(IsClipboardFormatAvailable(CF_TEXT) ? MF_ENABLED : MF_GRAYED));
+	/* delete */
+	EnableMenuItem32(hPopup, 5, MF_BYPOSITION |
+		((e - s) ? MF_ENABLED : MF_GRAYED));
+	/* select all */
+	EnableMenuItem32(hPopup, 7, MF_BYPOSITION |
+		(s || (e != EDIT_WM_GetTextLength(wndPtr, 0, 0)) ? MF_ENABLED : MF_GRAYED));
+
+	return 0;
+}
+
+
+/*********************************************************************
+ *
  *	WM_KEYDOWN
  *
  *	Handling of special keys that don't produce a WM_CHAR
@@ -3255,7 +3538,7 @@
 
 	DestroyCaret();
 	if(!(wndPtr->dwStyle & ES_NOHIDESEL)) {
-		EDIT_GetSel(wndPtr, &s, &e);
+		EDIT_EM_GetSel(wndPtr, (WPARAM32)&s, (LPARAM)&e);
 		EDIT_InvalidateText(wndPtr, s, e);
 	}
 	dprintf_edit(stddeb, "edit: notification EN_KILLFOCUS sent\n");
@@ -3320,8 +3603,9 @@
 		EDIT_GetSel(wndPtr, &s, NULL);
 	else
 		s = e;
-	EDIT_EM_SetSel(wndPtr, s, e);
+	EDIT_SetSel(wndPtr, s, e);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
+	SetTimer32(wndPtr->hwndSelf, 0, 100, NULL);
 	return 0;
 }
 
@@ -3333,8 +3617,10 @@
  */
 static LRESULT EDIT_WM_LButtonUp(WND *wndPtr, WPARAM32 wParam, LPARAM lParam)
 {
-	if (GetCapture32() == wndPtr->hwndSelf)
+	if (GetCapture32() == wndPtr->hwndSelf) {
+		KillTimer32(wndPtr->hwndSelf, 0);
 		ReleaseCapture();
+	}
 	return 0;
 }
 
@@ -3366,8 +3652,12 @@
 		c = EDIT_ColFromWndX(wndPtr, l, x);
 		EDIT_GetSel(wndPtr, &s, NULL);
 		li = (INT32)EDIT_EM_LineIndex(wndPtr, l, 0);
-		EDIT_EM_SetSel(wndPtr, s, li + c);
+		EDIT_SetSel(wndPtr, s, li + c);
 	}
+	/*
+	 *	FIXME: gotta do some scrolling if outside client (format ?)
+	 *		area.  Maybe reset the timer ?
+	 */
 	return 0;
 }
 
@@ -3390,7 +3680,9 @@
 	RECT32 rc;
 	RECT32 rcLine;
 	RECT32 rcRgn;
-	BOOL32 rev = IsWindowEnabled(wndPtr->hwndSelf) &&
+ 	LRESULT pos;
+ 	INT32 e;
+	BOOL32 rev = IsWindowEnabled32(wndPtr->hwndSelf) &&
 				((GetFocus32() == wndPtr->hwndSelf) ||
 					(wndPtr->dwStyle & ES_NOHIDESEL));
 
@@ -3401,7 +3693,7 @@
 	if (hFont)
 		oldFont = (HFONT32)SelectObject32(hdc, hFont);
 	EDIT_SEND_CTLCOLOR(wndPtr, hdc);
-	if (!IsWindowEnabled(wndPtr->hwndSelf))
+	if (!IsWindowEnabled32(wndPtr->hwndSelf))
 		SetTextColor(hdc, GetSysColor(COLOR_GRAYTEXT));
 	GetClipBox32(hdc, &rcRgn);
 	for (i = fv ; i <= MIN(fv + vlc, fv + lc - 1) ; i++ ) {
@@ -3410,6 +3702,11 @@
 			EDIT_PaintLine(wndPtr, hdc, i, rev);
 	}
 	if (hFont) SelectObject32(hdc, oldFont);
+	if (wndPtr->hwndSelf == GetFocus32()) {
+		EDIT_GetSel(wndPtr, NULL, &e);
+		pos = EDIT_EM_PosFromChar(wndPtr, e, 0);
+		SetCaretPos((INT16)LOWORD(pos), (INT16)HIWORD(pos));
+	}
 	EndPaint32(wndPtr->hwndSelf, &ps);
 	return 0;
 }
@@ -3428,7 +3725,7 @@
 	OpenClipboard(wndPtr->hwndSelf);
 	if ((hsrc = GetClipboardData(CF_TEXT))) {
 		src = (LPSTR)GlobalLock16(hsrc);
-		EDIT_EM_ReplaceSel(wndPtr, 0, (LPARAM)src);
+		EDIT_EM_ReplaceSel(wndPtr, (WPARAM32)TRUE, (LPARAM)src);
 		GlobalUnlock16(hsrc);
 	}
 	CloseClipboard();
@@ -3463,7 +3760,7 @@
 
 	EDIT_GetSel(wndPtr, &s, &e);
 	CreateCaret(wndPtr->hwndSelf, 0, 2, EDIT_GetLineHeight(wndPtr));
-	EDIT_EM_SetSel(wndPtr, s, e);
+	EDIT_SetSel(wndPtr, s, e);
 	if(!(wndPtr->dwStyle & ES_NOHIDESEL))
 		EDIT_InvalidateText(wndPtr, s, e);
 	ShowCaret(wndPtr->hwndSelf);
@@ -3502,7 +3799,7 @@
 	if (wndPtr->hwndSelf == GetFocus32()) {
 		DestroyCaret();
 		CreateCaret(wndPtr->hwndSelf, 0, 2, EDIT_GetLineHeight(wndPtr));
-		EDIT_EM_SetSel16(wndPtr, s, e);
+		EDIT_SetSel(wndPtr, s, e);
 		ShowCaret(wndPtr->hwndSelf);
 	}
 	return 0;
@@ -3532,10 +3829,7 @@
 {
 	EDIT_EM_SetSel(wndPtr, 0, -1);
 	if (lParam)
-		EDIT_EM_ReplaceSel(wndPtr, 0, lParam);
-	else
-            EDIT_WM_Clear(wndPtr, 0, 0);
-	EDIT_EM_EmptyUndoBuffer(wndPtr, 0, 0);
+		EDIT_EM_ReplaceSel(wndPtr, (WPARAM32)FALSE, lParam);
 	EDIT_EM_SetModify(wndPtr, TRUE, 0);
 	EDIT_EM_ScrollCaret(wndPtr, 0, 0);
 	return 1;
@@ -3552,7 +3846,9 @@
 static LRESULT EDIT_WM_Size(WND *wndPtr, WPARAM32 wParam, LPARAM lParam)
 {
 	EDITSTATE *es = EDITSTATEPTR(wndPtr);
-
+	INT32 e;
+	
+	EDIT_GetSel(wndPtr, 0, &e);
 	GetClientRect32(wndPtr->hwndSelf, &es->FormatRect);
 	if (EDIT_GetRedraw(wndPtr) &&
 			((wParam == SIZE_MAXIMIZED) ||
@@ -3567,6 +3863,35 @@
 
 /*********************************************************************
  *
+ *	WM_SYSKEYDOWN
+ *
+ */
+static LRESULT EDIT_WM_SysKeyDown(WND *wndPtr, WPARAM32 wParam, LPARAM lParam)
+{
+	if ((wParam == VK_BACK) && (lParam & 0x2000) &&
+			(BOOL32)EDIT_EM_CanUndo(wndPtr, 0, 0))
+		EDIT_EM_Undo(wndPtr, 0, 0);
+	return 0;
+}
+
+
+/*********************************************************************
+ *
+ *	WM_TIMER
+ *
+ */
+static LRESULT EDIT_WM_Timer(WND *wndPtr, WPARAM32 wParam, LPARAM lParam)
+{
+/*
+ *	FIXME: gotta do some scrolling here, like
+ *		EDIT_EM_LineScroll(wndPtr, 0, 1);
+ */
+	return 0;
+}
+
+
+/*********************************************************************
+ *
  *	WM_VSCROLL
  *
  *	FIXME: scrollbar code itself is broken, so this one is a hack.
diff --git a/controls/listbox.c b/controls/listbox.c
index 0f3b431..006de25 100644
--- a/controls/listbox.c
+++ b/controls/listbox.c
@@ -310,11 +310,11 @@
             dprintf_listbox(stddeb, "Listbox %04x: changing height %d -> %d\n",
                             wnd->hwndSelf, descr->height,
                             descr->height - descr->height%descr->item_height );
-            SetWindowPos( wnd->hwndSelf, 0, 0, 0,
-                          wnd->rectWindow.right - wnd->rectWindow.left,
-                          wnd->rectWindow.bottom - wnd->rectWindow.top -
-                              (descr->height % descr->item_height),
-                          SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE );
+            SetWindowPos32( wnd->hwndSelf, 0, 0, 0,
+                            wnd->rectWindow.right - wnd->rectWindow.left,
+                            wnd->rectWindow.bottom - wnd->rectWindow.top -
+                                (descr->height % descr->item_height),
+                            SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE );
             return;
         }
     }
diff --git a/controls/menu.c b/controls/menu.c
index 197262f..bedd677 100644
--- a/controls/menu.c
+++ b/controls/menu.c
@@ -650,7 +650,7 @@
 
     if (lpitem->item_flags & MF_BITMAP)
     {
-	GRAPH_DrawBitmap( hdc, (HBITMAP16)(UINT32)lpitem->text,
+	GRAPH_DrawBitmap( hdc, (HBITMAP32)lpitem->text,
                           rect.left, rect.top, 0, 0,
                           rect.right-rect.left, rect.bottom-rect.top );
 	return;
@@ -864,12 +864,12 @@
 
     wndPtr = WIN_FindWndPtr( menu->hWnd );
 
-    SetWindowPos(menu->hWnd, 0, x, y, width, height,
+    SetWindowPos32(menu->hWnd, 0, x, y, width, height,
 		  		      SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOREDRAW);
       /* Display the window */
 
-    SetWindowPos( menu->hWnd, HWND_TOP, 0, 0, 0, 0,
-		  SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE );
+    SetWindowPos32( menu->hWnd, HWND_TOP, 0, 0, 0, 0,
+		    SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE );
     UpdateWindow( menu->hWnd );
     return TRUE;
 }
@@ -1015,8 +1015,8 @@
             item->text = text;
         }
     }
-    else if ((flags & MF_BITMAP) || (flags & MF_OWNERDRAW))
-        item->text = (LPSTR)str;
+    else if (flags & MF_BITMAP) item->text = (LPSTR)(HBITMAP32)LOWORD(str);
+    else if (flags & MF_OWNERDRAW) item->text = (LPSTR)str;
     else item->text = NULL;
 
     item->item_flags = flags & ~(MF_HILITE | MF_MOUSESELECT);
@@ -1191,12 +1191,12 @@
     MENU_SelectItem( hwndOwner, hsubmenu, NO_SELECTED_ITEM, sendMenuSelect );
     if (submenu->hWnd == pTopPWnd->hwndSelf ) 
     {
-	ShowWindow( submenu->hWnd, SW_HIDE );
+	ShowWindow32( submenu->hWnd, SW_HIDE );
 	uSubPWndLevel = 0;
     }
     else
     {
-	DestroyWindow( submenu->hWnd );
+	DestroyWindow32( submenu->hWnd );
 	submenu->hWnd = 0;
     }
 }
@@ -1485,10 +1485,10 @@
 
     if( (menu->wFlags & (MF_POPUP | MF_SYSMENU)) == (MF_POPUP | MF_SYSMENU) )
 	{
-	  ShowWindow( menu->hWnd, SW_HIDE );
+	  ShowWindow32( menu->hWnd, SW_HIDE );
 	  uSubPWndLevel = 0;
 
-	  if( !IsIconic( *hwndOwner ) )
+	  if( !IsIconic32( *hwndOwner ) )
 	  { 
 	    HDC32 hdc = GetDCEx32( *hwndOwner, 0, DCX_CACHE | DCX_WINDOW);
 	    NC_DrawSysButton( *hwndOwner, hdc, FALSE );
@@ -1523,7 +1523,7 @@
                 MENU_ShowPopup( *hwndOwner, *hmenu, 0, rect.left, rect.bottom,
                                 SYSMETRICS_CXSIZE, SYSMETRICS_CYSIZE );
             
-            if( !IsIconic( *hwndOwner ) )
+            if( !IsIconic32( *hwndOwner ) )
             {
                 HDC32 hdc =  GetDCEx32( *hwndOwner, 0, DCX_CACHE | DCX_WINDOW);
                 NC_DrawSysButton( *hwndOwner, hdc, TRUE );
@@ -1818,7 +1818,7 @@
     menu = (POPUPMENU *) USER_HEAP_LIN_ADDR( hmenu );
     if (menu && menu->wFlags & MF_POPUP) 
     {
-         ShowWindow( menu->hWnd, SW_HIDE );
+         ShowWindow32( menu->hWnd, SW_HIDE );
 	 uSubPWndLevel = 0;
     }
     MENU_SelectItem( hwnd, hmenu, NO_SELECTED_ITEM, FALSE );
@@ -2702,7 +2702,7 @@
     if ((lppop->wFlags & MF_POPUP) &&
         lppop->hWnd &&
         (!pTopPWnd || (lppop->hWnd != pTopPWnd->hwndSelf)))
-        DestroyWindow( lppop->hWnd );
+        DestroyWindow32( lppop->hWnd );
 
     if (lppop->items)
     {
@@ -2824,9 +2824,9 @@
         lpmenu->wFlags &= ~MF_POPUP;  /* Can't be a popup */
         lpmenu->Height = 0;  /* Make sure we recalculate the size */
     }
-    if (IsWindowVisible(hWnd))
-        SetWindowPos( hWnd, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE |
-                      SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED );
+    if (IsWindowVisible32(hWnd))
+        SetWindowPos32( hWnd, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE |
+                        SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED );
     return TRUE;
 }
 
@@ -2877,8 +2877,8 @@
         if (lppop == NULL) return FALSE;
 
         lppop->Height = 0; /* Make sure we call MENU_MenuBarCalcSize */
-        SetWindowPos( hWnd, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE |
-                      SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED );
+        SetWindowPos32( hWnd, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE |
+                        SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED );
         return TRUE;
     }
     return FALSE;
diff --git a/controls/scroll.c b/controls/scroll.c
index ea04e38..14c3f40 100644
--- a/controls/scroll.c
+++ b/controls/scroll.c
@@ -778,24 +778,24 @@
 	    if (lpCreat->style & SBS_VERT)
             {
                 if (lpCreat->style & SBS_LEFTALIGN)
-                    MoveWindow( hwnd, lpCreat->x, lpCreat->y,
-                                SYSMETRICS_CXVSCROLL+1, lpCreat->cy, FALSE );
+                    MoveWindow32( hwnd, lpCreat->x, lpCreat->y,
+                                  SYSMETRICS_CXVSCROLL+1, lpCreat->cy, FALSE );
                 else if (lpCreat->style & SBS_RIGHTALIGN)
-                    MoveWindow( hwnd, 
-                                lpCreat->x+lpCreat->cx-SYSMETRICS_CXVSCROLL-1,
-                                lpCreat->y,
-                                SYSMETRICS_CXVSCROLL + 1, lpCreat->cy, FALSE );
+                    MoveWindow32( hwnd, 
+                                  lpCreat->x+lpCreat->cx-SYSMETRICS_CXVSCROLL-1,
+                                  lpCreat->y,
+                                  SYSMETRICS_CXVSCROLL+1, lpCreat->cy, FALSE );
             }
             else  /* SBS_HORZ */
             {
                 if (lpCreat->style & SBS_TOPALIGN)
-                    MoveWindow( hwnd, lpCreat->x, lpCreat->y,
-                                lpCreat->cx, SYSMETRICS_CYHSCROLL+1, FALSE );
+                    MoveWindow32( hwnd, lpCreat->x, lpCreat->y,
+                                  lpCreat->cx, SYSMETRICS_CYHSCROLL+1, FALSE );
                 else if (lpCreat->style & SBS_BOTTOMALIGN)
-                    MoveWindow( hwnd, 
-                                lpCreat->x,
-                                lpCreat->y+lpCreat->cy-SYSMETRICS_CYHSCROLL-1,
-                                lpCreat->cx, SYSMETRICS_CYHSCROLL+1, FALSE );
+                    MoveWindow32( hwnd, 
+                                  lpCreat->x,
+                                  lpCreat->y+lpCreat->cy-SYSMETRICS_CYHSCROLL-1,
+                                  lpCreat->cx, SYSMETRICS_CYHSCROLL+1, FALSE );
             }
         }
         if (!hUpArrow) SCROLL_LoadBitmaps();
@@ -1210,7 +1210,7 @@
     switch(nBar)
     {
     case SB_CTL:
-        ShowWindow( hwnd, fShow ? SW_SHOW : SW_HIDE );
+        ShowWindow32( hwnd, fShow ? SW_SHOW : SW_HIDE );
         return TRUE;
 
     case SB_HORZ:
@@ -1257,8 +1257,8 @@
     default:
         return TRUE;  /* Nothing to do! */
     }
-    SetWindowPos( hwnd, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE
-                 | SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED );
+    SetWindowPos32( hwnd, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE
+                    | SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED );
     return TRUE;
 }
 
diff --git a/controls/static.c b/controls/static.c
index 289b0a5..9184cf5 100644
--- a/controls/static.c
+++ b/controls/static.c
@@ -56,8 +56,8 @@
     if (hicon)
     {
         CURSORICONINFO *info = (CURSORICONINFO *) GlobalLock16( hicon );
-        SetWindowPos( wndPtr->hwndSelf, 0, 0, 0, info->nWidth, info->nHeight,
-                     SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER );
+        SetWindowPos32( wndPtr->hwndSelf, 0, 0, 0, info->nWidth, info->nHeight,
+                        SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER );
         GlobalUnlock16( hicon );
     }
     return prevIcon;
diff --git a/controls/status.c b/controls/status.c
index ccb188b..17c4372 100644
--- a/controls/status.c
+++ b/controls/status.c
@@ -85,7 +85,7 @@
 {
 	int	i;
 
-	if (!IsWindowVisible(hwnd)) {
+	if (!IsWindowVisible32(hwnd)) {
 	    return (TRUE);
 	}
 
@@ -284,7 +284,7 @@
     GetClientRect32(parent, &rect);
     width = rect.right - rect.left;
     height = (self->textHeight * 3)/2;
-    MoveWindow(hwnd, lpCreate->x, lpCreate->y-1, width, height, FALSE);
+    MoveWindow32(hwnd, lpCreate->x, lpCreate->y-1, width, height, FALSE);
     SW_SetPartBounds(hwnd, self);
     return 0;
 }
@@ -400,8 +400,8 @@
 	width = parent_rect.right - parent_rect.left;
 	x = parent_rect.left;
 	y = parent_rect.bottom - height;
-	MoveWindow(hwnd, parent_rect.left, parent_rect.bottom - height - 1,
-		   width, height, TRUE);
+	MoveWindow32(hwnd, parent_rect.left, parent_rect.bottom - height - 1,
+		     width, height, TRUE);
 	SW_SetPartBounds(hwnd, self);
     }
     return 0;
diff --git a/debugger/README b/debugger/README
index 02cad9b..412b7e8 100644
--- a/debugger/README
+++ b/debugger/README
@@ -1,8 +1,7 @@
-	This is the core of the Wine debugger.  Many pieces have been
-shamelessly stolen - the reverse assember was stolen from Mach more or
-less intact.  It turns out that there are two variables that are set
-differently if you are reverse assembling 16 bit code, and on the
-whole it seems to work.
+	This is the core of the Wine debugger.  The reverse assember
+was stolen from Mach more or less intact.  It turns out that there are
+two variables that are set differently if you are reverse assembling
+16 bit code, and on the whole it seems to work.
 
 NEWS:
 
@@ -63,6 +62,16 @@
 automatic display expressions.  An example is at the end of this file.  The
 syntax and usage should be identical to that of gdb.
 
+	8) Type casts can be made from within the debugger, but they currently
+don't work with typedef'ed types.  They only work with builtin types and
+named structures unions, etc.  The problem is that internally we don't always
+record the typedefed names of structures, so we have no guarantee that we
+would know what each type is.  This can be fixed, of course -  it just takes
+more memory.  Note that in some cases, typedefed structures could be cast
+using '(struct typedfname)' instead of '(typedfname)'.   Technically this
+isn't quite correct, but if and when the rest of this stuff gets fixed,
+this would need to get corrected too.
+
 NOTES:
 
 	If it weren't for the fact that gdb doesn't grok the Win32 debug
@@ -73,16 +82,6 @@
 
 LIMITATIONS AND DIFFERENCES FROM GDB:
 
-	You cannot use type casts in expressions that you give to the
-debugger.  The hardest part about adding support for this is fixing
-the parser/lexer to know when it is handling a type cast, and when it
-is handling any other type of parenthesized expression.  With lexer
-states, it may be possible to keep track of what we would expect at
-any given moment, but it would be tedious to go through and make sure
-that the state is set up correctly for all of the different operators
-and characters that we accept, and I am not yet convinced that this would
-even work.
-
 	You cannot set a breakpoint by file and line number as you can
 with gdb.  Adding support for this wouldn't be all that tough, I guess, but
 it would be a nuisance.   You can set a breakpoint given a function and
@@ -348,11 +347,6 @@
 	You can use the set command to set more or less anything.  Note
 however that you cannot use enumerated types on the RHS of the expression.
 
-	Finally, type casts are not yet supported in the expression
-handling.  There is sufficient information stored internally to be
-able to handle this - the main challenge is that the parser would
-need to be fixed to correctly parse the type cast.
-
 *******************************************************************
 
 
diff --git a/debugger/TODO b/debugger/TODO
index 3544b12..c527b922 100644
--- a/debugger/TODO
+++ b/debugger/TODO
@@ -3,10 +3,9 @@
 possible to me right now.   In no particular order.  If someone else
 wants to dig in, feel free.
 
-1) Some kind of watchpoint capability.  Pretty easy once we have a
-	single step capability, but we end up running the program
-	really slowly one instruction at a time.  Use hardware debug
-	registers for this???
+1) Some kind of watchpoint capability.  Pretty easy, but we end up
+        running the program really slowly one instruction at a time.  
+	Use hardware debug registers for this (much harder)???
 
 2) Some kind of .wdbinit file.
 
@@ -31,14 +30,6 @@
 8) Some of the newer displays are still a little bit sparse on information.
 	Make these more like gdb.
 
-9) Don't bother to disassemble an instruction when we stop at a breakpoint
-	and if we have a valid source line we are displaying.
-
-10) Add support for '/i', etc in display command.  Make sure 'display/i $eip'
-	does the correct thing, and then skip automatic disassembly completely.
-
-11)	Limit amount of information displayed with print command.
-
-12)	Make sure operator precedence works OK.
+9) Make sure operator precedence works OK.
 
 ****************
diff --git a/debugger/break.c b/debugger/break.c
index 5cf164f..d84427d 100644
--- a/debugger/break.c
+++ b/debugger/break.c
@@ -252,6 +252,13 @@
         fprintf( stderr, "Invalid breakpoint number %d\n", num );
         return;
     }
+
+    if( breakpoints[num].condition != NULL )
+      {
+	DEBUG_FreeExpr(breakpoints[num].condition);
+	breakpoints[num].condition = NULL;
+      }
+
     breakpoints[num].enabled = FALSE;
     breakpoints[num].in_use  = FALSE;
     breakpoints[num].skipcount = 0;
diff --git a/debugger/dbg.y b/debugger/dbg.y
index 8db0885..f79a3ff 100644
--- a/debugger/dbg.y
+++ b/debugger/dbg.y
@@ -41,6 +41,7 @@
     int              integer;
     struct list_id   listing;
     struct expr *    expression;
+    struct datatype * type;
 }
 
 %token tCONT tSTEP tLIST tNEXT tQUIT tHELP tBACKTRACE tINFO tWALK tUP tDOWN
@@ -48,12 +49,15 @@
 %token tCLASS tMODULE tSTACK tSEGMENTS tREGS tWND tQUEUE tLOCAL
 %token tEOL tSTRING
 %token tFRAME tSHARE tCOND tDISPLAY tUNDISPLAY
-%token tSTEPI tNEXTI tFINISH tSHOW tDIR 
+%token tSTEPI tNEXTI tFINISH tSHOW tDIR
 %token <string> tPATH
 %token <string> tIDENTIFIER tSTRING
 %token <integer> tNUM tFORMAT
 %token <reg> tREG
 
+%token tCHAR tSHORT tINT tLONG tFLOAT tDOUBLE tUNSIGNED tSIGNED 
+%token tSTRUCT tUNION tENUM
+
 /* %left ',' */
 /* %left '=' OP_OR_EQUAL OP_XOR_EQUAL OP_AND_EQUAL OP_SHL_EQUAL \
          OP_SHR_EQUAL OP_PLUS_EQUAL OP_MINUS_EQUAL \
@@ -66,14 +70,15 @@
 %left '&'
 %left OP_EQ OP_NE
 %left '<' '>' OP_LE OP_GE
-%left OP_SHL OP_SHR OP_DRF
+%left OP_SHL OP_SHR
 %left '+' '-'
 %left '*' '/' '%'
 %left OP_SIGN '!' '~' OP_DEREF /* OP_INC OP_DEC OP_ADDR */
-%left '.' '['
+%left '.' '[' OP_DRF
 %nonassoc ':'
 
-%type <expression> expr lval lvalue
+%type <expression> expr lval lvalue 
+%type <type> type_cast type_expr
 %type <address> expr_addr lval_addr
 %type <integer> expr_value
 %type <string> pathname
@@ -129,7 +134,9 @@
     | tSHOW tDIR tEOL	       { DEBUG_ShowDir(); }
     | tDIR pathname tEOL       { DEBUG_AddPath( $2 ); }
     | tDIR tEOL		       { DEBUG_NukePath(); }
-    | tDISPLAY expr tEOL       { DEBUG_AddDisplay($2); }
+    | tDISPLAY tEOL	       { DEBUG_InfoDisplay(); }
+    | tDISPLAY expr tEOL       { DEBUG_AddDisplay($2, 1, 0); }
+    | tDISPLAY tFORMAT expr tEOL { DEBUG_AddDisplay($3, $2 >> 8, $2 & 0xff); }
     | tDELETE tDISPLAY tNUM tEOL { DEBUG_DelDisplay( $3 ); }
     | tDELETE tDISPLAY tEOL    { DEBUG_DelDisplay( -1 ); }
     | tUNDISPLAY tNUM tEOL     { DEBUG_DelDisplay( $2 ); }
@@ -257,6 +264,30 @@
     | tWALK tWND tEOL           { WIN_WalkWindows( 0, 0 ); }
     | tWALK tWND tNUM tEOL      { WIN_WalkWindows( $3, 0 ); }
 
+
+type_cast: 
+      '(' type_expr ')'		{ $$ = $2; }
+
+type_expr:
+      type_expr '*'		{ $$ = DEBUG_FindOrMakePointerType($1); }
+    |  tINT			{ $$ = DEBUG_TypeCast(BASIC, "int"); }
+    | tCHAR			{ $$ = DEBUG_TypeCast(BASIC, "char"); }
+    | tLONG tINT		{ $$ = DEBUG_TypeCast(BASIC, "long int"); }
+    | tUNSIGNED tINT		{ $$ = DEBUG_TypeCast(BASIC, "unsigned int"); }
+    | tLONG tUNSIGNED tINT	{ $$ = DEBUG_TypeCast(BASIC, "long unsigned int"); }
+    | tLONG tLONG tINT		{ $$ = DEBUG_TypeCast(BASIC, "long long int"); }
+    | tLONG tLONG tUNSIGNED tINT { $$ = DEBUG_TypeCast(BASIC, "long long unsigned int"); }
+    | tSHORT tINT		{ $$ = DEBUG_TypeCast(BASIC, "short int"); }
+    | tSHORT tUNSIGNED tINT	{ $$ = DEBUG_TypeCast(BASIC, "short unsigned int"); }
+    | tSIGNED tCHAR		{ $$ = DEBUG_TypeCast(BASIC, "signed char"); }
+    | tUNSIGNED tCHAR		{ $$ = DEBUG_TypeCast(BASIC, "unsigned char"); }
+    | tFLOAT			{ $$ = DEBUG_TypeCast(BASIC, "float"); }
+    | tDOUBLE			{ $$ = DEBUG_TypeCast(BASIC, "double"); }
+    | tLONG tDOUBLE		{ $$ = DEBUG_TypeCast(BASIC, "long double"); }
+    | tSTRUCT tIDENTIFIER	{ $$ = DEBUG_TypeCast(STRUCT, $2); }
+    | tUNION tIDENTIFIER	{ $$ = DEBUG_TypeCast(STRUCT, $2); }
+    | tENUM tIDENTIFIER		{ $$ = DEBUG_TypeCast(ENUM, $2); }
+
 expr_addr:
     expr			 { $$ = DEBUG_EvalExpr($1) }
 
@@ -310,6 +341,7 @@
     | '(' expr ')'               { $$ = $2; }
     | '*' expr %prec OP_DEREF    { $$ = DEBUG_UnopExpr(EXP_OP_DEREF, $2); }
     | '&' expr %prec OP_DEREF    { $$ = DEBUG_UnopExpr(EXP_OP_ADDR, $2); }
+    | type_cast expr %prec OP_DEREF { $$ = DEBUG_TypeCastExpr($1, $2); } 
 	
 /*
  * The lvalue rule builds an expression tree.  This is a limited form
@@ -460,15 +492,18 @@
 	    DEBUG_SilentBackTrace();
 	}
 
-        /* Show where we crashed */
-        curr_frame = 0;
-        DEBUG_PrintAddress( &addr, dbg_mode, TRUE );
-        fprintf(stderr,":  ");
-        if (DBG_CHECK_READ_PTR( &addr, 1 ))
-        {
-            DEBUG_Disasm( &addr, TRUE );
-            fprintf(stderr,"\n");
-        }
+	if( signal != SIGTRAP )
+	  {
+	    /* Show where we crashed */
+	    curr_frame = 0;
+	    DEBUG_PrintAddress( &addr, dbg_mode, TRUE );
+	    fprintf(stderr,":  ");
+	    if (DBG_CHECK_READ_PTR( &addr, 1 ))
+	      {
+		DEBUG_Disasm( &addr, TRUE );
+		fprintf(stderr,"\n");
+	      }
+	  }
 
         ret_ok = 0;
         do
diff --git a/debugger/dbgmain.c b/debugger/dbgmain.c
index 9d3fb8c..7c1992b 100644
--- a/debugger/dbgmain.c
+++ b/debugger/dbgmain.c
@@ -6,15 +6,16 @@
 #include <signal.h>
 
 #include <ldt.h>
-#include <windows.h>
-#include <toolhelp.h>
-#include <module.h>
-#include <debugger.h>
-#include <class.h>
+#include "windows.h"
+#include "toolhelp.h"
+#include "module.h"
+#include "debugger.h"
+#include "class.h"
 #include <X11/Xlib.h>
 
 #include "debugger.h"
 #include "peexe.h"
+#include "pe_image.h"
 
 ldt_copy_entry ldt_copy[LDT_SIZE];
 unsigned char ldt_flags_copy[LDT_SIZE];
@@ -171,7 +172,7 @@
 	int				  dbg_size;
 	struct PE_Debug_dir		* dbgdir;
 	struct pe_data			* pe;
-        struct pe_segment_table         * sectp;
+        LPIMAGE_SECTION_HEADER            sectp;
 	int				  nsect;
 	short int			  dbg_index;			
 	char				  loaded;
@@ -190,7 +191,7 @@
   struct deferred_debug_info deefer;
   struct PE_Debug_dir	dinfo;
   struct CodeViewDebug cdebug;
-  struct pe_segment_table sects[10];
+  IMAGE_SECTION_HEADER  sects[10];
 
   memset(&deefer, 0, sizeof(deefer));
   memset(&dinfo, 0, sizeof(dinfo));
@@ -201,7 +202,7 @@
   dinfo.timestamp = 812932395;
   cdebug.cv_timestamp = 833392137  /* 841951397 */;
   deefer.dbgdir = &dinfo;
-  deefer.sectp = &sects;
+  deefer.sectp = sects;
   deefer.nsect = 10;
 
   DEBUG_InitTypes();
diff --git a/debugger/debug.l b/debugger/debug.l
index 5f6cce2..d33b4c0 100644
--- a/debugger/debug.l
+++ b/debugger/debug.l
@@ -113,7 +113,7 @@
 <INITIAL>list|lis|li|l			{ BEGIN(PATH_EXPECTED); return tLIST; }
 <INITIAL>enable|enabl|enab|ena		{ BEGIN(NOCMD); return tENABLE;}
 <INITIAL>disable|disabl|disab|disa|dis	{ BEGIN(NOCMD); return tDISABLE; }
-<INITIAL,INFO_CMD,DEL_CMD>display|displa|displ|disp	{ BEGIN(NOCMD); return tDISPLAY; }
+<INITIAL,INFO_CMD,DEL_CMD>display|displa|displ|disp	{ BEGIN(FORMAT_EXPECTED); return tDISPLAY; }
 <INITIAL>undisplay|undispla|undispl|undisp|undis|undi|und	{ BEGIN(NOCMD); return tUNDISPLAY; }
 <INITIAL>delete|delet|dele|del		{ BEGIN(DEL_CMD); return tDELETE; }
 <INITIAL>quit|qui|qu|q			{ BEGIN(NOCMD); return tQUIT; }
@@ -155,11 +155,22 @@
 <INITIAL,SHOW_CMD>directories|directorie|directori|director|directo|direct|direc|direc|dir { 
 			BEGIN(PATH_EXPECTED); return tDIR; }
 
+char					{ return tCHAR; }
+short					{ return tSHORT; }
+int					{ return tINT; }
+long					{ return tLONG; }
+float					{ return tFLOAT; }
+double					{ return tDOUBLE; }
+unsigned				{ return tUNSIGNED; }
+signed					{ return tSIGNED; }
+struct					{ return tSTRUCT; }
+union					{ return tUNION; }
+enum					{ return tENUM; }
+
 {IDENTIFIER}	{ yylval.string = make_symbol(yytext); return tIDENTIFIER; }
 
 <PATH_EXPECTED>{PATHNAME}	{ yylval.string = make_symbol(yytext); return tPATH; }
 
-
 [ \t]+        /* Eat up whitespace */
 
 .		{ if (syntax_error == 0)
diff --git a/debugger/display.c b/debugger/display.c
index b170026..fd7e8c6 100644
--- a/debugger/display.c
+++ b/debugger/display.c
@@ -20,10 +20,18 @@
 #include <stdarg.h>
 
 #define MAX_DISPLAY 25
-static struct expr * displaypoints[MAX_DISPLAY];
+
+struct display
+{
+  struct expr *	exp;
+  int		count;
+  char		format;
+};
+
+static struct display displaypoints[MAX_DISPLAY];
 
 int
-DEBUG_AddDisplay(struct expr * exp)
+DEBUG_AddDisplay(struct expr * exp, int count, char format)
 {
   int i;
 
@@ -32,9 +40,11 @@
    */
   for(i=0; i < MAX_DISPLAY; i++ )
     {
-      if( displaypoints[i] == NULL )
+      if( displaypoints[i].exp == NULL )
 	{
-	  displaypoints[i] = DEBUG_CloneExpr(exp);
+	  displaypoints[i].exp = DEBUG_CloneExpr(exp);
+	  displaypoints[i].count  = count;
+	  displaypoints[i].format = format;
 	  break;
 	}
     }
@@ -52,10 +62,10 @@
    */
   for(i=0; i < MAX_DISPLAY; i++ )
     {
-      if( displaypoints[i] != NULL )
+      if( displaypoints[i].exp != NULL )
 	{
 	  fprintf(stderr, "%d : ", i+1);
-	  DEBUG_DisplayExpr(displaypoints[i]);
+	  DEBUG_DisplayExpr(displaypoints[i].exp);
 	  fprintf(stderr, "\n");
 	}
     }
@@ -74,22 +84,33 @@
    */
   for(i=0; i < MAX_DISPLAY; i++ )
     {
-      if( displaypoints[i] != NULL )
+      if( displaypoints[i].exp != NULL )
 	{
-	  addr = DEBUG_EvalExpr(displaypoints[i]);
+	  addr = DEBUG_EvalExpr(displaypoints[i].exp);
 	  if( addr.type == NULL )
 	    {
 	      fprintf(stderr, "Unable to evaluate expression ");
-	      DEBUG_DisplayExpr(displaypoints[i]);
+	      DEBUG_DisplayExpr(displaypoints[i].exp);
 	      fprintf(stderr, "\nDisabling...\n");
 	      DEBUG_DelDisplay(i);
 	    }
 	  else
 	    {
 	      fprintf(stderr, "%d  : ", i + 1);
-	      DEBUG_DisplayExpr(displaypoints[i]);
+	      DEBUG_DisplayExpr(displaypoints[i].exp);
 	      fprintf(stderr, " = ");
-	      DEBUG_Print( &addr, 1, 0, 0);
+	      if( displaypoints[i].format == 'i' )
+		{
+		  DEBUG_ExamineMemory( &addr, 
+			       displaypoints[i].count, 
+			       displaypoints[i].format);
+		}
+	      else
+		{
+		  DEBUG_Print( &addr, 
+			       displaypoints[i].count, 
+			       displaypoints[i].format, 0);
+		}
 	    }
 	}
     }
@@ -111,17 +132,17 @@
     {
       for(i=0; i < MAX_DISPLAY; i++ )
 	{
-	  if( displaypoints[i] != NULL )
+	  if( displaypoints[i].exp != NULL )
 	    {
-	      DEBUG_FreeExpr(displaypoints[i]);
-	      displaypoints[i] = NULL;
+	      DEBUG_FreeExpr(displaypoints[i].exp);
+	      displaypoints[i].exp = NULL;
 	    }
 	}
     }
-  else if( displaypoints[displaynum - 1] != NULL )
+  else if( displaypoints[displaynum - 1].exp != NULL )
     {
-      DEBUG_FreeExpr(displaypoints[displaynum - 1]);
-      displaypoints[displaynum - 1] = NULL;
+      DEBUG_FreeExpr(displaypoints[displaynum - 1].exp);
+      displaypoints[displaynum - 1].exp = NULL;
     }
   return TRUE;
 }
diff --git a/debugger/expr.c b/debugger/expr.c
index 4bf78ef..6ef8d37 100644
--- a/debugger/expr.c
+++ b/debugger/expr.c
@@ -70,6 +70,12 @@
 
     struct
     {
+      struct datatype * cast;
+      struct expr     * expr;
+    } cast;
+
+    struct
+    {
       struct expr * exp1;
       const char * element_name;
       int result;
@@ -103,6 +109,7 @@
 #define EXPR_TYPE_ARRAY		8
 #define EXPR_TYPE_CALL		9
 #define EXPR_TYPE_STRING	10
+#define EXPR_TYPE_CAST		11
 
 static char expr_list[4096];
 static int next_expr_free = 0;
@@ -132,6 +139,18 @@
   next_expr_free = 0;
 }
 
+struct expr *
+DEBUG_TypeCastExpr(struct datatype * dt, struct expr * exp)
+{
+  struct expr * ex;
+
+  ex = DEBUG_GetFreeExpr();
+
+  ex->type        = EXPR_TYPE_CAST;
+  ex->un.cast.cast = dt;
+  ex->un.cast.expr = exp;
+  return ex;
+}
 
 struct expr *
 DEBUG_RegisterExpr(enum debug_regs regno)
@@ -294,6 +313,10 @@
 
   switch(exp->type)
     {
+    case EXPR_TYPE_CAST:
+      rtn = DEBUG_EvalExpr(exp->un.cast.expr);
+      rtn.type = exp->un.cast.cast;
+      break;
     case EXPR_TYPE_STRING:
       rtn.type = DEBUG_TypeString;
       rtn.off = (unsigned int) &exp->un.string.str;
@@ -620,6 +643,13 @@
 
   switch(exp->type)
     {
+    case EXPR_TYPE_CAST:
+      fprintf(stderr, "((");
+      DEBUG_PrintTypeCast(exp->un.cast.cast);
+      fprintf(stderr, ")");
+      DEBUG_DisplayExpr(exp->un.cast.expr);
+      fprintf(stderr, ")");
+      break;
     case EXPR_TYPE_REGISTER:
       DEBUG_PrintRegister(exp->un.rgister.reg);
       break;
@@ -780,6 +810,9 @@
 
   switch(exp->type)
     {
+    case EXPR_TYPE_CAST:
+      rtn->un.cast.expr = DEBUG_CloneExpr(exp->un.cast.expr);
+      break;
     case EXPR_TYPE_REGISTER:
     case EXPR_TYPE_US_CONST:
     case EXPR_TYPE_CONST:
@@ -834,6 +867,9 @@
 
   switch(exp->type)
     {
+    case EXPR_TYPE_CAST:
+      DEBUG_FreeExpr(exp->un.cast.expr);
+      break;
     case EXPR_TYPE_REGISTER:
     case EXPR_TYPE_US_CONST:
     case EXPR_TYPE_CONST:
diff --git a/debugger/hash.c b/debugger/hash.c
index 2684ea0..20f3e64 100644
--- a/debugger/hash.c
+++ b/debugger/hash.c
@@ -18,6 +18,9 @@
 #include "xmalloc.h"
 
 #define NR_NAME_HASH 16384
+#ifndef PATH_MAX
+#define PATH_MAX _MAX_PATH
+#endif
 
 static char * reg_name[] =
 {
diff --git a/debugger/info.c b/debugger/info.c
index 6c5f4de..dd5b76a 100644
--- a/debugger/info.c
+++ b/debugger/info.c
@@ -17,10 +17,10 @@
  */
 void DEBUG_PrintBasic( const DBG_ADDR *addr, int count, char format )
 {
-  char * default_format;
+  char        * default_format;
   long long int value;
 
-    if( addr->type == NULL )
+  if( addr->type == NULL )
     {
       fprintf(stderr, "Unable to evaluate expression\n");
       return;
@@ -32,16 +32,22 @@
   switch(format)
     {
     case 'x':
-      if (addr->seg) fprintf( stderr, "0x%04lx", (long unsigned int) value );
-      else fprintf( stderr, "0x%08lx", (long unsigned int) value );
+      if (addr->seg) 
+	{
+	  DEBUG_nchar += fprintf( stderr, "0x%04lx", (long unsigned int) value );
+	}
+      else 
+	{
+	  DEBUG_nchar += fprintf( stderr, "0x%08lx", (long unsigned int) value );
+	}
       break;
       
     case 'd':
-      fprintf( stderr, "%ld\n", (long int) value );
+      DEBUG_nchar += fprintf( stderr, "%ld\n", (long int) value );
       break;
       
     case 'c':
-      fprintf( stderr, "%d = '%c'",
+      DEBUG_nchar += fprintf( stderr, "%d = '%c'",
 	       (char)(value & 0xff), (char)(value & 0xff) );
       break;
       
@@ -53,11 +59,10 @@
     case 0:
       if( default_format != NULL )
 	{
-	  fprintf( stderr, default_format, value );
+	  DEBUG_nchar += fprintf( stderr, default_format, value );
 	}
       break;
     }
-
 }
 
 
diff --git a/debugger/msc.c b/debugger/msc.c
index 1c1817b..90bf0fd 100644
--- a/debugger/msc.c
+++ b/debugger/msc.c
@@ -512,9 +512,9 @@
 	char				* module_name;
 	char				* dbg_info;
 	int				  dbg_size;
-	struct PE_Debug_dir		* dbgdir;
+	LPIMAGE_DEBUG_DIRECTORY           dbgdir;
 	struct pe_data			* pe;
-        struct pe_segment_table         * sectp;
+        LPIMAGE_SECTION_HEADER	          sectp;
 	int				  nsect;
 	short int			  dbg_index;			
 	char				  loaded;
@@ -747,17 +747,24 @@
 	    }
 	  memset(symname, 0, sizeof(symname));
 	  memcpy(symname, type->structure.name, type->structure.namelen);
-	  typeptr = DEBUG_NewDataType(STRUCT, symname);
+	  if( strcmp(symname, "__unnamed") == 0 )
+	    {
+	      typeptr = DEBUG_NewDataType(STRUCT, NULL);
+	    }
+	  else
+	    {
+	      typeptr = DEBUG_NewDataType(STRUCT, symname);
+	    }
 	  cv_defined_types[curr_type - 0x1000] = typeptr;
 
 	  /*
 	   * Now copy the relevant bits from the fieldlist that we specified.
 	   */
 	  subtype = DEBUG_GetCVType(type->structure.fieldlist);
-	  DEBUG_SetStructSize(typeptr, type->structure.structlen);
 
 	  if( subtype != NULL )
 	    {
+	      DEBUG_SetStructSize(typeptr, type->structure.structlen);
 	      DEBUG_CopyFieldlist(typeptr, subtype);
 	    }
 	  break;
@@ -773,17 +780,26 @@
 	    }
 	  memset(symname, 0, sizeof(symname));
 	  memcpy(symname, type->t_union.name, type->t_union.namelen);
-	  typeptr = DEBUG_NewDataType(STRUCT, symname);
+
+	  if( strcmp(symname, "__unnamed") == 0 )
+	    {
+	      typeptr = DEBUG_NewDataType(STRUCT, NULL);
+	    }
+	  else
+	    {
+	      typeptr = DEBUG_NewDataType(STRUCT, symname);
+	    }
+
 	  cv_defined_types[curr_type - 0x1000] = typeptr;
 
 	  /*
 	   * Now copy the relevant bits from the fieldlist that we specified.
 	   */
 	  subtype = DEBUG_GetCVType(type->t_union.field);
-	  DEBUG_SetStructSize(typeptr, type->t_union.un_len);
 
 	  if( subtype != NULL )
 	    {
+	      DEBUG_SetStructSize(typeptr, type->t_union.un_len);
 	      DEBUG_CopyFieldlist(typeptr, subtype);
 	    }
 	  break;
@@ -874,14 +890,14 @@
   int			  has_codeview = FALSE;
   int			  rtn = FALSE;
   int			  orig_size;
-  struct PE_Debug_dir	* dbgptr;
+  LPIMAGE_DEBUG_DIRECTORY dbgptr;
   struct deferred_debug_info * deefer;
 
   orig_size = size;
-  dbgptr = (struct PE_Debug_dir *) (load_addr + v_addr);
+  dbgptr = (LPIMAGE_DEBUG_DIRECTORY) (load_addr + v_addr);
   for(; size > 0; size -= sizeof(*dbgptr), dbgptr++ )
     {
-      switch(dbgptr->type)
+      switch(dbgptr->Type)
 	{
 	case IMAGE_DEBUG_TYPE_CODEVIEW:
 	case IMAGE_DEBUG_TYPE_MISC:
@@ -891,10 +907,10 @@
     }
 
   size = orig_size;
-  dbgptr = (struct PE_Debug_dir *) (load_addr + v_addr);
+  dbgptr = (LPIMAGE_DEBUG_DIRECTORY) (load_addr + v_addr);
   for(; size > 0; size -= sizeof(*dbgptr), dbgptr++ )
     {
-      switch(dbgptr->type)
+      switch(dbgptr->Type)
 	{
 	case IMAGE_DEBUG_TYPE_COFF:
 	  /*
@@ -921,8 +937,8 @@
 	   * means that this entry points to a .DBG file.  Otherwise,
 	   * it just points to itself, and we can ignore this.
 	   */
-	  if(    (dbgptr->type == IMAGE_DEBUG_TYPE_MISC)
-	      && (pe->pe_header->coff.Characteristics & IMAGE_FILE_DEBUG_STRIPPED) == 0 )
+	  if(    (dbgptr->Type == IMAGE_DEBUG_TYPE_MISC)
+	      && (pe->pe_header->FileHeader.Characteristics & IMAGE_FILE_DEBUG_STRIPPED) == 0 )
 	    {
 	      break;
 	    }
@@ -938,9 +954,9 @@
 	   * upon the type, but this is always enough so we are able
 	   * to proceed if we know what we need to do next.
 	   */
-	  deefer->dbg_size = dbgptr->dbgsize;
-	  deefer->dbg_info = (char *) xmalloc(dbgptr->dbgsize);
-	  lseek(fd, dbgptr->dbgoff, SEEK_SET);
+	  deefer->dbg_size = dbgptr->SizeOfData;
+	  deefer->dbg_info = (char *) xmalloc(dbgptr->SizeOfData);
+	  lseek(fd, dbgptr->PointerToRawData, SEEK_SET);
 	  read(fd, deefer->dbg_info, deefer->dbg_size);
 
 	  deefer->load_addr = (char *) load_addr;
@@ -951,7 +967,7 @@
 	  deefer->module_name = xstrdup(DEBUG_curr_module);
 
 	  deefer->sectp = pe->pe_seg;
-	  deefer->nsect = pe->pe_header->coff.NumberOfSections;
+	  deefer->nsect = pe->pe_header->FileHeader.NumberOfSections;
 
 	  dbglist = deefer;
 	  break;
@@ -1538,7 +1554,7 @@
   DBG_ADDR		  new_addr;
   int			  nsect;
   union any_size	  ptr;
-  struct pe_segment_table * sectp;
+  IMAGE_SECTION_HEADER  * sectp;
   union	codeview_symbol	* sym;
   char			  symname[PATH_MAX];
   struct name_hash	* thunk_sym = NULL;
@@ -1601,7 +1617,7 @@
 	  new_addr.seg = 0;
 	  new_addr.type = DEBUG_GetCVType(sym->data.symtype);
 	  new_addr.off = (unsigned int) deefer->load_addr + 
-	    sectp[sym->data.seg - 1].Virtual_Address + 
+	    sectp[sym->data.seg - 1].VirtualAddress + 
 	    sym->data.offset;
 	  DEBUG_AddSymbol( symname, &new_addr, NULL, SYM_WIN32 | SYM_DATA );
 	  break;
@@ -1615,7 +1631,7 @@
 	  new_addr.seg = 0;
 	  new_addr.type = NULL;
 	  new_addr.off = (unsigned int) deefer->load_addr + 
-	    sectp[sym->thunk.segment - 1].Virtual_Address + 
+	    sectp[sym->thunk.segment - 1].VirtualAddress + 
 	    sym->thunk.offset;
 	  thunk_sym = DEBUG_AddSymbol( symname, &new_addr, NULL, 
 				       SYM_WIN32 | SYM_FUNC);
@@ -1630,7 +1646,7 @@
 	  new_addr.seg = 0;
 	  new_addr.type = DEBUG_GetCVType(sym->proc.proctype);
 	  new_addr.off = (unsigned int) deefer->load_addr + 
-	    sectp[sym->proc.segment - 1].Virtual_Address + 
+	    sectp[sym->proc.segment - 1].VirtualAddress + 
 	    sym->proc.offset;
 	  /*
 	   * See if we can find a segment that this goes with.  If so,
@@ -1640,10 +1656,10 @@
 	  for(i=0; linetab[i].linetab != NULL; i++)
 	    {
 	      if(     ((unsigned int) deefer->load_addr 
-		       + sectp[linetab[i].segno - 1].Virtual_Address 
+		       + sectp[linetab[i].segno - 1].VirtualAddress 
 		       + linetab[i].start <= new_addr.off)
 		  &&  ((unsigned int) deefer->load_addr 
-		       + sectp[linetab[i].segno - 1].Virtual_Address 
+		       + sectp[linetab[i].segno - 1].VirtualAddress 
 		       + linetab[i].end > new_addr.off) )
 		{
 		  break;
@@ -2119,8 +2135,8 @@
   int				j;
   struct codeview_linetab_hdr * linetab;
   int				nsect;
-  struct PE_DBG_FileHeader    * pdbg = NULL;
-  struct pe_segment_table     * sectp;
+  LPIMAGE_SEPARATE_DEBUG_HEADER pdbg = NULL;
+  IMAGE_SECTION_HEADER        * sectp;
   struct stat			statbuf;
   int				status;
   
@@ -2148,9 +2164,9 @@
   addr = mmap(0, statbuf.st_size, PROT_READ, 
 	      MAP_PRIVATE, fd, 0);
 
-  pdbg = (struct PE_DBG_FileHeader *) addr;
+  pdbg = (LPIMAGE_SEPARATE_DEBUG_HEADER) addr;
 
-  if( pdbg->TimeDateStamp != deefer->dbgdir->timestamp )
+  if( pdbg->TimeDateStamp != deefer->dbgdir->TimeDateStamp )
     {
       fprintf(stderr, "Warning - %s has incorrect internal timestamp\n",
 	      filename);
@@ -2160,10 +2176,10 @@
   fprintf(stderr, "Processing symbols from %s...\n", filename);
 
   dbghdr = (struct PE_Debug_dir *) (  addr + sizeof(*pdbg) 
-		 + pdbg->NumberOfSections * sizeof(struct pe_segment_table) 
+		 + pdbg->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) 
 		 + pdbg->ExportedNamesSize);
 
-  sectp = (struct pe_segment_table *) ((char *) pdbg + sizeof(*pdbg));
+  sectp = (LPIMAGE_SECTION_HEADER) ((char *) pdbg + sizeof(*pdbg));
   nsect = pdbg->NumberOfSections;
 
   for( i=0; i < pdbg->DebugDirectorySize / sizeof(*pdbg); i++, dbghdr++ )
@@ -2300,7 +2316,7 @@
 	  last_proc = deefer->dbg_index;
 	}
 
-      switch(deefer->dbgdir->type)
+      switch(deefer->dbgdir->Type)
 	{
 	case IMAGE_DEBUG_TYPE_COFF:
 	  /*
diff --git a/debugger/registers.c b/debugger/registers.c
index 7c68f6a..5ed74dd 100644
--- a/debugger/registers.c
+++ b/debugger/registers.c
@@ -188,7 +188,7 @@
 #ifdef GS_sig
     GS_sig(sigcontext)  = GS_reg(&DEBUG_context);
 #else
-    __asm__("movw %w0,%%gs"::"r" (FS_reg(&DEBUG_context)));
+    __asm__("movw %w0,%%gs"::"r" (GS_reg(&DEBUG_context)));
 #endif
 }
 
diff --git a/debugger/source.c b/debugger/source.c
index d80d386..4ece937 100644
--- a/debugger/source.c
+++ b/debugger/source.c
@@ -93,7 +93,7 @@
 }
 
 static
-void
+int
 DEBUG_DisplaySource(char * sourcefile, int start, int end)
 {
   char			      * addr;
@@ -103,6 +103,7 @@
   struct open_filelist	      * ol;
   int				nlines;
   char			      * pnt;
+  int				rtn;
   struct searchlist	      * sl;
   struct stat			statbuf;
   int				status;
@@ -217,7 +218,7 @@
 		  ol->linelist = NULL;
 		  ofiles = ol;
 		  fprintf(stderr,"Unable to open file %s\n", tmppath);
-		  return;
+		  return FALSE;
 		}
 	    }
 	}
@@ -239,13 +240,13 @@
       fd = open(tmppath, O_RDONLY);
       if( fd == -1 )
 	{
-	  return;
+	  return FALSE;
 	}
 
       addr = mmap(0, statbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
       if( addr == (char *) -1 )
 	{
-	  return;
+	  return FALSE;
 	}
 
       /*
@@ -285,19 +286,20 @@
       fd = open(ol->real_path, O_RDONLY);
       if( fd == -1 )
 	{
-	  return;
+	  return FALSE;
 	}
       
       addr = mmap(0, ol->size, PROT_READ, MAP_PRIVATE, fd, 0);
       if( addr == (char *) -1 )
 	{
-	  return;
+	  return FALSE;
 	}
     }
   
   /*
    * All we need to do is to display the source lines here.
    */
+  rtn = FALSE;
   for(i=start - 1; i <= end - 1; i++)
     {
       if( i < 0 || i >= ol->nlines - 1)
@@ -305,6 +307,7 @@
 	  continue;
 	}
 
+      rtn = TRUE;
       memset(&buffer, 0, sizeof(buffer));
       if( ol->linelist[i+1] != ol->linelist[i] )
 	{
@@ -317,6 +320,8 @@
   munmap(addr, ol->size);
   close(fd);
 
+  return rtn;
+
 }
 
 void
@@ -324,6 +329,7 @@
 			 int delta)
 {
   int    end;
+  int    rtn;
   int    start;
   char * sourcefile;
 
@@ -406,7 +412,7 @@
   /*
    * Now call this function to do the dirty work.
    */
-  DEBUG_DisplaySource(sourcefile, start, end);
+  rtn = DEBUG_DisplaySource(sourcefile, start, end);
 
   if( sourcefile != (char *) &DEBUG_current_sourcefile )
     {
diff --git a/debugger/stabs.c b/debugger/stabs.c
index 0c1ddf1..a52c467 100644
--- a/debugger/stabs.c
+++ b/debugger/stabs.c
@@ -75,6 +75,44 @@
   unsigned long n_value;
 };
 
+/*
+ * This is used to keep track of known datatypes so that we don't redefine
+ * them over and over again.  It sucks up lots of memory otherwise.
+ */
+struct known_typedef
+{
+  struct known_typedef * next;
+  char		       * name;
+  int			 ndefs;
+  struct datatype      * types[0];
+};
+
+#define NR_STAB_HASH 521
+
+struct known_typedef * ktd_head[NR_STAB_HASH];
+
+static unsigned int stab_hash( const char * name )
+{
+    unsigned int hash = 0;
+    unsigned int tmp;
+    const char * p;
+
+    p = name;
+
+    while (*p) 
+      {
+	hash = (hash << 4) + *p++;
+
+	if( (tmp = (hash & 0xf0000000)) )
+	  {
+	    hash ^= tmp >> 24;
+	  }
+	hash &= ~tmp;
+      }
+    return hash % NR_STAB_HASH;
+}
+
+
 static void stab_strcpy(char * dest, const char * source)
 {
   /*
@@ -89,6 +127,179 @@
   *dest++ = '\0';
 }
 
+#define MAX_TD_NESTING	128
+
+static
+int
+DEBUG_RegisterTypedef(const char * name, struct datatype ** types, int ndef)
+{
+  int			 hash;
+  struct known_typedef * ktd;
+
+  if( ndef == 1 )
+    {
+      return TRUE;
+    }
+
+  ktd = (struct known_typedef *) malloc(sizeof(struct known_typedef) 
+					+ ndef * sizeof(struct datatype *));
+  
+  hash = stab_hash(name);
+
+  ktd->name = xstrdup(name);
+  ktd->ndefs = ndef;
+  memcpy(&ktd->types[0], types, ndef * sizeof(struct datatype *));
+  ktd->next = ktd_head[hash];
+  ktd_head[hash] = ktd;
+
+  return TRUE;
+}
+
+static
+int
+DEBUG_HandlePreviousTypedef(const char * name, const char * stab)
+{
+  int			 count;
+  enum debug_type	 expect;
+  int			 hash;
+  struct known_typedef * ktd;
+  char		       * ptr;
+  char		       * tc;
+  int			 typenum;
+
+  hash = stab_hash(name);
+
+  for(ktd = ktd_head[hash]; ktd; ktd = ktd->next)
+    {
+      if(    (ktd->name[0] == name[0])
+	  && (strcmp(name, ktd->name) == 0) )
+	{
+	  break;
+	}
+    }
+
+  /*
+   * Didn't find it.  This must be a new one.
+   */
+  if( ktd == NULL )
+    {
+      return FALSE;
+    }
+
+  /*
+   * Examine the stab to make sure it has the same number of definitions.
+   */
+  count = 0;
+  for(ptr = strchr(stab, '='); ptr; ptr = strchr(ptr+1, '='))
+    {
+      if( count >= ktd->ndefs )
+	{
+	  return FALSE;
+	}
+
+      /*
+       * Make sure the types of all of the objects is consistent with
+       * what we have already parsed.
+       */
+      switch(ptr[1])
+	{
+	case '*':
+	  expect = POINTER;
+	  break;
+	case 's':
+	case 'u':
+	  expect = STRUCT;
+	  break;
+	case 'a':
+	  expect = ARRAY;
+	  break;
+	case '1':
+	case 'r':
+	  expect = BASIC;
+	  break;
+	case 'x':
+	  expect = STRUCT;
+	  break;
+	case 'e':
+	  expect = ENUM;
+	  break;
+	case 'f':
+	  expect = FUNC;
+	  break;
+	default:
+	  fprintf(stderr, "Unknown type.\n");
+          return FALSE;
+	}
+      if( expect != DEBUG_GetType(ktd->types[count]) )
+	{
+	  return FALSE;
+	}
+      count++;
+    }
+
+  if( ktd->ndefs != count )
+    {
+      return FALSE;
+    }
+
+  /*
+   * OK, this one is safe.  Go through, dig out all of the type numbers,
+   * and substitute the appropriate things.
+   */
+  count = 0;
+  for(ptr = strchr(stab, '='); ptr; ptr = strchr(ptr+1, '='))
+    {
+      /*
+       * Back up until we get to a non-numeric character.  This is the type
+       * number.
+       */
+      tc = ptr - 1;
+      while( *tc >= '0' && *tc <= '9' )
+	{
+	  tc--;
+	}
+      
+      typenum = atol(tc + 1);
+      if( num_stab_types <= typenum )
+	{
+	  num_stab_types = typenum + 32;
+	  stab_types = (struct datatype **) xrealloc(stab_types, 
+						     num_stab_types * sizeof(struct datatype *));
+	  if( stab_types == NULL )
+	    {
+	      return FALSE;
+	    }
+	}
+
+      stab_types[typenum] = ktd->types[count++];
+    }
+
+  return TRUE;
+}
+
+static int DEBUG_FreeRegisteredTypedefs()
+{
+  int			 count;
+  int			 j;
+  struct known_typedef * ktd;
+  struct known_typedef * next;
+
+  count = 0;
+  for(j=0; j < NR_STAB_HASH; j++ )
+    {
+      for(ktd = ktd_head[j]; ktd; ktd = next)
+	{
+	  count++;
+	  next = ktd->next;
+	  free(ktd->name);
+	  free(ktd);
+	}  
+      ktd_head[j] = NULL;
+    }
+
+  return TRUE;
+
+}
 
 static 
 int
@@ -96,21 +307,33 @@
 {
   int		    arrmax;
   int		    arrmin;
-  char * c;
+  char		  * c;
   struct datatype * curr_type;
   struct datatype * datatype;
+  struct datatype * curr_types[MAX_TD_NESTING];
   char	            element_name[1024];
+  int		    ntypes = 0;
   int		    offset;
+  const char	  * orig_typename;
   int		    rtn = FALSE;
   int		    size;
   char		  * tc;
   char		  * tc2;
   int		    typenum;
 
-  /*
-   * Go from back to front.  First we go through and figure out what type numbers
-   * we need, and register those types.  Then we go in and fill the details.
+  orig_typename = typename;
+
+  if( DEBUG_HandlePreviousTypedef(typename, ptr) == TRUE )
+    {
+      return TRUE;
+    }
+
+  /* 
+   * Go from back to front.  First we go through and figure out what
+   * type numbers we need, and register those types.  Then we go in
+   * and fill the details.  
    */
+
   for( c = strchr(ptr, '='); c != NULL; c = strchr(c + 1, '=') )
     {
       /*
@@ -134,31 +357,47 @@
 	    }
 	}
 
+      if( ntypes >= MAX_TD_NESTING )
+	{
+	  /*
+	   * If this ever happens, just bump the counter.
+	   */
+	  fprintf(stderr, "Typedef nesting overflow\n");
+	  return FALSE;
+	}
+
       switch(c[1])
 	{
 	case '*':
 	  stab_types[typenum] = DEBUG_NewDataType(POINTER, NULL);
+	  curr_types[ntypes++] = stab_types[typenum];
 	  break;
 	case 's':
 	case 'u':
 	  stab_types[typenum] = DEBUG_NewDataType(STRUCT, typename);
+	  curr_types[ntypes++] = stab_types[typenum];
 	  break;
 	case 'a':
 	  stab_types[typenum] = DEBUG_NewDataType(ARRAY, NULL);
+	  curr_types[ntypes++] = stab_types[typenum];
 	  break;
 	case '1':
 	case 'r':
 	  stab_types[typenum] = DEBUG_NewDataType(BASIC, typename);
+	  curr_types[ntypes++] = stab_types[typenum];
 	  break;
 	case 'x':
 	  stab_strcpy(element_name, c + 3);
 	  stab_types[typenum] = DEBUG_NewDataType(STRUCT, element_name);
+	  curr_types[ntypes++] = stab_types[typenum];
 	  break;
 	case 'e':
 	  stab_types[typenum] = DEBUG_NewDataType(ENUM, NULL);
+	  curr_types[ntypes++] = stab_types[typenum];
 	  break;
 	case 'f':
 	  stab_types[typenum] = DEBUG_NewDataType(FUNC, NULL);
+	  curr_types[ntypes++] = stab_types[typenum];
 	  break;
 	default:
 	  fprintf(stderr, "Unknown type.\n");
@@ -166,154 +405,184 @@
       typename = NULL;
     }
 
-     /*
-      * OK, now take a second sweep through.  Now we will be digging out the definitions
-      * of the various components, and storing them in the skeletons that we have already
-      * allocated.  We take a right-to left search as this is much easier to parse.
-      */
-  for( c = strrchr(ptr, '='); c != NULL; c = strrchr(ptr, '=') )
-    {
       /*
-       * Back up until we get to a non-numeric character.  This is the type
-       * number.
-       */
-      tc = c - 1;
-      while( *tc >= '0' && *tc <= '9' )
-	{
-	  tc--;
-	}
-      typenum = atol(tc + 1);
-      curr_type = stab_types[typenum];
+      * Now register the type so that if we encounter it again, we will know
+      * what to do.
+      */
+     DEBUG_RegisterTypedef(orig_typename, curr_types, ntypes);
 
-      switch(c[1])
-	{
-	case 'x':
-	  tc = c + 3;
-	  while( *tc != ':' )
-	    {
-	      tc ++;
-	    }
-	  tc++;
-	  if( *tc == '\0' )
-	    {
-	      *c = '\0';
-	    }
-	  else
-	    {
-	      strcpy(c, tc);
-	    }
+     /* 
+      * OK, now take a second sweep through.  Now we will be digging
+      * out the definitions of the various components, and storing
+      * them in the skeletons that we have already allocated.  We take
+      * a right-to left search as this is much easier to parse.  
+      */
+     for( c = strrchr(ptr, '='); c != NULL; c = strrchr(ptr, '=') )
+       {
+	 /*
+	  * Back up until we get to a non-numeric character.  This is the type
+	  * number.
+	  */
+	 tc = c - 1;
+	 while( *tc >= '0' && *tc <= '9' )
+	   {
+	     tc--;
+	   }
+	 typenum = atol(tc + 1);
+	 curr_type = stab_types[typenum];
+	 
+	 switch(c[1])
+	   {
+	   case 'x':
+	     tc = c + 3;
+	     while( *tc != ':' )
+	       {
+		 tc ++;
+	       }
+	     tc++;
+	     if( *tc == '\0' )
+	       {
+		 *c = '\0';
+	       }
+	     else
+	       {
+		 strcpy(c, tc);
+	       }
+	     
+	     break;
+	   case '*':
+	   case 'f':
+	     tc = c + 2;
+	     datatype = stab_types[strtol(tc, &tc, 10)];
+	     DEBUG_SetPointerType(curr_type, datatype);
+	     if( *tc == '\0' )
+	       {
+		 *c = '\0';
+	       }
+	     else
+	       {
+		 strcpy(c, tc);
+	       }
+	     break;
+	   case '1':
+	   case 'r':
+	     /*
+	      * We have already handled these above.
+	      */
+	     *c = '\0';
+	     break;
+	   case 'a':
+	     tc  = c + 5;
+	     arrmin = strtol(tc, &tc, 10);
+	     tc++;
+	     arrmax = strtol(tc, &tc, 10);
+	     tc++;
+	     datatype = stab_types[strtol(tc, &tc, 10)];
+	     if( *tc == '\0' )
+	       {
+		 *c = '\0';
+	       }
+	     else
+	       {
+		 strcpy(c, tc);
+	       }
+	     
+	     DEBUG_SetArrayParams(curr_type, arrmin, arrmax, datatype);
+	     break;
+	   case 's':
+	   case 'u':
+	     tc = c + 2;
+	     if( DEBUG_SetStructSize(curr_type, strtol(tc, &tc, 10)) == FALSE )
+	       {
+		 /*
+		  * We have already filled out this structure.  Nothing to do,
+		  * so just skip forward to the end of the definition.
+		  */
+		 while( tc[0] != ';' && tc[1] != ';' )
+		   {
+		     tc++;
+		   }
+		 
+		 tc += 2;
+		 
+		 if( *tc == '\0' )
+		   {
+		     *c = '\0';
+		   }
+		 else
+		   {
+		     strcpy(c, tc + 1);
+		   }
+		 continue;
+	       }
 
-	  break;
-	case '*':
-	case 'f':
-	  tc = c + 2;
-	  datatype = stab_types[strtol(tc, &tc, 10)];
-	  DEBUG_SetPointerType(curr_type, datatype);
-	  if( *tc == '\0' )
-	    {
-	      *c = '\0';
-	    }
-	  else
-	    {
-	      strcpy(c, tc);
-	    }
-	  break;
-	case '1':
-	case 'r':
-	  /*
-	   * We have already handled these above.
-	   */
-	  *c = '\0';
-	  break;
-	case 'a':
-	  tc  = c + 5;
- 	  arrmin = strtol(tc, &tc, 10);
-	  tc++;
- 	  arrmax = strtol(tc, &tc, 10);
-	  tc++;
-	  datatype = stab_types[strtol(tc, &tc, 10)];
-	  if( *tc == '\0' )
-	    {
-	      *c = '\0';
-	    }
-	  else
-	    {
-	      strcpy(c, tc);
-	    }
-	  
-	  DEBUG_SetArrayParams(curr_type, arrmin, arrmax, datatype);
-	  break;
-	case 's':
-	case 'u':
-	  tc = c + 2;
-	  DEBUG_SetStructSize(curr_type, strtol(tc, &tc, 10));
-	  /*
-	   * Now parse the individual elements of the structure/union.
-	   */
-	  while(*tc != ';')
-	    {
-	      tc2 = element_name;
-	      while(*tc != ':')
-		{
-		  *tc2++ = *tc++;
-		}
-	      tc++;
-	      *tc2++ = '\0';
-	      datatype = stab_types[strtol(tc, &tc, 10)];
-	      tc++;
-	      offset  = strtol(tc, &tc, 10);
-	      tc++;
-	      size  = strtol(tc, &tc, 10);
-	      tc++;
-	      DEBUG_AddStructElement(curr_type, element_name, datatype, offset, size);
-	    }
-	  if( *tc == '\0' )
-	    {
-	      *c = '\0';
-	    }
-	  else
-	    {
-	      strcpy(c, tc + 1);
-	    }
-	  break;
-	case 'e':
-	  tc = c + 2;
-	  /*
-	   * Now parse the individual elements of the structure/union.
-	   */
-	  while(*tc != ';')
-	    {
-	      tc2 = element_name;
-	      while(*tc != ':')
-		{
-		  *tc2++ = *tc++;
-		}
-	      tc++;
-	      *tc2++ = '\0';
-	      offset  = strtol(tc, &tc, 10);
-	      tc++;
-	      DEBUG_AddStructElement(curr_type, element_name, NULL, offset, 0);
-	    }
-	  if( *tc == '\0' )
-	    {
-	      *c = '\0';
-	    }
-	  else
-	    {
-	      strcpy(c, tc + 1);
-	    }
-	  break;
-	default:
-	  fprintf(stderr, "Unknown type.\n");
-	  break;
-	}
-    }
-
-  rtn = TRUE;
-
+	     /*
+	      * Now parse the individual elements of the structure/union.
+	      */
+	     while(*tc != ';')
+	       {
+		 tc2 = element_name;
+		 while(*tc != ':')
+		   {
+		     *tc2++ = *tc++;
+		   }
+		 tc++;
+		 *tc2++ = '\0';
+		 datatype = stab_types[strtol(tc, &tc, 10)];
+		 tc++;
+		 offset  = strtol(tc, &tc, 10);
+		 tc++;
+		 size  = strtol(tc, &tc, 10);
+		 tc++;
+		 DEBUG_AddStructElement(curr_type, element_name, datatype, offset, size);
+	       }
+	     if( *tc == '\0' )
+	       {
+		 *c = '\0';
+	       }
+	     else
+	       {
+		 strcpy(c, tc + 1);
+	       }
+	     break;
+	   case 'e':
+	     tc = c + 2;
+	     /*
+	      * Now parse the individual elements of the structure/union.
+	      */
+	     while(*tc != ';')
+	       {
+		 tc2 = element_name;
+		 while(*tc != ':')
+		   {
+		     *tc2++ = *tc++;
+		   }
+		 tc++;
+		 *tc2++ = '\0';
+		 offset  = strtol(tc, &tc, 10);
+		 tc++;
+		 DEBUG_AddStructElement(curr_type, element_name, NULL, offset, 0);
+	       }
+	     if( *tc == '\0' )
+	       {
+		 *c = '\0';
+	       }
+	     else
+	       {
+		 strcpy(c, tc + 1);
+	       }
+	     break;
+	   default:
+	     fprintf(stderr, "Unknown type.\n");
+	     break;
+	   }
+       }
+     
+     rtn = TRUE;
+     
 leave:
-
-  return rtn;
+     
+     return rtn;
 
 }
 
@@ -676,6 +945,9 @@
       num_stab_types = 0;
     }
 
+
+  DEBUG_FreeRegisteredTypedefs();
+
   return TRUE;
 }
 
diff --git a/debugger/types.c b/debugger/types.c
index 581d096..0b26d50 100644
--- a/debugger/types.c
+++ b/debugger/types.c
@@ -11,8 +11,11 @@
 #include <stdlib.h>
 
 #include <assert.h>
+#ifndef __EMX__
 #include <sys/mman.h>
+#endif
 #include <fcntl.h>
+#include <sys/types.h>
 #include <sys/stat.h>
 #include <limits.h>
 #include <strings.h>
@@ -28,6 +31,9 @@
 
 #define NR_TYPE_HASH 521
 
+int		  DEBUG_nchar;
+static int	  DEBUG_maxchar = 1024;
+
 struct en_values
 {
   struct en_values* next;
@@ -177,6 +183,32 @@
   return dt;
 }
 
+static
+struct datatype *
+DEBUG_LookupDataType(enum debug_type xtype, int hash, const char * typename)
+{
+  struct datatype * dt = NULL;
+
+  if( typename != NULL )
+    {
+      for( dt = type_hash_table[hash]; dt; dt = dt->next )
+	{
+	  if( xtype != dt->type || dt->name == NULL 
+	      || dt->name[0] != typename[0])
+	    {
+	      continue;
+	    }
+	  	  
+	  if( strcmp(dt->name, typename) == 0 )
+	    {
+	      return dt;
+	    }
+	}
+    }
+
+  return dt;
+}
+
 struct datatype *
 DEBUG_NewDataType(enum debug_type xtype, const char * typename)
 {
@@ -195,22 +227,7 @@
       hash = type_hash(typename);
     }
 
-  if( typename != NULL )
-    {
-      for( dt = type_hash_table[hash]; dt; dt = dt->next )
-	{
-	  if( xtype != dt->type || dt->name == NULL 
-	      || dt->name[0] != typename[0])
-	    {
-	      continue;
-	    }
-	  	  
-	  if( strcmp(dt->name, typename) == 0 )
-	    {
-	      return dt;
-	    }
-	}
-    }
+  dt = DEBUG_LookupDataType(xtype, hash, typename);
 
   if( dt == NULL )
     {
@@ -347,6 +364,11 @@
   switch(addr->type->type)
     {
     case BASIC:
+      if (!DBG_CHECK_READ_PTR( addr,  addr->type->un.basic.basic_size)) 
+	{
+	  return 0;
+	}
+
       memcpy(&rtn, (char *) addr->off, addr->type->un.basic.basic_size);
       if(    (addr->type->un.basic.b_signed)
 	  && ((addr->type->un.basic.basic_size & 3) != 0)
@@ -495,6 +517,12 @@
 DEBUG_SetStructSize(struct datatype * dt, int size)
 {
   assert(dt->type == STRUCT);
+
+  if( dt->un.structure.members != NULL )
+    {
+      return FALSE;
+    }
+
   dt->un.structure.size = size;
   dt->un.structure.members = NULL;
 
@@ -710,7 +738,8 @@
  *
  * Implementation of the 'print' command.
  */
-void DEBUG_Print( const DBG_ADDR *addr, int count, char format, int level )
+void
+DEBUG_Print( const DBG_ADDR *addr, int count, char format, int level )
 {
   DBG_ADDR	  addr1;
   int		  i;
@@ -728,9 +757,20 @@
   if( addr->type == NULL )
     {
       fprintf(stderr, "Unable to evaluate expression\n");
-      return;
+      goto leave;
     }
   
+  if( level == 0 )
+    {
+      DEBUG_nchar = 0;
+    }
+
+  if( DEBUG_nchar > DEBUG_maxchar )
+    {
+      fprintf(stderr, "...");
+      goto leave;
+    }
+
   if( format == 'i' || format == 's' || format == 'w' || format == 'b' )
     {
       fprintf( stderr, "Format specifier '%c' is meaningless in 'print' command\n", format );
@@ -746,20 +786,25 @@
       DEBUG_PrintBasic(addr, 1, format);
       break;
     case STRUCT:
-      fprintf(stderr, "{");
+      DEBUG_nchar += fprintf(stderr, "{");
       for(m = addr->type->un.structure.members; m; m = m->next)
 	{
 	  addr1 = *addr;
 	  DEBUG_FindStructElement(&addr1, m->name,
 				  (int *) &value);
-	  fprintf(stderr, "%s=", m->name);
+	  DEBUG_nchar += fprintf(stderr, "%s=", m->name);
 	  DEBUG_Print(&addr1, 1, format, level + 1);
 	  if( m->next != NULL )
 	    {
-	      fprintf(stderr, ", ");
+	      DEBUG_nchar += fprintf(stderr, ", ");
+	    }
+	  if( DEBUG_nchar > DEBUG_maxchar )
+	    {
+	      fprintf(stderr, "...}");
+	      goto leave;
 	    }
 	}
-      fprintf(stderr, "}");
+      DEBUG_nchar += fprintf(stderr, "}");
       break;
     case ARRAY:
       /*
@@ -772,28 +817,39 @@
 	   * Special handling for character arrays.
 	   */
 	  pnt = (char *) addr->off;
-	  fprintf(stderr, "\"");
+	  DEBUG_nchar += fprintf(stderr, "\"");
 	  for( i=addr->type->un.array.start; i < addr->type->un.array.end; i++ )
 	    {
 	      fputc(*pnt++, stderr);
+	      DEBUG_nchar++;
+	      if( DEBUG_nchar > DEBUG_maxchar )
+		{
+		  fprintf(stderr, "...\"");
+		  goto leave;
+		}
 	    }
-	  fprintf(stderr, "\"");
+	  DEBUG_nchar += fprintf(stderr, "\"");
 	  break;
 	}
       addr1 = *addr;
       addr1.type = addr->type->un.array.basictype;
-      fprintf(stderr, "{");
+      DEBUG_nchar += fprintf(stderr, "{");
       for( i=addr->type->un.array.start; i <= addr->type->un.array.end; i++ )
 	{
 	  DEBUG_Print(&addr1, 1, format, level + 1);
 	  addr1.off += size;
 	  if( i == addr->type->un.array.end )
 	    {
-	      fprintf(stderr, "}");
+	      DEBUG_nchar += fprintf(stderr, "}");
 	    }
 	  else
 	    {
-	      fprintf(stderr, ", ");
+	      DEBUG_nchar += fprintf(stderr, ", ");
+	    }
+	  if( DEBUG_nchar > DEBUG_maxchar )
+	    {
+	      fprintf(stderr, "...}");
+	      goto leave;
 	    }
 	}
       break;
@@ -802,8 +858,157 @@
       break;
     }
 
+leave:
+
   if( level == 0 )
     {
-      fprintf(stderr, "\n");
+      DEBUG_nchar += fprintf(stderr, "\n");
     }
+  return;
 }
+
+int
+DEBUG_DumpTypes()
+{
+  struct datatype * dt = NULL;
+  struct member * m;
+  int hash;
+  int nm;
+  char * name;
+  char * member_name;
+
+  for(hash = 0; hash < NR_TYPE_HASH + 1; hash++)
+    {
+      for( dt = type_hash_table[hash]; dt; dt = dt->next )
+	{
+	  name =  "none";
+	  if( dt->name != NULL )
+	    {
+	      name = dt->name;
+	    }
+	  switch(dt->type)
+	    {
+	    case BASIC:
+	      fprintf(stderr, "0x%p - BASIC(%s)\n",
+		      dt, name);
+	      break;
+	    case POINTER:
+	      fprintf(stderr, "0x%p - POINTER(%s)(%p)\n",
+		      dt, name, dt->un.pointer.pointsto);
+	      break;
+	    case STRUCT:
+	      member_name = "none";
+	      nm = 0;
+	      if( dt->un.structure.members != NULL
+		  && dt->un.structure.members->name != NULL )
+		{
+		  member_name = dt->un.structure.members->name;
+		  for( m = dt->un.structure.members; m; m = m->next)
+		    {
+		      nm++;
+		    }
+		}
+	      fprintf(stderr, "0x%p - STRUCT(%s) %d %d %s\n", dt, name,
+		      dt->un.structure.size, nm, member_name);
+	      break;
+	    case ARRAY:
+	      fprintf(stderr, "0x%p - ARRAY(%s)(%p)\n",
+		      dt, name, dt->un.array.basictype);
+	      break;
+	    case ENUM:
+	      fprintf(stderr, "0x%p - ENUM(%s)\n",
+		      dt, name);
+	      break;
+	    case BITFIELD:
+	      fprintf(stderr, "0x%p - BITFIELD(%s)\n", dt, name);
+	      break;
+	    case FUNC:
+	      fprintf(stderr, "0x%p - FUNC(%s)(%p)\n",
+		      dt, name, dt->un.funct.rettype);
+	      break;
+	    case CONST:
+	    case TYPEDEF:
+	      fprintf(stderr, "What???\n");
+	      break;
+	    }
+	}
+    }
+  return TRUE;
+}
+
+
+enum debug_type DEBUG_GetType(struct datatype * dt)
+{
+  return dt->type;
+}
+
+struct datatype *
+DEBUG_TypeCast(enum debug_type type, const char * name)
+{
+  int			  hash;
+  struct datatype	* rtn;
+
+  /*
+   * The last bucket is special, and is used to hold typeless names.
+   */
+  if( name == NULL )
+    {
+      hash = NR_TYPE_HASH;
+    }
+  else
+    {
+      hash = type_hash(name);
+    }
+
+  rtn = DEBUG_LookupDataType(type, hash, name);
+
+  return rtn;
+
+}
+
+int
+DEBUG_PrintTypeCast(struct datatype * dt)
+{
+  char		* name;
+
+  name =  "none";
+  if( dt->name != NULL )
+    {
+      name = dt->name;
+    }
+
+  switch(dt->type)
+    {
+    case BASIC:
+      fprintf(stderr, "%s", name);
+      break;
+    case POINTER:
+      DEBUG_PrintTypeCast(dt->un.pointer.pointsto);
+      fprintf(stderr, "*");
+      break;
+    case STRUCT:
+      fprintf(stderr, "struct %s", name);
+      break;
+    case ARRAY:
+      fprintf(stderr, "%s[]", name);
+      break;
+    case ENUM:
+      fprintf(stderr, "enum %s", name);
+      break;
+    case BITFIELD:
+      fprintf(stderr, "unsigned %s", name);
+      break;
+    case FUNC:
+      DEBUG_PrintTypeCast(dt->un.funct.rettype);
+      fprintf(stderr, "(*%s)()", name);
+      break;
+    case CONST:
+    case TYPEDEF:
+      fprintf(stderr, "What???\n");
+      break;
+    }
+
+  return TRUE;
+}
+
+
diff --git a/documentation/wine_os2.txt b/documentation/wine_os2.txt
index 9b1c0e3..97ad044 100644
--- a/documentation/wine_os2.txt
+++ b/documentation/wine_os2.txt
@@ -5,10 +5,11 @@
 XFree86 3.2 OS/2 (with development libraries)
 bash, gnu make, grep, tar, bison, flex
 sed (a working copy of)
+xpm
 diff and patch are recommended
 
 To compile:
-sh
+sh 
 tools/make_os2.sh
 make depend
 make (make doesn't work yet... I will need to do some others patch, or
@@ -16,14 +17,25 @@
 
 Currently:
 - configure and make depend work...
-- make doesn't work
+- make doesn't work well...
 - the selectors numbers (0) are wrong...
+- signal handling is horrible... (if any)
+- EMX doesn't seem to support mmap
+- debugger don't compile at all
+- sigcontext.h isn't right (incomplete structure?).
 
 What needs to be redone:
-File functions, I/O access (do it!), Interrupt (if int unknow, call
-current RealMode one...), verify that everything is thread safe (how
-does Win95/NT handle multi-thread?), move X functions in some files
-(and make a wrapper, to use PM instead latter), etc...
+- File functions, 
+- I/O access (do it!),
+- Communication (modem),
+- Interrupt (if int unknow, call current RealMode one...), 
+- verify that everything is thread safe (how does Win95/NT handle multi-thread?), 
+- move X functions in some files (and make a wrapper, to use PM instead latter), 
+- implement mmap (or find something else), 
+- make debugger work, 
+- return right CPU type, 
+- make winsock work
+
 
 The good things:
 - OS/2 have DOS interrupts
@@ -33,3 +45,4 @@
 
 Robert Pouliot <krynos@clic.net>
 January 9, 1997
+
diff --git a/files/dos_fs.c b/files/dos_fs.c
index 9b081a0..46786dd 100644
--- a/files/dos_fs.c
+++ b/files/dos_fs.c
@@ -1333,8 +1333,7 @@
     }
     lstrcpy32A(buffer,"\\DEV\\");
     lstrcat32A(buffer,devname);
-    if (s=strchr(buffer,':'))
-    	*s='\0';
+    if ((s=strchr(buffer,':'))) *s='\0';
     lstrcpyn32A(target,buffer,bufsize);
     return strlen(buffer);
 }
diff --git a/files/drive.c b/files/drive.c
index d59e02b..b38f2c1 100644
--- a/files/drive.c
+++ b/files/drive.c
@@ -19,7 +19,7 @@
 #include <sys/mount.h>
 #include <sys/errno.h>
 #endif
-#if defined(__svr4__) || defined(_SCO_DS)
+#if defined(__svr4__) || defined(_SCO_DS) || defined(__EMX__)
 #include <sys/statfs.h>
 #endif
 
@@ -505,7 +505,7 @@
     }
 
     *size = info.f_bsize * info.f_blocks;
-#if defined(__svr4__) || defined(_SCO_DS)
+#if defined(__svr4__) || defined(_SCO_DS) || defined(__EMX__)
     *available = info.f_bfree * info.f_bsize;
 #else
     *available = info.f_bavail * info.f_bsize;
diff --git a/files/file.c b/files/file.c
index 048e58d..b9e2b4a 100644
--- a/files/file.c
+++ b/files/file.c
@@ -13,6 +13,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <sys/errno.h>
+#include <sys/types.h>
 #include <sys/stat.h>
 #include <time.h>
 #include <unistd.h>
@@ -316,6 +317,8 @@
     info->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
     if (S_ISDIR(st->st_mode))
         info->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
+    if (!(st->st_mode & S_IWUSR))
+        info->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
 
     DOSFS_UnixTimeToFileTime( st->st_mtime, &info->ftCreationTime, 0 );
     DOSFS_UnixTimeToFileTime( st->st_mtime, &info->ftLastWriteTime, 0 );
@@ -510,6 +513,8 @@
     if (!path) return 0;
     strcpy( buffer, path );
     p = buffer + strlen(buffer);
+    /* add a \, if there isn't one ... */
+    if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
     *p++ = '~';
     for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
     sprintf( p, "%04x.tmp", num );
@@ -538,6 +543,8 @@
 
     if (DOSFS_GetFullName( buffer, FALSE, &full_name ))
     {
+        /* Check if we have write access in the directory */
+        if ((p = strrchr( full_name.long_name, '/' ))) *p = '\0';
         if (access( full_name.long_name, W_OK ) == -1)
             fprintf( stderr,
                      "Warning: GetTempFileName returns '%s', which doesn't seem to be writeable.\n"
diff --git a/graphics/win16drv/Makefile.in b/graphics/win16drv/Makefile.in
index 4514382..ad71b99 100644
--- a/graphics/win16drv/Makefile.in
+++ b/graphics/win16drv/Makefile.in
@@ -7,7 +7,8 @@
 
 C_SRCS = \
 	font.c \
-	init.c
+	init.c \
+	text.c
 
 all: $(MODULE).o
 
diff --git a/graphics/win16drv/init.c b/graphics/win16drv/init.c
index 0f0399a..930d005 100644
--- a/graphics/win16drv/init.c
+++ b/graphics/win16drv/init.c
@@ -31,6 +31,7 @@
                                  LPCSTR str, UINT16 count, const INT16 *lpDx);
 #endif
 
+DRAWMODE DrawMode;
 static BOOL32 WIN16DRV_CreateDC( DC *dc, LPCSTR driver, LPCSTR device,
                                  LPCSTR output, const DEVMODE16* initData );
 static INT32 WIN16DRV_Escape( DC *dc, INT32 nEscape, INT32 cbInput, 
@@ -49,7 +50,7 @@
     NULL,                            /* pExcludeClipRect */
     NULL,                            /* pExcludeVisRect */
     NULL,                            /* pExtFloodFill */
-    NULL,                            /* pExtTextOut */
+    WIN16DRV_ExtTextOut,             /* pExtTextOut */
     NULL,                            /* pGetPixel */
     WIN16DRV_GetTextExtentPoint,     /* pGetTextExtentPoint */
     WIN16DRV_GetTextMetrics,         /* pGetTextMetrics */
@@ -58,8 +59,8 @@
     NULL,                            /* pLineTo */
     NULL,                            /* pMoveToEx */
     NULL,                            /* pOffsetClipRgn */
-    NULL,                            /* pOffsetViewportOrg (optional) */
-    NULL,                            /* pOffsetWindowOrg (optional) */
+    NULL,                            /* pOffsetViewportOrgEx */
+    NULL,                            /* pOffsetWindowOrgEx */
     NULL,                            /* pPaintRgn */
     NULL,                            /* pPatBlt */
     NULL,                            /* pPie */
@@ -71,8 +72,8 @@
     NULL,                            /* pRestoreDC */
     NULL,                            /* pRoundRect */
     NULL,                            /* pSaveDC */
-    NULL,                            /* pScaleViewportExt (optional) */
-    NULL,                            /* pScaleWindowExt (optional) */
+    NULL,                            /* pScaleViewportExtEx */
+    NULL,                            /* pScaleWindowExtEx */
     NULL,                            /* pSelectClipRgn */
     NULL,                            /* pSelectObject */
     NULL,                            /* pSelectPalette */
@@ -80,7 +81,7 @@
     NULL,                            /* pSetBkMode */
     NULL,                            /* pSetDeviceClipping */
     NULL,                            /* pSetDIBitsToDevice */
-    NULL,                            /* pSetMapMode (optional) */
+    NULL,                            /* pSetMapMode */
     NULL,                            /* pSetMapperFlags */
     NULL,                            /* pSetPixel */
     NULL,                            /* pSetPolyFillMode */
@@ -91,10 +92,10 @@
     NULL,                            /* pSetTextCharacterExtra */
     NULL,                            /* pSetTextColor */
     NULL,                            /* pSetTextJustification */
-    NULL,                            /* pSetViewportExt (optional) */
-    NULL,                            /* pSetViewportOrg (optional) */
-    NULL,                            /* pSetWindowExt (optional) */
-    NULL,                            /* pSetWindowOrg (optional) */
+    NULL,                            /* pSetViewportExtEx */
+    NULL,                            /* pSetViewportOrgEx */
+    NULL,                            /* pSetWindowExtEx */
+    NULL,                            /* pSetWindowOrgEx */
     NULL,                            /* pStretchBlt */
     NULL                             /* pStretchDIBits */
 };
@@ -116,7 +117,7 @@
 
 /* Tempory functions, for initialising structures */
 /* These values should be calculated, not hardcoded */
-void InitTextXForm(LPTEXTXFORM lpTextXForm)
+void InitTextXForm(LPTEXTXFORM16 lpTextXForm)
 {
     lpTextXForm->txfHeight 	= 0x0001;
     lpTextXForm->txfWidth 	= 0x000c;
@@ -549,7 +550,7 @@
  */
 DWORD PRTDRV_RealizeObject(LPPDEVICE lpDestDev, WORD wStyle, 
 		    LPVOID lpInObj, LPVOID lpOutObj,
-                    LPTEXTXFORM lpTextXForm)
+                    LPTEXTXFORM16 lpTextXForm)
 {
     WORD dwRet = 0;
     LOADED_PRINTER_DRIVER *pLPD = NULL;
@@ -591,7 +592,7 @@
 	if (lpTextXForm != NULL)
 	{
 	    lP5 = SegPtr;
-	    nSize = sizeof(TEXTXFORM);
+	    nSize = sizeof(TEXTXFORM16);
 	    AddData(&SegPtr, lpTextXForm, nSize, Limit);	
 	}
 	else
@@ -616,9 +617,10 @@
     int nPDEVICEsize;
     PDEVICE_HEADER *pPDH;
     WIN16DRV_PDEVICE *physDev;
+    LPDRAWMODE lpDrawMode = &DrawMode;
 
     /* Realizing fonts */
-    TEXTXFORM TextXForm;
+    TEXTXFORM16 TextXForm;
     int nSize;
     char printerEnabled[20];
     PROFILE_GetWineIniString( "wine", "printer", "off",
@@ -751,7 +753,7 @@
     /* Quick look at structure */
     if (physDev->segptrFontInfo)
     {  
-	FONTINFO *p = (FONTINFO *)PTR_SEG_TO_LIN(physDev->segptrFontInfo);
+	FONTINFO16 *p = (FONTINFO16 *)PTR_SEG_TO_LIN(physDev->segptrFontInfo);
 
 	dprintf_win16drv(stddeb, "T:%d VR:%d HR:%d, F:%d L:%d\n",
 	       p->dfType,
@@ -762,6 +764,7 @@
 
 #endif
     /* TTD Lots more to do here */
+    InitDrawMode(lpDrawMode);
 
     return TRUE;
 }
@@ -799,7 +802,7 @@
 DWORD PRTDRV_ExtTextOut(LPPDEVICE lpDestDev, WORD wDestXOrg, WORD wDestYOrg,
                         RECT16 *lpClipRect, LPCSTR lpString, WORD wCount, 
                         SEGPTR lpFontInfo, LPDRAWMODE lpDrawMode, 
-                        LPTEXTXFORM lpTextXForm, SHORT *lpCharWidths,
+                        LPTEXTXFORM16 lpTextXForm, SHORT *lpCharWidths,
                         RECT16 *     lpOpaqueRect, WORD wOptions)
 {
     DWORD dwRet = 0;
@@ -811,6 +814,8 @@
     {
 	LONG lP1, lP4, lP5, lP7, lP8, lP9, lP10, lP11;  
 	WORD wP2, wP3, wP6, wP12;
+        INT16 iP6;
+
 	SEGPTR SegPtr = pLPD->ThunkBufSegPtr;
 	SEGPTR Limit = pLPD->ThunkBufLimit;
 	int   nSize;
@@ -841,6 +846,7 @@
 	    /* TTD WARNING THIS STRING ISNT NULL TERMINATED */
 	    lP5 = SegPtr;
 	    nSize = strlen(lpString);
+            nSize = abs(wCount);
             dprintf_win16drv(stddeb, "Adding string size %d\n",nSize);
             
 	    AddData(&SegPtr, lpString, nSize, Limit);	
@@ -848,7 +854,7 @@
 	else
 	  lP5 = 0L;
 	
-	wP6 = wCount;
+	iP6 = wCount;
 	
 	/* This should be realized by the driver, so in 16bit data area */
 	lP7 = lpFontInfo;
@@ -867,7 +873,7 @@
 	if (lpTextXForm != NULL)
 	{
 	    lP9 = SegPtr;
-	    nSize = sizeof(TEXTXFORM);
+	    nSize = sizeof(TEXTXFORM16);
             dprintf_win16drv(stddeb, "Adding TextXForm\n");
 	    AddData(&SegPtr, lpTextXForm, nSize, Limit);	
 	}
@@ -891,96 +897,20 @@
 	wP12 = wOptions;
 	dprintf_win16drv(stddeb, "Calling exttextout 0x%lx 0x%x 0x%x 0x%lx\n0x%lx 0x%x 0x%lx 0x%lx\n"
                "0x%lx 0x%lx 0x%lx 0x%x\n",lP1, wP2, wP3, lP4, 
-					   lP5, wP6, lP7, lP8, lP9, lP10,
+					   lP5, iP6, lP7, lP8, lP9, lP10,
 					   lP11, wP12);
 	dwRet = CallTo16_long_lwwllwlllllw(pLPD->fn[FUNC_EXTTEXTOUT], 
                                            lP1, wP2, wP3, lP4, 
-					   lP5, wP6, lP7, lP8, lP9, lP10,
+					   lP5, iP6, lP7, lP8, lP9, lP10,
 					   lP11, wP12);
+        if (lpDrawMode)
+            GetParamData(lP8, lpDrawMode, sizeof(DRAWMODE));
     }
     dprintf_win16drv(stddeb, "PRTDRV_ExtTextOut: return %lx\n", dwRet);
     return dwRet;
 }
 
 
-/*
- * ExtTextOut (GDI.351)
- */
-static BOOL16 windrvExtTextOut16( DC *dc, INT16 x, INT16 y, UINT16 flags, const RECT16 * lprect,
-                                 LPCSTR str, UINT16 count, const INT16 *lpDx)
-{
-    WIN16DRV_PDEVICE *physDev = (WIN16DRV_PDEVICE *)dc->physDev;
-    BOOL32 bRet = 1;
-    DRAWMODE DrawMode;
-    LPDRAWMODE lpDrawMode = &DrawMode;
-    TEXTXFORM TextXForm;
-    LPTEXTXFORM lpTextXForm = &TextXForm;
-    RECT16 rcClipRect;
-    RECT16 * lpClipRect = &rcClipRect;
-    RECT16 rcOpaqueRect;
-    RECT16 *lpOpaqueRect = &rcOpaqueRect;
-    WORD wOptions = 0;
-    WORD wCount = count;
-
-    static BOOL32 bInit = FALSE;
-    
-
-
-    if (count == 0)
-      return FALSE;
-
-    dprintf_win16drv(stddeb, "LPGDI_ExtTextOut: %04x %d %d %x %p %*s %p\n", dc->hSelf, x, y, 
-	   flags,  lprect, count > 0 ? count : 8, str, lpDx);
-
-    InitTextXForm(lpTextXForm);
-    InitDrawMode(lpDrawMode);
-
-    if (bInit == FALSE)
-    {
-	DWORD dwRet;
-
-	dwRet = PRTDRV_ExtTextOut(physDev->segptrPDEVICE, 0, 0, 
-				  NULL, " ", 
-				  -1,  physDev->segptrFontInfo, lpDrawMode, 
-				  lpTextXForm, NULL, NULL, 0);
-	bInit = TRUE;
-    }
-
-    if (dc != NULL)   
-    {
-	DWORD dwRet;
-/*
-	dwRet = PRTDRV_ExtTextOut(physDev->segptrPDEVICE, 0, 0, 
-				  NULL, "0", 
-				  -1,  physDev->segptrFontInfo, lpDrawMode, 
-				  lpTextXForm, NULL, NULL, 0);
-
-	dwRet = PRTDRV_ExtTextOut(physDev->segptrPDEVICE, 0, 0, 
-				  NULL, str, -wCount,
-				  physDev->segptrFontInfo, lpDrawMode, 
-				  lpTextXForm, NULL, NULL, 0);
-*/
-	lpClipRect->left = 0;
-	lpClipRect->top = 0;
-	lpClipRect->right = 0x3fc;
-	lpClipRect->bottom = 0x42;
-	lpOpaqueRect->left = x;
-	lpOpaqueRect->top = y;
-	lpOpaqueRect->right = 0x3a1;
-	lpOpaqueRect->bottom = 0x01;
-/*
-	dwRet = PRTDRV_ExtTextOut(physDev->segptrPDEVICE, x, y, 
-				  lpClipRect, str, 
-				  wCount,  physDev->segptrFontInfo, lpDrawMode, 
-				  lpTextXForm, lpDx, lpOpaqueRect, wOptions);
-*/
-	dwRet = PRTDRV_ExtTextOut(physDev->segptrPDEVICE, x, y, 
-				  NULL, str, 
-				  wCount,  physDev->segptrFontInfo, lpDrawMode, 
-				  lpTextXForm, NULL, NULL, wOptions);
-    }
-    return bRet;
-}
 
 /****************** misc. printer releated functions */
 
@@ -990,14 +920,90 @@
 #ifndef HPQ 
 #define HPQ WORD
 #endif
-HPQ CreatePQ(int size) { printf("CreatePQ: %d\n",size); return 1; }
-int DeletePQ(HPQ hPQ) { printf("DeletePQ: %x\n", hPQ); return 0; }
-int ExtractPQ(HPQ hPQ) { printf("ExtractPQ: %x\n", hPQ); return 0; }
-int InsertPQ(HPQ hPQ, int tag, int key) 
-{ printf("ExtractPQ: %x %d %d\n", hPQ, tag, key);  return 0; }
-int MinPQ(HPQ hPQ) { printf("MinPQ: %x\n", hPQ); return 0; }
-int SizePQ(HPQ hPQ, int sizechange) 
-{  printf("SizePQ: %x %d\n", hPQ, sizechange); return -1; }
+struct hpq 
+{
+    struct hpq 	*next;
+    int		 tag;
+    int		 key;
+};
+
+static struct hpq *hpqueue;
+
+HPQ 
+CreatePQ(int size) 
+{
+    printf("CreatePQ: %d\n",size);
+    return 1;
+}
+int 
+DeletePQ(HPQ hPQ) 
+{
+    printf("DeletePQ: %x\n", hPQ);
+    return 0;
+}
+int 
+ExtractPQ(HPQ hPQ) 
+{ 
+    struct hpq *queue, *prev, *current, *currentPrev;
+    int key, tag = -1;
+    currentPrev = prev = NULL;
+    queue = current = hpqueue;
+    if (current)
+        key = current->key;
+    
+    while (current)
+    {
+        currentPrev = current;
+        current = current->next;
+        if (current)
+        {
+            if (current->key < key)
+            {
+                queue = current;
+                prev = currentPrev;
+            }
+        }
+    }
+    if (queue)
+    {
+        tag = queue->tag;
+        
+        if (prev)
+            prev->next = queue->next;
+        else
+            hpqueue = queue->next;
+        free(queue);
+    }
+    
+    printf("ExtractPQ: %x got tag %d key %d\n", hPQ, tag, key); 
+
+    return tag;
+}
+
+int 
+InsertPQ(HPQ hPQ, int tag, int key) 
+{
+    struct hpq *queueItem = malloc(sizeof(struct hpq));
+    queueItem->next = hpqueue;
+    hpqueue = queueItem;
+    queueItem->key = key;
+    queueItem->tag = tag;
+    
+    printf("InsertPQ: %x %d %d\n", hPQ, tag, key);
+    return TRUE;
+}
+int
+MinPQ(HPQ hPQ) 
+{
+    printf("MinPQ: %x\n", hPQ); 
+    return 0;
+}
+int
+SizePQ(HPQ hPQ, int sizechange) 
+{  
+    printf("SizePQ: %x %d\n", hPQ, sizechange); 
+    return -1; 
+}
 
 /* 
  * The following functions implement part of the spooling process to 
@@ -1016,8 +1022,6 @@
 } PRINTJOB, *PPRINTJOB;
 
 #define MAX_PRINT_JOBS 1
-#define SP_ERROR -1
-#define SP_OUTOFDISK -4
 #define SP_OK 1
 
 PPRINTJOB gPrintJobsTable[MAX_PRINT_JOBS];
@@ -1142,7 +1146,7 @@
 
     dprintf_win16drv(stddeb, "WriteDialog: %04x %04x \"%s\"\n", hJob,  cchMsg, lpMsg);
 
-    nRet = MessageBox16(0, lpMsg, "Printing Error", MB_OKCANCEL);
+    nRet = MessageBox16(NULL, lpMsg, "Printing Error", MB_OKCANCEL);
     return nRet;
 }
 
diff --git a/graphics/win16drv/text.c b/graphics/win16drv/text.c
new file mode 100644
index 0000000..0620ddc
--- /dev/null
+++ b/graphics/win16drv/text.c
@@ -0,0 +1,137 @@
+/*
+ * win16 driver text functions
+ *
+ * Copyright 1996 John Harvey
+ */
+
+#include <stdlib.h>
+#include "windows.h"
+#include "win16drv.h"
+#include "dc.h"
+#include "gdi.h"
+#include "stddebug.h"
+/* #define DEBUG_WIN16DRV */
+#include "debug.h"
+
+/***********************************************************************
+ *           WIN16DRV_ExtTextOut
+ */
+BOOL32 WIN16DRV_ExtTextOut( DC *dc, INT32 x, INT32 y, UINT32 flags,
+                           const RECT32 *lprect, LPCSTR str, UINT32 count,
+                           const INT32 *lpDx )
+{
+    WIN16DRV_PDEVICE *physDev = (WIN16DRV_PDEVICE *)dc->physDev;
+    BOOL32 bRet = 1;
+    extern DRAWMODE DrawMode;
+    LPDRAWMODE lpDrawMode = &DrawMode;
+    TEXTXFORM16 TextXForm;
+    LPTEXTXFORM16 lpTextXForm = &TextXForm;
+    RECT16 rcClipRect;
+    RECT16 * lpClipRect = &rcClipRect;
+    RECT16 rcOpaqueRect;
+    RECT16 *lpOpaqueRect = &rcOpaqueRect;
+    WORD wOptions = 0;
+    WORD wCount = count;
+
+    static BOOL32 bInit = FALSE;
+    
+
+
+    if (count == 0)
+      return FALSE;
+
+    dprintf_win16drv(stddeb, "WIN16DRV_ExtTextOut: %04x %d %d %x %p %*s %p\n", dc->hSelf, x, y, 
+	   flags,  lprect, count > 0 ? count : 8, str, lpDx);
+
+    InitTextXForm(lpTextXForm);
+
+    if (bInit == FALSE)
+    {
+	DWORD dwRet;
+
+	dwRet = PRTDRV_ExtTextOut(physDev->segptrPDEVICE, 0, 0, 
+				  NULL, " ", 
+				  -1,  physDev->segptrFontInfo, lpDrawMode, 
+				  lpTextXForm, NULL, NULL, 0);
+	bInit = TRUE;
+    }
+
+    if (dc != NULL)   
+    {
+	DWORD dwRet;
+/*
+	dwRet = PRTDRV_ExtTextOut(physDev->segptrPDEVICE, 0, 0, 
+				  NULL, "0", 
+				  -1,  physDev->segptrFontInfo, lpDrawMode, 
+				  lpTextXForm, NULL, NULL, 0);
+
+	dwRet = PRTDRV_ExtTextOut(physDev->segptrPDEVICE, 0, 0, 
+				  NULL, str, -wCount,
+				  physDev->segptrFontInfo, lpDrawMode, 
+				  lpTextXForm, NULL, NULL, 0);
+*/
+	lpClipRect->left = lprect->left ;
+	lpClipRect->top = lprect->top;
+	lpClipRect->right = lprect->right;
+	lpClipRect->bottom = lprect->bottom;
+        dprintf_win16drv(stddeb, "WIN16DRV_ExtTextOut Clip rect left %d top %d rigt %d bottom %d\n",
+                         lpClipRect->left,lpClipRect->top,lpClipRect->right,lpClipRect->bottom);
+        
+	lpClipRect->left = 0;
+	lpClipRect->top = 0;
+	lpClipRect->right = 0x3fc;
+	lpClipRect->bottom = 0x630;
+        dprintf_win16drv(stddeb, "WIN16DRV_ExtTextOut Clip rect left %d top %d rigt %d bottom %d\n",
+                         lpClipRect->left,lpClipRect->top,lpClipRect->right,lpClipRect->bottom);
+	lpOpaqueRect->left = x;
+	lpOpaqueRect->top = y;
+	lpOpaqueRect->right = 0x3a1;
+	lpOpaqueRect->bottom = 0x01;
+        printf("drawmode ropt 0x%x bkMode 0x%x bkColor 0x%x textColor 0x%x tbbreakExtra 0x%x breakextra 0x%x\n",
+               lpDrawMode->Rop2,    lpDrawMode->bkMode,    lpDrawMode->bkColor,
+               lpDrawMode->TextColor,    lpDrawMode->TBreakExtra,    lpDrawMode->BreakExtra);
+        printf("breakerr 0x%x breakrem 0x%x breakcount 0x%x chextra 0x%x lbkcolor 0x%x ltextcolor 0x%x\n",
+               lpDrawMode->BreakErr,    lpDrawMode->BreakRem,    lpDrawMode->BreakCount,
+               lpDrawMode->CharExtra,	   lpDrawMode->LbkColor,    lpDrawMode->LTextColor);
+
+    {
+        RECT16 rcPageSize;
+	FONTINFO16 *p = (FONTINFO16 *)PTR_SEG_TO_LIN(physDev->segptrFontInfo);
+        rcPageSize.left = 0;
+        rcPageSize.right = 0x3c0;
+        
+        rcPageSize.top = 0;
+        rcPageSize.bottom = 0x630;
+        
+
+
+
+        if(y < rcPageSize.top  ||  y + p->dfPixHeight > rcPageSize.bottom)
+        {
+            printf("Failed 1 y %d top %d y +height %d bottom %d\n",
+                   y, rcPageSize.top  ,  y + p->dfPixHeight , rcPageSize.bottom);
+        }
+        
+
+        if(x >= rcPageSize.right  ||
+            x + wCount * p->dfPixWidth < rcPageSize.left)
+        {
+            printf("Faile 2\n");
+        }
+        
+    }
+        
+
+	dwRet = PRTDRV_ExtTextOut(physDev->segptrPDEVICE, x, y, 
+				  lpClipRect, str, 
+				  wCount,  physDev->segptrFontInfo, lpDrawMode, 
+				  lpTextXForm, NULL, NULL, wOptions);
+/*
+	dwRet = PRTDRV_ExtTextOut(physDev->segptrPDEVICE, x, y, 
+				  lpClipRect, str, 
+				  wCount,  physDev->segptrFontInfo, lpDrawMode, 
+				  lpTextXForm, lpDx, NULL, flags);
+*/
+    }
+    return bRet;
+}
diff --git a/graphics/wing.c b/graphics/wing.c
index c3254bc..aed0e39 100644
--- a/graphics/wing.c
+++ b/graphics/wing.c
@@ -8,7 +8,9 @@
 #include <X11/extensions/XShm.h>
 #include <sys/types.h>
 #include <sys/ipc.h>
+#ifndef __EMX__
 #include <sys/shm.h>
+#endif
 
 #include "windows.h"
 #include "bitmap.h"
diff --git a/graphics/x11drv/font.c b/graphics/x11drv/font.c
index 6faebae..4b816e2 100644
--- a/graphics/x11drv/font.c
+++ b/graphics/x11drv/font.c
@@ -25,3 +25,41 @@
 		    * dc->wndExtY / dc->vportExtY);
     return TRUE;
 }
+
+BOOL32 X11DRV_GetTextMetrics(DC *dc, TEXTMETRIC32A *metrics)
+{
+    
+    metrics->tmWeight           = dc->u.x.font.metrics.tmWeight;
+    metrics->tmOverhang         = dc->u.x.font.metrics.tmOverhang;
+    metrics->tmDigitizedAspectX = dc->u.x.font.metrics.tmDigitizedAspectX;
+    metrics->tmDigitizedAspectY = dc->u.x.font.metrics.tmDigitizedAspectY;
+    metrics->tmFirstChar        = dc->u.x.font.metrics.tmFirstChar;
+    metrics->tmLastChar         = dc->u.x.font.metrics.tmLastChar;
+    metrics->tmDefaultChar      = dc->u.x.font.metrics.tmDefaultChar;
+    metrics->tmBreakChar        = dc->u.x.font.metrics.tmBreakChar;
+    metrics->tmItalic           = dc->u.x.font.metrics.tmItalic;
+    metrics->tmUnderlined       = dc->u.x.font.metrics.tmUnderlined;
+    metrics->tmStruckOut        = dc->u.x.font.metrics.tmStruckOut;
+    metrics->tmPitchAndFamily   = dc->u.x.font.metrics.tmPitchAndFamily;
+    metrics->tmCharSet          = dc->u.x.font.metrics.tmCharSet;
+
+    metrics->tmAscent  = abs( dc->u.x.font.metrics.tmAscent
+			      * dc->wndExtY / dc->vportExtY );
+    metrics->tmDescent = abs( dc->u.x.font.metrics.tmDescent
+			      * dc->wndExtY / dc->vportExtY );
+    metrics->tmHeight  = dc->u.x.font.metrics.tmAscent + dc->u.x.font.metrics.tmDescent;
+    metrics->tmInternalLeading = abs( dc->u.x.font.metrics.tmInternalLeading
+				      * dc->wndExtY / dc->vportExtY );
+    metrics->tmExternalLeading = abs( dc->u.x.font.metrics.tmExternalLeading
+				      * dc->wndExtY / dc->vportExtY );
+    metrics->tmMaxCharWidth    = abs( dc->u.x.font.metrics.tmMaxCharWidth 
+				      * dc->wndExtX / dc->vportExtX );
+    metrics->tmAveCharWidth    = abs( dc->u.x.font.metrics.tmAveCharWidth
+				      * dc->wndExtX / dc->vportExtX );
+
+    return TRUE;
+    
+}
+
+
+
diff --git a/graphics/x11drv/graphics.c b/graphics/x11drv/graphics.c
index 834384a..2619425 100644
--- a/graphics/x11drv/graphics.c
+++ b/graphics/x11drv/graphics.c
@@ -5,6 +5,9 @@
  */
 
 #include <math.h>
+#if defined(__EMX__)
+#include <float.h>
+#endif
 #include <stdlib.h>
 #include <X11/Xlib.h>
 #include <X11/Xutil.h>
diff --git a/graphics/x11drv/init.c b/graphics/x11drv/init.c
index 799dec8..a7fd361 100644
--- a/graphics/x11drv/init.c
+++ b/graphics/x11drv/init.c
@@ -30,7 +30,7 @@
     X11DRV_ExtTextOut,               /* pExtTextOut */
     X11DRV_GetPixel,                 /* pGetPixel */
     X11DRV_GetTextExtentPoint,       /* pGetTextExtentPoint */
-    NULL,                            /* pGetTextMetrics */
+    X11DRV_GetTextMetrics,           /* pGetTextMetrics */
     NULL,                            /* pIntersectClipRect */
     NULL,                            /* pIntersectVisRect */
     X11DRV_LineTo,                   /* pLineTo */
diff --git a/graphics/x11drv/text.c b/graphics/x11drv/text.c
index 4ea2587..561cb5e 100644
--- a/graphics/x11drv/text.c
+++ b/graphics/x11drv/text.c
@@ -41,8 +41,8 @@
     if (!DC_SetupGCForText( dc )) return TRUE;
     font = dc->u.x.font.fstruct;
 
-    dprintf_text(stddeb,"ExtTextOut: hdc=%04x %d,%d '%*.*s', %d  flags=%d\n",
-                 dc->hSelf, x, y, count, count, str, count, flags);
+    dprintf_text(stddeb,"ExtTextOut: hdc=%04x %d,%d '%.*s', %d  flags=%d\n",
+                 dc->hSelf, x, y, (int)count, str, count, flags);
     if (lprect != NULL) dprintf_text(stddeb, "\trect=(%d,%d- %d,%d)\n",
                                      lprect->left, lprect->top,
                                      lprect->right, lprect->bottom );
diff --git a/if1632/advapi32.spec b/if1632/advapi32.spec
index 1b5cc7d..a78d78d 100644
--- a/if1632/advapi32.spec
+++ b/if1632/advapi32.spec
@@ -111,7 +111,7 @@
 0106 stub OpenBackupEventLogW
 0107 stub OpenEventLogA
 0108 stub OpenEventLogW
-0109 stub OpenProcessToken
+0109 stdcall OpenProcessToken(long long ptr) OpenProcessToken
 0110 stub OpenSCManagerA
 0111 stub OpenSCManagerW
 0112 stub OpenServiceA
@@ -129,7 +129,7 @@
 0124 stub ReadEventLogA
 0125 stub ReadEventLogW
 0126 stdcall RegCloseKey(long) RegCloseKey
-0127 stub RegConnectRegistryA
+0127 stdcall RegConnectRegistryA(ptr long ptr) RegConnectRegistry32A
 0128 stub RegConnectRegistryW
 0129 stdcall RegCreateKeyA(long ptr ptr) RegCreateKey32A
 0130 stdcall RegCreateKeyExA(long ptr long ptr long long ptr ptr ptr) RegCreateKeyEx32A
diff --git a/if1632/crtdll.spec b/if1632/crtdll.spec
index a7c6f88..b249b60 100644
--- a/if1632/crtdll.spec
+++ b/if1632/crtdll.spec
@@ -267,7 +267,7 @@
 262 stub _searchenv
 263 stub _seterrormode
 264 stub _setjmp
-265 stub _setmode
+265 cdecl _setmode(long long) CRTDLL__setmode
 266 stub _setsystime
 267 stub _sleep
 268 stub _snprintf
@@ -295,7 +295,7 @@
 290 stub _strlwr
 291 stub _strncnt
 292 stub _strnextc
-293 stub _strnicmp
+293 cdecl _strnicmp(ptr ptr long) lstrncmpi32A
 294 stub _strninc
 295 stub _strnset
 296 stub _strrev
@@ -347,7 +347,7 @@
 342 cdecl asin(long) CRTDLL_asin
 343 cdecl atan(long) CRTDLL_atan
 344 cdecl atan2(long long) CRTDLL_atan2
-345 stub atexit
+345 cdecl atexit(ptr) CRTDLL_atexit
 346 cdecl atof(ptr) CRTDLL_atof
 347 cdecl atoi(ptr) CRTDLL_atoi
 348 cdecl atol(ptr) CRTDLL_atol
@@ -446,7 +446,7 @@
 441 stub putc
 442 cdecl putchar(long) CRTDLL_putchar
 443 stub puts
-444 stub qsort
+444 cdecl qsort(ptr long long ptr) qsort
 445 stub raise
 446 cdecl rand() CRTDLL_rand
 447 cdecl realloc(ptr long) CRTDLL_realloc
diff --git a/if1632/gdi.spec b/if1632/gdi.spec
index 4d2846b..290fb85 100644
--- a/if1632/gdi.spec
+++ b/if1632/gdi.spec
@@ -44,7 +44,7 @@
                         s_word s_word long) StretchBlt16
 36  pascal16 Polygon (word ptr word) Polygon16
 37  pascal16 Polyline (word ptr word) Polyline16
-38  pascal Escape(word word word segptr segptr) Escape
+38  pascal Escape(word word word segptr segptr) Escape16
 39  pascal16 RestoreDC(word s_word) RestoreDC16
 40  pascal16 FillRgn(word word word) FillRgn16
 41  pascal16 FrameRgn(word word word word word) FrameRgn16
@@ -209,9 +209,9 @@
 281 pascal DrvSetPrinterData(ptr ptr ptr ptr long) DrvSetPrinterData
 282 pascal DrvGetPrinterData(ptr ptr ptr ptr long ptr) DrvGetPrinterData
 299 stub ENGINEGETCHARWIDTHEX
-300 stub ENGINEENUMERATEFONT
+300 pascal EnginEnumerateFont(ptr segptr long) EngineEnumerateFont
 301 stub ENGINEDELETEFONT
-302 stub ENGINEREALIZEFONT
+302 pascal EnginRealizeFont(ptr ptr ptr) EngineRealizeFont
 303 stub ENGINEGETCHARWIDTH
 304 stub ENGINESETFONTCONTEXT
 305 stub ENGINEGETGLYPHBMP
diff --git a/if1632/gdi32.spec b/if1632/gdi32.spec
index cc8f25f..c20eeaa 100644
--- a/if1632/gdi32.spec
+++ b/if1632/gdi32.spec
@@ -96,7 +96,7 @@
 0088 stub EnumMetaFile
 0089 stdcall EnumObjects(long long ptr long) THUNK_EnumObjects32
 0090 stdcall EqualRgn(long long) EqualRgn32
-0091 stdcall Escape(long long long ptr ptr) Escape
+0091 stdcall Escape(long long long ptr ptr) Escape32
 0092 stdcall ExcludeClipRect(long long long long long) ExcludeClipRect32
 0093 stub ExtCreatePen
 0094 stub ExtCreateRegion
diff --git a/if1632/kernel.spec b/if1632/kernel.spec
index f38b190..c7d01b9 100644
--- a/if1632/kernel.spec
+++ b/if1632/kernel.spec
@@ -63,7 +63,7 @@
 64  pascal16 AccessResource(word word) AccessResource16
 65  pascal SizeofResource(word word) SizeofResource16
 66  pascal16 AllocResource(word word long) AllocResource16
-67  stub SetResourceHandler
+67  pascal SetResourceHandler(word ptr ptr) SetResourceHandler
 68  pascal16 InitAtomTable(word) InitAtomTable
 69  pascal16 FindAtom(segptr) FindAtom
 70  pascal16 AddAtom(segptr) AddAtom
diff --git a/if1632/ntdll.spec b/if1632/ntdll.spec
index 47d4d37..48ece57 100644
--- a/if1632/ntdll.spec
+++ b/if1632/ntdll.spec
@@ -270,7 +270,7 @@
 266 stdcall RtlAllocateHeap(long long long) HeapAlloc
 267 stub RtlAnsiCharToUnicodeChar
 268 stub RtlAnsiStringToUnicodeSize
-269 stub RtlAnsiStringToUnicodeString
+269 stdcall RtlAnsiStringToUnicodeString(ptr ptr long) RtlAnsiStringToUnicodeString
 270 stub RtlAppendAsciizToString
 271 stub RtlAppendStringToString
 272 stub RtlAppendUnicodeStringToString
@@ -345,7 +345,7 @@
 341 stub RtlEnlargedIntegerMultiply
 342 stub RtlEnlargedUnsignedDivide
 343 stub RtlEnlargedUnsignedMultiply
-344 stub RtlEnterCriticalSection
+344 stdcall RtlEnterCriticalSection(ptr) EnterCriticalSection
 345 stub RtlEnumProcessHeaps
 346 stub RtlEnumerateGenericTable
 347 stub RtlEnumerateGenericTableWithoutSplaying
@@ -391,7 +391,7 @@
 387 stub RtlGetGroupSecurityDescriptor
 388 stub RtlGetLongestNtPathLength
 389 stub RtlGetNtGlobalFlags
-390 stub RtlGetNtProductType
+390 stdcall RtlGetNtProductType(ptr) RtlGetNtProductType
 391 stub RtlGetOwnerSecurityDescriptor
 392 stub RtlGetProcessHeaps
 393 stub RtlGetSaclSecurityDescriptor
@@ -403,11 +403,11 @@
 399 stub RtlInitAnsiString
 400 stub RtlInitCodePageTable
 401 stub RtlInitNlsTables
-402 stub RtlInitString
-403 stub RtlInitUnicodeString
+402 stdcall RtlInitString(ptr ptr) RtlInitString
+403 stdcall RtlInitUnicodeString(ptr ptr) RtlInitUnicodeString
 404 stub RtlInitializeBitMap
 405 stub RtlInitializeContext
-406 stub RtlInitializeCriticalSection
+406 stdcall RtlInitializeCriticalSection(ptr) InitializeCriticalSection
 407 stub RtlInitializeGenericTable
 408 stub RtlInitializeRXact
 409 stub RtlInitializeResource
@@ -427,7 +427,7 @@
 423 stub RtlLargeIntegerShiftRight
 424 stub RtlLargeIntegerSubtract
 425 stub RtlLargeIntegerToChar
-426 stub RtlLeaveCriticalSection
+426 stdcall RtlLeaveCriticalSection(ptr) LeaveCriticalSection
 427 stdcall RtlLengthRequiredSid(long) RtlLengthRequiredSid
 428 stub RtlLengthSecurityDescriptor
 429 stub RtlLengthSid
@@ -443,12 +443,12 @@
 439 stub RtlNewSecurityGrantedAccess
 440 stub RtlNewSecurityObject
 441 stdcall RtlNormalizeProcessParams(ptr) RtlNormalizeProcessParams
-442 stub RtlNtStatusToDosError
+442 stdcall RtlNtStatusToDosError(long) RtlNtStatusToDosError
 443 stub RtlNumberGenericTableElements
 444 stub RtlNumberOfClearBits
 445 stub RtlNumberOfSetBits
 446 stub RtlOemStringToUnicodeSize
-447 stub RtlOemStringToUnicodeString
+447 stdcall RtlOemStringToUnicodeString(ptr ptr long) RtlOemStringToUnicodeString
 448 stdcall RtlOemToUnicodeN(ptr long ptr ptr long) RtlOemToUnicodeN
 449 stub RtlOpenCurrentUser
 450 stub RtlPcToFileHeader
@@ -521,7 +521,7 @@
 517 stub RtlUnlockHeap
 518 stub RtlUnwind
 519 stub RtlUpcaseUnicodeChar
-520 stub RtlUpcaseUnicodeString
+520 stdcall RtlUpcaseUnicodeString(ptr ptr long) RtlUpcaseUnicodeString
 521 stub RtlUpcaseUnicodeStringToAnsiString
 522 stub RtlUpcaseUnicodeStringToCountedOemString
 523 stub RtlUpcaseUnicodeStringToOemString
@@ -549,8 +549,8 @@
 545 stub RtlpNtSetValueKey
 546 stub RtlpUnWaitCriticalSection
 547 stub RtlpWaitForCriticalSection
-548 stub RtlxAnsiStringToUnicodeSize
-549 stub RtlxOemStringToUnicodeSize
+548 stdcall RtlxAnsiStringToUnicodeSize(ptr) RtlxAnsiStringToUnicodeSize
+549 stdcall RtlxOemStringToUnicodeSize(ptr) RtlxOemStringToUnicodeSize
 550 stub RtlxUnicodeStringToAnsiSize
 551 stub RtlxUnicodeStringToOemSize
 552 stub SaveEm87Context
@@ -928,27 +928,27 @@
 924 stdcall strrchr(ptr long) strrchr
 925 stub strspn
 926 stub strstr
-927 stub swprintf
+927 stdcall swprintf() CRTDLL_swprintf
 928 stub tan
 929 stub tolower
 930 stub toupper
 931 stub towlower
 932 stub towupper
 933 stub vsprintf
-934 stub wcscat
-935 stub wcschr
+934 stdcall wcscat(ptr ptr) lstrcat32W
+935 stdcall wcschr(ptr long) CRTDLL_wcschr
 936 stub wcscmp
-937 stub wcscpy
+937 stdcall wcscpy(ptr ptr) lstrcpy32W
 938 stub wcscspn
-939 stub wcslen
+939 stdcall wcslen(ptr) lstrlen32W
 940 stub wcsncat
 941 stub wcsncmp
-942 stub wcsncpy
+942 stdcall wcsncpy(ptr ptr long) lstrcpyn32W
 943 stub wcspbrk
-944 stub wcsrchr
+944 stdcall wcsrchr(ptr long) CRTDLL_wcsrchr
 945 stub wcsspn
-946 stub wcsstr
+946 stdcall wcsstr(ptr ptr) CRTDLL_wcsstr
 947 stub wcstok
 948 stub wcstol
-949 stub wcstombs
+949 stdcall wcstombs(ptr ptr) lstrcpyWtoA
 950 stub wcstoul
diff --git a/if1632/relay.c b/if1632/relay.c
index 712046e..8de8495 100644
--- a/if1632/relay.c
+++ b/if1632/relay.c
@@ -232,7 +232,7 @@
     printf( ") ret=%08x\n", stack[1] );
     if (nb_args == -1)  /* Register function */
     {
-        CONTEXT *context = (CONTEXT *)((BYTE *)stack - sizeof(CONTEXT) - 12);
+        CONTEXT *context = (CONTEXT *)((BYTE *)stack - sizeof(CONTEXT) - 8);
         printf( " EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx ESI=%08lx EDI=%08lx\n",
                 context->Eax, context->Ebx, context->Ecx, context->Edx,
                 context->Esi, context->Edi );
@@ -263,7 +263,7 @@
             BUILTIN_GetEntryPoint32( (void *)stack[-2] ), ret_val, stack[1] );
     if (nb_args == -1)  /* Register function */
     {
-        CONTEXT *context = (CONTEXT *)((BYTE *)stack - sizeof(CONTEXT) - 12);
+        CONTEXT *context = (CONTEXT *)((BYTE *)stack - sizeof(CONTEXT) - 8);
         printf( " EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx ESI=%08lx EDI=%08lx\n",
                 context->Eax, context->Ebx, context->Ecx, context->Edx,
                 context->Esi, context->Edi );
diff --git a/if1632/user.spec b/if1632/user.spec
index c878724..daa24c2 100644
--- a/if1632/user.spec
+++ b/if1632/user.spec
@@ -30,11 +30,11 @@
 28  pascal16 ClientToScreen(word ptr) ClientToScreen16
 29  pascal16 ScreenToClient(word ptr) ScreenToClient16
 30  pascal16 WindowFromPoint(long) WindowFromPoint16
-31  pascal16 IsIconic(word) IsIconic
+31  pascal16 IsIconic(word) IsIconic16
 32  pascal16 GetWindowRect(word ptr) GetWindowRect16
 33  pascal16 GetClientRect(word ptr) GetClientRect16
-34  pascal16 EnableWindow(word word) EnableWindow
-35  pascal16 IsWindowEnabled(word) IsWindowEnabled
+34  pascal16 EnableWindow(word word) EnableWindow16
+35  pascal16 IsWindowEnabled(word) IsWindowEnabled16
 36  pascal16 GetWindowText(word segptr word) GetWindowText16
 37  pascal16 SetWindowText(word segptr) SetWindowText16
 38  pascal16 GetWindowTextLength(word) GetWindowTextLength16
@@ -42,25 +42,25 @@
 40  pascal16 EndPaint(word ptr) EndPaint16
 41  pascal16 CreateWindow(ptr ptr long s_word s_word s_word s_word
 	                  word word word segptr) CreateWindow16
-42  pascal16 ShowWindow(word word) ShowWindow
+42  pascal16 ShowWindow(word word) ShowWindow16
 43  pascal16 CloseWindow(word) CloseWindow
 44  pascal16 OpenIcon(word) OpenIcon
-45  pascal16 BringWindowToTop(word) BringWindowToTop
+45  pascal16 BringWindowToTop(word) BringWindowToTop16
 46  pascal16 GetParent(word) GetParent16
 47  pascal16 IsWindow(word) IsWindow
-48  pascal16 IsChild(word word) IsChild
-49  pascal16 IsWindowVisible(word) IsWindowVisible
+48  pascal16 IsChild(word word) IsChild16
+49  pascal16 IsWindowVisible(word) IsWindowVisible16
 50  pascal16 FindWindow(segptr ptr) FindWindow16
 #51 BEAR51
 52  pascal16 AnyPopup() AnyPopup
-53  pascal16 DestroyWindow(word) DestroyWindow
+53  pascal16 DestroyWindow(word) DestroyWindow16
 54  pascal16 EnumWindows(segptr long) THUNK_EnumWindows16
 55  pascal16 EnumChildWindows(word segptr long) THUNK_EnumChildWindows16
-56  pascal16 MoveWindow(word word word word word word) MoveWindow
+56  pascal16 MoveWindow(word word word word word word) MoveWindow16
 57  pascal16 RegisterClass(ptr) RegisterClass16
 58  pascal16 GetClassName(word ptr word) GetClassName16
-59  pascal16 SetActiveWindow(word) SetActiveWindow
-60  pascal16 GetActiveWindow() GetActiveWindow
+59  pascal16 SetActiveWindow(word) SetActiveWindow16
+60  pascal16 GetActiveWindow() GetActiveWindow16
 61  pascal16 ScrollWindow(word s_word s_word ptr ptr) ScrollWindow16
 62  pascal16 SetScrollPos(word word s_word word) SetScrollPos16
 63  pascal16 GetScrollPos(word word) GetScrollPos16
@@ -90,14 +90,14 @@
 88  pascal16 EndDialog(word s_word) EndDialog
 89  pascal16 CreateDialog(word segptr word segptr) CreateDialog16
 90  pascal16 IsDialogMessage(word ptr) IsDialogMessage
-91  pascal16 GetDlgItem(word word) GetDlgItem
+91  pascal16 GetDlgItem(word word) GetDlgItem16
 92  pascal16 SetDlgItemText(word word segptr) SetDlgItemText16
 93  pascal16 GetDlgItemText(word word segptr word) GetDlgItemText16
 94  pascal16 SetDlgItemInt(word word word word) SetDlgItemInt16
-95  pascal16 GetDlgItemInt(word word ptr word) GetDlgItemInt
-96  pascal16 CheckRadioButton(word word word word) CheckRadioButton
-97  pascal16 CheckDlgButton(word word word) CheckDlgButton
-98  pascal16 IsDlgButtonChecked(word word) IsDlgButtonChecked
+95  pascal16 GetDlgItemInt(word s_word ptr word) GetDlgItemInt16
+96  pascal16 CheckRadioButton(word word word word) CheckRadioButton16
+97  pascal16 CheckDlgButton(word word word) CheckDlgButton16
+98  pascal16 IsDlgButtonChecked(word word) IsDlgButtonChecked16
 99  pascal16 DlgDirSelect(word ptr word) DlgDirSelect
 100 pascal16 DlgDirList(word ptr word word word) DlgDirList16
 101 pascal   SendDlgItemMessage(word word word word long) SendDlgItemMessage16
@@ -169,7 +169,7 @@
 167 pascal16 ShowCaret(word) ShowCaret
 168 pascal16 SetCaretBlinkTime(word) SetCaretBlinkTime
 169 pascal16 GetCaretBlinkTime() GetCaretBlinkTime16
-170 pascal16 ArrangeIconicWindows(word) ArrangeIconicWindows
+170 pascal16 ArrangeIconicWindows(word) ArrangeIconicWindows16
 171 pascal16 WinHelp(word ptr word long) WinHelp16
 172 stub SwitchToThisWindow
 173 pascal16 LoadCursor(word segptr) LoadCursor16
@@ -229,10 +229,10 @@
 226 stub LockInput
 227 pascal16 GetNextDlgGroupItem(word word word) GetNextDlgGroupItem16
 228 pascal16 GetNextDlgTabItem(word word word) GetNextDlgTabItem16
-229 pascal16 GetTopWindow(word) GetTopWindow
-230 pascal16 GetNextWindow(word word) GetNextWindow
+229 pascal16 GetTopWindow(word) GetTopWindow16
+230 pascal16 GetNextWindow(word word) GetNextWindow16
 231 stub GetSystemDebugState
-232 pascal16 SetWindowPos(word word word word word word word) SetWindowPos
+232 pascal16 SetWindowPos(word word word word word word word) SetWindowPos16
 233 pascal16 SetParent(word word) SetParent
 234 pascal16 UnhookWindowsHook(s_word segptr) THUNK_UnhookWindowsHook16
 235 pascal   DefHookProc(s_word word long ptr) DefHookProc16
@@ -261,11 +261,11 @@
 256 pascal16 GetDriverInfo(word ptr) GetDriverInfo
 257 pascal16 GetNextDriver(word long) GetNextDriver
 258 pascal16 MapWindowPoints(word word ptr word) MapWindowPoints16
-259 pascal16 BeginDeferWindowPos(s_word) BeginDeferWindowPos
+259 pascal16 BeginDeferWindowPos(s_word) BeginDeferWindowPos16
 260 pascal16 DeferWindowPos(word word word s_word s_word s_word s_word word)
-             DeferWindowPos
-261 pascal16 EndDeferWindowPos(word) EndDeferWindowPos
-262 pascal16 GetWindow(word word) GetWindow
+             DeferWindowPos16
+261 pascal16 EndDeferWindowPos(word) EndDeferWindowPos16
+262 pascal16 GetWindow(word word) GetWindow16
 263 pascal16 GetMenuItemCount(word) GetMenuItemCount16
 264 pascal16 GetMenuItemID(word word) GetMenuItemID16
 265 pascal16 ShowOwnedPopups(word word) ShowOwnedPopups
@@ -275,12 +275,12 @@
 269 pascal16 GlobalDeleteAtom(word) GlobalDeleteAtom
 270 pascal16 GlobalFindAtom(segptr) GlobalFindAtom16
 271 pascal16 GlobalGetAtomName(word ptr s_word) GlobalGetAtomName16
-272 pascal16 IsZoomed(word) IsZoomed
+272 pascal16 IsZoomed(word) IsZoomed16
 273 stub ControlPanelInfo
 274 stub GetNextQueueWindow
 275 stub RepaintScreen
 276 stub LockMyTask
-277 pascal16 GetDlgCtrlID(word) GetDlgCtrlID
+277 pascal16 GetDlgCtrlID(word) GetDlgCtrlID16
 278 pascal16 GetDesktopHwnd() GetDesktopHwnd
 279 stub OldSetDeskPattern
 280 pascal16 SetSystemMenu(word word) SetSystemMenu16
diff --git a/if1632/user32.spec b/if1632/user32.spec
index 41bc522..7c51012 100644
--- a/if1632/user32.spec
+++ b/if1632/user32.spec
@@ -8,11 +8,11 @@
 0003 stub AnyPopup
 0004 stdcall AppendMenuA(long long long ptr) AppendMenu32A
 0005 stdcall AppendMenuW(long long long ptr) AppendMenu32W
-0006 stub ArrangeIconicWindows
+0006 stdcall ArrangeIconicWindows(long) ArrangeIconicWindows32
 0007 stub AttachThreadInput
-0008 stdcall BeginDeferWindowPos(long) BeginDeferWindowPos
+0008 stdcall BeginDeferWindowPos(long) BeginDeferWindowPos32
 0009 stdcall BeginPaint(long ptr) BeginPaint32
-0010 stdcall BringWindowToTop(long) BringWindowToTop
+0010 stdcall BringWindowToTop(long) BringWindowToTop32
 0011 stub BroadcastSystemMessage
 0012 stub CalcChildScroll
 0013 stub CallMsgFilter
@@ -46,10 +46,10 @@
 0041 stdcall CharUpperBuffA(ptr long) CharUpperBuff32A
 0042 stdcall CharUpperBuffW(ptr long) CharUpperBuff32W
 0043 stdcall CharUpperW(ptr) CharUpper32W
-0044 stdcall CheckDlgButton(long long long) CheckDlgButton
+0044 stdcall CheckDlgButton(long long long) CheckDlgButton32
 0045 stdcall CheckMenuItem(long long long) CheckMenuItem32
 0046 stub CheckMenuRadioItem
-0047 stdcall CheckRadioButton(long long long long) CheckRadioButton
+0047 stdcall CheckRadioButton(long long long long) CheckRadioButton32
 0048 stdcall ChildWindowFromPoint(long long long) ChildWindowFromPoint32
 0049 stub ChildWindowFromPointEx
 0050 stub ClientThreadConnect
@@ -106,7 +106,7 @@
 0099 stub DdeFreeDataHandle
 0100 stub DdeFreeStringHandle
 0101 stub DdeGetData
-0102 stub DdeGetLastError
+0102 return DdeGetLastError 4 0
 0103 stub DdeGetQualityOfService
 0104 stub DdeImpersonateClient
 0105 return DdeInitializeA 16 0
@@ -131,14 +131,14 @@
 0124 stdcall DefMDIChildProcW(long long long long) DefMDIChildProc32W
 0125 stdcall DefWindowProcA(long long long long) DefWindowProc32A
 0126 stdcall DefWindowProcW(long long long long) DefWindowProc32W
-0127 stdcall DeferWindowPos(long long long long long long long long) DeferWindowPos
+0127 stdcall DeferWindowPos(long long long long long long long long) DeferWindowPos32
 0128 stdcall DeleteMenu(long long long) DeleteMenu32
 0129 stub DestroyAcceleratorTable
 0130 stdcall DestroyCaret() DestroyCaret
 0131 stub DestroyCursor
 0132 stub DestroyIcon
 0133 stdcall DestroyMenu(long) DestroyMenu32
-0134 stdcall DestroyWindow(long) DestroyWindow
+0134 stdcall DestroyWindow(long) DestroyWindow32
 0135 stdcall DialogBoxIndirectParamA(long ptr long ptr long) DialogBoxIndirectParam32A
 0136 stub DialogBoxIndirectParamAorW
 0137 stdcall DialogBoxIndirectParamW(long ptr long ptr long) DialogBoxIndirectParam32W
@@ -175,8 +175,8 @@
 0168 stdcall EmptyClipboard() EmptyClipboard
 0169 stdcall EnableMenuItem(long long long) EnableMenuItem32
 0170 stdcall EnableScrollBar(long long long) EnableScrollBar32
-0171 stdcall EnableWindow(long long) EnableWindow
-0172 stdcall EndDeferWindowPos(long) EndDeferWindowPos
+0171 stdcall EnableWindow(long long) EnableWindow32
+0172 stdcall EndDeferWindowPos(long) EndDeferWindowPos32
 0173 stdcall EndDialog(long long) EndDialog
 0174 stdcall EndMenu() EndMenu
 0175 stdcall EndPaint(long ptr) EndPaint32
@@ -208,7 +208,7 @@
 0201 stdcall FlashWindow(long long) FlashWindow
 0202 stdcall FrameRect(long ptr long) FrameRect32
 0203 stub FreeDDElParam
-0204 stdcall GetActiveWindow() GetActiveWindow
+0204 stdcall GetActiveWindow() GetActiveWindow32
 0205 stdcall GetAppCompatFlags(long) GetAppCompatFlags
 0206 stdcall GetAsyncKeyState(long) GetAsyncKeyState
 0207 stdcall GetCapture() GetCapture32
@@ -237,9 +237,9 @@
 0230 stdcall GetDCEx(long long long) GetDCEx32
 0231 stdcall GetDesktopWindow() GetDesktopWindow32
 0232 stdcall GetDialogBaseUnits() GetDialogBaseUnits
-0233 stdcall GetDlgCtrlID(long) GetDlgCtrlID
-0234 stdcall GetDlgItem(long long) GetDlgItem
-0235 stdcall GetDlgItemInt(long long long long) GetDlgItemInt
+0233 stdcall GetDlgCtrlID(long) GetDlgCtrlID32
+0234 stdcall GetDlgItem(long long) GetDlgItem32
+0235 stdcall GetDlgItemInt(long long ptr long) GetDlgItemInt32
 0236 stdcall GetDlgItemTextA(long long ptr long) GetDlgItemText32A
 0237 stdcall GetDlgItemTextW(long long ptr long) GetDlgItemText32W
 0238 stub GetDoubleClickTime
@@ -259,7 +259,7 @@
 0252 stub GetKeyboardLayoutNameW
 0253 stub GetKeyboardState
 0254 stub GetKeyboardType
-0255 stub GetLastActivePopup
+0255 stdcall GetLastActivePopup(long) GetLastActivePopup
 0256 stdcall GetMenu(long) GetMenu32
 0257 stdcall GetMenuCheckMarkDimensions() GetMenuCheckMarkDimensions
 0258 stub GetMenuContextHelpId
@@ -299,13 +299,13 @@
 0292 stdcall GetTabbedTextExtentA(long ptr long long ptr) GetTabbedTextExtent
 0293 stub GetTabbedTextExtentW
 0294 stub GetThreadDesktop
-0295 stub GetTopWindow
+0295 stdcall GetTopWindow(long) GetTopWindow32
 0296 stdcall GetUpdateRect(long ptr long) GetUpdateRect32
 0297 stdcall GetUpdateRgn(long long long) GetUpdateRgn
 0298 stub GetUserObjectInformationA
 0299 stub GetUserObjectInformationW
 0300 stub GetUserObjectSecurity
-0301 stdcall GetWindow(long long) GetWindow
+0301 stdcall GetWindow(long long) GetWindow32
 0302 stub GetWindowContextHelpId
 0303 stdcall GetWindowDC(long) GetWindowDC32
 0304 stdcall GetWindowLongA(long long) GetWindowLong32A
@@ -342,20 +342,20 @@
 0335 stdcall IsCharLowerW(long) IsCharLower32W
 0336 stdcall IsCharUpperA(long) IsCharUpper32A
 0337 stdcall IsCharUpperW(long) IsCharUpper32W
-0338 stub IsChild
+0338 stdcall IsChild(long long) IsChild32
 0339 stdcall IsClipboardFormatAvailable(long) IsClipboardFormatAvailable
 0340 stub IsDialogMessage
 0341 stdcall IsDialogMessageA(long ptr) IsDialogMessage32A
 0342 stub IsDialogMessageW
-0343 stdcall IsDlgButtonChecked(long long) IsDlgButtonChecked
-0344 stdcall IsIconic(long) IsIconic
+0343 stdcall IsDlgButtonChecked(long long) IsDlgButtonChecked32
+0344 stdcall IsIconic(long) IsIconic32
 0345 stdcall IsMenu(long) IsMenu32
 0346 stdcall IsRectEmpty(ptr) IsRectEmpty32
 0347 stdcall IsWindow(long) IsWindow
-0348 stdcall IsWindowEnabled(long) IsWindowEnabled
+0348 stdcall IsWindowEnabled(long) IsWindowEnabled32
 0349 stdcall IsWindowUnicode(long) IsWindowUnicode
-0350 stdcall IsWindowVisible(long) IsWindowVisible
-0351 stdcall IsZoomed(long) IsZoomed
+0350 stdcall IsWindowVisible(long) IsWindowVisible32
+0351 stdcall IsZoomed(long) IsZoomed32
 0352 stdcall KillSystemTimer(long long) KillSystemTimer32
 0353 stdcall KillTimer(long long) KillTimer32
 0354 stdcall LoadAcceleratorsA(long ptr) LoadAccelerators32A
@@ -402,7 +402,7 @@
 0395 stdcall MessageBoxW(long ptr ptr long) MessageBox32W
 0396 stdcall ModifyMenuA(long long long long ptr) ModifyMenu32A
 0397 stdcall ModifyMenuW(long long long long ptr) ModifyMenu32W
-0398 stdcall MoveWindow(long long long long long long) MoveWindow
+0398 stdcall MoveWindow(long long long long long long) MoveWindow32
 0399 stub MsgWaitForMultipleObjects
 0400 stub OemKeyScan
 0401 stdcall OemToCharA(ptr ptr) OemToChar32A
@@ -466,7 +466,7 @@
 0459 stub SendNotifyMessageA
 0460 stub SendNotifyMessageW
 0461 stub ServerSetFunctionPointers
-0462 stdcall SetActiveWindow(long) SetActiveWindow
+0462 stdcall SetActiveWindow(long) SetActiveWindow32
 0463 stdcall SetCapture(long) SetCapture32
 0464 stdcall SetCaretBlinkTime(long) SetCaretBlinkTime
 0465 stdcall SetCaretPos(long long) SetCaretPos
@@ -523,7 +523,7 @@
 0516 stdcall SetWindowLongA(long long long) SetWindowLong32A
 0517 stdcall SetWindowLongW(long long long) SetWindowLong32W
 0518 stdcall SetWindowPlacement(long ptr) SetWindowPlacement32
-0519 stdcall SetWindowPos(long long long long long long long) SetWindowPos
+0519 stdcall SetWindowPos(long long long long long long long) SetWindowPos32
 0520 stub SetWindowStationUser
 0521 stdcall SetWindowTextA(long ptr) SetWindowText32A
 0522 stdcall SetWindowTextW(long ptr) SetWindowText32W
@@ -537,7 +537,7 @@
 0530 stub ShowOwnedPopups
 0531 stdcall ShowScrollBar(long long long) ShowScrollBar32
 0532 stub ShowStartGlass
-0533 stdcall ShowWindow(long long) ShowWindow
+0533 stdcall ShowWindow(long long) ShowWindow32
 0534 stub ShowWindowAsync
 0535 stdcall SubtractRect(ptr ptr ptr) SubtractRect32
 0536 stdcall SwapMouseButton(long) SwapMouseButton
diff --git a/include/debugger.h b/include/debugger.h
index 13779d0..91f5121 100644
--- a/include/debugger.h
+++ b/include/debugger.h
@@ -167,9 +167,9 @@
 struct expr * DEBUG_StructExpr(struct expr *, const char * element);
 struct expr * DEBUG_ArrayExpr(struct expr *, struct expr * index);
 struct expr * DEBUG_CallExpr(const char *, int nargs, ...);
+struct expr * DEBUG_TypeCastExpr(struct datatype *, struct expr *);
 extern   int  DEBUG_ExprValue(DBG_ADDR *, unsigned int *);
 DBG_ADDR DEBUG_EvalExpr(struct expr *);
-extern int DEBUG_AddDisplay(struct expr * exp);
 extern int DEBUG_DelDisplay(int displaynum);
 extern struct expr * DEBUG_CloneExpr(struct expr * exp);
 extern int DEBUG_FreeExpr(struct expr * exp);
@@ -180,7 +180,7 @@
 
   /* debugger/display.c */
 extern int DEBUG_DoDisplay(void);
-extern int DEBUG_AddDisplay(struct expr * exp);
+extern int DEBUG_AddDisplay(struct expr * exp, int count, char format);
 extern int DEBUG_DoDisplay(void);
 extern int DEBUG_DelDisplay(int displaynum);
 extern int DEBUG_InfoDisplay(void);
@@ -273,6 +273,7 @@
 extern void DEBUG_InitCVDataTypes(void);
 
   /* debugger/types.c */
+extern int DEBUG_nchar;
 extern void DEBUG_InitTypes(void);
 extern struct datatype * DEBUG_NewDataType(enum debug_type xtype, 
 					   const char * typename);
@@ -296,7 +297,9 @@
 extern int DEBUG_SetBitfieldParams(struct datatype * dt, int offset, 
 				   int nbits, struct datatype * dt2);
 extern int DEBUG_CopyFieldlist(struct datatype * dt, struct datatype * dt2);
-
+extern enum debug_type DEBUG_GetType(struct datatype * dt);
+extern struct datatype * DEBUG_TypeCast(enum debug_type, const char *);
+extern int DEBUG_PrintTypeCast(struct datatype *);
 
   /* debugger/source.c */
 extern void DEBUG_ShowDir(void);
diff --git a/include/keyboard.h b/include/keyboard.h
index 95f681c..9465e3c 100644
--- a/include/keyboard.h
+++ b/include/keyboard.h
@@ -1,32 +1,19 @@
 /*
- * Keyboard definitions
+ * Keyboard header file
+ * Copyright 1997 David Faure
  *
  */
 
 #ifndef __WINE_KEYBOARD_H
 #define __WINE_KEYBOARD_H
 
-#define WINE_VKEY_MAPPINGS\
-		vkcase('!', '1')\
-		vkcase('@', '2')\
-		vkcase('#', '3')\
-		vkcase('$', '4')\
-		vkcase('%', '5')\
-		vkcase('^', '6')\
-		vkcase('&', '7')\
-		vkcase('*', '8')\
-		vkcase('(', '9')\
-		vkcase(')', '0')\
-		vkcase2('`', '~', 0xc0)\
-		vkcase2('-', '_', 0xbd)\
-		vkcase2('=', '+', 0xbb)\
-		vkcase2('[', '{', 0xdb)\
-		vkcase2(']', '}', 0xdd)\
-		vkcase2(';', ':', 0xba)\
-		vkcase2('\'', '"', 0xde)\
-		vkcase2(',', '<', 0xbc)\
-		vkcase2('.', '>', 0xbe)\
-		vkcase2('/', '?', 0xbf)\
-		vkcase2('\\', '|', 0xdc)
+extern BOOL32 MouseButtonsStates[3];
+extern BOOL32 AsyncMouseButtonsStates[3];
+extern BYTE InputKeyStateTable[256];
+extern BYTE QueueKeyStateTable[256];
+extern BYTE AsyncKeyStateTable[256];
+
+extern BOOL32 KEYBOARD_Init(void);
+extern void KEYBOARD_HandleEvent( XKeyEvent *event );
 
 #endif  /* __WINE_KEYBOARD_H */
diff --git a/include/module.h b/include/module.h
index 3b52039..953cdfb 100644
--- a/include/module.h
+++ b/include/module.h
@@ -120,6 +120,7 @@
 extern HMODULE16 MODULE_FindModule( LPCSTR path );
 extern HINSTANCE16 MODULE_GetInstance( HMODULE16 hModule );
 extern HMODULE16 MODULE_CreateDummyModule( const OFSTRUCT *ofs );
+extern HINSTANCE16 MODULE_Load( LPCSTR name, LPVOID paramBlock, BOOL32 first );
 extern WORD MODULE_GetOrdinal( HMODULE16 hModule, const char *name );
 extern FARPROC16 MODULE_GetEntryPoint( HMODULE16 hModule, WORD ordinal );
 extern BOOL16 MODULE_SetEntryPoint( HMODULE16 hModule, WORD ordinal,
diff --git a/include/pe_image.h b/include/pe_image.h
index 1336fff..1130ba8 100644
--- a/include/pe_image.h
+++ b/include/pe_image.h
@@ -3,14 +3,16 @@
 
 #include <sys/types.h>
 #include "windows.h"
+#include "winnt.h"
+#include "peexe.h"
 
 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;
-	struct PE_Reloc_Block *pe_reloc;
+	LPIMAGE_NT_HEADERS			pe_header;
+	LPIMAGE_SECTION_HEADER			pe_seg;
+	LPIMAGE_IMPORT_DESCRIPTOR		pe_import;
+	LPIMAGE_EXPORT_DIRECTORY		pe_export;
+	LPIMAGE_RESOURCE_DIRECTORY		pe_resource;
+	LPIMAGE_BASE_RELOCATION			pe_reloc;
 	int base_addr;
 	int load_addr;
 	int vma_size;
diff --git a/include/peexe.h b/include/peexe.h
index ca46e97..c75450c 100644
--- a/include/peexe.h
+++ b/include/peexe.h
@@ -5,18 +5,17 @@
 #define __WINE_PEEXE_H
 
 
+typedef struct _IMAGE_FILE_HEADER {
+	WORD	Machine;
+	WORD	NumberOfSections;
+	DWORD	TimeDateStamp;
+	DWORD	PointerToSymbolTable;
+	DWORD	NumberOfSymbols;
+	WORD	SizeOfOptionalHeader;
+	WORD	Characteristics;
+} IMAGE_FILE_HEADER,*LPIMAGE_FILE_HEADER;
 
-struct coff_header
-{
-	u_short Machine;
-	u_short NumberOfSections;
-        u_long TimeDateStamp;
-        u_long PointerToSymbolTable;
-        u_long NumberOfSymbols;
-        u_short SizeOfOptionalHeader;
-        u_short Characteristics;
-};
-
+#define	IMAGE_SIZEOF_FILE_HEADER	20
 
 /* These defines describe the meanings of the bits in the Characteristics
    field */
@@ -34,194 +33,343 @@
 #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
+#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_R10000	0x168
+#define	IMAGE_FILE_MACHINE_ALPHA	0x184
+#define	IMAGE_FILE_MACHINE_POWERPC	0x1F0  
 
-struct Directory
+typedef struct _IMAGE_DATA_DIRECTORY
 {
-  u_long Virtual_address;
-  u_long Size;
-};
+	DWORD	VirtualAddress;
+	DWORD	Size;
+} IMAGE_DATA_DIRECTORY,*LPIMAGE_DATA_DIRECTORY;
 
+#define	IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16
 
 /* Optional coff header - used by NT to provide additional information. */
-
-struct ocoffhdr
+typedef struct _IMAGE_OPTIONAL_HEADER
 {
-	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];
-};
+	/*
+	 * Standard fields.
+	 */
+
+	WORD	Magic;
+	BYTE	MajorLinkerVersion;
+	BYTE	MinorLinkerVersion;
+	DWORD	SizeOfCode;
+	DWORD	SizeOfInitializedData;
+	DWORD	SizeOfUninitializedData;
+	DWORD	AddressOfEntryPoint;
+	DWORD	BaseOfCode;
+	DWORD	BaseOfData;
+
+	/*
+	 * NT additional fields.
+	 */
+
+	DWORD	ImageBase;
+	DWORD	SectionAlignment;
+	DWORD	FileAlignment;
+	WORD	MajorOperatingSystemVersion;
+	WORD	MinorOperatingSystemVersion;
+	WORD	MajorImageVersion;
+	WORD	MinorImageVersion;
+	WORD	MajorSubsystemVersion;
+	WORD	MinorSubsystemVersion;
+	DWORD	Reserved1;
+	DWORD	SizeOfImage;
+	DWORD	SizeOfHeaders;
+	DWORD	CheckSum;
+	WORD	Subsystem;
+	WORD	DllCharacteristics;
+	DWORD	SizeOfStackReserve;
+	DWORD	SizeOfStackCommit;
+	DWORD	SizeOfHeapReserve;
+	DWORD	SizeOfHeapCommit;
+	DWORD	LoaderFlags;
+	DWORD	NumberOfRvaAndSizes;
+	IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
+} IMAGE_OPTIONAL_HEADER,*LPIMAGE_OPTIONAL_HEADER;
 
 /* 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
+#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;
-};
+/* Directory Entries, indices into the DataDirectory array */
 
+#define	IMAGE_DIRECTORY_ENTRY_EXPORT		0
+#define	IMAGE_DIRECTORY_ENTRY_IMPORT		1
+#define	IMAGE_DIRECTORY_ENTRY_RESOURCE		2
+#define	IMAGE_DIRECTORY_ENTRY_EXCEPTION		3
+#define	IMAGE_DIRECTORY_ENTRY_SECURITY		4
+#define	IMAGE_DIRECTORY_ENTRY_BASERELOC		5
+#define	IMAGE_DIRECTORY_ENTRY_DEBUG		6
+#define	IMAGE_DIRECTORY_ENTRY_COPYRIGHT		7
+#define	IMAGE_DIRECTORY_ENTRY_GLOBALPTR		8   /* (MIPS GP) */
+#define	IMAGE_DIRECTORY_ENTRY_TLS		9
+#define	IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG	10
+#define	IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT	11
+#define	IMAGE_DIRECTORY_ENTRY_IAT		12  /* Import Address Table */
 
-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;
-};
+/* Subsystem Values */
+
+#define	IMAGE_SUBSYSTEM_UNKNOWN		0
+#define	IMAGE_SUBSYSTEM_NATIVE		1
+#define	IMAGE_SUBSYSTEM_WINDOWS_GUI	2	/* Windows GUI subsystem */
+#define	IMAGE_SUBSYSTEM_WINDOWS_CUI	3	/* Windows character subsystem*/
+#define	IMAGE_SUBSYSTEM_OS2_CUI		5
+#define	IMAGE_SUBSYSTEM_POSIX_CUI	7
+
+typedef struct _IMAGE_NT_HEADERS {
+	DWORD			Signature;
+	IMAGE_FILE_HEADER	FileHeader;
+	IMAGE_OPTIONAL_HEADER	OptionalHeader;
+} IMAGE_NT_HEADERS,*LPIMAGE_NT_HEADERS;
+
+/* Section header format */
+
+#define	IMAGE_SIZEOF_SHORT_NAME	8
+
+typedef struct _IMAGE_SECTION_HEADER {
+	BYTE	Name[IMAGE_SIZEOF_SHORT_NAME];
+	union {
+		DWORD	PhysicalAddress;
+		DWORD	VirtualSize;
+	} Misc;
+	DWORD	VirtualAddress;
+	DWORD	SizeOfRawData;
+	DWORD	PointerToRawData;
+	DWORD	PointerToRelocations;
+	DWORD	PointerToLinenumbers;
+	WORD	NumberOfRelocations;
+	WORD	NumberOfLinenumbers;
+	DWORD	Characteristics;
+} IMAGE_SECTION_HEADER,*LPIMAGE_SECTION_HEADER;
+
+#define	IMAGE_SIZEOF_SECTION_HEADER 40
 
 /* These defines are for the Characteristics bitfield. */
+/* #define IMAGE_SCN_TYPE_REG			0x00000000 - Reserved */
+/* #define IMAGE_SCN_TYPE_DSECT			0x00000001 - Reserved */
+/* #define IMAGE_SCN_TYPE_NOLOAD		0x00000002 - Reserved */
+/* #define IMAGE_SCN_TYPE_GROUP			0x00000004 - Reserved */
+/* #define IMAGE_SCN_TYPE_NO_PAD		0x00000008 - Reserved */
+/* #define IMAGE_SCN_TYPE_COPY			0x00000010 - Reserved */
 
-#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
+#define IMAGE_SCN_CNT_CODE			0x00000020
+#define IMAGE_SCN_CNT_INITIALIZED_DATA		0x00000040
+#define IMAGE_SCN_CNT_UNINITIALIZED_DATA	0x00000080
 
-/*
- * Import module directory stuff
- */
+#define	IMAGE_SCN_LNK_OTHER			0x00000100 
+#define	IMAGE_SCN_LNK_INFO			0x00000200  
+/* #define	IMAGE_SCN_TYPE_OVER		0x00000400 - Reserved */
+#define	IMAGE_SCN_LNK_REMOVE			0x00000800
+#define	IMAGE_SCN_LNK_COMDAT			0x00001000
 
-struct PE_Import_Directory
-{
-  u_int Import_List;
-  u_int TimeDate;
-  u_int Forwarder;
-  u_int ModuleName;
-  u_int Thunk_List;
-};
+/* 						0x00002000 - Reserved */
+/* #define IMAGE_SCN_MEM_PROTECTED 		0x00004000 - Obsolete */
+#define	IMAGE_SCN_MEM_FARDATA			0x00008000
 
-struct pe_import_name
-{
-  u_short Hint;
-  u_char Name[1];
-};
+/* #define IMAGE_SCN_MEM_SYSHEAP		0x00010000 - Obsolete */
+#define	IMAGE_SCN_MEM_PURGEABLE			0x00020000
+#define	IMAGE_SCN_MEM_16BIT			0x00020000
+#define	IMAGE_SCN_MEM_LOCKED			0x00040000
+#define	IMAGE_SCN_MEM_PRELOAD			0x00080000
 
-/*
- * Export module directory stuff
- */
+#define	IMAGE_SCN_ALIGN_1BYTES			0x00100000
+#define	IMAGE_SCN_ALIGN_2BYTES			0x00200000
+#define	IMAGE_SCN_ALIGN_4BYTES			0x00300000
+#define	IMAGE_SCN_ALIGN_8BYTES			0x00400000
+#define	IMAGE_SCN_ALIGN_16BYTES			0x00500000  /* Default */
+#define IMAGE_SCN_ALIGN_32BYTES			0x00600000
+#define IMAGE_SCN_ALIGN_64BYTES			0x00700000
+/* 						0x00800000 - Unused */
 
-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;
+#define IMAGE_SCN_LNK_NRELOC_OVFL		0x01000000
+
+
+#define IMAGE_SCN_MEM_DISCARDABLE		0x02000000
+#define IMAGE_SCN_MEM_NOT_CACHED		0x04000000
+#define IMAGE_SCN_MEM_NOT_PAGED			0x08000000
+#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 name entry */
+typedef struct _IMAGE_IMPORT_BY_NAME {
+	WORD	Hint;
+	BYTE	Name[1];
+} IMAGE_IMPORT_BY_NAME,*LPIMAGE_IMPORT_BY_NAME;
+
+/* Import thunk */
+typedef struct _IMAGE_THUNK_DATA {
+	union {
+		LPBYTE	ForwarderString;
+		LPDWORD	Function;
+		DWORD	Ordinal;
+		LPIMAGE_IMPORT_BY_NAME	AddressOfData;
+	} u1;
+} IMAGE_THUNK_DATA,*LPIMAGE_THUNK_DATA;
+
+/* Import module directory */
+
+typedef struct _IMAGE_IMPORT_DESCRIPTOR {
+	union {
+		DWORD	Characteristics; /* 0 for terminating null import descriptor  */
+		LPIMAGE_THUNK_DATA OriginalFirstThunk;	/* RVA to original unbound IAT */
+	} u;
+	DWORD	TimeDateStamp;	/* 0 if not bound,
+				 * -1 if bound, and real date\time stamp
+				 *    in IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
+				 * (new BIND)
+				 * otherwise date/time stamp of DLL bound to
+				 * (Old BIND)
+				 */
+	DWORD	ForwarderChain;	/* -1 if no forwarders */
+	DWORD	Name;
+	/* RVA to IAT (if bound this IAT has actual addresses) */
+	LPIMAGE_THUNK_DATA FirstThunk;	
+} IMAGE_IMPORT_DESCRIPTOR,*LPIMAGE_IMPORT_DESCRIPTOR;
+
+#define	IMAGE_ORDINAL_FLAG		0x80000000
+#define	IMAGE_SNAP_BY_ORDINAL(Ordinal)	((Ordinal & IMAGE_ORDINAL_FLAG) != 0)
+#define	IMAGE_ORDINAL(Ordinal)		(Ordinal & 0xffff)
+
+/* Export module directory */
+
+typedef struct _IMAGE_EXPORT_DIRECTORY {
+	DWORD	Characteristics;
+	DWORD	TimeDateStamp;
+	WORD	MajorVersion;
+	WORD	MinorVersion;
+	DWORD	Name;
+	DWORD	Base;
+	DWORD	NumberOfFunctions;
+	DWORD	NumberOfNames;
+	LPDWORD	*AddressOfFunctions;
+	LPDWORD	*AddressOfNames;
+	LPWORD	*AddressOfNameOrdinals;
 /*  u_char ModuleName[1]; */
-};
+} IMAGE_EXPORT_DIRECTORY,*LPIMAGE_EXPORT_DIRECTORY;
+
 
 /*
  * Resource directory stuff
  */
+typedef struct _IMAGE_RESOURCE_DIRECTORY {
+	DWORD	Characteristics;
+	DWORD	TimeDateStamp;
+	WORD	MajorVersion;
+	WORD	MinorVersion;
+	WORD	NumberOfNamedEntries;
+	WORD	NumberOfIdEntries;
+	/*  IMAGE_RESOURCE_DIRECTORY_ENTRY DirectoryEntries[]; */
+} IMAGE_RESOURCE_DIRECTORY,*LPIMAGE_RESOURCE_DIRECTORY;
 
-struct PE_Resource_Directory
+#define	IMAGE_RESOURCE_NAME_IS_STRING		0x80000000
+#define	IMAGE_RESOURCE_DATA_IS_DIRECTORY	0x80000000
+
+typedef struct _IMAGE_RESOURCE_DIRECTORY_ENTRY {
+	union {
+		struct {
+			DWORD NameOffset:31;
+			DWORD NameIsString:1;
+		} s;
+		DWORD   Name;
+		WORD    Id;
+	} u1;
+	union {
+		DWORD   OffsetToData;
+		struct {
+			DWORD   OffsetToDirectory:31;
+			DWORD   DataIsDirectory:1;
+		} s;
+	} u2;
+} IMAGE_RESOURCE_DIRECTORY_ENTRY,*LPIMAGE_RESOURCE_DIRECTORY_ENTRY;
+
+
+typedef struct _IMAGE_RESOURCE_DIRECTORY_STRING {
+	WORD	Length;
+	CHAR	NameString[ 1 ];
+} IMAGE_RESOURCE_DIRECTORY_STRING,*LPIMAGE_RESOURCE_DIRECTORY_STRING;
+
+typedef struct _IMAGE_RESOURCE_DIR_STRING_U {
+	WORD	Length;
+	WCHAR	NameString[ 1 ];
+} IMAGE_RESOURCE_DIR_STRING_U,*LPIMAGE_RESOURCE_DIR_STRING_U;
+
+typedef struct _IMAGE_RESOURCE_DATA_ENTRY {
+	DWORD	OffsetToData;
+	DWORD	Size;
+	DWORD	CodePage;
+	DWORD	Reserved;
+} IMAGE_RESOURCE_DATA_ENTRY,*LPIMAGE_RESOURCE_DATA_ENTRY;
+
+typedef struct _IMAGE_BASE_RELOCATION
 {
-  u_long Characteristics;
-  u_long TimeDateStamp;
-  u_short MajorVersion;
-  u_short MinorVersion;
-  u_short NumberOfNamedEntries;
-  u_short NumberOfIdEntries;
-};
+	DWORD	VirtualAddress;
+	DWORD	SizeOfBlock;
+	WORD	TypeOffset[1];
+} IMAGE_BASE_RELOCATION,*LPIMAGE_BASE_RELOCATION;
 
-struct PE_Directory_Entry
-{
-  u_long Name;
-  u_long OffsetToData;
-};
+typedef struct _IMAGE_DEBUG_DIRECTORY {
+	DWORD	Characteristics;
+	DWORD	TimeDateStamp;
+	WORD	MajorVersion;
+	WORD	MinorVersion;
+	DWORD	Type;
+	DWORD	SizeOfData;
+	DWORD	AddressOfRawData;
+	DWORD	PointerToRawData;
+} IMAGE_DEBUG_DIRECTORY,*LPIMAGE_DEBUG_DIRECTORY;
 
-struct PE_Directory_Name_String
-{
-  u_short Length;
-  char NameString[1];
-};
+typedef struct _IMAGE_LOAD_CONFIG_DIRECTORY {
+	DWORD	Characteristics;
+	DWORD	TimeDateStamp;
+	WORD	MajorVersion;
+	WORD	MinorVersion;
+	DWORD	GlobalFlagsClear;
+	DWORD	GlobalFlagsSet;
+	DWORD	CriticalSectionDefaultTimeout;
+	DWORD	DeCommitFreeBlockThreshold;
+	DWORD	DeCommitTotalFreeThreshold;
+	LPVOID	LockPrefixTable;
+	DWORD	MaximumAllocationSize;
+	DWORD	VirtualMemoryThreshold;
+	DWORD	ProcessHeapFlags;
+	DWORD	Reserved[ 4 ];
+} IMAGE_LOAD_CONFIG_DIRECTORY,*LPIMAGE_LOAD_CONFIG_DIRECTORY;
 
-struct PE_Directory_Name_String_U
-{
-  u_short Length;
-  u_short NameString[1];
-};
+typedef VOID (*LPIMAGE_TLS_CALLBACK)(
+	LPVOID DllHandle,DWORD Reason,LPVOID Reserved
+);
 
-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
-
-struct PE_Reloc_Block
-{
-	u_long PageRVA;
-	u_long BlockSize;
-	short Relocations[1];
-};
+typedef struct _IMAGE_TLS_DIRECTORY {
+	DWORD	StartAddressOfRawData;
+	DWORD	EndAddressOfRawData;
+	LPDWORD	AddressOfIndex;
+	LPIMAGE_TLS_CALLBACK *AddressOfCallBacks;
+	DWORD	SizeOfZeroFill;
+	DWORD	Characteristics;
+} IMAGE_TLS_DIRECTORY,*LPIMAGE_TLS_DIRECTORY;
 
 /*
- * The IMAGE_FILE_DEBUG_DIRECTORY data directory points to an array of
+ * The IMAGE_DEBUG_DIRECTORY data directory points to an array of
  * these structures.
  */
 struct PE_Debug_dir
@@ -245,30 +393,37 @@
 #define IMAGE_DEBUG_TYPE_CODEVIEW	2
 #define IMAGE_DEBUG_TYPE_FPO		3
 #define IMAGE_DEBUG_TYPE_MISC		4
+#define IMAGE_DEBUG_TYPE_EXCEPTION	5
+#define IMAGE_DEBUG_TYPE_FIXUP		6
+#define IMAGE_DEBUG_TYPE_OMAP_TO_SRC	7
+#define IMAGE_DEBUG_TYPE_OMAP_FROM_SRC	8
+
 
 #define IMAGE_REL_BASED_ABSOLUTE 		0
 #define IMAGE_REL_BASED_HIGH			1
-#define IMAGE_REL_BASED_LOW				2
+#define IMAGE_REL_BASED_LOW			2
 #define IMAGE_REL_BASED_HIGHLOW			3
 #define IMAGE_REL_BASED_HIGHADJ			4
-#define IMAGE_REL_BASED_MIPS_JMPADDR	5
+#define IMAGE_REL_BASED_MIPS_JMPADDR		5
 
 /*
  * This is the structure that appears at the very start of a .DBG file.
  */
-struct PE_DBG_FileHeader {
-    unsigned short int Signature;
-    unsigned short int Flags;
-    unsigned short int Machine;
-    unsigned short int Characteristics;
-    unsigned int       TimeDateStamp;
-    unsigned int       CheckSum;
-    unsigned int       ImageBase;
-    unsigned int       SizeOfImage;
-    unsigned int       NumberOfSections;
-    unsigned int       ExportedNamesSize;
-    unsigned int       DebugDirectorySize;
-    unsigned int       Reserved[ 3 ];
-};
+typedef struct _IMAGE_SEPARATE_DEBUG_HEADER {
+	WORD	Signature;
+	WORD	Flags;
+	WORD	Machine;
+	WORD	Characteristics;
+	DWORD	TimeDateStamp;
+	DWORD	CheckSum;
+	DWORD	ImageBase;
+	DWORD	SizeOfImage;
+	DWORD	NumberOfSections;
+	DWORD	ExportedNamesSize;
+	DWORD	DebugDirectorySize;
+	DWORD	Reserved[ 3 ];
+} IMAGE_SEPARATE_DEBUG_HEADER,*LPIMAGE_SEPARATE_DEBUG_HEADER;
+
+#define IMAGE_SEPARATE_DEBUG_SIGNATURE 0x4944
 
 #endif /* __WINE_PEEXE_H */
diff --git a/include/resource.h b/include/resource.h
index 0898fed..02a6dd4 100644
--- a/include/resource.h
+++ b/include/resource.h
@@ -22,6 +22,7 @@
 typedef enum
 {
     SYSRES_MENU_SYSMENU,
+    SYSRES_MENU_EDITMENU,
     SYSRES_DIALOG_MSGBOX,
     SYSRES_DIALOG_SHELL_ABOUT_MSGBOX,
     SYSRES_DIALOG_OPEN_FILE,
diff --git a/include/resource32.h b/include/resource32.h
deleted file mode 100644
index 644b6ae..0000000
--- a/include/resource32.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Win32 functions, structures, and types related to resources
- *
- * Copyright 1995 Thomas Sandford
- *
- */
-
-#ifndef __WINE_RESOURCE32_H
-#define __WINE_RESOURCE32_H
-
-#include <stddef.h>
-
-typedef struct _IMAGE_RESOURCE_DIRECTORY {
-	DWORD Characteristics;
-	DWORD TimeDateStamp;
-	WORD MajorVersion;
-	WORD MinorVersion;
-	WORD NumberOfNamedEntries;
-	WORD NumberOfIdEntries;
-} IMAGE_RESOURCE_DIRECTORY, *PIMAGE_RESOURCE_DIRECTORY;
-
-typedef struct _IMAGE_RESOURCE_DIRECTORY_ENTRY {
-	DWORD Name;
-	DWORD OffsetToData;
-} IMAGE_RESOURCE_DIRECTORY_ENTRY, *PIMAGE_RESOURCE_DIRECTORY_ENTRY;
-
-typedef struct _IMAGE_RESOURCE_DATA_ENTRY {
-	DWORD OffsetToData;
-	DWORD Size;
-	DWORD CodePage;
-	DWORD Reserved;
-} IMAGE_RESOURCE_DATA_ENTRY, *PIMAGE_RESOURCE_DATA_ENTRY;
-
-typedef struct _IMAGE_RESOURCE_DIR_STRING_U {
-	WORD Length;
-	WCHAR NameString[1];
-} IMAGE_RESOURCE_DIR_STRING_U, *PIMAGE_RESOURCE_DIR_STRING_U;
-
-#endif  /* __WINE_RESOURCE32_H */
diff --git a/include/sigcontext.h b/include/sigcontext.h
index 24e5a59..157bd91 100644
--- a/include/sigcontext.h
+++ b/include/sigcontext.h
@@ -44,6 +44,11 @@
 typedef struct sigcontext SIGCONTEXT;
 #endif  /* NetBSD */
 
+#ifdef __FreeBSD__
+#include <signal.h>
+typedef struct sigcontext SIGCONTEXT;
+#endif  /* FreeBSD */
+
 #if defined(__svr4__) || defined(_SCO_DS)
 #include <signal.h>
 #ifdef _SCO_DS
@@ -53,12 +58,12 @@
 typedef struct ucontext SIGCONTEXT;
 #endif  /* svr4 || SCO_DS */
 
-#ifdef __FreeBSD__
-#include <signal.h>
-typedef struct sigcontext SIGCONTEXT;
-#endif  /* FreeBSD */
+#ifdef __EMX__
+typedef struct CONTEXTRECORD SIGCONTEXT;
+#endif  /* __EMX__ */
 
-#if !defined(__svr4__) && !defined(_SCO_DS)
+
+#if defined(linux) || defined(__NetBSD__) || defined(__FreeBSD__)
 
 #define EAX_sig(context)     ((context)->sc_eax)
 #define EBX_sig(context)     ((context)->sc_ebx)
@@ -88,7 +93,9 @@
 #define EIP_sig(context)     ((context)->sc_eip)
 #define ESP_sig(context)     ((context)->sc_esp)
 
-#else  /* __svr4__ || _SCO_DS */
+#endif  /* linux || __NetBSD__ || __FreeBSD__ */
+
+#if defined(__svr4__) || defined(_SCO_DS)
 
 #ifdef _SCO_DS
 #define gregs regs
@@ -118,8 +125,31 @@
 #else
 #define ESP_sig(context)     ((context)->uc_mcontext.gregs[ESP])
 #endif
+
+#endif  /* svr4 || SCO_DS */
                             
-#endif  /* __svr4__ || _SCO_DS */
+#ifdef __EMX__
+
+#define EAX_sig(context)     ((context)->ctx_RegEax)
+#define EBX_sig(context)     ((context)->ctx_RegEbx)
+#define ECX_sig(context)     ((context)->ctx_RegEcx)
+#define EDX_sig(context)     ((context)->ctx_RegEdx)
+#define ESI_sig(context)     ((context)->ctx_RegEsi)
+#define EDI_sig(context)     ((context)->ctx_RegEdi)
+#define EBP_sig(context)     ((context)->ctx_RegEbp)
+#define ESP_sig(context)     ((context)->ctx_RegEsp)
+#define CS_sig(context)      ((context)->ctx_SegCS)
+#define DS_sig(context)      ((context)->ctx_SegDS)
+#define ES_sig(context)      ((context)->ctx_SegES)
+#define SS_sig(context)      ((context)->ctx_SegSS)
+#define FS_sig(context)      ((context)->ctx_SegFS)
+#define GS_sig(context)      ((context)->ctx_SegGS)
+#define EFL_sig(context)     ((context)->ctx_EFlags)
+#define EIP_sig(context)     ((context)->ctx_RegEip)
+
+#endif  /* __EMX__ */
+
+/* Generic definitions */
 
 #define AX_sig(context)      (*(WORD*)&EAX_sig(context))
 #define BX_sig(context)      (*(WORD*)&EBX_sig(context))
diff --git a/include/win16drv.h b/include/win16drv.h
index 6ee48af..c6d7349 100644
--- a/include/win16drv.h
+++ b/include/win16drv.h
@@ -110,23 +110,6 @@
 typedef short SHORT; 
 
 #pragma pack(1)
-
-typedef struct TEXTXFORM 
-{
-    SHORT  txfHeight;
-    SHORT  txfWidth;
-    SHORT  txfEscapement;
-    SHORT  txfOrientation;
-    SHORT  txfWeight;
-    CHAR   txfItalic;
-    CHAR   txfUnderline;
-    CHAR   txfStrikeOut;
-    CHAR   txfOutPrecision;
-    CHAR   txfClipPrecision;
-    SHORT  txfAccelerator WINE_PACKED;
-    SHORT  txfOverhang WINE_PACKED;
-} TEXTXFORM, *LPTEXTXFORM;
-
 #define PCOLOR DWORD
 typedef struct DRAWMODE 
 {
@@ -144,42 +127,6 @@
     COLORREF LTextColor; 
 } DRAWMODE, *LPDRAWMODE;
 
-typedef struct FONTINFO 
-{
-    SHORT dfType;
-    SHORT dfPoints;
-    SHORT dfVertRes;
-    SHORT dfHorizRes;
-    SHORT dfAscent;
-    SHORT dfInternalLeading;
-    SHORT dfExternalLeading;
-    CHAR  dfItalic;
-    CHAR  dfUnderline;
-    CHAR  dfStrikeOut;
-    SHORT dfWeight;
-    CHAR  dfCHARSet;
-    SHORT dfPixWidth;
-    SHORT dfPixHeight;
-    CHAR  dfPitchAndFamily;
-    SHORT dfAvgWidth;
-    SHORT dfMaxWidth;
-    CHAR  dfFirstCHAR;
-    CHAR  dfLastCHAR;
-    CHAR  dfDefaultCHAR;
-    CHAR  dfBreakCHAR;
-    SHORT dfWidthBytes;
-    LONG  dfDevice;
-    LONG  dfFace;
-    LONG  dfBitsPointer;
-    LONG  dfBitsOffset;
-    CHAR  dfReserved;
-    LONG  dfFlags;
-    SHORT dfAspace;
-    SHORT dfBspace;
-    SHORT dfCspace;
-    LONG  dfColorPointer;
-    LONG  dfReserved1[4];
-} FONTINFO, *LPFONTINFO;
 
 #pragma pack(4)
 
@@ -211,4 +158,7 @@
                                            LPSIZE32 size );
 extern BOOL32 WIN16DRV_GetTextMetrics( DC *dc, TEXTMETRIC32A *metrics );
 
+extern BOOL32 WIN16DRV_ExtTextOut( DC *dc, INT32 x, INT32 y, UINT32 flags,
+                                  const RECT32 *lprect, LPCSTR str, UINT32 count,
+                                  const INT32 *lpDx );
 #endif  /* __WINE_WIN16DRV_H */
diff --git a/include/winbase.h b/include/winbase.h
index 5b432c7..e277353 100644
--- a/include/winbase.h
+++ b/include/winbase.h
@@ -46,6 +46,7 @@
 
 /*WINAPI int  SetErrorMode(int);*/
 
+#define STATUS_SUCCESS                   0x00000000
 #define STATUS_WAIT_0                    0x00000000    
 #define STATUS_ABANDONED_WAIT_0          0x00000080    
 #define STATUS_USER_APC                  0x000000C0    
@@ -55,10 +56,12 @@
 #define STATUS_DATATYPE_MISALIGNMENT     0x80000002    
 #define STATUS_BREAKPOINT                0x80000003    
 #define STATUS_SINGLE_STEP               0x80000004    
+#define	STATUS_BUFFER_OVERFLOW           0x80000005
 #define STATUS_ACCESS_VIOLATION          0xC0000005    
 #define STATUS_IN_PAGE_ERROR             0xC0000006    
 #define STATUS_NO_MEMORY                 0xC0000017    
 #define STATUS_ILLEGAL_INSTRUCTION       0xC000001D    
+#define	STATUS_BUFFER_TOO_SMALL          0xC0000023
 #define STATUS_NONCONTINUABLE_EXCEPTION  0xC0000025    
 #define STATUS_INVALID_DISPOSITION       0xC0000026    
 #define STATUS_ARRAY_BOUNDS_EXCEEDED     0xC000008C    
@@ -72,6 +75,7 @@
 #define STATUS_INTEGER_DIVIDE_BY_ZERO    0xC0000094    
 #define STATUS_INTEGER_OVERFLOW          0xC0000095    
 #define STATUS_PRIVILEGED_INSTRUCTION    0xC0000096    
+#define	STATUS_INVALID_PARAMETER_2       0xC00000F0
 #define STATUS_STACK_OVERFLOW            0xC00000FD    
 #define STATUS_CONTROL_C_EXIT            0xC000013A    
 
diff --git a/include/windows.h b/include/windows.h
index a65782d..4d71ced 100644
--- a/include/windows.h
+++ b/include/windows.h
@@ -1087,6 +1087,58 @@
   DWORD fsCsb[2];
 } FONTSIGNATURE,*LPFONTSIGNATURE;
 
+typedef struct 
+{
+    INT16  txfHeight;
+    INT16  txfWidth;
+    INT16  txfEscapement;
+    INT16  txfOrientation;
+    INT16  txfWeight;
+    CHAR   txfItalic;
+    CHAR   txfUnderline;
+    CHAR   txfStrikeOut;
+    CHAR   txfOutPrecision;
+    CHAR   txfClipPrecision;
+    INT16  txfAccelerator WINE_PACKED;
+    INT16  txfOverhang WINE_PACKED;
+} TEXTXFORM16, *LPTEXTXFORM16;
+
+typedef struct
+{
+    INT16 dfType;
+    INT16 dfPoints;
+    INT16 dfVertRes;
+    INT16 dfHorizRes;
+    INT16 dfAscent;
+    INT16 dfInternalLeading;
+    INT16 dfExternalLeading;
+    CHAR  dfItalic;
+    CHAR  dfUnderline;
+    CHAR  dfStrikeOut;
+    INT16 dfWeight;
+    CHAR  dfCHARSet;
+    INT16 dfPixWidth;
+    INT16 dfPixHeight;
+    CHAR  dfPitchAndFamily;
+    INT16 dfAvgWidth;
+    INT16 dfMaxWidth;
+    CHAR  dfFirstCHAR;
+    CHAR  dfLastCHAR;
+    CHAR  dfDefaultCHAR;
+    CHAR  dfBreakCHAR;
+    INT16 dfWidthBytes;
+    LONG  dfDevice;
+    LONG  dfFace;
+    LONG  dfBitsPointer;
+    LONG  dfBitsOffset;
+    CHAR  dfReserved;
+    LONG  dfFlags;
+    INT16 dfAspace;
+    INT16 dfBspace;
+    INT16 dfCspace;
+    LONG  dfColorPointer;
+    LONG  dfReserved1[4];
+} FONTINFO16, *LPFONTINFO16;
 
   /* lfWeight values */
 #define FW_DONTCARE	    0
@@ -4438,8 +4490,8 @@
 } CSTRING,*LPCSTRING;
 
 typedef struct _UNICODE_STRING {
-	UINT16	Length;		/* bytes ? */
-	UINT16	MaximumLength;	/* bytes ? */
+	UINT16	Length;		/* bytes */
+	UINT16	MaximumLength;	/* bytes */
 	LPWSTR	Buffer;
 } UNICODE_STRING,*LPUNICODE_STRING;
 
@@ -4449,6 +4501,102 @@
 #define	HIGH_PRIORITY_CLASS	0x00000080
 #define	REALTIME_PRIORITY_CLASS	0x00000100
 
+/* GDI Escape commands */
+#define	NEWFRAME		1
+#define	ABORTDOC		2
+#define	NEXTBAND		3
+#define	SETCOLORTABLE		4
+#define	GETCOLORTABLE		5
+#define	FLUSHOUTPUT		6
+#define	DRAFTMODE		7
+#define	QUERYESCSUPPORT		8
+#define	SETABORTPROC		9
+#define	STARTDOC		10
+#define	ENDDOC			11
+#define	GETPHYSPAGESIZE		12
+#define	GETPRINTINGOFFSET	13
+#define	GETSCALINGFACTOR	14
+#define	MFCOMMENT		15
+#define	GETPENWIDTH		16
+#define	SETCOPYCOUNT		17
+#define	SELECTPAPERSOURCE	18
+#define	DEVICEDATA		19
+#define	PASSTHROUGH		19
+#define	GETTECHNOLGY		20
+#define	GETTECHNOLOGY		20 /* yes, both of them */
+#define	SETLINECAP		21
+#define	SETLINEJOIN		22
+#define	SETMITERLIMIT		23
+#define	BANDINFO		24
+#define	DRAWPATTERNRECT		25
+#define	GETVECTORPENSIZE	26
+#define	GETVECTORBRUSHSIZE	27
+#define	ENABLEDUPLEX		28
+#define	GETSETPAPERBINS		29
+#define	GETSETPRINTORIENT	30
+#define	ENUMPAPERBINS		31
+#define	SETDIBSCALING		32
+#define	EPSPRINTING		33
+#define	ENUMPAPERMETRICS	34
+#define	GETSETPAPERMETRICS	35
+#define	POSTSCRIPT_DATA		37
+#define	POSTSCRIPT_IGNORE	38
+#define	MOUSETRAILS		39
+#define	GETDEVICEUNITS		42
+
+#define	GETEXTENDEDTEXTMETRICS	256
+#define	GETEXTENTTABLE		257
+#define	GETPAIRKERNTABLE	258
+#define	GETTRACKKERNTABLE	259
+#define	EXTTEXTOUT		512
+#define	GETFACENAME		513
+#define	DOWNLOADFACE		514
+#define	ENABLERELATIVEWIDTHS	768
+#define	ENABLEPAIRKERNING	769
+#define	SETKERNTRACK		770
+#define	SETALLJUSTVALUES	771
+#define	SETCHARSET		772
+
+#define	STRETCHBLT		2048
+#define	GETSETSCREENPARAMS	3072
+#define	QUERYDIBSUPPORT		3073
+#define	BEGIN_PATH		4096
+#define	CLIP_TO_PATH		4097
+#define	END_PATH		4098
+#define	EXT_DEVICE_CAPS		4099
+#define	RESTORE_CTM		4100
+#define	SAVE_CTM		4101
+#define	SET_ARC_DIRECTION	4102
+#define	SET_BACKGROUND_COLOR	4103
+#define	SET_POLY_MODE		4104
+#define	SET_SCREEN_ANGLE	4105
+#define	SET_SPREAD		4106
+#define	TRANSFORM_CTM		4107
+#define	SET_CLIP_BOX		4108
+#define	SET_BOUNDS		4109
+#define	SET_MIRROR_MODE		4110
+#define	OPENCHANNEL		4110
+#define	DOWNLOADHEADER		4111
+#define CLOSECHANNEL		4112
+#define	POSTSCRIPT_PASSTHROUGH	4115
+#define	ENCAPSULATED_POSTSCRIPT	4116
+
+/* Flag returned from Escape QUERYDIBSUPPORT */
+#define	QDI_SETDIBITS		1
+#define	QDI_GETDIBITS		2
+#define	QDI_DIBTOSCREEN		4
+#define	QDI_STRETCHDIB		8
+
+/* Spooler Error Codes */
+#define	SP_NOTREPORTED	0x4000
+#define	SP_ERROR	(-1)
+#define	SP_APPABORT	(-2)
+#define	SP_USERABORT	(-3)
+#define	SP_OUTOFDISK	(-4)
+#define	SP_OUTOFMEMORY	(-5)
+
+#define PR_JOBSTATUS	0x0000
+
 #pragma pack(4)
 
 /* Declarations for functions that exist only in Win16 */
@@ -4724,8 +4872,6 @@
 
 /* Declarations for functions that are the same in Win16 and Win32 */
 
-BOOL16     CheckDlgButton(HWND32,INT32,UINT32);
-BOOL16     CheckRadioButton(HWND32,UINT32,UINT32,UINT32);
 HBITMAP16  CreateBitmap(INT32,INT32,UINT32,UINT32,LPCVOID);
 BOOL16     CreateCaret(HWND32,HBITMAP32,INT32,INT32);
 HBITMAP16  CreateCompatibleBitmap(HDC32,INT32,INT32);
@@ -4737,7 +4883,6 @@
 LONG       GetBitmapBits(HBITMAP32,LONG,LPVOID);
 WORD       GetClassWord(HWND32,INT32);
 DWORD      GetDialogBaseUnits(void);
-INT16      GetDlgCtrlID(HWND32);
 DWORD      GetLastError(void);
 DWORD      GetMenuCheckMarkDimensions(void);
 COLORREF   GetSysColor(INT32);
@@ -4816,12 +4961,21 @@
 BOOL16     Arc16(HDC16,INT16,INT16,INT16,INT16,INT16,INT16,INT16,INT16);
 BOOL32     Arc32(HDC32,INT32,INT32,INT32,INT32,INT32,INT32,INT32,INT32);
 #define    Arc WINELIB_NAME(Arc)
+UINT16     ArrangeIconicWindows16(HWND16);
+UINT32     ArrangeIconicWindows32(HWND32);
+#define    ArrangeIconicWindows WINELIB_NAME(ArrangeIconicWindows)
+HDWP16     BeginDeferWindowPos16(INT16);
+HDWP32     BeginDeferWindowPos32(INT32);
+#define    BeginDeferWindowPos WINELIB_NAME(BeginDeferWindowPos)
 HDC16      BeginPaint16(HWND16,LPPAINTSTRUCT16);
 HDC32      BeginPaint32(HWND32,LPPAINTSTRUCT32);
 #define    BeginPaint WINELIB_NAME(BeginPaint)
 BOOL16     BitBlt16(HDC16,INT16,INT16,INT16,INT16,HDC16,INT16,INT16,DWORD);
 BOOL32     BitBlt32(HDC32,INT32,INT32,INT32,INT32,HDC32,INT32,INT32,DWORD);
 #define    BitBlt WINELIB_NAME(BitBlt)
+BOOL16     BringWindowToTop16(HWND16);
+BOOL32     BringWindowToTop32(HWND32);
+#define    BringWindowToTop WINELIB_NAME(BringWindowToTop)
 BOOL16     BuildCommDCB16(LPCSTR,LPDCB16);
 BOOL32     BuildCommDCB32A(LPCSTR,LPDCB32);
 BOOL32     BuildCommDCB32W(LPCWSTR,LPDCB32);
@@ -4873,9 +5027,15 @@
 BOOL32     CharToOemBuff32A(LPCSTR,LPSTR,DWORD);
 BOOL32     CharToOemBuff32W(LPCWSTR,LPSTR,DWORD);
 #define    CharToOemBuff WINELIB_NAME_AW(CharToOemBuff)
+BOOL16     CheckDlgButton16(HWND16,INT16,UINT16);
+BOOL32     CheckDlgButton32(HWND32,INT32,UINT32);
+#define    CheckDlgButton WINELIB_NAME(CheckDlgButton)
 BOOL16     CheckMenuItem16(HMENU16,UINT16,UINT16);
 DWORD      CheckMenuItem32(HMENU32,UINT32,UINT32);
 #define    CheckMenuItem WINELIB_NAME(CheckMenuItem)
+BOOL16     CheckRadioButton16(HWND16,UINT16,UINT16,UINT16);
+BOOL32     CheckRadioButton32(HWND32,UINT32,UINT32,UINT32);
+#define    CheckRadioButton WINELIB_NAME(CheckRadioButton)
 HWND16     ChildWindowFromPoint16(HWND16,POINT16);
 HWND32     ChildWindowFromPoint32(HWND32,POINT32);
 #define    ChildWindowFromPoint WINELIB_NAME(ChildWindowFromPoint)
@@ -5037,6 +5197,9 @@
 LRESULT    DefDlgProc32A(HWND32,UINT32,WPARAM32,LPARAM);
 LRESULT    DefDlgProc32W(HWND32,UINT32,WPARAM32,LPARAM);
 #define    DefDlgProc WINELIB_NAME_AW(DefDlgProc)
+HDWP16     DeferWindowPos16(HDWP16,HWND16,HWND16,INT16,INT16,INT16,INT16,UINT16);
+HDWP32     DeferWindowPos32(HDWP32,HWND32,HWND32,INT32,INT32,INT32,INT32,UINT32);
+#define    DeferWindowPos WINELIB_NAME(DeferWindowPos)
 LRESULT    DefFrameProc16(HWND16,HWND16,UINT16,WPARAM16,LPARAM);
 LRESULT    DefFrameProc32A(HWND32,HWND32,UINT32,WPARAM32,LPARAM);
 LRESULT    DefFrameProc32W(HWND32,HWND32,UINT32,WPARAM32,LPARAM);
@@ -5072,6 +5235,9 @@
 BOOL16     DestroyMenu16(HMENU16);
 BOOL32     DestroyMenu32(HMENU32);
 #define    DestroyMenu WINELIB_NAME(DestroyMenu)
+BOOL16     DestroyWindow16(HWND16);
+BOOL32     DestroyWindow32(HWND32);
+#define    DestroyWindow WINELIB_NAME(DestroyWindow)
 INT16      DialogBox16(HINSTANCE16,SEGPTR,HWND16,DLGPROC16);
 #define    DialogBox32A(inst,template,owner,func) \
            DialogBoxParam32A(inst,template,owner,func,0)
@@ -5136,6 +5302,12 @@
 BOOL16     EnableScrollBar16(HWND16,INT16,UINT16);
 BOOL32     EnableScrollBar32(HWND32,INT32,UINT32);
 #define    EnableScrollBar WINELIB_NAME(EnableScrollBar)
+BOOL16     EnableWindow16(HWND16,BOOL16);
+BOOL32     EnableWindow32(HWND32,BOOL32);
+#define    EnableWindow WINELIB_NAME(EnableWindow)
+BOOL16     EndDeferWindowPos16(HDWP16);
+BOOL32     EndDeferWindowPos32(HDWP32);
+#define    EndDeferWindowPos WINELIB_NAME(EndDeferWindowPos)
 BOOL16     EndPaint16(HWND16,const PAINTSTRUCT16*);
 BOOL32     EndPaint32(HWND32,const PAINTSTRUCT32*);
 #define    EndPaint WINELIB_NAME(EndPaint)
@@ -5174,6 +5346,9 @@
 BOOL16     EqualRgn16(HRGN16,HRGN16);
 BOOL32     EqualRgn32(HRGN32,HRGN32);
 #define    EqualRgn WINELIB_NAME(EqualRgn)
+INT16      Escape16(HDC16,INT16,INT16,SEGPTR,SEGPTR);
+INT32      Escape32(HDC32,INT32,INT32,LPVOID,LPVOID);
+#define    Escape WINELIB_NAME(Escape)
 LONG       EscapeCommFunction16(UINT16,UINT16);
 BOOL32     EscapeCommFunction32(INT32,UINT32);
 #define    EscapeCommFunction WINELIB_NAME(EscapeCommFunction)
@@ -5241,6 +5416,9 @@
 BOOL16     FreeResource16(HGLOBAL16);
 BOOL32     FreeResource32(HGLOBAL32);
 #define    FreeResource WINELIB_NAME(FreeResource)
+HWND16     GetActiveWindow16(void);
+HWND32     GetActiveWindow32(void);
+#define    GetActiveWindow WINELIB_NAME(GetActiveWindow)
 BOOL16     GetBitmapDimensionEx16(HBITMAP16,LPSIZE16);
 BOOL32     GetBitmapDimensionEx32(HBITMAP32,LPSIZE32);
 #define    GetBitmapDimensionEx WINELIB_NAME(GetBitmapDimensionEx)
@@ -5327,6 +5505,15 @@
 BOOL32     GetDiskFreeSpace32A(LPCSTR,LPDWORD,LPDWORD,LPDWORD,LPDWORD);
 BOOL32     GetDiskFreeSpace32W(LPCWSTR,LPDWORD,LPDWORD,LPDWORD,LPDWORD);
 #define    GetDiskFreeSpace WINELIB_NAME_AW(GetDiskFreeSpace)
+INT16      GetDlgCtrlID16(HWND16);
+INT32      GetDlgCtrlID32(HWND32);
+#define    GetDlgCtrlID WINELIB_NAME(GetDlgCtrlID)
+HWND16     GetDlgItem16(HWND16,INT16);
+HWND32     GetDlgItem32(HWND32,INT32);
+#define    GetDlgItem WINELIB_NAME(GetDlgItem)
+UINT16     GetDlgItemInt16(HWND16,INT16,BOOL16*,BOOL16);
+UINT32     GetDlgItemInt32(HWND32,INT32,BOOL32*,BOOL32);
+#define    GetDlgItemInt WINELIB_NAME(GetDlgItemInt)
 INT16      GetDlgItemText16(HWND16,INT16,SEGPTR,UINT16);
 INT32      GetDlgItemText32A(HWND32,INT32,LPSTR,UINT32);
 INT32      GetDlgItemText32W(HWND32,INT32,LPWSTR,UINT32);
@@ -5393,6 +5580,9 @@
 HWND16     GetNextDlgTabItem16(HWND16,HWND16,BOOL16);
 HWND32     GetNextDlgTabItem32(HWND32,HWND32,BOOL32);
 #define    GetNextDlgTabItem WINELIB_NAME(GetNextDlgTabItem)
+HWND16     GetNextWindow16(HWND16,WORD);
+#define    GetNextWindow32 GetWindow32
+#define    GetNextWindow WINELIB_NAME(GetNextWindow)
 INT16      GetObject16(HANDLE16,INT16,LPVOID);
 INT32      GetObject32A(HANDLE32,INT32,LPVOID);
 INT32      GetObject32W(HANDLE32,INT32,LPVOID);
@@ -5497,6 +5687,9 @@
 BOOL32     GetTextMetrics32A(HDC32,LPTEXTMETRIC32A);
 BOOL32     GetTextMetrics32W(HDC32,LPTEXTMETRIC32W);
 #define    GetTextMetrics WINELIB_NAME_AW(GetTextMetrics)
+HWND16     GetTopWindow16(HWND16);
+HWND32     GetTopWindow32(HWND32);
+#define    GetTopWindow WINELIB_NAME(GetTopWindow)
 BOOL16     GetUpdateRect16(HWND16,LPRECT16,BOOL16);
 BOOL32     GetUpdateRect32(HWND32,LPRECT32,BOOL32);
 #define    GetUpdateRect WINELIB_NAME(GetUpdateRect)
@@ -5512,6 +5705,9 @@
 BOOL32     GetVolumeInformation32A(LPCSTR,LPSTR,DWORD,LPDWORD,LPDWORD,LPDWORD,LPSTR,DWORD);
 BOOL32     GetVolumeInformation32W(LPCWSTR,LPWSTR,DWORD,LPDWORD,LPDWORD,LPDWORD,LPWSTR,DWORD);
 #define    GetVolumeInformation WINELIB_NAME_AW(GetVolumeInformation)
+HWND16     GetWindow16(HWND16,WORD);
+HWND32     GetWindow32(HWND32,WORD);
+#define    GetWindow WINELIB_NAME(GetWindow)
 HDC16      GetWindowDC16(HWND16);
 HDC32      GetWindowDC32(HWND32);
 #define    GetWindowDC WINELIB_NAME(GetWindowDC)
@@ -5648,15 +5844,33 @@
 BOOL32     IsCharUpper32A(CHAR);
 BOOL32     IsCharUpper32W(WCHAR);
 #define    IsCharUpper WINELIB_NAME_AW(IsCharUpper)
+BOOL16     IsChild16(HWND16,HWND16);
+BOOL32     IsChild32(HWND32,HWND32);
+#define    IsChild WINELIB_NAME(IsChild)
 BOOL16     IsDBCSLeadByte16(BYTE);
 BOOL32     IsDBCSLeadByte32(BYTE);
 #define    IsDBCSLeadByte WINELIB_NAME(IsDBCSLeadByte)
+UINT16     IsDlgButtonChecked16(HWND16,UINT16);
+UINT32     IsDlgButtonChecked32(HWND32,UINT32);
+#define    IsDlgButtonChecked WINELIB_NAME(IsDlgButtonChecked)
+BOOL16     IsIconic16(HWND16);
+BOOL32     IsIconic32(HWND32);
+#define    IsIconic WINELIB_NAME(IsIconic)
 BOOL16     IsMenu16(HMENU16);
 BOOL32     IsMenu32(HMENU32);
 #define    IsMenu WINELIB_NAME(IsMenu)
 BOOL16     IsRectEmpty16(const RECT16*);
 BOOL32     IsRectEmpty32(const RECT32*);
 #define    IsRectEmpty WINELIB_NAME(IsRectEmpty)
+BOOL16     IsWindowEnabled16(HWND16);
+BOOL32     IsWindowEnabled32(HWND32);
+#define    IsWindowEnabled WINELIB_NAME(IsWindowEnabled)
+BOOL16     IsWindowVisible16(HWND16);
+BOOL32     IsWindowVisible32(HWND32);
+#define    IsWindowVisible WINELIB_NAME(IsWindowVisible)
+BOOL16     IsZoomed16(HWND16);
+BOOL32     IsZoomed32(HWND32);
+#define    IsZoomed WINELIB_NAME(IsZoomed)
 BOOL16     KillSystemTimer16(HWND16,UINT16);
 BOOL32     KillSystemTimer32(HWND32,UINT32);
 #define    KillSystemTimer WINELIB_NAME(KillSystemTimer)
@@ -5785,6 +5999,9 @@
 BOOL16     MoveToEx16(HDC16,INT16,INT16,LPPOINT16);
 BOOL32     MoveToEx32(HDC32,INT32,INT32,LPPOINT32);
 #define    MoveToEx WINELIB_NAME(MoveToEx)
+BOOL16     MoveWindow16(HWND16,INT16,INT16,INT16,INT16,BOOL16);
+BOOL32     MoveWindow32(HWND32,INT32,INT32,INT32,INT32,BOOL32);
+#define    MoveWindow WINELIB_NAME(MoveWindow)
 INT16      MulDiv16(INT16,INT16,INT16);
 INT32      MulDiv32(INT32,INT32,INT32);
 #define    MulDiv WINELIB_NAME(MulDiv)
@@ -5988,6 +6205,9 @@
 LRESULT    SendMessage32A(HWND32,UINT32,WPARAM32,LPARAM);
 LRESULT    SendMessage32W(HWND32,UINT32,WPARAM32,LPARAM);
 #define    SendMessage WINELIB_NAME_AW(SendMessage)
+HWND16     SetActiveWindow16(HWND16);
+HWND32     SetActiveWindow32(HWND32);
+#define    SetActiveWindow WINELIB_NAME(SetActiveWindow)
 BOOL16     SetBitmapDimensionEx16(HBITMAP16,INT16,INT16,LPSIZE16);
 BOOL32     SetBitmapDimensionEx32(HBITMAP32,INT32,INT32,LPSIZE32);
 #define    SetBitmapDimensionEx WINELIB_NAME(SetBitmapDimensionEx)
@@ -6129,6 +6349,9 @@
 HHOOK      SetWindowsHookEx32A(INT32,HOOKPROC32,HINSTANCE32,DWORD);
 HHOOK      SetWindowsHookEx32W(INT32,HOOKPROC32,HINSTANCE32,DWORD);
 #define    SetWindowsHookEx WINELIB_NAME_AW(SetWindowsHookEx)
+BOOL16     SetWindowPos16(HWND16,HWND16,INT16,INT16,INT16,INT16,WORD);
+BOOL32     SetWindowPos32(HWND32,HWND32,INT32,INT32,INT32,INT32,WORD);
+#define    SetWindowPos WINELIB_NAME(SetWindowPos)
 void       SetWindowText16(HWND16,SEGPTR);
 void       SetWindowText32A(HWND32,LPCSTR);
 void       SetWindowText32W(HWND32,LPCWSTR);
@@ -6140,6 +6363,9 @@
 void       ShowScrollBar16(HWND16,INT16,BOOL16);
 BOOL32     ShowScrollBar32(HWND32,INT32,BOOL32);
 #define    ShowScrollBar WINELIB_NAME(ShowScrollBar)
+BOOL16     ShowWindow16(HWND16,INT16);
+BOOL32     ShowWindow32(HWND32,INT32);
+#define    ShowWindow WINELIB_NAME(ShowWindow)
 BOOL16     StretchBlt16(HDC16,INT16,INT16,INT16,INT16,HDC16,INT16,INT16,
                         INT16,INT16,DWORD);
 BOOL32     StretchBlt32(HDC32,INT32,INT32,INT32,INT32,HDC32,INT32,INT32,
@@ -6196,9 +6422,9 @@
 DWORD      VerFindFile32A(UINT32,LPCSTR,LPCSTR,LPCSTR,LPSTR,UINT32*,LPSTR,UINT32*);
 DWORD      VerFindFile32W(UINT32,LPCWSTR,LPCWSTR,LPCWSTR,LPWSTR,UINT32*,LPWSTR,UINT32*);
 #define    VerFindFile WINELIB_NAME_AW(VerFindFile)
-DWORD      VerInstallFile16(UINT16,LPCSTR,LPCSTR,LPCSTR,LPCSTR,LPSTR,UINT16*);
-DWORD      VerInstallFile32A(UINT32,LPCSTR,LPCSTR,LPCSTR,LPCSTR,LPSTR,UINT32*);
-DWORD      VerInstallFile32W(UINT32,LPCWSTR,LPCWSTR,LPCWSTR,LPCWSTR,LPWSTR,UINT32*);
+DWORD      VerInstallFile16(UINT16,LPCSTR,LPCSTR,LPCSTR,LPCSTR,LPCSTR,LPSTR,UINT16*);
+DWORD      VerInstallFile32A(UINT32,LPCSTR,LPCSTR,LPCSTR,LPCSTR,LPCSTR,LPSTR,UINT32*);
+DWORD      VerInstallFile32W(UINT32,LPCWSTR,LPCWSTR,LPCWSTR,LPCWSTR,LPCWSTR,LPWSTR,UINT32*);
 #define    VerInstallFile WINELIB_NAME_AW(VerInstallFile)
 DWORD      VerLanguageName16(UINT16,LPSTR,UINT16);
 DWORD      VerLanguageName32A(UINT32,LPSTR,UINT32);
@@ -6345,9 +6571,6 @@
 INT        AddFontResource(LPCSTR);
 BOOL       AnimatePalette(HPALETTE16,UINT,UINT,LPPALETTEENTRY);
 BOOL       AnyPopup(void);
-UINT       ArrangeIconicWindows(HWND);
-HDWP16     BeginDeferWindowPos(INT);
-BOOL       BringWindowToTop(HWND);
 void       CalcChildScroll(HWND,WORD);
 BOOL       CallMsgFilter(SEGPTR,INT);
 BOOL       CloseClipboard(void);
@@ -6361,22 +6584,17 @@
 HGLOBAL16  CreateCursorIconIndirect(HINSTANCE16,CURSORICONINFO*,const BYTE*,const BYTE*);
 HICON16    CreateIcon(HINSTANCE16,INT,INT,BYTE,BYTE,const BYTE*,const BYTE*);
 HPALETTE16 CreatePalette(const LOGPALETTE*);
-HDWP16     DeferWindowPos(HDWP16,HWND,HWND,INT,INT,INT,INT,UINT);
 ATOM       DeleteAtom(ATOM);
 BOOL       DestroyCursor(HCURSOR16);
 BOOL       DestroyIcon(HICON16);
-BOOL       DestroyWindow(HWND);
 LONG       DispatchMessage(const MSG16*);
 BOOL16     DragDetect(HWND16,POINT16);
 DWORD      DragObject(HWND, HWND, WORD, HANDLE16, WORD, HCURSOR16);
 BOOL       DrawIcon(HDC16,INT,INT,HICON16);
 DWORD      DumpIcon(SEGPTR,WORD*,SEGPTR*,SEGPTR*);
 BOOL       EmptyClipboard(void);
-BOOL       EnableWindow(HWND,BOOL);
-BOOL       EndDeferWindowPos(HDWP16);
 UINT16     EnumClipboardFormats(UINT16);
 BOOL       EnumMetaFile(HDC16,HMETAFILE16,MFENUMPROC16,LPARAM);
-INT        Escape(HDC16,INT,INT,SEGPTR,SEGPTR);
 HICON16    ExtractIcon(HINSTANCE16,LPCSTR,WORD);
 void       FatalExit(int);
 ATOM       FindAtom(SEGPTR);
@@ -6385,7 +6603,6 @@
 void       FreeLibrary(HINSTANCE16);
 UINT       GDIRealizePalette(HDC16);
 HPALETTE16 GDISelectPalette(HDC16,HPALETTE16,WORD);
-HWND       GetActiveWindow(void);
 DWORD      GetAspectRatioFilter(HDC16);
 int        GetAsyncKeyState(int);
 WORD       GetAtomName(ATOM,LPSTR,short);
@@ -6398,8 +6615,6 @@
 HCURSOR16  GetCursor(void);
 SEGPTR     GetDOSEnvironment(void);
 int        GetDeviceCaps(HDC16,WORD);
-HWND       GetDlgItem(HWND,WORD);
-WORD       GetDlgItemInt(HWND,WORD,BOOL*,BOOL);
 WORD       GetDoubleClickTime(void);
 int        GetEnvironment(LPSTR,LPSTR,WORD);
 DWORD      GetFreeSpace(UINT16);
@@ -6421,7 +6636,6 @@
 INT16      GetModuleUsage(HINSTANCE16);
 DWORD      GetNearestColor(HDC16,DWORD);
 WORD       GetNearestPaletteIndex(HPALETTE16,DWORD);
-HWND       GetNextWindow(HWND,WORD);
 HWND       GetOpenClipboardWindow(void);
 WORD       GetPaletteEntries(HPALETTE16,WORD,WORD,LPPALETTEENTRY);
 int        GetPriorityClipboardFormat(WORD*,short);
@@ -6434,10 +6648,8 @@
 BYTE       GetTempDrive(BYTE);
 LPINT16    GetThresholdEvent(void);
 int        GetThresholdStatus(void);
-HWND       GetTopWindow(HWND);
 BOOL       GetWinDebugInfo(LPWINDEBUGINFO,UINT);
 LONG       GetWinFlags(void);
-HWND       GetWindow(HWND,WORD);
 ATOM       GlobalDeleteAtom(ATOM);
 void       GlobalFix(HGLOBAL16);
 BOOL16     GlobalUnWire(HGLOBAL16);
@@ -6446,20 +6658,13 @@
 BOOL       GrayString(HDC16,HBRUSH16,GRAYSTRINGPROC16,LPARAM,INT,INT,INT,INT,INT);
 BOOL       InSendMessage(void);
 WORD       InitAtomTable(WORD);
-BOOL       IsChild(HWND,HWND);
 BOOL       IsClipboardFormatAvailable(WORD);
-BOOL       IsDialogMessage(HWND,LPMSG16);
-WORD       IsDlgButtonChecked(HWND,WORD);
-BOOL       IsIconic(HWND);
+BOOL16     IsDialogMessage(HWND16,LPMSG16);
 BOOL       IsValidMetaFile(HMETAFILE16);
-BOOL       IsWindowEnabled(HWND);
-BOOL       IsWindowVisible(HWND);
-BOOL       IsZoomed(HWND);
 HINSTANCE16 LoadModule(LPCSTR,LPVOID);
 FARPROC16  LocalNotify(FARPROC16);
 WORD       MapVirtualKey(WORD,WORD);
 void       MessageBeep(WORD);
-BOOL       MoveWindow(HWND,short,short,short,short,BOOL);
 DWORD      OemKeyScan(WORD);
 BOOL       OpenClipboard(HWND);
 BOOL       OpenIcon(HWND);
@@ -6483,7 +6688,6 @@
 BOOL       ResizePalette(HPALETTE16,UINT);
 void       ScrollChildren(HWND,UINT,WPARAM16,LPARAM);
 HPALETTE16 SelectPalette(HDC16,HPALETTE16,BOOL);
-HWND       SetActiveWindow(HWND);
 HANDLE16   SetClipboardData(WORD,HANDLE16);
 HWND       SetClipboardViewer(HWND);
 void       SetConvertHook(BOOL);
@@ -6512,11 +6716,9 @@
 int        SetVoiceSound(int,LONG,int);
 int        SetVoiceThreshold(int,int);
 BOOL       SetWinDebugInfo(LPWINDEBUGINFO);
-BOOL       SetWindowPos(HWND,HWND,INT,INT,INT,INT,WORD);
 HINSTANCE16 ShellExecute(HWND,LPCSTR,LPCSTR,LPSTR,LPCSTR,INT);
 int        ShowCursor(BOOL);
 void       ShowOwnedPopups(HWND,BOOL);
-BOOL       ShowWindow(HWND,int);
 DWORD      SizeofResource(HMODULE16,HRSRC16);
 int        StartSound(void);
 int        StopSound(void);
diff --git a/include/winerror.h b/include/winerror.h
index 6488e5e..28cc005 100644
--- a/include/winerror.h
+++ b/include/winerror.h
@@ -20,6 +20,7 @@
 #define ERROR_BAD_FORMAT            11
 #define ERROR_OUTOFMEMORY           14
 #define ERROR_NO_MORE_FILES         18
+#define ERROR_SHARING_VIOLATION     32
 #define ERROR_FILE_EXISTS           80
 #define ERROR_INVALID_PARAMETER     87
 #define ERROR_BROKEN_PIPE           109
diff --git a/include/winpos.h b/include/winpos.h
index d8df072..be21ee2 100644
--- a/include/winpos.h
+++ b/include/winpos.h
@@ -9,7 +9,7 @@
 
 #include "win.h"
 
-#define DWP_MAGIC  0x5057  /* 'WP' */
+#define DWP_MAGIC  ((INT32)('W' | ('P' << 8) | ('O' << 16) | ('S' << 24)))
 
 /* undocumented SWP flags - from SDK 3.1 */
 #define SWP_NOCLIENTSIZE	0x0800
@@ -17,12 +17,12 @@
 
 typedef struct
 {
-    WORD        actualCount;
-    WORD        suggestedCount;
-    WORD        valid;
-    WORD        wMagic;
+    INT32       actualCount;
+    INT32       suggestedCount;
+    BOOL32      valid;
+    INT32       wMagic;
     HWND32      hwndParent;
-    WINDOWPOS16 winPos[1];
+    WINDOWPOS32 winPos[1];
 } DWP;
 
 extern void WINPOS_FindIconPos( HWND32 hwnd );
diff --git a/include/x11drv.h b/include/x11drv.h
index 9372224..127441d 100644
--- a/include/x11drv.h
+++ b/include/x11drv.h
@@ -55,6 +55,7 @@
                              INT32 xSrc, INT32 ySrc, DWORD rop );
 extern BOOL32 X11DRV_GetTextExtentPoint( struct tagDC *dc, LPCSTR str,
                                          INT32 count, LPSIZE32 size );
+extern BOOL32 X11DRV_GetTextMetrics(struct tagDC *dc, TEXTMETRIC32A *metrics);
 extern BOOL32 X11DRV_PatBlt( struct tagDC *dc, INT32 left, INT32 top,
                              INT32 width, INT32 height, DWORD rop );
 extern VOID X11DRV_SetDeviceClipping(struct tagDC *dc);
diff --git a/loader/main.c b/loader/main.c
index 9b13e8f..f78ee78 100644
--- a/loader/main.c
+++ b/loader/main.c
@@ -25,6 +25,7 @@
 #include "file.h"
 #include "gdi.h"
 #include "heap.h"
+#include "keyboard.h"
 #include "miscemu.h"
 #include "neexe.h"
 #include "options.h"
@@ -32,7 +33,6 @@
 #include "task.h"
 #include "user.h"
 #include "dce.h"
-#include "pe_image.h"
 #include "shell.h"
 #include "winproc.h"
 #include "stddebug.h"
@@ -123,6 +123,9 @@
       /* Create the DCEs */
     DCE_Init();
 
+    /* Initialize keyboard */
+    if (!KEYBOARD_Init()) return 0;
+
     /* Initialize window procedures */
     if (!WINPROC_Init()) return 0;
 
@@ -164,7 +167,7 @@
     extern BOOL32 MAIN_WineInit( int *argc, char *argv[] );
     extern char * DEBUG_argv0;
 
-    int i;
+    int i,loaded;
     HINSTANCE16 handle;
 
     /*
@@ -176,6 +179,7 @@
     if (!MAIN_WineInit( &argc, argv )) return 1;
     if (!MAIN_Init()) return 1;
 
+    loaded=0;
     for (i = 1; i < argc; i++)
     {
         if ((handle = WinExec32( argv[i], SW_SHOWNORMAL )) < 32)
@@ -190,6 +194,13 @@
             }
             return 1;
         }
+	loaded++;
+    }
+
+    if (!loaded) { /* nothing loaded */
+    	extern void MAIN_Usage(char*);
+    	MAIN_Usage(argv[0]);
+	return 1;
     }
 
     if (Options.debug) DEBUG_SetBreakpoints( TRUE );  /* Setup breakpoints */
diff --git a/loader/module.c b/loader/module.c
index e0b9f9d..4f4c1e4 100644
--- a/loader/module.c
+++ b/loader/module.c
@@ -1008,9 +1008,11 @@
 
 
 /**********************************************************************
- *	    LoadModule    (KERNEL.45)
+ *	    MODULE_Load
+ *
+ * Implementation of LoadModule()
  */
-HINSTANCE16 LoadModule( LPCSTR name, LPVOID paramBlock )
+HINSTANCE16 MODULE_Load( LPCSTR name, LPVOID paramBlock, BOOL32 first )
 {
     HMODULE16 hModule;
     HINSTANCE16 hInstance, hPrevInstance;
@@ -1021,7 +1023,7 @@
     WORD *pModRef, *pDLLs;
     HFILE32 hFile;
     int i;
-    extern char * DEBUG_curr_module;
+    extern const char * DEBUG_curr_module;
 
     hModule = MODULE_FindModule( name );
 
@@ -1089,8 +1091,9 @@
                 /* its handle in the list of DLLs to initialize.   */
                 HMODULE16 hDLL;
 
-                if ((hDLL = LoadModule( buffer, (LPVOID)-1 )) == 2)  /* file not found */
+                if ((hDLL = MODULE_Load( buffer, (LPVOID)-1, FALSE )) == 2)
                 {
+                    /* file not found */
                     char *p;
 
                     /* Try with prepending the path of the current module */
@@ -1098,7 +1101,7 @@
                     if (!(p = strrchr( buffer, '\\' ))) p = buffer;
                     memcpy( p + 1, pstr + 1, *pstr );
                     strcpy( p + 1 + *pstr, ".dll" );
-                    hDLL = LoadModule( buffer, (LPVOID)-1 );
+                    hDLL = MODULE_Load( buffer, (LPVOID)-1, FALSE );
                 }
                 if (hDLL < 32)
                 {
@@ -1212,6 +1215,9 @@
           /* the module, even if it contains circular DLL references */
 
         pModule->count = 1;
+
+        if (first && (pModule->flags & NE_FFLAGS_LIBMODULE))
+            NE_InitializeDLLs( hModule );
     }
     else
     {
@@ -1256,6 +1262,15 @@
 
 
 /**********************************************************************
+ *	    LoadModule    (KERNEL.45)
+ */
+HINSTANCE16 LoadModule( LPCSTR name, LPVOID paramBlock )
+{
+    return MODULE_Load( name, paramBlock, TRUE );
+}
+
+
+/**********************************************************************
  *	    FreeModule16    (KERNEL.46)
  */
 BOOL16 FreeModule16( HMODULE16 hModule )
@@ -1382,17 +1397,14 @@
      * therefore cause crashes on FreeLibrary calls.
     if ((handle = MODULE_FindModule( libname )) != 0) return handle;
      */
-    handle = LoadModule( libname, (LPVOID)-1 );
+    handle = MODULE_Load( libname, (LPVOID)-1, TRUE );
     if (handle == (HINSTANCE16)2)  /* file not found */
     {
         char buffer[256];
         lstrcpyn32A( buffer, libname, 252 );
         strcat( buffer, ".dll" );
-        handle = LoadModule( buffer, (LPVOID)-1 );
+        handle = MODULE_Load( buffer, (LPVOID)-1, TRUE );
     }
-#ifndef WINELIB
-    if (handle >= (HINSTANCE16)32) NE_InitializeDLLs( GetExePtr(handle) );
-#endif
     return handle;
 }
 
diff --git a/loader/pe_image.c b/loader/pe_image.c
index 73c9ce9..9d4816c 100644
--- a/loader/pe_image.c
+++ b/loader/pe_image.c
@@ -17,7 +17,9 @@
 #include <string.h>
 #include <unistd.h>
 #include <sys/types.h>
+#ifndef __EMX__
 #include <sys/mman.h>
+#endif
 #include "windows.h"
 #include "winbase.h"
 #include "callback.h"
@@ -33,50 +35,10 @@
 #include "debugger.h"
 #include "xmalloc.h"
 
-void my_wcstombs(char * result, u_short * source, int len)
-{
-  while(len--) {
-    /* this used to be isascii, but see isascii implementation in Linux'
-	   ctype.h */
-    if(*source<255) *result++ = *source++;
-    else {
-      printf("Unable to handle unicode right now\n");
-      exit(0);
-    }
-  };
-}
+/* convert PE image VirtualAddress to Real Address */
+#define RVA(x) ((unsigned int)load_addr+(unsigned int)(x))
 
-#if 0
-char * xmmap(char * vaddr, unsigned int v_size, unsigned int r_size,
-	int prot, int flags, int fd, unsigned int file_offset)
-{
-  char * result;
-  /* .bss has no associated storage in the PE file */
-  if(r_size)
-    v_size=r_size;
-  else
-#if defined(__svr4__) || defined(_SCO_DS)
-    fprintf(stderr,"xmmap: %s line %d doesn't support MAP_ANON\n",__FILE__, __LINE__);
-#else
-    flags |= MAP_ANON;
-#endif
-  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 = (char *)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;
-};
-#endif
-
-void dump_exports(struct PE_Export_Directory * pe_exports, unsigned int load_addr)
+void dump_exports(IMAGE_EXPORT_DIRECTORY * pe_exports, unsigned int load_addr)
 { 
   char		*Module;
   int		i;
@@ -88,30 +50,30 @@
 
   daddr.seg = 0;
   daddr.type = NULL;
-  Module = ((char*)load_addr)+pe_exports->Name;
+  Module = (char*)RVA(pe_exports->Name);
   dprintf_win32(stddeb,"\n*******EXPORT DATA*******\nModule name is %s, %ld functions, %ld names\n", 
 	 Module,
-	 pe_exports->Number_Of_Functions,
-	 pe_exports->Number_Of_Names);
+	 pe_exports->NumberOfFunctions,
+	 pe_exports->NumberOfNames);
 
-  ordinal=(u_short*)(((char*)load_addr)+(int)pe_exports->Address_Of_Name_Ordinals);
-  functions=function=(u_long*)(((char*)load_addr)+(int)pe_exports->AddressOfFunctions);
-  name=(u_char**)(((char*)load_addr)+(int)pe_exports->AddressOfNames);
+  ordinal=(u_short*) RVA(pe_exports->AddressOfNameOrdinals);
+  functions=function=(u_long*) RVA(pe_exports->AddressOfFunctions);
+  name=(u_char**) RVA(pe_exports->AddressOfNames);
 
   dprintf_win32(stddeb,"%-32s Ordinal Virt Addr\n", "Function Name");
-  for (i=0;i<pe_exports->Number_Of_Functions;i++) {
-      if (i<pe_exports->Number_Of_Names) {
-	  ename=(char*)(((char*)load_addr)+(int)*name++);
+  for (i=0;i<pe_exports->NumberOfFunctions;i++) {
+      if (i<pe_exports->NumberOfNames) {
+	  ename=(char*)RVA(*name++);
 	  dprintf_win32(stddeb,"%-32s %4d    %8.8lx (%8.8lx)\n",ename,*ordinal,functions[*ordinal],*function);
 	  sprintf(buffer,"%s.%s",Module,ename);
-	  daddr.off=load_addr+functions[*ordinal];
+	  daddr.off=RVA(functions[*ordinal]);
 	  ordinal++;
 	  function++;
       } else {
       	  /* ordinals/names no longer valid, but we still got functions */
 	  dprintf_win32(stddeb,"%-32s %4s    %8s %8.8lx\n","","","",*function);
 	  sprintf(buffer,"%s.%d",Module,i);
-	  daddr.off=load_addr+*functions;
+	  daddr.off=RVA(*functions);
 	  function++;
       }
       DEBUG_AddSymbol(buffer,&daddr, NULL, SYM_WIN32 | SYM_FUNC);
@@ -128,7 +90,7 @@
  */
 FARPROC32 PE_FindExportedFunction(struct pe_data *pe, LPCSTR funcName)
 {
-	struct PE_Export_Directory * exports = pe->pe_export;
+	IMAGE_EXPORT_DIRECTORY * exports = pe->pe_export;
 	unsigned load_addr = pe->load_addr;
 	u_short * ordinal;
 	u_long * function;
@@ -141,24 +103,24 @@
 		dprintf_win32(stddeb,"PE_FindExportedFunction(%d)\n",(int)funcName);
 	if (!exports)
 		return NULL;
-	ordinal=(u_short*)(((char*)load_addr)+(int)exports->Address_Of_Name_Ordinals);
-	function=(u_long*)(((char*)load_addr)+(int)exports->AddressOfFunctions);
-	name=(u_char **)(((char*)load_addr)+(int)exports->AddressOfNames);
+	ordinal=(u_short*) RVA(exports->AddressOfNameOrdinals);
+	function=(u_long*) RVA(exports->AddressOfFunctions);
+	name=(u_char **) RVA(exports->AddressOfNames);
 	if (HIWORD(funcName)) {
-		for(i=0; i<exports->Number_Of_Names; i++) {
-			ename=(char*)(((char*)load_addr)+(int)*name);
+		for(i=0; i<exports->NumberOfNames; i++) {
+			ename=(char*) RVA(*name);
 			if(!strcmp(ename,funcName))
-				return (FARPROC32)(load_addr+function[*ordinal]);
+				return (FARPROC32) RVA(function[*ordinal]);
 			ordinal++;
 			name++;
 		}
 	} else {
-		if (LOWORD(funcName)-exports->Base > exports->Number_Of_Functions) {
+		if (LOWORD(funcName)-exports->Base > exports->NumberOfFunctions) {
 			dprintf_win32(stddeb,"	ordinal %d out of range!\n",
                                       LOWORD(funcName));
 			return NULL;
 		}
-		return (FARPROC32)(load_addr+function[(int)funcName-exports->Base]);
+		return (FARPROC32) RVA(function[(int)funcName-exports->Base]);
 	}
 	return NULL;
 }
@@ -166,19 +128,27 @@
 void 
 fixup_imports (struct pe_data *pe, HMODULE16 hModule)
 {
-    struct PE_Import_Directory *pe_imp;
+    IMAGE_IMPORT_DESCRIPTOR *pe_imp;
     int	fixup_failed = 0;
     unsigned int load_addr = pe->load_addr;
     int i;
     NE_MODULE *ne_mod;
     HMODULE16 *mod_ptr;
+    char *modname;
+    
+    if (pe->pe_export)
+    	modname = (char*) RVA(pe->pe_export->Name);
+    else
+        modname = "<unknown>";
 
     /* OK, now dump the import list */
     dprintf_win32 (stddeb, "\nDumping imports list\n");
 
     /* first, count the number of imported non-internal modules */
     pe_imp = pe->pe_import;
-    for (i = 0; pe_imp->ModuleName; pe_imp++)
+
+    /* FIXME: should terminate on 0 Characteristics */
+    for (i = 0; pe_imp->Name; pe_imp++)
 	i++;
 
     /* Now, allocate memory for dlls_to_init */
@@ -187,9 +157,11 @@
                                         hModule, FALSE, FALSE, FALSE);
     mod_ptr = GlobalLock16 (ne_mod->dlls_to_init);
     /* load the modules and put their handles into the list */
-    for (i = 0, pe_imp = pe->pe_import; pe_imp->ModuleName; pe_imp++) {
-	char *name = (char *) load_addr + pe_imp->ModuleName;
-	mod_ptr[i] = LoadModule (name, (LPVOID) - 1);
+ 
+     /* FIXME: should terminate on 0 Characteristics */
+     for (i = 0, pe_imp = pe->pe_import; pe_imp->Name; pe_imp++) {
+ 	char *name = (char *) RVA(pe_imp->Name);
+	mod_ptr[i] = MODULE_Load( name, (LPVOID)-1, FALSE );
 	if (mod_ptr[i] <= (HMODULE16) 32) {
 	    char *p, buffer[256];
 
@@ -198,7 +170,7 @@
 	    if (!(p = strrchr (buffer, '\\')))
 		p = buffer;
 	    strcpy (p + 1, name);
-	    mod_ptr[i] = LoadModule (buffer, (LPVOID) - 1);
+	    mod_ptr[i] = MODULE_Load( buffer, (LPVOID)-1, FALSE );
 	}
 	if (mod_ptr[i] <= (HMODULE16) 32) {
 	    fprintf (stderr, "Module %s not found\n", name);
@@ -207,66 +179,80 @@
 	i++;
     }
     pe_imp = pe->pe_import;
-    while (pe_imp->ModuleName) {
-	char *Module;
-	struct pe_import_name *pe_name;
-	unsigned int *import_list, *thunk_list;
+    while (pe_imp->Name) {
+	char			*Module;
+	IMAGE_IMPORT_BY_NAME	*pe_name;
+	LPIMAGE_THUNK_DATA	import_list,thunk_list;
+	int			ordimportwarned;
 
-	Module = ((char *) load_addr) + pe_imp->ModuleName;
+        ordimportwarned = 0;
+	Module = (char *) RVA(pe_imp->Name);
 	dprintf_win32 (stddeb, "%s\n", Module);
 
-	if (pe_imp->Import_List != 0) {	/* original microsoft style */
+	if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
 	    dprintf_win32 (stddeb, "Microsoft style imports used\n");
-	    import_list = (unsigned int *)(((unsigned int)load_addr)+pe_imp->Import_List);
-	    thunk_list = (unsigned int *)(((unsigned int)load_addr)+pe_imp->Thunk_List);
+	    import_list =(LPIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
+	    thunk_list = (LPIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
 
-	    while (*import_list) {
-		pe_name = (struct pe_import_name *) ((int) load_addr + ((unsigned) *import_list & ~0x80000000));
-		if ((unsigned) *import_list & 0x80000000) {
-		    int ordinal = *import_list & (0x80000000 - 1);
+	    while (import_list->u1.Ordinal) {
+		if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
+		    int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
+
+		    if(!lstrncmpi32A(Module,"kernel32",8) && !ordimportwarned){
+		       fprintf(stderr,"%s imports kernel32.dll by ordinal. May crash.\n",modname);
+		       ordimportwarned = 1;
+		    }
 		    dprintf_win32 (stddeb, "--- Ordinal %s,%d\n", Module, ordinal);
-		    *thunk_list = (unsigned)GetProcAddress32(MODULE_FindModule (Module),
-		    				   (LPCSTR) ordinal);
-		    if (!*thunk_list) {
+		    thunk_list->u1.Function=(LPDWORD)GetProcAddress32(MODULE_FindModule(Module),(LPCSTR)ordinal);
+		    if (!thunk_list->u1.Function) {
 			fprintf(stderr,"No implementation for %s.%d, setting to NULL\n",
 				Module, ordinal);
 			/* fixup_failed=1; */
 		    }
 		} else {		/* import by name */
+		    pe_name = (LPIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
 		    dprintf_win32 (stddeb, "--- %s %s.%d\n", pe_name->Name, Module, pe_name->Hint);
-		    *thunk_list = (unsigned)GetProcAddress32(MODULE_FindModule (Module),
-						   pe_name->Name);
-		    if (!*thunk_list) {
-			fprintf(stderr, "No implementation for %s.%d(%s), setting to NULL\n",
-				Module, pe_name->Hint, pe_name->Name);
+		    thunk_list->u1.Function=(LPDWORD)GetProcAddress32(
+						MODULE_FindModule (Module),
+						pe_name->Name);
+		    if (!thunk_list->u1.Function) {
+			fprintf(stderr,"No implementation for %s.%d(%s), setting to NULL\n",
+				Module,pe_name->Hint,pe_name->Name);
 			/* fixup_failed=1; */
 		    }
 		}
 		import_list++;
 		thunk_list++;
 	    }
-	} else {			/* Borland style */
+	} else {	/* Borland style */
 	    dprintf_win32 (stddeb, "Borland style imports used\n");
-	    thunk_list = (unsigned int *)(((unsigned int)load_addr)+pe_imp->Thunk_List);
-	    while (*thunk_list) {
-		pe_name=(struct pe_import_name *)((int)load_addr+*thunk_list);
-		if ((unsigned) pe_name & 0x80000000) {
+	    thunk_list = (LPIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
+	    while (thunk_list->u1.Ordinal) {
+		if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
 		    /* not sure about this branch, but it seems to work */
-		    int ordinal = *thunk_list & ~0x80000000;
+		    int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
+
+
+		    if (!lstrncmpi32A(Module,"kernel32",8) && 
+		    	!ordimportwarned
+		    ) {
+		       fprintf(stderr,"%s imports kernel32.dll by ordinal. May crash.\n",modname);
+		       ordimportwarned = 1;
+		    }
 		    dprintf_win32(stddeb,"--- Ordinal %s.%d\n",Module,ordinal);
-		    *thunk_list = (unsigned)GetProcAddress32(MODULE_FindModule (Module),
-						   (LPCSTR) ordinal);
-		    if (!*thunk_list) {
+		    thunk_list->u1.Function=(LPDWORD)GetProcAddress32(MODULE_FindModule(Module),
+						     (LPCSTR) ordinal);
+		    if (!thunk_list->u1.Function) {
 			fprintf(stderr, "No implementation for %s.%d, setting to NULL\n",
 				Module,ordinal);
 			/* fixup_failed=1; */
 		    }
 		} else {
+		    pe_name=(LPIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
 		    dprintf_win32(stddeb,"--- %s %s.%d\n",
-		   		  pe_name->Name, Module, pe_name->Hint);
-		    *thunk_list = (unsigned)GetProcAddress32(MODULE_FindModule(Module),
-						   pe_name->Name);
-		    if (!*thunk_list) {
+		   		  pe_name->Name,Module,pe_name->Hint);
+		    thunk_list->u1.Function=(LPDWORD)GetProcAddress32(MODULE_FindModule(Module),pe_name->Name);
+		    if (!thunk_list->u1.Function) {
 		    	fprintf(stderr, "No implementation for %s.%d, setting to NULL\n",
 				Module, pe_name->Hint);
 		    	/* fixup_failed=1; */
@@ -286,13 +272,13 @@
 
   dprintf_win32(stddeb, "Dump of segment table\n");
   dprintf_win32(stddeb, "   Name    VSz  Vaddr     SzRaw   Fileadr  *Reloc *Lineum #Reloc #Linum Char\n");
-  for(i=0; i< pe->pe_header->coff.NumberOfSections; i++)
+  for(i=0; i< pe->pe_header->FileHeader.NumberOfSections; i++)
     {
       dprintf_win32(stddeb, "%8s: %4.4lx %8.8lx %8.8lx %8.8lx %8.8lx %8.8lx %4.4x %4.4x %8.8lx\n", 
 	     pe->pe_seg[i].Name, 
-	     pe->pe_seg[i].Virtual_Size,
-	     pe->pe_seg[i].Virtual_Address,
-	     pe->pe_seg[i].Size_Of_Raw_Data,
+	     pe->pe_seg[i].Misc.VirtualSize,
+	     pe->pe_seg[i].VirtualAddress,
+	     pe->pe_seg[i].SizeOfRawData,
 	     pe->pe_seg[i].PointerToRawData,
 	     pe->pe_seg[i].PointerToRelocations,
 	     pe->pe_seg[i].PointerToLinenumbers,
@@ -300,33 +286,36 @@
 	     pe->pe_seg[i].NumberOfLinenumbers,
 	     pe->pe_seg[i].Characteristics);
 	  pe->vma_size = MAX(pe->vma_size,
-	  		pe->pe_seg[i].Virtual_Address + 
-			pe->pe_seg[i].Size_Of_Raw_Data);
+	  		pe->pe_seg[i].VirtualAddress + 
+			pe->pe_seg[i].SizeOfRawData);
     }
 }
 
 static void do_relocations(struct pe_data *pe)
 {
 	int delta = pe->load_addr - pe->base_addr;
-	struct PE_Reloc_Block *r = pe->pe_reloc;
+	unsigned int load_addr = pe->load_addr;
+	IMAGE_BASE_RELOCATION	*r = pe->pe_reloc;
 	int hdelta = (delta >> 16) & 0xFFFF;
 	int ldelta = delta & 0xFFFF;
+
 	/* int reloc_size = */
+
 	if(delta == 0)
 		/* Nothing to do */
 		return;
-	while(r->PageRVA)
+	while(r->VirtualAddress)
 	{
-		char *page = (char*)pe->load_addr + r->PageRVA;
-		int count = (r->BlockSize - 8)/2;
+		char *page = (char*) RVA(r->VirtualAddress);
+		int count = (r->SizeOfBlock - 8)/2;
 		int i;
 		dprintf_fixup(stddeb, "%x relocations for page %lx\n",
-			count, r->PageRVA);
+			count, r->VirtualAddress);
 		/* patching in reverse order */
 		for(i=0;i<count;i++)
 		{
-			int offset = r->Relocations[i] & 0xFFF;
-			int type = r->Relocations[i] >> 12;
+			int offset = r->TypeOffset[i] & 0xFFF;
+			int type = r->TypeOffset[i] >> 12;
 			dprintf_fixup(stddeb,"patching %x type %x\n", offset, type);
 			switch(type)
 			{
@@ -342,7 +331,7 @@
 				*(int*)(page+offset) += delta;
 #else
 				{ int h=*(unsigned short*)(page+offset);
-				  int l=r->Relocations[++i];
+				  int l=r->TypeOffset[++i];
 				  *(unsigned int*)(page + offset) = (h<<16) + l + delta;
 				}
 #endif
@@ -358,7 +347,7 @@
 				break;
 			}
 		}
-		r = (struct PE_Reloc_Block*)((char*)r + r->BlockSize);
+		r = (IMAGE_BASE_RELOCATION*)((char*)r + r->SizeOfBlock);
 	}
 }
 		
@@ -372,40 +361,39 @@
  */
 static struct pe_data *PE_LoadImage( int fd, HMODULE16 hModule, WORD offset )
 {
-    struct pe_data *pe;
-    int i, result;
-    int load_addr;
-    struct Directory dir;
-    char	buffer[200];
-    DBG_ADDR	daddr;
+	struct pe_data		*pe;
+	int			i, result;
+	int			load_addr;
+	IMAGE_DATA_DIRECTORY	dir;
+	char			buffer[200];
+	DBG_ADDR		daddr;
 
 	daddr.seg=0;
 	daddr.type = NULL;
 	pe = xmalloc(sizeof(struct pe_data));
 	memset(pe,0,sizeof(struct pe_data));
-	pe->pe_header = xmalloc(sizeof(struct pe_header_s));
+	pe->pe_header = xmalloc(sizeof(IMAGE_NT_HEADERS));
 
 	/* read PE header */
 	lseek( fd, offset, SEEK_SET);
-	read( fd, pe->pe_header, sizeof(struct pe_header_s));
+	read( fd, pe->pe_header, sizeof(IMAGE_NT_HEADERS));
 
 /* FIXME: this is a *horrible* hack to make COMDLG32.DLL load OK. The
 problem needs to be fixed properly at some stage */
 
-	if (pe->pe_header->opt_coff.NumberOfRvaAndSizes != 16) {
+	if (pe->pe_header->OptionalHeader.NumberOfRvaAndSizes != 16) {
 		printf("Short PE Header!!!\n");
-		lseek( fd, -(16 - pe->pe_header->opt_coff.NumberOfRvaAndSizes) * sizeof (struct Directory), SEEK_CUR);
+		lseek( fd, -(16 - pe->pe_header->OptionalHeader.NumberOfRvaAndSizes) * sizeof(IMAGE_DATA_DIRECTORY), SEEK_CUR);
 	}
 
 /* horrible hack ends !!! */
-
 	/* read sections */
-	pe->pe_seg = xmalloc(sizeof(struct pe_segment_table) * 
-				   pe->pe_header->coff.NumberOfSections);
-	read( fd, pe->pe_seg, sizeof(struct pe_segment_table) * 
-			pe->pe_header->coff.NumberOfSections);
+	pe->pe_seg = xmalloc(sizeof(IMAGE_SECTION_HEADER) * 
+				   pe->pe_header->FileHeader.NumberOfSections);
+	read( fd, pe->pe_seg, sizeof(IMAGE_SECTION_HEADER) * 
+			pe->pe_header->FileHeader.NumberOfSections);
 
-	load_addr = pe->pe_header->opt_coff.BaseOfImage;
+	load_addr = pe->pe_header->OptionalHeader.ImageBase;
 	pe->base_addr=load_addr;
 	pe->vma_size=0;
 	dprintf_win32(stddeb, "Load addr is %x\n",load_addr);
@@ -429,135 +417,122 @@
 		pe->load_addr, pe->vma_size);
 	
 
-	for(i=0; i < pe->pe_header->coff.NumberOfSections; i++)
+	for(i=0; i < pe->pe_header->FileHeader.NumberOfSections; i++)
 	{
 		/* load only non-BSS segments */
 		if(pe->pe_seg[i].Characteristics & 
-			~ IMAGE_SCN_TYPE_CNT_UNINITIALIZED_DATA)
+			~ IMAGE_SCN_CNT_UNINITIALIZED_DATA)
 		if(lseek(fd,pe->pe_seg[i].PointerToRawData,SEEK_SET) == -1
-		|| read(fd,(char *)load_addr + pe->pe_seg[i].Virtual_Address,
-				pe->pe_seg[i].Size_Of_Raw_Data) 
-				!= pe->pe_seg[i].Size_Of_Raw_Data)
+		|| read(fd,(char*)RVA(pe->pe_seg[i].VirtualAddress),
+			   pe->pe_seg[i].SizeOfRawData) != pe->pe_seg[i].SizeOfRawData)
 		{
 			fprintf(stderr,"Failed to load section %x\n", i);
 			exit(0);
 		}
-		result = load_addr + pe->pe_seg[i].Virtual_Address;
-#if 0
-	if(!load_addr) {
-		
-		result = (int)xmmap((char *)0, pe->pe_seg[i].Virtual_Size,
-			pe->pe_seg[i].Size_Of_Raw_Data, 7,
-			MAP_PRIVATE, fd, pe->pe_seg[i].PointerToRawData);
-		load_addr = (unsigned int) result -  pe->pe_seg[i].Virtual_Address;
-	} else {
-		result = (int)xmmap((char *) load_addr + pe->pe_seg[i].Virtual_Address, 
-			  pe->pe_seg[i].Virtual_Size,
-		      pe->pe_seg[i].Size_Of_Raw_Data, 7, MAP_PRIVATE | MAP_FIXED, 
-		      fd, pe->pe_seg[i].PointerToRawData);
-	}
-	if(result==-1){
-		fprintf(stderr,"Could not load section %x to desired address %lx\n",
-			i, load_addr+pe->pe_seg[i].Virtual_Address);
-		fprintf(stderr,"Need to implement relocations now\n");
-		exit(0);
-	}
+		result = RVA (pe->pe_seg[i].VirtualAddress);
+#if 1
+		/* not needed, memory is zero */
+		if(strcmp(pe->pe_seg[i].Name, ".bss") == 0)
+		    memset((void *)result, 0, 
+			   pe->pe_seg[i].Misc.VirtualSize ?
+			   pe->pe_seg[i].Misc.VirtualSize :
+			   pe->pe_seg[i].SizeOfRawData);
 #endif
 
-#if 0
-	/* not needed, memory is zero */
-        if(strcmp(pe->pe_seg[i].Name, ".bss") == 0)
-            memset((void *)result, 0, 
-                   pe->pe_seg[i].Virtual_Size ?
-                   pe->pe_seg[i].Virtual_Size :
-                   pe->pe_seg[i].Size_Of_Raw_Data);
-#endif
+		if(strcmp(pe->pe_seg[i].Name, ".idata") == 0)
+			pe->pe_import = (LPIMAGE_IMPORT_DESCRIPTOR) result;
 
-	if(strcmp(pe->pe_seg[i].Name, ".idata") == 0)
-		pe->pe_import = (struct PE_Import_Directory *) result;
+		if(strcmp(pe->pe_seg[i].Name, ".edata") == 0)
+			pe->pe_export = (LPIMAGE_EXPORT_DIRECTORY) result;
 
-	if(strcmp(pe->pe_seg[i].Name, ".edata") == 0)
-		pe->pe_export = (struct PE_Export_Directory *) result;
+		if(strcmp(pe->pe_seg[i].Name, ".rsrc") == 0)
+			pe->pe_resource = (LPIMAGE_RESOURCE_DIRECTORY) result;
 
-	if(strcmp(pe->pe_seg[i].Name, ".rsrc") == 0)
-	    pe->pe_resource = (struct PE_Resource_Directory *) result;
-
-	if(strcmp(pe->pe_seg[i].Name, ".reloc") == 0)
-		pe->pe_reloc = (struct PE_Reloc_Block *) result;
+		if(strcmp(pe->pe_seg[i].Name, ".reloc") == 0)
+			pe->pe_reloc = (LPIMAGE_BASE_RELOCATION) result;
 
 	}
 
 	/* There is word that the actual loader does not care about the
 	   section names, and only goes for the DataDirectory */
-	dir=pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
+	dir=pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
 	if(dir.Size)
 	{
-		if(pe->pe_export && 
-			(int)pe->pe_export!=load_addr+dir.Virtual_address)
+		if(pe->pe_export && (int)pe->pe_export!=RVA(dir.VirtualAddress))
 			fprintf(stderr,"wrong export directory??\n");
 		/* always trust the directory */
-		pe->pe_export = (void *)(load_addr+dir.Virtual_address);
+		pe->pe_export = (LPIMAGE_EXPORT_DIRECTORY) RVA(dir.VirtualAddress);
 	}
 
-	dir=pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
+	dir=pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
 	if(dir.Size)
 	{
-		if(pe->pe_import && 
-			(int)pe->pe_import!=load_addr+dir.Virtual_address)
+		if(pe->pe_import && (int)pe->pe_import!=RVA(dir.VirtualAddress))
 			fprintf(stderr,"wrong import directory??\n");
-		pe->pe_import = (void *)(load_addr+dir.Virtual_address);
+		pe->pe_import = (LPIMAGE_IMPORT_DESCRIPTOR) RVA(dir.VirtualAddress);
 	}
 
-	dir=pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
+	dir=pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];
 	if(dir.Size)
 	{
-		if(pe->pe_resource && 
-			(int)pe->pe_resource!=load_addr+dir.Virtual_address)
+		if(pe->pe_resource && (int)pe->pe_resource!=RVA(dir.VirtualAddress))
 			fprintf(stderr,"wrong resource directory??\n");
-		pe->pe_resource = (void *)(load_addr+dir.Virtual_address);
+		pe->pe_resource = (LPIMAGE_RESOURCE_DIRECTORY) RVA(dir.VirtualAddress);
 	}
 
-	dir=pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_BASE_RELOCATION_TABLE];
-	if(dir.Size)
-	{
-		if(pe->pe_reloc && 
-			(int)pe->pe_reloc!=load_addr+dir.Virtual_address)
-			fprintf(stderr,"wrong relocation list??\n");
-		pe->pe_reloc = (void *)(load_addr+dir.Virtual_address);
-	}
-
-	if(pe->pe_header->opt_coff.DataDirectory
-		[IMAGE_FILE_EXCEPTION_DIRECTORY].Size)
+	if(pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size)
 		dprintf_win32(stdnimp,"Exception directory ignored\n");
 
-	if(pe->pe_header->opt_coff.DataDirectory
-		[IMAGE_FILE_SECURITY_DIRECTORY].Size)
+	if(pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size)
 		dprintf_win32(stdnimp,"Security directory ignored\n");
 
-	if(pe->pe_header->opt_coff.DataDirectory
-		[IMAGE_FILE_DEBUG_DIRECTORY].Size)
+
+
+	dir=pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
+	if(dir.Size)
+	{
+		if(pe->pe_reloc && (int)pe->pe_reloc!= RVA(dir.VirtualAddress))
+			fprintf(stderr,"wrong relocation list??\n");
+		pe->pe_reloc = (void *) RVA(dir.VirtualAddress);
+	}
+
+	if(pe->pe_header->OptionalHeader.DataDirectory
+		[IMAGE_DIRECTORY_ENTRY_DEBUG].Size)
 	  {
 	    DEBUG_RegisterDebugInfo(fd, pe, load_addr, 
-			pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_DEBUG_DIRECTORY].Virtual_address,
-			pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_DEBUG_DIRECTORY].Size);
+			pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress,
+			pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size);
 	  }
 
-	if(pe->pe_header->opt_coff.DataDirectory
-		[IMAGE_FILE_DESCRIPTION_STRING].Size)
-		dprintf_win32(stdnimp,"Description string ignored\n");
+	if(pe->pe_header->OptionalHeader.DataDirectory
+		[IMAGE_DIRECTORY_ENTRY_COPYRIGHT].Size)
+		dprintf_win32(stdnimp,"Copyright string ignored\n");
 
-	if(pe->pe_header->opt_coff.DataDirectory
-		[IMAGE_FILE_MACHINE_VALUE].Size)
-		dprintf_win32(stdnimp,"Machine Value ignored\n");
+	if(pe->pe_header->OptionalHeader.DataDirectory
+		[IMAGE_DIRECTORY_ENTRY_GLOBALPTR].Size)
+		dprintf_win32(stdnimp,"Global Pointer (MIPS) ignored\n");
 
-	if(pe->pe_header->opt_coff.DataDirectory
-		[IMAGE_FILE_THREAD_LOCAL_STORAGE].Size)
+	if(pe->pe_header->OptionalHeader.DataDirectory
+		[IMAGE_DIRECTORY_ENTRY_TLS].Size)
 		 dprintf_win32(stdnimp,"Thread local storage ignored\n");
 
-	if(pe->pe_header->opt_coff.DataDirectory
-		[IMAGE_FILE_CALLBACK_DIRECTORY].Size)
-		dprintf_win32(stdnimp,"Callback directory ignored\n");
+	if(pe->pe_header->OptionalHeader.DataDirectory
+		[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].Size)
+		dprintf_win32(stdnimp,"Load Configuration directory ignored\n");
 
+	if(pe->pe_header->OptionalHeader.DataDirectory
+		[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].Size)
+		dprintf_win32(stdnimp,"Bound Import directory ignored\n");
+
+	if(pe->pe_header->OptionalHeader.DataDirectory
+		[IMAGE_DIRECTORY_ENTRY_IAT].Size)
+		dprintf_win32(stdnimp,"Import Address Table directory ignored\n");
+	if(pe->pe_header->OptionalHeader.DataDirectory[13].Size)
+		dprintf_win32(stdnimp,"Unknown directory 13 ignored\n");
+	if(pe->pe_header->OptionalHeader.DataDirectory[14].Size)
+		dprintf_win32(stdnimp,"Unknown directory 14 ignored\n");
+	if(pe->pe_header->OptionalHeader.DataDirectory[15].Size)
+		dprintf_win32(stdnimp,"Unknown directory 15 ignored\n");
 
 	if(pe->pe_reloc) do_relocations(pe);
 	if(pe->pe_import) fixup_imports(pe, hModule);
@@ -565,21 +540,21 @@
   		
 	if (pe->pe_export) {
 		/* add start of sections as debugsymbols */
-		for(i=0;i<pe->pe_header->coff.NumberOfSections;i++) {
+		for(i=0;i<pe->pe_header->FileHeader.NumberOfSections;i++) {
 			sprintf(buffer,"%s.%s",
-				((char*)load_addr)+pe->pe_export->Name,
+				(char*)RVA(pe->pe_export->Name),
 				pe->pe_seg[i].Name
 			);
-			daddr.off=load_addr+pe->pe_seg[i].Virtual_Address;
+			daddr.off= RVA(pe->pe_seg[i].VirtualAddress);
 			DEBUG_AddSymbol(buffer,&daddr, NULL, SYM_WIN32 | SYM_FUNC);
 		}
 		/* add entry point */
-		sprintf(buffer,"%s.EntryPoint",((char*)load_addr)+pe->pe_export->Name);
-		daddr.off=load_addr+pe->pe_header->opt_coff.AddressOfEntryPoint;
+		sprintf(buffer,"%s.EntryPoint",(char*)RVA(pe->pe_export->Name));
+		daddr.off=RVA(pe->pe_header->OptionalHeader.AddressOfEntryPoint);
 		DEBUG_AddSymbol(buffer,&daddr, NULL, SYM_WIN32 | SYM_FUNC);
 		/* add start of DLL */
 		daddr.off=load_addr;
-		DEBUG_AddSymbol(((char*)load_addr)+pe->pe_export->Name,&daddr,
+		DEBUG_AddSymbol((char*) RVA(pe->pe_export->Name),&daddr,
 				NULL, SYM_WIN32 | SYM_FUNC);
 	}
         return pe;
@@ -605,7 +580,7 @@
 
     hInstance = MODULE_CreateInstance( hModule, params );
 
-    if (!(pModule->pe_module->pe_header->coff.Characteristics & IMAGE_FILE_DLL))
+    if (!(pModule->pe_module->pe_header->FileHeader.Characteristics & IMAGE_FILE_DLL))
     {
         TASK_CreateTask( hModule, hInstance, 0,
                          params->hEnvironment,
@@ -626,6 +601,7 @@
 {
     NE_MODULE *pModule;
     PE_MODULE *pe;
+    unsigned int load_addr;
 
     hModule = GetExePtr(hModule);
     if (!(pModule = MODULE_GetPtr(hModule))) return;
@@ -636,13 +612,18 @@
      *	      (the MSDN library JAN96 says 'reserved for future use')
      */
         
-    /* Is this a library? */
-    if (pe->pe_header->coff.Characteristics & IMAGE_FILE_DLL)
-    {
-        printf("InitPEDLL() called!\n");
-        CallDLLEntryProc32( (FARPROC32)(pe->load_addr + 
-                                  pe->pe_header->opt_coff.AddressOfEntryPoint),
-                            hModule, DLL_PROCESS_ATTACH, -1 );
+    /* Is this a library? And has it got an entrypoint? */
+    if (	(pe->pe_header->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
+		(pe->pe_header->OptionalHeader.AddressOfEntryPoint)
+    ) {
+        load_addr = pe->load_addr;
+	printf("InitPEDLL() called!\n");
+	CallDLLEntryProc32( 
+	    (FARPROC32)RVA(pe->pe_header->OptionalHeader.AddressOfEntryPoint),
+	    hModule,
+	    DLL_PROCESS_ATTACH,
+	    -1
+	);
     }
 }
 
diff --git a/loader/pe_resource.c b/loader/pe_resource.c
index 74b74bc..7c7e6af 100644
--- a/loader/pe_resource.c
+++ b/loader/pe_resource.c
@@ -20,7 +20,6 @@
 #include "heap.h"
 #include "handle32.h"
 #include "libres.h"
-#include "resource32.h"
 #include "stackframe.h"
 #include "neexe.h"
 #include "accel.h"
@@ -42,48 +41,47 @@
  *	Helper function - goes down one level of PE resource tree
  *
  */
-PIMAGE_RESOURCE_DIRECTORY GetResDirEntryW(PIMAGE_RESOURCE_DIRECTORY resdirptr,
-					 LPCWSTR name,
-					 DWORD root)
+LPIMAGE_RESOURCE_DIRECTORY GetResDirEntryW(LPIMAGE_RESOURCE_DIRECTORY resdirptr,
+					   LPCWSTR name,DWORD root)
 {
     int entrynum;
-    PIMAGE_RESOURCE_DIRECTORY_ENTRY entryTable;
-	int namelen;
+    LPIMAGE_RESOURCE_DIRECTORY_ENTRY entryTable;
+    int namelen;
 
     if (HIWORD(name)) {
     /* FIXME: what about #xxx names? */
-	entryTable = (PIMAGE_RESOURCE_DIRECTORY_ENTRY) (
+	entryTable = (LPIMAGE_RESOURCE_DIRECTORY_ENTRY) (
 			(BYTE *) resdirptr + 
                         sizeof(IMAGE_RESOURCE_DIRECTORY));
 	namelen = lstrlen32W(name);
 	for (entrynum = 0; entrynum < resdirptr->NumberOfNamedEntries; entrynum++)
 	{
-		PIMAGE_RESOURCE_DIR_STRING_U str =
-		(PIMAGE_RESOURCE_DIR_STRING_U) (root + 
-			(entryTable[entrynum].Name & 0x7fffffff));
+		LPIMAGE_RESOURCE_DIR_STRING_U str =
+		(LPIMAGE_RESOURCE_DIR_STRING_U) (root + 
+			entryTable[entrynum].u1.s.NameOffset);
 		if(namelen != str->Length)
 			continue;
 		if(lstrncmpi32W(name,str->NameString,str->Length)==0)
-			return (PIMAGE_RESOURCE_DIRECTORY) (
+			return (LPIMAGE_RESOURCE_DIRECTORY) (
 				root +
-				(entryTable[entrynum].OffsetToData & 0x7fffffff));
+				entryTable[entrynum].u2.s.OffsetToDirectory);
 	}
 	return NULL;
     } else {
-	entryTable = (PIMAGE_RESOURCE_DIRECTORY_ENTRY) (
+	entryTable = (LPIMAGE_RESOURCE_DIRECTORY_ENTRY) (
 			(BYTE *) resdirptr + 
                         sizeof(IMAGE_RESOURCE_DIRECTORY) +
 			resdirptr->NumberOfNamedEntries * sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY));
 	for (entrynum = 0; entrynum < resdirptr->NumberOfIdEntries; entrynum++)
-	    if ((DWORD)entryTable[entrynum].Name == (DWORD)name)
-		return (PIMAGE_RESOURCE_DIRECTORY) (
+	    if ((DWORD)entryTable[entrynum].u1.Name == (DWORD)name)
+		return (LPIMAGE_RESOURCE_DIRECTORY) (
 			root +
-			(entryTable[entrynum].OffsetToData & 0x7fffffff));
+			entryTable[entrynum].u2.s.OffsetToDirectory);
 	/* just use first entry if no default can be found */
 	if (!name && resdirptr->NumberOfIdEntries)
-		return (PIMAGE_RESOURCE_DIRECTORY) (
+		return (LPIMAGE_RESOURCE_DIRECTORY) (
 			root +
-			(entryTable[0].OffsetToData & 0x7fffffff));
+			entryTable[0].u2.s.OffsetToDirectory);
 	return NULL;
     }
 }
@@ -94,12 +92,12 @@
  *	Helper function - goes down one level of PE resource tree
  *
  */
-PIMAGE_RESOURCE_DIRECTORY GetResDirEntryA(PIMAGE_RESOURCE_DIRECTORY resdirptr,
-					 LPCSTR name,
-					 DWORD root)
+LPIMAGE_RESOURCE_DIRECTORY GetResDirEntryA(LPIMAGE_RESOURCE_DIRECTORY resdirptr,
+					   LPCSTR name,
+					   DWORD root)
 {
 	LPWSTR				xname;
-	PIMAGE_RESOURCE_DIRECTORY	ret;
+	LPIMAGE_RESOURCE_DIRECTORY	ret;
 
 	if (HIWORD((DWORD)name))
 		xname	= HEAP_strdupAtoW( GetProcessHeap(), 0, name );
@@ -115,13 +113,12 @@
 /**********************************************************************
  *	    PE_FindResourceEx32W
  */
-HANDLE32 PE_FindResourceEx32W( 
-	HINSTANCE32 hModule, LPCWSTR name, LPCWSTR type, WORD lang
-)
-{
+HANDLE32 PE_FindResourceEx32W(
+	HINSTANCE32 hModule,LPCWSTR name,LPCWSTR type,WORD lang
+) {
     PE_MODULE *pe;
     NE_MODULE *pModule;
-    PIMAGE_RESOURCE_DIRECTORY resdirptr;
+    LPIMAGE_RESOURCE_DIRECTORY resdirptr;
     DWORD root;
     HANDLE32 result;
 
@@ -135,7 +132,7 @@
     if (!(pModule->flags & NE_FFLAGS_WIN32)) return 0;  /* FIXME? */
     if (!(pe = pModule->pe_module) || !pe->pe_resource) return 0;
 
-    resdirptr = (PIMAGE_RESOURCE_DIRECTORY) pe->pe_resource;
+    resdirptr = pe->pe_resource;
     root = (DWORD) resdirptr;
     if ((resdirptr = GetResDirEntryW(resdirptr, type, root)) == NULL)
 	return 0;
@@ -166,6 +163,6 @@
     if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
     if (!(pModule->flags & NE_FFLAGS_WIN32)) return 0;  /* FIXME? */
     if (!(pe = pModule->pe_module) || !pe->pe_resource) return 0;
-    return (HANDLE32) (pe->load_addr+((PIMAGE_RESOURCE_DATA_ENTRY)hRsrc)->OffsetToData);
+    return (HANDLE32) (pe->load_addr+((LPIMAGE_RESOURCE_DATA_ENTRY)hRsrc)->OffsetToData);
 }
 #endif
diff --git a/loader/resource.c b/loader/resource.c
index 3ae6821..de289b6 100644
--- a/loader/resource.c
+++ b/loader/resource.c
@@ -731,3 +731,16 @@
     return retval;
 }
 
+
+/**********************************************************************
+ *	SetResourceHandler	(KERNEL.43)
+ */
+FARPROC16
+SetResourceHandler(HINSTANCE16 instance,LPSTR s,FARPROC16 farproc)
+{
+    if (HIWORD(s))
+	fprintf(stderr,"SetResourceHandler(%04x,%s,%p), empty STUB!\n",instance,s,farproc);
+    else
+	fprintf(stderr,"SetResourceHandler(%04x,0x%04x,%p), empty STUB!\n",instance,LOWORD(s),farproc);
+    return NULL;
+}
diff --git a/loader/signal.c b/loader/signal.c
index a2ea979..2d97ed5 100644
--- a/loader/signal.c
+++ b/loader/signal.c
@@ -12,8 +12,8 @@
 #include <sys/types.h>
 #include <sys/wait.h>
 
-#if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__svr4__) || defined(_SCO_DS)
-#ifndef _SCO_DS
+#if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__svr4__) || defined(_SCO_DS) || defined(__EMX__)
+#if !defined(_SCO_DS) && !defined(__EMX__)
 #include <sys/syscall.h>
 #endif
 #include <sys/param.h>
@@ -143,6 +143,7 @@
 static void SIGNAL_fault(int signal, int code, SIGCONTEXT *context)
 {
 #endif
+#ifndef __EMX__ /* FIXME: XX_sig(constext)=pointer to incomplete type (EMX) */
     if (CS_sig(context) == WINE_CODE_SELECTOR)
     {
         fprintf( stderr, "Segmentation fault in Wine program (%x:%lx)."
@@ -156,6 +157,7 @@
                  CS_sig(context), EIP_sig(context) );
     }
     wine_debug( signal, context );
+#endif
 }
 
 
@@ -257,7 +259,9 @@
 #ifdef CONFIG_IPC
     SIGNAL_SetHandler( SIGUSR2, (void (*)())stop_wait, 1); 	/* For IPC */
 #endif
+#ifndef __EMX__ /* FIXME */
     SIGNAL_SetHandler( SIGIO,   (void (*)())WINSOCK_sigio, 0); 
+#endif
     return TRUE;
 }
 
@@ -269,6 +273,7 @@
  */
 void SIGNAL_StartBIOSTimer(void)
 {
+#ifndef __EMX__ /* FIXME: Time don't work... Use BIOS directly instead */
     struct itimerval vt_timer;
     static int timer_started = 0;
 
@@ -279,6 +284,7 @@
     vt_timer.it_value = vt_timer.it_interval;
 
     setitimer(ITIMER_REAL, &vt_timer, NULL);
+#endif
 }
 
 /**********************************************************************
@@ -288,7 +294,9 @@
 {
   sigset_t 	set;
   sigemptyset(&set);
+#ifndef __EMX__ /* FIXME */
   sigaddset(&set, SIGIO);
+#endif
   sigaddset(&set, SIGUSR1);
 #ifdef CONFIG_IPC
   sigaddset(&set, SIGUSR2);
diff --git a/loader/task.c b/loader/task.c
index 27cfcbe..0b721e6 100644
--- a/loader/task.c
+++ b/loader/task.c
@@ -368,7 +368,7 @@
         __asm__ __volatile__("movw %w0,%%fs"::"r" (pCurrentThread->teb_sel));
         PE_InitializeDLLs( pTask->hModule );
         exit_code = CallTaskStart32((FARPROC32)(pModule->pe_module->load_addr + 
-                pModule->pe_module->pe_header->opt_coff.AddressOfEntryPoint) );
+                pModule->pe_module->pe_header->OptionalHeader.AddressOfEntryPoint) );
         TASK_KillCurrentTask( exit_code );
     }
     else
@@ -593,7 +593,7 @@
         if (pModule->flags & NE_FFLAGS_WIN32)
         {
             DBG_ADDR addr = { NULL, 0, pModule->pe_module->load_addr + 
-                              pModule->pe_module->pe_header->opt_coff.AddressOfEntryPoint };
+                              pModule->pe_module->pe_header->OptionalHeader.AddressOfEntryPoint };
             fprintf( stderr, "Win32 task '%s': ", name );
             DEBUG_AddBreakpoint( &addr );
         }
diff --git a/misc/Makefile.in b/misc/Makefile.in
index 702bb00..3b4dfaa 100644
--- a/misc/Makefile.in
+++ b/misc/Makefile.in
@@ -15,7 +15,7 @@
 	driver.c \
 	exec.c \
 	escape.c \
-	keyboard.c \
+	fontengine.c \
 	lstr.c \
 	lzexpand.c \
 	main.c \
diff --git a/misc/clipboard.c b/misc/clipboard.c
index aa7ba4d..f7d38ae 100644
--- a/misc/clipboard.c
+++ b/misc/clipboard.c
@@ -160,7 +160,7 @@
  */
 BOOL CLIPBOARD_RequestXSelection()
 {
-  HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
+  HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow16();
 
   if( !hWnd ) return FALSE;
 
diff --git a/misc/commdlg.c b/misc/commdlg.c
index e729d41..ece3f03 100644
--- a/misc/commdlg.c
+++ b/misc/commdlg.c
@@ -427,9 +427,9 @@
   n = DRIVE_GetCurrentDrive();
   SendDlgItemMessage16(hWnd, cmb2, CB_SETCURSEL16, n, 0);
   if (!(lpofn->Flags & OFN_SHOWHELP))
-    ShowWindow(GetDlgItem(hWnd, pshHelp), SW_HIDE);
+    ShowWindow32(GetDlgItem32(hWnd, pshHelp), SW_HIDE);
   if (lpofn->Flags & OFN_HIDEREADONLY)
-    ShowWindow(GetDlgItem(hWnd, chx1), SW_HIDE); 
+    ShowWindow32(GetDlgItem32(hWnd, chx1), SW_HIDE); 
   if (FILEDLG_HookCallChk(lpofn))
      return (BOOL)CallWindowProc16(lpofn->lpfnHook, 
                                    hWnd,  WM_INITDIALOG, wParam, lParam );
@@ -579,7 +579,7 @@
 	}
       else SetDlgItemText32A( hWnd, edt1, tmpstr );
 #if 0
-      ShowWindow(hWnd, SW_HIDE);   /* this should not be necessary ?! (%%%) */
+      ShowWindow16(hWnd, SW_HIDE);   /* this should not be necessary ?! (%%%) */
 #endif
       {
 	int drive = DRIVE_GetCurrentDrive();
@@ -614,7 +614,7 @@
        {
          *lpofn=ofn2; /* restore old state */
 #if 0
-         ShowWindow(hWnd, SW_SHOW);               /* only if above (%%%) SW_HIDE used */
+         ShowWindow16(hWnd, SW_SHOW);               /* only if above (%%%) SW_HIDE used */
 #endif         
          break;
        }
@@ -785,31 +785,31 @@
      * enabled.
      */
     SetDlgItemText16(hWnd, edt1, lpfr->lpstrFindWhat);
-    CheckRadioButton(hWnd, rad1, rad2, (lpfr->Flags & FR_DOWN) ? rad2 : rad1);
+    CheckRadioButton32(hWnd, rad1, rad2, (lpfr->Flags & FR_DOWN) ? rad2 : rad1);
     if (lpfr->Flags & (FR_HIDEUPDOWN | FR_NOUPDOWN)) {
-	EnableWindow(GetDlgItem(hWnd, rad1), FALSE);
-	EnableWindow(GetDlgItem(hWnd, rad2), FALSE);
+	EnableWindow32(GetDlgItem32(hWnd, rad1), FALSE);
+	EnableWindow32(GetDlgItem32(hWnd, rad2), FALSE);
     }
     if (lpfr->Flags & FR_HIDEUPDOWN) {
-	ShowWindow(GetDlgItem(hWnd, rad1), SW_HIDE);
-	ShowWindow(GetDlgItem(hWnd, rad2), SW_HIDE);
-	ShowWindow(GetDlgItem(hWnd, grp1), SW_HIDE);
+	ShowWindow32(GetDlgItem32(hWnd, rad1), SW_HIDE);
+	ShowWindow32(GetDlgItem32(hWnd, rad2), SW_HIDE);
+	ShowWindow32(GetDlgItem32(hWnd, grp1), SW_HIDE);
     }
-    CheckDlgButton(hWnd, chx1, (lpfr->Flags & FR_WHOLEWORD) ? 1 : 0);
+    CheckDlgButton32(hWnd, chx1, (lpfr->Flags & FR_WHOLEWORD) ? 1 : 0);
     if (lpfr->Flags & (FR_HIDEWHOLEWORD | FR_NOWHOLEWORD))
-	EnableWindow(GetDlgItem(hWnd, chx1), FALSE);
+	EnableWindow32(GetDlgItem32(hWnd, chx1), FALSE);
     if (lpfr->Flags & FR_HIDEWHOLEWORD)
-	ShowWindow(GetDlgItem(hWnd, chx1), SW_HIDE);
-    CheckDlgButton(hWnd, chx2, (lpfr->Flags & FR_MATCHCASE) ? 1 : 0);
+	ShowWindow32(GetDlgItem32(hWnd, chx1), SW_HIDE);
+    CheckDlgButton32(hWnd, chx2, (lpfr->Flags & FR_MATCHCASE) ? 1 : 0);
     if (lpfr->Flags & (FR_HIDEMATCHCASE | FR_NOMATCHCASE))
-	EnableWindow(GetDlgItem(hWnd, chx2), FALSE);
+	EnableWindow32(GetDlgItem32(hWnd, chx2), FALSE);
     if (lpfr->Flags & FR_HIDEMATCHCASE)
-	ShowWindow(GetDlgItem(hWnd, chx2), SW_HIDE);
+	ShowWindow32(GetDlgItem32(hWnd, chx2), SW_HIDE);
     if (!(lpfr->Flags & FR_SHOWHELP)) {
-	EnableWindow(GetDlgItem(hWnd, pshHelp), FALSE);
-	ShowWindow(GetDlgItem(hWnd, pshHelp), SW_HIDE);
+	EnableWindow32(GetDlgItem32(hWnd, pshHelp), FALSE);
+	ShowWindow32(GetDlgItem32(hWnd, pshHelp), SW_HIDE);
     }
-    ShowWindow(hWnd, SW_SHOWNORMAL);
+    ShowWindow32(hWnd, SW_SHOWNORMAL);
     return TRUE;
 }    
 
@@ -827,13 +827,13 @@
     switch (wParam) {
 	case IDOK:
 	    GetDlgItemText16(hWnd, edt1, lpfr->lpstrFindWhat, lpfr->wFindWhatLen);
-	    if (IsDlgButtonChecked(hWnd, rad2))
+	    if (IsDlgButtonChecked32(hWnd, rad2))
 		lpfr->Flags |= FR_DOWN;
 		else lpfr->Flags &= ~FR_DOWN;
-	    if (IsDlgButtonChecked(hWnd, chx1))
+	    if (IsDlgButtonChecked32(hWnd, chx1))
 		lpfr->Flags |= FR_WHOLEWORD; 
 		else lpfr->Flags &= ~FR_WHOLEWORD;
-	    if (IsDlgButtonChecked(hWnd, chx2))
+	    if (IsDlgButtonChecked32(hWnd, chx2))
 		lpfr->Flags |= FR_MATCHCASE; 
 		else lpfr->Flags &= ~FR_MATCHCASE;
             lpfr->Flags &= ~(FR_REPLACE | FR_REPLACEALL | FR_DIALOGTERM);
@@ -846,7 +846,7 @@
 	    lpfr->Flags |= FR_DIALOGTERM;
 	    SendMessage16(lpfr->hwndOwner, uFindReplaceMessage, 0,
                           GetWindowLong32A(hWnd, DWL_USER) );
-	    DestroyWindow(hWnd);
+	    DestroyWindow16(hWnd);
 	    return TRUE;
 	case pshHelp:
 	    /* FIXME : should lpfr structure be passed as an argument ??? */
@@ -889,21 +889,21 @@
      */
     SetDlgItemText16(hWnd, edt1, lpfr->lpstrFindWhat);
     SetDlgItemText16(hWnd, edt2, lpfr->lpstrReplaceWith);
-    CheckDlgButton(hWnd, chx1, (lpfr->Flags & FR_WHOLEWORD) ? 1 : 0);
+    CheckDlgButton32(hWnd, chx1, (lpfr->Flags & FR_WHOLEWORD) ? 1 : 0);
     if (lpfr->Flags & (FR_HIDEWHOLEWORD | FR_NOWHOLEWORD))
-	EnableWindow(GetDlgItem(hWnd, chx1), FALSE);
+	EnableWindow32(GetDlgItem32(hWnd, chx1), FALSE);
     if (lpfr->Flags & FR_HIDEWHOLEWORD)
-	ShowWindow(GetDlgItem(hWnd, chx1), SW_HIDE);
-    CheckDlgButton(hWnd, chx2, (lpfr->Flags & FR_MATCHCASE) ? 1 : 0);
+	ShowWindow32(GetDlgItem32(hWnd, chx1), SW_HIDE);
+    CheckDlgButton32(hWnd, chx2, (lpfr->Flags & FR_MATCHCASE) ? 1 : 0);
     if (lpfr->Flags & (FR_HIDEMATCHCASE | FR_NOMATCHCASE))
-	EnableWindow(GetDlgItem(hWnd, chx2), FALSE);
+	EnableWindow32(GetDlgItem32(hWnd, chx2), FALSE);
     if (lpfr->Flags & FR_HIDEMATCHCASE)
-	ShowWindow(GetDlgItem(hWnd, chx2), SW_HIDE);
+	ShowWindow32(GetDlgItem32(hWnd, chx2), SW_HIDE);
     if (!(lpfr->Flags & FR_SHOWHELP)) {
-	EnableWindow(GetDlgItem(hWnd, pshHelp), FALSE);
-	ShowWindow(GetDlgItem(hWnd, pshHelp), SW_HIDE);
+	EnableWindow32(GetDlgItem32(hWnd, pshHelp), FALSE);
+	ShowWindow32(GetDlgItem32(hWnd, pshHelp), SW_HIDE);
     }
-    ShowWindow(hWnd, SW_SHOWNORMAL);
+    ShowWindow32(hWnd, SW_SHOWNORMAL);
     return TRUE;
 }    
 
@@ -922,10 +922,10 @@
 	case IDOK:
 	    GetDlgItemText16(hWnd, edt1, lpfr->lpstrFindWhat, lpfr->wFindWhatLen);
 	    GetDlgItemText16(hWnd, edt2, lpfr->lpstrReplaceWith, lpfr->wReplaceWithLen);
-	    if (IsDlgButtonChecked(hWnd, chx1))
+	    if (IsDlgButtonChecked32(hWnd, chx1))
 		lpfr->Flags |= FR_WHOLEWORD; 
 		else lpfr->Flags &= ~FR_WHOLEWORD;
-	    if (IsDlgButtonChecked(hWnd, chx2))
+	    if (IsDlgButtonChecked32(hWnd, chx2))
 		lpfr->Flags |= FR_MATCHCASE; 
 		else lpfr->Flags &= ~FR_MATCHCASE;
             lpfr->Flags &= ~(FR_REPLACE | FR_REPLACEALL | FR_DIALOGTERM);
@@ -938,15 +938,15 @@
 	    lpfr->Flags |= FR_DIALOGTERM;
 	    SendMessage16(lpfr->hwndOwner, uFindReplaceMessage, 0,
                           GetWindowLong32A(hWnd, DWL_USER) );
-	    DestroyWindow(hWnd);
+	    DestroyWindow16(hWnd);
 	    return TRUE;
 	case psh1:
 	    GetDlgItemText16(hWnd, edt1, lpfr->lpstrFindWhat, lpfr->wFindWhatLen);
 	    GetDlgItemText16(hWnd, edt2, lpfr->lpstrReplaceWith, lpfr->wReplaceWithLen);
-	    if (IsDlgButtonChecked(hWnd, chx1))
+	    if (IsDlgButtonChecked32(hWnd, chx1))
 		lpfr->Flags |= FR_WHOLEWORD; 
 		else lpfr->Flags &= ~FR_WHOLEWORD;
-	    if (IsDlgButtonChecked(hWnd, chx2))
+	    if (IsDlgButtonChecked32(hWnd, chx2))
 		lpfr->Flags |= FR_MATCHCASE; 
 		else lpfr->Flags &= ~FR_MATCHCASE;
             lpfr->Flags &= ~(FR_FINDNEXT | FR_REPLACEALL | FR_DIALOGTERM);
@@ -957,10 +957,10 @@
 	case psh2:
 	    GetDlgItemText16(hWnd, edt1, lpfr->lpstrFindWhat, lpfr->wFindWhatLen);
 	    GetDlgItemText16(hWnd, edt2, lpfr->lpstrReplaceWith, lpfr->wReplaceWithLen);
-	    if (IsDlgButtonChecked(hWnd, chx1))
+	    if (IsDlgButtonChecked32(hWnd, chx1))
 		lpfr->Flags |= FR_WHOLEWORD; 
 		else lpfr->Flags &= ~FR_WHOLEWORD;
-	    if (IsDlgButtonChecked(hWnd, chx2))
+	    if (IsDlgButtonChecked32(hWnd, chx2))
 		lpfr->Flags |= FR_MATCHCASE; 
 		else lpfr->Flags &= ~FR_MATCHCASE;
             lpfr->Flags &= ~(FR_FINDNEXT | FR_REPLACE | FR_DIALOGTERM);
@@ -1035,7 +1035,7 @@
     {
     case WM_INITDIALOG:
       dprintf_commdlg(stddeb,"PrintDlgProc // WM_INITDIALOG lParam=%08lX\n", lParam);
-      ShowWindow(hWnd, SW_SHOWNORMAL);
+      ShowWindow16(hWnd, SW_SHOWNORMAL);
       return (TRUE);
     case WM_COMMAND:
       switch (wParam)
@@ -1062,7 +1062,7 @@
     {
     case WM_INITDIALOG:
       dprintf_commdlg(stddeb,"PrintSetupDlgProc // WM_INITDIALOG lParam=%08lX\n", lParam);
-      ShowWindow(hWnd, SW_SHOWNORMAL);
+      ShowWindow16(hWnd, SW_SHOWNORMAL);
       return (TRUE);
     case WM_COMMAND:
       switch (wParam) {
@@ -1339,7 +1339,7 @@
  int dx,dy,x,y;
 
  ClientToScreen16(hDlg,&point);
- hwnd=GetDlgItem(hDlg,dlgitem);
+ hwnd=GetDlgItem32(hDlg,dlgitem);
  GetWindowRect16(hwnd,&rect);
  if (PtInRect16(&rect,point))
  {
@@ -1371,7 +1371,7 @@
  int dx,dy,x,y;
 
  ClientToScreen16(hDlg,&point);
- hwnd=GetDlgItem(hDlg,dlgitem);
+ hwnd=GetDlgItem32(hDlg,dlgitem);
  GetWindowRect16(hwnd,&rect);
  if (PtInRect16(&rect,point))
  {
@@ -1406,13 +1406,13 @@
  */
 static int CC_MouseCheckColorGraph(HWND hDlg,int dlgitem,int *hori,int *vert,LPARAM lParam)
 {
- HWND hwnd;
+ HWND32 hwnd;
  POINT16 point = MAKEPOINT16(lParam);
  RECT16 rect;
  long x,y;
 
  ClientToScreen16(hDlg,&point);
- hwnd=GetDlgItem(hDlg,dlgitem);
+ hwnd=GetDlgItem32(hDlg,dlgitem);
  GetWindowRect16(hwnd,&rect);
  if (PtInRect16(&rect,point))
  {
@@ -1443,7 +1443,7 @@
  RECT16 rect;
 
  ClientToScreen16(hDlg,&point);
- hwnd=GetDlgItem(hDlg,0x2c5);
+ hwnd=GetDlgItem32(hDlg,0x2c5);
  GetWindowRect16(hwnd,&rect);
  if (PtInRect16(&rect,point))
  {
@@ -1502,8 +1502,8 @@
  RECT16 rect;
  HDC32  hdc;
  HBRUSH32 hBrush;
- HWND hwnd=GetDlgItem(hDlg,0x2c5);
- if (IsWindowVisible(GetDlgItem(hDlg,0x2c6)))   /* if full size */
+ HWND32 hwnd=GetDlgItem32(hDlg,0x2c5);
+ if (IsWindowVisible32(GetDlgItem32(hDlg,0x2c6)))   /* if full size */
  {
   hdc=GetDC32(hwnd);
   GetClientRect16 (hwnd, &rect) ;
@@ -1537,10 +1537,10 @@
  int height;
  int oben;
  RECT16 rect;
- HWND hwnd=GetDlgItem(hDlg,0x2be);
+ HWND hwnd=GetDlgItem32(hDlg,0x2be);
  struct CCPRIVATE *lpp=(struct CCPRIVATE *)GetWindowLong32A(hDlg, DWL_USER); 
 
- if (IsWindowVisible(GetDlgItem(hDlg,0x2c6)))   /* if full size */
+ if (IsWindowVisible32(GetDlgItem32(hDlg,0x2c6)))   /* if full size */
  {
    GetClientRect16(hwnd,&rect);
    height=rect.bottom;
@@ -1577,13 +1577,13 @@
 {
  HDC32 hDC;
  int w=GetDialogBaseUnits();
- HWND hwnd=GetDlgItem(hDlg,0x2c6);
+ HWND hwnd=GetDlgItem32(hDlg,0x2c6);
  struct CCPRIVATE * lpp=(struct CCPRIVATE *)GetWindowLong32A(hDlg, DWL_USER); 
  RECT16 rect;
  POINT16 point;
  HPEN32 hPen;
 
- if (IsWindowVisible(GetDlgItem(hDlg,0x2c6)))   /* if full size */
+ if (IsWindowVisible32(GetDlgItem32(hDlg,0x2c6)))   /* if full size */
  {
    GetClientRect16(hwnd,&rect);
    hDC=GetDC32(hwnd);
@@ -1622,7 +1622,7 @@
 static void CC_PrepareColorGraph(HWND hDlg)    
 {
  int sdif,hdif,xdif,ydif,r,g,b,hue,sat;
- HWND hwnd=GetDlgItem(hDlg,0x2c6);
+ HWND32 hwnd=GetDlgItem32(hDlg,0x2c6);
  struct CCPRIVATE * lpp=(struct CCPRIVATE *)GetWindowLong32A(hDlg, DWL_USER);  
  HBRUSH32 hbrush;
  HDC32 hdc ;
@@ -1665,11 +1665,11 @@
  */
 static void CC_PaintColorGraph(HWND hDlg)
 {
- HWND hwnd=GetDlgItem(hDlg,0x2c6);
+ HWND32 hwnd=GetDlgItem32(hDlg,0x2c6);
  struct CCPRIVATE * lpp=(struct CCPRIVATE *)GetWindowLong32A(hDlg, DWL_USER); 
  HDC32  hDC;
  RECT16 rect;
- if (IsWindowVisible(hwnd))   /* if full size */
+ if (IsWindowVisible32(hwnd))   /* if full size */
  {
   if (!lpp->hdcMem)
    CC_PrepareColorGraph(hDlg);   /* should not be necessary */
@@ -1688,13 +1688,13 @@
  */
 static void CC_PaintLumBar(HWND hDlg,int hue,int sat)
 {
- HWND hwnd=GetDlgItem(hDlg,0x2be);
+ HWND32 hwnd=GetDlgItem32(hDlg,0x2be);
  RECT16 rect,client;
  int lum,ldif,ydif,r,g,b;
  HBRUSH32 hbrush;
  HDC32 hDC;
 
- if (IsWindowVisible(hwnd))
+ if (IsWindowVisible32(hwnd))
  {
   hDC=GetDC32(hwnd);
   GetClientRect16(hwnd,&client);
@@ -1729,15 +1729,15 @@
  int r=GetRValue(cr);
  int g=GetGValue(cr);
  int b=GetBValue(cr);
- if (IsWindowVisible(GetDlgItem(hDlg,0x2c6)))   /* if full size */
+ if (IsWindowVisible32(GetDlgItem32(hDlg,0x2c6)))   /* if full size */
  {
    lpp->updating=TRUE;
    sprintf(buffer,"%d",r);
-   SetWindowText32A(GetDlgItem(hDlg,0x2c2),buffer);
+   SetWindowText32A(GetDlgItem32(hDlg,0x2c2),buffer);
    sprintf(buffer,"%d",g);
-   SetWindowText32A(GetDlgItem(hDlg,0x2c3),buffer);
+   SetWindowText32A(GetDlgItem32(hDlg,0x2c3),buffer);
    sprintf(buffer,"%d",b);
-   SetWindowText32A(GetDlgItem(hDlg,0x2c4),buffer);
+   SetWindowText32A(GetDlgItem32(hDlg,0x2c4),buffer);
    lpp->updating=FALSE;
  }
 }
@@ -1750,15 +1750,15 @@
  char buffer[10];
  struct CCPRIVATE * lpp=(struct CCPRIVATE *)GetWindowLong32A(hDlg, DWL_USER); 
  lpp->updating=TRUE;
- if (IsWindowVisible(GetDlgItem(hDlg,0x2c6)))   /* if full size */
+ if (IsWindowVisible32(GetDlgItem32(hDlg,0x2c6)))   /* if full size */
  {
    lpp->updating=TRUE;
    sprintf(buffer,"%d",h);
-   SetWindowText32A(GetDlgItem(hDlg,0x2bf),buffer);
+   SetWindowText32A(GetDlgItem32(hDlg,0x2bf),buffer);
    sprintf(buffer,"%d",s);
-   SetWindowText32A(GetDlgItem(hDlg,0x2c0),buffer);
+   SetWindowText32A(GetDlgItem32(hDlg,0x2c0),buffer);
    sprintf(buffer,"%d",l);
-   SetWindowText32A(GetDlgItem(hDlg,0x2c1),buffer);
+   SetWindowText32A(GetDlgItem32(hDlg,0x2c1),buffer);
    lpp->updating=FALSE;
  }
  CC_PaintLumBar(hDlg,h,s);
@@ -1772,22 +1772,22 @@
  int i;
  struct CCPRIVATE * lpp=(struct CCPRIVATE *)GetWindowLong32A(hDlg, DWL_USER); 
  
- EnableWindow(GetDlgItem(hDlg,0x2cf),FALSE);
+ EnableWindow32(GetDlgItem32(hDlg,0x2cf),FALSE);
  CC_PrepareColorGraph(hDlg);
  for (i=0x2bf;i<0x2c5;i++)
-   EnableWindow(GetDlgItem(hDlg,i),TRUE);
+   EnableWindow32(GetDlgItem32(hDlg,i),TRUE);
  for (i=0x2d3;i<0x2d9;i++)
-   EnableWindow(GetDlgItem(hDlg,i),TRUE);
- EnableWindow(GetDlgItem(hDlg,0x2c9),TRUE);
- EnableWindow(GetDlgItem(hDlg,0x2c8),TRUE);
+   EnableWindow32(GetDlgItem32(hDlg,i),TRUE);
+ EnableWindow32(GetDlgItem32(hDlg,0x2c9),TRUE);
+ EnableWindow32(GetDlgItem32(hDlg,0x2c8),TRUE);
 
  if (lprect)
-  SetWindowPos(hDlg,NULL,0,0,lprect->right-lprect->left,
+  SetWindowPos32(hDlg,NULL,0,0,lprect->right-lprect->left,
    lprect->bottom-lprect->top, SWP_NOMOVE|SWP_NOZORDER);
 
- ShowWindow(GetDlgItem(hDlg,0x2c6),SW_SHOW);
- ShowWindow(GetDlgItem(hDlg,0x2be),SW_SHOW);
- ShowWindow(GetDlgItem(hDlg,0x2c5),SW_SHOW);
+ ShowWindow32(GetDlgItem32(hDlg,0x2c6),SW_SHOW);
+ ShowWindow32(GetDlgItem32(hDlg,0x2be),SW_SHOW);
+ ShowWindow32(GetDlgItem32(hDlg,0x2c5),SW_SHOW);
 
  CC_EditSetRGB(hDlg,result);
  CC_EditSetHSL(hDlg,lpp->h,lpp->s,lpp->l);
@@ -1798,7 +1798,7 @@
  */
 static void CC_PaintPredefColorArray(HWND hDlg,int rows,int cols)
 {
- HWND hwnd=GetDlgItem(hDlg,0x2d0);
+ HWND32 hwnd=GetDlgItem32(hDlg,0x2d0);
  RECT16 rect;
  HDC32  hdc;
  HBRUSH32 hBrush;
@@ -1837,7 +1837,7 @@
  */
 static void CC_PaintUserColorArray(HWND hDlg,int rows,int cols,COLORREF* lpcr)
 {
- HWND hwnd=GetDlgItem(hDlg,0x2d1);
+ HWND32 hwnd=GetDlgItem32(hDlg,0x2d1);
  RECT16 rect;
  HDC32  hdc;
  HBRUSH32 hBrush;
@@ -1910,7 +1910,7 @@
    SetWindowLong32A(hDlg, DWL_USER, (LONG)lpp); 
 
    if (!(lpp->lpcc->Flags & CC_SHOWHELP))
-      ShowWindow(GetDlgItem(hDlg,0x40e),SW_HIDE);
+      ShowWindow32(GetDlgItem32(hDlg,0x40e),SW_HIDE);
    lpp->msetrgb=RegisterWindowMessage32A( SETRGBSTRING );
 #if 0
    cpos=MAKELONG(5,7); /* init */
@@ -1930,29 +1930,29 @@
    GetWindowRect16(hDlg,&lpp->fullsize);
    if (lpp->lpcc->Flags & CC_FULLOPEN || lpp->lpcc->Flags & CC_PREVENTFULLOPEN)
    {
-      hwnd=GetDlgItem(hDlg,0x2cf);
-      EnableWindow(hwnd,FALSE);
+      hwnd=GetDlgItem32(hDlg,0x2cf);
+      EnableWindow32(hwnd,FALSE);
    }
    if (!(lpp->lpcc->Flags & CC_FULLOPEN) || lpp->lpcc->Flags & CC_PREVENTFULLOPEN)
    {
       rect=lpp->fullsize;
       res=rect.bottom-rect.top;
-      hwnd=GetDlgItem(hDlg,0x2c6); /* cut at left border */
+      hwnd=GetDlgItem32(hDlg,0x2c6); /* cut at left border */
       point.x=point.y=0;
       ClientToScreen16(hwnd,&point);
       ScreenToClient16(hDlg,&point);
       GetClientRect16(hDlg,&rect);
       point.x+=GetSystemMetrics(SM_CXDLGFRAME);
-      SetWindowPos(hDlg,NULL,0,0,point.x,res,SWP_NOMOVE|SWP_NOZORDER);
+      SetWindowPos32(hDlg,NULL,0,0,point.x,res,SWP_NOMOVE|SWP_NOZORDER);
 
-      ShowWindow(GetDlgItem(hDlg,0x2c6),SW_HIDE);
-      ShowWindow(GetDlgItem(hDlg,0x2c5),SW_HIDE);
+      ShowWindow32(GetDlgItem32(hDlg,0x2c6),SW_HIDE);
+      ShowWindow32(GetDlgItem32(hDlg,0x2c5),SW_HIDE);
    }
    else
       CC_SwitchToFullSize(hDlg,lpp->lpcc->rgbResult,NULL);
    res=TRUE;
    for (i=0x2bf;i<0x2c5;i++)
-     SendMessage16(GetDlgItem(hDlg,i),EM_LIMITTEXT16,3,0);      /* max 3 digits:  xyz  */
+     SendMessage16(GetDlgItem32(hDlg,i),EM_LIMITTEXT16,3,0);      /* max 3 digits:  xyz  */
    if (CC_HookCallChk(lpp->lpcc))
       res=CallWindowProc16(lpp->lpcc->lpfnHook,hDlg,WM_INITDIALOG,wParam,lParam);
    return res;
@@ -2031,7 +2031,7 @@
           case 0x2cf:
                CC_SwitchToFullSize(hDlg,lpp->lpcc->rgbResult,&lpp->fullsize);
 	       InvalidateRect32( hDlg, NULL, TRUE );
-	       SetFocus32(GetDlgItem(hDlg,0x2bf));
+	       SetFocus32(GetDlgItem32(hDlg,0x2bf));
 	       break;
 
           case 0x2c8:    /* add colors ... column by column */
@@ -2102,11 +2102,11 @@
     CC_PaintSelectedColor(hDlg,lpp->lpcc->rgbResult);
 
     /* special necessary for Wine */
-    ValidateRect32(GetDlgItem(hDlg,0x2d0),NULL);
-    ValidateRect32(GetDlgItem(hDlg,0x2d1),NULL);
-    ValidateRect32(GetDlgItem(hDlg,0x2c6),NULL);
-    ValidateRect32(GetDlgItem(hDlg,0x2be),NULL);
-    ValidateRect32(GetDlgItem(hDlg,0x2c5),NULL);
+    ValidateRect32(GetDlgItem32(hDlg,0x2d0),NULL);
+    ValidateRect32(GetDlgItem32(hDlg,0x2d1),NULL);
+    ValidateRect32(GetDlgItem32(hDlg,0x2c6),NULL);
+    ValidateRect32(GetDlgItem32(hDlg,0x2be),NULL);
+    ValidateRect32(GetDlgItem32(hDlg,0x2c5),NULL);
     /* hope we can remove it later -->FIXME */
  return 0;
 }
@@ -2480,9 +2480,9 @@
     hBitmapTT = LoadBitmap16(0, MAKEINTRESOURCE(OBM_TRTYPE));
 			 
   if (!(lpcf->Flags & CF_SHOWHELP) || !IsWindow(lpcf->hwndOwner))
-    ShowWindow(GetDlgItem(hDlg,pshHelp),SW_HIDE);
+    ShowWindow32(GetDlgItem32(hDlg,pshHelp),SW_HIDE);
   if (!(lpcf->Flags & CF_APPLY))
-    ShowWindow(GetDlgItem(hDlg,psh3),SW_HIDE);
+    ShowWindow32(GetDlgItem32(hDlg,psh3),SW_HIDE);
   if (lpcf->Flags & CF_EFFECTS)
   {
     for (res=1,i=0;res && i<TEXT_COLORS;i++)
@@ -2500,16 +2500,17 @@
   }
   else
   {
-    ShowWindow(GetDlgItem(hDlg,cmb4),SW_HIDE);
-    ShowWindow(GetDlgItem(hDlg,chx1),SW_HIDE);
-    ShowWindow(GetDlgItem(hDlg,chx2),SW_HIDE);
-    ShowWindow(GetDlgItem(hDlg,grp1),SW_HIDE);
-    ShowWindow(GetDlgItem(hDlg,stc4),SW_HIDE);
+    ShowWindow32(GetDlgItem32(hDlg,cmb4),SW_HIDE);
+    ShowWindow32(GetDlgItem32(hDlg,chx1),SW_HIDE);
+    ShowWindow32(GetDlgItem32(hDlg,chx2),SW_HIDE);
+    ShowWindow32(GetDlgItem32(hDlg,grp1),SW_HIDE);
+    ShowWindow32(GetDlgItem32(hDlg,stc4),SW_HIDE);
   }
   hdc= (lpcf->Flags & CF_PRINTERFONTS && lpcf->hDC) ? lpcf->hDC : GetDC32(hDlg);
   if (hdc)
   {
-    if (!EnumFontFamilies16(hdc, NULL,FontFamilyEnumProc,(LPARAM)GetDlgItem(hDlg,cmb1)))
+    if (!EnumFontFamilies16(hdc, NULL,FontFamilyEnumProc,
+                            (LPARAM)GetDlgItem32(hDlg,cmb1)))
       dprintf_commdlg(stddeb,"WM_INITDIALOG: EnumFontFamilies returns 0\n");
     if (lpcf->Flags & CF_INITTOLOGFONTSTRUCT)
     {
@@ -2518,7 +2519,8 @@
       if (j!=CB_ERR)
       {
         SendDlgItemMessage16(hDlg,cmb1,CB_SETCURSEL16,j,0);
-	SendMessage16(hDlg,WM_COMMAND,cmb1,MAKELONG(GetDlgItem(hDlg,cmb1),CBN_SELCHANGE));
+	SendMessage16(hDlg,WM_COMMAND,cmb1,
+                      MAKELONG(GetDlgItem32(hDlg,cmb1),CBN_SELCHANGE));
         init=1;
         /* look for fitting font style in combobox2 */
         l=MAKELONG(lpxx->lfWeight > FW_MEDIUM ? FW_BOLD:FW_NORMAL,lpxx->lfItalic !=0);
@@ -2539,7 +2541,8 @@
       if (!init)
       {
         SendDlgItemMessage16(hDlg,cmb1,CB_SETCURSEL16,0,0);
-	SendMessage16(hDlg,WM_COMMAND,cmb1,MAKELONG(GetDlgItem(hDlg,cmb1),CBN_SELCHANGE));      
+	SendMessage16(hDlg,WM_COMMAND,cmb1,
+                      MAKELONG(GetDlgItem32(hDlg,cmb1),CBN_SELCHANGE));      
       }
     }
     if (lpcf->Flags & CF_USESTYLE && lpcf->lpszStyle)
@@ -2548,7 +2551,8 @@
       if (j!=CB_ERR)
       {
         j=SendDlgItemMessage16(hDlg,cmb2,CB_SETCURSEL16,j,0);
-        SendMessage16(hDlg,WM_COMMAND,cmb2,MAKELONG(GetDlgItem(hDlg,cmb2),CBN_SELCHANGE));
+        SendMessage16(hDlg,WM_COMMAND,cmb2,
+                      MAKELONG(GetDlgItem32(hDlg,cmb2),CBN_SELCHANGE));
       }
     }
   }
@@ -2686,7 +2690,7 @@
   LPCHOOSEFONT lpcf=(LPCHOOSEFONT)GetWindowLong32A(hDlg, DWL_USER); 
 
   if (lpcf->Flags & CF_EFFECTS)
-   if (HIWORD(lParam)==CTLCOLOR_STATIC && GetDlgCtrlID(LOWORD(lParam))==stc6)
+   if (HIWORD(lParam)==CTLCOLOR_STATIC && GetDlgCtrlID32(LOWORD(lParam))==stc6)
    {
      SetTextColor(wParam,lpcf->rgbColors);
      return GetStockObject32(WHITE_BRUSH);
@@ -2725,7 +2729,7 @@
                                              (LPARAM)SEGPTR_GET(str));
 	                dprintf_commdlg(stddeb,"WM_COMMAND/cmb1 =>%s\n",str);
        		        EnumFontFamilies16(hdc,str,FontStyleEnumProc,
-		             MAKELONG(GetDlgItem(hDlg,cmb2),GetDlgItem(hDlg,cmb3)));
+		             MAKELONG(GetDlgItem32(hDlg,cmb2),GetDlgItem32(hDlg,cmb3)));
 		        SetCursor(hcursor);     
                         SEGPTR_FREE(str);
 		      }
@@ -2778,8 +2782,8 @@
 		      lpxx->lfHeight=-LOWORD(SendDlgItemMessage16(hDlg,cmb3,CB_GETITEMDATA16,i,0));
 		    else
 		      lpxx->lfHeight=0;
-		    lpxx->lfStrikeOut=IsDlgButtonChecked(hDlg,chx1);
-		    lpxx->lfUnderline=IsDlgButtonChecked(hDlg,chx2);
+		    lpxx->lfStrikeOut=IsDlgButtonChecked32(hDlg,chx1);
+		    lpxx->lfUnderline=IsDlgButtonChecked32(hDlg,chx2);
 		    lpxx->lfWidth=lpxx->lfOrientation=lpxx->lfEscapement=0;
 		    lpxx->lfOutPrecision=OUT_DEFAULT_PRECIS;
 		    lpxx->lfClipPrecision=CLIP_DEFAULT_PRECIS;
@@ -2797,7 +2801,7 @@
 		  if (i!=CB_ERR)
 		  {
 		   lpcf->rgbColors=textcolors[i];
-		   InvalidateRect32( GetDlgItem(hDlg,stc6), NULL, 0 );
+		   InvalidateRect32( GetDlgItem32(hDlg,stc6), NULL, 0 );
 		  }
 		  break;
 	
diff --git a/misc/crtdll.c b/misc/crtdll.c
index 3d29bca..5909a53 100644
--- a/misc/crtdll.c
+++ b/misc/crtdll.c
@@ -848,3 +848,23 @@
 	return NULL;
 }
 
+/*********************************************************************
+ *                  _setmode           (CRTDLL.265)
+ * FIXME: dunno what this is.
+ */
+DWORD
+CRTDLL__setmode(LPVOID x,INT32 y) {
+	/* FIXME */
+	fprintf(stdnimp,"CRTDLL._setmode(%p,%d), STUB.\n",x,y);
+	return 0;
+}
+
+/*********************************************************************
+ *                  atexit           (CRTDLL.345)
+ */
+INT32
+CRTDLL_atexit(LPVOID x) {
+	/* FIXME */
+	fprintf(stdnimp,"CRTDLL.atexit(%p), STUB.\n",x);
+	return 0; /* successful */
+}
diff --git a/misc/escape.c b/misc/escape.c
index ec06156..a42827c 100644
--- a/misc/escape.c
+++ b/misc/escape.c
@@ -4,21 +4,25 @@
  * Copyright 1994  Bob Amstadt
  */
 
-#include <stdlib.h>
+#define NO_TRANSITION_TYPES
 #include <stdio.h>
 #include "windows.h"
 #include "gdi.h"
+#include "dc.h"
 
-INT Escape( HDC16 hdc, INT nEscape, INT cbInput,
-            SEGPTR lpszInData, SEGPTR lpvOutData )
+INT16 Escape16( HDC16 hdc, INT16 nEscape, INT16 cbInput,
+                SEGPTR lpszInData, SEGPTR lpvOutData )
 {
-    DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
-    if (!dc) 
-    {
-	dc = (DC *)GDI_GetObjPtr(hdc, METAFILE_DC_MAGIC);
-	if (!dc) return 0;
-    }
-
-    if (!dc->funcs->pEscape) return 0;
+    DC * dc = DC_GetDCPtr( hdc );
+    if (!dc || !dc->funcs->pEscape) return 0;
     return dc->funcs->pEscape( dc, nEscape, cbInput, lpszInData, lpvOutData );
 }
+
+INT32 Escape32( HDC32 hdc, INT32 nEscape, INT32 cbInput,
+                LPVOID lpszInData, LPVOID lpvOutData )
+{
+    DC * dc = DC_GetDCPtr( hdc );
+    if (!dc || !dc->funcs->pEscape) return 0;
+    return dc->funcs->pEscape( dc, nEscape, cbInput,
+                               (SEGPTR)lpszInData, (SEGPTR)lpvOutData );
+}
diff --git a/misc/fontengine.c b/misc/fontengine.c
new file mode 100644
index 0000000..d999807
--- /dev/null
+++ b/misc/fontengine.c
@@ -0,0 +1,68 @@
+/*
+ * True Type font engine support
+ *
+ * Copyright 1996 John Harvey
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include "windows.h"
+
+/* GDI 300 */
+WORD 
+EngineEnumerateFont(LPSTR fontname, FARPROC16 proc, DWORD data )
+{
+    printf("In engineEnumerateFont for %s\n",fontname);
+    return 0;
+}
+#ifdef NOTDEF
+/* GDI 301 */
+WORD 
+EngineDeleteFont(LPFONTINFO16 lpFontInfo)
+{
+    return 0
+}
+#endif
+/* GDI 302 */
+WORD
+EngineRealizeFont(LPLOGFONT16 lplogFont, LPTEXTXFORM16 lptextxform, LPFONTINFO16 lpfontInfo)
+{
+    printf("In EngineRealizeFont\n");
+    
+    return 0;
+}
+#ifdef NOTDEF
+/* GDI 303 */
+WORD 
+EngineGetCharWidth(LPFONTINFO16 lpFontInfo, BYTE, BYTE, LPINT16)
+{
+    return 0;
+}
+
+/* GDI 304 */
+WORD 
+EngineSetFontContext(LPFONTINFO lpFontInfo, WORD data)
+{
+}
+/* GDI 305 */
+WORD 
+EngineGetGlyphBMP(WORD word, LPFONTINFO lpFontInfo, WORD, WORD, LPSTR string, DWORD dword, LPBITMAPMETRICS16 metrics)
+{
+    return 0;
+}
+
+/* GDI 306 */
+DWORD 
+EngineMakeFontDir(HDC16 hdc, LPFONTDIR fontdir, LPCSTR string)
+{
+    return 0;
+    
+}
+
+/* GDI 314 */
+
+WORD 
+EngineExtTextOut()
+{
+}
+
+#endif
diff --git a/misc/main.c b/misc/main.c
index d1a4dcc3..14608d0 100644
--- a/misc/main.c
+++ b/misc/main.c
@@ -176,7 +176,7 @@
  *           MAIN_Usage
  */
 #ifndef WINELIB32
-static void MAIN_Usage( char *name )
+void MAIN_Usage( char *name )
 {
     fprintf( stderr, USAGE, name );
     exit(1);
@@ -642,7 +642,9 @@
     MSG_WineStartTicks = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
 
     XrmInitialize();
-    
+
+    putenv("XKB_DISABLE="); /* Disable XKB extension if present. */
+
     MAIN_ParseOptions( argc, argv );
 
     if (Options.desktopGeometry && Options.managed)
diff --git a/misc/ntdll.c b/misc/ntdll.c
index 7f43d32..6f18e26 100644
--- a/misc/ntdll.c
+++ b/misc/ntdll.c
@@ -7,16 +7,15 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <unistd.h>
 #include <time.h>
 #include <ctype.h>
 #include <math.h>
 #include "win.h"
 #include "windows.h"
+#include "heap.h"
 #include "stddebug.h"
 #include "debug.h"
 #include "module.h"
-#include "xmalloc.h"
 #include "heap.h"
 
 /**************************************************************************
@@ -74,12 +73,55 @@
 DWORD
 RtlCopySid(DWORD len,LPSID to,LPSID from) {
 	if (len<(from->SubAuthorityCount*4+8))
-		return 0xC0000023;
+		return STATUS_BUFFER_TOO_SMALL;
 	memmove(to,from,from->SubAuthorityCount*4+8);
-	return 0;
+	return STATUS_SUCCESS;
 }
 
 /**************************************************************************
+ *                 RtlAnsiStringToUnicodeString		[NTDLL]
+ */
+DWORD /* NTSTATUS */
+RtlAnsiStringToUnicodeString(LPUNICODE_STRING uni,LPANSI_STRING ansi,BOOL32 doalloc) {
+	DWORD	unilen = (ansi->Length+1)*sizeof(WCHAR);
+
+	if (unilen>0xFFFF)
+		return STATUS_INVALID_PARAMETER_2;
+	uni->Length = unilen;
+	if (doalloc) {
+		uni->MaximumLength = unilen;
+		uni->Buffer = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,unilen);
+		if (!uni->Buffer)
+			return STATUS_NO_MEMORY;
+	}
+	if (unilen>uni->MaximumLength)
+		return STATUS_BUFFER_OVERFLOW;
+	lstrcpynAtoW(uni->Buffer,ansi->Buffer,unilen/2);
+	return STATUS_SUCCESS;
+}
+
+/**************************************************************************
+ *                 RtlOemStringToUnicodeString		[NTDLL]
+ */
+DWORD /* NTSTATUS */
+RtlOemStringToUnicodeString(LPUNICODE_STRING uni,LPSTRING ansi,BOOL32 doalloc) {
+	DWORD	unilen = (ansi->Length+1)*sizeof(WCHAR);
+
+	if (unilen>0xFFFF)
+		return STATUS_INVALID_PARAMETER_2;
+	uni->Length = unilen;
+	if (doalloc) {
+		uni->MaximumLength = unilen;
+		uni->Buffer = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,unilen);
+		if (!uni->Buffer)
+			return STATUS_NO_MEMORY;
+	}
+	if (unilen>uni->MaximumLength)
+		return STATUS_BUFFER_OVERFLOW;
+	lstrcpynAtoW(uni->Buffer,ansi->Buffer,unilen/2);
+	return STATUS_SUCCESS;
+}
+/**************************************************************************
  *                 RtlOemToUnicodeN			[NTDLL]
  */
 DWORD /* NTSTATUS */
@@ -90,7 +132,7 @@
 	len = oemlen;
 	if (unilen/2 < len)
 		len = unilen/2;
-	x=(LPWSTR)xmalloc((len+1)*sizeof(WCHAR));
+	x=(LPWSTR)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,(len+1)*sizeof(WCHAR));
 	lstrcpynAtoW(x,oemstr,len+1);
 	memcpy(unistr,x,len*2);
 	if (reslen) *reslen = len*2;
@@ -98,6 +140,44 @@
 }
 
 /**************************************************************************
+ *                 RtlInitString			[NTDLL]
+ */
+VOID
+RtlInitAnsiString(LPANSI_STRING target,LPCSTR source) {
+	target->Length = target->MaximumLength = 0;
+	target->Buffer = (LPSTR)source;
+	if (!source)
+		return;
+	target->Length = lstrlen32A(target->Buffer);
+	target->MaximumLength = target->Length+1;
+}
+/**************************************************************************
+ *                 RtlInitString			[NTDLL]
+ */
+VOID
+RtlInitString(LPSTRING target,LPCSTR source) {
+	target->Length = target->MaximumLength = 0;
+	target->Buffer = (LPSTR)source;
+	if (!source)
+		return;
+	target->Length = lstrlen32A(target->Buffer);
+	target->MaximumLength = target->Length+1;
+}
+
+/**************************************************************************
+ *                 RtlInitUnicodeString			[NTDLL]
+ */
+VOID
+RtlInitUnicodeString(LPUNICODE_STRING target,LPCWSTR source) {
+	target->Length = target->MaximumLength = 0;
+	target->Buffer = (LPWSTR)source;
+	if (!source)
+		return;
+	target->Length = lstrlen32W(target->Buffer)*2;
+	target->MaximumLength = target->Length+2;
+}
+
+/**************************************************************************
  *                 RtlUnicodeToOemN			[NTDLL]
  */
 DWORD /* NTSTATUS */
@@ -108,7 +188,7 @@
 	len = oemlen;
 	if (unilen/2 < len)
 		len = unilen/2;
-	x=(LPSTR)xmalloc(len+1);
+	x=(LPSTR)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,len+1);
 	lstrcpynWtoA(x,unistr,len+1);
 	memcpy(oemstr,x,len);
 	if (reslen) *reslen = len;
@@ -122,10 +202,71 @@
 RtlUnicodeStringToOemString(LPUNICODE_STRING uni,LPANSI_STRING oem,BOOL32 alloc)
 {
 	if (alloc) {
-		oem->Buffer = (LPSTR)xmalloc(uni->Length/2)+1;
+		oem->Buffer = (LPSTR)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,uni->Length/2)+1;
 		oem->MaximumLength = uni->Length/2+1;
 	}
 	oem->Length = uni->Length/2;
 	lstrcpynWtoA(oem->Buffer,uni->Buffer,uni->Length/2+1);
 	return 0;
 }
+
+/**************************************************************************
+ *                 RtlNtStatusToDosErro			[NTDLL]
+ */
+DWORD
+RtlNtStatusToDosError(DWORD error) {
+	/* FIXME: map STATUS_ to ERROR_ */
+	return error;
+}
+
+/**************************************************************************
+ *                 RtlGetNtProductType			[NTDLL]
+ */
+DWORD
+RtlGetNtProductType(LPVOID x) {
+	/* FIXME : find documentation for this one */
+	return 0;
+}
+
+/**************************************************************************
+ *                 RtlUpcaseUnicodeString		[NTDLL]
+ */
+DWORD
+RtlUpcaseUnicodeString(LPUNICODE_STRING dest,LPUNICODE_STRING src,BOOL32 doalloc) {
+	LPWSTR	s,t;
+	DWORD	i,len;
+
+	len = src->Length;
+	if (doalloc) {
+		dest->MaximumLength = len; 
+		dest->Buffer = (LPWSTR)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,len);
+		if (!dest->Buffer)
+			return STATUS_NO_MEMORY;
+
+	}
+	if (dest->MaximumLength < len)
+		return STATUS_BUFFER_OVERFLOW;
+	s=dest->Buffer;t=src->Buffer;
+	for (i=0;i<len;i++) {
+		s[i]=toupper(t[i]);
+		s++;
+		t++;
+	}
+	return STATUS_SUCCESS;
+}
+
+/**************************************************************************
+ *                 RtlxOemStringToUnicodeSize		[NTDLL]
+ */
+UINT32
+RtlxOemStringToUnicodeSize(LPSTRING str) {
+	return str->Length*2+2;
+}
+
+/**************************************************************************
+ *                 RtlxAnsiStringToUnicodeSize		[NTDLL]
+ */
+UINT32
+RtlxAnsiStringToUnicodeSize(LPANSI_STRING str) {
+	return str->Length*2+2;
+}
diff --git a/misc/registry.c b/misc/registry.c
index 48b577f..222d994 100644
--- a/misc/registry.c
+++ b/misc/registry.c
@@ -3015,3 +3015,10 @@
 		free(lpszClassW);
 	return ret;
 }
+/* RegConnectRegistryA		[ADVAPI32.127] */
+DWORD RegConnectRegistry32A(LPCSTR machine,HKEY hkey,LPHKEY reskey) {
+	fprintf(stderr,"RegConnectRegistry32A(%s,%08lx,%p), STUB.\n",
+		machine,hkey,reskey
+	);
+	return ERROR_FILE_NOT_FOUND; /* FIXME */
+}
diff --git a/misc/shell.c b/misc/shell.c
index 506b13e..ad492c0 100644
--- a/misc/shell.c
+++ b/misc/shell.c
@@ -370,7 +370,7 @@
                 GetWindowText32A( hWnd, Template, sizeof(Template) );
                 sprintf( AppTitle, Template, info->szApp );
                 SetWindowText32A( hWnd, AppTitle );
-                SetWindowText32A( GetDlgItem(hWnd,100), info->szOtherStuff );
+                SetWindowText32A( GetDlgItem32(hWnd,100), info->szOtherStuff );
             }
         }
         return 1;
diff --git a/misc/ver.c b/misc/ver.c
index 7eedf6d..2779a00 100644
--- a/misc/ver.c
+++ b/misc/ver.c
@@ -3,7 +3,6 @@
  * 
  * Copyright 1996 Marcus Meissner
  */
-
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
@@ -40,6 +39,7 @@
 		LZSeek32(lzfd,mzh.ne_offset,SEEK_SET);
 		return 1;
 	}
+	fprintf(stderr,"misc/ver.c:read_ne_header:can't handle PE files yet.\n");
 	/* must handle PE files too. Later. */
 	return 0;
 }
@@ -442,37 +442,222 @@
 DWORD
 VerInstallFile16(
 	UINT16 flags,LPCSTR srcfilename,LPCSTR destfilename,LPCSTR srcdir,
-	LPCSTR destdir,LPSTR tmpfile,UINT16 *tmpfilelen
-) {
-	dprintf_ver(stddeb,"VerInstallFile(%x,%s,%s,%s,%s,%p,%d)\n",
-		flags,srcfilename,destfilename,srcdir,destdir,tmpfile,*tmpfilelen
-	);
-
-	/* FIXME: Implementation still missing .... */
-
-	return VIF_SRCOLD;
-}
-
-/* VerFindFileA					[VERSION.5] */
-DWORD
-VerInstallFile32A(
-	UINT32 flags,LPCSTR srcfilename,LPCSTR destfilename,LPCSTR srcdir,
-	LPCSTR destdir,LPSTR tmpfile,UINT32 *tmpfilelen )
+ 	LPCSTR destdir,LPCSTR curdir,LPSTR tmpfile,UINT16 *tmpfilelen )
 {
-    UINT16 filelen;
-    DWORD ret= VerInstallFile16(flags,srcfilename,destfilename,srcdir,
-                                destdir,tmpfile,&filelen);
+    UINT32	filelen;
+    DWORD ret= VerInstallFile32A(flags,srcfilename,destfilename,srcdir,
+                                 destdir,curdir,tmpfile,&filelen);
+
     *tmpfilelen = filelen;
     return ret;
 }
 
-/* VerFindFileW					[VERSION.6] */
+/* VerInstallFileA				[VERSION.7] */
+static LPBYTE
+_fetch_versioninfo(LPSTR fn) {
+    DWORD	alloclen;
+    LPBYTE	buf;
+    DWORD	ret;
+
+    alloclen = 1000;
+    buf= xmalloc(alloclen);
+    while (1) {
+    	ret = GetFileVersionInfo32A(fn,0,alloclen,buf);
+	if (!ret) {
+	    free(buf);
+	    return 0;
+	}
+	if (alloclen<*(WORD*)buf) {
+	    free(buf);
+	    alloclen = *(WORD*)buf;
+	    buf = xmalloc(alloclen);
+	} else
+	    return buf;
+    }
+}
+
+static DWORD
+_error2vif(DWORD error) {
+    switch (error) {
+    case ERROR_ACCESS_DENIED:
+    	return VIF_ACCESSVIOLATION;
+    case ERROR_SHARING_VIOLATION:
+    	return VIF_SHARINGVIOLATION;
+    default:
+    	return 0;
+    }
+}
+
+DWORD
+VerInstallFile32A(
+	UINT32 flags,LPCSTR srcfilename,LPCSTR destfilename,LPCSTR srcdir,
+ 	LPCSTR destdir,LPCSTR curdir,LPSTR tmpfile,UINT32 *tmpfilelen )
+{
+    char	destfn[260],tmpfn[260],srcfn[260];
+    HFILE32	hfsrc,hfdst;
+    DWORD	attr,ret,xret,tmplast;
+    LPBYTE	buf1,buf2;
+    OFSTRUCT	ofs;
+
+    fprintf(stddeb,"VerInstallFile(%x,%s,%s,%s,%s,%s,%p,%d)\n",
+	    flags,srcfilename,destfilename,srcdir,destdir,curdir,tmpfile,*tmpfilelen
+    );
+    xret = 0;
+    sprintf(srcfn,"%s\\%s",srcdir,srcfilename);
+    sprintf(destfn,"%s\\%s",destdir,destfilename);
+    hfsrc=LZOpenFile32A(srcfn,&ofs,OF_READ);
+    if (hfsrc==HFILE_ERROR32)
+    	return VIF_CANNOTREADSRC;
+    sprintf(tmpfn,"%s\\%s",destdir,destfilename);
+    tmplast=strlen(destdir)+1;
+    attr = GetFileAttributes32A(tmpfn);
+    if (attr!=-1) {
+	if (attr & FILE_ATTRIBUTE_READONLY) {
+	    LZClose32(hfsrc);
+	    return VIF_WRITEPROT;
+	}
+	/* FIXME: check if file currently in use and return VIF_FILEINUSE */
+    }
+    attr = -1;
+    if (flags & VIFF_FORCEINSTALL) {
+    	if (tmpfile[0]) {
+	    sprintf(tmpfn,"%s\\%s",destdir,tmpfile);
+	    tmplast = strlen(destdir)+1;
+	    attr = GetFileAttributes32A(tmpfn);
+	    /* if it exists, it has been copied by the call before.
+	     * we jump over the copy part... 
+	     */
+	}
+    }
+    if (attr == -1) {
+    	char	*s;
+
+	GetTempFileName32A(destdir,"ver",0,tmpfn); /* should not fail ... */
+	s=strrchr(tmpfn,'\\');
+	if (s)
+	    tmplast = s-tmpfn;
+	else
+	    tmplast = 0;
+	hfdst = OpenFile32(tmpfn,&ofs,OF_CREATE);
+	if (hfdst == HFILE_ERROR32) {
+	    LZClose32(hfsrc);
+	    return VIF_CANNOTCREATE; /* | translated dos error */
+	}
+	ret = LZCopy32(hfsrc,hfdst);
+	_lclose32(hfdst);
+	if (ret<0) {
+	    /* translate LZ errors into VIF_xxx */
+	    switch (ret) {
+	    case LZERROR_BADINHANDLE:
+	    case LZERROR_READ:
+	    case LZERROR_BADVALUE:
+	    case LZERROR_UNKNOWNALG:
+		ret = VIF_CANNOTREADSRC;
+		break;
+	    case LZERROR_BADOUTHANDLE:
+	    case LZERROR_WRITE:
+		ret = VIF_OUTOFMEMORY; /* FIXME: correct? */
+		break;
+	    case LZERROR_GLOBALLOC:
+	    case LZERROR_GLOBLOCK:
+		ret = VIF_OUTOFSPACE;
+		break;
+	    default: /* unknown error, should not happen */
+		ret = 0;
+		break;
+	    }
+	    if (ret) {
+		LZClose32(hfsrc);
+		return ret;
+	    }
+	}
+    }
+    xret = 0;
+    if (!(flags & VIFF_FORCEINSTALL)) {
+    	buf1 = _fetch_versioninfo(destfn);
+	if (buf1) {
+	    buf2 = _fetch_versioninfo(tmpfn);
+	    if (!buf2) {
+	    	char	*tbuf1,*tbuf2;
+		VS_FIXEDFILEINFO *destvffi,*tmpvffi;
+		UINT32	len1,len2;
+
+		destvffi= (VS_FIXEDFILEINFO*)(buf1+0x14);
+		tmpvffi = (VS_FIXEDFILEINFO*)(buf2+0x14);
+		len1=len2=40;
+
+		/* compare file versions */
+		if ((destvffi->dwFileVersionMS > tmpvffi->dwFileVersionMS)||
+		    ((destvffi->dwFileVersionMS==tmpvffi->dwFileVersionMS)&&
+		     (destvffi->dwFileVersionLS > tmpvffi->dwFileVersionLS)
+		    )
+		)
+		    xret |= VIF_MISMATCH|VIF_SRCOLD;
+		/* compare filetypes and filesubtypes */
+		if ((destvffi->dwFileType!=tmpvffi->dwFileType) ||
+		    (destvffi->dwFileSubtype!=tmpvffi->dwFileSubtype)
+		)
+		    xret |= VIF_MISMATCH|VIF_DIFFTYPE;
+		if (VerQueryValue32A(buf1,"\\VarFileInfo\\Translation",(LPVOID*)&tbuf1,&len1) &&
+		    VerQueryValue32A(buf2,"\\VarFileInfo\\Translation",(LPVOID*)&tbuf2,&len2)
+		) {
+		    /* irgendwas mit tbuf1 und tbuf2 machen 
+		     * generiert DIFFLANG|MISMATCH
+		     */
+		}
+		free(buf2);
+	    } else
+		xret=VIF_MISMATCH|VIF_SRCOLD;
+	    free(buf1);
+	}
+    }
+    if (xret) {
+	if (*tmpfilelen<strlen(tmpfn+tmplast)) {
+	    xret|=VIF_BUFTOSMALL;
+	    DeleteFile32A(tmpfn);
+	} else {
+	    strcpy(tmpfile,tmpfn+tmplast);
+	    *tmpfilelen = strlen(tmpfn+tmplast)+1;
+	    xret|=VIF_TEMPFILE;
+	}
+    } else {
+    	if (-1!=GetFileAttributes32A(destfn))
+	    if (!DeleteFile32A(destfn)) {
+		xret|=_error2vif(GetLastError())|VIF_CANNOTDELETE;
+		DeleteFile32A(tmpfn);
+		LZClose32(hfsrc);
+		return xret;
+	    }
+	if ((!(flags & VIFF_DONTDELETEOLD))	&& 
+	    curdir				&& 
+	    *curdir				&&
+	    lstrcmpi32A(curdir,destdir)
+	) {
+	    char curfn[260];
+
+	    sprintf(curfn,"%s\\%s",curdir,destfilename);
+	    if (-1!=GetFileAttributes32A(curfn)) {
+		/* FIXME: check if in use ... if it is, VIF_CANNOTDELETECUR */
+		if (!DeleteFile32A(curfn))
+	    	    xret|=_error2vif(GetLastError())|VIF_CANNOTDELETECUR;
+	    }
+	}
+	if (!MoveFile32A(tmpfn,destfn)) {
+	    xret|=_error2vif(GetLastError())|VIF_CANNOTRENAME;
+	    DeleteFile32A(tmpfn);
+	}
+    }
+    LZClose32(hfsrc);
+    return xret;
+}
+
+/* VerInstallFileW				[VERSION.8] */
 DWORD
 VerInstallFile32W(
 	UINT32 flags,LPCWSTR srcfilename,LPCWSTR destfilename,LPCWSTR srcdir,
-	LPCWSTR destdir,LPWSTR tmpfile,UINT32 *tmpfilelen )
+	LPCWSTR destdir,LPCWSTR curdir,LPWSTR tmpfile,UINT32 *tmpfilelen )
 {
-    LPSTR wsrcf,wsrcd,wdestf,wdestd,wtmpf;
+    LPSTR wsrcf,wsrcd,wdestf,wdestd,wtmpf,wcurd;
     DWORD ret;
 
     wsrcf  = HEAP_strdupWtoA( GetProcessHeap(), 0, srcfilename );
@@ -480,18 +665,23 @@
     wdestf = HEAP_strdupWtoA( GetProcessHeap(), 0, destfilename );
     wdestd = HEAP_strdupWtoA( GetProcessHeap(), 0, destdir );
     wtmpf  = HEAP_strdupWtoA( GetProcessHeap(), 0, tmpfile );
-    ret = VerInstallFile32A(flags,wsrcf,wdestf,wsrcd,wdestd,wtmpf,tmpfilelen);
+    wcurd  = HEAP_strdupWtoA( GetProcessHeap(), 0, curdir );
+    ret = VerInstallFile32A(flags,wsrcf,wdestf,wsrcd,wdestd,wcurd,wtmpf,tmpfilelen);
+    if (!ret)
+    	lstrcpynAtoW(tmpfile,wtmpf,*tmpfilelen);
     HeapFree( GetProcessHeap(), 0, wsrcf );
     HeapFree( GetProcessHeap(), 0, wsrcd );
     HeapFree( GetProcessHeap(), 0, wdestf );
     HeapFree( GetProcessHeap(), 0, wdestd );
     HeapFree( GetProcessHeap(), 0, wtmpf );
+    if (wcurd) 
+    	HeapFree( GetProcessHeap(), 0, wcurd );
     return ret;
 }
 
 /* FIXME: This table should, of course, be language dependend */
 static const struct map_id2str {
-	UINT	langid;
+	UINT16	langid;
 	const char *langname;
 } languages[]={
 	{0x0401,"Arabisch"},
diff --git a/misc/winsock.c b/misc/winsock.c
index 5acadcd..336c3fc 100644
--- a/misc/winsock.c
+++ b/misc/winsock.c
@@ -16,6 +16,9 @@
 #include <sys/ioccom.h>
 #include <sys/sockio.h>
 #endif
+#if defined(__EMX__)
+#include <sys/so_ioctl.h>
+#endif
 #include <sys/msg.h>
 #include <sys/wait.h>
 #include <sys/socket.h>
diff --git a/msdos/dosmem.c b/msdos/dosmem.c
index 55078af..aa84593 100644
--- a/msdos/dosmem.c
+++ b/msdos/dosmem.c
@@ -127,7 +127,7 @@
      * this feels more like a hack to me than this current implementation is.
      * If you find another, better, method, just change it. -Marcus Meissner
      */
-    DOSMEM_dosmem = VirtualAlloc(NULL,0x1000000,MEM_COMMIT,PAGE_EXECUTE_READWRITE);
+    DOSMEM_dosmem = VirtualAlloc(NULL,0x100000,MEM_COMMIT,PAGE_EXECUTE_READWRITE);
     if (!DOSMEM_dosmem)
     {
         fprintf( stderr, "Could not allocate DOS memory.\n" );
diff --git a/multimedia/mmsystem.c b/multimedia/mmsystem.c
index 6cb620c..bfe0588 100644
--- a/multimedia/mmsystem.c
+++ b/multimedia/mmsystem.c
@@ -827,11 +827,10 @@
 */
 UINT mciGetDeviceID (LPCSTR lpstrName)
 {
-	char	str[128];
-	dprintf_mci(stddeb, "mciGetDeviceID(%s)\n", lpstrName);
-	if (lpstrName && !lstrcmpi32A(lpstrName, "ALL"))
-            return MCI_ALL_DEVICE_ID;
-	return 0;
+    dprintf_mci(stddeb, "mciGetDeviceID(%s)\n", lpstrName);
+    if (lpstrName && !lstrcmpi32A(lpstrName, "ALL"))
+        return MCI_ALL_DEVICE_ID;
+    return 0;
 }
 
 /**************************************************************************
diff --git a/objects/cursoricon.c b/objects/cursoricon.c
index 0ee8657..46a5405 100644
--- a/objects/cursoricon.c
+++ b/objects/cursoricon.c
@@ -842,12 +842,12 @@
     else
     {
         /* Set the same cursor for all top-level windows */
-        HWND hwnd = GetWindow( GetDesktopWindow32(), GW_CHILD );
+        HWND hwnd = GetWindow32( GetDesktopWindow32(), GW_CHILD );
         while(hwnd)
         {
             Window win = WIN_GetXWindow( hwnd );
             if (win) XDefineCursor( display, win, cursor );
-            hwnd = GetWindow( hwnd, GW_HWNDNEXT );
+            hwnd = GetWindow32( hwnd, GW_HWNDNEXT );
         }
     }
     return TRUE;
diff --git a/objects/font.c b/objects/font.c
index 07b95a6..2489e4d 100644
--- a/objects/font.c
+++ b/objects/font.c
@@ -1027,77 +1027,9 @@
  */
 BOOL16 GetTextMetrics16( HDC16 hdc, TEXTMETRIC16 *metrics )
 {
-    DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
-    if (!dc) return FALSE;
-    memcpy( metrics, &dc->u.x.font.metrics, sizeof(*metrics) );
-
-    metrics->tmAscent  = abs( metrics->tmAscent
-			      * dc->wndExtY / dc->vportExtY );
-    metrics->tmDescent = abs( metrics->tmDescent
-			      * dc->wndExtY / dc->vportExtY );
-    metrics->tmHeight  = metrics->tmAscent + metrics->tmDescent;
-    metrics->tmInternalLeading = abs( metrics->tmInternalLeading
-				      * dc->wndExtY / dc->vportExtY );
-    metrics->tmExternalLeading = abs( metrics->tmExternalLeading
-				      * dc->wndExtY / dc->vportExtY );
-    metrics->tmMaxCharWidth    = abs( metrics->tmMaxCharWidth 
-				      * dc->wndExtX / dc->vportExtX );
-    metrics->tmAveCharWidth    = abs( metrics->tmAveCharWidth
-				      * dc->wndExtX / dc->vportExtX );
-
-    dprintf_font(stdnimp,"text metrics:\n
-	InternalLeading = %i
-	ExternalLeading = %i
-	MaxCharWidth = %i
-	Weight = %i
-	Italic = %i
-	Underlined = %i
-	StruckOut = %i
-	FirstChar = %i
-	LastChar = %i
-	DefaultChar = %i
-	BreakChar = %i
-	CharSet = %i
-	Overhang = %i
-	DigitizedAspectX = %i
-	DigitizedAspectY = %i
-	AveCharWidth = %i
-	MaxCharWidth = %i
-	Ascent = %i
-	Descent = %i
-	Height = %i\n",
-    metrics->tmInternalLeading,
-    metrics->tmExternalLeading,
-    metrics->tmMaxCharWidth,
-    metrics->tmWeight,
-    metrics->tmItalic,
-    metrics->tmUnderlined,
-    metrics->tmStruckOut,
-    metrics->tmFirstChar,
-    metrics->tmLastChar,
-    metrics->tmDefaultChar,
-    metrics->tmBreakChar,
-    metrics->tmCharSet,
-    metrics->tmOverhang,
-    metrics->tmDigitizedAspectX,
-    metrics->tmDigitizedAspectY,
-    metrics->tmAveCharWidth,
-    metrics->tmMaxCharWidth,
-    metrics->tmAscent,
-    metrics->tmDescent,
-    metrics->tmHeight);
-
-    return TRUE;
-}
-
-
-/***********************************************************************
- *           GetTextMetrics32A    (GDI32.236)
- */
-BOOL32 GetTextMetrics32A( HDC32 hdc, TEXTMETRIC32A *metrics )
-{
-    TEXTMETRIC16 tm;
-    if (!GetTextMetrics16( (HDC16)hdc, &tm )) return FALSE;
+    TEXTMETRIC32A tm;
+    
+    if (!GetTextMetrics32A( (HDC32)hdc, &tm )) return FALSE;
     metrics->tmHeight           = tm.tmHeight;
     metrics->tmAscent           = tm.tmAscent;
     metrics->tmDescent          = tm.tmDescent;
@@ -1123,12 +1055,72 @@
 
 
 /***********************************************************************
+ *           GetTextMetrics32A    (GDI32.236)
+ */
+BOOL32 GetTextMetrics32A( HDC32 hdc, TEXTMETRIC32A *metrics )
+{
+DC * dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
+    if (!dc)
+    {
+	if (!(dc = (DC *)GDI_GetObjPtr( hdc, METAFILE_DC_MAGIC )))
+            return FALSE;
+    }
+
+    if (!dc->funcs->pGetTextMetrics ||
+        !dc->funcs->pGetTextMetrics( dc,metrics ))
+        return FALSE;
+    dprintf_font(stdnimp,"text metrics:\n
+	InternalLeading = %i
+	ExternalLeading = %i
+	MaxCharWidth = %i
+	Weight = %i
+	Italic = %i
+	Underlined = %i
+	StruckOut = %i
+	FirstChar = %i
+	LastChar = %i
+	DefaultChar = %i
+	BreakChar = %i
+	CharSet = %i
+	Overhang = %i
+	DigitizedAspectX = %i
+	DigitizedAspectY = %i
+	AveCharWidth = %i
+	MaxCharWidth = %i
+	Ascent = %i
+	Descent = %i
+	Height = %i\n",
+                 metrics->tmInternalLeading,
+                 metrics->tmExternalLeading,
+                 metrics->tmMaxCharWidth,
+                 metrics->tmWeight,
+                 metrics->tmItalic,
+                 metrics->tmUnderlined,
+                 metrics->tmStruckOut,
+                 metrics->tmFirstChar,
+                 metrics->tmLastChar,
+                 metrics->tmDefaultChar,
+                 metrics->tmBreakChar,
+                 metrics->tmCharSet,
+                 metrics->tmOverhang,
+                 metrics->tmDigitizedAspectX,
+                 metrics->tmDigitizedAspectY,
+                 metrics->tmAveCharWidth,
+                 metrics->tmMaxCharWidth,
+                 metrics->tmAscent,
+                 metrics->tmDescent,
+                 metrics->tmHeight);
+    return TRUE;
+}
+
+
+/***********************************************************************
  *           GetTextMetrics32W    (GDI32.237)
  */
 BOOL32 GetTextMetrics32W( HDC32 hdc, TEXTMETRIC32W *metrics )
 {
-    TEXTMETRIC16 tm;
-    if (!GetTextMetrics16( (HDC16)hdc, &tm )) return FALSE;
+    TEXTMETRIC32A tm;
+    if (!GetTextMetrics32A( (HDC16)hdc, &tm )) return FALSE;
     metrics->tmHeight           = tm.tmHeight;
     metrics->tmAscent           = tm.tmAscent;
     metrics->tmDescent          = tm.tmDescent;
diff --git a/objects/palette.c b/objects/palette.c
index 7a67571..53089a9 100644
--- a/objects/palette.c
+++ b/objects/palette.c
@@ -416,11 +416,11 @@
     if( hPal != STOCK_DEFAULT_PALETTE )
     {
 	HWND32 hWnd = WindowFromDC32( hDC );
-	HWND32 hActive = GetActiveWindow();
+	HWND32 hActive = GetActiveWindow32();
 	
 	/* set primary palette if it's related to current active */
 
-	if((!hWnd || (hActive == hWnd || IsChild(hActive,hWnd))) &&
+	if((!hWnd || (hActive == hWnd || IsChild16(hActive,hWnd))) &&
             !bForceBackground )
 	    wBkgPalette = 0;
     }
diff --git a/programs/winhelp/winhelp.c b/programs/winhelp/winhelp.c
index ff003d5..ec9436a 100644
--- a/programs/winhelp/winhelp.c
+++ b/programs/winhelp/winhelp.c
@@ -306,7 +306,9 @@
 
 	  WINHELP_InitFonts(win->hMainWnd);
 
-	  SetWindowText(win->hMainWnd, page->file->lpszTitle);
+	  if (page) {
+	    SetWindowText(win->hMainWnd, page->file->lpszTitle);
+          }
 
 	  WINHELP_SetupText(win->hTextWnd);
 	  InvalidateRect(win->hTextWnd, NULL, TRUE);
diff --git a/resources/TODO b/resources/TODO
index 641d539..33f9dc4 100644
--- a/resources/TODO
+++ b/resources/TODO
@@ -72,3 +72,26 @@
 Albrecht Kleine
 kleine@ak.sax.de
 
+**************************************************************
+1997, January
+
+Subject: EDITMENU
+
+There now is a resource EDITMENU.  It is the menu that is displayed when you
+click the right mouse button within an edit control.  I included an English
+version in all sysres_??.rc files, which needs translation in your language.
+This has now been done for:
+
+* English
+.....
+
+Note: I picked the IDs of the menuitems "at random".  When someone wants to
+find out the "real" (win95) values, feel free to change them.  However, you
+should change _all_ sysres_??.rc files and subsequently the function
+EDIT_WM_Command() in controls/edit.c.  This is a matter of minutes (i.e. no
+programming skills required).
+
+Bye,
+
+Frans van Dorsselaer
+dorssel@rulhm1.LeidenUniv.nl
diff --git a/resources/sysres_Cz.rc b/resources/sysres_Cz.rc
index 9ddbc1c..db196b0 100644
--- a/resources/sysres_Cz.rc
+++ b/resources/sysres_Cz.rc
@@ -13,6 +13,21 @@
  MENUITEM "&O programu WINE", 61761
 }
 
+EDITMENU MENU LOADONCALL MOVEABLE DISCARDABLE
+{
+	POPUP ""
+	BEGIN
+		MENUITEM "&Undo", EM_UNDO32
+		MENUITEM SEPARATOR
+		MENUITEM "Cu&t", WM_CUT
+		MENUITEM "&Copy", WM_COPY
+		MENUITEM "&Paste", WM_PASTE
+		MENUITEM "&Delete", WM_CLEAR
+		MENUITEM SEPARATOR
+		MENUITEM "Select &All", EM_SETSEL32
+	END
+}
+
 MSGBOX DIALOG 100, 80, 216, 168
 STYLE DS_SYSMODAL | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
 BEGIN
diff --git a/resources/sysres_Da.rc b/resources/sysres_Da.rc
index 99425c5..d43a7e6 100644
--- a/resources/sysres_Da.rc
+++ b/resources/sysres_Da.rc
@@ -13,6 +13,21 @@
  MENUITEM "&Om WINE ...", 61761
 }
 
+EDITMENU MENU LOADONCALL MOVEABLE DISCARDABLE
+{
+	POPUP ""
+	BEGIN
+		MENUITEM "&Undo", EM_UNDO32
+		MENUITEM SEPARATOR
+		MENUITEM "Cu&t", WM_CUT
+		MENUITEM "&Copy", WM_COPY
+		MENUITEM "&Paste", WM_PASTE
+		MENUITEM "&Delete", WM_CLEAR
+		MENUITEM SEPARATOR
+		MENUITEM "Select &All", EM_SETSEL32
+	END
+}
+
 MSGBOX DIALOG 100, 80, 216, 168
 STYLE DS_SYSMODAL | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
 BEGIN
diff --git a/resources/sysres_De.rc b/resources/sysres_De.rc
index 13e5c1a..a9208cc 100644
--- a/resources/sysres_De.rc
+++ b/resources/sysres_De.rc
@@ -13,6 +13,21 @@
  MENUITEM "&Über WINE ...", 61761
 }
 
+EDITMENU MENU LOADONCALL MOVEABLE DISCARDABLE
+{
+	POPUP ""
+	BEGIN
+		MENUITEM "&Undo", EM_UNDO32
+		MENUITEM SEPARATOR
+		MENUITEM "Cu&t", WM_CUT
+		MENUITEM "&Copy", WM_COPY
+		MENUITEM "&Paste", WM_PASTE
+		MENUITEM "&Delete", WM_CLEAR
+		MENUITEM SEPARATOR
+		MENUITEM "Select &All", EM_SETSEL32
+	END
+}
+
 MSGBOX DIALOG 100, 80, 216, 168
 STYLE DS_SYSMODAL | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
 BEGIN
diff --git a/resources/sysres_En.rc b/resources/sysres_En.rc
index ebe8dba..b7b6ade 100644
--- a/resources/sysres_En.rc
+++ b/resources/sysres_En.rc
@@ -13,6 +13,21 @@
  MENUITEM "&About WINE ...", 61761
 }
 
+EDITMENU MENU LOADONCALL MOVEABLE DISCARDABLE
+{
+	POPUP ""
+	BEGIN
+		MENUITEM "&Undo", EM_UNDO32
+		MENUITEM SEPARATOR
+		MENUITEM "Cu&t", WM_CUT
+		MENUITEM "&Copy", WM_COPY
+		MENUITEM "&Paste", WM_PASTE
+		MENUITEM "&Delete", WM_CLEAR
+		MENUITEM SEPARATOR
+		MENUITEM "Select &All", EM_SETSEL32
+	END
+}
+
 MSGBOX DIALOG 100, 80, 216, 168
 STYLE DS_SYSMODAL | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
 BEGIN
diff --git a/resources/sysres_Eo.rc b/resources/sysres_Eo.rc
index bb3d7d0..a5d5b31e 100644
--- a/resources/sysres_Eo.rc
+++ b/resources/sysres_Eo.rc
@@ -13,6 +13,21 @@
  MENUITEM "&Pri WINE ...", 61761
 }
 
+EDITMENU MENU LOADONCALL MOVEABLE DISCARDABLE
+{
+	POPUP ""
+	BEGIN
+		MENUITEM "&Undo", EM_UNDO32
+		MENUITEM SEPARATOR
+		MENUITEM "Cu&t", WM_CUT
+		MENUITEM "&Copy", WM_COPY
+		MENUITEM "&Paste", WM_PASTE
+		MENUITEM "&Delete", WM_CLEAR
+		MENUITEM SEPARATOR
+		MENUITEM "Select &All", EM_SETSEL32
+	END
+}
+
 MSGBOX DIALOG 100, 80, 216, 168
 STYLE DS_SYSMODAL | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
 BEGIN
diff --git a/resources/sysres_Es.rc b/resources/sysres_Es.rc
index 7380894..e3b3dac 100644
--- a/resources/sysres_Es.rc
+++ b/resources/sysres_Es.rc
@@ -14,6 +14,21 @@
  MENUITEM "&Acerca de WINE...", 61761
 }
 
+EDITMENU MENU LOADONCALL MOVEABLE DISCARDABLE
+{
+	POPUP ""
+	BEGIN
+		MENUITEM "&Undo", EM_UNDO32
+		MENUITEM SEPARATOR
+		MENUITEM "Cu&t", WM_CUT
+		MENUITEM "&Copy", WM_COPY
+		MENUITEM "&Paste", WM_PASTE
+		MENUITEM "&Delete", WM_CLEAR
+		MENUITEM SEPARATOR
+		MENUITEM "Select &All", EM_SETSEL32
+	END
+}
+
 MSGBOX DIALOG 100, 80, 216, 168
 STYLE DS_SYSMODAL | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
 BEGIN
diff --git a/resources/sysres_Fi.rc b/resources/sysres_Fi.rc
index 2dc3aff..59fa171 100644
--- a/resources/sysres_Fi.rc
+++ b/resources/sysres_Fi.rc
@@ -13,6 +13,21 @@
  MENUITEM "&Tietoja WINEista...", 61761
 }
 
+EDITMENU MENU LOADONCALL MOVEABLE DISCARDABLE
+{
+	POPUP ""
+	BEGIN
+		MENUITEM "&Undo", EM_UNDO32
+		MENUITEM SEPARATOR
+		MENUITEM "Cu&t", WM_CUT
+		MENUITEM "&Copy", WM_COPY
+		MENUITEM "&Paste", WM_PASTE
+		MENUITEM "&Delete", WM_CLEAR
+		MENUITEM SEPARATOR
+		MENUITEM "Select &All", EM_SETSEL32
+	END
+}
+
 MSGBOX DIALOG 100, 80, 216, 168
 STYLE DS_SYSMODAL | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
 BEGIN
diff --git a/resources/sysres_Fr.rc b/resources/sysres_Fr.rc
index a8801dc..c58bbc9 100644
--- a/resources/sysres_Fr.rc
+++ b/resources/sysres_Fr.rc
@@ -14,6 +14,21 @@
  MENUITEM "A propos de &Wine ...", 61761
 }
 
+EDITMENU MENU LOADONCALL MOVEABLE DISCARDABLE
+{
+	POPUP ""
+	BEGIN
+		MENUITEM "&Undo", EM_UNDO32
+		MENUITEM SEPARATOR
+		MENUITEM "Cu&t", WM_CUT
+		MENUITEM "&Copy", WM_COPY
+		MENUITEM "&Paste", WM_PASTE
+		MENUITEM "&Delete", WM_CLEAR
+		MENUITEM SEPARATOR
+		MENUITEM "Select &All", EM_SETSEL32
+	END
+}
+
 MSGBOX DIALOG 100, 80, 216, 168
 STYLE DS_SYSMODAL | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
 BEGIN
diff --git a/resources/sysres_It.rc b/resources/sysres_It.rc
index 82a9bb9..afa6d03 100644
--- a/resources/sysres_It.rc
+++ b/resources/sysres_It.rc
@@ -13,6 +13,21 @@
  MENUITEM "&Info su WINE ...", 61761
 }
 
+EDITMENU MENU LOADONCALL MOVEABLE DISCARDABLE
+{
+	POPUP ""
+	BEGIN
+		MENUITEM "&Undo", EM_UNDO32
+		MENUITEM SEPARATOR
+		MENUITEM "Cu&t", WM_CUT
+		MENUITEM "&Copy", WM_COPY
+		MENUITEM "&Paste", WM_PASTE
+		MENUITEM "&Delete", WM_CLEAR
+		MENUITEM SEPARATOR
+		MENUITEM "Select &All", EM_SETSEL32
+	END
+}
+
 MSGBOX DIALOG 100, 80, 216, 168
 STYLE DS_SYSMODAL | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
 BEGIN
diff --git a/resources/sysres_Ko.rc b/resources/sysres_Ko.rc
index 24dfb4e..ab26d06 100644
--- a/resources/sysres_Ko.rc
+++ b/resources/sysres_Ko.rc
@@ -13,6 +13,21 @@
  MENUITEM "¿ÍÀο¡ °üÇÏ¿© ...", 61761
 }
 
+EDITMENU MENU LOADONCALL MOVEABLE DISCARDABLE
+{
+	POPUP ""
+	BEGIN
+		MENUITEM "&Undo", EM_UNDO32
+		MENUITEM SEPARATOR
+		MENUITEM "Cu&t", WM_CUT
+		MENUITEM "&Copy", WM_COPY
+		MENUITEM "&Paste", WM_PASTE
+		MENUITEM "&Delete", WM_CLEAR
+		MENUITEM SEPARATOR
+		MENUITEM "Select &All", EM_SETSEL32
+	END
+}
+
 MSGBOX DIALOG 100, 80, 216, 168
 STYLE DS_SYSMODAL | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
 BEGIN
diff --git a/resources/sysres_No.rc b/resources/sysres_No.rc
index 4192142..eed7dfe 100644
--- a/resources/sysres_No.rc
+++ b/resources/sysres_No.rc
@@ -13,6 +13,21 @@
  MENUITEM "&Om WINE ...", 61761
 }
 
+EDITMENU MENU LOADONCALL MOVEABLE DISCARDABLE
+{
+	POPUP ""
+	BEGIN
+		MENUITEM "&Undo", EM_UNDO32
+		MENUITEM SEPARATOR
+		MENUITEM "Cu&t", WM_CUT
+		MENUITEM "&Copy", WM_COPY
+		MENUITEM "&Paste", WM_PASTE
+		MENUITEM "&Delete", WM_CLEAR
+		MENUITEM SEPARATOR
+		MENUITEM "Select &All", EM_SETSEL32
+	END
+}
+
 MSGBOX DIALOG 100, 80, 216, 168
 STYLE DS_SYSMODAL | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
 BEGIN
diff --git a/tools/build.c b/tools/build.c
index 894b73c..866aaf0 100644
--- a/tools/build.c
+++ b/tools/build.c
@@ -1325,7 +1325,7 @@
 
     fprintf( outfile, "\n\t.align 4\n" );
 #ifdef __GNUC__
-    fprintf( outfile, ".stabs \"CallTo32_LargeStack:F1\",36,0,0,CallTo32_LargeStack\n");
+    fprintf( outfile, ".stabs \"CallTo32_LargeStack:F1\",36,0,0," PREFIX "CallTo32_LargeStack\n");
 #endif
     fprintf( outfile, "\t.globl " PREFIX "CallTo32_LargeStack\n" );
     fprintf( outfile, PREFIX "CallTo32_LargeStack:\n" );
@@ -1604,7 +1604,7 @@
 
     fprintf( outfile, "\n\t.align 4\n" );
 #ifdef __GNUC__
-    fprintf( outfile, ".stabs \"CallFrom16_%s:F1\",36,0,0,CallFrom16_%s\n", 
+    fprintf( outfile, ".stabs \"CallFrom16_%s:F1\",36,0,0," PREFIX "CallFrom16_%s\n", 
 	     profile, profile);
 #endif
     fprintf( outfile, "\t.globl " PREFIX "CallFrom16_%s\n", profile );
@@ -1823,7 +1823,7 @@
 
     fprintf( outfile, "\n\t.align 4\n" );
 #ifdef __GNUC__
-    fprintf( outfile, ".stabs \"CallTo16_%s:F1\",36,0,0,CallTo16_%s\n", 
+    fprintf( outfile, ".stabs \"CallTo16_%s:F1\",36,0,0," PREFIX "CallTo16_%s\n", 
 	     profile, profile);
 #endif
     fprintf( outfile, "\t.globl " PREFIX "CallTo16_%s\n", profile );
@@ -2073,13 +2073,15 @@
 {
     /* Restore the context structure */
 
-    fprintf( outfile, "\tleal %d(%%ebp),%%esp\n", -sizeof(CONTEXT)-12 );
+    fprintf( outfile, "\tleal %d(%%ebp),%%esp\n", -sizeof(CONTEXT)-8 );
     fprintf( outfile, "\tfrstor %d(%%esp)\n", CONTEXTOFFSET(FloatSave) );
 
     fprintf( outfile, "\tmovl %d(%%esp),%%eax\n", CONTEXTOFFSET(Eip) );
     fprintf( outfile, "\tmovl %%eax,4(%%ebp)\n" ); /* %eip at time of call */
     fprintf( outfile, "\tmovl %d(%%esp),%%eax\n", CONTEXTOFFSET(Ebp) );
     fprintf( outfile, "\tmovl %%eax,0(%%ebp)\n" ); /* %ebp at time of call */
+
+    /* Store flags over the relay addr */
     fprintf( outfile, "\tmovl %d(%%esp),%%eax\n", CONTEXTOFFSET(EFlags) );
     fprintf( outfile, "\tmovl %%eax,%d(%%esp)\n", sizeof(CONTEXT) );
 
@@ -2152,7 +2154,7 @@
 
     fprintf( outfile, "\n\t.align 4\n" );
 #ifdef __GNUC__
-    fprintf( outfile, ".stabs \"CallFrom32_%s:F1\",36,0,0,CallFrom32_%s\n", 
+    fprintf( outfile, ".stabs \"CallFrom32_%s:F1\",36,0,0," PREFIX "CallFrom32_%s\n", 
 	     profile, profile);
 #endif
     fprintf( outfile, "\t.globl " PREFIX "CallFrom32_%s\n", profile );
@@ -2243,7 +2245,7 @@
 
     fprintf( outfile, "\n\t.align 4\n" );
 #ifdef __GNUC__
-    fprintf( outfile, ".stabs \"CallTo32_%d:F1\",36,0,0,CallTo32_%d\n", 
+    fprintf( outfile, ".stabs \"CallTo32_%d:F1\",36,0,0," PREFIX "CallTo32_%d\n", 
 	     args, args);
 #endif
     fprintf( outfile, "\t.globl " PREFIX "CallTo32_%d\n", args );
diff --git a/tools/makedep.c b/tools/makedep.c
index 1638987..9511f80 100644
--- a/tools/makedep.c
+++ b/tools/makedep.c
@@ -271,6 +271,7 @@
         while (fgets( buffer, sizeof(buffer), file ))
             if (!strncmp( buffer, Separator, strlen(Separator) )) break;
         ftruncate( fileno(file), ftell(file) );
+        fseek( file, 0L, SEEK_END );
     }
     if (!file)
     {
diff --git a/win32/time.c b/win32/time.c
index bfc26ef..6b38eb8 100644
--- a/win32/time.c
+++ b/win32/time.c
@@ -123,7 +123,11 @@
     struct timezone tz;
 
     tz.tz_minuteswest = tzinfo->Bias;
+#ifdef __EMX__ /* FIXME */
+    tz.tz_dsttime = 0;
+#else
     tz.tz_dsttime = DST_NONE;
+#endif
     return !settimeofday(NULL, &tz);
 }
 
diff --git a/windows/dce.c b/windows/dce.c
index 56889ce..08c09e1 100644
--- a/windows/dce.c
+++ b/windows/dce.c
@@ -273,7 +273,7 @@
  * clipped by the client area of all ancestors, and then optionally
  * by siblings and children.
  */
-HRGN32 DCE_GetVisRgn( HWND hwnd, WORD flags )
+HRGN32 DCE_GetVisRgn( HWND32 hwnd, WORD flags )
 {
     RECT16 rect;
     HRGN32 hrgn;
diff --git a/windows/defdlg.c b/windows/defdlg.c
index a4808e9..0ec5c44 100644
--- a/windows/defdlg.c
+++ b/windows/defdlg.c
@@ -21,7 +21,7 @@
 {
     HWND32 hwndPrev = GetFocus32();
 
-    if (IsChild( hwndDlg, hwndPrev ))
+    if (IsChild32( hwndDlg, hwndPrev ))
     {
         if (SendMessage16( hwndPrev, WM_GETDLGCODE, 0, 0 ) & DLGC_HASSETSEL)
             SendMessage16( hwndPrev, EM_SETSEL16, TRUE, MAKELONG( -1, 0 ) );
@@ -39,7 +39,7 @@
 {
     HWND32 hwndFocus = GetFocus32();
 
-    if (!hwndFocus || !IsChild( hwnd, hwndFocus )) return FALSE;
+    if (!hwndFocus || !IsChild32( hwnd, hwndFocus )) return FALSE;
     infoPtr->hwndFocus = hwndFocus;
       /* Remove default button */
     return TRUE;
@@ -51,7 +51,7 @@
  */
 static BOOL32 DEFDLG_RestoreFocus( HWND32 hwnd, DIALOGINFO *infoPtr )
 {
-    if (!infoPtr->hwndFocus || IsIconic(hwnd)) return FALSE;
+    if (!infoPtr->hwndFocus || IsIconic32(hwnd)) return FALSE;
     if (!IsWindow( infoPtr->hwndFocus )) return FALSE;
     DEFDLG_SetFocus( hwnd, infoPtr->hwndFocus );
     infoPtr->hwndFocus = 0;
@@ -66,12 +66,12 @@
  */
 static HWND32 DEFDLG_FindDefButton( HWND32 hwndDlg )
 {
-    HWND32 hwndChild = GetWindow( hwndDlg, GW_CHILD );
+    HWND32 hwndChild = GetWindow32( hwndDlg, GW_CHILD );
     while (hwndChild)
     {
         if (SendMessage16( hwndChild, WM_GETDLGCODE, 0, 0 ) & DLGC_DEFPUSHBUTTON)
             break;
-        hwndChild = GetWindow( hwndChild, GW_HWNDNEXT );
+        hwndChild = GetWindow32( hwndChild, GW_HWNDNEXT );
     }
     return hwndChild;
 }
@@ -91,14 +91,14 @@
     
     if (dlgInfo->idResult)  /* There's already a default pushbutton */
     {
-        HWND32 hwndOld = GetDlgItem( hwndDlg, dlgInfo->idResult );
+        HWND32 hwndOld = GetDlgItem32( hwndDlg, dlgInfo->idResult );
         if (SendMessage32A( hwndOld, WM_GETDLGCODE, 0, 0) & DLGC_DEFPUSHBUTTON)
             SendMessage32A( hwndOld, BM_SETSTYLE32, BS_PUSHBUTTON, TRUE );
     }
     if (hwndNew)
     {
         SendMessage32A( hwndNew, BM_SETSTYLE32, BS_DEFPUSHBUTTON, TRUE );
-        dlgInfo->idResult = GetDlgCtrlID( hwndNew );
+        dlgInfo->idResult = GetDlgCtrlID32( hwndNew );
     }
     else dlgInfo->idResult = 0;
     return TRUE;
@@ -170,7 +170,7 @@
         case DM_SETDEFID:
             if (dlgInfo->fEnd) return 1;
             DEFDLG_SetDefButton( hwnd, dlgInfo,
-                                 wParam ? GetDlgItem( hwnd, wParam ) : 0 );
+                                 wParam ? GetDlgItem32( hwnd, wParam ) : 0 );
             return 1;
 
         case DM_GETDEFID:
@@ -179,7 +179,7 @@
 	      return MAKELONG( dlgInfo->idResult, DC_HASDEFID );
 	    hwndDefId = DEFDLG_FindDefButton( hwnd );
 	    if (hwndDefId)
-	      return MAKELONG( GetDlgCtrlID( hwndDefId ), DC_HASDEFID);
+	      return MAKELONG( GetDlgCtrlID32( hwndDefId ), DC_HASDEFID);
 	    return 0;
 
 	case WM_NEXTDLGCTL:
@@ -197,7 +197,7 @@
 
         case WM_CLOSE:
             EndDialog( hwnd, TRUE );
-            DestroyWindow( hwnd );
+            DestroyWindow32( hwnd );
             return 0;
     }
     return 0;
diff --git a/windows/defwnd.c b/windows/defwnd.c
index b666cca..c393eb7 100644
--- a/windows/defwnd.c
+++ b/windows/defwnd.c
@@ -132,11 +132,15 @@
             ValidateRect32( wndPtr->hwndSelf, NULL );
             wndPtr->flags |= WIN_NO_REDRAW;
         }
-        else wndPtr->flags &= ~WIN_NO_REDRAW;
+        else
+        {
+            wndPtr->flags &= ~WIN_NO_REDRAW;
+            ShowWindow32( wndPtr->hwndSelf, SW_SHOW );
+        }
         return 0;
 
     case WM_CLOSE:
-	DestroyWindow( wndPtr->hwndSelf );
+	DestroyWindow32( wndPtr->hwndSelf );
 	return 0;
 
     case WM_MOUSEACTIVATE:
@@ -297,7 +301,7 @@
         if (!(wndPtr->dwStyle & WS_POPUP) || !wndPtr->owner) return 0;
         if ((wndPtr->dwStyle & WS_VISIBLE) && wParam) return 0;
 	else if (!(wndPtr->dwStyle & WS_VISIBLE) && !wParam) return 0;
-        ShowWindow( wndPtr->hwndSelf, wParam ? SW_SHOWNOACTIVATE : SW_HIDE );
+        ShowWindow32( wndPtr->hwndSelf, wParam ? SW_SHOWNOACTIVATE : SW_HIDE );
 	break; 
 
     case WM_CANCELMODE:
diff --git a/windows/dialog.c b/windows/dialog.c
index bcd73ea..5fbd4ee 100644
--- a/windows/dialog.c
+++ b/windows/dialog.c
@@ -5,6 +5,7 @@
  */
 
 #include <ctype.h>
+#include <limits.h>
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
@@ -226,7 +227,7 @@
  * Create the control windows for a dialog.
  */
 static BOOL32 DIALOG_CreateControls( WND *pWnd, LPCSTR template, INT32 items,
-                                     HINSTANCE32 hInst, BOOL win32 )
+                                     HINSTANCE32 hInst, BOOL32 win32 )
 {
     DIALOGINFO *dlgInfo = (DIALOGINFO *)pWnd->wExtra;
     DLG_CONTROL_INFO info;
@@ -465,8 +466,8 @@
 {
     HMENU16 hMenu = 0;
     HFONT16 hFont = 0;
-    HWND hwnd;
-    RECT16 rect;
+    HWND32 hwnd;
+    RECT32 rect;
     WND * wndPtr;
     DLG_TEMPLATE template;
     DIALOGINFO * dlgInfo;
@@ -524,7 +525,7 @@
     rect.bottom = template.cy * yUnit / 8;
     if (template.style & DS_MODALFRAME)
         template.exStyle |= WS_EX_DLGMODALFRAME;
-    AdjustWindowRectEx16( &rect, template.style, 
+    AdjustWindowRectEx32( &rect, template.style, 
                           hMenu ? TRUE : FALSE , template.exStyle );
     rect.right -= rect.left;
     rect.bottom -= rect.top;
@@ -543,7 +544,7 @@
             INT16 dX, dY;
 
             if( !(template.style & DS_ABSALIGN) )
-                ClientToScreen16( owner, (POINT16 *)&rect );
+                ClientToScreen32( owner, (POINT32 *)&rect );
 	    
             /* try to fit it into the desktop */
 
@@ -596,7 +597,7 @@
     if (!DIALOG_CreateControls( wndPtr, dlgTemplate, template.nbItems,
                                 hInst, win32Template ))
     {
-        DestroyWindow( hwnd );
+        DestroyWindow32( hwnd );
         return 0;
     }
 
@@ -606,7 +607,7 @@
     if (SendMessage32A( hwnd, WM_INITDIALOG,
                         (WPARAM32)dlgInfo->hwndFocus, param ))
 	SetFocus32( dlgInfo->hwndFocus );
-    if (template.style & WS_VISIBLE) ShowWindow( hwnd, SW_SHOW );
+    if (template.style & WS_VISIBLE) ShowWindow32( hwnd, SW_SHOW );
     return hwnd;
 }
 
@@ -736,8 +737,8 @@
     owner = WIN_GetTopParent( owner );
     if (!(wndPtr = WIN_FindWndPtr( hwnd ))) return -1;
     dlgInfo = (DIALOGINFO *)wndPtr->wExtra;
-    EnableWindow( owner, FALSE );
-    ShowWindow( hwnd, SW_SHOW );
+    EnableWindow32( owner, FALSE );
+    ShowWindow32( hwnd, SW_SHOW );
 
     while (MSG_InternalGetMessage(&msg, hwnd, owner, MSGF_DIALOGBOX, PM_REMOVE,
                                   !(wndPtr->dwStyle & DS_NOIDLEMSG) ))
@@ -750,8 +751,8 @@
 	if (dlgInfo->fEnd) break;
     }
     retval = dlgInfo->idResult;
-    EnableWindow( owner, TRUE );
-    DestroyWindow( hwnd );
+    EnableWindow32( owner, TRUE );
+    DestroyWindow32( hwnd );
     return retval;
 }
 
@@ -872,13 +873,13 @@
 /***********************************************************************
  *           IsDialogMessage   (USER.90)
  */
-BOOL IsDialogMessage( HWND hwndDlg, LPMSG16 msg )
+BOOL16 IsDialogMessage( HWND16 hwndDlg, LPMSG16 msg )
 {
     WND * wndPtr;
     int dlgCode;
 
     if (!(wndPtr = WIN_FindWndPtr( hwndDlg ))) return FALSE;
-    if ((hwndDlg != msg->hwnd) && !IsChild( hwndDlg, msg->hwnd )) return FALSE;
+    if ((hwndDlg != msg->hwnd) && !IsChild16( hwndDlg, msg->hwnd )) return FALSE;
 
       /* Only the key messages get special processing */
     if ((msg->message != WM_KEYDOWN) &&
@@ -930,7 +931,7 @@
 
         case VK_ESCAPE:
             SendMessage32A( hwndDlg, WM_COMMAND, IDCANCEL,
-                            (LPARAM)GetDlgItem( hwndDlg, IDCANCEL ) );
+                            (LPARAM)GetDlgItem32( hwndDlg, IDCANCEL ) );
             break;
 
         case VK_RETURN:
@@ -939,10 +940,10 @@
                 if (HIWORD(dw) == DC_HASDEFID)
                     SendMessage32A( hwndDlg, WM_COMMAND, 
                                     MAKEWPARAM( LOWORD(dw), BN_CLICKED ),
-                                    (LPARAM)GetDlgItem( hwndDlg, LOWORD(dw) ));
+                                    (LPARAM)GetDlgItem32(hwndDlg, LOWORD(dw)));
                 else
                     SendMessage32A( hwndDlg, WM_COMMAND, IDOK,
-                                    (LPARAM)GetDlgItem( hwndDlg, IDOK ) );
+                                    (LPARAM)GetDlgItem32( hwndDlg, IDOK ) );
             }
             break;
 
@@ -969,9 +970,20 @@
 
 
 /****************************************************************
- *         GetDlgCtrlID   (USER.277) (USER32.233)
+ *         GetDlgCtrlID16   (USER.277)
  */
-INT16 GetDlgCtrlID( HWND32 hwnd )
+INT16 GetDlgCtrlID16( HWND16 hwnd )
+{
+    WND *wndPtr = WIN_FindWndPtr(hwnd);
+    if (wndPtr) return wndPtr->wIDmenu;
+    else return 0;
+}
+ 
+
+/****************************************************************
+ *         GetDlgCtrlID32   (USER32.233)
+ */
+INT32 GetDlgCtrlID32( HWND32 hwnd )
 {
     WND *wndPtr = WIN_FindWndPtr(hwnd);
     if (wndPtr) return wndPtr->wIDmenu;
@@ -980,15 +992,29 @@
  
 
 /***********************************************************************
- *           GetDlgItem   (USER.91)
+ *           GetDlgItem16   (USER.91)
  */
-HWND GetDlgItem( HWND hwndDlg, WORD id )
+HWND16 GetDlgItem16( HWND16 hwndDlg, INT16 id )
 {
     WND *pWnd;
 
     if (!(pWnd = WIN_FindWndPtr( hwndDlg ))) return 0;
     for (pWnd = pWnd->child; pWnd; pWnd = pWnd->next)
-        if (pWnd->wIDmenu == id) return pWnd->hwndSelf;
+        if (pWnd->wIDmenu == (UINT16)id) return pWnd->hwndSelf;
+    return 0;
+}
+
+
+/***********************************************************************
+ *           GetDlgItem32   (USER32.234)
+ */
+HWND32 GetDlgItem32( HWND32 hwndDlg, INT32 id )
+{
+    WND *pWnd;
+
+    if (!(pWnd = WIN_FindWndPtr( hwndDlg ))) return 0;
+    for (pWnd = pWnd->child; pWnd; pWnd = pWnd->next)
+        if (pWnd->wIDmenu == (UINT16)id) return pWnd->hwndSelf;
     return 0;
 }
 
@@ -999,7 +1025,7 @@
 LRESULT SendDlgItemMessage16( HWND16 hwnd, INT16 id, UINT16 msg,
                               WPARAM16 wParam, LPARAM lParam )
 {
-    HWND16 hwndCtrl = GetDlgItem( hwnd, id );
+    HWND16 hwndCtrl = GetDlgItem16( hwnd, id );
     if (hwndCtrl) return SendMessage16( hwndCtrl, msg, wParam, lParam );
     else return 0;
 }
@@ -1011,7 +1037,7 @@
 LRESULT SendDlgItemMessage32A( HWND32 hwnd, INT32 id, UINT32 msg,
                                WPARAM32 wParam, LPARAM lParam )
 {
-    HWND hwndCtrl = GetDlgItem( (HWND16)hwnd, (INT16)id );
+    HWND32 hwndCtrl = GetDlgItem32( hwnd, id );
     if (hwndCtrl) return SendMessage32A( hwndCtrl, msg, wParam, lParam );
     else return 0;
 }
@@ -1023,7 +1049,7 @@
 LRESULT SendDlgItemMessage32W( HWND32 hwnd, INT32 id, UINT32 msg,
                                WPARAM32 wParam, LPARAM lParam )
 {
-    HWND hwndCtrl = GetDlgItem( (HWND16)hwnd, (INT16)id );
+    HWND32 hwndCtrl = GetDlgItem32( hwnd, id );
     if (hwndCtrl) return SendMessage32W( hwndCtrl, msg, wParam, lParam );
     else return 0;
 }
@@ -1091,13 +1117,7 @@
  */
 void SetDlgItemInt16( HWND16 hwnd, INT16 id, UINT16 value, BOOL16 fSigned )
 {
-    char *str = (char *)SEGPTR_ALLOC( 20 * sizeof(char) );
-
-    if (!str) return;
-    if (fSigned) sprintf( str, "%d", (INT32)(INT16)value );
-    else sprintf( str, "%u", value );
-    SendDlgItemMessage16( hwnd, id, WM_SETTEXT, 0, (LPARAM)SEGPTR_GET(str) );
-    SEGPTR_FREE(str);
+    return SetDlgItemInt32( hwnd, (UINT32)(UINT16)id, value, fSigned );
 }
 
 
@@ -1115,42 +1135,67 @@
 
 
 /***********************************************************************
- *           GetDlgItemInt   (USER.95)
+ *           GetDlgItemInt16   (USER.95)
  */
-WORD GetDlgItemInt( HWND hwnd, WORD id, BOOL * translated, BOOL fSigned )
+UINT16 GetDlgItemInt16( HWND16 hwnd, INT16 id, BOOL16 *translated,
+                        BOOL16 fSigned )
 {
-    char *str;
-    long result = 0;
-    
+    UINT32 result;
+    BOOL32 ok;
+
     if (translated) *translated = FALSE;
-    if (!(str = (char *)SEGPTR_ALLOC( 30 * sizeof(char) ))) return 0;
-    if (SendDlgItemMessage16( hwnd, id, WM_GETTEXT, 30, (LPARAM)SEGPTR_GET(str)))
+    result = GetDlgItemInt32( hwnd, (UINT32)(UINT16)id, &ok, fSigned );
+    if (!ok) return 0;
+    if (fSigned)
     {
-	char * endptr;
-	result = strtol( str, &endptr, 10 );
-	if (endptr && (endptr != str))  /* Conversion was successful */
-	{
-	    if (fSigned)
-	    {
-		if ((result < -32767) || (result > 32767)) result = 0;
-		else if (translated) *translated = TRUE;
-	    }
-	    else
-	    {
-		if ((result < 0) || (result > 65535)) result = 0;
-		else if (translated) *translated = TRUE;
-	    }
-	}
+        if (((INT32)result < -32767) || ((INT32)result > 32767)) return 0;
     }
-    SEGPTR_FREE(str);
-    return (WORD)result;
+    else
+    {
+        if (result > 65535) return 0;
+    }
+    if (translated) *translated = TRUE;
+    return (UINT16)result;
 }
 
 
 /***********************************************************************
- *           CheckDlgButton   (USER.97) (USER32.44)
+ *           GetDlgItemInt32   (USER32.235)
  */
-BOOL16 CheckDlgButton( HWND32 hwnd, INT32 id, UINT32 check )
+UINT32 GetDlgItemInt32( HWND32 hwnd, INT32 id, BOOL32 *translated,
+                        BOOL32 fSigned )
+{
+    char str[30];
+    char * endptr;
+    long result = 0;
+    
+    if (translated) *translated = FALSE;
+    if (!SendDlgItemMessage32A(hwnd, id, WM_GETTEXT, sizeof(str), (LPARAM)str))
+        return 0;
+    if (fSigned)
+    {
+        result = strtol( str, &endptr, 10 );
+        if (!endptr || (endptr == str))  /* Conversion was unsuccessful */
+            return 0;
+        if (((result == LONG_MIN) || (result == LONG_MAX)) && (errno==ERANGE))
+            return 0;
+    }
+    else
+    {
+        result = strtoul( str, &endptr, 10 );
+        if (!endptr || (endptr == str))  /* Conversion was unsuccessful */
+            return 0;
+        if ((result == ULONG_MAX) && (errno == ERANGE)) return 0;
+    }
+    if (translated) *translated = TRUE;
+    return (UINT32)result;
+}
+
+
+/***********************************************************************
+ *           CheckDlgButton16   (USER.97)
+ */
+BOOL16 CheckDlgButton16( HWND16 hwnd, INT16 id, UINT16 check )
 {
     SendDlgItemMessage32A( hwnd, id, BM_SETCHECK32, check, 0 );
     return TRUE;
@@ -1158,19 +1203,48 @@
 
 
 /***********************************************************************
- *           IsDlgButtonChecked   (USER.98)
+ *           CheckDlgButton32   (USER32.44)
  */
-WORD IsDlgButtonChecked( HWND hwnd, WORD id )
+BOOL32 CheckDlgButton32( HWND32 hwnd, INT32 id, UINT32 check )
 {
-    return (WORD)SendDlgItemMessage32A( hwnd, id, BM_GETCHECK32, 0, 0 );
+    SendDlgItemMessage32A( hwnd, id, BM_SETCHECK32, check, 0 );
+    return TRUE;
 }
 
 
 /***********************************************************************
- *           CheckRadioButton   (USER.96) (USER32.47)
+ *           IsDlgButtonChecked16   (USER.98)
  */
-BOOL16 CheckRadioButton( HWND32 hwndDlg, UINT32 firstID, UINT32 lastID,
-                         UINT32 checkID )
+UINT16 IsDlgButtonChecked16( HWND16 hwnd, UINT16 id )
+{
+    return (UINT16)SendDlgItemMessage32A( hwnd, id, BM_GETCHECK32, 0, 0 );
+}
+
+
+/***********************************************************************
+ *           IsDlgButtonChecked32   (USER32.343)
+ */
+UINT32 IsDlgButtonChecked32( HWND32 hwnd, UINT32 id )
+{
+    return (UINT32)SendDlgItemMessage32A( hwnd, id, BM_GETCHECK32, 0, 0 );
+}
+
+
+/***********************************************************************
+ *           CheckRadioButton16   (USER.96)
+ */
+BOOL16 CheckRadioButton16( HWND16 hwndDlg, UINT16 firstID, UINT16 lastID,
+                           UINT16 checkID )
+{
+    return CheckRadioButton32( hwndDlg, firstID, lastID, checkID );
+}
+
+
+/***********************************************************************
+ *           CheckRadioButton32   (USER32.47)
+ */
+BOOL32 CheckRadioButton32( HWND32 hwndDlg, UINT32 firstID, UINT32 lastID,
+                           UINT32 checkID )
 {
     WND *pWnd = WIN_FindWndPtr( hwndDlg );
     if (!pWnd) return FALSE;
@@ -1354,7 +1428,7 @@
     char *buffer, *ptr;
     INT32 item, size;
     BOOL32 ret;
-    HWND32 listbox = GetDlgItem( hwnd, id );
+    HWND32 listbox = GetDlgItem32( hwnd, id );
 
     dprintf_dialog( stddeb, "DlgDirSelect: %04x '%s' %d\n", hwnd, str, id );
     if (!listbox) return FALSE;
@@ -1436,7 +1510,7 @@
     }
     else drive = DRIVE_GetCurrentDrive();
 
-    if (idLBox && ((hwnd = GetDlgItem( hDlg, idLBox )) != 0))
+    if (idLBox && ((hwnd = GetDlgItem32( hDlg, idLBox )) != 0))
     {
         /* If the path exists and is a directory, chdir to it */
         if (!spec || !spec[0] || DRIVE_Chdir( drive, spec )) spec = "*.*";
@@ -1484,7 +1558,7 @@
         }
     }
 
-    if (idStatic && ((hwnd = GetDlgItem( hDlg, idStatic )) != 0))
+    if (idStatic && ((hwnd = GetDlgItem32( hDlg, idStatic )) != 0))
     {
         char temp[512];
         int drive = DRIVE_GetCurrentDrive();
diff --git a/windows/event.c b/windows/event.c
index 19480dd..d8e6dfb 100644
--- a/windows/event.c
+++ b/windows/event.c
@@ -58,11 +58,6 @@
   /* X context to associate a hwnd to an X window */
 static XContext winContext = 0;
 
-  /* State variables */
-BOOL MouseButtonsStates[NB_BUTTONS];
-BOOL AsyncMouseButtonsStates[NB_BUTTONS];
-BYTE InputKeyStateTable[256];
-
 static INT16  captureHT = HTCLIENT;
 static HWND32 captureWnd = 0;
 static BOOL32 InputEnabled = TRUE;
@@ -85,7 +80,7 @@
 };
 
   /* Event handlers */
-static void EVENT_key( 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 );
@@ -128,7 +123,7 @@
     case KeyPress:
     case KeyRelease:
         if (InputEnabled)
-            EVENT_key( (XKeyEvent*)event );
+            EVENT_Key( (XKeyEvent*)event );
 	break;
 	
     case ButtonPress:
@@ -445,417 +440,13 @@
 
 
 /***********************************************************************
- *           EVENT_key
+ *           EVENT_Key
  *
  * Handle a X key event
  */
-
-/* Keyboard translation tables */
-static const int special_key[] =
+static void EVENT_Key( XKeyEvent *event )
 {
-    VK_BACK, VK_TAB, 0, VK_CLEAR, 0, VK_RETURN, 0, 0,           /* FF08 */
-    0, 0, 0, VK_PAUSE, VK_SCROLL, 0, 0, 0,                      /* FF10 */
-    0, 0, 0, VK_ESCAPE                                          /* FF18 */
-};
-
-static const int cursor_key[] =
-{
-    VK_HOME, VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN, VK_PRIOR, 
-                                       VK_NEXT, VK_END          /* FF50 */
-};
-
-static const int misc_key[] =
-{
-    VK_SELECT, VK_SNAPSHOT, VK_EXECUTE, VK_INSERT, 0, 0, 0, 0,  /* FF60 */
-    VK_CANCEL, VK_HELP, VK_CANCEL, VK_MENU                      /* FF68 */
-};
-
-static const int keypad_key[] =
-{
-    0, VK_NUMLOCK,                                        	/* FF7E */
-    0, 0, 0, 0, 0, 0, 0, 0,                                     /* FF80 */
-    0, 0, 0, 0, 0, VK_RETURN, 0, 0,                             /* FF88 */
-    0, 0, 0, 0, 0, VK_HOME, VK_LEFT, VK_UP,                     /* FF90 */
-    VK_RIGHT, VK_DOWN, VK_PRIOR, VK_NEXT, VK_END, 0,
-				 VK_INSERT, VK_DELETE,          /* FF98 */
-    0, 0, 0, 0, 0, 0, 0, 0,                                     /* FFA0 */
-    0, 0, VK_MULTIPLY, VK_ADD, VK_SEPARATOR, VK_SUBTRACT, 
-                               VK_DECIMAL, VK_DIVIDE,           /* FFA8 */
-    VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4,
-                            VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, /* FFB0 */
-    VK_NUMPAD8, VK_NUMPAD9                                      /* FFB8 */
-};
-    
-static const int function_key[] =
-{
-    VK_F1, VK_F2,                                               /* FFBE */
-    VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10,    /* FFC0 */
-    VK_F11, VK_F12, VK_F13, VK_F14, VK_F15, VK_F16              /* FFC8 */
-};
-
-static const int modifier_key[] =
-{
-    VK_SHIFT, VK_SHIFT, VK_CONTROL, VK_CONTROL, VK_CAPITAL, 0, /* FFE1 */
-    VK_MENU, VK_MENU, VK_MENU, VK_MENU                         /* FFE7 */
-};
-
-static int AltGrMask;
-static int min_keycode, max_keycode;
-static int keyc2vkey [256];
-/* For example : keyc2vkey[10] is the VK_* associated with keycode10 */
-
-static WORD EVENT_event_to_vkey( XKeyEvent *e)
-{
-  static int keysyms_per_keycode;
-  int i;
-  KeySym keysym;
-
-  if (!keysyms_per_keycode) /* First time : Initialization */
-    {
-      KeySym *ksp;
-      XModifierKeymap *mmp;
-      KeyCode *kcp;
-      XKeyEvent e2;
-      WORD vkey, OEMvkey;
-
-      XDisplayKeycodes(e->display, &min_keycode, &max_keycode);
-      ksp = XGetKeyboardMapping(e->display, min_keycode,
-				max_keycode + 1 - min_keycode, &keysyms_per_keycode);
-      /* We are only interested in keysyms_per_keycode.
-	 There is no need to hold a local copy of the keysyms table */
-      XFree(ksp);
-      mmp = XGetModifierMapping(e->display);
-      kcp = mmp->modifiermap;
-      for (i = 0; i < 8; i += 1) /* There are 8 modifier keys */
-	{
-	  int j;
-
-	  for (j = 0; j < mmp->max_keypermod; j += 1, kcp += 1)
-	    if (*kcp)
-	      {
-		int k;
-
-		for (k = 0; k < keysyms_per_keycode; k += 1)
-		  if (XKeycodeToKeysym(e->display, *kcp, k)
-		      == XK_Mode_switch)
-		    {
-		      AltGrMask = 1 << i;
-		      dprintf_key(stddeb, "AltGrMask is %x\n", AltGrMask);
-		    }
-	      }
-	}
-      XFreeModifiermap(mmp);
-	
-	/* Now build two conversion arrays :
-	 * keycode -> vkey + extended
-	 * vkey + extended -> keycode */
-
-      e2.display = e->display;
-      e2.state = 0;
-
-      OEMvkey = 0xb9; /* first OEM virtual key available is ba */
-      for (e2.keycode=min_keycode; e2.keycode<=max_keycode; e2.keycode++)
-	{
-	  XLookupString(&e2, NULL, 0, &keysym, NULL);
-	  vkey = 0;
-	  if (keysym)  /* otherwise, keycode not used */
-	    {
-	      if ((keysym >> 8) == 0xFF)         /* non-character key */
-		{
-		  int key = keysym & 0xff;
-		
-		  if (key >= 0x08 && key <= 0x1B)         /* special key */
-		    vkey = special_key[key - 0x08];
-		  else if (key >= 0x50 && key <= 0x57)    /* cursor key */
-		    vkey = cursor_key[key - 0x50];
-		  else if (key >= 0x60 && key <= 0x6B)    /* miscellaneous key */
-		    vkey = misc_key[key - 0x60];
-		  else if (key >= 0x7E && key <= 0xB9)    /* keypad key */
-		    vkey = keypad_key[key - 0x7E];
-		  else if (key >= 0xBE && key <= 0xCD)    /* function key */
-		    {
-		      vkey = function_key[key - 0xBE];
-		      vkey |= 0x100; /* set extended bit */
-		    }
-		  else if (key >= 0xE1 && key <= 0xEA)    /* modifier key */
-		    vkey = modifier_key[key - 0xE1];
-		  else if (key == 0xFF)                   /* DEL key */
-		    vkey = VK_DELETE;
-		  /* extended must also be set for ALT_R, CTRL_R,
-		     INS, DEL, HOME, END, PAGE_UP, PAGE_DOWN, ARROW keys,
-		     keypad / and keypad ENTER (SDK 3.1 Vol.3 p 138) */
-		  switch (keysym)
-		    {
-		    case XK_Control_R :
-		    case XK_Alt_R :
-		    case XK_Insert :
-		    case XK_Delete :
-		    case XK_Home :
-		    case XK_End :
-		    case XK_Prior :
-		    case XK_Next :
-		    case XK_Left :
-		    case XK_Up :
-		    case XK_Right :
-		    case XK_Down :
-		    case XK_KP_Divide :
-		    case XK_KP_Enter :
-		      vkey |= 0x100;
-		    }
-		}
-	      for (i = 0; (i < keysyms_per_keycode) && (!vkey); i++)
-		{
-		  keysym = XLookupKeysym(&e2, i);
-		  if ((keysym >= VK_0 && keysym <= VK_9)
-		      || (keysym >= VK_A && keysym <= VK_Z)
-		      || keysym == VK_SPACE)
-		    vkey = keysym;
-		}
-
-	      if (!vkey)
-		{
-		  /* Others keys: let's assign OEM virtual key codes in the allowed range,
-		   * that is ([0xba,0xc0], [0xdb,0xe4], 0xe6 (given up) et [0xe9,0xf5]) */
-		  switch (++OEMvkey)
-		    {
-		    case 0xc1 : OEMvkey=0xdb; break;
-		    case 0xe5 : OEMvkey=0xe9; break;
-		    case 0xf6 : OEMvkey=0xf5; fprintf(stderr,"No more OEM vkey available!\n");
-		    }
-		  
-		  vkey = OEMvkey;
-		  
-		  if (debugging_keyboard)
-		    {
-		      fprintf(stddeb,"OEM specific virtual key %X assigned to keycode %X :\n ("
-			      ,OEMvkey,e2.keycode);
-		      for (i = 0; i < keysyms_per_keycode; i += 1)
-			{
-			  char	*ksname;
-			  
-			  keysym = XLookupKeysym(&e2, i);
-			  ksname = XKeysymToString(keysym);
-			  if (!ksname)
-			    ksname = "NoSymbol";
-			  fprintf(stddeb, "%lX (%s) ", keysym, ksname);
-			}
-		      fprintf(stddeb, ")\n");
-		    }
-		}
-	    }
-	  keyc2vkey[e2.keycode] = vkey;
-	} /* for */
-    } /* Initialization */
-  
-  return keyc2vkey[e->keycode];
-  
-}
-
-int EVENT_ToAscii(WORD wVirtKey, WORD wScanCode, LPSTR lpKeyState, 
-	LPVOID lpChar, WORD wFlags) 
-{
-    XKeyEvent e;
-    KeySym keysym;
-    static XComposeStatus cs;
-    int ret;
-    WORD keyc;
-
-    e.display = display;
-    e.keycode = 0;
-    for (keyc=min_keycode; keyc<=max_keycode; keyc++)
-      { /* this could be speed up by making another table, an array of struct vkey,keycode
-	 * (vkey -> keycode) with vkeys sorted .... but it takes memory (512*3 bytes)!  DF */
-	if ((keyc2vkey[keyc] & 0xFF)== wVirtKey) /* no need to make a more precise test (with the extended bit correctly set above wVirtKey ... VK* are different enough... */
-	  {
-	    if ((e.keycode) && ((wVirtKey<0x10) || (wVirtKey>0x12))) 
-		/* it's normal to have 2 shift, control, and alt ! */
-		dprintf_keyboard(stddeb,"Strange ... the keycodes %X and %X are matching!\n",
-				 e.keycode,keyc);
-	    e.keycode = keyc;
-	  }
-      }
-    if (!e.keycode) 
-      {
-	fprintf(stderr,"Unknown virtual key %X !!! \n",wVirtKey);
-	return wVirtKey; /* whatever */
-      }
-    e.state = 0;
-    if (lpKeyState[VK_SHIFT] & 0x80)
-	e.state |= ShiftMask;
-    if (lpKeyState[VK_CAPITAL] & 0x80)
-	e.state |= LockMask;
-    if (lpKeyState[VK_CONTROL] & 0x80)
-	if (lpKeyState[VK_MENU] & 0x80)
-	    e.state |= AltGrMask;
-	else
-	    e.state |= ControlMask;
-    if (lpKeyState[VK_NUMLOCK] & 0x80)
-	e.state |= Mod2Mask;
-    dprintf_key(stddeb, "EVENT_ToAscii(%04X, %04X) : faked state = %X\n",
-		wVirtKey, wScanCode, e.state);
-    ret = XLookupString(&e, lpChar, 2, &keysym, &cs);
-    if (ret == 0)
-	{
-	BYTE dead_char = 0;
-
-	((char*)lpChar)[1] = '\0';
-	switch (keysym)
-	    {
-	    case XK_dead_tilde :
-	    case 0x1000FE7E : /* Xfree's XK_Dtilde */
-		dead_char = '~';
-		break;
-	    case XK_dead_acute :
-	    case 0x1000FE27 : /* Xfree's XK_Dacute_accent */
-		dead_char = 0xb4;
-		break;
-	    case XK_dead_circumflex :
-	    case 0x1000FE5E : /* Xfree's XK_Dcircumflex_accent */
-		dead_char = '^';
-		break;
-	    case XK_dead_grave :
-	    case 0x1000FE60 : /* Xfree's XK_Dgrave_accent */
-		dead_char = '`';
-		break;
-	    case XK_dead_diaeresis :
-	    case 0x1000FE22 : /* Xfree's XK_Ddiaeresis */
-		dead_char = 0xa8;
-		break;
-	    }
-	if (dead_char)
-	    {
-	    *(char*)lpChar = dead_char;
-	    ret = -1;
-	    }
-	else
-	    {
-	    char	*ksname;
-
-	    ksname = XKeysymToString(keysym);
-	    if (!ksname)
-		ksname = "No Name";
-	    if ((keysym >> 8) != 0xff)
-		{
-		fprintf(stderr, "Please report : no char for keysym %04lX (%s) :\n",
-			keysym, ksname);
-		fprintf(stderr, "  wVirtKey = %X, wScanCode = %X, keycode = %X, state = %X\n",
-			wVirtKey, wScanCode, e.keycode, e.state);
-		}
-	    }
-	}
-    dprintf_key(stddeb, "EVENT_ToAscii about to return %d with char %x\n",
-		ret, *(char*)lpChar);
-    return ret;
-}
-
-typedef union
-{
-    struct
-    {
-	unsigned long count : 16;
-	unsigned long code : 8;
-	unsigned long extended : 1;
-	unsigned long unused : 2;
-	unsigned long win_internal : 2;
-	unsigned long context : 1;
-	unsigned long previous : 1;
-	unsigned long transition : 1;
-    } lp1;
-    unsigned long lp2;
-} KEYLP;
-
-static void EVENT_key( XKeyEvent *event )
-{
-    char Str[24]; 
-    XComposeStatus cs; 
-    KeySym keysym;
-    WORD vkey = 0;
-    KEYLP keylp;
-    WORD message;
-    static BOOL force_extended = FALSE; /* hack for AltGr translation */
-
-    int ascii_chars = XLookupString(event, Str, 1, &keysym, &cs);
-
-    dprintf_key(stddeb, "EVENT_key : state = %X\n", event->state);
-    if (keysym == XK_Mode_switch)
-	{
-	dprintf_key(stddeb, "Alt Gr key event received\n");
-	event->keycode = XKeysymToKeycode(event->display, XK_Control_L);
-	dprintf_key(stddeb, "Control_L is keycode 0x%x\n", event->keycode);
-	EVENT_key(event);
-	event->keycode = XKeysymToKeycode(event->display, XK_Alt_L);
-	dprintf_key(stddeb, "Alt_L is keycode 0x%x\n", event->keycode);
-	force_extended = TRUE;
-	EVENT_key(event);
-	force_extended = FALSE;
-	return;
-	}
-
-    Str[ascii_chars] = '\0';
-    if (debugging_key)
-	{
-	char	*ksname;
-
-	ksname = XKeysymToString(keysym);
-	if (!ksname)
-	    ksname = "No Name";
-	fprintf(stddeb, "%s : keysym=%lX (%s), ascii chars=%u / %X / '%s'\n", 
-	    event_names[event->type], keysym, ksname,
-	    ascii_chars, Str[0] & 0xff, Str);
-	}
-
-#if 0
-    /* Ctrl-Alt-Return enters the debugger */
-    if ((keysym == XK_Return) && (event->type == KeyPress) &&
-        (event->state & ControlMask) && (event->state & Mod1Mask))
-        DEBUG_EnterDebugger();
-#endif
-
-    vkey = EVENT_event_to_vkey(event);
-    if (force_extended) vkey |= 0x100;
-
-    dprintf_key(stddeb, "keycode 0x%x converted to vkey 0x%x\n",
-		    event->keycode, vkey);
-
-    keylp.lp1.count = 1;
-    keylp.lp1.code = LOBYTE(event->keycode) - 8;
-    keylp.lp1.extended = (vkey & 0x100 ? 1 : 0);
-    keylp.lp1.win_internal = 0; /* this has something to do with dialogs, 
-				* don't remember where I read it - AK */
-				/* it's '1' under windows, when a dialog box appears
-				 * and you press one of the underlined keys - DF*/
-    vkey &= 0xff;
-    if (event->type == KeyPress)
-    {
-	keylp.lp1.previous = (InputKeyStateTable[vkey] & 0x80) != 0;
-        if (!(InputKeyStateTable[vkey] & 0x80))
-            InputKeyStateTable[vkey] ^= 0x01;
-	InputKeyStateTable[vkey] |= 0x80;
-	keylp.lp1.transition = 0;
-	message = (InputKeyStateTable[VK_MENU] & 0x80)
-		    && !(InputKeyStateTable[VK_CONTROL] & 0x80)
-			 ? WM_SYSKEYDOWN : WM_KEYDOWN;
-    }
-    else
-    {
-	UINT sysKey = (InputKeyStateTable[VK_MENU] & 0x80)
-			&& !(InputKeyStateTable[VK_CONTROL] & 0x80)
-			&& (force_extended == FALSE); /* for Alt from AltGr */
-
-	InputKeyStateTable[vkey] &= ~0x80; 
-	keylp.lp1.previous = 1;
-	keylp.lp1.transition = 1;
-	message = sysKey ? WM_SYSKEYUP : WM_KEYUP;
-    }
-    keylp.lp1.context = ( (event->state & Mod1Mask)  || 
-			  (InputKeyStateTable[VK_MENU] & 0x80)) ? 1 : 0;
-    dprintf_key(stddeb,"            wParam=%04X, lParam=%08lX\n", 
-		vkey, keylp.lp2 );
-    dprintf_key(stddeb,"            InputKeyState=%X\n",
-		InputKeyStateTable[vkey]);
-
-    hardware_event( message, vkey, keylp.lp2, event->x_root - desktopX,
-	    event->y_root - desktopY, event->time - MSG_WineStartTicks, 0 );
+    KEYBOARD_HandleEvent( event );
 }
 
 
@@ -933,8 +524,8 @@
 static void EVENT_FocusIn (HWND hwnd, XFocusChangeEvent *event )
 {
     if (event->detail == NotifyPointer) return;
-    if (hwnd != GetActiveWindow()) WINPOS_ChangeActiveWindow( hwnd, FALSE );
-    if ((hwnd != GetFocus32()) && !IsChild( hwnd, GetFocus32()))
+    if (hwnd != GetActiveWindow32()) WINPOS_ChangeActiveWindow( hwnd, FALSE );
+    if ((hwnd != GetFocus32()) && !IsChild32( hwnd, GetFocus32()))
         SetFocus32( hwnd );
 }
 
@@ -947,8 +538,8 @@
 static void EVENT_FocusOut( HWND hwnd, XFocusChangeEvent *event )
 {
     if (event->detail == NotifyPointer) return;
-    if (hwnd == GetActiveWindow()) WINPOS_ChangeActiveWindow( 0, FALSE );
-    if ((hwnd == GetFocus32()) || IsChild( hwnd, GetFocus32()))
+    if (hwnd == GetActiveWindow32()) WINPOS_ChangeActiveWindow( 0, FALSE );
+    if ((hwnd == GetFocus32()) || IsChild32( hwnd, GetFocus32()))
         SetFocus32( 0 );
 }
 
@@ -1271,7 +862,7 @@
 {
     HWND32 hwndFocus = GetFocus32();
 
-    if (hwndFocus && IsChild( hWnd, hwndFocus ))
+    if (hwndFocus && IsChild32( hWnd, hwndFocus ))
       FOCUS_SetXFocus( (HWND32)hwndFocus );
 
     return;
diff --git a/windows/focus.c b/windows/focus.c
index 7d284d0..f40c5db 100644
--- a/windows/focus.c
+++ b/windows/focus.c
@@ -106,7 +106,7 @@
 	    return 0;
 
         /* activate hwndTop if needed. */
-	if (hwndTop != GetActiveWindow())
+	if (hwndTop != GetActiveWindow32())
 	{
 	    if (!WINPOS_SetActiveWindow(hwndTop, 0, 0)) return 0;
 
diff --git a/windows/keyboard.c b/windows/keyboard.c
index 1a418fd..12c3fce 100644
--- a/windows/keyboard.c
+++ b/windows/keyboard.c
@@ -3,22 +3,424 @@
  *
  * Copyright 1993 Bob Amstadt
  * Copyright 1996 Albrecht Kleine 
+ * Copyright 1997 David Faure
+ *
  */
-
+#include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
-#include "win.h"
-#include "windows.h"
-#include "accel.h"
-#include "stddebug.h"
-#include "debug.h"
+#include <ctype.h>
+#include <X11/keysym.h>
+#include <X11/Xlib.h>
+#include <X11/Xresource.h>
+#include <X11/Xutil.h>
+#include <X11/Xatom.h>
 
-extern BOOL MouseButtonsStates[3];
-extern BOOL AsyncMouseButtonsStates[3];
-extern BYTE InputKeyStateTable[256];
+#include "windows.h"
+#include "win.h"
+#include "gdi.h"
+#include "keyboard.h"
+#include "message.h"
+#include "stddebug.h"
+/* #define DEBUG_KEYBOARD */
+#include "debug.h"
+#include "xmalloc.h"
+#include "accel.h"
+
+BOOL32 MouseButtonsStates[3];
+BOOL32 AsyncMouseButtonsStates[3];
+BYTE InputKeyStateTable[256];
+BYTE QueueKeyStateTable[256];
 BYTE AsyncKeyStateTable[256];
 
-extern BYTE QueueKeyStateTable[256];
+static int NumLockMask;
+static int AltGrMask;
+static int min_keycode, max_keycode;
+static int keyc2vkey[256];
+
+typedef union
+{
+    struct
+    {
+	unsigned long count : 16;
+	unsigned long code : 8;
+	unsigned long extended : 1;
+	unsigned long unused : 2;
+	unsigned long win_internal : 2;
+	unsigned long context : 1;
+	unsigned long previous : 1;
+	unsigned long transition : 1;
+    } lp1;
+    unsigned long lp2;
+} KEYLP;
+
+typedef enum {OFF,INTERM,ON} ToggleKeyState;
+
+/* Keyboard translation tables */
+static const int special_key[] =
+{
+    VK_BACK, VK_TAB, 0, VK_CLEAR, 0, VK_RETURN, 0, 0,           /* FF08 */
+    0, 0, 0, VK_PAUSE, VK_SCROLL, 0, 0, 0,                      /* FF10 */
+    0, 0, 0, VK_ESCAPE                                          /* FF18 */
+};
+
+static const int cursor_key[] =
+{
+    VK_HOME, VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN, VK_PRIOR, 
+                                       VK_NEXT, VK_END          /* FF50 */
+};
+
+static const int misc_key[] =
+{
+    VK_SELECT, VK_SNAPSHOT, VK_EXECUTE, VK_INSERT, 0, 0, 0, 0,  /* FF60 */
+    VK_CANCEL, VK_HELP, VK_CANCEL, VK_MENU                      /* FF68 */
+};
+
+static const int keypad_key[] =
+{
+    0, VK_NUMLOCK,                                        	/* FF7E */
+    0, 0, 0, 0, 0, 0, 0, 0,                                     /* FF80 */
+    0, 0, 0, 0, 0, VK_RETURN, 0, 0,                             /* FF88 */
+    0, 0, 0, 0, 0, VK_HOME, VK_LEFT, VK_UP,                     /* FF90 */
+    VK_RIGHT, VK_DOWN, VK_PRIOR, VK_NEXT, VK_END, 0,
+				 VK_INSERT, VK_DELETE,          /* FF98 */
+    0, 0, 0, 0, 0, 0, 0, 0,                                     /* FFA0 */
+    0, 0, VK_MULTIPLY, VK_ADD, VK_SEPARATOR, VK_SUBTRACT, 
+                               VK_DECIMAL, VK_DIVIDE,           /* FFA8 */
+    VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4,
+                            VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, /* FFB0 */
+    VK_NUMPAD8, VK_NUMPAD9                                      /* FFB8 */
+};
+    
+static const int function_key[] =
+{
+    VK_F1, VK_F2,                                               /* FFBE */
+    VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10,    /* FFC0 */
+    VK_F11, VK_F12, VK_F13, VK_F14, VK_F15, VK_F16              /* FFC8 */
+};
+
+static const int modifier_key[] =
+{
+    VK_SHIFT, VK_SHIFT, VK_CONTROL, VK_CONTROL, VK_CAPITAL, 0, /* FFE1 */
+    VK_MENU, VK_MENU, VK_MENU, VK_MENU                         /* FFE7 */
+};
+
+
+static WORD EVENT_event_to_vkey( XKeyEvent *e)
+{
+    KeySym keysym;
+
+    XLookupString(e, NULL, 0, &keysym, NULL);
+
+    if ((keysym >= 0xFFAE) && (keysym <= 0xFFB9) && (e->state & NumLockMask)) 
+        /* Only the Keypad keys 0-9 and . send different keysyms
+         * depending on the NumLock state */
+        return keypad_key[(keysym & 0xFF) - 0x7E];
+
+    return keyc2vkey[e->keycode];
+}
+
+/**********************************************************************
+ *		KEYBOARD_Init
+ */
+BOOL32 KEYBOARD_Init(void)
+{
+    int i, keysyms_per_keycode;
+    KeySym *ksp;
+    XModifierKeymap *mmp;
+    KeySym keysym;
+    KeyCode *kcp;
+    XKeyEvent e2;
+    WORD vkey, OEMvkey;
+
+    XDisplayKeycodes(display, &min_keycode, &max_keycode);
+    ksp = XGetKeyboardMapping(display, min_keycode,
+                              max_keycode + 1 - min_keycode, &keysyms_per_keycode);
+    /* We are only interested in keysyms_per_keycode.
+       There is no need to hold a local copy of the keysyms table */
+    XFree(ksp);
+    mmp = XGetModifierMapping(display);
+    kcp = mmp->modifiermap;
+    for (i = 0; i < 8; i += 1) /* There are 8 modifier keys */
+    {
+        int j;
+        
+        for (j = 0; j < mmp->max_keypermod; j += 1, kcp += 1)
+	    if (*kcp)
+            {
+		int k;
+                
+		for (k = 0; k < keysyms_per_keycode; k += 1)
+                    if (XKeycodeToKeysym(display, *kcp, k) == XK_Mode_switch)
+		    {
+                        AltGrMask = 1 << i;
+                        dprintf_key(stddeb, "AltGrMask is %x\n", AltGrMask);
+		    }
+                    else if (XKeycodeToKeysym(display, *kcp, k) == XK_Num_Lock)
+		    {
+                        NumLockMask = 1 << i;
+                        dprintf_key(stddeb, "NumLockMask is %x\n", NumLockMask);
+		    }
+            }
+    }
+    XFreeModifiermap(mmp);
+
+    /* Now build two conversion arrays :
+     * keycode -> vkey + extended
+     * vkey + extended -> keycode */
+
+    e2.display = display;
+    e2.state = 0;
+
+    OEMvkey = 0xb9; /* first OEM virtual key available is ba */
+    for (e2.keycode=min_keycode; e2.keycode<=max_keycode; e2.keycode++)
+    {
+        XLookupString(&e2, NULL, 0, &keysym, NULL);
+        vkey = 0;
+        if (keysym)  /* otherwise, keycode not used */
+        {
+            if ((keysym >> 8) == 0xFF)         /* non-character key */
+            {
+                int key = keysym & 0xff;
+		
+                if (key >= 0x08 && key <= 0x1B)         /* special key */
+		    vkey = special_key[key - 0x08];
+                else if (key >= 0x50 && key <= 0x57)    /* cursor key */
+		    vkey = cursor_key[key - 0x50];
+                else if (key >= 0x60 && key <= 0x6B)    /* miscellaneous key */
+		    vkey = misc_key[key - 0x60];
+                else if (key >= 0x7E && key <= 0xB9)    /* keypad key */
+		    vkey = keypad_key[key - 0x7E];
+                else if (key >= 0xBE && key <= 0xCD)    /* function key */
+                {
+                    vkey = function_key[key - 0xBE];
+                    vkey |= 0x100; /* set extended bit */
+                }
+                else if (key >= 0xE1 && key <= 0xEA)    /* modifier key */
+		    vkey = modifier_key[key - 0xE1];
+                else if (key == 0xFF)                   /* DEL key */
+		    vkey = VK_DELETE;
+                /* extended must also be set for ALT_R, CTRL_R,
+                   INS, DEL, HOME, END, PAGE_UP, PAGE_DOWN, ARROW keys,
+                   keypad / and keypad ENTER (SDK 3.1 Vol.3 p 138) */
+                /* FIXME should we set extended bit for NumLock ? My
+                 * Windows does ... DF */
+                switch (keysym)
+                {
+                case XK_Control_R :
+                case XK_Alt_R :
+                case XK_Insert :
+                case XK_Delete :
+                case XK_Home :
+                case XK_End :
+                case XK_Prior :
+                case XK_Next :
+                case XK_Left :
+                case XK_Up :
+                case XK_Right :
+                case XK_Down :
+                case XK_KP_Divide :
+                case XK_KP_Enter :
+                    vkey |= 0x100;
+                }
+            }
+            for (i = 0; (i < keysyms_per_keycode) && (!vkey); i++)
+            {
+                keysym = XLookupKeysym(&e2, i);
+                if ((keysym >= VK_0 && keysym <= VK_9)
+                    || (keysym >= VK_A && keysym <= VK_Z)
+                    || keysym == VK_SPACE)
+		    vkey = keysym;
+            }
+
+            if (!vkey)
+            {
+                /* Others keys: let's assign OEM virtual key codes in the allowed range,
+                 * that is ([0xba,0xc0], [0xdb,0xe4], 0xe6 (given up) et [0xe9,0xf5]) */
+                switch (++OEMvkey)
+                {
+                case 0xc1 : OEMvkey=0xdb; break;
+                case 0xe5 : OEMvkey=0xe9; break;
+                case 0xf6 : OEMvkey=0xf5; fprintf(stderr,"No more OEM vkey available!\n");
+                }
+
+                vkey = OEMvkey;
+		  
+                if (debugging_keyboard)
+                {
+                    fprintf(stddeb,"OEM specific virtual key %X assigned to keycode %X :\n ("
+                            ,OEMvkey,e2.keycode);
+                    for (i = 0; i < keysyms_per_keycode; i += 1)
+                    {
+                        char	*ksname;
+                        
+                        keysym = XLookupKeysym(&e2, i);
+                        ksname = XKeysymToString(keysym);
+                        if (!ksname)
+			    ksname = "NoSymbol";
+                        fprintf(stddeb, "%lX (%s) ", keysym, ksname);
+                    }
+                    fprintf(stddeb, ")\n");
+                }
+            }
+        }
+        keyc2vkey[e2.keycode] = vkey;
+    } /* for */
+    return TRUE;
+}
+
+
+/***********************************************************************
+ *           KEYBOARD_HandleEvent
+ *
+ * Handle a X key event
+ */
+void KEYBOARD_HandleEvent( XKeyEvent *event )
+{
+    char Str[24]; 
+    XComposeStatus cs; 
+    KeySym keysym;
+    WORD vkey = 0;
+    KEYLP keylp;
+    WORD message;
+    static BOOL force_extended = FALSE; /* hack for AltGr translation */
+    BOOL DontPropagate;
+    ToggleKeyState * State;
+    static ToggleKeyState NumState=OFF, CapsState=OFF;
+
+    int ascii_chars = XLookupString(event, Str, 1, &keysym, &cs);
+
+    dprintf_key(stddeb, "EVENT_key : state = %X\n", event->state);
+    if (keysym == XK_Mode_switch)
+	{
+	dprintf_key(stddeb, "Alt Gr key event received\n");
+	event->keycode = XKeysymToKeycode(event->display, XK_Control_L);
+	dprintf_key(stddeb, "Control_L is keycode 0x%x\n", event->keycode);
+	KEYBOARD_HandleEvent(event);
+	event->keycode = XKeysymToKeycode(event->display, XK_Alt_L);
+	dprintf_key(stddeb, "Alt_L is keycode 0x%x\n", event->keycode);
+	force_extended = TRUE;
+	KEYBOARD_HandleEvent(event);
+	force_extended = FALSE;
+	return;
+	}
+
+    Str[ascii_chars] = '\0';
+    if (debugging_key)
+	{
+	char	*ksname;
+
+	ksname = XKeysymToString(keysym);
+	if (!ksname)
+	    ksname = "No Name";
+	fprintf(stddeb, "%s : keysym=%lX (%s), ascii chars=%u / %X / '%s'\n", 
+                (event->type == KeyPress) ? "KeyPress" : "KeyRelease",
+                keysym, ksname, ascii_chars, Str[0] & 0xff, Str);
+	}
+
+#if 0
+    /* Ctrl-Alt-Return enters the debugger */
+    if ((keysym == XK_Return) && (event->type == KeyPress) &&
+        (event->state & ControlMask) && (event->state & Mod1Mask))
+        DEBUG_EnterDebugger();
+#endif
+
+    vkey = EVENT_event_to_vkey(event);
+    if (force_extended) vkey |= 0x100;
+
+    dprintf_key(stddeb, "keycode 0x%x converted to vkey 0x%x\n",
+		    event->keycode, vkey);
+
+    if (vkey)
+    {
+    keylp.lp1.count = 1;
+    keylp.lp1.code = LOBYTE(event->keycode) - 8;
+    keylp.lp1.extended = (vkey & 0x100 ? 1 : 0);
+    keylp.lp1.win_internal = 0; /* this has something to do with dialogs, 
+				* don't remember where I read it - AK */
+				/* it's '1' under windows, when a dialog box appears
+				 * and you press one of the underlined keys - DF*/
+    vkey &= 0xff;
+    if (event->type == KeyPress)
+    {
+	keylp.lp1.previous = (InputKeyStateTable[vkey] & 0x80) != 0;
+        if (!(InputKeyStateTable[vkey] & 0x80))
+            InputKeyStateTable[vkey] ^= 0x01;
+	InputKeyStateTable[vkey] |= 0x80;
+	keylp.lp1.transition = 0;
+	message = (InputKeyStateTable[VK_MENU] & 0x80)
+		    && !(InputKeyStateTable[VK_CONTROL] & 0x80)
+			 ? WM_SYSKEYDOWN : WM_KEYDOWN;
+    }
+    else
+    {
+	UINT sysKey = (InputKeyStateTable[VK_MENU] & 0x80)
+			&& !(InputKeyStateTable[VK_CONTROL] & 0x80)
+			&& (force_extended == FALSE); /* for Alt from AltGr */
+
+	InputKeyStateTable[vkey] &= ~0x80; 
+	keylp.lp1.previous = 1;
+	keylp.lp1.transition = 1;
+	message = sysKey ? WM_SYSKEYUP : WM_KEYUP;
+    }
+    keylp.lp1.context = ( (event->state & Mod1Mask)  || 
+			  (InputKeyStateTable[VK_MENU] & 0x80)) ? 1 : 0;
+    DontPropagate = FALSE;
+    if ((vkey==VK_NUMLOCK) || (vkey==VK_CAPITAL))
+      {
+	
+	switch (*( State = (vkey==VK_NUMLOCK? &NumState : &CapsState))) {
+	case OFF:if (event->type==KeyPress)
+	  {
+	    dprintf_keyboard(stddeb,"OFF + Keypress => DOWN and UP generated. \n");
+	    hardware_event( message, vkey, keylp.lp2, event->x_root - desktopX,
+			    event->y_root - desktopY, event->time - MSG_WineStartTicks, 0);
+	    message += WM_KEYUP - WM_KEYDOWN; /* create a *UP message from the *DOWN one */
+	    keylp.lp1.previous = 1;
+	    keylp.lp1.transition = 1;
+	    *State = INTERM;
+	  } break;
+	case INTERM:
+	  /* The 'INTERM' state means : just after a 'press' event, if a 'release' event comes,
+	     don't "propagate" it. It's from the same key press. Then the state goes to ON.
+	     And from there, a 'release' event will switch off the toggle key. */
+	  DontPropagate = TRUE;
+	  *State=ON;
+	  InputKeyStateTable[vkey] |= 0x01; /* force to 'on' event if a release event was received */
+	  dprintf_keyboard(stddeb,"INTERM : don\'t propagate press/release of toggle key. InputKeyStateTable[%#x] = %#x",vkey,InputKeyStateTable[vkey]);
+	  break;
+	case ON: if (event->type==KeyPress) DontPropagate = TRUE; else
+	  {
+	    KEYLP downkeylp = keylp;
+	    dprintf_keyboard(stddeb,"ON + KeyRelease => generating DOWN msg before the UP\n");
+	    message += WM_KEYDOWN - WM_KEYUP; /* create the *DOWN from the *UP */
+	    downkeylp.lp1.previous = 0; /* ? */
+	    downkeylp.lp1.transition = 0;
+	    hardware_event( message, vkey, downkeylp.lp2, event->x_root - desktopX,
+			    event->y_root - desktopY, event->time - MSG_WineStartTicks, 0);
+	    message += WM_KEYUP - WM_KEYDOWN; /* back to the UP message */
+            *State=OFF;
+	  } break;
+	}
+	dprintf_keyboard(stddeb,"Internal State : %d (0=OFF 1=INTERM 2=ON). InputTable state : %#x \n",*State,InputKeyStateTable[vkey]);
+      } else {
+	if (NumState == INTERM) NumState = ON;
+	if (CapsState == INTERM) CapsState = ON;
+      }
+    
+    if (!DontPropagate)
+      {
+	dprintf_key(stddeb,"            wParam=%04X, lParam=%08lX\n", 
+		    vkey, keylp.lp2 );
+	dprintf_key(stddeb,"            InputKeyState=%X\n",
+		    InputKeyStateTable[vkey]);
+
+	hardware_event( message, vkey, keylp.lp2, event->x_root - desktopX,
+			event->y_root - desktopY, event->time - MSG_WineStartTicks, 0 );
+      }
+    }
+}
+
 
 /**********************************************************************
  *		GetKeyState			[USER.106]
@@ -201,7 +603,7 @@
          if (GetCapture16())
            mesg=2;
          else
-          if (!IsWindowEnabled(hWnd))
+          if (!IsWindowEnabled16(hWnd))
             mesg=3;
           else
           {
@@ -226,7 +628,7 @@
             {
               if (iStat!=-1)
               {
-                if (IsIconic(hWnd))
+                if (IsIconic32(hWnd))
                   mesg=5;
                 else
                 {
@@ -268,3 +670,264 @@
     GlobalUnlock16(hAccel);
     return 0;
 }
+
+
+DWORD OemKeyScan(WORD wOemChar)
+{
+    dprintf_keyboard(stddeb,"*OemKeyScan (%d)\n",wOemChar);
+
+    return wOemChar;
+}
+
+/* VkKeyScan translates an ANSI character to a virtual-key and shift code
+ * for the current keyboard.
+ * FIXME high-order byte should yield :
+ *	0	Unshifted
+ *	1	Shift
+ *	2	Ctrl
+ *	3-5	Shift-key combinations that are not used for characters
+ *	6	Ctrl-Alt
+ *	7	Ctrl-Alt-Shift
+ *	I.e. :	Shift = 1, Ctrl = 2, Alt = 4.
+ */
+
+WORD VkKeyScan(WORD cChar)
+{
+	KeyCode keycode;
+    	dprintf_keyboard(stddeb,"VkKeyScan '%c'(%d) ",cChar,cChar);
+	
+/* let's do this : char = keysym (for ANSI chars) -> keyc [ + shift ... (?? how ??)]
+keyc -> (keyc2vkey) vkey */
+
+	keycode = XKeysymToKeycode(display, cChar & 0xFF);
+	
+	dprintf_keyboard(stddeb," ... got keycode 0x%x ... returning 0x%x\n",
+			 keycode,keyc2vkey[keycode]);
+	return keyc2vkey[keycode];
+}
+
+WORD VkKeyScan32W(WORD cChar)
+{
+	/* lower part of cChar is used anyway */
+	return VkKeyScan(cChar);
+}
+
+int GetKeyboardType(int nTypeFlag)
+{
+  dprintf_keyboard(stddeb,"GetKeyboardType(%d)\n",nTypeFlag);
+  switch(nTypeFlag)
+    {
+    case 0:      /* Keyboard type */
+      return 4;    /* AT-101 */
+      break;
+    case 1:      /* Keyboard Subtype */
+      return 0;    /* There are no defined subtypes */
+      break;
+    case 2:      /* Number of F-keys */
+      return 12;   /* We're doing an 101 for now, so return 12 F-keys */
+      break;
+    default:     
+      fprintf(stderr, "Unknown type on GetKeyboardType\n");
+      return 0;    /* The book says 0 here, so 0 */
+    }
+}
+
+/* MapVirtualKey translates keycodes from one format to another. */
+
+WORD MapVirtualKey(WORD wCode, WORD wMapType)
+{
+#define returnMVK(value) { dprintf_keyboard(stddeb,"returning 0x%x.\n",value); return value; }
+
+	dprintf_keyboard(stddeb,"MapVirtualKey wCode=0x%x wMapType=%d ... ",wCode,wMapType);
+	switch(wMapType) {
+		case 0:	{ /* vkey-code to scan-code */
+			/* let's do vkey -> keycode -> scan */
+			KeyCode keyc;
+			for (keyc=min_keycode; keyc<=max_keycode; keyc++) /* see event.c */
+				if ((keyc2vkey[keyc] & 0xFF)== wCode)
+					returnMVK (keyc - 8);
+		        return 0; }
+
+		case 1: /* scan-code to vkey-code */
+			/* let's do scan -> keycode -> vkey */
+
+			returnMVK (keyc2vkey[(wCode & 0xFF) + 8]);
+
+		case 2: { /* vkey-code to unshifted ANSI code */
+			/* (was FIXME) : what does unshifted mean ? 'a' or 'A' ? */
+		        /* My Windows returns 'A'. */
+			/* let's do vkey -> keycode -> (XLookupString) ansi char */
+			XKeyEvent e;
+			KeySym keysym;
+			char s[2];
+			e.display = display;
+			e.state = 0; /* unshifted */
+			e.keycode = MapVirtualKey( wCode, 0);
+			if (!XLookupString(&e, s , 2 , &keysym, NULL))
+			  returnMVK (*s);
+			
+			return 0;
+			}
+		default: /* reserved */
+			fprintf(stderr, "MapVirtualKey: unknown wMapType %d !\n",
+				wMapType);
+			return 0;	
+	}
+	return 0;
+}
+
+int GetKbCodePage(void)
+{
+    	dprintf_keyboard(stddeb,"GetKbCodePage()\n");
+	return 850;
+}
+
+/****************************************************************************
+ *	GetKeyNameText32W   (USER32.247)
+ */
+INT32 GetKeyNameText32W(LONG lParam, LPWSTR lpBuffer, INT32 nSize)
+{
+	LPSTR buf = xmalloc(nSize);
+	int	res = GetKeyNameText32A(lParam,buf,nSize);
+
+	lstrcpynAtoW(lpBuffer,buf,nSize);
+	free(buf);
+	return res;
+}
+
+/****************************************************************************
+ *	GetKeyNameText32A   (USER32.246)
+ */
+INT32 GetKeyNameText32A(LONG lParam, LPSTR lpBuffer, INT32 nSize)
+{
+	return GetKeyNameText16(lParam,lpBuffer,nSize);
+}
+
+/****************************************************************************
+ *	GetKeyNameText16   (KEYBOARD.133)
+ */
+INT16 GetKeyNameText16(LONG lParam, LPSTR lpBuffer, INT16 nSize)
+{
+  /*	int i; */
+	
+    	dprintf_keyboard(stddeb,"GetKeyNameText(%ld,<ptr>,%d)\n",lParam,nSize);
+
+	lParam >>= 16;
+	lParam &= 0xff;
+
+	/*	for (i = 0 ; i != KeyTableSize ; i++) 
+		if (KeyTable[i].scancode == lParam)  {
+			lstrcpyn32A( lpBuffer, KeyTable[i].name, nSize );
+			return strlen(lpBuffer);
+		}
+		*/
+	/* FIXME ! GetKeyNameText is still to do...
+ */
+	*lpBuffer = 0;
+	return 0;
+}
+
+int ToAscii(WORD wVirtKey, WORD wScanCode, LPSTR lpKeyState, 
+	LPVOID lpChar, WORD wFlags) 
+{
+    XKeyEvent e;
+    KeySym keysym;
+    static XComposeStatus cs;
+    int ret;
+    WORD keyc;
+
+    e.display = display;
+    e.keycode = 0;
+    for (keyc=min_keycode; keyc<=max_keycode; keyc++)
+      { /* this could be speeded up by making another table, an array of struct vkey,keycode
+	 * (vkey -> keycode) with vkeys sorted .... but it takes memory (512*3 bytes)!  DF */
+	if ((keyc2vkey[keyc] & 0xFF)== wVirtKey) /* no need to make a more precise test (with the extended bit correctly set above wVirtKey ... VK* are different enough... */
+	  {
+	    if ((e.keycode) && ((wVirtKey<0x10) || (wVirtKey>0x12))) 
+		/* it's normal to have 2 shift, control, and alt ! */
+		dprintf_keyboard(stddeb,"ToAscii : The keycodes %X and %X are matching the same vkey %X\n",
+				 e.keycode,keyc,wVirtKey);
+	    e.keycode = keyc;
+	  }
+      }
+    if ((!e.keycode) && (lpKeyState[VK_NUMLOCK] & 0x01)) 
+      {
+	if ((wVirtKey>=VK_NUMPAD0) && (wVirtKey<=VK_NUMPAD9))
+	  e.keycode = XKeysymToKeycode(e.display, wVirtKey-VK_NUMPAD0+XK_KP_0);
+	if (wVirtKey==VK_DECIMAL)
+	  e.keycode = XKeysymToKeycode(e.display, XK_KP_Decimal);
+      }
+    if (!e.keycode)
+      {
+	fprintf(stderr,"ToAscii : Unknown virtual key %X !!! \n",wVirtKey);
+	return wVirtKey; /* whatever */
+      }
+    e.state = 0;
+    if (lpKeyState[VK_SHIFT] & 0x80)
+	e.state |= ShiftMask;
+    dprintf_keyboard(stddeb,"ToAscii : lpKeyState[0x14(VK_CAPITAL)]=%#x\n",lpKeyState[VK_CAPITAL]);
+    if (lpKeyState[VK_CAPITAL] & 0x01)
+	e.state |= LockMask;
+    if (lpKeyState[VK_CONTROL] & 0x80)
+	if (lpKeyState[VK_MENU] & 0x80)
+	    e.state |= AltGrMask;
+	else
+	    e.state |= ControlMask;
+    if (lpKeyState[VK_NUMLOCK] & 0x01)
+	e.state |= NumLockMask;
+    dprintf_key(stddeb, "ToAscii(%04X, %04X) : faked state = %X\n",
+		wVirtKey, wScanCode, e.state);
+    ret = XLookupString(&e, lpChar, 2, &keysym, &cs);
+    if (ret == 0)
+	{
+	BYTE dead_char = 0;
+
+	((char*)lpChar)[1] = '\0';
+	switch (keysym)
+	    {
+	    case XK_dead_tilde :
+	    case 0x1000FE7E : /* Xfree's XK_Dtilde */
+		dead_char = '~';
+		break;
+	    case XK_dead_acute :
+	    case 0x1000FE27 : /* Xfree's XK_Dacute_accent */
+		dead_char = 0xb4;
+		break;
+	    case XK_dead_circumflex :
+	    case 0x1000FE5E : /* Xfree's XK_Dcircumflex_accent */
+		dead_char = '^';
+		break;
+	    case XK_dead_grave :
+	    case 0x1000FE60 : /* Xfree's XK_Dgrave_accent */
+		dead_char = '`';
+		break;
+	    case XK_dead_diaeresis :
+	    case 0x1000FE22 : /* Xfree's XK_Ddiaeresis */
+		dead_char = 0xa8;
+		break;
+	    }
+	if (dead_char)
+	    {
+	    *(char*)lpChar = dead_char;
+	    ret = -1;
+	    }
+	else
+	    {
+	    char	*ksname;
+
+	    ksname = XKeysymToString(keysym);
+	    if (!ksname)
+		ksname = "No Name";
+	    if ((keysym >> 8) != 0xff)
+		{
+		fprintf(stderr, "Please report : no char for keysym %04lX (%s) :\n",
+			keysym, ksname);
+		fprintf(stderr, "  wVirtKey = %X, wScanCode = %X, keycode = %X, state = %X\n",
+			wVirtKey, wScanCode, e.keycode, e.state);
+		}
+	    }
+	}
+    dprintf_key(stddeb, "ToAscii about to return %d with char %x\n",
+		ret, *(char*)lpChar);
+    return ret;
+}
diff --git a/windows/mdi.c b/windows/mdi.c
index f6e5bac..558f9ce 100644
--- a/windows/mdi.c
+++ b/windows/mdi.c
@@ -284,7 +284,7 @@
  */
 WORD MDIIconArrange(HWND parent)
 {
-  return ArrangeIconicWindows(parent);		/* Any reason why the    */
+  return ArrangeIconicWindows16(parent);	/* Any reason why the    */
 						/* existing icon arrange */
 						/* can't be used here?	 */
 						/* -DRP			 */
@@ -333,7 +333,7 @@
 	if( style & WS_MAXIMIZE )
 	  SendMessage16(w->hwndSelf, WM_SETREDRAW, FALSE, 0L );
 	hwndMax = ci->hwndChildMaximized;
-	ShowWindow( hwndMax, SW_SHOWNOACTIVATE );
+	ShowWindow16( hwndMax, SW_SHOWNOACTIVATE );
 	if( style & WS_MAXIMIZE )
 	  SendMessage16(w->hwndSelf, WM_SETREDRAW, TRUE, 0L );
       }
@@ -365,10 +365,10 @@
 
 	MDI_MenuModifyItem(w ,hwnd); 
 	if( wnd->dwStyle & WS_MINIMIZE && ci->hwndActiveChild )
-	    ShowWindow( hwnd, SW_SHOWMINNOACTIVE );
+	    ShowWindow16( hwnd, SW_SHOWMINNOACTIVE );
 	else
 	  {
-	    SetWindowPos( hwnd, 0, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE );
+	    SetWindowPos32( hwnd, 0, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE );
 
 	    /* Set maximized state here in case hwnd didn't receive WM_SIZE
 	     * during CreateWindow - bad!
@@ -388,7 +388,7 @@
 	ci->nActiveChildren--;
 	DeleteMenu32(ci->hWindowMenu,wIDmenu,MF_BYCOMMAND);
 	if( IsWindow(hwndMax) )
-	    ShowWindow(hwndMax, SW_SHOWMAXIMIZED);
+	    ShowWindow16(hwndMax, SW_SHOWMAXIMIZED);
     }
 	
     return hwnd;
@@ -453,16 +453,16 @@
 	      w->dwStyle &= ~WS_VISIBLE;
 	    }
 
-	  SetWindowPos( hwndTo, HWND_TOP, 0, 0, 0, 0, 
+	  SetWindowPos32( hwndTo, HWND_TOP, 0, 0, 0, 0, 
 			SWP_NOMOVE | SWP_NOSIZE );
 	  if( !wTo && hwndPrev )
 	    {
-	       SetWindowPos( hwndPrev, HWND_BOTTOM, 0, 0, 0, 0, 
+	       SetWindowPos32( hwndPrev, HWND_BOTTOM, 0, 0, 0, 0, 
 		  	     SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
 	    }
 
 	  if( bOptimize )
-	       ShowWindow( clientHwnd, SW_SHOW );
+	       ShowWindow16( clientHwnd, SW_SHOW );
 	}
 }
 
@@ -483,7 +483,7 @@
 
 	    if( child == ci->hwndActiveChild )
 	      {
-		ShowWindow( child, SW_HIDE);
+		ShowWindow16( child, SW_HIDE);
 		if( child == ci->hwndChildMaximized )
 		  {
 		    MDI_RestoreFrameMenu(w_parent->parent, child);
@@ -502,8 +502,8 @@
 
         if (flagDestroy)
 	   {
-	     MDI_PostUpdate(GetParent16(child), ci, SB_BOTH+1);
-            DestroyWindow(child);
+	    MDI_PostUpdate(GetParent16(child), ci, SB_BOTH+1);
+            DestroyWindow32(child);
 	   }
     }
 
@@ -531,7 +531,7 @@
 
     dprintf_mdi(stddeb,"MDI_ChildActivate: %04x\n", hWndChild);
 
-    if( GetActiveWindow() == clientPtr->parent->hwndSelf )
+    if( GetActiveWindow32() == clientPtr->parent->hwndSelf )
         isActiveFrameWnd = TRUE;
 	
     /* deactivate prev. active child */
@@ -560,10 +560,10 @@
         if( hWndChild )
 	        {
 		  clientInfo->hwndActiveChild = hWndChild;
-		  ShowWindow( hWndChild, SW_SHOWMAXIMIZED);
+		  ShowWindow16( hWndChild, SW_SHOWMAXIMIZED);
 	        }
 	else
-		ShowWindow( clientInfo->hwndActiveChild, 
+		ShowWindow16( clientInfo->hwndActiveChild, 
 			    SW_SHOWNORMAL );
 
     clientInfo->hwndActiveChild = hWndChild;
@@ -582,7 +582,7 @@
                                wndPtr->wIDmenu, MF_CHECKED);
 
     /* bring active child to the top */
-    SetWindowPos( hWndChild, 0,0,0,0,0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
+    SetWindowPos32( hWndChild, 0,0,0,0,0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
 
     if( isActiveFrameWnd )
 	  {
@@ -696,7 +696,7 @@
     POINT16       pos[2];
   
     if (ci->hwndChildMaximized)
-        ShowWindow( ci->hwndChildMaximized, SW_NORMAL);
+        ShowWindow16( ci->hwndChildMaximized, SW_NORMAL);
 
     if (ci->nActiveChildren == 0) return 0;
 
@@ -714,8 +714,8 @@
 	if( listTop->hChild )
         {
             MDI_CalcDefaultChildPos(clientWnd, n++, pos, delta);
-            SetWindowPos(listTop->hChild, 0, pos[0].x, pos[0].y, pos[1].x, pos[1].y,
-                         SWP_DRAWFRAME | SWP_NOACTIVATE | SWP_NOZORDER);
+            SetWindowPos32(listTop->hChild, 0, pos[0].x, pos[0].y, pos[1].x, pos[1].y,
+                           SWP_DRAWFRAME | SWP_NOACTIVATE | SWP_NOZORDER);
         }
 
 	listPrev = listTop->prev;
@@ -724,7 +724,7 @@
     }
 
     if( iToPosition < ci->nActiveChildren )
-        ArrangeIconicWindows( clientWnd->hwndSelf );
+        ArrangeIconicWindows32( clientWnd->hwndSelf );
 
     return 0;
 }
@@ -745,7 +745,7 @@
     INT16	  iToPosition = 0;
 
     if (ci->hwndChildMaximized)
-	ShowWindow(ci->hwndChildMaximized, SW_NORMAL);
+	ShowWindow16(ci->hwndChildMaximized, SW_NORMAL);
 
     if (ci->nActiveChildren == 0) return 0;
 
@@ -804,8 +804,8 @@
     	            free(listTop);
     	            listTop = listPrev;
     	        }                
-                SetWindowPos(listTop->hChild, 0, x, y, xsize, ysize, 
-                             SWP_DRAWFRAME | SWP_NOACTIVATE | SWP_NOZORDER);
+                SetWindowPos32(listTop->hChild, 0, x, y, xsize, ysize, 
+                               SWP_DRAWFRAME | SWP_NOACTIVATE | SWP_NOZORDER);
                 y += ysize;
     	        listPrev = listTop->prev;
     	        free(listTop);
@@ -824,7 +824,7 @@
     }
     
     if (iToPosition < ci->nActiveChildren )
-        ArrangeIconicWindows( wndClient->hwndSelf );
+        ArrangeIconicWindows32( wndClient->hwndSelf );
 
     return 0;
 }
@@ -959,8 +959,8 @@
 
  DEFWND_SetText( frameWnd, lpBuffer );
  if( repaint == MDI_REPAINTFRAME)
-     SetWindowPos(frameWnd->hwndSelf, 0,0,0,0,0, SWP_FRAMECHANGED |
-                  SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER );
+     SetWindowPos32(frameWnd->hwndSelf, 0,0,0,0,0, SWP_FRAMECHANGED |
+                    SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER );
 }
 
 
@@ -1029,7 +1029,7 @@
 
       case WM_MDIACTIVATE:
         if( ci->hwndActiveChild != (HWND)wParam )
-	    SetWindowPos((HWND)wParam, 0,0,0,0,0, SWP_NOSIZE | SWP_NOMOVE ); 
+	    SetWindowPos32((HWND)wParam, 0,0,0,0,0, SWP_NOSIZE | SWP_NOMOVE ); 
 	return 0;
 
       case WM_MDICASCADE:
@@ -1053,7 +1053,7 @@
 	return 0;
 	
       case WM_MDIMAXIMIZE:
-	ShowWindow((HWND)wParam, SW_MAXIMIZE);
+	ShowWindow16((HWND16)wParam, SW_MAXIMIZE);
 	return 0;
 
       case WM_MDINEXT:
@@ -1061,7 +1061,7 @@
 	break;
 	
       case WM_MDIRESTORE:
-	ShowWindow( (HWND)wParam, SW_NORMAL);
+	ShowWindow16( (HWND16)wParam, SW_NORMAL);
 	return 0;
 
       case WM_MDISETMENU:
@@ -1115,7 +1115,7 @@
                 if( wnd->owner ) child = wnd->owner->hwndSelf;
 
                 if( child != ci->hwndActiveChild )
-                    SetWindowPos(child, 0,0,0,0,0, SWP_NOSIZE | SWP_NOMOVE );
+                    SetWindowPos32(child, 0,0,0,0,0, SWP_NOSIZE | SWP_NOMOVE );
               }
           }
         return 0;
@@ -1127,8 +1127,8 @@
 	     RECT16	rect  = { 0, 0, LOWORD(lParam), HIWORD(lParam) };
 
 	     AdjustWindowRectEx16(&rect, child->dwStyle, 0, child->dwExStyle);
-	     MoveWindow(ci->hwndChildMaximized, rect.left, rect.top,
-			rect.right - rect.left, rect.bottom - rect.top, 1);
+	     MoveWindow16(ci->hwndChildMaximized, rect.left, rect.top,
+			  rect.right - rect.left, rect.bottom - rect.top, 1);
 	  }
 	else
 	  MDI_PostUpdate(hwnd, ci, SB_BOTH+1);
@@ -1213,8 +1213,8 @@
 	    break;
 
 	  case WM_SIZE:
-	    MoveWindow(hwndMDIClient, 0, 0, 
-		       LOWORD(lParam), HIWORD(lParam), TRUE);
+	    MoveWindow16(hwndMDIClient, 0, 0, 
+		         LOWORD(lParam), HIWORD(lParam), TRUE);
 	    break;
 
 	  case WM_NEXTMENU:
@@ -1414,7 +1414,7 @@
 	       SendMessage16( hMaxChild, WM_SETREDRAW, FALSE, 0L );
 
 	       MDI_RestoreFrameMenu( clientWnd->parent, hMaxChild);
-	       ShowWindow( hMaxChild, SW_SHOWNOACTIVATE);
+	       ShowWindow16( hMaxChild, SW_SHOWNOACTIVATE);
 
 	       SendMessage16( hMaxChild, WM_SETREDRAW, TRUE, 0L );
 	      }
@@ -1640,8 +1640,8 @@
 	case SB_BOTH:
 			SCROLL_SetNCSbState( Wnd, vmin, vmax, vpos,
 						  hmin, hmax, hpos);
-			SetWindowPos(hwnd, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE
-                                 | SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED );
+			SetWindowPos32(hwnd, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE
+                                       | SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED );
       }    
 }
 
diff --git a/windows/message.c b/windows/message.c
index 203d7e8..7358f4b 100644
--- a/windows/message.c
+++ b/windows/message.c
@@ -16,6 +16,7 @@
 #include "sysmetrics.h"
 #include "heap.h"
 #include "hook.h"
+#include "keyboard.h"
 #include "spy.h"
 #include "winpos.h"
 #include "atom.h"
@@ -35,13 +36,6 @@
 typedef enum { SYSQ_MSG_ABANDON, SYSQ_MSG_SKIP, 
                SYSQ_MSG_ACCEPT, SYSQ_MSG_CONTINUE } SYSQ_STATUS;
 
-extern BOOL MouseButtonsStates[3];
-extern BOOL AsyncMouseButtonsStates[3];
-extern BYTE InputKeyStateTable[256];
-extern BYTE AsyncKeyStateTable[256];
-
-BYTE QueueKeyStateTable[256];
-
 extern MESSAGEQUEUE *pCursorQueue;			 /* queue.c */
 extern MESSAGEQUEUE *pActiveQueue;
 
@@ -121,7 +115,7 @@
 	/* check if hWnd is within hWndScope */
 
     if( hWndScope && hWnd != hWndScope )
-	if( !IsChild(hWndScope, hWnd) ) return SYSQ_MSG_CONTINUE;
+	if( !IsChild16(hWndScope, hWnd) ) return SYSQ_MSG_CONTINUE;
 
     if( mouseClick )
     {
@@ -203,7 +197,7 @@
 
             /* Activate the window if needed */
 
-            if (hWnd != GetActiveWindow() && hWnd != GetDesktopWindow16())
+            if (hWnd != GetActiveWindow16() && hWnd != GetDesktopWindow16())
             {
                 LONG ret = SendMessage16( hWnd, WM_MOUSEACTIVATE, hwndTop,
                                           MAKELONG( hittest, message ) );
@@ -212,7 +206,7 @@
                          eatMsg = TRUE;
 
                 if (((ret == MA_ACTIVATE) || (ret == MA_ACTIVATEANDEAT)) 
-                      && hwndTop != GetActiveWindow() )
+                      && hwndTop != GetActiveWindow16() )
                       if (!WINPOS_SetActiveWindow( hwndTop, TRUE , TRUE ))
 			 eatMsg = TRUE;
             }
@@ -252,7 +246,7 @@
 	  /* Send the message to the active window instead,  */
 	  /* translating messages to their WM_SYS equivalent */
 
-	hWnd = GetActiveWindow();
+	hWnd = GetActiveWindow16();
 
 	if( message < WM_SYSKEYDOWN )
 	    message += WM_SYSKEYDOWN - WM_KEYDOWN;
@@ -270,7 +264,7 @@
     }
 
     if (hWndScope && hWnd != hWndScope)
-	if (!IsChild(hWndScope, hWnd)) return SYSQ_MSG_CONTINUE;
+	if (!IsChild16(hWndScope, hWnd)) return SYSQ_MSG_CONTINUE;
     if (!MSG_CheckFilter(message, filter)) return SYSQ_MSG_CONTINUE;
 
     msg->hwnd = hWnd;
@@ -760,7 +754,7 @@
                     msg->wParam = 1;
                 }
 
-                if( !hwnd || msg->hwnd == hwnd || IsChild(hwnd,msg->hwnd) )
+                if( !hwnd || msg->hwnd == hwnd || IsChild16(hwnd,msg->hwnd) )
                 {
                     if( wndPtr->flags & WIN_INTERNAL_PAINT && !wndPtr->hrgnUpdate)
                     {
diff --git a/windows/msgbox.c b/windows/msgbox.c
index 40d9344..f5a5d26 100644
--- a/windows/msgbox.c
+++ b/windows/msgbox.c
@@ -42,33 +42,33 @@
    case WM_INITDIALOG:
     lpmb = (LPMSGBOX)lParam;
     if (lpmb->title) SetWindowText32A(hwnd, lpmb->title);
-    SetWindowText32A(GetDlgItem(hwnd, 100), lpmb->text);
+    SetWindowText32A(GetDlgItem32(hwnd, 100), lpmb->text);
     /* Hide not selected buttons */
     switch(lpmb->type & MB_TYPEMASK) {
      case MB_OK:
-      ShowWindow(GetDlgItem(hwnd, 2), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 2), SW_HIDE);
       /* fall through */
      case MB_OKCANCEL:
-      ShowWindow(GetDlgItem(hwnd, 3), SW_HIDE);
-      ShowWindow(GetDlgItem(hwnd, 4), SW_HIDE);
-      ShowWindow(GetDlgItem(hwnd, 5), SW_HIDE);
-      ShowWindow(GetDlgItem(hwnd, 6), SW_HIDE);
-      ShowWindow(GetDlgItem(hwnd, 7), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 3), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 4), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 5), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 6), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 7), SW_HIDE);
       break;
      case MB_ABORTRETRYIGNORE:
-      ShowWindow(GetDlgItem(hwnd, 1), SW_HIDE);
-      ShowWindow(GetDlgItem(hwnd, 2), SW_HIDE);
-      ShowWindow(GetDlgItem(hwnd, 6), SW_HIDE);
-      ShowWindow(GetDlgItem(hwnd, 7), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 1), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 2), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 6), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 7), SW_HIDE);
       break;
      case MB_YESNO:
-      ShowWindow(GetDlgItem(hwnd, 2), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 2), SW_HIDE);
       /* fall through */
      case MB_YESNOCANCEL:
-      ShowWindow(GetDlgItem(hwnd, 1), SW_HIDE);
-      ShowWindow(GetDlgItem(hwnd, 3), SW_HIDE);
-      ShowWindow(GetDlgItem(hwnd, 4), SW_HIDE);
-      ShowWindow(GetDlgItem(hwnd, 5), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 1), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 3), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 4), SW_HIDE);
+      ShowWindow32(GetDlgItem32(hwnd, 5), SW_HIDE);
       break;
     }
     /* Set the icon */
@@ -100,23 +100,23 @@
     borheight -= rect.bottom - rect.top;
 
     /* Get the icon height */
-    GetWindowRect32(GetDlgItem(hwnd, 1088), &rect);
+    GetWindowRect32(GetDlgItem32(hwnd, 1088), &rect);
     iheight = rect.bottom - rect.top;
     
     /* Get the number of visible buttons and their width */
-    GetWindowRect32(GetDlgItem(hwnd, 2), &rect);
+    GetWindowRect32(GetDlgItem32(hwnd, 2), &rect);
     bheight = rect.bottom - rect.top;
     bwidth = rect.left;
-    GetWindowRect32(GetDlgItem(hwnd, 1), &rect);
+    GetWindowRect32(GetDlgItem32(hwnd, 1), &rect);
     bwidth -= rect.left;
     for (buttons = 0, i = 1; i < 8; i++)
     {
-      hItem = GetDlgItem(hwnd, i);
+      hItem = GetDlgItem32(hwnd, i);
       if (GetWindowLong32A(hItem, GWL_STYLE) & WS_VISIBLE) buttons++;
     }
     
     /* Get the text size */
-    hItem = GetDlgItem(hwnd, 100);
+    hItem = GetDlgItem32(hwnd, 100);
     GetWindowRect32(hItem, &textrect);
     MapWindowPoints32(0, hwnd, (LPPOINT32)&textrect, 2);
     
@@ -129,34 +129,34 @@
     ReleaseDC32(hItem, hdc);
     
     /* Position the text */
-    SetWindowPos(hItem, 0, textrect.left, (tiheight - theight) / 2, 
-		 rect.right - rect.left, theight,
-		 SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);
+    SetWindowPos32(hItem, 0, textrect.left, (tiheight - theight) / 2, 
+		   rect.right - rect.left, theight,
+		   SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);
     
     /* Position the icon */
-    hItem = GetDlgItem(hwnd, 1088);
+    hItem = GetDlgItem32(hwnd, 1088);
     GetWindowRect32(hItem, &rect);
     MapWindowPoints32(0, hwnd, (LPPOINT32)&rect, 2);
-    SetWindowPos(hItem, 0, rect.left, (tiheight - iheight) / 2, 0, 0,
-		 SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);
+    SetWindowPos32(hItem, 0, rect.left, (tiheight - iheight) / 2, 0, 0,
+		   SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);
     
     /* Resize the window */
-    SetWindowPos(hwnd, 0, 0, 0, wwidth, 8 + tiheight + bheight + borheight,
-		 SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);
+    SetWindowPos32(hwnd, 0, 0, 0, wwidth, 8 + tiheight + bheight + borheight,
+		   SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);
     
     /* Position the buttons */
     bpos = (wwidth - bwidth * buttons) / 2;
-    GetWindowRect32(GetDlgItem(hwnd, 1), &rect);
+    GetWindowRect32(GetDlgItem32(hwnd, 1), &rect);
     for (buttons = i = 0; i < 7; i++) {
       /* some arithmetic to get the right order for YesNoCancel windows */
-      hItem = GetDlgItem(hwnd, (i + 5) % 7 + 1);
+      hItem = GetDlgItem32(hwnd, (i + 5) % 7 + 1);
       if (GetWindowLong32A(hItem, GWL_STYLE) & WS_VISIBLE) {
 	if (buttons++ == ((lpmb->type & MB_DEFMASK) >> 8)) {
 	  SetFocus32(hItem);
 	  SendMessage32A( hItem, BM_SETSTYLE32, BS_DEFPUSHBUTTON, TRUE );
 	}
-	SetWindowPos(hItem, 0, bpos, tiheight, 0, 0,
-		     SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW);
+	SetWindowPos32(hItem, 0, bpos, tiheight, 0, 0,
+		       SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOREDRAW);
 	bpos += bwidth;
       }
     }
diff --git a/windows/nonclient.c b/windows/nonclient.c
index 2f93a6a..ba5f6cc 100644
--- a/windows/nonclient.c
+++ b/windows/nonclient.c
@@ -465,7 +465,7 @@
     if( !(wndPtr->flags & WIN_MANAGED) )
     {
       NC_GetInsideRect( hwnd, &rect );
-      GRAPH_DrawBitmap( hdc, (IsZoomed(hwnd) ?
+      GRAPH_DrawBitmap( hdc, (IsZoomed32(hwnd) ?
 			     (down ? hbitmapRestoreD : hbitmapRestore) :
 			     (down ? hbitmapMaximizeD : hbitmapMaximize)),
 		        rect.right - SYSMETRICS_CXSIZE - 1, rect.top,
@@ -1024,7 +1024,7 @@
     BOOL32    iconic = wndPtr->dwStyle & WS_MINIMIZE;
     int       moved = 0;
 
-    if (IsZoomed(hwnd) || !IsWindowVisible(hwnd) ||
+    if (IsZoomed32(hwnd) || !IsWindowVisible32(hwnd) ||
         (wndPtr->flags & WIN_MANAGED)) return;
 
     if ((wParam & 0xfff0) == SC_MOVE)
@@ -1197,7 +1197,7 @@
        }
     }
     SendMessage16( hwnd, WM_EXITSIZEMOVE, 0, 0 );
-    SendMessage16( hwnd, WM_SETVISIBLE, !IsIconic(hwnd), 0L);
+    SendMessage16( hwnd, WM_SETVISIBLE, !IsIconic16(hwnd), 0L);
 
     /* Single click brings up the system menu when iconized */
 
@@ -1211,12 +1211,12 @@
     if ((msg.message == WM_KEYDOWN) && (msg.wParam == VK_ESCAPE)) return;
 
     if (hittest != HTCAPTION)
-	SetWindowPos( hwnd, 0, sizingRect.left, sizingRect.top,
-		     sizingRect.right - sizingRect.left,
-		     sizingRect.bottom - sizingRect.top,
-		     SWP_NOACTIVATE | SWP_NOZORDER );
-    else SetWindowPos( hwnd, 0, sizingRect.left, sizingRect.top, 0, 0,
-		      SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER );
+	SetWindowPos32( hwnd, 0, sizingRect.left, sizingRect.top,
+		        sizingRect.right - sizingRect.left,
+		        sizingRect.bottom - sizingRect.top,
+		        SWP_NOACTIVATE | SWP_NOZORDER );
+    else SetWindowPos32( hwnd, 0, sizingRect.left, sizingRect.top, 0, 0,
+		         SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER );
 }
 
 
@@ -1259,7 +1259,7 @@
 	SendMessage16( hwnd, WM_SYSCOMMAND, SC_MINIMIZE, *(LONG*)&msg.pt );
     else
 	SendMessage16( hwnd, WM_SYSCOMMAND, 
-		  IsZoomed(hwnd) ? SC_RESTORE : SC_MAXIMIZE, *(LONG*)&msg.pt );
+		  IsZoomed32(hwnd) ? SC_RESTORE:SC_MAXIMIZE, *(LONG*)&msg.pt );
 }
 
 
@@ -1431,15 +1431,15 @@
 	break;
 
     case SC_MINIMIZE:
-	ShowWindow( hwnd, SW_MINIMIZE ); 
+	ShowWindow32( hwnd, SW_MINIMIZE ); 
 	break;
 
     case SC_MAXIMIZE:
-	ShowWindow( hwnd, SW_MAXIMIZE );
+	ShowWindow32( hwnd, SW_MAXIMIZE );
 	break;
 
     case SC_RESTORE:
-	ShowWindow( hwnd, SW_RESTORE );
+	ShowWindow32( hwnd, SW_RESTORE );
 	break;
 
     case SC_CLOSE:
diff --git a/windows/painting.c b/windows/painting.c
index 42dacc6..bdc5593 100644
--- a/windows/painting.c
+++ b/windows/painting.c
@@ -71,7 +71,7 @@
 
     wnd->flags &= ~WIN_NEEDS_NCPAINT;
 
-    if ((wnd->hwndSelf == GetActiveWindow()) &&
+    if ((wnd->hwndSelf == GetActiveWindow32()) &&
         !(wnd->flags & WIN_NCACTIVATED))
     {
         wnd->flags |= WIN_NCACTIVATED;
@@ -256,7 +256,7 @@
 
     if (!hwnd) hwnd = GetDesktopWindow32();
     if (!(wndPtr = WIN_FindWndPtr( hwnd ))) return FALSE;
-    if (!IsWindowVisible(hwnd) || (wndPtr->flags & WIN_NO_REDRAW))
+    if (!IsWindowVisible32(hwnd) || (wndPtr->flags & WIN_NO_REDRAW))
         return TRUE;  /* No redraw needed */
 
     bIcon = (wndPtr->dwStyle & WS_MINIMIZE && wndPtr->class->hIcon);
diff --git a/windows/scroll.c b/windows/scroll.c
index 8689f90..9fec3e0 100644
--- a/windows/scroll.c
+++ b/windows/scroll.c
@@ -64,7 +64,7 @@
 	  GetClientRect32(hwnd, &rc);
 	  hrgnClip = CreateRectRgnIndirect32( &rc );
 
-          if ((hCaretWnd == hwnd) || IsChild(hwnd,hCaretWnd))
+          if ((hCaretWnd == hwnd) || IsChild32(hwnd,hCaretWnd))
               HideCaret(hCaretWnd);
           else hCaretWnd = 0;
  
@@ -98,10 +98,10 @@
 	OffsetRgn32( wndScroll->hrgnUpdate, dx, dy );
 
       for (wndPtr = wndScroll->child; wndPtr; wndPtr = wndPtr->next)
-        SetWindowPos(wndPtr->hwndSelf, 0, wndPtr->rectWindow.left + dx,
-                     wndPtr->rectWindow.top  + dy, 0,0, SWP_NOZORDER |
-                     SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOREDRAW |
-                     SWP_DEFERERASE );
+        SetWindowPos32(wndPtr->hwndSelf, 0, wndPtr->rectWindow.left + dx,
+                       wndPtr->rectWindow.top  + dy, 0,0, SWP_NOZORDER |
+                       SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOREDRAW |
+                       SWP_DEFERERASE );
     }
 
     PAINT_RedrawWindow( hwnd, NULL, hrgnUpdate, RDW_ALLCHILDREN |
@@ -323,7 +323,7 @@
        RECT32	rc;
        CARET_GetRect( &rc );
        if( hCaret == hWnd ||
-          (flags & SW_SCROLLCHILDREN && IsChild(hWnd, hCaret)) )
+          (flags & SW_SCROLLCHILDREN && IsChild32(hWnd, hCaret)) )
        {
            POINT32     pt;
 
@@ -436,10 +436,10 @@
 	    {
 		 CONV_RECT16TO32( &w->rectWindow, &r );
 	         if( IntersectRect32(&r, &r, &cliprc) )
-		     SetWindowPos(w->hwndSelf, 0, w->rectWindow.left + dx,
-				  w->rectWindow.top  + dy, 0,0, SWP_NOZORDER |
-				  SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOREDRAW |
-				  SWP_DEFERERASE );
+		     SetWindowPos32(w->hwndSelf, 0, w->rectWindow.left + dx,
+				    w->rectWindow.top  + dy, 0,0, SWP_NOZORDER |
+				    SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOREDRAW |
+				    SWP_DEFERERASE );
 	    }
 	}
 
diff --git a/windows/win.c b/windows/win.c
index 0966b49..31ceffd 100644
--- a/windows/win.c
+++ b/windows/win.c
@@ -29,6 +29,7 @@
 #include "dde_proc.h"
 #include "clipboard.h"
 #include "winproc.h"
+#include "thread.h"
 #include "stddebug.h"
 /* #define DEBUG_WIN  */ 
 /* #define DEBUG_MENU */
@@ -385,7 +386,7 @@
         next = wnd->next;
         if (wnd->hmemTaskQ == hQueue)
 	   if( hNew ) wnd->hmemTaskQ = hNew;
-	   else DestroyWindow( wnd->hwndSelf );
+	   else DestroyWindow32( wnd->hwndSelf );
         else WIN_ResetQueueWindows( wnd->child, hQueue, hNew );
         wnd = next;
     }
@@ -782,20 +783,20 @@
 
         wndPtr->dwStyle &= ~WS_MAXIMIZE;
         WINPOS_FindIconPos( hwnd );
-        SetWindowPos( hwnd, 0, wndPtr->ptIconPos.x, wndPtr->ptIconPos.y,
-                      SYSMETRICS_CXICON, SYSMETRICS_CYICON, 
-                      SWP_FRAMECHANGED | ((GetActiveWindow())? SWP_NOACTIVATE : 0)  );
+        SetWindowPos32( hwnd, 0, wndPtr->ptIconPos.x, wndPtr->ptIconPos.y,
+                        SYSMETRICS_CXICON, SYSMETRICS_CYICON, 
+                        SWP_FRAMECHANGED | ((GetActiveWindow32())? SWP_NOACTIVATE : 0)  );
     }
     else if (wndPtr->dwStyle & WS_MAXIMIZE)
     {
 	/* MinMaximize(hwnd, SW_SHOWMAXIMIZED, 1) */
 
         NC_GetMinMaxInfo( wndPtr, &maxSize, &maxPos, &minTrack, &maxTrack );
-        SetWindowPos( hwnd, 0, maxPos.x, maxPos.y, maxSize.x, maxSize.y,
-            ((GetActiveWindow())? SWP_NOACTIVATE : 0) | SWP_FRAMECHANGED );
+        SetWindowPos32( hwnd, 0, maxPos.x, maxPos.y, maxSize.x, maxSize.y,
+            ((GetActiveWindow32())? SWP_NOACTIVATE : 0) | SWP_FRAMECHANGED );
     }
     
-    if (cs->style & WS_VISIBLE) ShowWindow( hwnd, SW_SHOW );
+    if (cs->style & WS_VISIBLE) ShowWindow32( hwnd, SW_SHOW );
 
     /* Call WH_SHELL hook */
 
@@ -989,7 +990,14 @@
 /***********************************************************************
  *           DestroyWindow   (USER.53)
  */
-BOOL DestroyWindow( HWND hwnd )
+BOOL16 DestroyWindow16( HWND16 hwnd )
+{
+    return DestroyWindow32(hwnd);
+}
+/***********************************************************************
+ *           DestroyWindow   (USER32.134)
+ */
+BOOL32 DestroyWindow32( HWND32 hwnd )
 {
     WND * wndPtr;
 
@@ -1021,9 +1029,9 @@
 
     if (wndPtr->dwStyle & WS_VISIBLE)
     {
-        SetWindowPos( hwnd, 0, 0, 0, 0, 0, SWP_HIDEWINDOW |
-		      SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE |
-		    ((QUEUE_IsDoomedQueue(wndPtr->hmemTaskQ))?SWP_DEFERERASE:0) );
+        SetWindowPos32( hwnd, 0, 0, 0, 0, 0, SWP_HIDEWINDOW |
+		        SWP_NOACTIVATE|SWP_NOZORDER|SWP_NOMOVE|SWP_NOSIZE|
+		        ((QUEUE_IsDoomedQueue(wndPtr->hmemTaskQ))?SWP_DEFERERASE:0) );
 	if( !IsWindow(hwnd) ) return TRUE;
     }
 
@@ -1043,7 +1051,7 @@
                    siblingPtr->owner = NULL;
             siblingPtr = siblingPtr->next;
         }
-        if (siblingPtr) DestroyWindow( siblingPtr->hwndSelf );
+        if (siblingPtr) DestroyWindow32( siblingPtr->hwndSelf );
         else break;
       }
 
@@ -1077,7 +1085,7 @@
 {
     WND * wndPtr = WIN_FindWndPtr(hWnd);
     if (!wndPtr || (wndPtr->dwStyle & WS_CHILD)) return TRUE;
-    ShowWindow(hWnd, SW_MINIMIZE);
+    ShowWindow32(hWnd, SW_MINIMIZE);
     return TRUE;
 }
 
@@ -1087,8 +1095,8 @@
  */
 BOOL OpenIcon(HWND hWnd)
 {
-    if (!IsIconic(hWnd)) return FALSE;
-    ShowWindow(hWnd, SW_SHOWNORMAL);
+    if (!IsIconic16(hWnd)) return FALSE;
+    ShowWindow32(hWnd, SW_SHOWNORMAL);
     return(TRUE);
 }
 
@@ -1276,9 +1284,18 @@
 
 
 /*******************************************************************
- *           EnableWindow   (USER.34)
+ *           EnableWindow16   (USER.34)
  */
-BOOL EnableWindow( HWND hwnd, BOOL enable )
+BOOL16 EnableWindow16( HWND16 hwnd, BOOL16 enable )
+{
+    return EnableWindow32( hwnd, enable );
+}
+
+
+/*******************************************************************
+ *           EnableWindow32   (USER32.171)
+ */
+BOOL32 EnableWindow32( HWND32 hwnd, BOOL32 enable )
 {
     WND *wndPtr;
 
@@ -1287,18 +1304,18 @@
     {
 	  /* Enable window */
 	wndPtr->dwStyle &= ~WS_DISABLED;
-	SendMessage16( hwnd, WM_ENABLE, TRUE, 0 );
+	SendMessage32A( hwnd, WM_ENABLE, TRUE, 0 );
 	return TRUE;
     }
     else if (!enable && !(wndPtr->dwStyle & WS_DISABLED))
     {
 	  /* Disable window */
 	wndPtr->dwStyle |= WS_DISABLED;
-	if ((hwnd == GetFocus32()) || IsChild( hwnd, GetFocus32() ))
+	if ((hwnd == GetFocus32()) || IsChild32( hwnd, GetFocus32() ))
 	    SetFocus32( 0 );  /* A disabled window can't have the focus */
-	if ((hwnd == GetCapture32()) || IsChild( hwnd, GetCapture32() ))
+	if ((hwnd == GetCapture32()) || IsChild32( hwnd, GetCapture32() ))
 	    ReleaseCapture();  /* A disabled window can't capture the mouse */
-	SendMessage16( hwnd, WM_ENABLE, FALSE, 0 );
+	SendMessage32A( hwnd, WM_ENABLE, FALSE, 0 );
 	return FALSE;
     }
     return ((wndPtr->dwStyle & WS_DISABLED) != 0);
@@ -1306,9 +1323,18 @@
 
 
 /***********************************************************************
- *           IsWindowEnabled   (USER.35) (USER32.348)
+ *           IsWindowEnabled16   (USER.35)
  */ 
-BOOL IsWindowEnabled(HWND hWnd)
+BOOL16 IsWindowEnabled16(HWND16 hWnd)
+{
+    return IsWindowEnabled32(hWnd);
+}
+
+
+/***********************************************************************
+ *           IsWindowEnabled32   (USER32.348)
+ */ 
+BOOL32 IsWindowEnabled32(HWND32 hWnd)
 {
     WND * wndPtr; 
 
@@ -1691,7 +1717,7 @@
     if (hwndNewParent) wndPtr->parent = pWndParent;
     WIN_LinkWindow(hwndChild, HWND_BOTTOM);
     
-    if (IsWindowVisible(hwndChild)) UpdateWindow(hwndChild);
+    if (IsWindowVisible32(hwndChild)) UpdateWindow(hwndChild);
     
     return oldParent;
 }
@@ -1701,7 +1727,14 @@
 /*******************************************************************
  *         IsChild    (USER.48)
  */
-BOOL IsChild( HWND parent, HWND child )
+BOOL16 IsChild16( HWND16 parent, HWND16 child )
+{
+    return IsChild32(parent,child);
+}
+/*******************************************************************
+ *         IsChild    (USER32.338)
+ */
+BOOL32 IsChild32( HWND32 parent, HWND32 child )
 {
     WND * wndPtr = WIN_FindWndPtr( child );
     while (wndPtr && (wndPtr->dwStyle & WS_CHILD))
@@ -1714,9 +1747,16 @@
 
 
 /***********************************************************************
- *           IsWindowVisible   (USER.49) (USER32.350)
+ *           IsWindowVisible   (USER.49)
  */
-BOOL IsWindowVisible( HWND hwnd )
+BOOL16 IsWindowVisible16( HWND16 hwnd )
+{
+    return IsWindowVisible32(hwnd);
+}
+/***********************************************************************
+ *           IsWindowVisible   (USER32.350)
+ */
+BOOL32 IsWindowVisible32( HWND32 hwnd )
 {
     WND *wndPtr = WIN_FindWndPtr( hwnd );
     while (wndPtr && (wndPtr->dwStyle & WS_CHILD))
@@ -1753,7 +1793,14 @@
 /*******************************************************************
  *         GetTopWindow    (USER.229)
  */
-HWND GetTopWindow( HWND hwnd )
+HWND16 GetTopWindow16( HWND16 hwnd )
+{
+    return GetTopWindow32(hwnd);
+}
+/*******************************************************************
+ *         GetTopWindow    (USER.229)
+ */
+HWND32 GetTopWindow32( HWND32 hwnd )
 {
     WND * wndPtr = WIN_FindWndPtr( hwnd );
     if (wndPtr && wndPtr->child) return wndPtr->child->hwndSelf;
@@ -1764,7 +1811,14 @@
 /*******************************************************************
  *         GetWindow    (USER.262)
  */
-HWND GetWindow( HWND hwnd, WORD rel )
+HWND16 GetWindow16( HWND16 hwnd, WORD rel )
+{
+    return GetWindow32( hwnd,rel );
+}
+/*******************************************************************
+ *         GetWindow    (USER32.301)
+ */
+HWND32 GetWindow32( HWND32 hwnd, WORD rel )
 {
     WND * wndPtr = WIN_FindWndPtr( hwnd );
     if (!wndPtr) return 0;
@@ -1807,10 +1861,10 @@
 /*******************************************************************
  *         GetNextWindow    (USER.230)
  */
-HWND GetNextWindow( HWND hwnd, WORD flag )
+HWND16 GetNextWindow16( HWND16 hwnd, WORD flag )
 {
     if ((flag != GW_HWNDNEXT) && (flag != GW_HWNDPREV)) return 0;
-    return GetWindow( hwnd, flag );
+    return GetWindow16( hwnd, flag );
 }
 
 /*******************************************************************
@@ -1823,7 +1877,7 @@
     {
         if (pWnd->owner && (pWnd->owner->hwndSelf == owner) &&
             (pWnd->dwStyle & WS_POPUP))
-            ShowWindow( pWnd->hwndSelf, fShow ? SW_SHOW : SW_HIDE );
+            ShowWindow32( pWnd->hwndSelf, fShow ? SW_SHOW : SW_HIDE );
         pWnd = pWnd->next;
     }
 }
@@ -1937,7 +1991,9 @@
  */
 BOOL32 EnumThreadWindows( DWORD id, WNDENUMPROC32 func, LPARAM lParam )
 {
-    return (BOOL16)EnumTaskWindows16((HTASK16)id, (WNDENUMPROC16)func, lParam);
+    THDB	*tdb = (THDB*)id;
+
+    return (BOOL16)EnumTaskWindows16(tdb->teb.htask16, (WNDENUMPROC16)func, lParam);
 }
 
 
@@ -2039,7 +2095,7 @@
     {
         WPARAM16 wparam;
         if (bInvert) wparam = !(wndPtr->flags & WIN_NCACTIVATED);
-        else wparam = (hWnd == GetActiveWindow());
+        else wparam = (hWnd == GetActiveWindow32());
 
         SendMessage16( hWnd, WM_NCACTIVATE, wparam, (LPARAM)0 );
         return wparam;
diff --git a/windows/winpos.c b/windows/winpos.c
index 40516f3..adac82f 100644
--- a/windows/winpos.c
+++ b/windows/winpos.c
@@ -5,6 +5,7 @@
  *                       1995,1996 Alex Korobka
  */
 
+#define NO_TRANSITION_TYPES
 #include <X11/Xlib.h>
 #include <X11/Xutil.h>
 #include <X11/Xatom.h>
@@ -38,15 +39,15 @@
 
 /* ----- external functions ----- */
 
-extern void 	FOCUS_SwitchFocus( HWND , HWND );
-extern HRGN32 	DCE_GetVisRgn( HWND, WORD );
-extern HWND	CARET_GetHwnd();
-extern BOOL     DCE_InvalidateDCE(WND*, RECT16* );
+extern void 	FOCUS_SwitchFocus( HWND32 , HWND32 );
+extern HRGN32 	DCE_GetVisRgn( HWND32, WORD );
+extern HWND32	CARET_GetHwnd();
+extern BOOL32   DCE_InvalidateDCE(WND*, RECT16* );
 
 /* ----- internal variables ----- */
 
-static HWND hwndActive      = 0;  /* Currently active window */
-static HWND hwndPrevActive  = 0;  /* Previously active window */
+static HWND32 hwndActive      = 0;  /* Currently active window */
+static HWND32 hwndPrevActive  = 0;  /* Previously active window */
 
 extern MESSAGEQUEUE* pActiveQueue;
 
@@ -117,26 +118,32 @@
 
 
 /***********************************************************************
+ *           ArrangeIconicWindows   (USER32.6)
+ */
+UINT16 ArrangeIconicWindows16( HWND16 parent) {
+    return ArrangeIconicWindows32(parent);
+}
+/***********************************************************************
  *           ArrangeIconicWindows   (USER.170)
  */
-UINT ArrangeIconicWindows( HWND parent )
+UINT32 ArrangeIconicWindows32( HWND32 parent )
 {
-    RECT16 rectParent;
-    HWND hwndChild;
-    INT x, y, xspacing, yspacing;
+    RECT32 rectParent;
+    HWND32 hwndChild;
+    INT32 x, y, xspacing, yspacing;
 
-    GetClientRect16( parent, &rectParent );
+    GetClientRect32( parent, &rectParent );
     x = rectParent.left;
     y = rectParent.bottom;
     xspacing = yspacing = 70;  /* FIXME: This should come from WIN.INI */
-    hwndChild = GetWindow( parent, GW_CHILD );
+    hwndChild = GetWindow32( parent, GW_CHILD );
     while (hwndChild)
     {
-        if (IsIconic( hwndChild ))
+        if (IsIconic32( hwndChild ))
         {
-            SetWindowPos( hwndChild, 0, x + (xspacing - SYSMETRICS_CXICON) / 2,
-                          y - (yspacing + SYSMETRICS_CYICON) / 2, 0, 0,
-                          SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE );
+            SetWindowPos32( hwndChild, 0, x + (xspacing - SYSMETRICS_CXICON) / 2,
+                            y - (yspacing + SYSMETRICS_CYICON) / 2, 0, 0,
+                            SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE );
             if (x <= rectParent.right - xspacing) x += xspacing;
             else
             {
@@ -144,7 +151,7 @@
                 y -= yspacing;
             }
         }
-        hwndChild = GetWindow( hwndChild, GW_HWNDNEXT );
+        hwndChild = GetWindow32( hwndChild, GW_HWNDNEXT );
     }
     return yspacing;
 }
@@ -316,7 +323,7 @@
 
         /* Send the WM_NCHITTEST message (only if to the same task) */
         if ((*ppWnd)->hmemTaskQ != GetTaskQueue(0)) return HTCLIENT;
-        hittest = (INT)SendMessage16( (*ppWnd)->hwndSelf, WM_NCHITTEST, 0,
+        hittest = (INT16)SendMessage16( (*ppWnd)->hwndSelf, WM_NCHITTEST, 0,
                                     MAKELONG( pt.x, pt.y ) );
         if (hittest != HTTRANSPARENT) return hittest;  /* Found the window */
 
@@ -485,7 +492,14 @@
 /***********************************************************************
  *           IsIconic   (USER.31)
  */
-BOOL IsIconic(HWND hWnd)
+BOOL16 IsIconic16(HWND16 hWnd)
+{
+    return IsIconic32(hWnd);
+}
+/***********************************************************************
+ *           IsIconic   (USER32.344)
+ */
+BOOL32 IsIconic32(HWND32 hWnd)
 {
     WND * wndPtr = WIN_FindWndPtr(hWnd);
     if (wndPtr == NULL) return FALSE;
@@ -496,7 +510,14 @@
 /***********************************************************************
  *           IsZoomed   (USER.272)
  */
-BOOL IsZoomed(HWND hWnd)
+BOOL16 IsZoomed16(HWND16 hWnd)
+{
+    return IsZoomed32(hWnd);
+}
+/***********************************************************************
+ *           IsZoomed   (USER32.351)
+ */
+BOOL32 IsZoomed32(HWND32 hWnd)
 {
     WND * wndPtr = WIN_FindWndPtr(hWnd);
     if (wndPtr == NULL) return FALSE;
@@ -507,7 +528,14 @@
 /*******************************************************************
  *         GetActiveWindow    (USER.60)
  */
-HWND GetActiveWindow(void)
+HWND16 GetActiveWindow16(void)
+{
+    return GetActiveWindow32();
+}
+/*******************************************************************
+ *         GetActiveWindow    (USER32.204)
+ */
+HWND32 GetActiveWindow32(void)
 {
     return hwndActive;
 }
@@ -526,9 +554,16 @@
 /*******************************************************************
  *         SetActiveWindow    (USER.59)
  */
-HWND SetActiveWindow( HWND hwnd )
+HWND16 SetActiveWindow16( HWND16 hwnd )
 {
-    HWND prev = hwndActive;
+    return SetActiveWindow32(hwnd);
+}
+/*******************************************************************
+ *         SetActiveWindow    (USER.59)
+ */
+HWND32 SetActiveWindow32( HWND32 hwnd )
+{
+    HWND32 prev = hwndActive;
     WND *wndPtr = WIN_FindWndPtr( hwnd );
 
     if ( !WINPOS_IsGoodEnough(wndPtr) ) return 0;
@@ -541,29 +576,51 @@
 /***********************************************************************
  *           BringWindowToTop   (USER.45)
  */
-BOOL BringWindowToTop( HWND hwnd )
+BOOL16 BringWindowToTop16( HWND16 hwnd )
 {
-    return SetWindowPos( hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE );
+    return BringWindowToTop32(hwnd);
+}
+/***********************************************************************
+ *           BringWindowToTop   (USER32.10)
+ */
+BOOL32 BringWindowToTop32( HWND32 hwnd )
+{
+    return SetWindowPos32( hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE );
 }
 
 
 /***********************************************************************
  *           MoveWindow   (USER.56)
  */
-BOOL MoveWindow( HWND hwnd, short x, short y, short cx, short cy, BOOL repaint)
-{    
+BOOL16 MoveWindow16(
+	HWND16 hwnd, INT16 x, INT16 y, INT16 cx, INT16 cy, BOOL16 repaint
+) {
+    return MoveWindow32(hwnd,x,y,cx,cy,repaint);
+}
+/***********************************************************************
+ *           MoveWindow   (USER32.398)
+ */
+BOOL32 MoveWindow32(
+	HWND32 hwnd, INT32 x, INT32 y, INT32 cx, INT32 cy, BOOL32 repaint
+) {    
     int flags = SWP_NOZORDER | SWP_NOACTIVATE;
     if (!repaint) flags |= SWP_NOREDRAW;
     dprintf_win(stddeb, "MoveWindow: %04x %d,%d %dx%d %d\n", 
 	    hwnd, x, y, cx, cy, repaint );
-    return SetWindowPos( hwnd, 0, x, y, cx, cy, flags );
+    return SetWindowPos32( hwnd, 0, x, y, cx, cy, flags );
 }
 
-
 /***********************************************************************
  *           ShowWindow   (USER.42)
  */
-BOOL ShowWindow( HWND hwnd, int cmd ) 
+BOOL16 ShowWindow16( HWND16 hwnd, INT16 cmd ) 
+{    
+    return ShowWindow32(hwnd,cmd);
+}
+/***********************************************************************
+ *           ShowWindow   (USER.42)
+ */
+BOOL32 ShowWindow32( HWND32 hwnd, INT32 cmd ) 
 {    
     WND * wndPtr = WIN_FindWndPtr( hwnd );
     BOOL32 wasVisible, showFlag;
@@ -636,7 +693,7 @@
                 y  = wndPtr->ptMaxPos.y;
 
 		if( wndPtr->dwStyle & WS_MINIMIZE )
-		    if( !SendMessage16( hwnd, WM_QUERYOPEN, 0, 0L ) )
+		    if( !SendMessage32A( hwnd, WM_QUERYOPEN, 0, 0L ) )
 			{
 		         swpflags |= SWP_NOSIZE | SWP_NOMOVE;
 			 break;
@@ -660,7 +717,7 @@
 
 	case SW_SHOWNOACTIVATE:
             swpflags |= SWP_NOZORDER;
-            if (GetActiveWindow()) swpflags |= SWP_NOACTIVATE;
+            if (GetActiveWindow32()) swpflags |= SWP_NOACTIVATE;
             /* fall through */
 	case SW_SHOWNORMAL:  /* same as SW_NORMAL: */
 	case SW_SHOWDEFAULT: /* FIXME: should have its own handler */
@@ -725,10 +782,10 @@
     }
 
     if ((wndPtr->dwStyle & WS_CHILD) &&
-        !IsWindowVisible( wndPtr->parent->hwndSelf ) &&
+        !IsWindowVisible32( wndPtr->parent->hwndSelf ) &&
         (swpflags & SWP_NOSIZE) && (swpflags & SWP_NOMOVE))
     {
-        /* Don't call SetWindowPos() on invisible child windows */
+        /* Don't call SetWindowPos32() on invisible child windows */
         if (cmd == SW_HIDE) wndPtr->dwStyle &= ~WS_VISIBLE;
         else wndPtr->dwStyle |= WS_VISIBLE;
     }
@@ -737,7 +794,7 @@
         /* We can't activate a child window */
         if (wndPtr->dwStyle & WS_CHILD)
             swpflags |= SWP_NOACTIVATE | SWP_NOZORDER;
-        SetWindowPos( hwnd, HWND_TOP, x, y, cx, cy, swpflags );
+        SetWindowPos32( hwnd, HWND_TOP, x, y, cx, cy, swpflags );
         if (!IsWindow( hwnd )) return wasVisible;
     }
 
@@ -835,8 +892,8 @@
 
     wndpl->length  = sizeof(*wndpl);
     wndpl->flags   = 0;
-    wndpl->showCmd = IsZoomed(hwnd) ? SW_SHOWMAXIMIZED : 
-	             (IsIconic(hwnd) ? SW_SHOWMINIMIZED : SW_SHOWNORMAL);
+    wndpl->showCmd = IsZoomed16(hwnd) ? SW_SHOWMAXIMIZED : 
+	             (IsIconic16(hwnd) ? SW_SHOWMINIMIZED : SW_SHOWNORMAL);
     wndpl->ptMinPosition = wndPtr->ptIconPos;
     wndpl->ptMaxPosition = wndPtr->ptMaxPos;
     wndpl->rcNormalPosition = wndPtr->rectNormal;
@@ -854,8 +911,8 @@
 
     wndpl->length  = sizeof(*wndpl);
     wndpl->flags   = 0;
-    wndpl->showCmd = IsZoomed(hwnd) ? SW_SHOWMAXIMIZED : 
-	             (IsIconic(hwnd) ? SW_SHOWMINIMIZED : SW_SHOWNORMAL);
+    wndpl->showCmd = IsZoomed32(hwnd) ? SW_SHOWMAXIMIZED : 
+	             (IsIconic32(hwnd) ? SW_SHOWMINIMIZED : SW_SHOWNORMAL);
     CONV_POINT16TO32( &wndPtr->ptIconPos, &wndpl->ptMinPosition );
     CONV_POINT16TO32( &wndPtr->ptMaxPos, &wndpl->ptMaxPosition );
     CONV_RECT16TO32( &wndPtr->rectNormal, &wndpl->rcNormalPosition );
@@ -877,7 +934,7 @@
 	(wndpl->showCmd == SW_SHOWMINIMIZED)) wndPtr->flags |= WIN_RESTORE_MAX;
     wndPtr->ptMaxPos   = wndpl->ptMaxPosition;
     wndPtr->rectNormal = wndpl->rcNormalPosition;
-    ShowWindow( hwnd, wndpl->showCmd );
+    ShowWindow16( hwnd, wndpl->showCmd );
     return TRUE;
 }
 
@@ -896,7 +953,7 @@
 	(wndpl->showCmd == SW_SHOWMINIMIZED)) wndPtr->flags |= WIN_RESTORE_MAX;
     CONV_POINT32TO16( &wndpl->ptMaxPosition, &wndPtr->ptMaxPos );
     CONV_RECT32TO16( &wndpl->rcNormalPosition, &wndPtr->rectNormal );
-    ShowWindow( hwnd, wndpl->showCmd );
+    ShowWindow32( hwnd, wndpl->showCmd );
     return TRUE;
 }
 
@@ -1010,8 +1067,8 @@
 	    if (wndTemp->dwStyle & WS_VISIBLE) break;
 
 	if( wndTemp != wndPtr )
-	    SetWindowPos(hWnd, HWND_TOP, 0,0,0,0, 
-			 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE );
+	    SetWindowPos32(hWnd, HWND_TOP, 0,0,0,0, 
+			   SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE );
         if( !IsWindow(hWnd) ) return 0;
     }
 
@@ -1254,9 +1311,9 @@
  * 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 )
+static void WINPOS_MoveWindowZOrder( HWND32 hwnd, HWND32 hwndAfter )
 {
-    BOOL movingUp;
+    BOOL32 movingUp;
     WND *pWndAfter, *pWndCur, *wndPtr = WIN_FindWndPtr( hwnd );
 
     /* We have two possible cases:
@@ -1332,7 +1389,7 @@
  * fix Z order taking into account owned popups -
  * basically we need to maintain them above owner window
  */
-HWND WINPOS_ReorderOwnedPopups(HWND hwndInsertAfter, WND* wndPtr, WORD flags)
+HWND32 WINPOS_ReorderOwnedPopups(HWND32 hwndInsertAfter,WND* wndPtr,WORD flags)
 {
  WND* 	w = WIN_GetDesktop()->child;
 
@@ -1340,7 +1397,7 @@
   {
    /* implement "local z-order" between the top and owner window */
 
-     HWND hwndLocalPrev = HWND_TOP;
+     HWND32 hwndLocalPrev = HWND_TOP;
 
      if( hwndInsertAfter != HWND_TOP )
      {
@@ -1363,8 +1420,8 @@
 
     if( w->dwStyle & WS_POPUP && w->owner == wndPtr )
     {
-      SetWindowPos(w->hwndSelf, hwndInsertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE |
-                                SWP_NOACTIVATE | SWP_NOSENDCHANGING | SWP_DEFERERASE);
+      SetWindowPos32(w->hwndSelf, hwndInsertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE |
+                     SWP_NOACTIVATE | SWP_NOSENDCHANGING | SWP_DEFERERASE);
       hwndInsertAfter = w->hwndSelf;
     }
     w = w->next;
@@ -1384,7 +1441,7 @@
  * update regions are in window client coordinates
  * client and window rectangles are in parent client coordinates
  */
-static UINT WINPOS_SizeMoveClean(WND* Wnd, HRGN32 oldVisRgn, LPRECT16 lpOldWndRect, LPRECT16 lpOldClientRect, UINT uFlags )
+static UINT32 WINPOS_SizeMoveClean(WND* Wnd, HRGN32 oldVisRgn, LPRECT16 lpOldWndRect, LPRECT16 lpOldClientRect, UINT32 uFlags )
 {
  HRGN32 newVisRgn = DCE_GetVisRgn(Wnd->hwndSelf,DCX_WINDOW | DCX_CLIPSIBLINGS);
  HRGN32 dirtyRgn = CreateRectRgn32(0,0,0,0);
@@ -1605,16 +1662,25 @@
 /***********************************************************************
  *           SetWindowPos   (USER.232)
  */
-BOOL SetWindowPos( HWND hwnd, HWND hwndInsertAfter, INT x, INT y,
-		   INT cx, INT cy, WORD flags )
+BOOL16 SetWindowPos16( HWND16 hwnd, HWND16 hwndInsertAfter, INT16 x, INT16 y,
+                       INT16 cx, INT16 cy, WORD flags )
+{
+    return SetWindowPos32(hwnd,(INT32)(INT16)hwndInsertAfter,x,y,cx,cy,flags);
+}
+
+/***********************************************************************
+ *           SetWindowPos   (USER32.519)
+ */
+BOOL32 SetWindowPos32( HWND32 hwnd, HWND32 hwndInsertAfter, INT32 x, INT32 y,
+                       INT32 cx, INT32 cy, WORD flags )
 {
     WINDOWPOS16 *winpos;
     WND *	wndPtr;
     RECT16 	newWindowRect, newClientRect, oldWindowRect;
     HRGN32	visRgn = 0;
-    HWND	tempInsertAfter= 0;
+    HWND32	tempInsertAfter= 0;
     int 	result = 0;
-    UINT 	uFlags = 0;
+    UINT32 	uFlags = 0;
 
     dprintf_win(stddeb,"SetWindowPos: hwnd %04x, (%i,%i)-(%i,%i) flags %08x\n", 
 						 hwnd, x, y, x+cx, y+cy, flags);  
@@ -1914,7 +1980,7 @@
         }
 
         if ((winpos->hwnd == GetFocus32()) ||
-            IsChild( winpos->hwnd, GetFocus32()))
+            IsChild32( winpos->hwnd, GetFocus32()))
         {
             /* Revert focus to parent */
             SetFocus32( GetParent32(winpos->hwnd) );
@@ -1924,10 +1990,10 @@
 	if (winpos->hwnd == hwndActive)
 	{
 	      /* Activate previously active window if possible */
-	    HWND newActive = hwndPrevActive;
+	    HWND32 newActive = hwndPrevActive;
 	    if (!IsWindow(newActive) || (newActive == winpos->hwnd))
 	    {
-		newActive = GetTopWindow( GetDesktopWindow32() );
+		newActive = GetTopWindow32( GetDesktopWindow32() );
 		if (newActive == winpos->hwnd)
                     newActive = wndPtr->next ? wndPtr->next->hwndSelf : 0;
 	    }	    
@@ -1973,15 +2039,24 @@
 
 					
 /***********************************************************************
- *           BeginDeferWindowPos   (USER.259)
+ *           BeginDeferWindowPos16   (USER.259)
  */
-HDWP16 BeginDeferWindowPos( INT count )
+HDWP16 BeginDeferWindowPos16( INT16 count )
 {
-    HDWP16 handle;
+    return BeginDeferWindowPos32( count );
+}
+
+
+/***********************************************************************
+ *           BeginDeferWindowPos32   (USER32.8)
+ */
+HDWP32 BeginDeferWindowPos32( INT32 count )
+{
+    HDWP32 handle;
     DWP *pDWP;
 
     if (count <= 0) return 0;
-    handle = USER_HEAP_ALLOC( sizeof(DWP) + (count-1)*sizeof(WINDOWPOS16) );
+    handle = USER_HEAP_ALLOC( sizeof(DWP) + (count-1)*sizeof(WINDOWPOS32) );
     if (!handle) return 0;
     pDWP = (DWP *) USER_HEAP_LIN_ADDR( handle );
     pDWP->actualCount    = 0;
@@ -1994,15 +2069,26 @@
 
 
 /***********************************************************************
- *           DeferWindowPos   (USER.260)
+ *           DeferWindowPos16   (USER.260)
  */
-HDWP16 DeferWindowPos( HDWP16 hdwp, HWND hwnd, HWND hwndAfter, INT x, INT y,
-                       INT cx, INT cy, UINT flags )
+HDWP16 DeferWindowPos16( HDWP16 hdwp, HWND16 hwnd, HWND16 hwndAfter,
+                         INT16 x, INT16 y, INT16 cx, INT16 cy, UINT16 flags )
+{
+    return DeferWindowPos32( hdwp, hwnd, (INT32)(INT16)hwndAfter,
+                             x, y, cx, cy, flags );
+}
+
+
+/***********************************************************************
+ *           DeferWindowPos32   (USER32.127)
+ */
+HDWP32 DeferWindowPos32( HDWP32 hdwp, HWND32 hwnd, HWND32 hwndAfter,
+                         INT32 x, INT32 y, INT32 cx, INT32 cy, UINT32 flags )
 {
     DWP *pDWP;
     int i;
-    HDWP16 newhdwp = hdwp;
-    HWND parent;
+    HDWP32 newhdwp = hdwp;
+    HWND32 parent;
 
     pDWP = (DWP *) USER_HEAP_LIN_ADDR( hdwp );
     if (!pDWP) return 0;
@@ -2049,7 +2135,7 @@
     if (pDWP->actualCount >= pDWP->suggestedCount)
     {
         newhdwp = USER_HEAP_REALLOC( hdwp,
-                      sizeof(DWP) + pDWP->suggestedCount*sizeof(WINDOWPOS16) );
+                      sizeof(DWP) + pDWP->suggestedCount*sizeof(WINDOWPOS32) );
         if (!newhdwp) return 0;
         pDWP = (DWP *) USER_HEAP_LIN_ADDR( newhdwp );
         pDWP->suggestedCount++;
@@ -2067,22 +2153,31 @@
 
 
 /***********************************************************************
- *           EndDeferWindowPos   (USER.261)
+ *           EndDeferWindowPos16   (USER.261)
  */
-BOOL EndDeferWindowPos( HDWP16 hdwp )
+BOOL16 EndDeferWindowPos16( HDWP16 hdwp )
+{
+    return EndDeferWindowPos32( hdwp );
+}
+
+
+/***********************************************************************
+ *           EndDeferWindowPos32   (USER32.172)
+ */
+BOOL32 EndDeferWindowPos32( HDWP32 hdwp )
 {
     DWP *pDWP;
-    WINDOWPOS16 *winpos;
-    BOOL res = TRUE;
+    WINDOWPOS32 *winpos;
+    BOOL32 res = TRUE;
     int i;
 
     pDWP = (DWP *) USER_HEAP_LIN_ADDR( hdwp );
     if (!pDWP) return FALSE;
     for (i = 0, winpos = pDWP->winPos; i < pDWP->actualCount; i++, winpos++)
     {
-        if (!(res = SetWindowPos( winpos->hwnd, winpos->hwndInsertAfter,
-                                  winpos->x, winpos->y, winpos->cx, winpos->cy,
-                                  winpos->flags ))) break;
+        if (!(res = SetWindowPos32( winpos->hwnd, winpos->hwndInsertAfter,
+                                    winpos->x, winpos->y, winpos->cx,
+                                    winpos->cy, winpos->flags ))) break;
     }
     USER_HEAP_FREE( hdwp );
     return res;
@@ -2092,7 +2187,7 @@
 /***********************************************************************
  *           TileChildWindows   (USER.199)
  */
-void TileChildWindows( HWND parent, WORD action )
+void TileChildWindows( HWND16 parent, WORD action )
 {
     printf("STUB TileChildWindows(%04x, %d)\n", parent, action);
 }
@@ -2100,7 +2195,7 @@
 /***********************************************************************
  *           CascageChildWindows   (USER.198)
  */
-void CascadeChildWindows( HWND parent, WORD action )
+void CascadeChildWindows( HWND16 parent, WORD action )
 {
     printf("STUB CascadeChildWindows(%04x, %d)\n", parent, action);
 }