Release 980503

Thu Apr 30 16:28:12 1998  James Juran <jrj120@psu.edu>

	* [scheduler/process.c]
	Implemented GetExitCodeProcess.  The code is a direct translation
	of GetExitCodeThread.

Mon Apr 27 22:20:25 1998  Uwe Bonnes <bon@elektron.ikp.physik.tu-darmstadt.de>

	* [loader/pe_image.c]
	Unload dummy module when PE_LoadLibraryEx32A fails with
	PE_LoadImage (makes Encarta 98 installer proceed).

	* [files/drive.c]
	Make GetDriveType16 return DRIVE_REMOVABLE for TYPE_CDROM.
	Make GetCurrentDirectory32 behave like the code does and not
	like the help describes.

	* [files/profile.c]
	Revoke recent change in PROFILE_GetSection and try better 
	handling of special case.

	* [include/windows.h]
	Change definition of ACCEL32.

	* [misc/commdlg.c]
	Replace the GetXXXFilename32 macros by normal code.
	Fix two reported bugs in my changes to commdlg.

	* [windows/win.c]
	Add a hook to catch bogus WM_SIZE messages by emitting a warning
	in the appropriate case.

	* [objects/bitmap.c]
	Reject unreasonbable large size arguments in
	CreateCompatibleBitmap32 and add an fixme for that situation.

Sun Apr 26 18:30:07 1998  Alexandre Julliard  <julliard@lrc.epfl.ch>

	* [include/ldt.h] [debugger/*.c] [miscemu/instr.c]
	Added IS_SELECTOR_SYSTEM and IS_SELECTOR_32BIT macros.
	Make instruction emulation support system selectors.

	* [loader/*.c]
	Started moving NE specific functions to the new loader/ne
	directory.

	* [memory/environ.c]
	Enforce the 127 chars limit only when creating the environment of
	a Win16 process.

Sun Apr 26 12:22:23 1998  Andreas Mohr <100.30936@germany.net>

	* [files/file.c]
	Fixed an incredible typo in CopyFile32A that made it unusable
	since a rewrite in 970112 (!!).

	* [files/directory.c]
	Fixed GetTempPath32A/W to include trailing backslash.

	* [misc/ver.c]
	Make find_pe_resource "work" with corrupt files.

	* [misc/wsprintf.c]
	Altered WPRINTF_ParseFormatA/W to treat invalid format chars
	as normal output, too.

	* [msdos/dpmi.c]
	Implemented "Allocate/Free real mode callback" (0x0303/0x0304).
	Cross your fingers if you need to use it ;) (completely untested)
	Implemented "Call real mode proc with far return" (0x0301, tested).

	* [msdos/int21.c]
	Fixed ioctlGenericBlkDevReq/0x60.

	* [relay32/dplayx.spec] [relay32/builtin32.c] [relay32/Makefile.in]
	Added built-in DPLAYX.DLL. 

	* [windows/win.c]
	Fixed GetWindowWord()/GWW_HWNDPARENT to return the window's owner
	if it has no parent (SDK).

Sat Apr 25 15:09:53 1998  M.T.Fortescue  <mark@mtfhpc.demon.co.uk>

	* [debugger/db_disasm.c]
	Fixed disassemble bug for no-display option and 'lock',
	'repne' and 'repe' prefixes.

	* [debugger/registers.c]
	Added textual flag description output on 'info regs'.

Sat Apr 25 14:18:26 1998  Matthew Becker <mbecker@glasscity.net>

	* [*/*.c]
	Added stubs and/or documentation for the following functions: 
	LookupPrivilegeValue, OpenService, ControlService, RegGetKeySecurity, 
	StartService, SetComputerName, DeleteService, CloseServiceHandle, 
	OpenProcessToken, OpenSCManager, DeregisterEventSource, 
	WaitForDebugEvent, WaitForInputIdle, RegisterEventSource,
	SetDebugErrorLevel, SetConsoleCursorPosition, ChoosePixelFormat,
	SetPixelFormat, GetPixelFormat, DescribePixelFormat, SwapBuffers,
	PolyBezier, AbortPath, DestroyAcceleratorTable, HeapWalk,
	DdeInitialize, DdeUninitialize, DdeConnectList, DdeDisconnectList,
	DdeCreateStringHandle, DdePostAdvise, DdeGetData, DdeNameService,
	DdeGetLastError, WNetGetDirectoryType, EnumPrinters, RegFlushKey,
	RegGetKeySecurity, DllGetClassObject, DllCanUnloadNow, CreateBitmap,
	CreateCompatibleBitmap, CreateBitmapIndirect, GetBitmapBits,
	SetBitmapBits, LoadImage, CopyImage, LoadBitmap, DrawIcon,
	CreateDiscardableBitmap, SetDIBits, GetCharABCWidths, LoadTypeLib,
	SetConsoleCtrlHandler, CreateConsoleScreenBuffer, ReadConsoleInput,
	GetConsoleCursorInfo, SetConsoleCursorInfo, SetConsoleWindowInfo,
	SetConsoleTextAttribute, SetConsoleScreenBufferSize,
	FillConsoleOutputCharacter, FillConsoleOutputAttribute,
	CreateMailslot, GetMailslotInfo, GetCompressedFileSize,
	GetProcessWindowStation, GetThreadDesktop, SetDebugErrorLevel,
	WaitForDebugEvent, SetComputerName, CreateMDIWindow.

Thu Apr 23 23:54:04 1998  Douglas Ridgway  <ridgway@winehq.com>

	* [include/windows.h] [objects/enhmetafile.c] [relay32/gdi32.spec]
	Implement CopyEnhMetaFile, Get/SetEnhMetaFileBits, other fixes.

	* [include/windows.h] [objects/metafile.c] [relay32/gdi32.spec]
	32-bit metafile fixes, implement EnumMetaFile32, GetMetaFileBitsEx.

	* [objects/font.c] [graphics/x11drv/xfont.c] [graphics/x11drv/text.c]
	Some rotated text support for X11R6 displays.

	* [win32/newfns.c] [ole/ole2nls.c]
	Moved GetNumberFormat32A.

Wed Apr 22 17:38:20 1998  David Lee Lambert <lamber45@egr.msu.edu>

	* [ole/ole2nls.c] [misc/network.c]
	Changed some function documentation to the new style.

	* [misc/network.c] [include/windows.h] [if1632/user.spec]
	  [relay32/mpr.spec] [misc/mpr.c]
	Added stubs for some Win32 network functions;  renamed some 
	16-bit ones with 32-bit counterparts,  as well as
	WNetGetDirectoryType;  moved the stubs in misc/mpr.c (three of
	them!) to misc/network.c.

	* [ole/compobj.c] [ole/storage.c] [ole/ole2disp.c] 
	  [ole/ole2nls.c] [ole/folders.c] [ole/moniker.c] [ole/ole2.c]
	  [graphics/fontengine.c] [graphics/ddraw.c] [graphics/env.c]
	  [graphics/driver.c] [graphics/escape.c]
	Changed fprintf's to proper debug-macros.

	* [include/winnls.h]
	Added some flags (for internal use).

	* [ole/ole2nls.c] 
	Added the Unicode core function, and worked out a way to hide
	the commonality of the core.

	* [relay32/kernel32.spec]
	Added support for GetDate/Time32A/W.

Wed Apr 22 09:16:03 1998  Gordon Chaffee  <chaffee@cs.berkeley.edu>

	* [win32/code_page.c]
	Fixed problem with MultiByteToWideChar that was introduced in
	last release.  Made MultiByteToWideChar more compatible with Win32.

	* [graphics/x11drv/graphics.c]
	Fixed problem with drawing arcs.

Tue Apr 21 11:24:58 1998  Constantine Sapuntzakis  <csapuntz@tma-1.lcs.mit.edu>

	*  [ole/ole2nls.c]
	Move stuff from 0x409 case to Lang_En. 

	*  [relay32/user32.spec] [windows/winpos.c]
	Added stubs for GetWindowRgn32 and SetWindowRgn32. Makes Office
	Paperclip happy.

Tue Apr 21 11:16:16 1998  Constantine Sapuntzakis  <csapuntz@tma-1.lcs.mit.edu>

	*  [loader/pe_image.c]
	If image is relocated, TLS addresses need to be adjusted.

	* [debugger/*.c]
	Generalized tests for 32-bit segments.

Tue Apr 21 02:04:59 1998  James Juran  <jrj120@psu.edu>
	
	* [misc/*.c] [miscemu/*.c] [msdos/*.c] [if1632/*.c] 
	  [include/*.h] [loader/*.c] [memory/*.c] [multimedia/*.c] 
	  [objects/*.c]
	Almost all fprintf statements converted to appropriate 
	debug messages.

	* [README]
	Updated "GETTING MORE INFORMATION" section to include WineHQ.

	* [documentation/debugger]
	Fixed typo.

	* [windows/defwnd.c]
	Added function documentation.

Sun Apr 19 16:30:58 1998  Marcus Meissner <marcus@mud.de>

	* [Make.rules.in]
	Added lint target (using lclint).

	* [relay32/oleaut32.spec][relay32/Makefile.in][ole/typelib.c]
	  [ole/ole2disp.c]
	Added oleaut32 spec, added some SysString functions.

	* [if1632/signal.c]
	Added printing of faultaddress in Linux (using CR2 debug register).

	* [configure.in]
	Added <sys/types.h> for statfs checks.

	* [loader/*.c][debugger/break.c][debugger/hash.c]
	Started to split win32/win16 module handling, preparing support
	for other binary formats (like ELF).

Sat Apr 18 10:07:41 1998  Rein Klazes <rklazes@casema.net>

	* [misc/registry.c]
	Fixed a bug that made RegQueryValuexxx returning
	incorrect registry values.

Fri Apr 17 22:59:22 1998  Alexander V. Lukyanov <lav@long.yar.ru>

	* [misc/lstr.c]
	FormatMessage32*: remove linefeed when nolinefeed set;
	check for target underflow.

Fri Apr 17 00:38:14 1998  Alexander V. Lukyanov <lav@long.yar.ru>

	* [misc/crtdll.c]
	Implement xlat_file_ptr for CRT stdin/stdout/stderr address
	translation.

Wed Apr 15 20:43:56 1998  Jim Peterson <jspeter@birch.ee.vt.edu>

	* [controls/menu.c]
	Added 'odaction' parameter to MENU_DrawMenuItem() and redirected
	WM_DRAWITEM messages to GetWindow(hwnd,GW_OWNER).

Tue Apr 14 16:17:55 1998  Berend Reitsma <berend@united-info.com>

	* [graphics/metafiledrv/init.c]	[graphics/painting.c] 
	  [graphics/win16drv/init.c] [graphics/x11drv/graphics.c]
	  [graphics/x11drv/init.c] [include/gdi.h] [include/x11drv.h]
	  [relay32/gdi32.spec]
	Added PolyPolyline routine.

	* [windows/winproc.c]
	Changed WINPROC_GetProc() to return proc instead of &(jmp proc).
diff --git a/ANNOUNCE b/ANNOUNCE
index 78ee48c..1e0549f 100644
--- a/ANNOUNCE
+++ b/ANNOUNCE
@@ -1,14 +1,14 @@
-This is release 980413 of Wine, the MS Windows emulator.  This is still a
+This is release 980503 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-980413: (see ChangeLog for details)
-	- Flat thunks support.
-	- Many more autoconf checks for better portability.
-	- DIALOGEX resource support.
+WHAT'S NEW with Wine-980503: (see ChangeLog for details)
+	- Module loading restructuration.
+	- Some rotated text support.
+	- Documentation for many more functions.
 	- Lots of bug fixes.
 
 See the README file in the distribution for installation instructions.
@@ -17,10 +17,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-980413.tar.gz
-  ftp://tsx-11.mit.edu/pub/linux/ALPHA/Wine/development/Wine-980413.tar.gz
-  ftp://ftp.infomagic.com/pub/mirrors/linux/wine/development/Wine-980413.tar.gz
-  ftp://ftp.progsoc.uts.edu.au/pub/Wine/development/Wine-980413.tar.gz
+  ftp://sunsite.unc.edu/pub/Linux/ALPHA/wine/development/Wine-980503.tar.gz
+  ftp://tsx-11.mit.edu/pub/linux/ALPHA/Wine/development/Wine-980503.tar.gz
+  ftp://ftp.infomagic.com/pub/mirrors/linux/sunsite/ALPHA/wine/development/Wine-980503.tar.gz
+  ftp://ftp.progsoc.uts.edu.au/pub/Wine/development/Wine-980503.tar.gz
 
 It should also be available from any site that mirrors tsx-11 or sunsite.
 
diff --git a/ChangeLog b/ChangeLog
index 6119f63..7f3f722 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,4 +1,260 @@
 ----------------------------------------------------------------------
+Thu Apr 30 16:28:12 1998  James Juran <jrj120@psu.edu>
+
+	* [scheduler/process.c]
+	Implemented GetExitCodeProcess.  The code is a direct translation
+	of GetExitCodeThread.
+
+Mon Apr 27 22:20:25 1998  Uwe Bonnes <bon@elektron.ikp.physik.tu-darmstadt.de>
+
+	* [loader/pe_image.c]
+	Unload dummy module when PE_LoadLibraryEx32A fails with
+	PE_LoadImage (makes Encarta 98 installer proceed).
+
+	* [files/drive.c]
+	Make GetDriveType16 return DRIVE_REMOVABLE for TYPE_CDROM.
+	Make GetCurrentDirectory32 behave like the code does and not
+	like the help describes.
+
+	* [files/profile.c]
+	Revoke recent change in PROFILE_GetSection and try better 
+	handling of special case.
+
+	* [include/windows.h]
+	Change definition of ACCEL32.
+
+	* [misc/commdlg.c]
+	Replace the GetXXXFilename32 macros by normal code.
+	Fix two reported bugs in my changes to commdlg.
+
+	* [windows/win.c]
+	Add a hook to catch bogus WM_SIZE messages by emitting a warning
+	in the appropriate case.
+
+	* [objects/bitmap.c]
+	Reject unreasonbable large size arguments in
+	CreateCompatibleBitmap32 and add an fixme for that situation.
+
+Sun Apr 26 18:30:07 1998  Alexandre Julliard  <julliard@lrc.epfl.ch>
+
+	* [include/ldt.h] [debugger/*.c] [miscemu/instr.c]
+	Added IS_SELECTOR_SYSTEM and IS_SELECTOR_32BIT macros.
+	Make instruction emulation support system selectors.
+
+	* [loader/*.c]
+	Started moving NE specific functions to the new loader/ne
+	directory.
+
+	* [memory/environ.c]
+	Enforce the 127 chars limit only when creating the environment of
+	a Win16 process.
+
+Sun Apr 26 12:22:23 1998  Andreas Mohr <100.30936@germany.net>
+
+	* [files/file.c]
+	Fixed an incredible typo in CopyFile32A that made it unusable
+	since a rewrite in 970112 (!!).
+
+	* [files/directory.c]
+	Fixed GetTempPath32A/W to include trailing backslash.
+
+	* [misc/ver.c]
+	Make find_pe_resource "work" with corrupt files.
+
+	* [misc/wsprintf.c]
+	Altered WPRINTF_ParseFormatA/W to treat invalid format chars
+	as normal output, too.
+
+	* [msdos/dpmi.c]
+	Implemented "Allocate/Free real mode callback" (0x0303/0x0304).
+	Cross your fingers if you need to use it ;) (completely untested)
+	Implemented "Call real mode proc with far return" (0x0301, tested).
+
+	* [msdos/int21.c]
+	Fixed ioctlGenericBlkDevReq/0x60.
+
+	* [relay32/dplayx.spec] [relay32/builtin32.c] [relay32/Makefile.in]
+	Added built-in DPLAYX.DLL. 
+
+	* [windows/win.c]
+	Fixed GetWindowWord()/GWW_HWNDPARENT to return the window's owner
+	if it has no parent (SDK).
+
+Sat Apr 25 15:09:53 1998  M.T.Fortescue  <mark@mtfhpc.demon.co.uk>
+
+	* [debugger/db_disasm.c]
+	Fixed disassemble bug for no-display option and 'lock',
+	'repne' and 'repe' prefixes.
+
+	* [debugger/registers.c]
+	Added textual flag description output on 'info regs'.
+
+Sat Apr 25 14:18:26 1998  Matthew Becker <mbecker@glasscity.net>
+
+	* [*/*.c]
+	Added stubs and/or documentation for the following functions: 
+	LookupPrivilegeValue, OpenService, ControlService, RegGetKeySecurity, 
+	StartService, SetComputerName, DeleteService, CloseServiceHandle, 
+	OpenProcessToken, OpenSCManager, DeregisterEventSource, 
+	WaitForDebugEvent, WaitForInputIdle, RegisterEventSource,
+	SetDebugErrorLevel, SetConsoleCursorPosition, ChoosePixelFormat,
+	SetPixelFormat, GetPixelFormat, DescribePixelFormat, SwapBuffers,
+	PolyBezier, AbortPath, DestroyAcceleratorTable, HeapWalk,
+	DdeInitialize, DdeUninitialize, DdeConnectList, DdeDisconnectList,
+	DdeCreateStringHandle, DdePostAdvise, DdeGetData, DdeNameService,
+	DdeGetLastError, WNetGetDirectoryType, EnumPrinters, RegFlushKey,
+	RegGetKeySecurity, DllGetClassObject, DllCanUnloadNow, CreateBitmap,
+	CreateCompatibleBitmap, CreateBitmapIndirect, GetBitmapBits,
+	SetBitmapBits, LoadImage, CopyImage, LoadBitmap, DrawIcon,
+	CreateDiscardableBitmap, SetDIBits, GetCharABCWidths, LoadTypeLib,
+	SetConsoleCtrlHandler, CreateConsoleScreenBuffer, ReadConsoleInput,
+	GetConsoleCursorInfo, SetConsoleCursorInfo, SetConsoleWindowInfo,
+	SetConsoleTextAttribute, SetConsoleScreenBufferSize,
+	FillConsoleOutputCharacter, FillConsoleOutputAttribute,
+	CreateMailslot, GetMailslotInfo, GetCompressedFileSize,
+	GetProcessWindowStation, GetThreadDesktop, SetDebugErrorLevel,
+	WaitForDebugEvent, SetComputerName, CreateMDIWindow.
+
+Thu Apr 23 23:54:04 1998  Douglas Ridgway  <ridgway@winehq.com>
+
+	* [include/windows.h] [objects/enhmetafile.c] [relay32/gdi32.spec]
+	Implement CopyEnhMetaFile, Get/SetEnhMetaFileBits, other fixes.
+
+	* [include/windows.h] [objects/metafile.c] [relay32/gdi32.spec]
+	32-bit metafile fixes, implement EnumMetaFile32, GetMetaFileBitsEx.
+
+	* [objects/font.c] [graphics/x11drv/xfont.c] [graphics/x11drv/text.c]
+	Some rotated text support for X11R6 displays.
+
+	* [win32/newfns.c] [ole/ole2nls.c]
+	Moved GetNumberFormat32A.
+
+Wed Apr 22 17:38:20 1998  David Lee Lambert <lamber45@egr.msu.edu>
+
+	* [ole/ole2nls.c] [misc/network.c]
+	Changed some function documentation to the new style.
+
+	* [misc/network.c] [include/windows.h] [if1632/user.spec]
+	  [relay32/mpr.spec] [misc/mpr.c]
+	Added stubs for some Win32 network functions;  renamed some 
+	16-bit ones with 32-bit counterparts,  as well as
+	WNetGetDirectoryType;  moved the stubs in misc/mpr.c (three of
+	them!) to misc/network.c.
+
+	* [ole/compobj.c] [ole/storage.c] [ole/ole2disp.c] 
+	  [ole/ole2nls.c] [ole/folders.c] [ole/moniker.c] [ole/ole2.c]
+	  [graphics/fontengine.c] [graphics/ddraw.c] [graphics/env.c]
+	  [graphics/driver.c] [graphics/escape.c]
+	Changed fprintf's to proper debug-macros.
+
+	* [include/winnls.h]
+	Added some flags (for internal use).
+
+	* [ole/ole2nls.c] 
+	Added the Unicode core function, and worked out a way to hide
+	the commonality of the core.
+
+	* [relay32/kernel32.spec]
+	Added support for GetDate/Time32A/W.
+
+Wed Apr 22 09:16:03 1998  Gordon Chaffee  <chaffee@cs.berkeley.edu>
+
+	* [win32/code_page.c]
+	Fixed problem with MultiByteToWideChar that was introduced in
+	last release.  Made MultiByteToWideChar more compatible with Win32.
+
+	* [graphics/x11drv/graphics.c]
+	Fixed problem with drawing arcs.
+
+Tue Apr 21 11:24:58 1998  Constantine Sapuntzakis  <csapuntz@tma-1.lcs.mit.edu>
+
+	*  [ole/ole2nls.c]
+	Move stuff from 0x409 case to Lang_En. 
+
+	*  [relay32/user32.spec] [windows/winpos.c]
+	Added stubs for GetWindowRgn32 and SetWindowRgn32. Makes Office
+	Paperclip happy.
+
+Tue Apr 21 11:16:16 1998  Constantine Sapuntzakis  <csapuntz@tma-1.lcs.mit.edu>
+
+	*  [loader/pe_image.c]
+	If image is relocated, TLS addresses need to be adjusted.
+
+	* [debugger/*.c]
+	Generalized tests for 32-bit segments.
+
+Tue Apr 21 02:04:59 1998  James Juran  <jrj120@psu.edu>
+	
+	* [misc/*.c] [miscemu/*.c] [msdos/*.c] [if1632/*.c] 
+	  [include/*.h] [loader/*.c] [memory/*.c] [multimedia/*.c] 
+	  [objects/*.c]
+	Almost all fprintf statements converted to appropriate 
+	debug messages.
+
+	* [README]
+	Updated "GETTING MORE INFORMATION" section to include WineHQ.
+
+	* [documentation/debugger]
+	Fixed typo.
+
+	* [windows/defwnd.c]
+	Added function documentation.
+
+Sun Apr 19 16:30:58 1998  Marcus Meissner <marcus@mud.de>
+
+	* [Make.rules.in]
+	Added lint target (using lclint).
+
+	* [relay32/oleaut32.spec][relay32/Makefile.in][ole/typelib.c]
+	  [ole/ole2disp.c]
+	Added oleaut32 spec, added some SysString functions.
+
+	* [if1632/signal.c]
+	Added printing of faultaddress in Linux (using CR2 debug register).
+
+	* [configure.in]
+	Added <sys/types.h> for statfs checks.
+
+	* [loader/*.c][debugger/break.c][debugger/hash.c]
+	Started to split win32/win16 module handling, preparing support
+	for other binary formats (like ELF).
+
+Sat Apr 18 10:07:41 1998  Rein Klazes <rklazes@casema.net>
+
+	* [misc/registry.c]
+	Fixed a bug that made RegQueryValuexxx returning
+	incorrect registry values.
+
+Fri Apr 17 22:59:22 1998  Alexander V. Lukyanov <lav@long.yar.ru>
+
+	* [misc/lstr.c]
+	FormatMessage32*: remove linefeed when nolinefeed set;
+	check for target underflow.
+
+Fri Apr 17 00:38:14 1998  Alexander V. Lukyanov <lav@long.yar.ru>
+
+	* [misc/crtdll.c]
+	Implement xlat_file_ptr for CRT stdin/stdout/stderr address
+	translation.
+
+Wed Apr 15 20:43:56 1998  Jim Peterson <jspeter@birch.ee.vt.edu>
+
+	* [controls/menu.c]
+	Added 'odaction' parameter to MENU_DrawMenuItem() and redirected
+	WM_DRAWITEM messages to GetWindow(hwnd,GW_OWNER).
+
+Tue Apr 14 16:17:55 1998  Berend Reitsma <berend@united-info.com>
+
+	* [graphics/metafiledrv/init.c]	[graphics/painting.c] 
+	  [graphics/win16drv/init.c] [graphics/x11drv/graphics.c]
+	  [graphics/x11drv/init.c] [include/gdi.h] [include/x11drv.h]
+	  [relay32/gdi32.spec]
+	Added PolyPolyline routine.
+
+	* [windows/winproc.c]
+	Changed WINPROC_GetProc() to return proc instead of &(jmp proc).
+
+----------------------------------------------------------------------
 Sun Apr 12 12:22:23 1997  Andreas Mohr <100.30936@germany.net>
 
 	* [files/drive.c]
diff --git a/Make.rules.in b/Make.rules.in
index d8e6e93..76a2f1c 100644
--- a/Make.rules.in
+++ b/Make.rules.in
@@ -37,6 +37,8 @@
 RM        = rm -f
 MKDIR     = mkdir
 C2MAN     = @C2MAN@
+LINT      = lclint
+LINTFLAGS = +posixlib +gnuextensions +trytorecover
 BUILD     = $(TOPOBJDIR)/tools/build@PROGEXT@
 MAKEDEP   = $(TOPOBJDIR)/tools/makedep@PROGEXT@
 WINERC    = $(TOPOBJDIR)/rc/winerc@PROGEXT@
@@ -114,6 +116,16 @@
 man: $(C_SRCS)
 	for i in $(C_SRCS); do $(C2MAN) -L -o$(TOPOBJDIR)/documentation/man3w -S3w $(DIVINCL) $$i; done
 
+# Rule for linting
+
+lint:
+	for i in $(C_SRCS); do $(LINT) $(LINTFLAGS) -D__WINE__ $(OPTIONS) $(DIVINCL) $(X_CFLAGS) $$i; done
+
+# Rule for html pages
+
+html: $(C_SRCS)
+	for i in $(C_SRCS); do $(C2MAN) -L -o$(TOPOBJDIR)/documentation/html -Th -iwindows.h  $(DIVINCL) $$i; done
+
 # Misc. rules
 
 depend:: $(MAKEDEP) $(C_SRCS) $(RC_SRCS) $(EXTRA_SRCS)
diff --git a/Makefile.in b/Makefile.in
index 003637c..c9548fa 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -34,6 +34,7 @@
 	ipc \
 	library \
 	loader \
+	loader/ne \
 	memory \
 	misc \
 	msdos \
@@ -78,6 +79,7 @@
 	graphics/x11drv/x11drv.o \
 	ipc/ipc.o \
 	loader/loader.o \
+	loader/ne/ne.o \
 	memory/memory.o \
 	misc/misc.o \
 	msdos/msdos.o \
@@ -149,6 +151,10 @@
 	-$(MKDIR) $(TOPOBJDIR)/documentation/man3w
 	for i in $(LIBSUBDIRS); do (cd $$i && $(MAKE) man); done
 
+htmlpages:
+	-$(MKDIR) $(TOPOBJDIR)/documentation/html
+	for i in $(LIBSUBDIRS); do (cd $$i && $(MAKE) html); done
+
 clean::
 	for i in $(ALLSUBDIRS); do (cd $$i; $(MAKE) clean) || exit 1; done
 	for i in include; do (cd $$i; $(RM) *.o \#*\# *~ *.bak *.orig *.rej *.flc); done
diff --git a/README b/README
index dd56ba1..25be8f4 100644
--- a/README
+++ b/README
@@ -83,10 +83,21 @@
 
 5. GETTING MORE INFORMATION
 
-The best place to get help or to report bugs is the Usenet newsgroup
-comp.emulators.ms-windows.wine. The Wine FAQ is posted there every
-month. Also, you may want to browse old messages on www.dejanews.com 
-to check whether your problem is already fixed. 
+Usenet:	The best place to get help or to report bugs is the Usenet newsgroup
+	comp.emulators.ms-windows.wine. The Wine FAQ is posted there every
+	month. 
+
+WWW:	Please browse old messages on http://www.dejanews.com to check whether 
+	your problem is already fixed before posting a bug report to the 
+	newsgroup. 
+
+	A great deal of information about Wine is available from WineHQ at
+	http://www.winehq.com. Untested patches against the current
+	release are available at http://www.winehq.com/patches.  
+
+
+FAQ:	The Wine FAQ is located at http://home.pacbell.net/dagar/wine.html.
+
 
 If you add something, or fix a bug, please send a patch ('diff -u'
 format preferred) to julliard@lrc.epfl.ch for inclusion in the next
diff --git a/configure b/configure
index 1d32b1c..8a11a0c 100755
--- a/configure
+++ b/configure
@@ -2820,6 +2820,7 @@
 #line 2821 "configure"
 #include "confdefs.h"
 
+	#include <sys/types.h>
 	#ifdef HAVE_SYS_PARAM_H
 	# include <sys/param.h>
 	#endif
@@ -2841,7 +2842,7 @@
 	
 ; return 0; }
 EOF
-if { (eval echo configure:2845: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+if { (eval echo configure:2846: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
   rm -rf conftest*
   wine_cv_statfs_bavail=yes
 else
@@ -2865,7 +2866,7 @@
 fi
 
 echo $ac_n "checking "for statfs.f_bfree"""... $ac_c" 1>&6
-echo "configure:2869: checking "for statfs.f_bfree"" >&5
+echo "configure:2870: checking "for statfs.f_bfree"" >&5
 if eval "test \"`echo '$''{'wine_cv_statfs_bfree'+set}'`\" = set"; then
   echo $ac_n "(cached) $ac_c" 1>&6
 else
@@ -2874,9 +2875,10 @@
         wine_cv_statfs_bfree=no
     else
     	cat > conftest.$ac_ext <<EOF
-#line 2878 "configure"
+#line 2879 "configure"
 #include "confdefs.h"
 
+	#include <sys/types.h>
 	#ifdef HAVE_SYS_PARAM_H
 	# include <sys/param.h>
 	#endif
@@ -2898,7 +2900,7 @@
 	
 ; return 0; }
 EOF
-if { (eval echo configure:2902: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+if { (eval echo configure:2904: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
   rm -rf conftest*
   wine_cv_statfs_bfree=yes
 else
@@ -3043,6 +3045,7 @@
 library/Makefile
 libtest/Makefile
 loader/Makefile
+loader/ne/Makefile
 memory/Makefile
 misc/Makefile
 miscemu/Makefile
@@ -3172,6 +3175,7 @@
 library/Makefile
 libtest/Makefile
 loader/Makefile
+loader/ne/Makefile
 memory/Makefile
 misc/Makefile
 miscemu/Makefile
diff --git a/configure.in b/configure.in
index 5dba6fa..d783a00 100644
--- a/configure.in
+++ b/configure.in
@@ -227,6 +227,7 @@
         wine_cv_statfs_bavail=no
     else
     	AC_TRY_COMPILE([
+	#include <sys/types.h>
 	#ifdef HAVE_SYS_PARAM_H
 	# include <sys/param.h>
 	#endif
@@ -257,6 +258,7 @@
         wine_cv_statfs_bfree=no
     else
     	AC_TRY_COMPILE([
+	#include <sys/types.h>
 	#ifdef HAVE_SYS_PARAM_H
 	# include <sys/param.h>
 	#endif
@@ -303,6 +305,7 @@
 library/Makefile
 libtest/Makefile
 loader/Makefile
+loader/ne/Makefile
 memory/Makefile
 misc/Makefile
 miscemu/Makefile
diff --git a/controls/menu.c b/controls/menu.c
index f9efbf8..3cfe51f 100644
--- a/controls/menu.c
+++ b/controls/menu.c
@@ -817,7 +817,7 @@
  * Draw a single menu item.
  */
 static void MENU_DrawMenuItem( HWND32 hwnd, HDC32 hdc, MENUITEM *lpitem,
-			       UINT32 height, BOOL32 menuBar )
+			       UINT32 height, BOOL32 menuBar, UINT32 odaction )
 {
     RECT32 rect;
 
@@ -843,7 +843,6 @@
     {
         DRAWITEMSTRUCT32 dis;
 
-        TRACE(menu, "Ownerdraw!\n" );
         dis.CtlType   = ODT_MENU;
         dis.itemID    = lpitem->wID;
         dis.itemData  = (DWORD)lpitem->text;
@@ -851,11 +850,16 @@
         if (lpitem->fState & MF_CHECKED) dis.itemState |= ODS_CHECKED;
         if (lpitem->fState & MF_GRAYED)  dis.itemState |= ODS_GRAYED;
         if (lpitem->fState & MF_HILITE)  dis.itemState |= ODS_SELECTED;
-        dis.itemAction = ODA_DRAWENTIRE | ODA_SELECT | ODA_FOCUS;
+        dis.itemAction = odaction; /* ODA_DRAWENTIRE | ODA_SELECT | ODA_FOCUS; */
         dis.hwndItem   = hwnd;
         dis.hDC        = hdc;
         dis.rcItem     = lpitem->rect;
-        SendMessage32A( hwnd, WM_DRAWITEM, 0, (LPARAM)&dis );
+        TRACE(menu, "Ownerdraw: itemID=%d, itemState=%d, itemAction=%d, "
+	      "hwndItem=%04x, hdc=%04x, rcItem={%d,%d,%d,%d}, rcItem=%p\n",dis.itemID,
+	      dis.itemState, dis.itemAction, dis.hwndItem, dis.hDC,
+	      dis.rcItem.left, dis.rcItem.top, dis.rcItem.right,
+	      dis.rcItem.bottom, dis.rcItem );
+        SendMessage32A( GetWindow32(hwnd,GW_OWNER), WM_DRAWITEM, 0, (LPARAM)&dis );
         return;
     }
 
@@ -1114,7 +1118,8 @@
 		UINT32 u;
 
 		for (u = menu->nItems, item = menu->items; u > 0; u--, item++)
-		    MENU_DrawMenuItem( hwnd, hdc, item, menu->Height, FALSE );
+		    MENU_DrawMenuItem( hwnd, hdc, item, menu->Height, FALSE,
+				       ODA_DRAWENTIRE );
 
 	    }
 	} else SelectObject32( hdc, hPrevBrush );
@@ -1156,7 +1161,8 @@
     if (lppop->nItems == 0) return SYSMETRICS_CYMENU;
     for (i = 0; i < lppop->nItems; i++)
     {
-	MENU_DrawMenuItem( hwnd, hDC, &lppop->items[i], lppop->Height, TRUE );
+	MENU_DrawMenuItem( hwnd, hDC, &lppop->items[i], lppop->Height, TRUE,
+			   ODA_DRAWENTIRE );
     }
     return lppop->Height;
 } 
@@ -1339,7 +1345,8 @@
     {
 	lppop->items[lppop->FocusedItem].fState &= ~(MF_HILITE|MF_MOUSESELECT);
 	MENU_DrawMenuItem(lppop->hWnd,hdc,&lppop->items[lppop->FocusedItem],
-                          lppop->Height, !(lppop->wFlags & MF_POPUP) );
+                          lppop->Height, !(lppop->wFlags & MF_POPUP),
+			  ODA_SELECT );
     }
 
       /* Highlight new item (if any) */
@@ -1348,7 +1355,8 @@
     {
 	lppop->items[lppop->FocusedItem].fState |= MF_HILITE;
 	MENU_DrawMenuItem( lppop->hWnd, hdc, &lppop->items[lppop->FocusedItem],
-                           lppop->Height, !(lppop->wFlags & MF_POPUP) );
+                           lppop->Height, !(lppop->wFlags & MF_POPUP),
+			   ODA_SELECT );
         if (sendMenuSelect)
         {
             MENUITEM *ip = &lppop->items[lppop->FocusedItem];
@@ -1742,7 +1750,7 @@
         if (menu->wFlags & MF_POPUP) hdc = GetDC32( menu->hWnd );
         else hdc = GetDCEx32( menu->hWnd, 0, DCX_CACHE | DCX_WINDOW);
         item->fState |= MF_HILITE;
-        MENU_DrawMenuItem( menu->hWnd, hdc, item, menu->Height, !(menu->wFlags & MF_POPUP) ); 
+        MENU_DrawMenuItem( menu->hWnd, hdc, item, menu->Height, !(menu->wFlags & MF_POPUP), ODA_DRAWENTIRE ); 
 	ReleaseDC32( menu->hWnd, hdc );
     }
     if (!item->rect.top && !item->rect.left && !item->rect.bottom && !item->rect.right)
diff --git a/debugger/break.c b/debugger/break.c
index f584ba9..17e055e 100644
--- a/debugger/break.c
+++ b/debugger/break.c
@@ -339,37 +339,14 @@
     NE_MODULE *pModule;
     BOOL32 ok;
     DBG_ADDR addr = { NULL, 0, 0 };
+    WINE_MODREF *wm;
 
     for (ok = ModuleFirst(&entry); ok; ok = ModuleNext(&entry))
     {
-        if (!(pModule = MODULE_GetPtr( entry.hModule ))) continue;
+        if (!(pModule = MODULE_GetPtr16( entry.hModule ))) continue;
         if (pModule->flags & NE_FFLAGS_LIBMODULE) continue;  /* Library */
 
-        if (pModule->flags & NE_FFLAGS_WIN32)  /* PE module */
-        {
-            PE_MODREF *pem = PROCESS_Current()->modref_list;
-            if (!pem)
-            {
-                addr.seg = 0;
-                addr.off = (DWORD)RVA_PTR( pModule->module32,
-                                           OptionalHeader.AddressOfEntryPoint);
-            }
-            else
-            {
-                while (pem)
-                {
-                   if (pem->module == pModule->module32) break;
-                   pem = pem->next;
-                }
-                if (!pem) continue;
-                addr.seg = 0;
-                addr.off = (DWORD)RVA_PTR( pem->module,
-                                           OptionalHeader.AddressOfEntryPoint);
-            }
-            fprintf( stderr, "Win32 task '%s': ", entry.szModule );
-            DEBUG_AddBreakpoint( &addr );
-        }
-        else  /* NE module */
+        if (!(pModule->flags & NE_FFLAGS_WIN32))  /* NE module */
         {
             addr.seg = NE_SEG_TABLE(pModule)[pModule->cs-1].selector;
             addr.off = pModule->ip;
@@ -377,6 +354,12 @@
             DEBUG_AddBreakpoint( &addr );
         }
     }
+    for (wm=PROCESS_Current()->modref_list;wm;wm=wm->next) {
+	addr.seg = 0;
+	addr.off =(DWORD)RVA_PTR(wm->module,OptionalHeader.AddressOfEntryPoint);
+        fprintf( stderr, "Win32 module '%s': ", wm->modname );
+        DEBUG_AddBreakpoint( &addr );
+    }
 
     DEBUG_SetBreakpoints( TRUE );  /* Setup breakpoints */
 }
@@ -394,15 +377,14 @@
     DBG_ADDR cond_addr;
     int bpnum;
     struct list_id list;
-    WORD cs;
 
       /* If not single-stepping, back up over the int3 instruction */
     if (!(EFL_reg(&DEBUG_context) & STEP_FLAG)) EIP_reg(&DEBUG_context)--;
 
-    GET_CS(cs);
-    addr.seg = (CS_reg(&DEBUG_context) == cs) ? 0 : CS_reg(&DEBUG_context);
+    addr.seg = CS_reg(&DEBUG_context);
     addr.off = EIP_reg(&DEBUG_context);
-        
+    if (IS_SELECTOR_SYSTEM(addr.seg)) addr.seg = 0;
+
     bpnum = DEBUG_FindBreakpoint( &addr );
     breakpoints[0].enabled = 0;  /* disable the step-over breakpoint */
 
@@ -519,11 +501,10 @@
     unsigned int * value;
     enum exec_mode ret_mode;
     BYTE *instr;
-    WORD cs;
 
-    GET_CS(cs);
-    addr.seg = (CS_reg(&DEBUG_context) == cs) ? 0 : CS_reg(&DEBUG_context);
+    addr.seg = CS_reg(&DEBUG_context);
     addr.off = EIP_reg(&DEBUG_context);
+    if (IS_SELECTOR_SYSTEM(addr.seg)) addr.seg = 0;
 
     /*
      * This is the mode we will be running in after we finish.  We would like
diff --git a/debugger/db_disasm.c b/debugger/db_disasm.c
index bd8e11f..05686a7 100644
--- a/debugger/db_disasm.c
+++ b/debugger/db_disasm.c
@@ -1009,8 +1009,6 @@
     switch(size)
     {
     case BYTE:
-        fprintf(stderr, "0x%2.2x", addr & 0xff );
-        break;
     case WORD:
         fprintf(stderr, "0x%4.4x", addr & 0xffff );
         break;
@@ -1162,9 +1160,7 @@
 	 * Set this so we get can supress the printout if we need to.
 	 */
 	db_display = display;
-
-        if (!addr->seg) db_disasm_16 = FALSE;
-        else db_disasm_16 = !(GET_SEL_FLAGS(addr->seg) & LDT_FLAGS_32BIT);
+        db_disasm_16 = !IS_SELECTOR_32BIT(addr->seg);
 
 	get_value_inc( inst, addr, 1, FALSE );
 
@@ -1212,13 +1208,16 @@
 		    seg = "%gs";
 		    break;
 		case 0xf0:
-		    fprintf(stderr,"lock ");
+		    if( db_display )
+			fprintf(stderr,"lock ");
 		    break;
 		case 0xf2:
-		    fprintf(stderr,"repne ");
+		    if( db_display )
+			fprintf(stderr,"repne ");
 		    break;
 		case 0xf3:
-		    fprintf(stderr,"repe ");	/* XXX repe VS rep */
+		    if( db_display )
+			fprintf(stderr,"repe ");	/* XXX repe VS rep */
 		    break;
 		default:
 		    prefix = FALSE;
diff --git a/debugger/dbg.y b/debugger/dbg.y
index 7a54e7d..f7963ef 100644
--- a/debugger/dbg.y
+++ b/debugger/dbg.y
@@ -17,6 +17,7 @@
 #include "win.h"
 #include "winnt.h"
 #include "debugger.h"
+#include "neexe.h"
 
 #include "expr.h"
 
@@ -253,7 +254,7 @@
     | tINFO tCLASS expr_value tEOL    { CLASS_DumpClass( (CLASS *)$3 ); 
  					     DEBUG_FreeExprMem(); }
     | tINFO tSHARE tEOL		{ DEBUG_InfoShare(); }
-    | tINFO tMODULE expr_value tEOL   { MODULE_DumpModule( $3 ); 
+    | tINFO tMODULE expr_value tEOL   { NE_DumpModule( $3 ); 
  					     DEBUG_FreeExprMem(); }
     | tINFO tQUEUE expr_value tEOL    { QUEUE_DumpQueue( $3 ); 
  					     DEBUG_FreeExprMem(); }
@@ -270,7 +271,7 @@
 
 walk_command:
       tWALK tCLASS tEOL         { CLASS_WalkClasses(); }
-    | tWALK tMODULE tEOL        { MODULE_WalkModules(); }
+    | tWALK tMODULE tEOL        { NE_WalkModules(); }
     | tWALK tQUEUE tEOL         { QUEUE_WalkQueues(); }
     | tWALK tWND tEOL           { WIN_WalkWindows( 0, 0 ); }
     | tWALK tWND tNUM tEOL      { WIN_WalkWindows( $3, 0 ); }
@@ -476,9 +477,7 @@
         XUngrabServer( display );
         XFlush( display );
 
-        if (!addr.seg) newmode = 32;
-        else newmode = (GET_SEL_FLAGS(addr.seg) & LDT_FLAGS_32BIT) ? 32 : 16;
-
+        newmode = IS_SELECTOR_32BIT(addr.seg) ? 32 : 16;
         if (newmode != dbg_mode)
             fprintf(stderr,"In %d bit mode.\n", dbg_mode = newmode);
 
diff --git a/debugger/dbgmain.c b/debugger/dbgmain.c
index 04cf7ac..2f47132 100644
--- a/debugger/dbgmain.c
+++ b/debugger/dbgmain.c
@@ -103,12 +103,12 @@
   exit(0);
 }
 
-NE_MODULE *MODULE_GetPtr( HMODULE16 hModule )
+NE_MODULE *MODULE_GetPtr16( HMODULE16 hModule )
 {
   exit(0);
 }
 
-FARPROC16 MODULE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
+FARPROC16 NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
 {
   exit(0);
 }
diff --git a/debugger/hash.c b/debugger/hash.c
index aba001b..492769c 100644
--- a/debugger/hash.c
+++ b/debugger/hash.c
@@ -754,8 +754,7 @@
     {
         cpnt += *cpnt + 1 + sizeof(WORD);
         sprintf( buffer, "%s.%.*s", name, *cpnt, cpnt + 1 );
-        if ((address = MODULE_GetEntryPoint( hModule,
-                                             *(WORD *)(cpnt + *cpnt + 1) )))
+        if ((address = NE_GetEntryPoint(hModule, *(WORD *)(cpnt + *cpnt + 1))))
         {
             addr.seg = HIWORD(address);
             addr.off = LOWORD(address);
@@ -772,8 +771,7 @@
     {
         cpnt += *cpnt + 1 + sizeof(WORD);
         sprintf( buffer, "%s.%.*s", name, *cpnt, cpnt + 1 );
-        if ((address = MODULE_GetEntryPoint( hModule,
-                                             *(WORD *)(cpnt + *cpnt + 1) )))
+        if ((address = NE_GetEntryPoint(hModule, *(WORD *)(cpnt + *cpnt + 1))))
         {
             addr.seg = HIWORD(address);
             addr.off = LOWORD(address);
@@ -875,17 +873,20 @@
     MODULEENTRY entry;
     NE_MODULE *pModule;
     BOOL32 ok;
+    WINE_MODREF	*wm;
 
     for (ok = ModuleFirst(&entry); ok; ok = ModuleNext(&entry))
     {
-        if (!(pModule = MODULE_GetPtr( entry.hModule ))) continue;
+        if (!(pModule = MODULE_GetPtr16( entry.hModule ))) continue;
         fprintf( stderr, " %s", entry.szModule );
 
-        if (pModule->flags & NE_FFLAGS_WIN32)  /* PE module */
-            DEBUG_LoadEntryPoints32( pModule->module32, entry.szModule );
-        else  /* NE module */
+        if (!(pModule->flags & NE_FFLAGS_WIN32))  /* NE module */
             DEBUG_LoadEntryPoints16( entry.hModule, pModule, entry.szModule );
     }
+    for (wm=PROCESS_Current()->modref_list;wm;wm=wm->next) {
+        fprintf( stderr, " %s", wm->modname );
+	DEBUG_LoadEntryPoints32( wm->module, wm->modname );
+    }
 }
 
 
diff --git a/debugger/registers.c b/debugger/registers.c
index 6ab0bac..b6a8a23 100644
--- a/debugger/registers.c
+++ b/debugger/registers.c
@@ -192,6 +192,59 @@
 #endif
 }
 
+/***********************************************************************
+ *           DEBUG_Flags
+ *
+ * Return Flag String.
+ */
+char *DEBUG_Flags( DWORD flag, char *buf )
+{
+    char *pt;
+
+    strcpy( buf, "   - 00      - - - " );
+    pt = buf + strlen( buf );
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00000001 ) *pt = 'C'; /* Carry Falg */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00000002 ) *pt = '1';
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00000004 ) *pt = 'P'; /* Parity Flag */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00000008 ) *pt = '-';
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00000010 ) *pt = 'A'; /* Auxiliary Carry Flag */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00000020 ) *pt = '-';
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00000040 ) *pt = 'Z'; /* Zero Flag */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00000080 ) *pt = 'S'; /* Sign Flag */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00000100 ) *pt = 'T'; /* Trap/Trace Flag */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00000200 ) *pt = 'I'; /* Interupt Enable Flag */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00000400 ) *pt = 'D'; /* Direction Indicator */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00000800 ) *pt = 'O'; /* Overflow Flag */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00001000 ) *pt = '1'; /* I/O Privilage Level */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00002000 ) *pt = '1'; /* I/O Privilage Level */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00004000 ) *pt = 'N'; /* Nested Task Flag */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00008000 ) *pt = '-';
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00010000 ) *pt = 'R'; /* Resume Flag */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00020000 ) *pt = 'V'; /* Vritual Mode Flag */
+    if ( buf >= pt-- ) return( buf );
+    if ( flag & 0x00040000 ) *pt = 'a'; /* Alignment Check Flag */
+    if ( buf >= pt-- ) return( buf );
+    return( buf );
+}
+
 
 /***********************************************************************
  *           DEBUG_InfoRegisters
@@ -200,6 +253,8 @@
  */
 void DEBUG_InfoRegisters(void)
 {
+    char flag[33];
+
     fprintf(stderr,"Register dump:\n");
 
     /* First get the segment registers out of the way */
@@ -209,9 +264,10 @@
              (WORD)FS_reg(&DEBUG_context), (WORD)GS_reg(&DEBUG_context) );
     if (dbg_mode == 16)
     {
-        fprintf( stderr,"\n IP:%04x SP:%04x BP:%04x FLAGS:%04x\n",
+        fprintf( stderr,"\n IP:%04x SP:%04x BP:%04x FLAGS:%04x(%s)\n",
                  IP_reg(&DEBUG_context), SP_reg(&DEBUG_context),
-                 BP_reg(&DEBUG_context), FL_reg(&DEBUG_context) );
+                 BP_reg(&DEBUG_context), FL_reg(&DEBUG_context),
+		 DEBUG_Flags(FL_reg(&DEBUG_context), flag));
 	fprintf( stderr," AX:%04x BX:%04x CX:%04x DX:%04x SI:%04x DI:%04x\n",
                  AX_reg(&DEBUG_context), BX_reg(&DEBUG_context),
                  CX_reg(&DEBUG_context), DX_reg(&DEBUG_context),
@@ -219,9 +275,10 @@
     }
     else  /* 32-bit mode */
     {
-        fprintf( stderr, "\n EIP:%08lx ESP:%08lx EBP:%08lx EFLAGS:%08lx\n", 
+        fprintf( stderr, "\n EIP:%08lx ESP:%08lx EBP:%08lx EFLAGS:%08lx(%s)\n", 
                  EIP_reg(&DEBUG_context), ESP_reg(&DEBUG_context),
-                 EBP_reg(&DEBUG_context), EFL_reg(&DEBUG_context) );
+                 EBP_reg(&DEBUG_context), EFL_reg(&DEBUG_context),
+		 DEBUG_Flags(EFL_reg(&DEBUG_context), flag));
 	fprintf( stderr, " EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n", 
 		 EAX_reg(&DEBUG_context), EBX_reg(&DEBUG_context),
                  ECX_reg(&DEBUG_context), EDX_reg(&DEBUG_context) );
diff --git a/debugger/source.c b/debugger/source.c
index 1a37195..4d3715b 100644
--- a/debugger/source.c
+++ b/debugger/source.c
@@ -492,10 +492,9 @@
     last = DEBUG_LastDisassemble;
     if (!last.seg && !last.off)
     {
-        WORD cs;
-        GET_CS(cs);
-        last.seg = (CS_reg(&DEBUG_context) == cs) ? 0 : CS_reg(&DEBUG_context);
+        last.seg = CS_reg(&DEBUG_context);
         last.off = EIP_reg(&DEBUG_context);
+        if (IS_SELECTOR_SYSTEM(last.seg)) last.seg = 0;
     }
     for (i=0;i<offset;i++)
       if (!_disassemble(&last)) break;
diff --git a/debugger/stack.c b/debugger/stack.c
index 37f6d5a..2fe17c0 100644
--- a/debugger/stack.c
+++ b/debugger/stack.c
@@ -51,24 +51,16 @@
  */
 void DEBUG_InfoStack(void)
 {
-    DBG_ADDR addr;
-    WORD ss;
+    DBG_ADDR addr = { NULL, SS_reg(&DEBUG_context), ESP_reg(&DEBUG_context) };
 
     fprintf(stderr,"Stack dump:\n");
-    GET_SS(ss);
-    if ((SS_reg(&DEBUG_context) == ss) ||
-        (GET_SEL_FLAGS(SS_reg(&DEBUG_context)) & LDT_FLAGS_32BIT))
+    if (IS_SELECTOR_32BIT(addr.seg))
     {  /* 32-bit mode */
-        addr.seg = 0;
-        addr.off = ESP_reg(&DEBUG_context);
-	addr.type = NULL;
         DEBUG_ExamineMemory( &addr, 24, 'x' );
     }
     else  /* 16-bit mode */
     {
-        addr.seg = SS_reg(&DEBUG_context);
-        addr.off = SP_reg(&DEBUG_context);
-	addr.type = NULL;
+        addr.off &= 0xffff;
         DEBUG_ExamineMemory( &addr, 24, 'w' );
     }
     fprintf(stderr,"\n");
@@ -84,11 +76,9 @@
 {
     DBG_ADDR addr;
     int frameno = 0;
-    WORD ss;
 
     fprintf(stderr,"Backtrace:\n");
-    GET_SS(ss);
-    if (SS_reg(&DEBUG_context) == ss)  /* 32-bit mode */
+    if (IS_SELECTOR_SYSTEM(SS_reg(&DEBUG_context)))  /* system stack */
     {
         nframe = 1;
         if (frames) free( frames );
@@ -163,15 +153,13 @@
  */
 void DEBUG_SilentBackTrace(void)
 {
-    WORD ss;
     DBG_ADDR addr;
     int frameno = 0;
 
     nframe = 1;
     if (frames) free( frames );
     frames = (struct bt_info *) xmalloc( sizeof(struct bt_info) );
-    GET_SS(ss);
-    if (SS_reg(&DEBUG_context) == ss)  /* 32-bit mode */
+    if (IS_SELECTOR_SYSTEM(SS_reg(&DEBUG_context)))  /* system stack */
     {
         addr.seg = 0;
         addr.off = EIP_reg(&DEBUG_context);
diff --git a/documentation/debugging b/documentation/debugging
index 3e2b5a2..6de0cb5 100644
--- a/documentation/debugging
+++ b/documentation/debugging
@@ -119,8 +119,8 @@
   Since the failure happens usually directly before setting up the Messagebox
   you can start wine with "-debug" added to the commandline, set a breakpoint
   at "MessageBox32A" (called by win16 and win32 programs) and proceed with
-  "continue". With "-debugmsg +all" Wine will now stop directly directly
-  before setting up the Messagebox.  Proceed as explained above.
+  "continue". With "-debugmsg +all" Wine will now stop directly before 
+  setting up the Messagebox.  Proceed as explained above.
 
   You can also run wine using "wine -debugmsg +relay program.exe 2>&1|less -i"
   and in less search for messagebox.
diff --git a/documentation/wine.man b/documentation/wine.man
index 7eeb53c..0be4451 100644
--- a/documentation/wine.man
+++ b/documentation/wine.man
@@ -71,9 +71,8 @@
 env, event, exec, file, fixup, font, gdi, global, graphics, heap, hook,
 icon, int, key, keyboard, ldt, listbox, local, mci, mcianim, mciwave, mdi,
 menu, message, metafile, midi, mmio, mmsys, mmtime, module, msg, nonclient,
-ole, palette, profile, prop, reg, region, relay, resource, scroll, selector,
-sem, sendmsg, shm, stress, string, syscolor, task, text, timer, toolhelp,
-ver, vxd, win, win32, winsock.
+ole, palette, profile, prop, reg, region, relay, resource, scroll, segment,
+selector,sem, sendmsg, shm, stress, string, syscolor, task, text, timer, toolhelp,ver, vxd, win, win32, winsock.
 .TP
 .I -depth n
 Change the depth to use for multiple-depth screens
diff --git a/files/directory.c b/files/directory.c
index a780e36..0f211d7 100644
--- a/files/directory.c
+++ b/files/directory.c
@@ -129,7 +129,13 @@
     UINT32 ret;
     if (!(ret = GetEnvironmentVariable32A( "TMP", path, count )))
         if (!(ret = GetEnvironmentVariable32A( "TEMP", path, count )))
-            ret = GetCurrentDirectory32A( count, path );
+            if (!(ret = GetCurrentDirectory32A( count, path )))
+                return 0;
+    if ((ret < count - 1) && (path[ret-1] != '\\'))
+    {
+        path[ret++] = '\\';
+        path[ret]   = '\0';
+    }
     return ret;
 }
 
@@ -144,7 +150,13 @@
     UINT32 ret;
     if (!(ret = GetEnvironmentVariable32W( tmp, path, count )))
         if (!(ret = GetEnvironmentVariable32W( temp, path, count )))
-            ret = GetCurrentDirectory32W( count, path );
+            if (!(ret = GetCurrentDirectory32W( count, path )))
+                return 0;
+    if ((ret < count - 1) && (path[ret-1] != '\\'))
+    {
+        path[ret++] = '\\';
+        path[ret]   = '\0';
+    }
     return ret;
 }
 
diff --git a/files/drive.c b/files/drive.c
index 47b543d..c07d350 100644
--- a/files/drive.c
+++ b/files/drive.c
@@ -745,7 +745,7 @@
     {
     case TYPE_FLOPPY:  return DRIVE_REMOVABLE;
     case TYPE_HD:      return DRIVE_FIXED;
-    case TYPE_CDROM:   return DRIVE_REMOTE;
+    case TYPE_CDROM:   return DRIVE_REMOVABLE;
     case TYPE_NETWORK: return DRIVE_REMOTE;
     case TYPE_INVALID:
     default:           return DRIVE_CANNOTDETERMINE;
@@ -801,16 +801,22 @@
  *           GetCurrentDirectory32A   (KERNEL32.196)
  *
  * Returns "X:\\path\\etc\\".
+ *
+ * Despite the API description, return required length including the 
+ * terminating null when buffer too small. This is the real behaviour.
  */
 UINT32 WINAPI GetCurrentDirectory32A( UINT32 buflen, LPSTR buf )
 {
-    char *pref = "A:\\";
+    UINT32 ret;
     const char *s = DRIVE_GetDosCwd( DRIVE_GetCurrentDrive() );
+
     assert(s);
-    lstrcpyn32A( buf, pref, MIN( 4, buflen ) );
+    ret = strlen(s) + 3; /* length of WHOLE current directory */
+    if (ret >= buflen) return ret + 1;
+    lstrcpyn32A( buf, "A:\\", MIN( 4, buflen ) );
     if (buflen) buf[0] += DRIVE_GetCurrentDrive();
     if (buflen > 3) lstrcpyn32A( buf + 3, s, buflen - 3 );
-    return strlen(s) + 3; /* length of WHOLE current directory */
+    return ret;
 }
 
 
diff --git a/files/file.c b/files/file.c
index 721f11a..d94b7ff 100644
--- a/files/file.c
+++ b/files/file.c
@@ -632,10 +632,7 @@
     if (drive & TF_FORCEDRIVE)
         sprintf(temppath,"%c:", drive & ~TF_FORCEDRIVE );
     else
-    {
         GetTempPath32A( 132, temppath );
-        strcat( temppath, "\\" );
-    }
     return (UINT16)GetTempFileName32A( temppath, prefix, unique, buffer );
 }
 
@@ -1611,7 +1608,7 @@
         CloseHandle( h1 );
         return FALSE;
     }
-    while ((count = _lread32( h2, buffer, sizeof(buffer) )) > 0)
+    while ((count = _lread32( h1, buffer, sizeof(buffer) )) > 0)
     {
         char *p = buffer;
         while (count > 0)
diff --git a/files/profile.c b/files/profile.c
index 123ab91..037cfb0 100644
--- a/files/profile.c
+++ b/files/profile.c
@@ -477,15 +477,18 @@
                 PROFILE_CopyEntry( buffer, key->name, len - 1, handle_env );
                 len -= strlen(buffer) + 1;
                 buffer += strlen(buffer) + 1;
-                if (key->value)
-                {
-                    buffer[-1] = '=';
-                    PROFILE_CopyEntry(buffer, key->value, len - 1, handle_env);
-                    len -= strlen(buffer) + 1; 
-                    buffer += strlen(buffer) + 1;
-                }
             }
             *buffer = '\0';
+            if (len < 1)
+                /*If either lpszSection or lpszKey is NULL and the supplied
+                  destination buffer is too small to hold all the strings, 
+                  the last string is truncated and followed by two null characters.
+                  In this case, the return value is equal to cchReturnBuffer
+                  minus two. */
+            {
+		buffer[-1] = '\0';
+                return oldlen - 2;
+            }
             return oldlen - len + 1;
         }
         section = section->next;
diff --git a/graphics/ddraw.c b/graphics/ddraw.c
index 33c7d1b..92c118f 100644
--- a/graphics/ddraw.c
+++ b/graphics/ddraw.c
@@ -94,7 +94,7 @@
 
 HRESULT WINAPI 
 DSoundHelp(DWORD x,DWORD y,DWORD z) {
-	fprintf(stderr,"DSoundHelp(0x%08lx,0x%08lx,0x%08lx),stub!\n",x,y,z);
+	FIXME(ddraw,"(0x%08lx,0x%08lx,0x%08lx),stub!\n",x,y,z);
 	return 0;
 }
 
@@ -122,8 +122,12 @@
 		FE(DDBLTFX_ZBUFFERBASEDEST)
 	};
 	for (i=0;i<sizeof(flags)/sizeof(flags[0]);i++)
-		if (flags[i].mask & flagmask)
-			fprintf(stderr,"%s ",flags[i].name);
+	   if (flags[i].mask & flagmask) {
+	      DUMP("%s ",flags[i].name);
+	      
+	   };
+	DUMP("\n");
+	
 }
 
 static void _dump_DDBLTFAST(DWORD flagmask) {
@@ -140,7 +144,8 @@
 	};
 	for (i=0;i<sizeof(flags)/sizeof(flags[0]);i++)
 		if (flags[i].mask & flagmask)
-			fprintf(stderr,"%s ",flags[i].name);
+			DUMP("%s ",i,flags[i].name);
+	DUMP("\n");
 }
 
 static void _dump_DDBLT(DWORD flagmask) {
@@ -179,7 +184,7 @@
 	};
 	for (i=0;i<sizeof(flags)/sizeof(flags[0]);i++)
 		if (flags[i].mask & flagmask)
-			fprintf(stderr,"%s ",flags[i].name);
+			DUMP("%s ",i,flags[i].name);
 }
 
 static void _dump_DDSCAPS(DWORD flagmask) {
@@ -222,7 +227,8 @@
 	};
 	for (i=0;i<sizeof(flags)/sizeof(flags[0]);i++)
 		if (flags[i].mask & flagmask)
-			fprintf(stderr,"%s ",flags[i].name);
+			DUMP("%s ",flags[i].name);
+	DUMP("\n");
 }
 
 static void _dump_DDCAPS(DWORD flagmask) {
@@ -267,7 +273,8 @@
 	};
 	for (i=0;i<sizeof(flags)/sizeof(flags[0]);i++)
 		if (flags[i].mask & flagmask)
-			fprintf(stderr,"%s ",flags[i].name);
+			DUMP("%s ",flags[i].name);
+	DUMP("\n");
 }
 
 static void _dump_DDSD(DWORD flagmask) {
@@ -295,7 +302,8 @@
 	};
 	for (i=0;i<sizeof(flags)/sizeof(flags[0]);i++)
 		if (flags[i].mask & flagmask)
-			fprintf(stderr,"%s ",flags[i].name);
+			DUMP("%s ",i,flags[i].name);
+	DUMP("\n");
 }
 
 static int _getpixelformat(LPDIRECTDRAW ddraw,LPDDPIXELFORMAT pf) {
@@ -325,7 +333,7 @@
 		pf->xy.dwRGBAlphaBitMask= 0;
 		return 0;
 	}
-	fprintf(stderr,"_getpixelformat:oops?\n");
+	FIXME(ddraw,"_getpixelformat:oops?\n");
 	return DDERR_GENERIC;
 }
 
@@ -458,15 +466,15 @@
 		return 0;
 	}
 	if (dwFlags) {
-		fprintf(stderr,"IDirectDrawSurface(%p)->Blt(%p,%p,%p,%08lx,%p),stub!\n",
+		FIXME(ddraw,"(%p)->(%p,%p,%p,%08lx,%p),stub!\n",
 			this,rdst,src,rsrc,dwFlags,lpbltfx
 		);
-		if (rdst) fprintf(stderr,"	destrect :%dx%d-%dx%d\n",rdst->left,rdst->top,rdst->right,rdst->bottom);
-		if (rsrc) fprintf(stderr,"	srcrect  :%dx%d-%dx%d\n",rsrc->left,rsrc->top,rsrc->right,rsrc->bottom);
-		fprintf(stderr,"\tflags: ");_dump_DDBLT(dwFlags);fprintf(stderr,"\n");
+		if (rdst) TRACE(ddraw,"	destrect :%dx%d-%dx%d\n",rdst->left,rdst->top,rdst->right,rdst->bottom);
+		if (rsrc) TRACE(ddraw,"	srcrect  :%dx%d-%dx%d\n",rsrc->left,rsrc->top,rsrc->right,rsrc->bottom);
+		TRACE(ddraw,"\tflags: ");_dump_DDBLT(dwFlags);fprintf(stderr,"\n");
 	}
 	if (dwFlags & DDBLT_DDFX) {
-		fprintf(stderr,"	blitfx: ");_dump_DDBLTFX(lpbltfx->dwDDFX);fprintf(stderr,"\n");
+		TRACE(ddraw,"	blitfx: \n");_dump_DDBLTFX(lpbltfx->dwDDFX);
 	}
 	return 0;
 }
@@ -476,11 +484,11 @@
 ) {
 	int	i,bpp;
 	if (TRACE_ON(ddraw)) {
-	    fprintf(stderr,"IDirectDrawSurface(%p)->BltFast(%ld,%ld,%p,%p,%08lx),stub!\n",
+	    FIXME(ddraw,"(%p)->(%ld,%ld,%p,%p,%08lx),stub!\n",
 		    this,dstx,dsty,src,rsrc,trans
 	    );
-	    fprintf(stderr,"	trans:");_dump_DDBLTFAST(trans);fprintf(stderr,"\n");
-	    fprintf(stderr,"	srcrect: %dx%d-%dx%d\n",rsrc->left,rsrc->top,rsrc->right,rsrc->bottom);
+	    TRACE(ddraw,"	trans:");_dump_DDBLTFAST(trans);fprintf(stderr,"\n");
+	    TRACE(ddraw,"	srcrect: %dx%d-%dx%d\n",rsrc->left,rsrc->top,rsrc->right,rsrc->bottom);
 	}
 	bpp = this->s.ddraw->d.depth/8;
 	for (i=0;i<rsrc->bottom-rsrc->top;i++) {
@@ -495,7 +503,7 @@
 static HRESULT WINAPI IDirectDrawSurface_BltBatch(
 	LPDIRECTDRAWSURFACE this,LPDDBLTBATCH ddbltbatch,DWORD x,DWORD y
 ) {
-	fprintf(stderr,"IDirectDrawSurface(%p)->BltBatch(%p,%08lx,%08lx),stub!\n",
+	TRACE(ddraw,"(%p)->BltBatch(%p,%08lx,%08lx),stub!\n",
 		this,ddbltbatch,x,y
 	);
 	return 0;
@@ -560,12 +568,11 @@
         TRACE(ddraw, "(%p)->GetAttachedSurface(%p,%p)\n",
 		     this, lpddsd, lpdsf);
 	if (TRACE_ON(ddraw)) {
-		fprintf(stderr,"	caps ");
+		TRACE(ddraw,"	caps ");
 		_dump_DDSCAPS(lpddsd->dwCaps);
-		fprintf(stderr,"\n");
 	}
 	if (!(lpddsd->dwCaps & DDSCAPS_BACKBUFFER)) {
-		fprintf(stderr,"IDirectDrawSurface::GetAttachedSurface():whoops, can only handle backbuffers for now\n");
+		FIXME(ddraw,"whoops, can only handle backbuffers for now\n");
 		return E_FAIL;
 	}
 	/* FIXME: should handle more than one backbuffer */
@@ -586,7 +593,7 @@
 }
 
 static HRESULT WINAPI IDirectDrawSurface_GetBltStatus(LPDIRECTDRAWSURFACE this,DWORD dwFlags) {
-	fprintf(stderr,"IDirectDrawSurface(%p)->GetBltStatus(0x%08lx),stub!\n",
+	FIXME(ddraw,"(%p)->(0x%08lx),stub!\n",
 		this,dwFlags
 	);
 	return 0;
@@ -595,7 +602,7 @@
 static HRESULT WINAPI IDirectDrawSurface_GetOverlayPosition(
 	LPDIRECTDRAWSURFACE this,LPLONG x1,LPLONG x2
 ) {
-	fprintf(stderr,"IDirectDrawSurface(%p)->GetOverlayPosition(%p,%p),stub!\n",
+	FIXME(ddraw,"(%p)->(%p,%p),stub!\n",
 		this,x1,x2
 	);
 	return 0;
@@ -604,20 +611,20 @@
 static HRESULT WINAPI IDirectDrawSurface_SetClipper(
 	LPDIRECTDRAWSURFACE this,LPDIRECTDRAWCLIPPER clipper
 ) {
-	fprintf(stderr,"IDirectDrawSurface(%p)->SetClipper(%p),stub!\n",this,clipper);
+	FIXME(ddraw,"(%p)->(%p),stub!\n",this,clipper);
 	return 0;
 }
 
 static HRESULT WINAPI IDirectDrawSurface_AddAttachedSurface(
 	LPDIRECTDRAWSURFACE this,LPDIRECTDRAWSURFACE surf
 ) {
-	fprintf(stderr,"IDirectDrawSurface(%p)->AddAttachedSurface(%p),stub!\n",this,surf);
+	FIXME(ddraw,"(%p)->(%p),stub!\n",this,surf);
 	this->s.backbuffer = surf;
 	return 0;
 }
 
 static HRESULT WINAPI IDirectDrawSurface_GetDC(LPDIRECTDRAWSURFACE this,HDC32* lphdc) {
-	fprintf(stderr,"IDirectDrawSurface(%p)->GetDC(%p),stub!\n",this,lphdc);
+	FIXME(ddraw,"(%p)->GetDC(%p),stub!\n",this,lphdc);
 	return 0;
 }
 
@@ -625,7 +632,7 @@
         char    xrefiid[50];
 
         WINE_StringFromCLSID((LPCLSID)refiid,xrefiid);
-        TRACE(ddraw,"(%p)->QueryInterface(%s,%p)\n",this,xrefiid,obj);
+        TRACE(ddraw,"(%p)->(%s,%p)\n",this,xrefiid,obj);
 	
 	/* thats version 3 (DirectX 5) */
 	if (	!memcmp(&IID_IDirectDrawSurface3,refiid,sizeof(IID_IDirectDrawSurface3))) {
@@ -647,7 +654,7 @@
 		*obj = this;
 		return 0;
 	}
-	fprintf(stderr,"IDirectDrawSurface(%p):interface for IID %s _NOT_ found!\n",this,xrefiid);
+	WARN(ddraw,"(%p):interface for IID %s _NOT_ found!\n",this,xrefiid);
     	return OLE_E_ENUM_NOMORE;
 }
 
@@ -738,7 +745,7 @@
 }
 
 static HRESULT WINAPI IDirectDrawSurface2_EnumAttachedSurfaces(LPDIRECTDRAWSURFACE2 this,LPVOID context,LPDDENUMSURFACESCALLBACK esfcb) {
-	fprintf(stderr,"IDirectDrawSurface(%p)->EnumAttachedSurfaces(%p,%p),stub!\n",this,context,esfcb);
+	FIXME(ddraw,"(%p)->(%p,%p),stub!\n",this,context,esfcb);
 	return 0;
 }
 
@@ -876,7 +883,7 @@
 }
 
 static HRESULT WINAPI IDirectDrawSurface3_EnumAttachedSurfaces(LPDIRECTDRAWSURFACE3 this,LPVOID context,LPDDENUMSURFACESCALLBACK esfcb) {
-	fprintf(stderr,"IDirectDrawSurface3(%p)->EnumAttachedSurfaces(%p,%p),stub!\n",this,context,esfcb);
+	FIXME(ddraw,"(%p)->(%p,%p),stub!\n",this,context,esfcb);
 	return 0;
 }
 
@@ -942,7 +949,7 @@
 static HRESULT WINAPI IDirectDrawClipper_SetHwnd(
 	LPDIRECTDRAWCLIPPER this,DWORD x,HWND32 hwnd
 ) {
-	fprintf(stderr,"IDirectDrawClipper(%p)->SetHwnd(0x%08lx,0x%08lx),stub!\n",this,x,(DWORD)hwnd);
+	FIXME(ddraw,"(%p)->SetHwnd(0x%08lx,0x%08lx),stub!\n",this,x,(DWORD)hwnd);
 	return 0;
 }
 
@@ -974,7 +981,7 @@
 ) {
 	int	i;
 
-	fprintf(stderr,"IDirectDrawPalette(%p)->GetEntries(%08lx,%ld,%ld,%p),stub!\n",
+	FIXME(ddraw,"(%p)->GetEntries(%08lx,%ld,%ld,%p),stub!\n",
 		this,x,start,end,palent
 	);
 	for (i=start;i<end;i++) {
@@ -995,7 +1002,7 @@
 		this,x,start,end,palent
 	);
 	if (!this->cm) /* should not happen */ {
-		fprintf(stderr,"no colormap in SetEntries???\n");
+		ERR(ddraw,"no colormap in SetEntries???\n");
 		return DDERR_GENERIC;
 	}
 /* FIXME: free colorcells instead of freeing whole map */
@@ -1093,7 +1100,7 @@
 ) {
 	D3DDEVICEDESC	d1,d2;
 
-	fprintf(stderr,"IDirect3D2(%p)->EnumDevices(%p,%p),stub!\n",this,cb,context);
+	FIXME(ddraw,"(%p)->(%p,%p),stub!\n",this,cb,context);
 	d1.dwSize	= sizeof(d1);
 	d1.dwFlags	= 0;
 
@@ -1123,10 +1130,10 @@
 ) {
 	int	i;
 
-	TRACE(ddraw, "(%p)->CreateSurface(%p,%p,%p)\n",
+	TRACE(ddraw, "(%p)->(%p,%p,%p)\n",
 		     this,lpddsd,lpdsf,lpunk);
 	if (TRACE_ON(ddraw)) {
-		fprintf(stderr,"[w=%ld,h=%ld,flags ",lpddsd->dwWidth,lpddsd->dwHeight);
+		DUMP("[w=%ld,h=%ld,flags ",lpddsd->dwWidth,lpddsd->dwHeight);
 		_dump_DDSD(lpddsd->dwFlags);
 		fprintf(stderr,"caps ");
 		_dump_DDSCAPS(lpddsd->ddsCaps.dwCaps);
@@ -1170,7 +1177,7 @@
 		LPDIRECTDRAWSURFACE	back;
 
 		if (lpddsd->dwBackBufferCount>1)
-			fprintf(stderr,"urks, wants to have more than one backbuffer (%ld)!\n",lpddsd->dwBackBufferCount);
+			FIXME(ddraw,"urks, wants to have more than one backbuffer (%ld)!\n",lpddsd->dwBackBufferCount);
 
 		(*lpdsf)->s.backbuffer = back = (LPDIRECTDRAWSURFACE)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDirectDrawSurface));
 		this->lpvtbl->fnAddRef(this);
@@ -1198,7 +1205,7 @@
 static HRESULT WINAPI IDirectDraw_DuplicateSurface(
 	LPDIRECTDRAW this,LPDIRECTDRAWSURFACE src,LPDIRECTDRAWSURFACE *dst
 ) {
-	fprintf(stderr,"(%p)->DuplicateSurface(%p,%p)\n",this,src,dst);
+	FIXME(ddraw,"(%p)->(%p,%p) simply copies\n",this,src,dst);
 	*dst = src; /* FIXME */
 	return 0;
 }
@@ -1222,7 +1229,7 @@
 		FE(DDSCL_CREATEDEVICEWINDOW)
 	};
 
-	TRACE(ddraw,"(%p)->SetCooperativeLevel(%08lx,%08lx)\n",
+	TRACE(ddraw,"(%p)->(%08lx,%08lx)\n",
 		this,(DWORD)hwnd,cooplevel
 	);
 	if(TRACE_ON(ddraw)){
@@ -1243,7 +1250,7 @@
 	int	i,*depths,depcount;
 	char	buf[200];
 
-	TRACE(ddraw, "(%p)->SetDisplayMode(%ld,%ld,%ld)\n",
+	TRACE(ddraw, "(%p)->(%ld,%ld,%ld)\n",
 		      this, width, height, depth);
 
 	depths = TSXListDepths(display,DefaultScreen(display),&depcount);
@@ -1252,13 +1259,11 @@
 			break;
 	TSXFree(depths);
 	if (i==depcount) {/* not found */
-		sprintf(buf,"SetDisplayMode(w=%ld,h=%ld,d=%ld), unsupported depth!",width,height,depth);
-		MessageBox32A(0,buf,"WINE DirectDraw",MB_OK|MB_ICONSTOP);
+		ERR(ddraw,"(w=%ld,h=%ld,d=%ld), unsupported depth!\n",width,height,depth);
 		return DDERR_UNSUPPORTEDMODE;
 	}
 	if (this->d.fb_width < width) {
-		sprintf(buf,"SetDisplayMode(w=%ld,h=%ld,d=%ld), width %ld exceeds framebuffer width %ld",width,height,depth,width,this->d.fb_width);
-		MessageBox32A(0,buf,"WINE DirectDraw",MB_OK|MB_ICONSTOP);
+		ERR(ddraw,"SetDisplayMode(w=%ld,h=%ld,d=%ld), width %ld exceeds framebuffer width %ld\n",width,height,depth,width,this->d.fb_width);
 		return DDERR_UNSUPPORTEDMODE;
 	}
 	this->d.width	= width;
@@ -1286,7 +1291,7 @@
 static HRESULT WINAPI IDirectDraw_GetCaps(
 	LPDIRECTDRAW this,LPDDCAPS caps1,LPDDCAPS caps2
 )  {
-	TRACE(ddraw,"(%p)->GetCaps(%p,%p)\n",this,caps1,caps2);
+	TRACE(ddraw,"(%p)->(%p,%p)\n",this,caps1,caps2);
 	caps1->dwVidMemTotal = this->d.fb_memsize;
 	caps1->dwCaps = 0xffffffff&~(DDCAPS_BANKSWITCHED);		/* we can do anything */
 	caps1->ddsCaps.dwCaps = 0xffffffff;	/* we can do anything */
@@ -1301,7 +1306,7 @@
 static HRESULT WINAPI IDirectDraw_CreateClipper(
 	LPDIRECTDRAW this,DWORD x,LPDIRECTDRAWCLIPPER *lpddclip,LPUNKNOWN lpunk
 ) {
-	fprintf(stderr,"(%p)->CreateClipper(%08lx,%p,%p),stub!\n",
+	FIXME(ddraw,"(%p)->(%08lx,%p,%p),stub!\n",
 		this,x,lpddclip,lpunk
 	);
 	*lpddclip = (LPDIRECTDRAWCLIPPER)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDirectDrawClipper));
@@ -1313,7 +1318,7 @@
 static HRESULT WINAPI IDirectDraw_CreatePalette(
 	LPDIRECTDRAW this,DWORD x,LPPALETTEENTRY palent,LPDIRECTDRAWPALETTE *lpddpal,LPUNKNOWN lpunk
 ) {
-	TRACE(ddraw,"(%p)->CreatePalette(%08lx,%p,%p,%p)\n",
+	TRACE(ddraw,"(%p)->(%08lx,%p,%p,%p)\n",
 		this,x,palent,lpddpal,lpunk
 	);
 	*lpddpal = (LPDIRECTDRAWPALETTE)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDirectDrawPalette));
@@ -1329,7 +1334,7 @@
 }
 
 static HRESULT WINAPI IDirectDraw_RestoreDisplayMode(LPDIRECTDRAW this) {
-	TRACE(ddraw, "(%p)->RestoreDisplayMode()\n", 
+	TRACE(ddraw, "(%p)->()\n", 
 		      this);
 	Sleep(1000);
 	XF86DGADirectVideo(display,DefaultScreen(display),0);
@@ -1343,7 +1348,7 @@
 static HRESULT WINAPI IDirectDraw_WaitForVerticalBlank(
 	LPDIRECTDRAW this,DWORD x,HANDLE32 h
 ) {
-	TRACE(ddraw,"(%p)->WaitForVerticalBlank(0x%08lx,0x%08x)\n",this,x,h);
+	TRACE(ddraw,"(%p)->(0x%08lx,0x%08x)\n",this,x,h);
 	return 0;
 }
 
@@ -1369,7 +1374,7 @@
         char    xrefiid[50];
 
         WINE_StringFromCLSID((LPCLSID)refiid,xrefiid);
-        TRACE(ddraw,"(%p)->QueryInterface(%s,%p)\n",this,xrefiid,obj);
+        TRACE(ddraw,"(%p)->(%s,%p)\n",this,xrefiid,obj);
         if (!memcmp(&IID_IUnknown,refiid,sizeof(IID_IUnknown))) {
                 *obj = this;
 		this->lpvtbl->fnAddRef(this);
@@ -1408,14 +1413,14 @@
 		*obj = d3d;
 		return 0;
 	}
-	fprintf(stderr,"(%p):interface for IID %s _NOT_ found!\n",this,xrefiid);
+	WARN(ddraw,"(%p):interface for IID %s _NOT_ found!\n",this,xrefiid);
         return OLE_E_ENUM_NOMORE;
 }
 
 static HRESULT WINAPI IDirectDraw_GetVerticalBlankStatus(
 	LPDIRECTDRAW this,BOOL32 *status
 ) {
-        TRACE(ddraw,"(%p)->GetVerticalBlankSatus(%p)\n",this,status);
+        TRACE(ddraw,"(%p)->(%p)\n",this,status);
 	*status = TRUE;
 	return 0;
 }
@@ -1425,7 +1430,7 @@
 ) {
 	DDSURFACEDESC	ddsfd;
 
-	TRACE(ddraw,"(%p)->EnumDisplayModes(0x%08lx,%p,%p,%p)\n",this,dwFlags,lpddsfd,context,modescb);
+	TRACE(ddraw,"(%p)->(0x%08lx,%p,%p,%p)\n",this,dwFlags,lpddsfd,context,modescb);
 
 
 	_getpixelformat(this,&(ddsfd.ddpfPixelFormat));
@@ -1460,7 +1465,7 @@
 static HRESULT WINAPI IDirectDraw_GetDisplayMode(
 	LPDIRECTDRAW this,LPDDSURFACEDESC lpddsfd
 ) {
-	TRACE(ddraw,"(%p)->GetDisplayMode(%p)\n",this,lpddsfd);
+	TRACE(ddraw,"(%p)->(%p)\n",this,lpddsfd);
 	lpddsfd->dwFlags = DDSD_HEIGHT|DDSD_WIDTH|DDSD_PITCH|DDSD_BACKBUFFERCOUNT|DDSD_PIXELFORMAT|DDSD_CAPS;
 	lpddsfd->dwHeight = screenHeight;
 	lpddsfd->dwWidth = screenWidth;
@@ -1473,14 +1478,14 @@
 }
 
 static HRESULT WINAPI IDirectDraw_FlipToGDISurface(LPDIRECTDRAW this) {
-	fprintf(stderr,"(%p)->FlipToGDISurface()\n",this);
+	TRACE(ddraw,"(%p)->()\n",this);
 	return DD_OK;
 }
 
 static HRESULT WINAPI IDirectDraw_GetMonitorFrequency(
 	LPDIRECTDRAW this,LPDWORD freq
 ) {
-	fprintf(stderr,"(%p)->GetMonitorFrequency(%p)\n",this,freq);
+	FIXME(ddraw,"(%p)->(%p) returns 60 Hz always\n",this,freq);
 	*freq = 60*100; /* 60 Hz */
 	return 0;
 }
@@ -1563,7 +1568,7 @@
 static HRESULT WINAPI IDirectDraw2_SetDisplayMode(
 	LPDIRECTDRAW2 this,DWORD width,DWORD height,DWORD depth,DWORD xx,DWORD yy
 ) {
-	TRACE(ddraw,"IDirectDraw2(%p)->SetDisplayMode(%ld,%ld,%ld,%08lx,%08lx)\n",
+	TRACE(ddraw,"(%p)->(%ld,%ld,%ld,%08lx,%08lx)\n",
 		      this, width, height, depth, xx, yy);
 
 	return IDirectDraw_SetDisplayMode((LPDIRECTDRAW)this,width,height,depth);
@@ -1576,7 +1581,7 @@
 static HRESULT WINAPI IDirectDraw2_EnumSurfaces(
 	LPDIRECTDRAW2 this,DWORD x,LPDDSURFACEDESC ddsfd,LPVOID context,LPDDENUMSURFACESCALLBACK ddsfcb
 ) {
-	fprintf(stderr,"IDirectDraw2(%p)->EnumSurfaces(0x%08lx,%p,%p,%p),stub!\n",this,x,ddsfd,context,ddsfcb);
+	FIXME(ddraw,"(%p)->(0x%08lx,%p,%p,%p),stub!\n",this,x,ddsfd,context,ddsfcb);
 	return 0;
 }
 
@@ -1595,7 +1600,7 @@
 static HRESULT WINAPI IDirectDraw2_GetAvailableVidMem(
 	LPDIRECTDRAW2 this,LPDDSCAPS ddscaps,LPDWORD total,LPDWORD free
 ) {
-	fprintf(stderr,"IDirectDraw2(%p)->GetAvailableVidMem(%p,%p,%p)\n",
+	TRACE(ddraw,"(%p)->(%p,%p,%p)\n",
 		this,ddscaps,total,free
 	);
 	if (total) *total = this->d.fb_memsize * 1024;
@@ -1666,6 +1671,7 @@
 
 	TRACE(ddraw,"(%s,%p,%p)\n",xclsid,lplpDD,pUnkOuter);
 	if (getuid()) {
+		MSG("Must be root to use XF86DGA!\n");
 		MessageBox32A(0,"Using the XF86DGA extension requires the program to be run using UID 0.","WINE DirectDraw",MB_OK|MB_ICONSTOP);
 		return E_UNEXPECTED;
 	}
@@ -1673,14 +1679,14 @@
 	(*lplpDD)->lpvtbl = &ddvt;
 	(*lplpDD)->ref = 1;
 	if (!XF86DGAQueryExtension(display,&evbase,&evret)) {
-		fprintf(stderr,"No XF86DGA detected.\n");
+		MSG("Wine DirectDraw: No XF86DGA detected.\n");
 		return 0;
 	}
 	XF86DGAQueryVersion(display,&major,&minor);
 	TRACE(ddraw,"XF86DGA is version %d.%d\n",major,minor);
 	XF86DGAQueryDirectVideo(display,DefaultScreen(display),&flags);
 	if (!(flags & XF86DGADirectPresent))
-		fprintf(stderr,"direct video is NOT ENABLED.\n");
+		MSG("direct video is NOT ENABLED.\n");
 	XF86DGAGetVideo(display,DefaultScreen(display),&addr,&width,&banksize,&memsize);
 	TRACE(ddraw,"video framebuffer: begin %p, width %d,banksize %d,memsize %d\n",
 		addr,width,banksize,memsize
diff --git a/graphics/driver.c b/graphics/driver.c
index e26b2c3..7c09b2b 100644
--- a/graphics/driver.c
+++ b/graphics/driver.c
@@ -7,6 +7,7 @@
 #include <stdio.h>
 #include "gdi.h"
 #include "heap.h"
+#include "debug.h"
 
 typedef struct tagGRAPHICS_DRIVER
 {
@@ -36,7 +37,7 @@
     /* No name -> it's the generic driver */
     if (genericDriver)
     {
-        fprintf( stderr, "DRIVER_RegisterDriver: already a generic driver\n" );
+        WARN(driver, " already a generic driver\n" );
         HeapFree( SystemHeap, 0, driver );
         return FALSE;
     }
diff --git a/graphics/env.c b/graphics/env.c
index 13aa37f..a004ee8 100644
--- a/graphics/env.c
+++ b/graphics/env.c
@@ -5,18 +5,18 @@
  *
  * Copyright 1997 Marcus Meissner
  */
+#include <windows.h>
 #include <stdio.h>
-#include "windows.h"
-#include "gdi.h"
-#include "debug.h"
+#include <config.h>
+#include <gdi.h>
+#include <debug.h>
 
 /***********************************************************************
  *           GetEnvironment   (GDI.134)
  */
 INT16 WINAPI GetEnvironment(LPCSTR lpPortName, LPDEVMODE16 lpdev, UINT16 nMaxSiz)
 {
-    fprintf(stddeb, "GetEnvironment('%s','%p',%d),\n",
-		lpPortName, lpdev, nMaxSiz);
+   FIXME(gdi, "('%s','%p',%d),stub\n", lpPortName, lpdev, nMaxSiz);
     return 0;
 }
 
@@ -25,9 +25,9 @@
  */
 INT16 WINAPI SetEnvironment(LPCSTR lpPortName, LPDEVMODE16 lpdev, UINT16 nCount)
 {
-    fprintf(stddeb, "SetEnvironment('%s', '%p', %d) !\n", 
-		lpPortName, lpdev, nCount);
-    fprintf(stderr,
+
+   FIXME(gdi, "('%s', '%p', %d) stub!\n", lpPortName, lpdev, nCount);
+   if (TRACE_ON(gdi)) DUMP(
     	"\tdevmode:\n"
     	"\tname = %s\n"
 	"\tdmSpecVersion = %d\n"
diff --git a/graphics/escape.c b/graphics/escape.c
index cd3873c..c7bac2c 100644
--- a/graphics/escape.c
+++ b/graphics/escape.c
@@ -10,6 +10,8 @@
 #include "heap.h"
 #include "ldt.h"
 #include "dc.h"
+#include <debug.h>
+
 
 INT16 WINAPI Escape16( HDC16 hdc, INT16 nEscape, INT16 cbInput,
                        SEGPTR lpszInData, SEGPTR lpvOutData )
@@ -77,7 +79,7 @@
     switch(nEscape) {
     case QUERYESCSUPPORT:
     	if (ret)
-		fprintf(stderr,"target DC implements Escape %d\n",nEscape);
+		TRACE(driver,"target DC implements Escape %d\n",nEscape);
     	SEGPTR_FREE(PTR_SEG_TO_LIN(segin));
 	break;
     case GETSCALINGFACTOR:
@@ -115,7 +117,7 @@
 }
 
 INT32 WINAPI ExtEscape32(HDC32 hdc,INT32 nEscape,INT32 cbInput,LPCSTR x,INT32 cbOutput,LPSTR out) {
-	fprintf(stderr,"ExtEscape32(0x%04x,0x%x,%d,%s,%d,%p),stub!\n",
+	FIXME(driver,"(0x%04x,0x%x,%d,%s,%d,%p),stub!\n",
 		hdc,nEscape,cbInput,x,cbOutput,out
 	);
 	return 1;
diff --git a/graphics/fontengine.c b/graphics/fontengine.c
index f261b13..0a65297 100644
--- a/graphics/fontengine.c
+++ b/graphics/fontengine.c
@@ -2,28 +2,38 @@
  * True Type font engine support
  *
  * Copyright 1996 John Harvey
+ * Copyright 1998 David Lee Lambert
+ * 
  */
+#include "windows.h"
 #include <stdio.h>
 #include <stdlib.h>
-#include "windows.h"
+#include <debug.h>     
 #include "font.h"
 
-/* GDI 300 */
-WORD WINAPI EngineEnumerateFont(LPSTR fontname, FARPROC16 proc, DWORD data )
+
+
+/* **************************************************************** 
+ *    EngineEnumerateFont [GDI.300] 
+ */
+WORD WINAPI 
+EngineEnumerateFont(LPSTR fontname, FARPROC16 proc, DWORD data )
 {
-    fprintf(stderr,"EngineEnumerateFont(%s,%p,%lx),stub\n",fontname,proc,data);
+    FIXME(font,"(%s,%p,%lx),stub\n",fontname,proc,data);
     return 0;
 }
 
-/* GDI 301 */
+/* **************************************************************** 
+ *   EngineDeleteFont [GDI.301] 
+ */
 WORD WINAPI EngineDeleteFont(LPFONTINFO16 lpFontInfo)
 {
     WORD handle;
 
     /*	untested, don't know if it works.
 	We seem to access some structure that is located after the
-	FONTINFO. The FONTINFO docu says that there may follow some char-width
-	table or font bitmap or vector info.
+	FONTINFO. The FONTINFO documentation says that there may 
+	follow some char-width table or font bitmap or vector info.
 	I think it is some kind of font bitmap that begins at offset 0x52,
 	as FONTINFO goes up to 0x51.
 	If this is correct, everything should be implemented correctly.
@@ -39,46 +49,63 @@
     return 1;
 }
 
-/* GDI 302 */
+/* ****************************************************************
+ *       EngineRealizeFont [GDI.302] 
+ */
 WORD WINAPI EngineRealizeFont(LPLOGFONT16 lplogFont, LPTEXTXFORM16 lptextxform, LPFONTINFO16 lpfontInfo)
 {
-    fprintf(stderr,"EngineRealizeFont(%p,%p,%p),stub\n",lplogFont,lptextxform,lpfontInfo);
+    FIXME(font,"(%p,%p,%p),stub\n",lplogFont,lptextxform,lpfontInfo);
     
     return 0;
 }
 
-/* GDI 303 */
+/* ****************************************************************
+ *        EngineGetCharWidth [GDI.303] 
+ */
 WORD WINAPI EngineGetCharWidth(LPFONTINFO16 lpFontInfo, BYTE firstChar, BYTE lastChar, LPINT16 buffer)
 {
     int i;
 
     for (i = firstChar; i <= lastChar; i++)
+       FIXME(font, " returns font's average width for range %d to %d\n", firstChar, lastChar);
 	*buffer++ = lpFontInfo->dfAvgWidth; /* insert some charwidth functionality here; use average width for now */
     return 1;
 }
 
-/* GDI 304 */
+/* ****************************************************************
+ *      EngineSetFontContext [GDI.304] 
+ */
 WORD WINAPI EngineSetFontContext(LPFONTINFO16 lpFontInfo, WORD data)
 {
+   FIXME(font, "stub?\n");
 	return 0;
 }
 
-/* GDI 305 */
+/* ****************************************************************
+ *       EngineGetGlyphBMP   [GDI.305] 
+ */
 WORD WINAPI EngineGetGlyphBMP(WORD word, LPFONTINFO16 lpFontInfo, WORD w1, WORD w2, LPSTR string, DWORD dword, /*LPBITMAPMETRICS16*/ LPVOID metrics)
 {
+   FIXME(font, "stub?\n");
     return 0;
 }
 
-/* GDI 306 */
+/* ****************************************************************
+ *             EngineMakeFontDir  [GDI.306] 
+ */
 DWORD WINAPI EngineMakeFontDir(HDC16 hdc, LPFONTDIR16 fontdir, LPCSTR string)
 {
+   FIXME(font, " stub! (always fails)\n");
     return -1; /* error */
     
 }
 
-/* GDI 314 */
+/* ****************************************************************
+ *              EngineExtTextOut [GDI.314] 
+ */
 
 WORD WINAPI EngineExtTextOut()
 {
+   FIXME(font, "stub!\n");
     return 0;
 }
diff --git a/graphics/metafiledrv/init.c b/graphics/metafiledrv/init.c
index c26b066..77ecba5 100644
--- a/graphics/metafiledrv/init.c
+++ b/graphics/metafiledrv/init.c
@@ -43,6 +43,7 @@
     MFDRV_PatBlt,                    /* pPatBlt */
     MFDRV_Pie,                       /* pPie */
     MFDRV_PolyPolygon,               /* pPolyPolygon */
+    NULL,                            /* pPolyPolyline */
     MFDRV_Polygon,                   /* pPolygon */
     MFDRV_Polyline,                  /* pPolyline */
     NULL,                            /* pRealizePalette */
diff --git a/graphics/painting.c b/graphics/painting.c
index b343023..a142c91 100644
--- a/graphics/painting.c
+++ b/graphics/painting.c
@@ -368,7 +368,7 @@
 }
 
 /***********************************************************************
- *           SetPixel32    (GDI32.329)
+ *           SetPixelV32    (GDI32.329)
  */
 BOOL32 WINAPI SetPixelV32( HDC32 hdc, INT32 x, INT32 y, COLORREF color )
 {
@@ -407,6 +407,104 @@
 }
 
 
+/******************************************************************************
+ * ChoosePixelFormat [GDI32.13]
+ * Matches a pixel format to given format
+ *
+ * PARAMS
+ *    hdc  [I] Device context to search for best pixel match
+ *    ppfd [I] Pixel format for which a match is sought
+ *
+ * RETURNS
+ *    Success: Pixel format index closest to given format
+ *    Failure: 0
+ */
+INT32 WINAPI ChoosePixelFormat( HDC32 hdc, PIXELFORMATDESCRIPTOR *ppfd )
+{
+    FIXME(gdi, "(%d,%p): stub\n",hdc,ppfd);
+    ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR);
+    ppfd->nVersion = 1;
+    return 1;
+}
+
+
+/******************************************************************************
+ * SetPixelFormat [GDI32.328]
+ * Sets pixel format of device context
+ *
+ * PARAMS
+ *    hdc          [I] Device context to search for best pixel match
+ *    iPixelFormat [I] Pixel format index
+ *    ppfd         [I] Pixel format for which a match is sought
+ *
+ * RETURNS STD
+ */
+BOOL32 WINAPI SetPixelFormat( HDC32 hdc, int iPixelFormat, 
+                              PIXELFORMATDESCRIPTOR * ppfd)
+{
+    FIXME(gdi, "(%d,%d,%p): stub\n",hdc,iPixelFormat,ppfd);
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * GetPixelFormat [GDI32.212]
+ * Gets index of pixel format of DC
+ *
+ * PARAMETERS
+ *    hdc [I] Device context whose pixel format index is sought
+ *
+ * RETURNS
+ *    Success: Currently selected pixel format
+ *    Failure: 0
+ */
+int WINAPI GetPixelFormat( HDC32 hdc )
+{
+    FIXME(gdi, "(%d): stub\n",hdc);
+    return 1;
+}
+
+
+/******************************************************************************
+ * DescribePixelFormat [GDI32.71]
+ * Gets info about pixel format from DC
+ *
+ * PARAMS
+ *    hdc          [I] Device context
+ *    iPixelFormat [I] Pixel format selector
+ *    nBytes       [I] Size of buffer
+ *    ppfd         [O] Pointer to structure to receive pixel format data
+ *
+ * RETURNS
+ *    Success: Maximum pixel format index of the device context
+ *    Failure: 0
+ */
+int WINAPI DescribePixelFormat( HDC32 hdc, int iPixelFormat, UINT32 nBytes,
+                                LPPIXELFORMATDESCRIPTOR ppfd )
+{
+    FIXME(gdi, "(%d,%d,%d,%p): stub\n",hdc,iPixelFormat,nBytes,ppfd);
+    ppfd->nSize = nBytes;
+    ppfd->nVersion = 1;
+    return 3;
+}
+
+
+/******************************************************************************
+ * SwapBuffers [GDI32.354]
+ * Exchanges front and back buffers of window
+ *
+ * PARAMS
+ *    hdc [I] Device context whose buffers get swapped
+ *
+ * RETURNS STD
+ */
+BOOL32 WINAPI SwapBuffers( HDC32 hdc )
+{
+    FIXME(gdi, "(%d): stub\n",hdc);
+    return TRUE;
+}
+
+
 /***********************************************************************
  *           PaintRgn16    (GDI.43)
  */
@@ -648,6 +746,18 @@
 }
 
 /**********************************************************************
+ *          PolyPolyline32  (GDI32.272)
+ */
+BOOL32 WINAPI PolyPolyline32( HDC32 hdc, LPPOINT32 pt, LPINT32 counts,
+                             UINT32 polylines )
+{
+    DC * dc = DC_GetDCPtr( hdc );
+
+    return dc && dc->funcs->pPolyPolyline &&
+    	   dc->funcs->pPolyPolyline(dc,pt,counts,polylines);
+}
+
+/**********************************************************************
  *          ExtFloodFill16   (GDI.372)
  */
 BOOL16 WINAPI ExtFloodFill16( HDC16 hdc, INT16 x, INT16 y, COLORREF color,
@@ -935,3 +1045,31 @@
 {
     return PAINTING_DrawState32(hdc, hbr, (DRAWSTATEPROC32)func, ldata, wdata, x, y, cx, cy, flags, FALSE, FALSE);
 }
+
+
+/******************************************************************************
+ * PolyBezier16 [GDI.502]
+ */
+BOOL16 WINAPI PolyBezier16( HDC16 hDc, LPPOINT16 lppt, INT16 cPoints )
+{
+    FIXME(gdi, "(%x,%p,%d): stub\n",hDc,lppt,cPoints);
+    return TRUE;
+}
+
+/******************************************************************************
+ * PolyBezier32 [GDI32.268]
+ * Draws one or more Bezier curves
+ *
+ * PARAMS
+ *    hDc     [I] Handle to device context
+ *    lppt    [I] Pointer to endpoints and control points
+ *    cPoints [I] Count of endpoints and control points
+ *
+ * RETURNS STD
+ */
+BOOL32 WINAPI PolyBezier32( HDC32 hDc, LPPOINT32 lppt, DWORD cPoints )
+{
+    FIXME(gdi, "(%x,%p,%ld): stub\n",hDc,lppt,cPoints);
+    return TRUE;
+}
+
diff --git a/graphics/path.c b/graphics/path.c
index 09dbc5f..a795af8 100644
--- a/graphics/path.c
+++ b/graphics/path.c
@@ -157,11 +157,19 @@
 }
 
 
-/***********************************************************************
- *           AbortPath32    (GDI32.1)
+/******************************************************************************
+ * AbortPath32 [GDI32.1]
+ * Closes and discards paths from device context
+ *
+ * NOTES
+ *    Check that SetLastError is being called correctly
+ *
+ * PARAMS
+ *    hdc [I] Handle to device context
+ *
+ * RETURNS STD
  */
-BOOL32 WINAPI AbortPath32(HDC32 hdc)
-/* FIXME: Check that SetLastError is being called correctly */
+BOOL32 WINAPI AbortPath32( HDC32 hdc )
 {
    GdiPath *pPath;
    
diff --git a/graphics/win16drv/font.c b/graphics/win16drv/font.c
index f735eff..7ed9f71 100644
--- a/graphics/win16drv/font.c
+++ b/graphics/win16drv/font.c
@@ -181,8 +181,7 @@
     WEPFC wepfc = {proc, lp};
 
     /* EnumDFontCallback is GDI.158 */
-    FARPROC16 pfnCallback = MODULE_GetEntryPoint( GetModuleHandle16("GDI"),
-						              158 );
+    FARPROC16 pfnCallback = NE_GetEntryPoint( GetModuleHandle16("GDI"), 158 );
 
     wRet = PRTDRV_EnumDFonts(physDev->segptrPDEVICE, plf->lfFaceName[0] ?
 			     plf->lfFaceName : NULL , pfnCallback , &wepfc );
diff --git a/graphics/win16drv/init.c b/graphics/win16drv/init.c
index 4440d81..2b85707 100644
--- a/graphics/win16drv/init.c
+++ b/graphics/win16drv/init.c
@@ -76,6 +76,7 @@
     WIN16DRV_PatBlt,                 /* pPatBlt */
     NULL,                            /* pPie */
     NULL,                            /* pPolyPolygon */
+    NULL,                            /* pPolyPolyline */
     WIN16DRV_Polygon,                /* pPolygon */
     WIN16DRV_Polyline,               /* pPolyline */
     NULL,                            /* pRealizePalette */
diff --git a/graphics/x11drv/graphics.c b/graphics/x11drv/graphics.c
index ba8ec8a..8442320 100644
--- a/graphics/x11drv/graphics.c
+++ b/graphics/x11drv/graphics.c
@@ -90,6 +90,7 @@
     ystart = YLPTODP( dc, ystart );
     xend   = XLPTODP( dc, xend );
     yend   = YLPTODP( dc, yend );
+
     if ((left == right) || (top == bottom)) return FALSE;
 
     if (left > right) { tmp=left; left=right; right=tmp; }
@@ -113,11 +114,7 @@
 	end_angle = - PI;
     istart_angle = (INT32)(start_angle * 180 * 64 / PI);
     idiff_angle  = (INT32)((end_angle - start_angle) * 180 * 64 / PI );
-    if (idiff_angle < 0) 
-      {
-	istart_angle+= idiff_angle;
-	idiff_angle = abs(idiff_angle);
-      }
+    if (idiff_angle <= 0) idiff_angle += 360 * 64;
 
       /* Fill arc with brush if Chord() or Pie() */
 
@@ -583,6 +580,38 @@
 
 
 /**********************************************************************
+ *          X11DRV_PolyPolyline
+ */
+BOOL32 
+X11DRV_PolyPolyline( DC *dc, LPPOINT32 pt, LPINT32 counts, UINT32 polylines )
+{
+    if (DC_SetupGCForPen ( dc ))
+    {
+        int i, j, max = 0;
+        XPoint *points;
+
+        for (i = 0; i < polylines; i++) if (counts[i] > max) max = counts[i];
+        points = (XPoint *) xmalloc( sizeof(XPoint) * (max+1) );
+
+        for (i = 0; i < polylines; i++)
+        {
+            for (j = 0; j < counts[i]; j++)
+            {
+                points[j].x = dc->w.DCOrgX + XLPTODP( dc, pt->x );
+                points[j].y = dc->w.DCOrgY + YLPTODP( dc, pt->y );
+                pt++;
+            }
+            points[j] = points[0];
+            TSXDrawLines( display, dc->u.x.drawable, dc->u.x.gc,
+                        points, j + 1, CoordModeOrigin );
+        }
+        free( points );
+    }
+    return TRUE;
+}
+
+
+/**********************************************************************
  *          X11DRV_InternalFloodFill
  *
  * Internal helper function for flood fill.
diff --git a/graphics/x11drv/init.c b/graphics/x11drv/init.c
index 2193fb9..d5f11aa 100644
--- a/graphics/x11drv/init.c
+++ b/graphics/x11drv/init.c
@@ -47,6 +47,7 @@
     X11DRV_PatBlt,                   /* pPatBlt */
     X11DRV_Pie,                      /* pPie */
     X11DRV_PolyPolygon,              /* pPolyPolygon */
+    X11DRV_PolyPolyline,             /* pPolyPolyline */
     X11DRV_Polygon,                  /* pPolygon */
     X11DRV_Polyline,                 /* pPolyline */
     NULL,                            /* pRealizePalette */
diff --git a/graphics/x11drv/text.c b/graphics/x11drv/text.c
index f4a243c..ea8c361 100644
--- a/graphics/x11drv/text.c
+++ b/graphics/x11drv/text.c
@@ -8,6 +8,7 @@
 #include "ts_xlib.h"
 #include <X11/Xatom.h>
 #include "windows.h"
+#include <math.h>
 #include "dc.h"
 #include "gdi.h"
 /*#include "callback.h"*/
@@ -17,7 +18,7 @@
 #include "debug.h"
 
 #define SWAP_INT(a,b)  { int t = a; a = b; b = t; }
-
+#define IROUND(x) (int)((x)>0? (x)+0.5 : (x) - 0.5)
 
 /***********************************************************************
  *           X11DRV_ExtTextOut
@@ -186,8 +187,35 @@
     TSXSetForeground( display, dc->u.x.gc, dc->w.textPixel );
     if (!dc->w.charExtra && !dc->w.breakExtra && !lpDx)
     {
+      if (!pfo->lf.lfOrientation)  /* angled baseline? */
+      {
         TSXDrawString( display, dc->u.x.drawable, dc->u.x.gc, 
                      dc->w.DCOrgX + x, dc->w.DCOrgY + y, str, count );
+      }
+      else 
+      {  
+	/* have to render character by character. */
+	double offset = 0.0;
+	int i;
+	/* tenths of degrees to radians */
+	double theta = M_PI*pfo->lf.lfOrientation/1800.;
+	/* components of pointsize matrix */
+	double xc = pfo->fi->lfd_decipoints*cos(theta)/10.;
+	double yc = pfo->fi->lfd_decipoints*sin(theta)/10.;
+	
+	for(i=0; i<count; i++) {
+	  int char_metric_offset = (unsigned char) str[i] 
+	    - font->min_char_or_byte2;
+	  int x_i = IROUND((double) (dc->w.DCOrgX + x) + offset*xc/1000. );
+	  int y_i = IROUND((double) (dc->w.DCOrgY + y) - offset*yc/1000. );
+	   
+	  TSXDrawString( display, dc->u.x.drawable, dc->u.x.gc,
+			 x_i, y_i, &str[i], 1);
+	  offset += (double) (font->per_char ?
+		     font->per_char[char_metric_offset].attributes:
+		     font->min_bounds.attributes);
+	}
+      }
     }
     else  /* Now the fun begins... */
     {
diff --git a/graphics/x11drv/xfont.c b/graphics/x11drv/xfont.c
index 58093b0..505f444 100644
--- a/graphics/x11drv/xfont.c
+++ b/graphics/x11drv/xfont.c
@@ -18,6 +18,7 @@
 #include <fcntl.h>
 #include "ts_xlib.h"
 #include <X11/Xatom.h>
+#include <math.h>
 #include "heap.h"
 #include "options.h"
 #include "x11font.h"
@@ -383,6 +384,7 @@
    return TRUE;					
 }
 
+
 /*************************************************************************
  *           LFD_ComposeLFD
  */
@@ -392,6 +394,7 @@
    int		h, w, ch, enc_ch, point = 0;
    char*	lpch; 
    const char*  lpEncoding = NULL;
+   char         h_string[64], point_string[64];
 
    lstrcpy32A( lpLFD, fo->fr->resource );
 
@@ -448,6 +451,23 @@
 	if( fo->fi->fi_flags & FI_SCALABLE ) /* adjust h/w ratio */
 	    point = h * 72 * 10 / fo->fi->lfd_resolution;
 
+   /* handle rotated fonts */
+   if (fo->lf.lfEscapement) {
+     /* escapement is in tenths of degrees, theta is in radians */
+     double theta = M_PI*fo->lf.lfEscapement/1800.;  
+     double h_matrix[4] = {h*cos(theta), h*sin(theta), -h*sin(theta), h*cos(theta)};
+     double point_matrix[4] = {point*cos(theta), point*sin(theta), -point*sin(theta), point*cos(theta)};
+     char *s;
+     sprintf(h_string, "[%+f%+f%+f%+f]", h_matrix[0], h_matrix[1], h_matrix[2], h_matrix[3]);
+     sprintf(point_string, "[%+f%+f%+f%+f]", point_matrix[0], point_matrix[1], point_matrix[2], point_matrix[3]);
+     while (s = strchr(h_string, '-')) *s='~';
+     while (s = strchr(point_string, '-')) *s='~';
+   } else {
+     sprintf(h_string, "%d", h);
+     sprintf(point_string, "%d", point);
+   }
+
+
 /* spacing and width */
 
    if( fo->fi->fi_flags & FI_FIXEDPITCH ) 
@@ -496,20 +516,21 @@
        case 0: 
 	    if( point )
 	    {
-	        sprintf( lpch, "%i-%i-%i-%c-%c-*-%s%c", h, point, 
+	        sprintf( lpch, "%s-%s-%i-%c-%c-*-%s%c", h_string, 
+			 point_string, 
 			 fo->fi->lfd_resolution, ch, w, lpEncoding, enc_ch );
 	        break;
 	    }
 	    /* fall through */
 
        case 1: 
-	    sprintf( lpch, "%i-*-%i-%c-%c-*-%s%c", h, 
+	    sprintf( lpch, "%s-*-%i-%c-%c-*-%s%c", h_string, 
 			fo->fi->lfd_resolution, ch, w, lpEncoding, enc_ch );
 	    break;
 
        case 2:
-	    sprintf( lpch, "%i-*-%i-%c-*-*-%s%c",
-			h, fo->fi->lfd_resolution, ch, lpEncoding, enc_ch );
+	    sprintf( lpch, "%s-*-%i-%c-*-*-%s%c",
+			h_string, fo->fi->lfd_resolution, ch, lpEncoding, enc_ch );
 	    break;
 
        case 3:
diff --git a/if1632/builtin.c b/if1632/builtin.c
index a0f2d2f..c06d91c 100644
--- a/if1632/builtin.c
+++ b/if1632/builtin.c
@@ -170,7 +170,7 @@
     if (pModule->heap_size)
         LocalInit( pSegTable->selector, pSegTable->minsize, minsize );
 
-    MODULE_RegisterModule( pModule );
+    NE_RegisterModule( pModule );
     return hModule;
 }
 
@@ -197,27 +197,42 @@
 
     /* Set the USER and GDI heap selectors */
 
-    pModule      = MODULE_GetPtr( GetModuleHandle16( "USER" ));
+    pModule      = MODULE_GetPtr16( GetModuleHandle16( "USER" ));
     USER_HeapSel = (NE_SEG_TABLE( pModule ) + pModule->dgroup - 1)->selector;
-    pModule      = MODULE_GetPtr( GetModuleHandle16( "GDI" ));
+    pModule      = MODULE_GetPtr16( GetModuleHandle16( "GDI" ));
     GDI_HeapSel  = (NE_SEG_TABLE( pModule ) + pModule->dgroup - 1)->selector;
 
     /* Initialize KERNEL.178 (__WINFLAGS) with the correct flags value */
 
     hModule = GetModuleHandle16( "KERNEL" );
-    MODULE_SetEntryPoint( hModule, 178, GetWinFlags() );
+    NE_SetEntryPoint( hModule, 178, GetWinFlags() );
 
     /* Initialize the real-mode selector entry points */
 
-    DOSMEM_InitExports( hModule );
+#define SET_ENTRY_POINT( num, addr ) \
+    NE_SetEntryPoint( hModule, (num), GLOBAL_CreateBlock( GMEM_FIXED, \
+                      DOSMEM_MapDosToLinear(addr), 0x10000, hModule, \
+                      FALSE, FALSE, FALSE, NULL ))
+
+    SET_ENTRY_POINT( 183, 0x00000 );  /* KERNEL.183: __0000H */
+    SET_ENTRY_POINT( 174, 0xa0000 );  /* KERNEL.174: __A000H */
+    SET_ENTRY_POINT( 181, 0xb0000 );  /* KERNEL.181: __B000H */
+    SET_ENTRY_POINT( 182, 0xb8000 );  /* KERNEL.182: __B800H */
+    SET_ENTRY_POINT( 195, 0xc0000 );  /* KERNEL.195: __C000H */
+    SET_ENTRY_POINT( 179, 0xd0000 );  /* KERNEL.179: __D000H */
+    SET_ENTRY_POINT( 190, 0xe0000 );  /* KERNEL.190: __E000H */
+    SET_ENTRY_POINT( 173, 0xf0000 );  /* KERNEL.173: __ROMBIOS */
+    SET_ENTRY_POINT( 194, 0xf0000 );  /* KERNEL.194: __F000H */
+    NE_SetEntryPoint( hModule, 193, DOSMEM_BiosSeg ); /* KERNEL.193: __0040H */
+#undef SET_ENTRY_POINT
 
     /* Set interrupt vectors from entry points in WPROCS.DLL */
 
     hModule = GetModuleHandle16( "WPROCS" );
     for (vector = 0; vector < 256; vector++)
     {
-        FARPROC16 proc = MODULE_GetEntryPoint( hModule,
-                                               FIRST_INTERRUPT_ORDINAL+vector);
+        FARPROC16 proc = NE_GetEntryPoint( hModule,
+                                           FIRST_INTERRUPT_ORDINAL + vector );
         assert(proc);
         INT_SetHandler( vector, proc );
     }
@@ -266,7 +281,7 @@
     register BYTE *p;
     NE_MODULE *pModule;
 
-    if (!(pModule = MODULE_GetPtr( FarGetOwner( GlobalHandle16(cs) ))))
+    if (!(pModule = MODULE_GetPtr16( FarGetOwner( GlobalHandle16(cs) ))))
         return NULL;
 
     /* Search for the ordinal */
@@ -299,7 +314,7 @@
             }
             break;
         case 0xff: /* moveable (should not happen in built-in modules) */
-            fprintf( stderr, "Built-in module has moveable entry\n" );
+            TRACE( relay, "Built-in module has moveable entry\n" );
             ordinal += *p;
             p += 2 + *p * 6;
             break;
@@ -396,14 +411,14 @@
     int i;
     BUILTIN16_DLL *dll;
 
-    fprintf(stderr,"Example: -dll -ole2    Do not use emulated OLE2.DLL\n");
-    fprintf(stderr,"Available Win16 DLLs:\n");
+    MSG("Example: -dll -ole2    Do not use emulated OLE2.DLL\n");
+    MSG("Available Win16 DLLs:\n");
     for (i = 0, dll = BuiltinDLLs; dll->descr; dll++)
     {
         if (!(dll->flags & DLL_FLAG_ALWAYS_USED))
-            fprintf( stderr, "%-9s%c", dll->descr->name,
+            MSG("%-9s%c", dll->descr->name,
                      ((++i) % 8) ? ' ' : '\n' );
     }
-    fprintf(stderr,"\n");
+    MSG("\n");
     BUILTIN32_PrintDLLs();
 }
diff --git a/if1632/commdlg.spec b/if1632/commdlg.spec
index aec5ffd..01c97ae 100644
--- a/if1632/commdlg.spec
+++ b/if1632/commdlg.spec
@@ -12,10 +12,10 @@
 12  pascal16 ReplaceText(segptr) ReplaceText16
 13  pascal   FindTextDlgProc(word word word long) FindTextDlgProc16
 14  pascal   ReplaceTextDlgProc(word word word long) ReplaceTextDlgProc16
-15  pascal16 ChooseFont(ptr) ChooseFont
-16  pascal16 FormatCharDlgProc(word word word long) FormatCharDlgProc
-18  pascal16 FontStyleEnumProc(ptr ptr word long)   FontStyleEnumProc
-19  pascal16 FontFamilyEnumProc(ptr ptr word long)  FontFamilyEnumProc
+15  pascal16 ChooseFont(ptr) ChooseFont16
+16  pascal16 FormatCharDlgProc(word word word long) FormatCharDlgProc16
+18  pascal16 FontStyleEnumProc(ptr ptr word long)   FontStyleEnumProc16
+19  pascal16 FontFamilyEnumProc(ptr ptr word long)  FontFamilyEnumProc16
 20  pascal16 PrintDlg(segptr) PrintDlg16
 21  pascal   PrintDlgProc(word word word long) PrintDlgProc
 22  pascal   PrintSetupDlgProc(word word word long) PrintSetupDlgProc
diff --git a/if1632/ddeml.spec b/if1632/ddeml.spec
index 991d20c..30498d1 100644
--- a/if1632/ddeml.spec
+++ b/if1632/ddeml.spec
@@ -3,9 +3,9 @@
 
 2 pascal16 DdeInitialize(ptr segptr long long) DdeInitialize16
 3 pascal16 DdeUninitialize(long) DdeUninitialize16
-4 pascal DdeConnectList(long word word word ptr) DdeConnectList
+4 pascal DdeConnectList(long word word word ptr) DdeConnectList16
 5 pascal DdeQueryNextServer(word word) DdeQueryNextServer
-6 pascal DdeDisconnectList(word) DdeDisconnectList
+6 pascal DdeDisconnectList(word) DdeDisconnectList16
 7 pascal   DdeConnect(long long long ptr) DdeConnect16
 8 pascal16 DdeDisconnect(long) DdeDisconnect16
 9 stub DdeQueryConvInfo #(word long ptr) DdeQueryConvInfo
@@ -13,10 +13,10 @@
 11 pascal   DdeClientTransaction(ptr long long long s_word s_word long ptr)
             DdeClientTransaction16
 12 pascal DdeAbandonTransaction(long word long) DdeAbandonTransaction
-13 pascal DdePostAdvise(long word word) DdePostAdvise
+13 pascal DdePostAdvise(long word word) DdePostAdvise16
 14 pascal DdeCreateDataHandle(long ptr long long word word word) DdeCreateDataHandle
 15 pascal DdeAddData(word ptr long long) DdeAddData
-16 pascal DdeGetData(word ptr long long) DdeGetData
+16 pascal DdeGetData(word ptr long long) DdeGetData16
 17 pascal DdeAccessData(word ptr) DdeAccessData
 18 pascal DdeUnaccessData(word) DdeUnaccessData
 19 pascal16 DdeFreeDataHandle(long) DdeFreeDataHandle16
diff --git a/if1632/dummy.c b/if1632/dummy.c
index 7babcac..4c67b5d 100644
--- a/if1632/dummy.c
+++ b/if1632/dummy.c
@@ -1,51 +1,57 @@
+/*
+ * Dummy function definitions
+ */
+
 #include <stdio.h>
 #include "wintypes.h"
-long WINAPI stub_GDI_379(void) { fprintf(stderr, "Warning: GDI_379:STARTPAGE unimplemented stub\n"); return 1; }
-long WINAPI stub_GDI_380(void) { fprintf(stderr, "Warning: GDI_380:ENDPAGE unimplemented stub\n"); return 1; }
-long WINAPI stub_GDI_381(HDC16 hdc, SEGPTR proc) { fprintf(stderr, "Warning: GDI_381:SETABORTPROC unimplemented stub\n"); return 1; }
-long WINAPI stub_GDI_382(void) { fprintf(stderr, "Warning: GDI_382:ABORTPROC unimplemented stub\n"); return 1; }
-long WINAPI stub_GDI_530(void) { fprintf(stderr, "Warning: GDI_530: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_531(void) { fprintf(stderr, "Warning: GDI_531: unimplemented stub\n"); return 0; }
+#include "debug.h"
+
+long WINAPI stub_GDI_379(void) { FIXME(relay, "STARTPAGE: stub\n"); return 1; }
+long WINAPI stub_GDI_380(void) { FIXME(relay, "ENDPAGE: stub\n"); return 1; }
+long WINAPI stub_GDI_381(HDC16 hdc, SEGPTR proc) { FIXME(relay, "SETABORTPROC: stub\n"); return 1; }
+long WINAPI stub_GDI_382(void) { FIXME(relay, "ABORTPROC: stub\n"); return 1; }
+long WINAPI stub_GDI_530(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_531(void) { FIXME(relay, "stub\n"); return 0; }
 long WINAPI stub_GDI_532(LPINT16 buffer, INT16 xx) { 
-      fprintf(stderr, "STUB GDI_532(%p, %hd)\n",buffer,xx); 
+      FIXME(relay, "(%p, %hd): stub\n",buffer,xx); 
       return 0; 
 }
-long WINAPI stub_GDI_536(void) { fprintf(stderr, "Warning: GDI_536: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_538(void) { fprintf(stderr, "Warning: GDI_538: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_540(void) { fprintf(stderr, "Warning: GDI_540: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_543(void) { fprintf(stderr, "Warning: GDI_543: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_555(void) { fprintf(stderr, "Warning: GDI_555: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_560(void) { fprintf(stderr, "Warning: GDI_560: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_561(void) { fprintf(stderr, "Warning: GDI_561: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_564(void) { fprintf(stderr, "Warning: GDI_564: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_565(void) { fprintf(stderr, "Warning: GDI_565: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_566(void) { fprintf(stderr, "Warning: GDI_566: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_571(void) { fprintf(stderr, "Warning: GDI_571: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_572(void) { fprintf(stderr, "Warning: GDI_572: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_573(void) { fprintf(stderr, "Warning: GDI_573: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_556(void) { fprintf(stderr, "Warning: GDI_556: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_558(void) { fprintf(stderr, "Warning: GDI_558: unimplemented stub\n"); return 0; }
-long WINAPI stub_GDI_569(void) { fprintf(stderr, "Warning: GDI_569: unimplemented stub\n"); return 0; }
-long WINAPI stub_KERNEL_450(void) { fprintf(stderr, "Warning: KERNEL_450: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_489(void) { fprintf(stderr, "Warning: USER_489: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_490(void) { fprintf(stderr, "Warning: USER_490: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_492(void) { fprintf(stderr, "Warning: USER_492: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_496(void) { fprintf(stderr, "Warning: USER_496: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_902(void) { fprintf(stderr, "Warning: USER_902: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_905(void) { fprintf(stderr, "Warning: USER_905: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_906(void) { fprintf(stderr, "Warning: USER_906: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_907(void) { fprintf(stderr, "Warning: USER_907: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_909(void) { fprintf(stderr, "Warning: USER_909: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_910(void) { fprintf(stderr, "Warning: USER_910: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_911(void) { fprintf(stderr, "Warning: USER_911: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_912(void) { fprintf(stderr, "Warning: USER_912: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_913(void) { fprintf(stderr, "Warning: USER_913: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_914(void) { fprintf(stderr, "Warning: USER_914: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_915(void) { fprintf(stderr, "Warning: USER_915: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_916(void) { fprintf(stderr, "Warning: USER_916: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_918(void) { fprintf(stderr, "Warning: USER_918: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_919(void) { fprintf(stderr, "Warning: USER_919: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_920(void) { fprintf(stderr, "Warning: USER_920: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_922(void) { fprintf(stderr, "Warning: USER_922: unimplemented stub\n"); return 0; }
-long WINAPI stub_USER_923(void) { fprintf(stderr, "Warning: USER_923: unimplemented stub\n"); return 0; }
-long WINAPI stub_KERNEL_700(void) { fprintf(stderr, "Warning: KERNEL_700: unimplemented stub\n"); return 1; }
+long WINAPI stub_GDI_536(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_538(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_540(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_543(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_555(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_560(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_561(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_564(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_565(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_566(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_571(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_572(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_573(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_556(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_558(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_GDI_569(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_KERNEL_450(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_489(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_490(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_492(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_496(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_902(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_905(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_906(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_907(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_909(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_910(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_911(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_912(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_913(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_914(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_915(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_916(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_918(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_919(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_920(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_922(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_USER_923(void) { FIXME(relay, "stub\n"); return 0; }
+long WINAPI stub_KERNEL_700(void) { FIXME(relay, "stub\n"); return 1; }
diff --git a/if1632/gdi.spec b/if1632/gdi.spec
index 02bbbef..34cef32 100644
--- a/if1632/gdi.spec
+++ b/if1632/gdi.spec
@@ -326,7 +326,7 @@
 498 stub GetEnhMetafileDescription
 499 stub GetEnhMetafileHeader
 501 stub GetEnhMetafilePaletteEntries
-502 stub PolyBezier
+502 pascal16 PolyBezier(word ptr word) PolyBezier16
 503 stub PolyBezierTo
 504 stub PlayEnhMetafileRecord
 505 stub SetEnhMetafileBits
diff --git a/if1632/kernel.spec b/if1632/kernel.spec
index 3e4ab9d..8a82169 100644
--- a/if1632/kernel.spec
+++ b/if1632/kernel.spec
@@ -63,7 +63,7 @@
 63  pascal16 FreeResource(word) FreeResource16
 64  pascal16 AccessResource(word word) AccessResource16
 65  pascal SizeofResource(word word) SizeofResource16
-66  pascal16 AllocResource(word word long) AllocResource16
+66  pascal16 AllocResource(word word long) AllocResource
 67  pascal SetResourceHandler(word segstr segptr) THUNK_SetResourceHandler
 68  pascal16 InitAtomTable(word) InitAtomTable16
 69  pascal16 FindAtom(segstr) FindAtom16
diff --git a/if1632/ole2disp.spec b/if1632/ole2disp.spec
index 3c36c9e..dce0c29 100644
--- a/if1632/ole2disp.spec
+++ b/if1632/ole2disp.spec
@@ -2,12 +2,12 @@
 type	win16
 
 1 stub DLLGETCLASSOBJECT
-2 pascal SysAllocString(str)		SysAllocString
-3 pascal SysReallocString(ptr str)	SysReAllocString
-4 pascal SysAllocStringLen(str word)	SysAllocStringLen
-5 pascal SysReAllocStringLen(ptr str word) SysReAllocStringLen
-6 pascal SysFreeString(segstr)		SysFreeString
-7 pascal SysStringLen(segstr)		SysStringLen
+2 pascal SysAllocString(str)		SysAllocString16
+3 pascal SysReallocString(ptr str)	SysReAllocString16
+4 pascal SysAllocStringLen(str word)	SysAllocStringLen16
+5 pascal SysReAllocStringLen(ptr str word) SysReAllocStringLen16
+6 pascal SysFreeString(segstr)		SysFreeString16
+7 pascal SysStringLen(segstr)		SysStringLen16
 8 stub VARIANTINIT
 9 stub VARIANTCLEAR
 10 stub VARIANTCOPY
diff --git a/if1632/relay.c b/if1632/relay.c
index 6a40aef..1999d76 100644
--- a/if1632/relay.c
+++ b/if1632/relay.c
@@ -16,11 +16,6 @@
 #include "debugstr.h"
 #include "debug.h"
 
-#if 0
-/* Make make_debug think these were really used */
-TRACE(relay, "test - dummy");
-#endif
-
 
 /***********************************************************************
  *           RELAY_Init
@@ -228,7 +223,7 @@
 {
     WORD ordinal;
     STACK16FRAME *frame = CURRENT_STACK16;
-    fprintf(stderr,"No handler for Win16 routine %s (called from %04x:%04x)\n",
+    MSG("No handler for Win16 routine %s (called from %04x:%04x)\n",
             BUILTIN_GetEntryPoint16(frame->entry_cs,frame->entry_ip,&ordinal),
             frame->cs, frame->ip );
     TASK_KillCurrentTask(1);
@@ -366,22 +361,21 @@
 
     IP_reg(context) = lpbuf[0];
     CS_reg(context) = lpbuf[1];
-    SP_reg(context) = lpbuf[2] + 4 * sizeof(WORD) + sizeof(WORD) /*extra arg*/;
+    SP_reg(context) = lpbuf[2] + 4 * sizeof(WORD) - sizeof(WORD) /*extra arg*/;
     BP_reg(context) = lpbuf[3];
     SI_reg(context) = lpbuf[4];
     DI_reg(context) = lpbuf[5];
     DS_reg(context) = lpbuf[6];
 
     if (lpbuf[8] != SS_reg(context))
-        fprintf( stderr, "Switching stack segment with Throw() not supported; expect crash now\n" );
+        ERR(relay, "Switching stack segment with Throw() not supported; expect crash now\n" );
 
     if (TRACE_ON(relay))  /* Make sure we have a valid entry point address */
     {
         static FARPROC16 entryPoint = NULL;
 
         if (!entryPoint)  /* Get entry point for Throw() */
-            entryPoint = MODULE_GetEntryPoint( GetModuleHandle16("KERNEL"),
-                                               56 );
+            entryPoint = NE_GetEntryPoint( GetModuleHandle16("KERNEL"), 56 );
         pFrame->entry_cs = SELECTOROF(entryPoint);
         pFrame->entry_ip = OFFSETOF(entryPoint);
     }
@@ -452,7 +446,7 @@
 		break;
 	default:
 		/* FIXME: should go up to 32  arguments */
-		fprintf(stderr,"CallProc32W: unsupported number of arguments %ld, please report.\n",nrofargs);
+		ERR(relay,"Unsupported number of arguments %ld, please report.\n",nrofargs);
 		ret = 0;
 		break;
 	}
diff --git a/if1632/signal.c b/if1632/signal.c
index 431565a..e07d41a 100644
--- a/if1632/signal.c
+++ b/if1632/signal.c
@@ -22,6 +22,7 @@
 #include "sig_context.h"
 #include "miscemu.h"
 #include "thread.h"
+#include "debug.h"
 
 
 extern void SIGNAL_SetHandler( int sig, void (*func)(), int flags );
@@ -61,20 +62,21 @@
  */
 static HANDLER_DEF(SIGNAL_fault)
 {
-    WORD cs;
-    GET_CS(cs);
     HANDLER_INIT();
-    if (CS_sig(HANDLER_CONTEXT) == cs)
+    if (INSTR_EmulateInstruction( HANDLER_CONTEXT )) return;
+    if (IS_SELECTOR_SYSTEM(CS_sig(HANDLER_CONTEXT)))
     {
-        fprintf( stderr, "Segmentation fault in 32-bit code (0x%08lx).\n",
-                 EIP_sig(HANDLER_CONTEXT) );
+        MSG("Segmentation fault in 32-bit code (0x%08lx).\n",
+            EIP_sig(HANDLER_CONTEXT) );
     }
     else
     {
-        if (INSTR_EmulateInstruction( HANDLER_CONTEXT )) return;
-        fprintf( stderr, "Segmentation fault in 16-bit code (%04x:%04lx).\n",
-                 (WORD)CS_sig(HANDLER_CONTEXT), EIP_sig(HANDLER_CONTEXT) );
+        MSG("Segmentation fault in 16-bit code (%04x:%04lx).\n",
+            (WORD)CS_sig(HANDLER_CONTEXT), EIP_sig(HANDLER_CONTEXT) );
     }
+#ifdef CR2_sig
+    fprintf(stderr,"Fault address is 0x%08lx\n",CR2_sig(HANDLER_CONTEXT));
+#endif
     wine_debug( signal, HANDLER_CONTEXT );
 }
 
@@ -158,17 +160,17 @@
  */
 void SIGNAL_InfoRegisters( CONTEXT *context )
 {
-    fprintf( stderr," CS:%04x SS:%04x DS:%04x ES:%04x FS:%04x GS:%04x",
+    MSG(" CS:%04x SS:%04x DS:%04x ES:%04x FS:%04x GS:%04x",
              (WORD)CS_reg(context), (WORD)SS_reg(context),
              (WORD)DS_reg(context), (WORD)ES_reg(context),
              (WORD)FS_reg(context), (WORD)GS_reg(context) );
-    fprintf( stderr, "\n EIP:%08lx ESP:%08lx EBP:%08lx EFLAGS:%08lx\n", 
+    MSG( "\n EIP:%08lx ESP:%08lx EBP:%08lx EFLAGS:%08lx\n", 
              EIP_reg(context), ESP_reg(context),
              EBP_reg(context), EFL_reg(context) );
-    fprintf( stderr, " EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n", 
+    MSG( " EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n", 
              EAX_reg(context), EBX_reg(context),
              ECX_reg(context), EDX_reg(context) );
-    fprintf( stderr, " ESI:%08lx EDI:%08lx\n",
+    MSG( " ESI:%08lx EDI:%08lx\n",
              ESI_reg(context), EDI_reg(context) );
 }
 
diff --git a/if1632/thunk.c b/if1632/thunk.c
index 68a511b..c4740d4 100644
--- a/if1632/thunk.c
+++ b/if1632/thunk.c
@@ -492,7 +492,7 @@
     THUNK *thunk, *oldThunk;
 
     if (!defDCHookProc)  /* Get DCHook Win16 entry point */
-        defDCHookProc = MODULE_GetEntryPoint( GetModuleHandle16("USER"), 362 );
+        defDCHookProc = NE_GetEntryPoint( GetModuleHandle16("USER"), 362 );
 
     if (proc != defDCHookProc)
     {
@@ -521,8 +521,7 @@
         if (thunk == (THUNK *)DCHook)
         {
             if (!defDCHookProc)  /* Get DCHook Win16 entry point */
-                defDCHookProc = MODULE_GetEntryPoint(GetModuleHandle16("USER"),
-                                                     362 );
+                defDCHookProc = NE_GetEntryPoint(GetModuleHandle16("USER"),362);
             *phookProc = defDCHookProc;
         }
         else *phookProc = thunk->proc;
@@ -541,7 +540,7 @@
     THUNK *thunk = NULL;
 
     if( !defSignalProc16 )
-	defSignalProc16 = MODULE_GetEntryPoint(GetModuleHandle16("USER"), 314 );
+	defSignalProc16 = NE_GetEntryPoint(GetModuleHandle16("USER"), 314 );
 
     if( proc == defSignalProc16 )
 	thunk = (THUNK*)SetTaskSignalProc( hTask, (FARPROC16)&USER_SignalProc );
@@ -569,9 +568,6 @@
  */
 FARPROC16 WINAPI THUNK_SetResourceHandler( HMODULE16 hModule, SEGPTR typeId, FARPROC16 proc )
 {
-    /* loader/ne_resource.c */
-    extern HGLOBAL16 WINAPI NE_DefResourceHandler(HGLOBAL16,HMODULE16,HRSRC16);
-
     static FARPROC16 defDIBIconLoader16 = NULL;
     static FARPROC16 defDIBCursorLoader16 = NULL;
     static FARPROC16 defResourceLoader16 = NULL;
@@ -581,8 +577,8 @@
     if( !defResourceLoader16 )
     {
 	HMODULE16 hUser = GetModuleHandle16("USER");
-	defDIBIconLoader16 = MODULE_GetEntryPoint( hUser, 357 );
-	defDIBCursorLoader16 = MODULE_GetEntryPoint( hUser, 356 );
+	defDIBIconLoader16 = NE_GetEntryPoint( hUser, 357 );
+	defDIBCursorLoader16 = NE_GetEntryPoint( hUser, 356 );
 	defResourceLoader16 = MODULE_GetWndProcEntry16( "DefResourceHandler" );
     }
 
@@ -703,7 +699,7 @@
 	    );
 	    break;
     default:
-	    fprintf(stderr,"CALLBACK_CallWOWCallback16Ex(), %ld arguments not supported.!n",cbArgs);
+	    ERR(thunk,"%ld arguments not supported.\n",cbArgs);
 	    if (dwFlags == WCB16_CDECL)
 		HeapFree(GetProcessHeap(),0,args);
 	    return FALSE;
diff --git a/if1632/typelib.spec b/if1632/typelib.spec
index 7d2bccf..5b8b311 100644
--- a/if1632/typelib.spec
+++ b/if1632/typelib.spec
@@ -2,7 +2,7 @@
 type win16
 
 2  stub CREATETYPELIB                
-3  stub LOADTYPELIB                  
+3  pascal LoadTypeLib(ptr ptr) LoadTypeLib
 4  stub LHASHVALOFNAMESYS            
 5  stub _IID_ICREATETYPEINFO         
 6  stub _IID_ICREATETYPELIB          
@@ -11,5 +11,5 @@
 9  stub _IID_ITYPELIB                
 10 stub REGISTERTYPELIB              
 11 stub LOADREGTYPELIB               
-14 pascal QueryPathOfRegTypeLib(ptr word word word ptr) QueryPathOfRegTypeLib
+14 pascal QueryPathOfRegTypeLib(ptr word word word ptr) QueryPathOfRegTypeLib16
 15 pascal OABuildVersion() OABuildVersion               
diff --git a/if1632/user.spec b/if1632/user.spec
index 84b32e5..5eea87b 100644
--- a/if1632/user.spec
+++ b/if1632/user.spec
@@ -462,7 +462,7 @@
 514 pascal16 WNetDeviceMode(word) WNetDeviceMode
 515 pascal16 WNetBrowseDialog(word word ptr) WNetBrowseDialog
 516 pascal16 WNetGetUser(ptr ptr ptr) WNetGetUser
-517 pascal16 WNetAddConnection(ptr ptr ptr) WNetAddConnection
+517 pascal16 WNetAddConnection(ptr ptr ptr) WNetAddConnection16
 518 pascal16 WNetCancelConnection(ptr word) WNetCancelConnection
 519 pascal16 WNetGetError(ptr) WNetGetError
 520 pascal16 WNetGetErrorText(word ptr ptr) WNetGetErrorText
@@ -475,7 +475,7 @@
 527 pascal16 WNetConnectionDialog(word word) WNetConnectionDialog
 528 pascal16 WNetViewQueueDialog(word ptr) WNetViewQueueDialog
 529 pascal16 WNetPropertyDialog(word word ptr word) WNetPropertyDialog
-530 pascal16 WNetGetDirectoryType(ptr ptr) WNetGetDirectoryType
+530 pascal16 WNetGetDirectoryType(ptr ptr) WNetGetDirectoryType16
 531 pascal16 WNetDirectoryNotify(word ptr word) WNetDirectoryNotify
 532 pascal16 WNetGetPropertyText(word word word ptr word) WNetGetPropertyText
 533 stub WNetInitialize
diff --git a/if1632/wprocs.spec b/if1632/wprocs.spec
index 40fa9b5..db7aa66 100644
--- a/if1632/wprocs.spec
+++ b/if1632/wprocs.spec
@@ -9,10 +9,10 @@
 19 pascal PrintSetupDlgProc(word word word long) PrintSetupDlgProc
 20 pascal PrintDlgProc(word word word long) PrintDlgProc
 24 pascal16 TASK_Reschedule() TASK_Reschedule
-27 pascal EntryAddrProc(word word) EntryAddrProc
-28 pascal MyAlloc(word word word) MODULE_AllocateSegment
+27 pascal EntryAddrProc(word word) NE_GetEntryPoint
+28 pascal MyAlloc(word word word) NE_AllocateSegment
 29 pascal DefResourceHandler(word word word) NE_DefResourceHandler
-30 pascal FormatCharDlgProc(word word word long) FormatCharDlgProc
+30 pascal FormatCharDlgProc(word word word long) FormatCharDlgProc16
  
 # Interrupt vectors 0-255 are ordinals 100-355
 # The 'word' parameter are the flags pushed on the stack by the interrupt
diff --git a/include/commdlg.h b/include/commdlg.h
index 126b940..7edc7ba 100644
--- a/include/commdlg.h
+++ b/include/commdlg.h
@@ -228,7 +228,7 @@
 	short			nSizeMin WINE_PACKED;   /* minimum pt size allowed & */
 	short			nSizeMax WINE_PACKED;   /* max pt size allowed if    */
 							/* CF_LIMITSIZE is used      */
-} CHOOSEFONT, *LPCHOOSEFONT;
+} CHOOSEFONT16, *LPCHOOSEFONT16;
 
 typedef struct
 {
@@ -248,7 +248,30 @@
 	UINT16	___MISSING_ALIGNMENT__; 
 	INT32   	nSizeMin; 
 	INT32		nSizeMax; 
-} CHOOSEFONT32A, *PCHOOSEFONT32A;
+} CHOOSEFONT32A, *LPCHOOSEFONT32A;
+
+typedef struct
+{
+	UINT32  	lStructSize; 
+	HWND32 		hwndOwner; 
+	HDC32  		hDC; 
+	LPLOGFONT32W    lpLogFont; 
+	INT32		iPointSize; 
+	UINT32		Flags; 
+	COLORREF	rgbColors; 
+	LPARAM		lCustData; 
+	WNDPROC32 	lpfnHook; 
+	LPCWSTR		lpTemplateName; 
+	HINSTANCE32	hInstance; 
+	LPWSTR		lpszStyle; 
+	UINT16		nFontType; 
+	UINT16	___MISSING_ALIGNMENT__; 
+	INT32   	nSizeMin; 
+	INT32		nSizeMax; 
+} CHOOSEFONT32W, *LPCHOOSEFONT32W;
+
+DECL_WINELIB_TYPE_AW(CHOOSEFONT);
+DECL_WINELIB_TYPE_AW(LPCHOOSEFONT);
 
 #pragma pack(4)
 
@@ -264,6 +287,7 @@
 #define CF_EFFECTS                   0x00000100L
 #define CF_APPLY                     0x00000200L
 #define CF_ANSIONLY                  0x00000400L
+#define CF_SCRIPTSONLY               CF_ANSIONLY
 #define CF_NOVECTORFONTS             0x00000800L
 #define CF_NOOEMFONTS                CF_NOVECTORFONTS
 #define CF_NOSIMULATIONS             0x00001000L
@@ -276,6 +300,9 @@
 #define CF_NOFACESEL                 0x00080000L
 #define CF_NOSTYLESEL                0x00100000L
 #define CF_NOSIZESEL                 0x00200000L
+#define CF_SELECTSCRIPT              0x00400000L
+#define CF_NOSCRIPTSEL               0x00800000L
+#define CF_NOVERTFONTS               0x01000000L
 
 #define SIMULATED_FONTTYPE      0x8000
 #define PRINTER_FONTTYPE        0x4000
@@ -285,6 +312,8 @@
 #define REGULAR_FONTTYPE        0x0400
 
 #define WM_CHOOSEFONT_GETLOGFONT        (WM_USER + 1)
+#define WM_CHOOSEFONT_SETLOGFONT	(WM_USER + 101)
+#define WM_CHOOSEFONT_SETFLAGS		(WM_USER + 102)
 
 #define LBSELCHSTRING  "commdlg_LBSelChangedNotify"
 #define SHAREVISTRING  "commdlg_ShareViolation"
@@ -446,7 +475,10 @@
 HWND32  WINAPI ReplaceText32A( LPFINDREPLACE32A lpFind);
 HWND32  WINAPI ReplaceText32W( LPFINDREPLACE32W lpFind);
 #define ReplaceText WINELIB_NAME_AW(ReplaceText)
-BOOL16  WINAPI ChooseFont(LPCHOOSEFONT lpChFont);
+BOOL16  WINAPI ChooseFont16(LPCHOOSEFONT16);
+BOOL32  WINAPI ChooseFont32A(LPCHOOSEFONT32A);
+BOOL32  WINAPI ChooseFont32W(LPCHOOSEFONT32W);
+#define ChooseFont WINELIB_NAME_AW(ChooseFont)
 LRESULT WINAPI FileOpenDlgProc(HWND16 hWnd, UINT16 wMsg, WPARAM16 wParam, LPARAM lParam);
 LRESULT WINAPI FileSaveDlgProc(HWND16 hWnd, UINT16 wMsg, WPARAM16 wParam, LPARAM lParam);
 LRESULT WINAPI ColorDlgProc(HWND16 hWnd, UINT16 wMsg, WPARAM16 wParam, LPARAM lParam);
@@ -460,8 +492,10 @@
 #define ReplaceTextProc WINELIB_NAME_AW(ReplaceTextDlgProc)
 LRESULT WINAPI PrintDlgProc(HWND16 hWnd, UINT16 wMsg, WPARAM16 wParam, LPARAM lParam);
 LRESULT WINAPI PrintSetupDlgProc(HWND16 hWnd, UINT16 wMsg, WPARAM16 wParam, LPARAM lParam);
-LRESULT WINAPI FormatCharDlgProc(HWND16 hWnd, UINT16 wMsg, WPARAM16 wParam, LPARAM lParam);
-
+LRESULT WINAPI FormatCharDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
+LRESULT WINAPI FormatCharDlgProc32A(HWND32,UINT32,WPARAM32,LPARAM);
+LRESULT WINAPI FormatCharDlgProc32W(HWND32,UINT32,WPARAM32,LPARAM);
+#define FormatCharDlgProc LIBWINE_NAME_AW(FormatCharDlgProc)
 #ifdef __cplusplus
 }
 #endif
diff --git a/include/ddeml.h b/include/ddeml.h
index 845a58b..09c2e20 100644
--- a/include/ddeml.h
+++ b/include/ddeml.h
@@ -51,9 +51,13 @@
 BOOL16    WINAPI DdeUninitialize16(DWORD);
 BOOL32    WINAPI DdeUninitialize32(DWORD);
 #define   DdeUninitialize WINELIB_NAME(DdeUninitialize)
-HCONVLIST WINAPI DdeConnectList(DWORD,HSZ,HSZ,HCONVLIST,LPCONVCONTEXT16);
+HCONVLIST WINAPI DdeConnectList16(DWORD,HSZ,HSZ,HCONVLIST,LPCONVCONTEXT16);
+HCONVLIST WINAPI DdeConnectList32(DWORD,HSZ,HSZ,HCONVLIST,LPCONVCONTEXT32);
+#define   DdeConnectList WINELIB_NAME(DdeConnectList)
 HCONV     WINAPI DdeQueryNextServer(HCONVLIST, HCONV);
-BOOL16    WINAPI DdeDisconnectList(HCONVLIST);
+BOOL16    WINAPI DdeDisconnectList16(HCONVLIST);
+BOOL32    WINAPI DdeDisconnectList32(HCONVLIST);
+#define   DdeDisConnectList WINELIB_NAME(DdeDisconnectList)
 HCONV     WINAPI DdeConnect16(DWORD,HSZ,HSZ,LPCONVCONTEXT16);
 HCONV     WINAPI DdeConnect32(DWORD,HSZ,HSZ,LPCONVCONTEXT32);
 #define   DdeConnect WINELIB_NAME(DdeConnect)
@@ -82,7 +86,9 @@
                                         UINT32,DWORD,LPDWORD);
 #define   DdeClientTransaction WINELIB_NAME(DdeClientTransaction)
 BOOL16    WINAPI DdeAbandonTransaction(DWORD,HCONV,DWORD);
-BOOL16    WINAPI DdePostAdvise(DWORD,HSZ,HSZ);
+BOOL16    WINAPI DdePostAdvise16(DWORD,HSZ,HSZ);
+BOOL32    WINAPI DdePostAdvise32(DWORD,HSZ,HSZ);
+#define   DdePostAdvise WINELIB_NAME(DdePostAdvise)
 HDDEDATA  WINAPI DdeAddData(HDDEDATA,LPBYTE,DWORD,DWORD);
 DWORD     WINAPI DdeGetData(HDDEDATA,LPBYTE,DWORD,DWORD);
 LPBYTE    WINAPI DdeAccessData(HDDEDATA,LPDWORD);
diff --git a/include/debug.h b/include/debug.h
index d601ff4..6c6289c 100644
--- a/include/debug.h
+++ b/include/debug.h
@@ -31,87 +31,90 @@
 #define dbch_dialog 23
 #define dbch_dll 24
 #define dbch_dosfs 25
-#define dbch_driver 26
-#define dbch_dsound 27
-#define dbch_edit 28
-#define dbch_event 29
-#define dbch_exec 30
-#define dbch_file 31
-#define dbch_fixup 32
-#define dbch_font 33
-#define dbch_gdi 34
-#define dbch_global 35
-#define dbch_graphics 36
-#define dbch_heap 37
-#define dbch_hook 38
-#define dbch_icon 39
-#define dbch_imagelist 40
-#define dbch_int 41
-#define dbch_int21 42
-#define dbch_int31 43
-#define dbch_key 44
-#define dbch_keyboard 45
-#define dbch_ldt 46
-#define dbch_listbox 47
-#define dbch_local 48
-#define dbch_mci 49
-#define dbch_mcianim 50
-#define dbch_mciwave 51
-#define dbch_mdi 52
-#define dbch_menu 53
-#define dbch_message 54
-#define dbch_metafile 55
-#define dbch_midi 56
-#define dbch_mmaux 57
-#define dbch_mmio 58
-#define dbch_mmsys 59
-#define dbch_mmtime 60
-#define dbch_module 61
-#define dbch_mpr 62
-#define dbch_msg 63
-#define dbch_nonclient 64
-#define dbch_ntdll 65
-#define dbch_ole 66
-#define dbch_palette 67
-#define dbch_print 68
-#define dbch_profile 69
-#define dbch_progress 70
-#define dbch_prop 71
-#define dbch_reg 72
-#define dbch_region 73
-#define dbch_relay 74
-#define dbch_resource 75
-#define dbch_scroll 76
-#define dbch_security 77
-#define dbch_selector 78
-#define dbch_sem 79
-#define dbch_sendmsg 80
-#define dbch_shell 81
-#define dbch_shm 82
-#define dbch_sound 83
-#define dbch_static 84
-#define dbch_stress 85
-#define dbch_string 86
-#define dbch_task 87
-#define dbch_text 88
-#define dbch_thread 89
-#define dbch_thunk 90
-#define dbch_timer 91
-#define dbch_toolhelp 92
-#define dbch_tweak 93
-#define dbch_uitools 94
-#define dbch_updown 95
-#define dbch_ver 96
-#define dbch_virtual 97
-#define dbch_vxd 98
-#define dbch_win 99
-#define dbch_win16drv 100
-#define dbch_win32 101
-#define dbch_wing 102
-#define dbch_winsock 103
-#define dbch_wnet 104
-#define dbch_x11 105
-#define dbch_x11drv 106
+#define dbch_dosmem 26
+#define dbch_driver 27
+#define dbch_dsound 28
+#define dbch_edit 29
+#define dbch_event 30
+#define dbch_exec 31
+#define dbch_file 32
+#define dbch_fixup 33
+#define dbch_font 34
+#define dbch_gdi 35
+#define dbch_global 36
+#define dbch_graphics 37
+#define dbch_heap 38
+#define dbch_hook 39
+#define dbch_icon 40
+#define dbch_imagelist 41
+#define dbch_int 42
+#define dbch_int21 43
+#define dbch_int31 44
+#define dbch_key 45
+#define dbch_keyboard 46
+#define dbch_ldt 47
+#define dbch_listbox 48
+#define dbch_local 49
+#define dbch_mci 50
+#define dbch_mcianim 51
+#define dbch_mciwave 52
+#define dbch_mdi 53
+#define dbch_menu 54
+#define dbch_message 55
+#define dbch_metafile 56
+#define dbch_midi 57
+#define dbch_mmaux 58
+#define dbch_mmio 59
+#define dbch_mmsys 60
+#define dbch_mmtime 61
+#define dbch_module 62
+#define dbch_mpr 63
+#define dbch_msg 64
+#define dbch_nonclient 65
+#define dbch_ntdll 66
+#define dbch_ole 67
+#define dbch_palette 68
+#define dbch_print 69
+#define dbch_profile 70
+#define dbch_progress 71
+#define dbch_prop 72
+#define dbch_reg 73
+#define dbch_region 74
+#define dbch_relay 75
+#define dbch_resource 76
+#define dbch_scroll 77
+#define dbch_security 78
+#define dbch_segment 79
+#define dbch_selector 80
+#define dbch_sem 81
+#define dbch_sendmsg 82
+#define dbch_shell 83
+#define dbch_shm 84
+#define dbch_sound 85
+#define dbch_static 86
+#define dbch_stress 87
+#define dbch_string 88
+#define dbch_system 89
+#define dbch_task 90
+#define dbch_text 91
+#define dbch_thread 92
+#define dbch_thunk 93
+#define dbch_timer 94
+#define dbch_toolhelp 95
+#define dbch_tweak 96
+#define dbch_uitools 97
+#define dbch_updown 98
+#define dbch_ver 99
+#define dbch_virtual 100
+#define dbch_vxd 101
+#define dbch_win 102
+#define dbch_win16drv 103
+#define dbch_win32 104
+#define dbch_wing 105
+#define dbch_winsock 106
+#define dbch_wnet 107
+#define dbch_x11 108
+#define dbch_x11drv 109
 /* Definitions for classes identifiers */
 #define dbcl_fixme 0
 #define dbcl_err 1
diff --git a/include/debugdefs.h b/include/debugdefs.h
index 6189cf5..2b8f5fc 100644
--- a/include/debugdefs.h
+++ b/include/debugdefs.h
@@ -4,7 +4,7 @@
 #include "debugtools.h"
 #endif
 
-#define DEBUG_CHANNEL_COUNT 107
+#define DEBUG_CHANNEL_COUNT 110
 #ifdef DEBUG_RUNTIME
 short debug_msg_enabled[][DEBUG_CLASS_COUNT] = {
 {1, 1, 0, 0},
@@ -114,6 +114,9 @@
 {1, 1, 0, 0},
 {1, 1, 0, 0},
 {1, 1, 0, 0},
+{1, 1, 0, 0},
+{1, 1, 0, 0},
+{1, 1, 0, 0},
 };
 const char* debug_ch_name[] = {
 "accel",
@@ -142,6 +145,7 @@
 "dialog",
 "dll",
 "dosfs",
+"dosmem",
 "driver",
 "dsound",
 "edit",
@@ -194,6 +198,7 @@
 "resource",
 "scroll",
 "security",
+"segment",
 "selector",
 "sem",
 "sendmsg",
@@ -203,6 +208,7 @@
 "static",
 "stress",
 "string",
+"system",
 "task",
 "text",
 "thread",
diff --git a/include/debugger.h b/include/debugger.h
index 94d71aa..866634d 100644
--- a/include/debugger.h
+++ b/include/debugger.h
@@ -85,14 +85,13 @@
 typedef struct wine_locals WineLocals;
 
 
-#define DBG_FIX_ADDR_SEG(addr,default) \
-    { WORD cs, ds; GET_CS(cs); GET_DS(ds); \
+#define DBG_FIX_ADDR_SEG(addr,default) { \
       if ((addr)->seg == 0xffffffff) (addr)->seg = (default); \
-      if (((addr)->seg == cs) || (addr)->seg == ds) (addr)->seg = 0; }
+      if (IS_SELECTOR_SYSTEM((addr)->seg)) (addr)->seg = 0; }
 
 #define DBG_ADDR_TO_LIN(addr) \
-    ((addr)->seg ? (char *)PTR_SEG_OFF_TO_LIN((addr)->seg,(addr)->off) \
-                 : (char *)(addr)->off)
+    (IS_SELECTOR_SYSTEM((addr)->seg) ? (char *)(addr)->off \
+      : (char *)PTR_SEG_OFF_TO_LIN((addr)->seg,(addr)->off))
 
 #define DBG_CHECK_READ_PTR(addr,len) \
     (!DEBUG_IsBadReadPtr((addr),(len)) || \
diff --git a/include/gdi.h b/include/gdi.h
index cce4270..4ea7c7b 100644
--- a/include/gdi.h
+++ b/include/gdi.h
@@ -198,6 +198,7 @@
     BOOL32     (*pPatBlt)(DC*,INT32,INT32,INT32,INT32,DWORD);
     BOOL32     (*pPie)(DC*,INT32,INT32,INT32,INT32,INT32,INT32,INT32,INT32);
     BOOL32     (*pPolyPolygon)(DC*,LPPOINT32,LPINT32,UINT32);
+    BOOL32     (*pPolyPolyline)(DC*,LPPOINT32,LPINT32,UINT32);
     BOOL32     (*pPolygon)(DC*,LPPOINT32,INT32);
     BOOL32     (*pPolyline)(DC*,LPPOINT32,INT32);
     UINT32     (*pRealizePalette)(DC*);
diff --git a/include/ldt.h b/include/ldt.h
index 4d6713f..0f46d9a 100644
--- a/include/ldt.h
+++ b/include/ldt.h
@@ -59,13 +59,13 @@
 /* Convert a segmented ptr (16:16) to a linear (32) pointer */
 
 #define PTR_SEG_OFF_TO_LIN(seg,off) \
- ((void*)(GET_SEL_BASE(seg) + (unsigned int)(off)))
+   ((void*)(GET_SEL_BASE(seg) + (unsigned int)(off)))
 #define PTR_SEG_TO_LIN(ptr) \
- (__winelib ? (void*)(ptr) : PTR_SEG_OFF_TO_LIN(SELECTOROF(ptr),OFFSETOF(ptr)))
+   PTR_SEG_OFF_TO_LIN(SELECTOROF(ptr),OFFSETOF(ptr))
 #define PTR_SEG_OFF_TO_SEGPTR(seg,off) \
- (__winelib ? (SEGPTR)PTR_SEG_OFF_TO_LIN(seg,off) : (SEGPTR)MAKELONG(off,seg))
+   ((SEGPTR)MAKELONG(off,seg))
 #define PTR_SEG_OFF_TO_HUGEPTR(seg,off) \
- (PTR_SEG_OFF_TO_SEGPTR( (seg) + (HIWORD(off) << __AHSHIFT), LOWORD(off) ))
+   PTR_SEG_OFF_TO_SEGPTR( (seg) + (HIWORD(off) << __AHSHIFT), LOWORD(off) )
 
 extern unsigned char ldt_flags_copy[LDT_SIZE];
 
@@ -78,4 +78,12 @@
 
 #define GET_SEL_FLAGS(sel)   (ldt_flags_copy[SELECTOR_TO_ENTRY(sel)])
 
+#define FIRST_LDT_ENTRY_TO_ALLOC  17
+
+/* Determine if sel is a system selector (i.e. not managed by Wine) */
+#define IS_SELECTOR_SYSTEM(sel) \
+   (!((sel) & 4) || (SELECTOR_TO_ENTRY(sel) < FIRST_LDT_ENTRY_TO_ALLOC))
+#define IS_SELECTOR_32BIT(sel) \
+   (IS_SELECTOR_SYSTEM(sel) || (GET_SEL_FLAGS(sel) & LDT_FLAGS_32BIT))
+
 #endif  /* __WINE_LDT_H */
diff --git a/include/miscemu.h b/include/miscemu.h
index 4b5847b..3d58a6c 100644
--- a/include/miscemu.h
+++ b/include/miscemu.h
@@ -15,7 +15,6 @@
 extern DWORD DOSMEM_CollateTable;
 
 extern BOOL32 DOSMEM_Init(void);
-extern void   DOSMEM_InitExports(HMODULE16);
 extern void   DOSMEM_Tick(void);
 extern WORD   DOSMEM_AllocSelector(WORD);
 extern LPVOID DOSMEM_GetBlock(UINT32 size, UINT16* p);
diff --git a/include/module.h b/include/module.h
index 017b3c2..5666695 100644
--- a/include/module.h
+++ b/include/module.h
@@ -101,6 +101,25 @@
 
 #pragma pack(4)
 
+/* internal representation of 32bit modules. per process. */
+typedef enum { MODULE32_PE=1, MODULE32_ELF, /* ... */ } MODULE32_TYPE;
+typedef struct _wine_modref
+{
+	struct _wine_modref	*next;
+	MODULE32_TYPE		type;
+	union {
+		PE_MODREF	pe;
+		/* ELF_MODREF 	elf; */
+	} binfmt;
+
+	HMODULE32		module;
+
+	char			*modname;
+	char 			*fullname;
+	char			*shortname;
+	char			*unixname;
+} WINE_MODREF;
+
 /* Resource types */
 typedef struct resource_typeinfo_s NE_TYPEINFO;
 typedef struct resource_nameinfo_s NE_NAMEINFO;
@@ -114,32 +133,48 @@
 #define NE_MODULE_NAME(pModule) \
     (((OFSTRUCT *)((char*)(pModule) + (pModule)->fileinfo))->szPathName)
 
-#define NE_WIN32_MODULE(pModule) \
-    ((((pModule)->flags & NE_FFLAGS_WIN32) ? \
-                    ((NE_WIN32_EXTRAINFO *)((pModule) + 1))->module32 : 0))
-
 /* module.c */
-extern NE_MODULE *MODULE_GetPtr( HMODULE32 hModule );
+extern NE_MODULE *MODULE_GetPtr16( HMODULE16 hModule );
+extern NE_MODULE *MODULE_GetPtr32( HMODULE32 hModule );
 extern HMODULE16 MODULE_HANDLEtoHMODULE16( HANDLE32 handle );
-extern HMODULE32 MODULE_HANDLEtoHMODULE32( HANDLE32 handle );
-extern void MODULE_DumpModule( HMODULE32 hmodule );
-extern void MODULE_WalkModules(void);
 extern int MODULE_OpenFile( HMODULE32 hModule );
 extern LPSTR MODULE_GetModuleName( HMODULE32 hModule );
-extern void MODULE_RegisterModule( NE_MODULE *pModule );
-extern HMODULE32 MODULE_FindModule( LPCSTR path );
-extern HINSTANCE16 MODULE_CreateInstance( HMODULE16 hModule, BOOL32 lib_only );
-extern HINSTANCE16 MODULE_GetInstance( HMODULE32 hModule );
+extern FARPROC32 MODULE_GetProcAddress32( struct _PDB32*pdb,HMODULE32 hModule,LPCSTR function );
+extern WINE_MODREF *MODULE32_LookupHMODULE( struct _PDB32 *process, HMODULE32 hModule );
+extern HMODULE32 MODULE_FindModule16( LPCSTR path );
+extern HMODULE32 MODULE_FindModule32( struct _PDB32 *process, LPCSTR path );
+extern HINSTANCE16 MODULE_CreateInstance( HMODULE16 hModule, HINSTANCE16 *prev,
+                                          BOOL32 lib_only );
 extern HMODULE32 MODULE_CreateDummyModule( const OFSTRUCT *ofs );
 extern HINSTANCE16 MODULE_Load( LPCSTR name, UINT16 uFlags, LPCSTR cmd_line,
                                 LPCSTR env, UINT32 show_cmd );
-extern WORD MODULE_GetOrdinal( HMODULE32 hModule, const char *name );
-extern FARPROC16 MODULE_GetEntryPoint( HMODULE32 hModule, WORD ordinal );
-extern BOOL16 MODULE_SetEntryPoint( HMODULE32 hModule, WORD ordinal,
-                                    WORD offset );
 extern FARPROC16 MODULE_GetWndProcEntry16( const char *name );
 extern FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE32 hmodule, LPSTR name );
 
+typedef HGLOBAL16 (CALLBACK *RESOURCEHANDLER16)(HGLOBAL16,HMODULE16,HRSRC16);
+
+/* loader/ne/module.c */
+extern void NE_DumpModule( HMODULE16 hModule );
+extern void NE_WalkModules(void);
+extern void NE_RegisterModule( NE_MODULE *pModule );
+extern WORD NE_GetOrdinal( HMODULE16 hModule, const char *name );
+extern FARPROC16 NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal );
+extern BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset );
+extern HINSTANCE16 NE_LoadModule( HFILE32 hFile, OFSTRUCT *ofs, UINT16 flags,
+                                  LPCSTR cmd_line, LPCSTR env,
+                                  UINT32 show_cmd );
+
+/* loader/ne/resource.c */
+extern HGLOBAL16 WINAPI NE_DefResourceHandler(HGLOBAL16,HMODULE16,HRSRC16);
+extern BOOL32 NE_InitResourceHandler( HMODULE16 hModule );
+
+/* loader/ne/segment.c */
+extern BOOL32 NE_LoadSegment( NE_MODULE *pModule, WORD segnum );
+extern BOOL32 NE_LoadAllSegments( NE_MODULE *pModule );
+extern void NE_FixupPrologs( NE_MODULE *pModule );
+extern void NE_InitializeDLLs( HMODULE16 hModule );
+extern BOOL32 NE_CreateSegments( HMODULE16 hModule );
+
 /* builtin.c */
 extern BOOL32 BUILTIN_Init(void);
 extern HMODULE32 BUILTIN_LoadModule( LPCSTR name, BOOL32 force );
@@ -149,13 +184,6 @@
 extern BOOL32 BUILTIN_ParseDLLOptions( const char *str );
 extern void BUILTIN_PrintDLLs(void);
 
-/* ne_image.c */
-extern BOOL32 NE_LoadSegment( NE_MODULE *pModule, WORD segnum );
-extern BOOL32 NE_LoadAllSegments( NE_MODULE *pModule );
-extern BOOL32 NE_LoadDLLs( NE_MODULE *pModule );
-extern void NE_FixupPrologs( NE_MODULE *pModule );
-extern void NE_InitializeDLLs( HMODULE16 hModule );
-
 /* relay32/builtin.c */
 extern HMODULE32 BUILTIN32_LoadModule( LPCSTR name, BOOL32 force,
                                        struct _PDB32 *process );
diff --git a/include/neexe.h b/include/neexe.h
index ff83390..7a428fd 100644
--- a/include/neexe.h
+++ b/include/neexe.h
@@ -168,51 +168,6 @@
 #define NE_RELFLAG_ADDITIVE	4
 
 /*
- * DOS PSP
- */
-struct dos_psp_s
-{
-    unsigned short pspInt20;
-    unsigned short pspNextParagraph;
-    unsigned char  pspReserved1;
-    unsigned char  pspDispatcher[5];
-    unsigned short pspTerminateVector[2];
-    unsigned short pspControlCVector[2];
-    unsigned short pspCritErrorVector[2];
-    unsigned short pspReserved2[11];
-    unsigned short pspEnvironment;
-    unsigned short pspReserved3[23];
-    unsigned char  pspFCB_1[16];
-    unsigned char  pspFCB_2[16];
-    unsigned char  pspReserved4[4];
-    unsigned char  pspCommandTailCount;
-    unsigned char  pspCommandTail[128];
-};
-
-/*
- * Entry table structures.
- */
-struct entry_tab_header_s
-{
-    unsigned char n_entries;
-    unsigned char seg_number;
-};
-
-struct entry_tab_movable_s
-{
-    unsigned char flags;
-    unsigned char int3f[2];
-    unsigned char seg_number;
-    unsigned short offset;
-};
-
-struct entry_tab_fixed_s
-{
-    unsigned char flags;
-    unsigned char offset[2];
-};
-
-/*
  * Resource table structures.
  */
 struct resource_nameinfo_s
@@ -229,7 +184,7 @@
 {
     unsigned short type_id;	/* Type identifier */
     unsigned short count;	/* Number of resources of this type */
-    DWORD	   resloader;	/* SetResourceHandler() */
+    FARPROC16	   resloader;	/* SetResourceHandler() */
     /*
      * Name info array.
      */
diff --git a/include/ole.h b/include/ole.h
index fd671be..42ba711 100644
--- a/include/ole.h
+++ b/include/ole.h
@@ -7,24 +7,29 @@
 
 #include "windows.h"
 
-typedef CHAR	OLECHAR16;
-typedef LPSTR	LPOLESTR16;
-typedef LPCSTR	LPCOLESTR16;
-typedef WCHAR	OLECHAR32;
-typedef LPWSTR	LPOLESTR32;
-typedef LPCWSTR	LPCOLESTR32;
+typedef CHAR		OLECHAR16;
+typedef OLECHAR16	*BSTR16;
+typedef BSTR16		*LPBSTR16;
+typedef LPSTR		LPOLESTR16;
+typedef LPCSTR		LPCOLESTR16;
+typedef WCHAR		OLECHAR32;
+typedef OLECHAR32	*BSTR32;
+typedef BSTR32		*LPBSTR32;
+typedef LPWSTR		LPOLESTR32;
+typedef LPCWSTR		LPCOLESTR32;
 DECL_WINELIB_TYPE(OLECHAR);
 DECL_WINELIB_TYPE(LPOLESTR);
 DECL_WINELIB_TYPE(LPCOLESTR);
+DECL_WINELIB_TYPE(BSTR);
+DECL_WINELIB_TYPE(LPBSTR);
 
 #define OLESTR16(x) x
-#define OLESTR32(x) L##x
+#define OLESTR32(x) L##x	/* probably wrong */
 #define OLESTR WINELIB_NAME(OLESTR)
 
 typedef unsigned short VARTYPE;
 typedef LONG DISPID;
 
-
 /* object types */
 #define OT_LINK		1
 #define OT_EMBEDDED	2
diff --git a/include/oleauto.h b/include/oleauto.h
new file mode 100644
index 0000000..8a0f265
--- /dev/null
+++ b/include/oleauto.h
@@ -0,0 +1,14 @@
+#ifndef __WINE_OLEAUTO_H
+#define __WINE_OLEAUTO_H
+
+BSTR16 SysAllocString16(LPOLESTR16);
+BSTR32 SysAllocString32(LPOLESTR32);
+#define SysAllocString WINELIB_NAME(SysAllocString)
+INT16 SysReAllocString16(LPBSTR16,LPOLESTR16);
+INT32 SysReAllocString32(LPBSTR32,LPOLESTR32);
+#define SysReAllocString WINELIB_NAME(SysReAllocString)
+VOID SysFreeString16(BSTR16);
+VOID SysFreeString32(BSTR32);
+#define SysFreeString WINELIB_NAME(SysFreeString)
+
+#endif
diff --git a/include/pe_image.h b/include/pe_image.h
index 61c5912..bf276f6 100644
--- a/include/pe_image.h
+++ b/include/pe_image.h
@@ -9,9 +9,7 @@
 /* modreference used for attached processes
  * all section are calculated here, relocations etc.
  */
-struct pe_modref {
-	struct pe_modref		*next;
-        HMODULE32                       module;
+typedef struct {
 	LPIMAGE_IMPORT_DESCRIPTOR	pe_import;
 	LPIMAGE_EXPORT_DIRECTORY	pe_export;
 	LPIMAGE_RESOURCE_DIRECTORY	pe_resource;
@@ -21,16 +19,16 @@
 #define PE_MODREF_NO_DLL_CALLS		0x00000002
 #define PE_MODREF_RELOCS_DONE		0x00000004
 #define PE_MODREF_TLS_ALLOCED		0x00000008
+#define PE_MODREF_INTERNAL		0x00000010
 	int				tlsindex;
-};
+} PE_MODREF;
 
 struct _PDB32;
-
-typedef struct pe_modref PE_MODREF;
-
+struct _wine_modref;
 extern int PE_unloadImage(HMODULE32 hModule);
-extern FARPROC32 PE_FindExportedFunction( struct _PDB32 *process,
-                                          HMODULE32 hModule, LPCSTR funcName);
+extern FARPROC32 PE_FindExportedFunction( 
+	struct _PDB32 *process,struct _wine_modref *wm, LPCSTR funcName
+);
 extern void my_wcstombs(char * result, u_short * source, int len);
 extern BOOL32 PE_EnumResourceTypes32A(HMODULE32,ENUMRESTYPEPROC32A,LONG);
 extern BOOL32 PE_EnumResourceTypes32W(HMODULE32,ENUMRESTYPEPROC32W,LONG);
@@ -38,10 +36,10 @@
 extern BOOL32 PE_EnumResourceNames32W(HMODULE32,LPCWSTR,ENUMRESNAMEPROC32W,LONG);
 extern BOOL32 PE_EnumResourceLanguages32A(HMODULE32,LPCSTR,LPCSTR,ENUMRESLANGPROC32A,LONG);
 extern BOOL32 PE_EnumResourceLanguages32W(HMODULE32,LPCWSTR,LPCWSTR,ENUMRESLANGPROC32W,LONG);
-extern HRSRC32 PE_FindResourceEx32W(HINSTANCE32,LPCWSTR,LPCWSTR,WORD);
-extern DWORD PE_SizeofResource32(HINSTANCE32,HRSRC32);
+extern HRSRC32 PE_FindResourceEx32W(struct _wine_modref*,LPCWSTR,LPCWSTR,WORD);
+extern DWORD PE_SizeofResource32(HMODULE32,HRSRC32);
 extern HMODULE32 PE_LoadLibraryEx32A(LPCSTR,struct _PDB32*,HFILE32,DWORD);
-extern HGLOBAL32 PE_LoadResource32(HINSTANCE32,HRSRC32);
+extern HGLOBAL32 PE_LoadResource32(struct _wine_modref *wm,HRSRC32);
 extern HINSTANCE16 PE_LoadModule( HFILE32 hFile, OFSTRUCT *ofs,
                                   LPCSTR cmd_line, LPCSTR env, UINT16 showCmd);
 
diff --git a/include/process.h b/include/process.h
index 54c699f..dbdfbf3 100644
--- a/include/process.h
+++ b/include/process.h
@@ -10,8 +10,8 @@
 #include "windows.h"
 #include "winbase.h"
 #include "winnt.h"
+#include "module.h"
 #include "k32obj.h"
-#include "pe_image.h"
 
 struct _NE_MODULE;
 
@@ -77,7 +77,7 @@
     ENVDB           *env_db;           /* 40 Environment database */
     HANDLE_TABLE    *handle_table;     /* 44 Handle table */
     struct _PDB32   *parent;           /* 48 Parent process */
-    PE_MODREF       *modref_list;      /* 4c MODREF list */
+    WINE_MODREF     *modref_list;      /* 4c MODREF list */
     void            *thread_list;      /* 50 List of threads */
     void            *debuggee_CB;      /* 54 Debuggee context block */
     void            *local_heap_free;  /* 58 Head of local heap free list */
@@ -88,7 +88,7 @@
     DWORD            tls_bits[2];      /* 88 TLS in-use bits */
     DWORD            process_dword;    /* 90 Unknown */
     struct _PDB32   *group;            /* 94 Process group */
-    PE_MODREF       *exe_modref;       /* 98 MODREF for the process EXE */
+    WINE_MODREF     *exe_modref;       /* 98 MODREF for the process EXE */
     LPTOP_LEVEL_EXCEPTION_FILTER top_filter; /* 9c Top exception filter */
     DWORD            priority;         /* a0 Priority level */
     HANDLE32         heap_list;        /* a4 Head of process heap list */
@@ -103,6 +103,12 @@
     LCID             locale;           /* c4 Locale to be queried by GetThreadLocale (NT) */
 } PDB32;
 
+/* Process flags */
+#define PDB32_WIN16_PROC    0x0008  /* Win16 process */
+#define PDB32_DOS_PROC      0x0010  /* Dos process */
+#define PDB32_CONSOLE_PROC  0x0020  /* Console process */
+#define PDB32_FILE_APIS_OEM 0x0040  /* File APIs are OEM */
+
 /* PDB <-> Process id conversion macros */
 #define PROCESS_OBFUSCATOR     ((DWORD)0xdeadbeef)
 #define PROCESS_ID_TO_PDB(id)  ((PDB32 *)((id) ^ PROCESS_OBFUSCATOR))
diff --git a/include/resource.h b/include/resource.h
index 4f1cd26..0c89906 100644
--- a/include/resource.h
+++ b/include/resource.h
@@ -45,22 +45,6 @@
 #undef HAVE_WINE_CONSTRUCTOR
 #endif
 
-typedef HGLOBAL16 (CALLBACK *RESOURCEHANDLER16)(HGLOBAL16, HMODULE16, HRSRC16 );
-
-/* FIXME: convert all NE_ functions to accept NE_MODULE pointer instead
- * of redundant hModule (which is always verified prior to calling these).
- */
-
-extern int NE_AccessResource( HMODULE16 hModule, HRSRC16 hRsrc );
-extern BOOL32 NE_FreeResource( HMODULE16 hModule, HGLOBAL16 handle );
-extern HRSRC16 NE_FindResource(HMODULE16 hModule, SEGPTR typeId, SEGPTR resId);
-extern DWORD NE_SizeofResource( HMODULE16 hModule, HRSRC16 hRsrc );
-extern SEGPTR NE_LockResource( HMODULE16 hModule, HGLOBAL16 handle );
-extern HGLOBAL16 NE_AllocResource( HMODULE16 hModule, HRSRC16 hRsrc, DWORD size );
-extern HGLOBAL16 NE_LoadResource( HMODULE16 hModule,  HRSRC16 hRsrc );
-extern BOOL32 NE_InitResourceHandler( HMODULE16 hModule );
-extern FARPROC32 NE_SetResourceHandler( HMODULE16 hModule, SEGPTR typeId, FARPROC32 handler);
-
 extern HGLOBAL16 SYSRES_LoadResource( SYSTEM_RESOURCE id );
 extern void SYSRES_FreeResource( HGLOBAL16 handle );
 extern LPCVOID SYSRES_GetResPtr( SYSTEM_RESOURCE id );
diff --git a/include/sig_context.h b/include/sig_context.h
index 3db18ea..b1edc30 100644
--- a/include/sig_context.h
+++ b/include/sig_context.h
@@ -120,9 +120,10 @@
 #define SS_sig(context)      ((context)->sc_ss)
                             
 #ifdef linux
-/* fs and gs are not supported on *BSD. Hopefully we won't need them. */
+/* fs and gs are not supported on *BSD. */
 #define FS_sig(context)      ((context)->sc_fs)
 #define GS_sig(context)      ((context)->sc_gs)
+#define CR2_sig(context)     ((context)->cr2)
 #endif
                             
 #ifndef __FreeBSD__         
diff --git a/include/version.h b/include/version.h
index c098d61..aed6733 100644
--- a/include/version.h
+++ b/include/version.h
@@ -1 +1 @@
-#define WINE_RELEASE_INFO "Wine release 980413"
+#define WINE_RELEASE_INFO "Wine release 980503"
diff --git a/include/winbase.h b/include/winbase.h
index 0983276..78835f2 100644
--- a/include/winbase.h
+++ b/include/winbase.h
@@ -160,7 +160,7 @@
 	WCHAR szCSDVersion[128];
 } OSVERSIONINFO32W;
 
-DECL_WINELIB_TYPE_AW(OSVERSIONINFO);
+DECL_WINELIB_TYPE_AW(OSVERSIONINFO)
 
 #define VER_PLATFORM_WIN32s             0
 #define VER_PLATFORM_WIN32_WINDOWS      1
diff --git a/include/wincon.h b/include/wincon.h
index da8b20e..bc7c710 100644
--- a/include/wincon.h
+++ b/include/wincon.h
@@ -31,11 +31,13 @@
 #define BACKGROUND_RED       0x0040 /* background color contains red. */
 #define BACKGROUND_INTENSITY 0x0080 /* background color is intensified. */
 
+/*
 typedef struct tagCOORD
 {
     INT16 x;
     INT16 y;
 } COORD,*LPCOORD;
+*/
 
 typedef struct tagSMALL_RECT
 {
diff --git a/include/windows.h b/include/windows.h
index e1861ae..6a66752 100644
--- a/include/windows.h
+++ b/include/windows.h
@@ -24,8 +24,8 @@
     INT32  cy;
 } SIZE32, *LPSIZE32;
 
-DECL_WINELIB_TYPE(SIZE);
-DECL_WINELIB_TYPE(LPSIZE);
+DECL_WINELIB_TYPE(SIZE)
+DECL_WINELIB_TYPE(LPSIZE)
 
 #define CONV_SIZE16TO32(s16,s32) \
             ((s32)->cx = (INT32)(s16)->cx, (s32)->cy = (INT32)(s16)->cy)
@@ -46,8 +46,8 @@
     INT32  y;
 } POINT32, *LPPOINT32;
 
-DECL_WINELIB_TYPE(POINT);
-DECL_WINELIB_TYPE(LPPOINT);
+DECL_WINELIB_TYPE(POINT)
+DECL_WINELIB_TYPE(LPPOINT)
 
 #define CONV_POINT16TO32(p16,p32) \
             ((p32)->x = (INT32)(p16)->x, (p32)->y = (INT32)(p16)->y)
@@ -75,8 +75,8 @@
     INT32  bottom;
 } RECT32, *LPRECT32;
 
-DECL_WINELIB_TYPE(RECT);
-DECL_WINELIB_TYPE(LPRECT);
+DECL_WINELIB_TYPE(RECT)
+DECL_WINELIB_TYPE(LPRECT)
 
 #define CONV_RECT16TO32(r16,r32) \
     ((r32)->left  = (INT32)(r16)->left,  (r32)->top    = (INT32)(r16)->top, \
@@ -85,6 +85,13 @@
     ((r16)->left  = (INT16)(r32)->left,  (r16)->top    = (INT16)(r32)->top, \
      (r16)->right = (INT16)(r32)->right, (r16)->bottom = (INT16)(r32)->bottom)
 
+
+typedef struct tagCOORD {
+    INT16 x;
+    INT16 y;
+} COORD, *LPCOORD;
+
+
 typedef struct
 {
     WORD   wFirst;
@@ -99,8 +106,8 @@
     INT32  iKernAmount;
 } KERNINGPAIR32, *LPKERNINGPAIR32;
 
-DECL_WINELIB_TYPE(KERNINGPAIR);
-DECL_WINELIB_TYPE(LPKERNINGPAIR);
+DECL_WINELIB_TYPE(KERNINGPAIR)
+DECL_WINELIB_TYPE(LPKERNINGPAIR)
 
 typedef struct
 {
@@ -122,10 +129,39 @@
     BYTE    rgbReserved[32];
 } PAINTSTRUCT32, *LPPAINTSTRUCT32;
 
-DECL_WINELIB_TYPE(PAINTSTRUCT);
-DECL_WINELIB_TYPE(LPPAINTSTRUCT);
+DECL_WINELIB_TYPE(PAINTSTRUCT)
+DECL_WINELIB_TYPE(LPPAINTSTRUCT)
 
 
+typedef struct tagPIXELFORMATDESCRIPTOR {
+    WORD  nSize;
+    WORD  nVersion;
+    DWORD dwFlags;
+    BYTE  iPixelType;
+    BYTE  cColorBits;
+    BYTE  cRedBits;
+    BYTE  cRedShift;
+    BYTE  cGreenBits;
+    BYTE  cGreenShift;
+    BYTE  cBlueBits;
+    BYTE  cBlueShift;
+    BYTE  cAlphaBits;
+    BYTE  cAlphaShift;
+    BYTE  cAccumBits;
+    BYTE  cAccumRedBits;
+    BYTE  cAccumGreenBits;
+    BYTE  cAccumBlueBits;
+    BYTE  cAccumAlphaBits;
+    BYTE  cDepthBits;
+    BYTE  cStencilBits;
+    BYTE  cAuxBuffers;
+    BYTE  iLayerType;
+    BYTE  bReserved;
+    DWORD dwLayerMask;
+    DWORD dwVisibleMask;
+    DWORD dwDamageMask;
+} PIXELFORMATDESCRIPTOR, *LPPIXELFORMATDESCRIPTOR;
+
   /* Windows */
 
 typedef struct
@@ -176,8 +212,8 @@
     DWORD       dwExStyle;
 } CREATESTRUCT32W, *LPCREATESTRUCT32W;
 
-DECL_WINELIB_TYPE_AW(CREATESTRUCT);
-DECL_WINELIB_TYPE_AW(LPCREATESTRUCT);
+DECL_WINELIB_TYPE_AW(CREATESTRUCT)
+DECL_WINELIB_TYPE_AW(LPCREATESTRUCT)
 
 typedef struct 
 {
@@ -191,8 +227,8 @@
     UINT32    idFirstChild;
 } CLIENTCREATESTRUCT32, *LPCLIENTCREATESTRUCT32;
 
-DECL_WINELIB_TYPE(CLIENTCREATESTRUCT);
-DECL_WINELIB_TYPE(LPCLIENTCREATESTRUCT);
+DECL_WINELIB_TYPE(CLIENTCREATESTRUCT)
+DECL_WINELIB_TYPE(LPCLIENTCREATESTRUCT)
 
 typedef struct
 {
@@ -233,8 +269,8 @@
     LPARAM       lParam;
 } MDICREATESTRUCT32W, *LPMDICREATESTRUCT32W;
 
-DECL_WINELIB_TYPE_AW(MDICREATESTRUCT);
-DECL_WINELIB_TYPE_AW(LPMDICREATESTRUCT);
+DECL_WINELIB_TYPE_AW(MDICREATESTRUCT)
+DECL_WINELIB_TYPE_AW(LPMDICREATESTRUCT)
 
 #define MDITILE_VERTICAL     0x0000   
 #define MDITILE_HORIZONTAL   0x0001
@@ -289,7 +325,7 @@
     POINT32   ptMaxTrackSize;
 } MINMAXINFO32;
 
-DECL_WINELIB_TYPE(MINMAXINFO);
+DECL_WINELIB_TYPE(MINMAXINFO)
 
   /* RedrawWindow() flags */
 #define RDW_INVALIDATE       0x0001
@@ -334,7 +370,7 @@
     UINT32  flags;
 } WINDOWPOS32;
 
-DECL_WINELIB_TYPE(WINDOWPOS);
+DECL_WINELIB_TYPE(WINDOWPOS)
 
   /* SetWindowPlacement() struct */
 typedef struct
@@ -357,8 +393,8 @@
     RECT32   rcNormalPosition WINE_PACKED;
 } WINDOWPLACEMENT32, *LPWINDOWPLACEMENT32;
 
-DECL_WINELIB_TYPE(WINDOWPLACEMENT);
-DECL_WINELIB_TYPE(LPWINDOWPLACEMENT);
+DECL_WINELIB_TYPE(WINDOWPLACEMENT)
+DECL_WINELIB_TYPE(LPWINDOWPLACEMENT)
 
   /* WINDOWPLACEMENT flags */
 #define WPF_SETMINPOSITION      0x0001
@@ -388,8 +424,8 @@
     WINDOWPOS32 *lppos;
 } NCCALCSIZE_PARAMS32, *LPNCCALCSIZE_PARAMS32;
 
-DECL_WINELIB_TYPE(NCCALCSIZE_PARAMS);
-DECL_WINELIB_TYPE(LPNCCALCSIZE_PARAMS);
+DECL_WINELIB_TYPE(NCCALCSIZE_PARAMS)
+DECL_WINELIB_TYPE(LPNCCALCSIZE_PARAMS)
 
   /* WM_NCCALCSIZE return flags */
 #define WVR_ALIGNTOP        0x0010
@@ -489,8 +525,8 @@
     LPCWSTR     lpszClassName;
 } WNDCLASS32W, *LPWNDCLASS32W;
 
-DECL_WINELIB_TYPE_AW(WNDCLASS);
-DECL_WINELIB_TYPE_AW(LPWNDCLASS);
+DECL_WINELIB_TYPE_AW(WNDCLASS)
+DECL_WINELIB_TYPE_AW(LPWNDCLASS)
 
 typedef struct
 {
@@ -540,8 +576,8 @@
     HICON32     hIconSm;
 } WNDCLASSEX32W, *LPWNDCLASSEX32W;
 
-DECL_WINELIB_TYPE_AW(WNDCLASSEX);
-DECL_WINELIB_TYPE_AW(LPWNDCLASSEX);
+DECL_WINELIB_TYPE_AW(WNDCLASSEX)
+DECL_WINELIB_TYPE_AW(LPWNDCLASSEX)
 
 #define CS_VREDRAW          0x0001
 #define CS_HREDRAW          0x0002
@@ -645,8 +681,8 @@
     HWND32  hwnd;
 } EVENTMSG32, *LPEVENTMSG32;
 
-DECL_WINELIB_TYPE(EVENTMSG);
-DECL_WINELIB_TYPE(LPEVENTMSG);
+DECL_WINELIB_TYPE(EVENTMSG)
+DECL_WINELIB_TYPE(LPEVENTMSG)
 
   /* Mouse hook structure */
 
@@ -666,8 +702,8 @@
     DWORD   dwExtraInfo;
 } MOUSEHOOKSTRUCT32, *LPMOUSEHOOKSTRUCT32;
 
-DECL_WINELIB_TYPE(MOUSEHOOKSTRUCT);
-DECL_WINELIB_TYPE(LPMOUSEHOOKSTRUCT);
+DECL_WINELIB_TYPE(MOUSEHOOKSTRUCT)
+DECL_WINELIB_TYPE(LPMOUSEHOOKSTRUCT)
 
   /* Hardware hook structure */
 
@@ -687,8 +723,8 @@
     LPARAM    lParam;
 } HARDWAREHOOKSTRUCT32, *LPHARDWAREHOOKSTRUCT32;
 
-DECL_WINELIB_TYPE(HARDWAREHOOKSTRUCT);
-DECL_WINELIB_TYPE(LPHARDWAREHOOKSTRUCT);
+DECL_WINELIB_TYPE(HARDWAREHOOKSTRUCT)
+DECL_WINELIB_TYPE(LPHARDWAREHOOKSTRUCT)
 
   /* CBT hook values */
 #define HCBT_MOVESIZE	    0
@@ -722,8 +758,8 @@
     HWND32           hwndInsertAfter;
 } CBT_CREATEWND32W, *LPCBT_CREATEWND32W;
 
-DECL_WINELIB_TYPE_AW(CBT_CREATEWND);
-DECL_WINELIB_TYPE_AW(LPCBT_CREATEWND);
+DECL_WINELIB_TYPE_AW(CBT_CREATEWND)
+DECL_WINELIB_TYPE_AW(LPCBT_CREATEWND)
 
 typedef struct
 {
@@ -737,8 +773,8 @@
     HWND32    hWndActive;
 } CBTACTIVATESTRUCT32, *LPCBTACTIVATESTRUCT32;
 
-DECL_WINELIB_TYPE(CBTACTIVATESTRUCT);
-DECL_WINELIB_TYPE(LPCBTACTIVATESTRUCT);
+DECL_WINELIB_TYPE(CBTACTIVATESTRUCT)
+DECL_WINELIB_TYPE(LPCBTACTIVATESTRUCT)
 
   /* Shell hook values */
 #define HSHELL_WINDOWCREATED       1
@@ -765,8 +801,94 @@
     INT32       code;
 } DEBUGHOOKINFO32, *LPDEBUGHOOKINFO32;
 
-DECL_WINELIB_TYPE(DEBUGHOOKINFO);
-DECL_WINELIB_TYPE(LPDEBUGHOOKINFO);
+DECL_WINELIB_TYPE(DEBUGHOOKINFO)
+DECL_WINELIB_TYPE(LPDEBUGHOOKINFO)
+
+typedef DWORD (CALLBACK *LPTHREAD_START_ROUTINE)(LPVOID);
+
+/* This is also defined in winnt.h */
+/* typedef struct _EXCEPTION_RECORD {
+    DWORD   ExceptionCode;
+    DWORD   ExceptionFlags;
+    struct  _EXCEPTION_RECORD *ExceptionRecord;
+    LPVOID  ExceptionAddress;
+    DWORD   NumberParameters;
+    DWORD   ExceptionInformation[15];
+} EXCEPTION_RECORD; */
+
+typedef struct _EXCEPTION_DEBUG_INFO {
+/*    EXCEPTION_RECORD ExceptionRecord; */
+    DWORD dwFirstChange;
+} EXCEPTION_DEBUG_INFO;
+
+typedef struct _CREATE_THREAD_DEBUG_INFO {
+    HANDLE32 hThread;
+    LPVOID lpThreadLocalBase;
+    LPTHREAD_START_ROUTINE lpStartAddress;
+} CREATE_THREAD_DEBUG_INFO;
+
+typedef struct _CREATE_PROCESS_DEBUG_INFO {
+    HANDLE32 hFile;
+    HANDLE32 hProcess;
+    HANDLE32 hThread;
+    LPVOID lpBaseOfImage;
+    DWORD dwDebugInfoFileOffset;
+    DWORD nDebugInfoSize;
+    LPVOID lpThreadLocalBase;
+    LPTHREAD_START_ROUTINE lpStartAddress;
+    LPVOID lpImageName;
+    WORD fUnicode;
+} CREATE_PROCESS_DEBUG_INFO;
+
+typedef struct _EXIT_THREAD_DEBUG_INFO {
+    DWORD dwExitCode;
+} EXIT_THREAD_DEBUG_INFO;
+
+typedef struct _EXIT_PROCESS_DEBUG_INFO {
+    DWORD dwExitCode;
+} EXIT_PROCESS_DEBUG_INFO;
+
+typedef struct _LOAD_DLL_DEBUG_INFO {
+    HANDLE32 hFile;
+    LPVOID   lpBaseOfDll;
+    DWORD    dwDebugInfoFileOffset;
+    DWORD    nDebugInfoSize;
+    LPVOID   lpImageName;
+    WORD     fUnicode;
+} LOAD_DLL_DEBUG_INFO;
+
+typedef struct _UNLOAD_DLL_DEBUG_INFO {
+    LPVOID lpBaseOfDll;
+} UNLOAD_DLL_DEBUG_INFO;
+
+typedef struct _OUTPUT_DEBUG_STRING_INFO {
+    LPSTR lpDebugStringData;
+    WORD  fUnicode;
+    WORD  nDebugStringLength;
+} OUTPUT_DEBUG_STRING_INFO;
+
+typedef struct _RIP_INFO {
+    DWORD dwError;
+    DWORD dwType;
+} RIP_INFO;
+
+typedef struct _DEBUG_EVENT {
+    DWORD dwDebugEventCode;
+    DWORD dwProcessId;
+    DWORD dwThreadId;
+    union {
+        EXCEPTION_DEBUG_INFO      Exception;
+        CREATE_THREAD_DEBUG_INFO  CreateThread;
+        CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
+        EXIT_THREAD_DEBUG_INFO    ExitThread;
+        EXIT_PROCESS_DEBUG_INFO   ExitProcess;
+        LOAD_DLL_DEBUG_INFO       LoadDll;
+        UNLOAD_DLL_DEBUG_INFO     UnloadDll;
+        OUTPUT_DEBUG_STRING_INFO  DebugString;
+        RIP_INFO                  RipInfo;
+    } u;
+} DEBUG_EVENT, *LPDEBUG_EVENT;
+
 
 /***** Dialogs *****/
 
@@ -841,8 +963,8 @@
     POINT32   pt;
 } MSG32, *LPMSG32;
 
-DECL_WINELIB_TYPE(MSG);
-DECL_WINELIB_TYPE(LPMSG);
+DECL_WINELIB_TYPE(MSG)
+DECL_WINELIB_TYPE(LPMSG)
 	
   /* Raster operations */
 
@@ -966,8 +1088,8 @@
     LPVOID bmBits WINE_PACKED;
 } BITMAP32, *LPBITMAP32;
 
-DECL_WINELIB_TYPE(BITMAP);
-DECL_WINELIB_TYPE(LPBITMAP);
+DECL_WINELIB_TYPE(BITMAP)
+DECL_WINELIB_TYPE(LPBITMAP)
 
   /* Brushes */
 
@@ -985,8 +1107,8 @@
     INT32      lbHatch;
 } LOGBRUSH32, *LPLOGBRUSH32;
 
-DECL_WINELIB_TYPE(LOGBRUSH);
-DECL_WINELIB_TYPE(LPLOGBRUSH);
+DECL_WINELIB_TYPE(LOGBRUSH)
+DECL_WINELIB_TYPE(LPLOGBRUSH)
 
   /* Brush styles */
 #define BS_SOLID	    0
@@ -1072,8 +1194,8 @@
     WCHAR  lfFaceName[LF_FACESIZE];
 } LOGFONT32W, *LPLOGFONT32W;
 
-DECL_WINELIB_TYPE_AW(LOGFONT);
-DECL_WINELIB_TYPE_AW(LPLOGFONT);
+DECL_WINELIB_TYPE_AW(LOGFONT)
+DECL_WINELIB_TYPE_AW(LPLOGFONT)
 
 typedef struct
 {
@@ -1120,9 +1242,9 @@
   WCHAR      elfScript[LF_FACESIZE] WINE_PACKED;
 } ENUMLOGFONTEX32W,*LPENUMLOGFONTEX32W;
 
-DECL_WINELIB_TYPE_AW(ENUMLOGFONT);
-DECL_WINELIB_TYPE_AW(LPENUMLOGFONT);
-DECL_WINELIB_TYPE_AW(LPENUMLOGFONTEX);
+DECL_WINELIB_TYPE_AW(ENUMLOGFONT)
+DECL_WINELIB_TYPE_AW(LPENUMLOGFONT)
+DECL_WINELIB_TYPE_AW(LPENUMLOGFONTEX)
 
 typedef struct
 {
@@ -1341,8 +1463,8 @@
     BYTE      tmCharSet;
 } TEXTMETRIC32W, *LPTEXTMETRIC32W;
 
-DECL_WINELIB_TYPE_AW(TEXTMETRIC);
-DECL_WINELIB_TYPE_AW(LPTEXTMETRIC);
+DECL_WINELIB_TYPE_AW(TEXTMETRIC)
+DECL_WINELIB_TYPE_AW(LPTEXTMETRIC)
 
 /* ntmFlags field flags */
 #define NTM_REGULAR     0x00000040L
@@ -1433,8 +1555,8 @@
     UINT32    ntmAvgWidth;
 } NEWTEXTMETRIC32W, *LPNEWTEXTMETRIC32W;
 
-DECL_WINELIB_TYPE_AW(NEWTEXTMETRIC);
-DECL_WINELIB_TYPE_AW(LPNEWTEXTMETRIC);
+DECL_WINELIB_TYPE_AW(NEWTEXTMETRIC)
+DECL_WINELIB_TYPE_AW(LPNEWTEXTMETRIC)
 
 typedef struct
 {
@@ -1454,8 +1576,8 @@
     FONTSIGNATURE       ntmeFontSignature;
 } NEWTEXTMETRICEX32W,*LPNEWTEXTMETRICEX32W;
 
-DECL_WINELIB_TYPE_AW(NEWTEXTMETRICEX);
-DECL_WINELIB_TYPE_AW(LPNEWTEXTMETRICEX);
+DECL_WINELIB_TYPE_AW(NEWTEXTMETRICEX)
+DECL_WINELIB_TYPE_AW(LPNEWTEXTMETRICEX)
 
 
 typedef INT16 (CALLBACK *FONTENUMPROC16)(SEGPTR,SEGPTR,UINT16,LPARAM);
@@ -1463,12 +1585,12 @@
                                           UINT32,LPARAM);
 typedef INT32 (CALLBACK *FONTENUMPROC32W)(LPENUMLOGFONT32W,LPNEWTEXTMETRIC32W,
                                           UINT32,LPARAM);
-DECL_WINELIB_TYPE_AW(FONTENUMPROC);
+DECL_WINELIB_TYPE_AW(FONTENUMPROC)
 
 typedef INT16 (CALLBACK *FONTENUMPROCEX16)(SEGPTR,SEGPTR,UINT16,LPARAM);
 typedef INT32 (CALLBACK *FONTENUMPROCEX32A)(LPENUMLOGFONTEX32A,LPNEWTEXTMETRICEX32A,UINT32,LPARAM);
 typedef INT32 (CALLBACK *FONTENUMPROCEX32W)(LPENUMLOGFONTEX32W,LPNEWTEXTMETRICEX32W,UINT32,LPARAM);
-DECL_WINELIB_TYPE_AW(FONTENUMPROCEX);
+DECL_WINELIB_TYPE_AW(FONTENUMPROCEX)
 
   /* tmPitchAndFamily bits */
 #define TMPF_FIXED_PITCH    1		/* means variable pitch */
@@ -1509,8 +1631,8 @@
     INT16	gmCellIncY;
 } GLYPHMETRICS32, *LPGLYPHMETRICS32;
 
-DECL_WINELIB_TYPE(GLYPHMETRICS);
-DECL_WINELIB_TYPE(LPGLYPHMETRICS);
+DECL_WINELIB_TYPE(GLYPHMETRICS)
+DECL_WINELIB_TYPE(LPGLYPHMETRICS)
 
 #define GGO_METRICS         0
 #define GGO_BITMAP          1
@@ -1545,8 +1667,8 @@
     INT32   abcC;
 } ABC32, *LPABC32;
 
-DECL_WINELIB_TYPE(ABC);
-DECL_WINELIB_TYPE(LPABC);
+DECL_WINELIB_TYPE(ABC)
+DECL_WINELIB_TYPE(LPABC)
 
   /* Rasterizer status */
 typedef struct
@@ -1596,8 +1718,8 @@
     COLORREF lopnColor WINE_PACKED;
 } LOGPEN32, *LPLOGPEN32;
 
-DECL_WINELIB_TYPE(LOGPEN);
-DECL_WINELIB_TYPE(LPLOGPEN);
+DECL_WINELIB_TYPE(LOGPEN)
+DECL_WINELIB_TYPE(LPLOGPEN)
 
 #define PS_SOLID         0x00000000
 #define PS_DASH          0x00000001
@@ -2000,11 +2122,10 @@
     BYTE   pad0;
     WORD   key;
     WORD   cmd;
-    WORD   pad1;
 } ACCEL32, *LPACCEL32;
 
-DECL_WINELIB_TYPE(ACCEL);
-DECL_WINELIB_TYPE(LPACCEL);
+DECL_WINELIB_TYPE(ACCEL)
+DECL_WINELIB_TYPE(LPACCEL)
 
 /* modifiers for RegisterHotKey */
 #define	MOD_ALT		0x0001
@@ -2100,6 +2221,9 @@
     BOOL32  bInheritHandle;
 } SECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
 
+typedef DWORD   SECURITY_INFORMATION;
+
+
 /* 64 bit number of 100 nanoseconds intervals since January 1, 1601 */
 typedef struct
 {
@@ -2136,8 +2260,8 @@
     WCHAR     cAlternateFileName[14];
 } WIN32_FIND_DATA32W, *LPWIN32_FIND_DATA32W;
 
-DECL_WINELIB_TYPE_AW(WIN32_FIND_DATA);
-DECL_WINELIB_TYPE_AW(LPWIN32_FIND_DATA);
+DECL_WINELIB_TYPE_AW(WIN32_FIND_DATA)
+DECL_WINELIB_TYPE_AW(LPWIN32_FIND_DATA)
 
 #define INVALID_HANDLE_VALUE16  ((HANDLE16) -1)
 #define INVALID_HANDLE_VALUE32  ((HANDLE32) -1)
@@ -2302,8 +2426,8 @@
     char EvtChar;
 } DCB32, *LPDCB32;
 
-DECL_WINELIB_TYPE(DCB);
-DECL_WINELIB_TYPE(LPDCB);
+DECL_WINELIB_TYPE(DCB)
+DECL_WINELIB_TYPE(LPDCB)
 
 #define	RTS_CONTROL_DISABLE	0
 #define	RTS_CONTROL_ENABLE	1
@@ -3164,8 +3288,8 @@
   UINT32    cch;
 } MENUITEMINFO32W, *LPMENUITEMINFO32W;
 
-DECL_WINELIB_TYPE_AW(MENUITEMINFO);
-DECL_WINELIB_TYPE_AW(LPMENUITEMINFO);
+DECL_WINELIB_TYPE_AW(MENUITEMINFO)
+DECL_WINELIB_TYPE_AW(LPMENUITEMINFO)
 
 /* Field specifiers for MENUITEMINFO[AW] type.  */
 #define MIIM_STATE       0x00000001
@@ -3323,7 +3447,7 @@
 /* DrawState defines ... */
 typedef BOOL16 (CALLBACK *DRAWSTATEPROC16)(HDC16,LPARAM,WPARAM16,INT16,INT16);
 typedef BOOL32 (CALLBACK *DRAWSTATEPROC32)(HDC32,LPARAM,WPARAM32,INT32,INT32);
-DECL_WINELIB_TYPE(DRAWSTATEPROC);
+DECL_WINELIB_TYPE(DRAWSTATEPROC)
 
 /* Image type */
 #define	DST_COMPLEX	0x0000
@@ -4069,9 +4193,9 @@
     DWORD       itemData WINE_PACKED;
 } DRAWITEMSTRUCT32, *PDRAWITEMSTRUCT32, *LPDRAWITEMSTRUCT32;
 
-DECL_WINELIB_TYPE(DRAWITEMSTRUCT);
-DECL_WINELIB_TYPE(PDRAWITEMSTRUCT);
-DECL_WINELIB_TYPE(LPDRAWITEMSTRUCT);
+DECL_WINELIB_TYPE(DRAWITEMSTRUCT)
+DECL_WINELIB_TYPE(PDRAWITEMSTRUCT)
+DECL_WINELIB_TYPE(LPDRAWITEMSTRUCT)
 
 typedef struct
 {
@@ -4093,9 +4217,9 @@
     DWORD       itemData;
 } MEASUREITEMSTRUCT32, *PMEASUREITEMSTRUCT32, *LPMEASUREITEMSTRUCT32;
 
-DECL_WINELIB_TYPE(MEASUREITEMSTRUCT);
-DECL_WINELIB_TYPE(PMEASUREITEMSTRUCT);
-DECL_WINELIB_TYPE(LPMEASUREITEMSTRUCT);
+DECL_WINELIB_TYPE(MEASUREITEMSTRUCT)
+DECL_WINELIB_TYPE(PMEASUREITEMSTRUCT)
+DECL_WINELIB_TYPE(LPMEASUREITEMSTRUCT)
 
 typedef struct
 {
@@ -4115,8 +4239,8 @@
     DWORD      itemData;
 } DELETEITEMSTRUCT32, *LPDELETEITEMSTRUCT32;
 
-DECL_WINELIB_TYPE(DELETEITEMSTRUCT);
-DECL_WINELIB_TYPE(LPDELETEITEMSTRUCT);
+DECL_WINELIB_TYPE(DELETEITEMSTRUCT)
+DECL_WINELIB_TYPE(LPDELETEITEMSTRUCT)
 
 typedef struct
 {
@@ -4141,8 +4265,8 @@
     DWORD       dwLocaleId;
 } COMPAREITEMSTRUCT32, *LPCOMPAREITEMSTRUCT32;
 
-DECL_WINELIB_TYPE(COMPAREITEMSTRUCT);
-DECL_WINELIB_TYPE(LPCOMPAREITEMSTRUCT);
+DECL_WINELIB_TYPE(COMPAREITEMSTRUCT)
+DECL_WINELIB_TYPE(LPCOMPAREITEMSTRUCT)
 
 /* WM_KEYUP/DOWN/CHAR HIWORD(lParam) flags */
 #define KF_EXTENDED         0x0100
@@ -4431,8 +4555,8 @@
     HGDIOBJ32 objectHandle[1];
 } HANDLETABLE32, *LPHANDLETABLE32;
 
-DECL_WINELIB_TYPE(HANDLETABLE);
-DECL_WINELIB_TYPE(LPHANDLETABLE);
+DECL_WINELIB_TYPE(HANDLETABLE)
+DECL_WINELIB_TYPE(LPHANDLETABLE)
 
 /* Clipboard metafile picture structure */
 typedef struct
@@ -4451,8 +4575,8 @@
     HMETAFILE32  hMF;
 } METAFILEPICT32, *LPMETAFILEPICT32;
 
-DECL_WINELIB_TYPE(METAFILEPICT);
-DECL_WINELIB_TYPE(LPMETAFILEPICT);
+DECL_WINELIB_TYPE(METAFILEPICT)
+DECL_WINELIB_TYPE(LPMETAFILEPICT)
 
 /* Metafile functions */
 #define META_SETBKCOLOR              0x0201
@@ -4539,7 +4663,7 @@
                                        INT16,LPARAM);
 typedef INT32 (CALLBACK *MFENUMPROC32)(HDC32,HANDLETABLE32*,METARECORD*,
                                        INT32,LPARAM);
-DECL_WINELIB_TYPE(MFENUMPROC);
+DECL_WINELIB_TYPE(MFENUMPROC)
 
 /* enhanced metafile structures and functions */
 
@@ -4916,8 +5040,8 @@
         HANDLE32 hStdError;
 } STARTUPINFO32W, *LPSTARTUPINFO32W;
 
-DECL_WINELIB_TYPE_AW(STARTUPINFO);
-DECL_WINELIB_TYPE_AW(LPSTARTUPINFO);
+DECL_WINELIB_TYPE_AW(STARTUPINFO)
+DECL_WINELIB_TYPE_AW(LPSTARTUPINFO)
 
 typedef struct {
 	HANDLE32	hProcess;
@@ -5172,8 +5296,8 @@
     DWORD  dmReserved2;
 } DEVMODE32W, *LPDEVMODE32W;
 
-DECL_WINELIB_TYPE_AW(DEVMODE);
-DECL_WINELIB_TYPE_AW(LPDEVMODE);
+DECL_WINELIB_TYPE_AW(DEVMODE)
+DECL_WINELIB_TYPE_AW(LPDEVMODE)
 
 typedef struct _PRINTER_DEFAULTS32A {
     LPSTR        pDatatype;
@@ -5187,8 +5311,8 @@
     ACCESS_MASK  DesiredAccess;
 } PRINTER_DEFAULTS32W, *LPPRINTER_DEFAULTS32W;
 
-DECL_WINELIB_TYPE_AW(PRINTER_DEFAULTS);
-DECL_WINELIB_TYPE_AW(LPPRINTER_DEFAULTS);
+DECL_WINELIB_TYPE_AW(PRINTER_DEFAULTS)
+DECL_WINELIB_TYPE_AW(LPPRINTER_DEFAULTS)
 
 typedef struct _SYSTEM_POWER_STATUS
 {
@@ -5267,14 +5391,13 @@
     DWORD    Type;
 } MEMORY_BASIC_INFORMATION,*LPMEMORY_BASIC_INFORMATION;
 
-typedef DWORD (CALLBACK *LPTHREAD_START_ROUTINE)(LPVOID);
 
 typedef BOOL32 (CALLBACK *CODEPAGE_ENUMPROC32A)(LPSTR);
 typedef BOOL32 (CALLBACK *CODEPAGE_ENUMPROC32W)(LPWSTR);
-DECL_WINELIB_TYPE_AW(CODEPAGE_ENUMPROC);
+DECL_WINELIB_TYPE_AW(CODEPAGE_ENUMPROC)
 typedef BOOL32 (CALLBACK *LOCALE_ENUMPROC32A)(LPSTR);
 typedef BOOL32 (CALLBACK *LOCALE_ENUMPROC32W)(LPWSTR);
-DECL_WINELIB_TYPE_AW(LOCALE_ENUMPROC);
+DECL_WINELIB_TYPE_AW(LOCALE_ENUMPROC)
 
 typedef struct tagSYSTEM_INFO
 {
@@ -5313,7 +5436,7 @@
 /* service main function prototype */
 typedef VOID (CALLBACK *LPSERVICE_MAIN_FUNCTION32A)(DWORD,LPSTR);
 typedef VOID (CALLBACK *LPSERVICE_MAIN_FUNCTION32W)(DWORD,LPWSTR);
-DECL_WINELIB_TYPE_AW(LPSERVICE_MAIN_FUNCTION);
+DECL_WINELIB_TYPE_AW(LPSERVICE_MAIN_FUNCTION)
 
 /* service start table */
 typedef struct
@@ -5328,8 +5451,20 @@
     LPSERVICE_MAIN_FUNCTION32W	lpServiceProc;
 } *LPSERVICE_TABLE_ENTRY32W, SERVICE_TABLE_ENTRY32W;
 
-DECL_WINELIB_TYPE_AW(SERVICE_TABLE_ENTRY);
-DECL_WINELIB_TYPE_AW(LPSERVICE_TABLE_ENTRY);
+DECL_WINELIB_TYPE_AW(SERVICE_TABLE_ENTRY)
+DECL_WINELIB_TYPE_AW(LPSERVICE_TABLE_ENTRY)
+
+/* Used by: ControlService */
+typedef struct _SERVICE_STATUS {
+    DWORD dwServiceType;
+    DWORD dwCurrentState;
+    DWORD dwControlsAccepted;
+    DWORD dwWin32ExitCode;
+    DWORD dwServiceSpecificExitCode;
+    DWORD dwCheckPoint;
+    DWORD dwWaitHint;
+} SERVICE_STATUS, *LPSERVICE_STATUS;
+
 
 /* {G,S}etPriorityClass */
 #define	NORMAL_PRIORITY_CLASS	0x00000020
@@ -5440,9 +5575,9 @@
 typedef BOOL32 (CALLBACK *ENUMRESLANGPROC32A)(HMODULE32,LPCSTR,LPCSTR,WORD,LONG);
 typedef BOOL32 (CALLBACK *ENUMRESLANGPROC32W)(HMODULE32,LPCWSTR,LPCWSTR,WORD,LONG);
 
-DECL_WINELIB_TYPE_AW(ENUMRESTYPEPROC);
-DECL_WINELIB_TYPE_AW(ENUMRESNAMEPROC);
-DECL_WINELIB_TYPE_AW(ENUMRESLANGPROC);
+DECL_WINELIB_TYPE_AW(ENUMRESTYPEPROC)
+DECL_WINELIB_TYPE_AW(ENUMRESNAMEPROC)
+DECL_WINELIB_TYPE_AW(ENUMRESLANGPROC)
 
 /* Character Type Flags */
 #define	CT_CTYPE1		0x00000001	/* usual ctype */
@@ -5519,8 +5654,8 @@
     DWORD    fwType;
 } DOCINFO32W, *LPDOCINFO32W;
 
-DECL_WINELIB_TYPE_AW(DOCINFO);
-DECL_WINELIB_TYPE_AW(LPDOCINFO);
+DECL_WINELIB_TYPE_AW(DOCINFO)
+DECL_WINELIB_TYPE_AW(LPDOCINFO)
 
 typedef struct {
 	DWORD	dwScope;
@@ -5544,8 +5679,8 @@
 	LPWSTR	lpProvider;
 } NETRESOURCE32W,*LPNETRESOURCE32W;
 
-DECL_WINELIB_TYPE_AW(NETRESOURCE);
-DECL_WINELIB_TYPE_AW(LPNETRESOURCE);
+DECL_WINELIB_TYPE_AW(NETRESOURCE)
+DECL_WINELIB_TYPE_AW(LPNETRESOURCE)
 
 typedef struct {
 	DWORD	cbStructure;
@@ -5609,8 +5744,8 @@
 	LOGFONT32W	lfMessageFont;
 } NONCLIENTMETRICS32W,*LPNONCLIENTMETRICS32W;
 
-DECL_WINELIB_TYPE_AW(NONCLIENTMETRICS);
-DECL_WINELIB_TYPE_AW(LPNONCLIENTMETRICS);
+DECL_WINELIB_TYPE_AW(NONCLIENTMETRICS)
+DECL_WINELIB_TYPE_AW(LPNONCLIENTMETRICS)
 
 typedef struct tagANIMATIONINFO
 {
@@ -5731,8 +5866,8 @@
     DWORD	dwLanguageId;
 } MSGBOXPARAMS32W,*LPMSGBOXPARAMS32W;
 
-DECL_WINELIB_TYPE_AW(MSGBOXPARAMS);
-DECL_WINELIB_TYPE_AW(LPMSGBOXPARAMS);
+DECL_WINELIB_TYPE_AW(MSGBOXPARAMS)
+DECL_WINELIB_TYPE_AW(LPMSGBOXPARAMS)
 
 /* for WOWHandle{16,32} */
 typedef enum _WOW_HANDLE_TYPE { /* WOW */
@@ -5759,13 +5894,35 @@
 #define WCB16_PASCAL		0x0
 #define WCB16_CDECL		0x1
 
+typedef struct _numberfmt32a {
+    UINT32 NumDigits;
+    UINT32 LeadingZero;
+    UINT32 Grouping;
+    LPCSTR lpDecimalSep;
+    LPCSTR lpThousandSep;
+    UINT32 NegativeOrder;
+} NUMBERFMT32A;
+
+typedef struct _numberfmt32w {
+    UINT32 NumDigits;
+    UINT32 LeadingZero;
+    UINT32 Grouping;
+    LPCWSTR lpDecimalSep;
+    LPCWSTR lpThousandSep;
+    UINT32 NegativeOrder;
+} NUMBERFMT32W;
+
+
+
+
 #pragma pack(4)
 
 /* Declarations for functions that exist only in Win16 */
 
-#ifndef WINELIB
+#ifdef __WINE__
 WORD        WINAPI AllocCStoDSAlias(WORD);
 WORD        WINAPI AllocDStoCSAlias(WORD);
+HGLOBAL16   WINAPI AllocResource(HINSTANCE16,HRSRC16,DWORD);
 WORD        WINAPI AllocSelector(WORD);
 WORD        WINAPI AllocSelectorArray(WORD);
 VOID        WINAPI CalcChildScroll(HWND16,WORD);
@@ -5916,7 +6073,7 @@
 INT16       WINAPI WriteComm(INT16,LPSTR,INT16);
 VOID        WINAPI WriteOutProfiles(VOID);
 VOID        WINAPI hmemcpy(LPVOID,LPCVOID,LONG);
-#endif /* WINELIB */
+#endif  /* __WINE__ */
 
 /* Declarations for functions that exist only in Win32 */
 
@@ -5925,15 +6082,18 @@
 BOOL32      WINAPI Beep(DWORD,DWORD);
 BOOL32      WINAPI ClearCommError(INT32,LPDWORD,LPCOMSTAT);
 BOOL32      WINAPI CloseHandle(HANDLE32);
+BOOL32      WINAPI CloseServiceHandle(HANDLE32);
 INT32       WINAPI CopyAcceleratorTable32A(HACCEL32,LPACCEL32,INT32);
 INT32       WINAPI CopyAcceleratorTable32W(HACCEL32,LPACCEL32,INT32);
 #define     CopyAcceleratorTable WINELIB_NAME_AW(CopyAcceleratorTable)
 HENHMETAFILE32 WINAPI CopyEnhMetaFile32A(HENHMETAFILE32,LPCSTR);
+HENHMETAFILE32 WINAPI CopyEnhMetaFile32W(HENHMETAFILE32,LPCWSTR);
 #define     CopyEnhMetaFile WINELIB_NAME_AW(CopyEnhMetaFile)
 BOOL32      WINAPI CopyFile32A(LPCSTR,LPCSTR,BOOL32);
 BOOL32      WINAPI CopyFile32W(LPCWSTR,LPCWSTR,BOOL32);
 #define     CopyFile WINELIB_NAME_AW(CopyFile)
 INT32       WINAPI CompareFileTime(LPFILETIME,LPFILETIME);
+BOOL32      WINAPI ControlService(HANDLE32,DWORD,LPSERVICE_STATUS);
 HANDLE32    WINAPI CreateEvent32A(LPSECURITY_ATTRIBUTES,BOOL32,BOOL32,LPCSTR);
 HANDLE32    WINAPI CreateEvent32W(LPSECURITY_ATTRIBUTES,BOOL32,BOOL32,LPCWSTR);
 #define     CreateEvent WINELIB_NAME_AW(CreateEvent)
@@ -5957,6 +6117,8 @@
 #define     CreateSemaphore WINELIB_NAME_AW(CreateSemaphore)
 HANDLE32    WINAPI CreateThread(LPSECURITY_ATTRIBUTES,DWORD,LPTHREAD_START_ROUTINE,LPVOID,DWORD,LPDWORD);
 BOOL32      WINAPI DeleteEnhMetaFile(HENHMETAFILE32);
+BOOL32      WINAPI DeleteService(HANDLE32);
+BOOL32      WINAPI DeregisterEventSource(HANDLE32);
 BOOL32      WINAPI DestroyAcceleratorTable(HACCEL32);
 BOOL32      WINAPI DisableThreadLibraryCalls(HMODULE32);
 BOOL32      WINAPI DosDateTimeToFileTime(WORD,WORD,LPFILETIME);
@@ -5994,8 +6156,8 @@
 BOOL32      WINAPI FileTimeToDosDateTime(const FILETIME*,LPWORD,LPWORD);
 BOOL32      WINAPI FileTimeToLocalFileTime(const FILETIME*,LPFILETIME);
 BOOL32      WINAPI FileTimeToSystemTime(const FILETIME*,LPSYSTEMTIME);
-HRSRC32     WINAPI FindResourceEx32A(HINSTANCE32,LPCSTR,LPCSTR,WORD);
-HRSRC32     WINAPI FindResourceEx32W(HINSTANCE32,LPCWSTR,LPCWSTR,WORD);
+HRSRC32     WINAPI FindResourceEx32A(HMODULE32,LPCSTR,LPCSTR,WORD);
+HRSRC32     WINAPI FindResourceEx32W(HMODULE32,LPCWSTR,LPCWSTR,WORD);
 #define     FindResourceEx WINELIB_NAME_AW(FindResourceEx)
 BOOL32      WINAPI FlushConsoleInputBuffer(HANDLE32);
 BOOL32      WINAPI FlushFileBuffers(HFILE32);
@@ -6033,6 +6195,7 @@
 HENHMETAFILE32 WINAPI GetEnhMetaFile32A(LPCSTR);
 HENHMETAFILE32 WINAPI GetEnhMetaFile32W(LPCWSTR);
 #define     GetEnhMetaFile WINELIB_NAME_AW(GetEnhMetaFile)
+UINT32      WINAPI GetEnhMetaFileBits(HENHMETAFILE32,UINT32,LPBYTE);
 UINT32      WINAPI GetEnhMetaFileHeader(HENHMETAFILE32,UINT32,LPENHMETAHEADER);
 LPSTR       WINAPI GetEnvironmentStrings32A(void);
 LPWSTR      WINAPI GetEnvironmentStrings32W(void);
@@ -6055,6 +6218,7 @@
 BOOL32      WINAPI GetMenuItemInfo32A(HMENU32,UINT32,BOOL32,MENUITEMINFO32A*);
 BOOL32      WINAPI GetMenuItemInfo32W(HMENU32,UINT32,BOOL32,MENUITEMINFO32W*);
 #define     GetMenuItemInfo WINELIB_NAME_AW(GetMenuItemInfo)
+UINT32      WINAPI GetMetaFileBitsEx(HMETAFILE32,UINT32,LPVOID);
 BOOL32      WINAPI GetNumberOfConsoleInputEvents(HANDLE32,LPDWORD);
 BOOL32      WINAPI GetNumberOfConsoleMouseButtons(LPDWORD);
 DWORD       WINAPI GetObjectType(HANDLE32);
@@ -6112,6 +6276,9 @@
 BOOL32      WINAPI IsValidLocale(DWORD,DWORD);
 BOOL32      WINAPI LocalFileTimeToFileTime(const FILETIME*,LPFILETIME);
 BOOL32      WINAPI LockFile(HFILE32,DWORD,DWORD,DWORD,DWORD);
+BOOL32      WINAPI LookupPrivilegeValue32A(LPCSTR,LPCSTR,LPVOID);
+BOOL32      WINAPI LookupPrivilegeValue32W(LPCWSTR,LPCWSTR,LPVOID);
+#define     LookupPrivilegeValue WINELIB_NAME_AW(LookupPrivilegeValue)
 SEGPTR      WINAPI MapLS(LPVOID);
 LPVOID      WINAPI MapSL(SEGPTR);
 LPVOID      WINAPI MapViewOfFile(HANDLE32,DWORD,DWORD,DWORD,DWORD);
@@ -6138,9 +6305,16 @@
 HANDLE32    WINAPI OpenMutex32W(DWORD,BOOL32,LPCWSTR);
 #define     OpenMutex WINELIB_NAME_AW(OpenMutex)
 HANDLE32    WINAPI OpenProcess(DWORD,BOOL32,DWORD);
+BOOL32      WINAPI OpenProcessToken(HANDLE32,DWORD,HANDLE32*);
+HANDLE32    WINAPI OpenSCManager32A(LPCSTR,LPCSTR,DWORD);
+HANDLE32    WINAPI OpenSCManager32W(LPCWSTR,LPCWSTR,DWORD);
+#define     OpenSCManager WINELIB_NAME_AW(OpenSCManager)
 HANDLE32    WINAPI OpenSemaphore32A(DWORD,BOOL32,LPCSTR);
 HANDLE32    WINAPI OpenSemaphore32W(DWORD,BOOL32,LPCWSTR);
 #define     OpenSemaphore WINELIB_NAME_AW(OpenSemaphore)
+HANDLE32    WINAPI OpenService32A(HANDLE32,LPCSTR,DWORD);
+HANDLE32    WINAPI OpenService32W(HANDLE32,LPCWSTR,DWORD);
+#define     OpenService WINELIB_NAME_AW(OpenService)
 BOOL32      WINAPI PlayEnhMetaFile(HDC32,HENHMETAFILE32,const RECT32*);
 BOOL32      WINAPI PlayEnhMetaFileRecord(HDC32,LPHANDLETABLE32,const ENHMETARECORD*,UINT32);
 BOOL32      WINAPI PulseEvent(HANDLE32);
@@ -6162,6 +6336,10 @@
 DWORD       WINAPI RegEnumKeyEx32W(HKEY,DWORD,LPWSTR,LPDWORD,LPDWORD,LPWSTR,
                                    LPDWORD,LPFILETIME);
 #define     RegEnumKeyEx WINELIB_NAME_AW(RegEnumKeyEx)
+LONG        WINAPI RegGetKeySecurity(HKEY,SECURITY_INFORMATION,LPVOID,LPDWORD);
+HANDLE32    WINAPI RegisterEventSource32A(LPCSTR,LPCSTR);
+HANDLE32    WINAPI RegisterEventSource32W(LPCWSTR,LPCWSTR);
+#define     RegisterEventSource WINELIB_NAME_AW(RegisterEventSource)
 DWORD       WINAPI RegOpenKeyEx32W(HKEY,LPCWSTR,DWORD,REGSAM,LPHKEY);
 DWORD       WINAPI RegOpenKeyEx32A(HKEY,LPCSTR,DWORD,REGSAM,LPHKEY);
 #define     RegOpenKeyEx WINELIB_NAME_AW(RegOpenKeyEx)
@@ -6183,11 +6361,17 @@
 BOOL32      WINAPI SetBrushOrgEx(HDC32,INT32,INT32,LPPOINT32);
 BOOL32      WINAPI SetCommMask(INT32,DWORD);
 BOOL32      WINAPI SetCommTimeouts(INT32,LPCOMMTIMEOUTS);
+BOOL32      WINAPI SetComputerName32A(LPCSTR);
+BOOL32      WINAPI SetComputerName32W(LPCWSTR);
+#define     SetComputerName WINELIB_NAME_AW(SetComputerName)
+BOOL32      WINAPI SetConsoleCursorPosition(HANDLE32,COORD);
 BOOL32      WINAPI SetConsoleMode(HANDLE32,DWORD);
 BOOL32      WINAPI SetConsoleTitle32A(LPCSTR);
 BOOL32      WINAPI SetConsoleTitle32W(LPCWSTR);
 #define     SetConsoleTitle WINELIB_NAME_AW(SetConsoleTitle)
+VOID        WINAPI SetDebugErrorLevel(DWORD);
 BOOL32      WINAPI SetEndOfFile(HFILE32);
+HENHMETAFILE32 WINAPI SetEnhMetaFileBits(UINT32,const BYTE *);
 BOOL32      WINAPI SetEnvironmentVariable32A(LPCSTR,LPCSTR);
 BOOL32      WINAPI SetEnvironmentVariable32W(LPCWSTR,LPCWSTR);
 #define     SetEnvironmentVariable WINELIB_NAME_AW(SetEnvironmentVariable)
@@ -6213,6 +6397,9 @@
 BOOL32      WINAPI SetWindowContextHelpId(HWND32,DWORD);
 BOOL32      WINAPI SetWorldTransform(HDC32,const XFORM*);
 VOID        WINAPI Sleep(DWORD);
+BOOL32      WINAPI StartService32A(HANDLE32,DWORD,LPCSTR*);
+BOOL32      WINAPI StartService32W(HANDLE32,DWORD,LPCWSTR*);
+#define     StartService WINELIB_NAME_AW(StartService)
 BOOL32      WINAPI SystemTimeToFileTime(const SYSTEMTIME*,LPFILETIME);
 BOOL32      WINAPI TrackPopupMenuEx(HMENU32,UINT32,INT32,INT32,HWND32,
                                     LPTPMPARAMS);
@@ -6231,10 +6418,18 @@
 DWORD       WINAPI VirtualQuery(LPCVOID,LPMEMORY_BASIC_INFORMATION,DWORD);
 DWORD       WINAPI VirtualQueryEx(HANDLE32,LPCVOID,LPMEMORY_BASIC_INFORMATION,DWORD);
 BOOL32      WINAPI VirtualUnlock(LPVOID,DWORD);
+BOOL32      WINAPI WaitForDebugEvent(LPDEBUG_EVENT,DWORD);
+DWORD       WINAPI WaitForInputIdle(HANDLE32,DWORD);
 DWORD       WINAPI WaitForMultipleObjects(DWORD,const HANDLE32*,BOOL32,DWORD);
 DWORD       WINAPI WaitForMultipleObjectsEx(DWORD,const HANDLE32*,BOOL32,DWORD,BOOL32);
 DWORD       WINAPI WaitForSingleObject(HANDLE32,DWORD);
 DWORD       WINAPI WaitForSingleObjectEx(HANDLE32,DWORD,BOOL32);
+UINT32      WINAPI WNetAddConnection2_32A(LPNETRESOURCE32A,LPCSTR,LPCSTR,DWORD);
+UINT32      WINAPI WNetAddConnection2_32W(LPNETRESOURCE32W,LPCWSTR,LPCWSTR,DWORD);
+#define     WNetAddConnection2 WINELIB_NAME_AW(WNetAddConnection2_)
+UINT32      WINAPI WNetAddConnection3_32A(HWND32,LPNETRESOURCE32A,LPCSTR,LPCSTR,DWORD);
+UINT32      WINAPI WNetAddConnection3_32W(HWND32,LPNETRESOURCE32W,LPCWSTR,LPCWSTR,DWORD);
+#define     WNetAddConnection3 WINELIB_NAME_AW(WNetAddConnection3_)
 SEGPTR      WINAPI WOWGlobalAllocLock16(DWORD,DWORD,HGLOBAL16*);
 DWORD       WINAPI WOWCallback16(FARPROC16,DWORD);
 BOOL32      WINAPI WOWCallback16Ex(FARPROC16,DWORD,DWORD,LPVOID,LPDWORD);
@@ -6283,7 +6478,7 @@
 LRESULT     WINAPI AboutDlgProc32(HWND32,UINT32,WPARAM32,LPARAM);
 #define     AboutDlgProc WINELIB_NAME(AboutDlgProc)
 INT16       WINAPI AccessResource16(HINSTANCE16,HRSRC16);
-INT32       WINAPI AccessResource32(HINSTANCE32,HRSRC32);
+INT32       WINAPI AccessResource32(HMODULE32,HRSRC32);
 #define     AccessResource WINELIB_NAME(AccessResource)
 ATOM        WINAPI AddAtom16(SEGPTR);
 ATOM        WINAPI AddAtom32A(LPCSTR);
@@ -6299,9 +6494,6 @@
 BOOL16      WINAPI AdjustWindowRectEx16(LPRECT16,DWORD,BOOL16,DWORD);
 BOOL32      WINAPI AdjustWindowRectEx32(LPRECT32,DWORD,BOOL32,DWORD);
 #define     AdjustWindowRectEx WINELIB_NAME(AdjustWindowRectEx)
-HGLOBAL16   WINAPI AllocResource16(HINSTANCE16,HRSRC16,DWORD);
-HGLOBAL32   WINAPI AllocResource32(HINSTANCE32,HRSRC32,DWORD);
-#define     AllocResource WINELIB_NAME(AllocResource)
 void        WINAPI AnimatePalette16(HPALETTE16,UINT16,UINT16,LPPALETTEENTRY);
 BOOL32      WINAPI AnimatePalette32(HPALETTE32,UINT32,UINT32,LPPALETTEENTRY);
 #define     AnimatePalette WINELIB_NAME(AnimatePalette)
@@ -6435,6 +6627,7 @@
 HWND16      WINAPI ChildWindowFromPoint16(HWND16,POINT16);
 HWND32      WINAPI ChildWindowFromPoint32(HWND32,POINT32);
 #define     ChildWindowFromPoint WINELIB_NAME(ChildWindowFromPoint)
+INT32       ChoosePixelFormat(HDC32,PIXELFORMATDESCRIPTOR*);
 BOOL16      WINAPI Chord16(HDC16,INT16,INT16,INT16,INT16,INT16,INT16,INT16,INT16);
 BOOL32      WINAPI Chord32(HDC32,INT32,INT32,INT32,INT32,INT32,INT32,INT32,INT32);
 #define     Chord WINELIB_NAME(Chord)
@@ -6696,6 +6889,8 @@
 BOOL16      WINAPI DeleteObject16(HGDIOBJ16);
 BOOL32      WINAPI DeleteObject32(HGDIOBJ32);
 #define     DeleteObject WINELIB_NAME(DeleteObject)
+INT32       WINAPI DescribePixelFormat(HDC32,int,UINT32,
+                                       LPPIXELFORMATDESCRIPTOR);
 VOID        WINAPI DestroyCaret16(void);
 BOOL32      WINAPI DestroyCaret32(void);
 #define     DestroyCaret WINELIB_NAME(DestroyCaret)
@@ -6924,8 +7119,8 @@
 BOOL32      WINAPI FindNextFile32W(HANDLE32,LPWIN32_FIND_DATA32W);
 #define     FindNextFile WINELIB_NAME_AW(FindNextFile)
 HRSRC16     WINAPI FindResource16(HINSTANCE16,SEGPTR,SEGPTR);
-HRSRC32     WINAPI FindResource32A(HINSTANCE32,LPCSTR,LPCSTR);
-HRSRC32     WINAPI FindResource32W(HINSTANCE32,LPCWSTR,LPCWSTR);
+HRSRC32     WINAPI FindResource32A(HMODULE32,LPCSTR,LPCSTR);
+HRSRC32     WINAPI FindResource32W(HMODULE32,LPCWSTR,LPCWSTR);
 #define     FindResource WINELIB_NAME_AW(FindResource)
 HWND16      WINAPI FindWindow16(SEGPTR,LPCSTR);
 HWND32      WINAPI FindWindow32A(LPCSTR,LPCSTR);
@@ -7246,6 +7441,7 @@
 COLORREF    WINAPI GetPixel16(HDC16,INT16,INT16);
 COLORREF    WINAPI GetPixel32(HDC32,INT32,INT32);
 #define     GetPixel WINELIB_NAME(GetPixel)
+INT32       WINAPI GetPixelFormat(HDC32);
 INT16       WINAPI GetPolyFillMode16(HDC16);
 INT32       WINAPI GetPolyFillMode32(HDC32);
 #define     GetPolyFillMode WINELIB_NAME(GetPolyFillMode)
@@ -7682,7 +7878,7 @@
 DWORD       WINAPI LoadModule32(LPCSTR,LPVOID);
 #define     LoadModule WINELIB_NAME(LoadModule)
 HGLOBAL16   WINAPI LoadResource16(HINSTANCE16,HRSRC16);
-HGLOBAL32   WINAPI LoadResource32(HINSTANCE32,HRSRC32);
+HGLOBAL32   WINAPI LoadResource32(HMODULE32,HRSRC32);
 #define     LoadResource WINELIB_NAME(LoadResource)
 INT16       WINAPI LoadString16(HINSTANCE16,UINT16,LPSTR,INT16);
 INT32       WINAPI LoadString32A(HINSTANCE32,UINT32,LPSTR,INT32);
@@ -7852,6 +8048,9 @@
 VOID        WINAPI PlayMetaFileRecord16(HDC16,LPHANDLETABLE16,LPMETARECORD,UINT16);
 BOOL32      WINAPI PlayMetaFileRecord32(HDC32,LPHANDLETABLE32,LPMETARECORD,UINT32);
 #define     PlayMetaFileRecord WINELIB_NAME(PlayMetaFileRecord)
+BOOL16      WINAPI PolyBezier16(HDC16,LPPOINT16,INT16);
+BOOL32      WINAPI PolyBezier32(HDC32,LPPOINT32,DWORD);
+#define     PolyBezier WINELIB_NAME(PolyBezier)
 BOOL16      WINAPI PolyPolygon16(HDC16,LPPOINT16,LPINT16,UINT16);
 BOOL32      WINAPI PolyPolygon32(HDC32,LPPOINT32,LPINT32,UINT32);
 #define     PolyPolygon WINELIB_NAME(PolyPolygon)
@@ -8166,6 +8365,7 @@
 COLORREF    WINAPI SetPixel16(HDC16,INT16,INT16,COLORREF);
 COLORREF    WINAPI SetPixel32(HDC32,INT32,INT32,COLORREF);
 #define     SetPixel WINELIB_NAME(SetPixel)
+BOOL32      WINAPI SetPixelFormat(HDC32,int,PIXELFORMATDESCRIPTOR*);
 INT16       WINAPI SetPolyFillMode16(HDC16,INT16);
 INT32       WINAPI SetPolyFillMode32(HDC32,INT32);
 #define     SetPolyFillMode WINELIB_NAME(SetPolyFillMode)
@@ -8340,6 +8540,7 @@
 BOOL16      WINAPI SubtractRect16(LPRECT16,const RECT16*,const RECT16*);
 BOOL32      WINAPI SubtractRect32(LPRECT32,const RECT32*,const RECT32*);
 #define     SubtractRect WINELIB_NAME(SubtractRect)
+BOOL32      WINAPI SwapBuffers(HDC32);
 BOOL16      WINAPI SwapMouseButton16(BOOL16);
 BOOL32      WINAPI SwapMouseButton32(BOOL32);
 #define     SwapMouseButton WINELIB_NAME(SwapMouseButton)
@@ -8485,6 +8686,10 @@
 BOOL32      WINAPI WinHelp32A(HWND32,LPCSTR,UINT32,DWORD);
 BOOL32      WINAPI WinHelp32W(HWND32,LPCWSTR,UINT32,DWORD);
 #define     WinHelp WINELIB_NAME_AW(WinHelp)
+UINT16      WNetAddConnection16(LPSTR,LPSTR,LPSTR);
+UINT32      WNetAddConnection32A(LPSTR,LPSTR,LPSTR);
+UINT32      WNetAddConnection32W(LPWSTR,LPWSTR,LPWSTR);
+#define     WNetAddConnection WINELIB_NAME_AW(WNetAddConnection)
 INT16       WINAPIV wsnprintf16(LPSTR,UINT16,LPCSTR,...);
 INT32       WINAPIV wsnprintf32A(LPSTR,UINT32,LPCSTR,...);
 INT32       WINAPIV wsnprintf32W(LPWSTR,UINT32,LPCWSTR,...);
@@ -8530,8 +8735,8 @@
 
 HPEN16      WINAPI GetSysColorPen16(INT16);
 HPEN32      WINAPI GetSysColorPen32(INT32);
-INT32       WINAPI LoadMessage32A(HINSTANCE32,UINT32,WORD,LPSTR,INT32);
-INT32       WINAPI LoadMessage32W(HINSTANCE32,UINT32,WORD,LPWSTR,INT32);
+INT32       WINAPI LoadMessage32A(HMODULE32,UINT32,WORD,LPSTR,INT32);
+INT32       WINAPI LoadMessage32W(HMODULE32,UINT32,WORD,LPWSTR,INT32);
 SEGPTR      WINAPI WIN16_GlobalLock16(HGLOBAL16);
 SEGPTR      WINAPI WIN16_LockResource(HGLOBAL16);
 LONG        WINAPI WIN16_hread(HFILE16,SEGPTR,LONG);
diff --git a/include/winnls.h b/include/winnls.h
index d09bc96..af6d7de 100644
--- a/include/winnls.h
+++ b/include/winnls.h
@@ -5,6 +5,8 @@
 #define	LOCALE_NOUSEROVERRIDE	    0x80000000
 #define	LOCALE_USE_CP_ACP	    0x40000000
 
+#define LOCALE_LOCALEINFOFLAGSMASK  0xC0000000
+
 /* When adding new defines, don't forget to add an entry to the
  * locale2id map in misc/ole2nls.c
  */
@@ -205,6 +207,14 @@
 #define DATE_LONGDATE          0x00000002  /* use long date picture */
 #define DATE_USE_ALT_CALENDAR  0x00000004  /* use alternate calendar */
                           /* alt. calendar support is broken anyway */
+#define TIME_NOSECONDS         0x00000002  /* show no seconds */
+#define TIME_NOMINUTESORSECONDS 0x0000001  /* show no minutes either */
+
+/* internal flags for GetDateFormat system */
+#define DATE_DATEVARSONLY      0x00000100  /* only date stuff: yMdg */
+#define TIME_TIMEVARSONLY      0x00000200  /* only time stuff: hHmst */
+/* use this in a WineLib program if you really want all types */
+#define LOCALE_TIMEDATEBOTH    0x00000300  /* full set */
 
 
 #endif  /* __WINE_WINNLS_H */
diff --git a/include/wintypes.h b/include/wintypes.h
index 3586b4a..655f7b2 100644
--- a/include/wintypes.h
+++ b/include/wintypes.h
@@ -9,38 +9,31 @@
 
 #ifdef __WINE__
 # include "config.h"
-# undef WINELIB
 # undef UNICODE
-#else  /* __WINE__ */
-# ifndef WINELIB
-#  define WINELIB
-# endif
 #endif  /* __WINE__ */
 
 /* Macros to map Winelib names to the correct implementation name */
-/* depending on WINELIB and UNICODE macros.                       */
-/* Note that WINELIB is purely Win32.                             */
+/* depending on __WINE__ and UNICODE macros.                      */
+/* Note that Winelib is purely Win32.                             */
 
 #ifdef __WINE__
 # define WINELIB_NAME(func)      this is a syntax error
 # define WINELIB_NAME_AW(func)   this is a syntax error
 #else  /* __WINE__ */
-# ifdef WINELIB
-#  define WINELIB_NAME(func)     func##32
-#  ifdef UNICODE
-#   define WINELIB_NAME_AW(func) func##32W
-#  else
-#   define WINELIB_NAME_AW(func) func##32A
-#  endif  /* UNICODE */
-# endif  /* WINELIB */
+# define WINELIB_NAME(func)     func##32
+# ifdef UNICODE
+#  define WINELIB_NAME_AW(func) func##32W
+# else
+#  define WINELIB_NAME_AW(func) func##32A
+# endif  /* UNICODE */
 #endif  /* __WINE__ */
 
 #ifdef __WINE__
 # define DECL_WINELIB_TYPE(type)     /* nothing */
 # define DECL_WINELIB_TYPE_AW(type)  /* nothing */
 #else   /* __WINE__ */
-# define DECL_WINELIB_TYPE(type)     typedef WINELIB_NAME(type) type
-# define DECL_WINELIB_TYPE_AW(type)  typedef WINELIB_NAME_AW(type) type
+# define DECL_WINELIB_TYPE(type)     typedef WINELIB_NAME(type) type;
+# define DECL_WINELIB_TYPE_AW(type)  typedef WINELIB_NAME_AW(type) type;
 #endif  /* __WINE__ */
 
 
@@ -180,105 +173,105 @@
 
 typedef LRESULT (CALLBACK *DLGPROC16)(HWND16,UINT16,WPARAM16,LPARAM);
 typedef LRESULT (CALLBACK *DLGPROC32)(HWND32,UINT32,WPARAM32,LPARAM);
-DECL_WINELIB_TYPE(DLGPROC);
+DECL_WINELIB_TYPE(DLGPROC)
 typedef LRESULT (CALLBACK *DRIVERPROC16)(DWORD,HDRVR16,UINT16,LPARAM,LPARAM);
 typedef LRESULT (CALLBACK *DRIVERPROC32)(DWORD,HDRVR32,UINT32,LPARAM,LPARAM);
-DECL_WINELIB_TYPE(DRIVERPROC);
+DECL_WINELIB_TYPE(DRIVERPROC)
 typedef INT16   (CALLBACK *EDITWORDBREAKPROC16)(LPSTR,INT16,INT16,INT16);
 typedef INT32   (CALLBACK *EDITWORDBREAKPROC32A)(LPSTR,INT32,INT32,INT32);
 typedef INT32   (CALLBACK *EDITWORDBREAKPROC32W)(LPWSTR,INT32,INT32,INT32);
-DECL_WINELIB_TYPE_AW(EDITWORDBREAKPROC);
+DECL_WINELIB_TYPE_AW(EDITWORDBREAKPROC)
 typedef LRESULT (CALLBACK *FARPROC16)();
 typedef LRESULT (CALLBACK *FARPROC32)();
-DECL_WINELIB_TYPE(FARPROC);
+DECL_WINELIB_TYPE(FARPROC)
 typedef INT16   (CALLBACK *GOBJENUMPROC16)(SEGPTR,LPARAM);
 typedef INT32   (CALLBACK *GOBJENUMPROC32)(LPVOID,LPARAM);
-DECL_WINELIB_TYPE(GOBJENUMPROC);
+DECL_WINELIB_TYPE(GOBJENUMPROC)
 typedef BOOL16  (CALLBACK *GRAYSTRINGPROC16)(HDC16,LPARAM,INT16);
 typedef BOOL32  (CALLBACK *GRAYSTRINGPROC32)(HDC32,LPARAM,INT32);
-DECL_WINELIB_TYPE(GRAYSTRINGPROC);
+DECL_WINELIB_TYPE(GRAYSTRINGPROC)
 typedef LRESULT (CALLBACK *HOOKPROC16)(INT16,WPARAM16,LPARAM);
 typedef LRESULT (CALLBACK *HOOKPROC32)(INT32,WPARAM32,LPARAM);
-DECL_WINELIB_TYPE(HOOKPROC);
+DECL_WINELIB_TYPE(HOOKPROC)
 typedef VOID    (CALLBACK *LINEDDAPROC16)(INT16,INT16,LPARAM);
 typedef VOID    (CALLBACK *LINEDDAPROC32)(INT32,INT32,LPARAM);
-DECL_WINELIB_TYPE(LINEDDAPROC);
+DECL_WINELIB_TYPE(LINEDDAPROC)
 typedef BOOL16  (CALLBACK *PROPENUMPROC16)(HWND16,SEGPTR,HANDLE16);
 typedef BOOL32  (CALLBACK *PROPENUMPROC32A)(HWND32,LPCSTR,HANDLE32);
 typedef BOOL32  (CALLBACK *PROPENUMPROC32W)(HWND32,LPCWSTR,HANDLE32);
-DECL_WINELIB_TYPE_AW(PROPENUMPROC);
+DECL_WINELIB_TYPE_AW(PROPENUMPROC)
 typedef BOOL32  (CALLBACK *PROPENUMPROCEX32A)(HWND32,LPCSTR,HANDLE32,LPARAM);
 typedef BOOL32  (CALLBACK *PROPENUMPROCEX32W)(HWND32,LPCWSTR,HANDLE32,LPARAM);
-DECL_WINELIB_TYPE_AW(PROPENUMPROCEX);
+DECL_WINELIB_TYPE_AW(PROPENUMPROCEX)
 typedef VOID    (CALLBACK *TIMERPROC16)(HWND16,UINT16,UINT16,DWORD);
 typedef VOID    (CALLBACK *TIMERPROC32)(HWND32,UINT32,UINT32,DWORD);
-DECL_WINELIB_TYPE(TIMERPROC);
+DECL_WINELIB_TYPE(TIMERPROC)
 typedef LRESULT (CALLBACK *WNDENUMPROC16)(HWND16,LPARAM);
 typedef LRESULT (CALLBACK *WNDENUMPROC32)(HWND32,LPARAM);
-DECL_WINELIB_TYPE(WNDENUMPROC);
+DECL_WINELIB_TYPE(WNDENUMPROC)
 typedef LRESULT (CALLBACK *WNDPROC16)(HWND16,UINT16,WPARAM16,LPARAM);
 typedef LRESULT (CALLBACK *WNDPROC32)(HWND32,UINT32,WPARAM32,LPARAM);
-DECL_WINELIB_TYPE(WNDPROC);
+DECL_WINELIB_TYPE(WNDPROC)
 
 /* TCHAR data types definitions for Winelib. */
 /* These types are _not_ defined for the emulator, because they */
 /* depend on the UNICODE macro that only exists in user's code. */
 
 #ifndef __WINE__
-# if defined(WINELIB32) && defined(UNICODE)
+# ifdef UNICODE
 typedef WCHAR TCHAR;
 typedef LPWSTR LPTSTR;
 typedef LPCWSTR LPCTSTR;
-# else  /* WINELIB32 && UNICODE */
+# else  /* UNICODE */
 typedef CHAR TCHAR;
 typedef LPSTR LPTSTR;
 typedef LPCSTR LPCTSTR;
-# endif /* WINELIB32 && UNICODE */
+# endif /* UNICODE */
 #endif   /* __WINE__ */
 
 /* Data types specific to the library. These do _not_ exist in the emulator. */
 
-DECL_WINELIB_TYPE(INT);
-DECL_WINELIB_TYPE(LPINT);
-DECL_WINELIB_TYPE(LPUINT);
-DECL_WINELIB_TYPE(UINT);
-DECL_WINELIB_TYPE(BOOL);
-DECL_WINELIB_TYPE(WPARAM);
+DECL_WINELIB_TYPE(INT)
+DECL_WINELIB_TYPE(LPINT)
+DECL_WINELIB_TYPE(LPUINT)
+DECL_WINELIB_TYPE(UINT)
+DECL_WINELIB_TYPE(BOOL)
+DECL_WINELIB_TYPE(WPARAM)
 
-DECL_WINELIB_TYPE(HACCEL);
-DECL_WINELIB_TYPE(HANDLE);
-DECL_WINELIB_TYPE(HBITMAP);
-DECL_WINELIB_TYPE(HBRUSH);
-DECL_WINELIB_TYPE(HCURSOR);
-DECL_WINELIB_TYPE(HDC);
-DECL_WINELIB_TYPE(HDROP);
-DECL_WINELIB_TYPE(HDRVR);
-DECL_WINELIB_TYPE(HDWP);
-DECL_WINELIB_TYPE(HENHMETAFILE);
-DECL_WINELIB_TYPE(HFILE);
-DECL_WINELIB_TYPE(HFONT);
-DECL_WINELIB_TYPE(HGDIOBJ);
-DECL_WINELIB_TYPE(HGLOBAL);
-DECL_WINELIB_TYPE(HICON);
-DECL_WINELIB_TYPE(HINSTANCE);
-DECL_WINELIB_TYPE(HLOCAL);
-DECL_WINELIB_TYPE(HMENU);
-DECL_WINELIB_TYPE(HMETAFILE);
-DECL_WINELIB_TYPE(HMIDI);
-DECL_WINELIB_TYPE(HMIDIIN);
-DECL_WINELIB_TYPE(HMIDIOUT);
-DECL_WINELIB_TYPE(HMMIO);
-DECL_WINELIB_TYPE(HMODULE);
-DECL_WINELIB_TYPE(HPALETTE);
-DECL_WINELIB_TYPE(HPEN);
-DECL_WINELIB_TYPE(HQUEUE);
-DECL_WINELIB_TYPE(HRGN);
-DECL_WINELIB_TYPE(HRSRC);
-DECL_WINELIB_TYPE(HTASK);
-DECL_WINELIB_TYPE(HWAVE);
-DECL_WINELIB_TYPE(HWAVEIN);
-DECL_WINELIB_TYPE(HWAVEOUT);
-DECL_WINELIB_TYPE(HWND);
+DECL_WINELIB_TYPE(HACCEL)
+DECL_WINELIB_TYPE(HANDLE)
+DECL_WINELIB_TYPE(HBITMAP)
+DECL_WINELIB_TYPE(HBRUSH)
+DECL_WINELIB_TYPE(HCURSOR)
+DECL_WINELIB_TYPE(HDC)
+DECL_WINELIB_TYPE(HDROP)
+DECL_WINELIB_TYPE(HDRVR)
+DECL_WINELIB_TYPE(HDWP)
+DECL_WINELIB_TYPE(HENHMETAFILE)
+DECL_WINELIB_TYPE(HFILE)
+DECL_WINELIB_TYPE(HFONT)
+DECL_WINELIB_TYPE(HGDIOBJ)
+DECL_WINELIB_TYPE(HGLOBAL)
+DECL_WINELIB_TYPE(HICON)
+DECL_WINELIB_TYPE(HINSTANCE)
+DECL_WINELIB_TYPE(HLOCAL)
+DECL_WINELIB_TYPE(HMENU)
+DECL_WINELIB_TYPE(HMETAFILE)
+DECL_WINELIB_TYPE(HMIDI)
+DECL_WINELIB_TYPE(HMIDIIN)
+DECL_WINELIB_TYPE(HMIDIOUT)
+DECL_WINELIB_TYPE(HMMIO)
+DECL_WINELIB_TYPE(HMODULE)
+DECL_WINELIB_TYPE(HPALETTE)
+DECL_WINELIB_TYPE(HPEN)
+DECL_WINELIB_TYPE(HQUEUE)
+DECL_WINELIB_TYPE(HRGN)
+DECL_WINELIB_TYPE(HRSRC)
+DECL_WINELIB_TYPE(HTASK)
+DECL_WINELIB_TYPE(HWAVE)
+DECL_WINELIB_TYPE(HWAVEIN)
+DECL_WINELIB_TYPE(HWAVEOUT)
+DECL_WINELIB_TYPE(HWND)
 
 /* Misc. constants. */
 
diff --git a/include/x11drv.h b/include/x11drv.h
index cddfaab..78d911d 100644
--- a/include/x11drv.h
+++ b/include/x11drv.h
@@ -94,6 +94,8 @@
 extern BOOL32 X11DRV_Polygon( struct tagDC *dc, LPPOINT32 pt, INT32 count );
 extern BOOL32 X11DRV_PolyPolygon( struct tagDC *dc, LPPOINT32 pt,
 				  LPINT32 counts, UINT32 polygons);
+extern BOOL32 X11DRV_PolyPolyline( struct tagDC *dc, LPPOINT32 pt,
+				  LPINT32 counts, UINT32 polylines);
 
 extern HGDIOBJ32 X11DRV_SelectObject( struct tagDC *dc, HGDIOBJ32 handle );
 
diff --git a/loader/Makefile.in b/loader/Makefile.in
index 549c3c1..7f0ae30 100644
--- a/loader/Makefile.in
+++ b/loader/Makefile.in
@@ -9,8 +9,6 @@
 	libres.c \
 	main.c \
 	module.c \
-	ne_image.c \
-	ne_resource.c \
 	pe_image.c \
 	pe_resource.c \
 	resource.c \
diff --git a/loader/libres.c b/loader/libres.c
index cc5bd3a..5dafc8f 100644
--- a/loader/libres.c
+++ b/loader/libres.c
@@ -6,6 +6,7 @@
 
 #include <stdio.h>
 #include <stdlib.h>
+#include "debug.h"
 #include "libres.h"
 #include "heap.h"
 #include "windows.h"
@@ -31,57 +32,9 @@
 }
 
 /**********************************************************************
- *	    LIBRES_FindResource16    
+ *	    LIBRES_FindResource
  */
-HRSRC32 LIBRES_FindResource16( HINSTANCE32 hModule, LPCSTR name, LPCSTR type )
-{
-  int nameid=0,typeid;
-  ResListE* ResBlock;
-  const struct resource* const * Res;
-
-  if(HIWORD(name))
-  {
-    if(*name=='#')
-    {
-      nameid=atoi(name+1);
-      name=NULL;
-    }
-  }
-  else
-  {
-    nameid=LOWORD(name);
-    name=NULL;
-  }
-  if(HIWORD(type))
-  {
-    if(*type=='#')
-      typeid=atoi(type+1);
-    else
-    {
-      fprintf(stderr,"LIBRES_FindResource16(*,*,type=string)");
-      return 0;
-    }
-  }
-  else
-    typeid=LOWORD(type);
-  
-  for(ResBlock=ResourceList; ResBlock; ResBlock=ResBlock->next)
-    for(Res=ResBlock->Resources; *Res; Res++)
-      if(name)
-      {
-	if((*Res)->type==typeid && !lstrcmpi32A((*Res)->name,name))
-	  return (HRSRC32)*Res;
-      }
-      else
-	if((*Res)->type==typeid && (*Res)->id==nameid)
-	  return (HRSRC32)*Res;
-  return 0;
-}
-
-/**********************************************************************
- *	    LIBRES_FindResource32    
- */
-HRSRC32 LIBRES_FindResource32( HINSTANCE32 hModule, LPCWSTR name, LPCWSTR type )
+HRSRC32 LIBRES_FindResource( HINSTANCE32 hModule, LPCWSTR name, LPCWSTR type )
 {
   int nameid=0,typeid;
   ResListE* ResBlock;
@@ -112,7 +65,7 @@
     }
     else
     {
-      fprintf(stderr,"LIBRES_FindResource32(*,*,type=string)");
+      TRACE(resource, "(*,*,type=string): Returning 0\n");
       return 0;
     }
   }
@@ -143,48 +96,9 @@
 
 
 /**********************************************************************
- *	    LIBRES_LockResource    
- */
-LPVOID LIBRES_LockResource( HGLOBAL32 handle )
-{
-  return (LPVOID)handle;
-}
-
-
-/**********************************************************************
- *	    LIBRES_FreeResource    
- */
-BOOL32 LIBRES_FreeResource( HGLOBAL32 handle )
-{
-  return 0; /* Obsolete in Win32 */
-}
-
-
-/**********************************************************************
- *	    LIBRES_AccessResource    
- */
-INT32 LIBRES_AccessResource( HINSTANCE32 hModule, HRSRC32 hRsrc )
-{
-  fprintf(stderr,"LIBRES_AccessResource()");
-  return -1; /* Obsolete in Win32 */
-}
-
-
-/**********************************************************************
  *	    LIBRES_SizeofResource    
  */
 DWORD LIBRES_SizeofResource( HINSTANCE32 hModule, HRSRC32 hRsrc )
 {
   return (DWORD)(((struct resource*)hRsrc)->size);
 }
-
-
-/**********************************************************************
- *	    LIBRES_AllocResource    
- */
-HGLOBAL32 LIBRES_AllocResource( HINSTANCE32 hModule, HRSRC32 hRsrc, DWORD size)
-{
-  fprintf(stderr,"LIBRES_AllocResource()");
-  return 0; /* Obsolete in Win32 */
-}
-
diff --git a/loader/module.c b/loader/module.c
index 1e1db94..63568ee 100644
--- a/loader/module.c
+++ b/loader/module.c
@@ -31,23 +31,48 @@
 
 extern BOOL32 THREAD_InitDone;
 
-static HMODULE16 hFirstModule = 0;
+extern HMODULE16 hFirstModule;  /* FIXME */
 static HMODULE16 hCachedModule = 0;  /* Module cached by MODULE_OpenFile */
 
 static HMODULE32 MODULE_LoadModule(LPCSTR name,BOOL32 force) { return 0; }
 HMODULE32 (*fnBUILTIN_LoadModule)(LPCSTR name,BOOL32 force) = MODULE_LoadModule;
 
 
-/***********************************************************************
- *           MODULE_GetPtr
+/*************************************************************************
+ *		MODULE32_LookupHMODULE
+ * looks for the referenced HMODULE in the current process
  */
-NE_MODULE *MODULE_GetPtr( HMODULE32 hModule )
-{
-    HMODULE16 hnd =MODULE_HANDLEtoHMODULE16(hModule);
+WINE_MODREF*
+MODULE32_LookupHMODULE(PDB32 *process,HMODULE32 hmod) {
+    WINE_MODREF	*wm;
 
-    if (!hnd)
-    	return NULL;
-    return (NE_MODULE*)GlobalLock16(hnd);
+    if (!hmod) 
+    	return process->exe_modref;
+    if (!HIWORD(hmod)) {
+    	ERR(module,"tried to lookup 0x%04x in win32 module handler!\n",hmod);
+	return NULL;
+    }
+    for (wm = process->modref_list;wm;wm=wm->next)
+	if (wm->module == hmod)
+	    return wm;
+    return NULL;
+}
+
+/***********************************************************************
+ *           MODULE_GetPtr16
+ */
+NE_MODULE *MODULE_GetPtr16( HMODULE16 hModule )
+{
+    return (NE_MODULE*)GlobalLock16( GetExePtr(hModule) );
+}
+
+
+/***********************************************************************
+ *           MODULE_GetPtr32
+ */
+NE_MODULE *MODULE_GetPtr32( HMODULE32 hModule )
+{
+    return (NE_MODULE*)GlobalLock16( MODULE_HANDLEtoHMODULE16(hModule) );
 }
 
 /***********************************************************************
@@ -59,6 +84,7 @@
 
     if (HIWORD(handle))
     {
+        WARN(module,"looking up 0x%08x in win16 function!\n",handle);
 	/* this is a HMODULE32 */
 
         /* walk the list looking for the correct startaddress */
@@ -74,192 +100,6 @@
 }
 
 /***********************************************************************
- *           MODULE_HANDLEtoHMODULE32
- * return HMODULE32, if possible, HMODULE16 otherwise
- */
-HMODULE32
-MODULE_HANDLEtoHMODULE32(HANDLE32 handle) {
-    NE_MODULE *pModule;
-
-    if (HIWORD(handle))
-    	return (HMODULE32)handle;
-    else {
-    	handle = GetExePtr(handle);
-	if (!handle)
-	    return 0;
-    	pModule = (NE_MODULE *)GlobalLock16( handle );
-	if (!pModule)
-	    return 0;
-	
-	if (pModule->module32) return pModule->module32;
-	return handle;
-    }
-}
-
-/***********************************************************************
- *           MODULE_DumpModule
- */
-void MODULE_DumpModule( HMODULE32 hModule )
-{
-    int i, ordinal;
-    SEGTABLEENTRY *pSeg;
-    BYTE *pstr;
-    WORD *pword;
-    NE_MODULE *pModule;
-
-    if (!(pModule = MODULE_GetPtr( hModule )))
-    {
-        fprintf( stderr, "**** %04x is not a module handle\n", hModule );
-        return;
-    }
-
-      /* Dump the module info */
-    DUMP( "---\n" );
-    DUMP( "Module %04x:\n", hModule );
-    DUMP( "count=%d flags=%04x heap=%d stack=%d\n",
-	  pModule->count, pModule->flags,
-	  pModule->heap_size, pModule->stack_size );
-    DUMP( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
-	  pModule->cs, pModule->ip, pModule->ss, pModule->sp, pModule->dgroup,
-	  pModule->seg_count, pModule->modref_count );
-    DUMP( "os_flags=%d swap_area=%d version=%04x\n",
-	  pModule->os_flags, pModule->min_swap_area,
-	  pModule->expected_version );
-    if (pModule->flags & NE_FFLAGS_WIN32)
-        DUMP( "PE module=%08x\n", pModule->module32 );
-
-      /* Dump the file info */
-    DUMP( "---\n" );
-    DUMP( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
-
-      /* Dump the segment table */
-    DUMP( "---\n" );
-    DUMP( "Segment table:\n" );
-    pSeg = NE_SEG_TABLE( pModule );
-    for (i = 0; i < pModule->seg_count; i++, pSeg++)
-        DUMP( "%02x: pos=%d size=%d flags=%04x minsize=%d sel=%04x\n",
-	      i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
-	      pSeg->minsize, pSeg->selector );
-
-      /* Dump the resource table */
-    DUMP( "---\n" );
-    DUMP( "Resource table:\n" );
-    if (pModule->res_table)
-    {
-        pword = (WORD *)((BYTE *)pModule + pModule->res_table);
-        DUMP( "Alignment: %d\n", *pword++ );
-        while (*pword)
-        {
-            struct resource_typeinfo_s *ptr = (struct resource_typeinfo_s *)pword;
-            struct resource_nameinfo_s *pname = (struct resource_nameinfo_s *)(ptr + 1);
-            DUMP( "id=%04x count=%d\n", ptr->type_id, ptr->count );
-            for (i = 0; i < ptr->count; i++, pname++)
-                DUMP( "offset=%d len=%d id=%04x\n",
-		      pname->offset, pname->length, pname->id );
-            pword = (WORD *)pname;
-        }
-    }
-    else DUMP( "None\n" );
-
-      /* Dump the resident name table */
-    DUMP( "---\n" );
-    DUMP( "Resident-name table:\n" );
-    pstr = (char *)pModule + pModule->name_table;
-    while (*pstr)
-    {
-        DUMP( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
-	      *(WORD *)(pstr + *pstr + 1) );
-        pstr += *pstr + 1 + sizeof(WORD);
-    }
-
-      /* Dump the module reference table */
-    DUMP( "---\n" );
-    DUMP( "Module ref table:\n" );
-    if (pModule->modref_table)
-    {
-        pword = (WORD *)((BYTE *)pModule + pModule->modref_table);
-        for (i = 0; i < pModule->modref_count; i++, pword++)
-        {
-	    DUMP( "%d: %04x -> '%s'\n", i, *pword,
-		    MODULE_GetModuleName(*pword));
-        }
-    }
-    else DUMP( "None\n" );
-
-      /* Dump the entry table */
-    DUMP( "---\n" );
-    DUMP( "Entry table:\n" );
-    pstr = (char *)pModule + pModule->entry_table;
-    ordinal = 1;
-    while (*pstr)
-    {
-        DUMP( "Bundle %d-%d: %02x\n", ordinal, ordinal + *pstr - 1, pstr[1]);
-        if (!pstr[1])
-        {
-            ordinal += *pstr;
-            pstr += 2;
-        }
-        else if ((BYTE)pstr[1] == 0xff)  /* moveable */
-        {
-            struct entry_tab_movable_s *pe = (struct entry_tab_movable_s*)(pstr+2);
-            for (i = 0; i < *pstr; i++, pe++)
-                DUMP( "%d: %02x:%04x (moveable)\n",
-		      ordinal++, pe->seg_number, pe->offset );
-            pstr = (char *)pe;
-        }
-        else  /* fixed */
-        {
-            struct entry_tab_fixed_s *pe = (struct entry_tab_fixed_s*)(pstr+2);
-            for (i = 0; i < *pstr; i++, pe++)
-                DUMP( "%d: %04x (fixed)\n",
-		      ordinal++, pe->offset[0] + (pe->offset[1] << 8) );
-            pstr = (char *)pe;
-        }
-    }
-
-    /* Dump the non-resident names table */
-    DUMP( "---\n" );
-    DUMP( "Non-resident names table:\n" );
-    if (pModule->nrname_handle)
-    {
-        pstr = (char *)GlobalLock16( pModule->nrname_handle );
-        while (*pstr)
-        {
-            DUMP( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
-                   *(WORD *)(pstr + *pstr + 1) );
-            pstr += *pstr + 1 + sizeof(WORD);
-        }
-    }
-    DUMP( "\n" );
-}
-
-
-/***********************************************************************
- *           MODULE_WalkModules
- *
- * Walk the module list and print the modules.
- */
-void MODULE_WalkModules(void)
-{
-    HMODULE16 hModule = hFirstModule;
-    fprintf( stderr, "Module Flags Name\n" );
-    while (hModule)
-    {
-        NE_MODULE *pModule = MODULE_GetPtr( hModule );
-        if (!pModule)
-        {
-            fprintf( stderr, "**** Bad module %04x in list\n", hModule );
-            return;
-        }
-        fprintf( stderr, " %04x  %04x  %.*s\n", hModule, pModule->flags,
-                 *((char *)pModule + pModule->name_table),
-                 (char *)pModule + pModule->name_table + 1 );
-        hModule = pModule->next;
-    }
-}
-
-
-/***********************************************************************
  *           MODULE_OpenFile
  */
 int MODULE_OpenFile( HMODULE32 hModule )
@@ -273,14 +113,14 @@
     hModule = MODULE_HANDLEtoHMODULE16(hModule);
     TRACE(module, "(%04x) cache: mod=%04x fd=%d\n",
                     hModule, hCachedModule, cachedfd );
-    if (!(pModule = MODULE_GetPtr( hModule ))) return -1;
+    if (!(pModule = MODULE_GetPtr32( hModule ))) return -1;
     if (hCachedModule == hModule) return cachedfd;
     close( cachedfd );
     hCachedModule = hModule;
     name = NE_MODULE_NAME( pModule );
     if (!DOSFS_GetFullName( name, TRUE, &full_name ) ||
         (cachedfd = open( full_name.long_name, O_RDONLY )) == -1)
-        fprintf( stderr, "MODULE_OpenFile: can't open file '%s' for module %04x\n",
+        WARN( module, "Can't open file '%s' for module %04x\n",
                  name, hModule );
     TRACE(module, "opened '%s' -> %d\n",
                     name, cachedfd );
@@ -289,112 +129,33 @@
 
 
 /***********************************************************************
- *           MODULE_Ne2MemFlags
- *
- * This function translates NE segment flags to GlobalAlloc flags
- */
-static WORD MODULE_Ne2MemFlags(WORD flags)
-{ 
-    WORD memflags = 0;
-#if 0
-    if (flags & NE_SEGFLAGS_DISCARDABLE) 
-      memflags |= GMEM_DISCARDABLE;
-    if (flags & NE_SEGFLAGS_MOVEABLE || 
-	( ! (flags & NE_SEGFLAGS_DATA) &&
-	  ! (flags & NE_SEGFLAGS_LOADED) &&
-	  ! (flags & NE_SEGFLAGS_ALLOCATED)
-	 )
-	)
-      memflags |= GMEM_MOVEABLE;
-    memflags |= GMEM_ZEROINIT;
-#else
-    memflags = GMEM_ZEROINIT | GMEM_FIXED;
-    return memflags;
-#endif
-}
-
-/***********************************************************************
- *           MODULE_AllocateSegment (WPROCS.26)
- */
-
-DWORD WINAPI MODULE_AllocateSegment(WORD wFlags, WORD wSize, WORD wElem)
-{
-    WORD size = wSize << wElem;
-    HANDLE16 hMem = GlobalAlloc16( MODULE_Ne2MemFlags(wFlags), size);
-    return MAKELONG( hMem, GlobalHandleToSel(hMem) );
-}
-
-/***********************************************************************
- *           MODULE_CreateSegments
- */
-static BOOL32 MODULE_CreateSegments( HMODULE32 hModule )
-{
-    SEGTABLEENTRY *pSegment;
-    NE_MODULE *pModule;
-    int i, minsize;
-
-    if (!(pModule = MODULE_GetPtr( hModule ))) return FALSE;
-    pSegment = NE_SEG_TABLE( pModule );
-    for (i = 1; i <= pModule->seg_count; i++, pSegment++)
-    {
-        minsize = pSegment->minsize ? pSegment->minsize : 0x10000;
-        if (i == pModule->ss) minsize += pModule->stack_size;
-	/* The DGROUP is allocated by MODULE_CreateInstance */
-        if (i == pModule->dgroup) continue;
-        pSegment->selector = GLOBAL_Alloc( MODULE_Ne2MemFlags(pSegment->flags),
-                                      minsize, hModule,
-                                      !(pSegment->flags & NE_SEGFLAGS_DATA),
-                                      FALSE,
-                            FALSE /*pSegment->flags & NE_SEGFLAGS_READONLY*/ );
-        if (!pSegment->selector) return FALSE;
-    }
-
-    pModule->dgroup_entry = pModule->dgroup ? pModule->seg_table +
-                            (pModule->dgroup - 1) * sizeof(SEGTABLEENTRY) : 0;
-    return TRUE;
-}
-
-
-/***********************************************************************
- *           MODULE_GetInstance
- */
-HINSTANCE16 MODULE_GetInstance( HMODULE32 hModule )
-{
-    SEGTABLEENTRY *pSegment;
-    NE_MODULE *pModule;
-    
-    if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
-    if (pModule->dgroup == 0) return hModule;
-
-    pSegment = NE_SEG_TABLE( pModule ) + pModule->dgroup - 1;
-    
-    return pSegment->selector;
-}
-
-
-/***********************************************************************
  *           MODULE_CreateInstance
  *
  * If lib_only is TRUE, handle the module like a library even if it is a .EXE
  */
-HINSTANCE16 MODULE_CreateInstance( HMODULE16 hModule, BOOL32 lib_only )
+HINSTANCE16 MODULE_CreateInstance( HMODULE16 hModule, HINSTANCE16 *prev,
+                                   BOOL32 lib_only )
 {
     SEGTABLEENTRY *pSegment;
     NE_MODULE *pModule;
     int minsize;
-    HINSTANCE16 hNewInstance, hPrevInstance;
+    HINSTANCE16 hNewInstance;
 
-    if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
-    if (pModule->dgroup == 0) return hModule;
+    if (!(pModule = MODULE_GetPtr16( hModule ))) return 0;
+    if (pModule->dgroup == 0)
+    {
+        if (prev) *prev = hModule;
+        return hModule;
+    }
 
     pSegment = NE_SEG_TABLE( pModule ) + pModule->dgroup - 1;
-    hPrevInstance = pSegment->selector;
+    if (prev) *prev = pSegment->selector;
 
       /* if it's a library, create a new instance only the first time */
-    if (hPrevInstance)
+    if (pSegment->selector)
     {
-        if (pModule->flags & NE_FFLAGS_LIBMODULE) return hPrevInstance;
-        if (lib_only) return hPrevInstance;
+        if (pModule->flags & NE_FFLAGS_LIBMODULE) return pSegment->selector;
+        if (lib_only) return pSegment->selector;
     }
 
     minsize = pSegment->minsize ? pSegment->minsize : 0x10000;
@@ -491,432 +252,12 @@
     pModule->res_table = pModule->import_table = pModule->entry_table =
 		(int)pStr - (int)pModule;
 
-    MODULE_RegisterModule( pModule );
+    NE_RegisterModule( pModule );
     return hModule;
 }
 
 
 /***********************************************************************
- *           MODULE_LoadExeHeader
- */
-static HMODULE32 MODULE_LoadExeHeader( HFILE32 hFile, OFSTRUCT *ofs )
-{
-    IMAGE_DOS_HEADER mz_header;
-    IMAGE_OS2_HEADER ne_header;
-    int size;
-    HMODULE32 hModule;
-    NE_MODULE *pModule;
-    BYTE *pData;
-    char *buffer, *fastload = NULL;
-    int fastload_offset = 0, fastload_length = 0;
-
-  /* Read a block from either the file or the fast-load area. */
-#define READ(offset,size,buffer) \
-       ((fastload && ((offset) >= fastload_offset) && \
-         ((offset)+(size) <= fastload_offset+fastload_length)) ? \
-        (memcpy( buffer, fastload+(offset)-fastload_offset, (size) ), TRUE) : \
-        (_llseek32( hFile, (offset), SEEK_SET), \
-         _lread32( hFile, (buffer), (size) ) == (size)))
-
-    _llseek32( hFile, 0, SEEK_SET );
-    if ((_lread32(hFile,&mz_header,sizeof(mz_header)) != sizeof(mz_header)) ||
-        (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
-        return (HMODULE32)11;  /* invalid exe */
-
-    _llseek32( hFile, mz_header.e_lfanew, SEEK_SET );
-    if (_lread32( hFile, &ne_header, sizeof(ne_header) ) != sizeof(ne_header))
-        return (HMODULE32)11;  /* invalid exe */
-
-    if (ne_header.ne_magic == IMAGE_NT_SIGNATURE) return (HMODULE32)21;  /* win32 exe */
-    if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE) return (HMODULE32)11;  /* invalid exe */
-
-    if (ne_header.ne_magic == IMAGE_OS2_SIGNATURE_LX) {
-      fprintf(stderr, "Sorry, this is an OS/2 linear executable (LX) file !\n");
-      return (HMODULE32)12;
-    }
-
-    /* We now have a valid NE header */
-
-    size = sizeof(NE_MODULE) +
-             /* loaded file info */
-           sizeof(OFSTRUCT)-sizeof(ofs->szPathName)+strlen(ofs->szPathName)+1+
-             /* segment table */
-           ne_header.n_segment_tab * sizeof(SEGTABLEENTRY) +
-             /* resource table */
-           ne_header.rname_tab_offset - ne_header.resource_tab_offset +
-             /* resident names table */
-           ne_header.moduleref_tab_offset - ne_header.rname_tab_offset +
-             /* module ref table */
-           ne_header.n_mod_ref_tab * sizeof(WORD) + 
-             /* imported names table */
-           ne_header.entry_tab_offset - ne_header.iname_tab_offset +
-             /* entry table length */
-           ne_header.entry_tab_length;
-
-    hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
-    if (!hModule) return (HMODULE32)11;  /* invalid exe */
-    FarSetOwner( hModule, hModule );
-    pModule = (NE_MODULE *)GlobalLock16( hModule );
-    memcpy( pModule, &ne_header, sizeof(ne_header) );
-    pModule->count = 0;
-    pModule->module32 = 0;
-    pModule->self = hModule;
-    pModule->self_loading_sel = 0;
-    pData = (BYTE *)(pModule + 1);
-
-    /* Clear internal Wine flags in case they are set in the EXE file */
-
-    pModule->flags &= ~(NE_FFLAGS_BUILTIN|NE_FFLAGS_WIN32|NE_FFLAGS_IMPLICIT);
-
-    /* Read the fast-load area */
-
-    if (ne_header.additional_flags & NE_AFLAGS_FASTLOAD)
-    {
-        fastload_offset=ne_header.fastload_offset<<ne_header.align_shift_count;
-        fastload_length=ne_header.fastload_length<<ne_header.align_shift_count;
-        TRACE(module, "Using fast-load area offset=%x len=%d\n",
-                        fastload_offset, fastload_length );
-        if ((fastload = HeapAlloc( SystemHeap, 0, fastload_length )) != NULL)
-        {
-            _llseek32( hFile, fastload_offset, SEEK_SET);
-            if (_lread32(hFile, fastload, fastload_length) != fastload_length)
-            {
-                HeapFree( SystemHeap, 0, fastload );
-                fprintf(stderr, "Error reading fast-load area !\n");
-                fastload = NULL;
-            }
-        }
-    }
-
-    /* Store the filename information */
-
-    pModule->fileinfo = (int)pData - (int)pModule;
-    size = sizeof(OFSTRUCT)-sizeof(ofs->szPathName)+strlen(ofs->szPathName)+1;
-    memcpy( pData, ofs, size );
-    ((OFSTRUCT *)pData)->cBytes = size - 1;
-    pData += size;
-
-    /* Get the segment table */
-
-    pModule->seg_table = (int)pData - (int)pModule;
-    buffer = HeapAlloc( SystemHeap, 0, ne_header.n_segment_tab *
-                                      sizeof(struct ne_segment_table_entry_s));
-    if (buffer)
-    {
-        int i;
-        struct ne_segment_table_entry_s *pSeg;
-
-        if (!READ( mz_header.e_lfanew + ne_header.segment_tab_offset,
-             ne_header.n_segment_tab * sizeof(struct ne_segment_table_entry_s),
-             buffer ))
-        {
-            HeapFree( SystemHeap, 0, buffer );
-            if (fastload) HeapFree( SystemHeap, 0, fastload );
-            GlobalFree16( hModule );
-            return (HMODULE32)11;  /* invalid exe */
-        }
-        pSeg = (struct ne_segment_table_entry_s *)buffer;
-        for (i = ne_header.n_segment_tab; i > 0; i--, pSeg++)
-        {
-            memcpy( pData, pSeg, sizeof(*pSeg) );
-            pData += sizeof(SEGTABLEENTRY);
-        }
-        HeapFree( SystemHeap, 0, buffer );
-    }
-    else
-    {
-        if (fastload) HeapFree( SystemHeap, 0, fastload );
-        GlobalFree16( hModule );
-        return (HMODULE32)11;  /* invalid exe */
-    }
-
-    /* Get the resource table */
-
-    if (ne_header.resource_tab_offset < ne_header.rname_tab_offset)
-    {
-        pModule->res_table = (int)pData - (int)pModule;
-        if (!READ(mz_header.e_lfanew + ne_header.resource_tab_offset,
-                  ne_header.rname_tab_offset - ne_header.resource_tab_offset,
-                  pData )) return (HMODULE32)11;  /* invalid exe */
-        pData += ne_header.rname_tab_offset - ne_header.resource_tab_offset;
-	NE_InitResourceHandler( hModule );
-    }
-    else pModule->res_table = 0;  /* No resource table */
-
-    /* Get the resident names table */
-
-    pModule->name_table = (int)pData - (int)pModule;
-    if (!READ( mz_header.e_lfanew + ne_header.rname_tab_offset,
-               ne_header.moduleref_tab_offset - ne_header.rname_tab_offset,
-               pData ))
-    {
-        if (fastload) HeapFree( SystemHeap, 0, fastload );
-        GlobalFree16( hModule );
-        return (HMODULE32)11;  /* invalid exe */
-    }
-    pData += ne_header.moduleref_tab_offset - ne_header.rname_tab_offset;
-
-    /* Get the module references table */
-
-    if (ne_header.n_mod_ref_tab > 0)
-    {
-        pModule->modref_table = (int)pData - (int)pModule;
-        if (!READ( mz_header.e_lfanew + ne_header.moduleref_tab_offset,
-                  ne_header.n_mod_ref_tab * sizeof(WORD),
-                  pData ))
-        {
-            if (fastload) HeapFree( SystemHeap, 0, fastload );
-            GlobalFree16( hModule );
-            return (HMODULE32)11;  /* invalid exe */
-        }
-        pData += ne_header.n_mod_ref_tab * sizeof(WORD);
-    }
-    else pModule->modref_table = 0;  /* No module references */
-
-    /* Get the imported names table */
-
-    pModule->import_table = (int)pData - (int)pModule;
-    if (!READ( mz_header.e_lfanew + ne_header.iname_tab_offset, 
-               ne_header.entry_tab_offset - ne_header.iname_tab_offset,
-               pData ))
-    {
-        if (fastload) HeapFree( SystemHeap, 0, fastload );
-        GlobalFree16( hModule );
-        return (HMODULE32)11;  /* invalid exe */
-    }
-    pData += ne_header.entry_tab_offset - ne_header.iname_tab_offset;
-
-    /* Get the entry table */
-
-    pModule->entry_table = (int)pData - (int)pModule;
-    if (!READ( mz_header.e_lfanew + ne_header.entry_tab_offset,
-               ne_header.entry_tab_length,
-               pData ))
-    {
-        if (fastload) HeapFree( SystemHeap, 0, fastload );
-        GlobalFree16( hModule );
-        return (HMODULE32)11;  /* invalid exe */
-    }
-    pData += ne_header.entry_tab_length;
-
-    /* Free the fast-load area */
-
-#undef READ
-    if (fastload) HeapFree( SystemHeap, 0, fastload );
-
-    /* Get the non-resident names table */
-
-    if (ne_header.nrname_tab_length)
-    {
-        pModule->nrname_handle = GLOBAL_Alloc( 0, ne_header.nrname_tab_length,
-                                               hModule, FALSE, FALSE, FALSE );
-        if (!pModule->nrname_handle)
-        {
-            GlobalFree16( hModule );
-            return (HMODULE32)11;  /* invalid exe */
-        }
-        buffer = GlobalLock16( pModule->nrname_handle );
-        _llseek32( hFile, ne_header.nrname_tab_offset, SEEK_SET );
-        if (_lread32( hFile, buffer, ne_header.nrname_tab_length )
-              != ne_header.nrname_tab_length)
-        {
-            GlobalFree16( pModule->nrname_handle );
-            GlobalFree16( hModule );
-            return (HMODULE32)11;  /* invalid exe */
-        }
-    }
-    else pModule->nrname_handle = 0;
-
-    /* Allocate a segment for the implicitly-loaded DLLs */
-
-    if (pModule->modref_count)
-    {
-        pModule->dlls_to_init = GLOBAL_Alloc(GMEM_ZEROINIT,
-                                    (pModule->modref_count+1)*sizeof(HMODULE32),
-                                    hModule, FALSE, FALSE, FALSE );
-        if (!pModule->dlls_to_init)
-        {
-            if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
-            GlobalFree16( hModule );
-            return (HMODULE32)11;  /* invalid exe */
-        }
-    }
-    else pModule->dlls_to_init = 0;
-
-    MODULE_RegisterModule( pModule );
-    return hModule;
-}
-
-
-/***********************************************************************
- *           MODULE_GetOrdinal
- *
- * Lookup the ordinal for a given name.
- */
-WORD MODULE_GetOrdinal( HMODULE32 hModule, const char *name )
-{
-    unsigned char buffer[256], *cpnt;
-    BYTE len;
-    NE_MODULE *pModule;
-
-    if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
-
-    TRACE(module, "(%04x,'%s')\n",
-                    hModule, name );
-
-      /* First handle names of the form '#xxxx' */
-
-    if (name[0] == '#') return atoi( name + 1 );
-
-      /* Now copy and uppercase the string */
-
-    strcpy( buffer, name );
-    CharUpper32A( buffer );
-    len = strlen( buffer );
-
-      /* First search the resident names */
-
-    cpnt = (char *)pModule + pModule->name_table;
-
-      /* Skip the first entry (module name) */
-    cpnt += *cpnt + 1 + sizeof(WORD);
-    while (*cpnt)
-    {
-        if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
-        {
-            TRACE(module, "  Found: ordinal=%d\n",
-                            *(WORD *)(cpnt + *cpnt + 1) );
-            return *(WORD *)(cpnt + *cpnt + 1);
-        }
-        cpnt += *cpnt + 1 + sizeof(WORD);
-    }
-
-      /* Now search the non-resident names table */
-
-    if (!pModule->nrname_handle) return 0;  /* No non-resident table */
-    cpnt = (char *)GlobalLock16( pModule->nrname_handle );
-
-      /* Skip the first entry (module description string) */
-    cpnt += *cpnt + 1 + sizeof(WORD);
-    while (*cpnt)
-    {
-        if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
-        {
-            TRACE(module, "  Found: ordinal=%d\n",
-                            *(WORD *)(cpnt + *cpnt + 1) );
-            return *(WORD *)(cpnt + *cpnt + 1);
-        }
-        cpnt += *cpnt + 1 + sizeof(WORD);
-    }
-    return 0;
-}
-
-
-/***********************************************************************
- *           MODULE_GetEntryPoint
- *
- * Return the entry point for a given ordinal.
- */
-FARPROC16 MODULE_GetEntryPoint( HMODULE32 hModule, WORD ordinal )
-{
-    NE_MODULE *pModule;
-    WORD curOrdinal = 1;
-    BYTE *p;
-    WORD sel, offset;
-
-    if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
-
-    p = (BYTE *)pModule + pModule->entry_table;
-    while (*p && (curOrdinal + *p <= ordinal))
-    {
-          /* Skipping this bundle */
-        curOrdinal += *p;
-        switch(p[1])
-        {
-            case 0:    p += 2; break;  /* unused */
-            case 0xff: p += 2 + *p * 6; break;  /* moveable */
-            default:   p += 2 + *p * 3; break;  /* fixed */
-        }
-    }
-    if (!*p) return 0;
-
-    switch(p[1])
-    {
-        case 0:  /* unused */
-            return 0;
-        case 0xff:  /* moveable */
-            p += 2 + 6 * (ordinal - curOrdinal);
-            sel = p[3];
-            offset = *(WORD *)(p + 4);
-            break;
-        default:  /* fixed */
-            sel = p[1];
-            p += 2 + 3 * (ordinal - curOrdinal);
-            offset = *(WORD *)(p + 1);
-            break;
-    }
-
-    if (sel == 0xfe) sel = 0xffff;  /* constant entry */
-    else sel = (WORD)(DWORD)NE_SEG_TABLE(pModule)[sel-1].selector;
-    return (FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset );
-}
-
-
-/***********************************************************************
- *           EntryAddrProc   (WPROCS.27)
- */
-FARPROC16 WINAPI EntryAddrProc( HMODULE16 hModule, WORD ordinal )
-{
-    return MODULE_GetEntryPoint( hModule, ordinal );
-}
-
-
-/***********************************************************************
- *           MODULE_SetEntryPoint
- *
- * Change the value of an entry point. Use with caution!
- * It can only change the offset value, not the selector.
- */
-BOOL16 MODULE_SetEntryPoint( HMODULE32 hModule, WORD ordinal, WORD offset )
-{
-    NE_MODULE *pModule;
-    WORD curOrdinal = 1;
-    BYTE *p;
-
-    if (!(pModule = MODULE_GetPtr( hModule ))) return FALSE;
-
-    p = (BYTE *)pModule + pModule->entry_table;
-    while (*p && (curOrdinal + *p <= ordinal))
-    {
-          /* Skipping this bundle */
-        curOrdinal += *p;
-        switch(p[1])
-        {
-            case 0:    p += 2; break;  /* unused */
-            case 0xff: p += 2 + *p * 6; break;  /* moveable */
-            default:   p += 2 + *p * 3; break;  /* fixed */
-        }
-    }
-    if (!*p) return FALSE;
-
-    switch(p[1])
-    {
-        case 0:  /* unused */
-            return FALSE;
-        case 0xff:  /* moveable */
-            p += 2 + 6 * (ordinal - curOrdinal);
-            *(WORD *)(p + 4) = offset;
-            break;
-        default:  /* fixed */
-            p += 2 + 3 * (ordinal - curOrdinal);
-            *(WORD *)(p + 1) = offset;
-            break;
-    }
-    return TRUE;
-}
-
-
-/***********************************************************************
  *           MODULE_GetWndProcEntry16  (not a Windows API function)
  *
  * Return an entry point from the WPROCS dll.
@@ -950,7 +291,7 @@
             return (FARPROC16)PrintSetupDlgProc;
         if (!strcmp(name,"ReplaceTextDlgProc"))
             return (FARPROC16)ReplaceTextDlgProc16;
-        fprintf(stderr,"warning: No mapping for %s(), add one in library/miscstubs.c\n",name);
+        WARN(module,"No mapping for %s(), add one in library/miscstubs.c\n",name);
         assert( FALSE );
         return NULL;
     }
@@ -960,10 +301,10 @@
         static HMODULE32 hModule = 0;
 
         if (!hModule) hModule = GetModuleHandle16( "WPROCS" );
-        ordinal = MODULE_GetOrdinal( hModule, name );
-        if (!(ret = MODULE_GetEntryPoint( hModule, ordinal )))
+        ordinal = NE_GetOrdinal( hModule, name );
+        if (!(ret = NE_GetEntryPoint( hModule, ordinal )))
         {            
-            fprintf( stderr, "GetWndProc16: %s not found\n", name );
+            WARN( module, "%s not found\n", name );
             assert( FALSE );
         }
     }
@@ -980,7 +321,7 @@
     BYTE *p, len;
     static char buffer[10];
 
-    if (!(pModule = MODULE_GetPtr( hModule ))) return NULL;
+    if (!(pModule = MODULE_GetPtr32( hModule ))) return NULL;
     p = (BYTE *)pModule + pModule->name_table;
     len = MIN( *p, 8 );
     memcpy( buffer, p + 1, len );
@@ -990,25 +331,19 @@
 
 
 /**********************************************************************
- *           MODULE_RegisterModule
- */
-void MODULE_RegisterModule( NE_MODULE *pModule )
-{
-    pModule->next = hFirstModule;
-    hFirstModule = pModule->self;
-}
-
-
-/**********************************************************************
  *	    MODULE_FindModule
  *
  * Find a module from a path name.
+ * RETURNS
+ *	the win16 module handle if found
+ * 	0 if not
  */
-HMODULE32 MODULE_FindModule( LPCSTR path )
-{
+HMODULE32 MODULE_FindModule16(
+	LPCSTR path	/* [in] path of the module to be found */
+) {
     HMODULE32 hModule = hFirstModule;
-    LPCSTR filename, dotptr, modulepath, modulename;
-    BYTE len, *name_table;
+    LPCSTR	filename, dotptr, modulepath, modulename;
+    BYTE	len, *name_table;
 
     if (!(filename = strrchr( path, '\\' ))) filename = path;
     else filename++;
@@ -1018,7 +353,7 @@
 
     while(hModule)
     {
-        NE_MODULE *pModule = MODULE_GetPtr( hModule );
+        NE_MODULE *pModule = MODULE_GetPtr16( hModule );
         if (!pModule) break;
         modulepath = NE_MODULE_NAME(pModule);
         if (!(modulename = strrchr( modulepath, '\\' )))
@@ -1034,6 +369,62 @@
     return 0;
 }
 
+/**********************************************************************
+ *	    MODULE_FindModule32
+ *
+ * Find a (loaded) win32 module depending on path
+ * The handling of '.' is a bit weird, but we need it that way, 
+ * for sometimes the programs use '<name>.exe' and '<name>.dll' and
+ * this is the only way to differentiate. (mainly hypertrm.exe)
+ *
+ * RETURNS
+ *	the module handle if found
+ * 	0 if not
+ */
+HMODULE32 MODULE_FindModule32(
+	PDB32* process,	/* [in] process in which to find the library */
+	LPCSTR path	/* [in] pathname of module/library to be found */
+) {
+    LPSTR	filename;
+    LPSTR	dotptr;
+    WINE_MODREF	*wm;
+
+    if (!(filename = strrchr( path, '\\' )))
+    	filename = HEAP_strdupA(process->heap,0,path);
+    else 
+    	filename = HEAP_strdupA(process->heap,0,filename+1);
+    dotptr=strrchr(filename,'.');
+
+    if (!process) {
+    	HeapFree(process->heap,0,filename);
+    	return 0;
+    }
+    for (wm=process->modref_list;wm;wm=wm->next) {
+    	LPSTR	xmodname,xdotptr;
+
+	assert (wm->modname);
+	xmodname = HEAP_strdupA(process->heap,0,wm->modname);
+	xdotptr=strrchr(xmodname,'.');
+	if (	(xdotptr && !dotptr) ||
+		(!xdotptr && dotptr)
+	) {
+	    if (dotptr)	*dotptr		= '\0';
+	    if (xdotptr) *xdotptr	= '\0';
+	}
+	if (!lstrcmpi32A( filename, xmodname)) {
+	    HeapFree(process->heap,0,filename);
+	    HeapFree(process->heap,0,xmodname);
+	    return wm->module;
+	}
+	if (dotptr) *dotptr='.';
+	/* FIXME: add paths, shortname */
+	HeapFree(process->heap,0,xmodname);
+    }
+    HeapFree(process->heap,0,filename);
+    return 0;
+}
+
+
 
 /**********************************************************************
  *	    MODULE_CallWEP
@@ -1044,9 +435,9 @@
 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
 {
     FARPROC16 WEP = (FARPROC16)0;
-    WORD ordinal = MODULE_GetOrdinal( hModule, "WEP" );
+    WORD ordinal = NE_GetOrdinal( hModule, "WEP" );
 
-    if (ordinal) WEP = MODULE_GetEntryPoint( hModule, ordinal );
+    if (ordinal) WEP = NE_GetEntryPoint( hModule, ordinal );
     if (!WEP)
     {
 	WARN(module, "module %04x doesn't have a WEP\n", hModule );
@@ -1069,7 +460,7 @@
     HMODULE16 *pModRef;
     int i;
 
-    if (!(pModule = MODULE_GetPtr( hModule ))) return FALSE;
+    if (!(pModule = MODULE_GetPtr32( hModule ))) return FALSE;
     hModule = pModule->self;
 
     if (((INT16)(--pModule->count)) > 0 ) return TRUE;
@@ -1100,7 +491,7 @@
     hPrevModule = &hFirstModule;
     while (*hPrevModule && (*hPrevModule != hModule))
     {
-        hPrevModule = &(MODULE_GetPtr( *hPrevModule ))->next;
+        hPrevModule = &(MODULE_GetPtr16( *hPrevModule ))->next;
     }
     if (*hPrevModule) *hPrevModule = pModule->next;
 
@@ -1157,12 +548,12 @@
         lstrcpyn32A( ofs.szPathName, name, sizeof(ofs.szPathName) );
         if ((hModule = MODULE_CreateDummyModule( &ofs )) < 32) return hModule;
         pModule = (NE_MODULE *)GlobalLock16( hModule );
-        hPrevInstance = 0;
-        hInstance = MODULE_CreateInstance( hModule, (cmd_line == NULL) );
+        hInstance = MODULE_CreateInstance( hModule, &hPrevInstance,
+                                           (cmd_line == NULL) );
     }
     else
     {
-        hModule = MODULE_FindModule( name );
+        hModule = MODULE_FindModule16( name );
 
         if (!hModule)  /* We have to load the module */
         {
@@ -1175,7 +566,7 @@
                 /* Now try the built-in even if disabled */
                 if ((hModule = fnBUILTIN_LoadModule( name, TRUE )))
                 {
-                    fprintf( stderr, "Warning: could not load Windows DLL '%s', using built-in module.\n", name );
+                    WARN(module, "Could not load Windows DLL '%s', using built-in module.\n", name );
                     return MODULE_HANDLEtoHMODULE16( hModule );
                 }
                 return 2;  /* File not found */
@@ -1183,59 +574,26 @@
 
             /* Create the module structure */
 
-            hModule = MODULE_LoadExeHeader( hFile, &ofs );
+            hModule = NE_LoadModule( hFile, &ofs, uFlags, cmd_line,
+                                     env, show_cmd );
             if (hModule < 32)
             {
                 if ((hModule == 21) && cmd_line)
                     hModule = PE_LoadModule( hFile, &ofs, cmd_line,
                                              env, show_cmd );
-                _lclose32( hFile );
-
-                if (hModule < 32)
-                    fprintf( stderr, "LoadModule: can't load '%s', error=%d\n",
-                             name, hModule );
-                return hModule;
             }
+
+            if (hModule < 32)
+                fprintf( stderr, "LoadModule: can't load '%s', error=%d\n",
+                         name, hModule );
             _lclose32( hFile );
-            pModule = MODULE_GetPtr( hModule );
-            pModule->flags |= uFlags; /* stamp implicitly loaded modules */
-
-            /* Allocate the segments for this module */
-
-            MODULE_CreateSegments( hModule );
-            hPrevInstance = 0;
-            hInstance = MODULE_CreateInstance( hModule, (cmd_line == NULL) );
-
-            /* Load the referenced DLLs */
-
-            if (!NE_LoadDLLs( pModule )) return 2;  /* File not found */
-
-            /* Load the segments */
-
-            NE_LoadAllSegments( pModule );
-
-            /* Fixup the functions prologs */
-
-            NE_FixupPrologs( pModule );
-
-            /* Make sure the usage count is 1 on the first loading of  */
-            /* the module, even if it contains circular DLL references */
-
-            pModule->count = 1;
-
-            /* Call initialization rountines for all loaded DLLs. Note that
-             * when we load implicitly linked DLLs this will be done by InitTask().
-             */
-
-            if ((pModule->flags & (NE_FFLAGS_LIBMODULE | NE_FFLAGS_IMPLICIT)) ==
-                                       NE_FFLAGS_LIBMODULE )
-                NE_InitializeDLLs( hModule );
+            return hModule;
         }
         else /* module is already loaded, just create a new data segment if it's a task */
         {
-            pModule = MODULE_GetPtr( hModule );
-            hPrevInstance = MODULE_GetInstance( hModule );
-            hInstance = MODULE_CreateInstance( hModule, (cmd_line == NULL) );
+            pModule = MODULE_GetPtr32( hModule );
+            hInstance = MODULE_CreateInstance( hModule, &hPrevInstance,
+                                               (cmd_line == NULL) );
             if (hInstance != hPrevInstance)  /* not a library */
                 NE_LoadSegment( pModule, pModule->dgroup );
             pModule->count++;
@@ -1337,7 +695,7 @@
 {
     NE_MODULE *pModule;
 
-    if (!(pModule = MODULE_GetPtr( hModule ))) return FALSE;
+    if (!(pModule = MODULE_GetPtr16( hModule ))) return FALSE;
     TRACE(module, "%s count %d\n", 
 		    MODULE_GetModuleName(hModule), pModule->count );
 
@@ -1350,13 +708,13 @@
  */
 HMODULE16 WINAPI WIN16_GetModuleHandle( SEGPTR name )
 {
-    if (HIWORD(name) == 0) return MODULE_HANDLEtoHMODULE16( (HINSTANCE16)name );
-    return MODULE_FindModule( PTR_SEG_TO_LIN(name) );
+    if (HIWORD(name) == 0) return GetExePtr( (HINSTANCE16)name );
+    return MODULE_FindModule16( PTR_SEG_TO_LIN(name) );
 }
 
 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
 {
-    return MODULE_FindModule( name );
+    return MODULE_FindModule16( name );
 }
 
 /***********************************************************************
@@ -1364,17 +722,12 @@
  */
 HMODULE32 WINAPI GetModuleHandle32A(LPCSTR module)
 {
-    HMODULE32	hModule;
 
     TRACE(win32, "%s\n", module ? module : "NULL");
-/* Freecell uses the result of GetModuleHandleA(0) as the hInstance in
-all calls to e.g. CreateWindowEx. */
-    if (module == NULL) {
-	TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
-	hModule = pTask->hInstance;
-    } else
-	hModule = MODULE_FindModule(module);
-    return MODULE_HANDLEtoHMODULE32(hModule);
+    if (module == NULL)
+    	return PROCESS_Current()->exe_modref->module;
+    else
+	return MODULE_FindModule32(PROCESS_Current(),module);
 }
 
 HMODULE32 WINAPI GetModuleHandle32W(LPCWSTR module)
@@ -1394,7 +747,7 @@
 {
     NE_MODULE *pModule;
 
-    if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
+    if (!(pModule = MODULE_GetPtr16( hModule ))) return 0;
     TRACE(module, "(%04x): returning %d\n",
                     hModule, pModule->count );
     return pModule->count;
@@ -1410,7 +763,7 @@
     NE_MODULE *pModule;
 
     if (!hModule) hModule = GetCurrentTask();
-    if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
+    if (!(pModule = MODULE_GetPtr16( hModule ))) return 0;
     lstrcpyn32A( lpFileName, NE_MODULE_NAME(pModule), nSize );
     TRACE(module, "%s\n", lpFileName );
     return strlen(lpFileName);
@@ -1419,6 +772,7 @@
 
 /***********************************************************************
  *              GetModuleFileName32A      (KERNEL32.235)
+ * FIXME FIXME
  */
 DWORD WINAPI GetModuleFileName32A( HMODULE32 hModule, LPSTR lpFileName,
                                    DWORD size )
@@ -1430,7 +784,7 @@
         TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
         hModule = pTask->hInstance;
     }
-    if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
+    if (!(pModule = MODULE_GetPtr32( hModule ))) return 0;
     lstrcpyn32A( lpFileName, NE_MODULE_NAME(pModule), size );
     TRACE(module, "%s\n", lpFileName );
     return strlen(lpFileName);
@@ -1471,7 +825,7 @@
 HMODULE32 WINAPI LoadLibraryEx32W16( LPCSTR libname, HANDLE16 hf,
                                        DWORD flags )
 {
-    fprintf(stderr,"LoadLibraryEx32W(%s,%d,%08lx)\n",libname,hf,flags);
+    TRACE(module,"(%s,%d,%08lx)\n",libname,hf,flags);
     return LoadLibraryEx32A(libname, hf,flags);
 }
 
@@ -1528,9 +882,8 @@
  */
 BOOL32 WINAPI FreeLibrary32(HINSTANCE32 hLibModule)
 {
-	TRACE(module,"hLibModule=%08x\n", hLibModule);
-	return MODULE_FreeModule(hLibModule, 
-	                         GlobalLock16(GetCurrentTask()) );
+    TRACE(module,"hLibModule=%08x\n", hLibModule);
+    return MODULE_FreeModule(hLibModule,GlobalLock16(GetCurrentTask()) );
 }
 
 
@@ -1541,11 +894,6 @@
 {
     HINSTANCE16 handle;
 
-    if (__winelib)
-    {
-        fprintf( stderr, "LoadLibrary not supported in Winelib\n" );
-        return 0;
-    }
     TRACE(module, "(%08x) %s\n", (int)libname, libname);
 
     handle = MODULE_Load( libname, 0, NULL, NULL, 0 );
@@ -1730,7 +1078,7 @@
 		    execvp(argv[0] , (char**)argv);
 
 		    /* Failed ! */
-		    fprintf(stderr, "WinExec: can't exec 'wine %s'\n",
+		    MSG("WinExec: can't exec 'wine %s'\n",
 			    lpCmdLine);
 		}
 		exit(1);
@@ -1752,12 +1100,12 @@
     FARPROC16	ret;
 
     if (!hModule) {
-    	fprintf(stderr,"WIN32_GetProcAddress16: hModule may not be 0!\n");
+    	WARN(module,"hModule may not be 0!\n");
 	return (FARPROC16)0;
     }
     hModule = MODULE_HANDLEtoHMODULE16(hModule);
     if (HIWORD(name)) {
-        ordinal = MODULE_GetOrdinal( hModule, name );
+        ordinal = NE_GetOrdinal( hModule, name );
         TRACE(module, "%04x '%s'\n",
                         hModule, name );
     } else {
@@ -1766,7 +1114,7 @@
                         hModule, ordinal );
     }
     if (!ordinal) return (FARPROC16)0;
-    ret = MODULE_GetEntryPoint( hModule, ordinal );
+    ret = NE_GetEntryPoint( hModule, ordinal );
     TRACE(module,"returning %08x\n",(UINT32)ret);
     return ret;
 }
@@ -1780,11 +1128,11 @@
     FARPROC16 ret;
 
     if (!hModule) hModule = GetCurrentTask();
-    hModule = MODULE_HANDLEtoHMODULE16( hModule );
+    hModule = GetExePtr( hModule );
 
     if (HIWORD(name) != 0)
     {
-        ordinal = MODULE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
+        ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
         TRACE(module, "%04x '%s'\n",
                         hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
     }
@@ -1796,7 +1144,7 @@
     }
     if (!ordinal) return (FARPROC16)0;
 
-    ret = MODULE_GetEntryPoint( hModule, ordinal );
+    ret = NE_GetEntryPoint( hModule, ordinal );
 
     TRACE(module, "returning %08x\n", (UINT32)ret );
     return ret;
@@ -1804,29 +1152,41 @@
 
 
 /***********************************************************************
- *           GetProcAddress32   (KERNEL32.257)
+ *           GetProcAddress32   		(KERNEL32.257)
  */
 FARPROC32 WINAPI GetProcAddress32( HMODULE32 hModule, LPCSTR function )
 {
-    NE_MODULE *pModule;
+    return MODULE_GetProcAddress32( PROCESS_Current(), hModule, function );
+}
+
+
+/***********************************************************************
+ *           MODULE_GetProcAddress32   		(internal)
+ */
+FARPROC32 MODULE_GetProcAddress32( 
+	PDB32 *process,		/* [in] process context */
+	HMODULE32 hModule, 	/* [in] current module handle */
+	LPCSTR function )	/* [in] function to be looked up */
+{
+    WINE_MODREF	*wm = MODULE32_LookupHMODULE(process,hModule);
 
     if (HIWORD(function))
 	TRACE(win32,"(%08lx,%s)\n",(DWORD)hModule,function);
     else
 	TRACE(win32,"(%08lx,%p)\n",(DWORD)hModule,function);
-    if (!(pModule = MODULE_GetPtr( hModule )))
+    if (!wm)
         return (FARPROC32)0;
-    if (!pModule->module32)
+    switch (wm->type)
     {
-    	fprintf(stderr,"Oops, Module 0x%08lx has got no module32?\n",
-		(DWORD)MODULE_HANDLEtoHMODULE32(hModule)
-	);
-	return (FARPROC32)0;
+    case MODULE32_PE:
+    	return PE_FindExportedFunction( process, wm, function);
+    default:
+    	ERR(module,"wine_modref type %d not handled.\n",wm->type);
+    	return (FARPROC32)0;
     }
-    return PE_FindExportedFunction( PROCESS_Current(), pModule->module32,
-                                    function );
 }
 
+
 /***********************************************************************
  *           RtlImageNtHeaders   (NTDLL)
  */
@@ -1837,13 +1197,9 @@
      * but we could get HMODULE16 or the like (think builtin modules)
      */
 
-    NE_MODULE *pModule;
-
-    if (!(pModule = MODULE_GetPtr( hModule )))
-        return (LPIMAGE_NT_HEADERS)0;
-    if (!(pModule->flags & NE_FFLAGS_WIN32) || !pModule->module32)
-        return (LPIMAGE_NT_HEADERS)0;
-    return PE_HEADER(pModule->module32);
+    WINE_MODREF	*wm = MODULE32_LookupHMODULE( PROCESS_Current(), hModule );
+    if (!wm || (wm->type != MODULE32_PE)) return (LPIMAGE_NT_HEADERS)0;
+    return PE_HEADER(wm->module);
 }
 
 
@@ -1852,7 +1208,7 @@
  */
 WORD WINAPI GetExpWinVer( HMODULE16 hModule )
 {
-    NE_MODULE *pModule = MODULE_GetPtr( hModule );
+    NE_MODULE *pModule = MODULE_GetPtr16( hModule );
     return pModule ? pModule->expected_version : 0;
 }
 
@@ -1863,7 +1219,7 @@
 BOOL16 WINAPI IsSharedSelector( HANDLE16 selector )
 {
     /* Check whether the selector belongs to a DLL */
-    NE_MODULE *pModule = MODULE_GetPtr( selector );
+    NE_MODULE *pModule = MODULE_GetPtr16( selector );
     if (!pModule) return FALSE;
     return (pModule->flags & NE_FFLAGS_LIBMODULE) != 0;
 }
@@ -1888,7 +1244,7 @@
     char *name;
 
     if (!lpme->wNext) return FALSE;
-    if (!(pModule = MODULE_GetPtr( lpme->wNext ))) return FALSE;
+    if (!(pModule = MODULE_GetPtr16( lpme->wNext ))) return FALSE;
     name = (char *)pModule + pModule->name_table;
     memcpy( lpme->szModule, name + 1, *name );
     lpme->szModule[(BYTE)*name] = '\0';
@@ -1916,7 +1272,7 @@
  */
 BOOL16 WINAPI ModuleFindHandle( MODULEENTRY *lpme, HMODULE16 hModule )
 {
-    hModule = MODULE_HANDLEtoHMODULE16( hModule );
+    hModule = GetExePtr( hModule );
     lpme->wNext = hModule;
     return ModuleNext( lpme );
 }
diff --git a/loader/ne/Makefile.in b/loader/ne/Makefile.in
new file mode 100644
index 0000000..0acbdc1
--- /dev/null
+++ b/loader/ne/Makefile.in
@@ -0,0 +1,17 @@
+DEFS      = @DLLFLAGS@ -D__WINE__
+TOPSRCDIR = @top_srcdir@
+TOPOBJDIR = ../..
+SRCDIR    = @srcdir@
+VPATH     = @srcdir@
+MODULE    = ne
+
+C_SRCS = \
+	module.c \
+	resource.c \
+	segment.c
+
+all: $(MODULE).o
+
+@MAKE_RULES@
+
+### Dependencies:
diff --git a/loader/ne/module.c b/loader/ne/module.c
new file mode 100644
index 0000000..5cd97f8
--- /dev/null
+++ b/loader/ne/module.c
@@ -0,0 +1,736 @@
+/*
+ * NE modules
+ *
+ * Copyright 1995 Alexandre Julliard
+ */
+
+#include <assert.h>
+#include <stdlib.h>
+#include "module.h"
+#include "ldt.h"
+#include "heap.h"
+#include "global.h"
+#include "process.h"
+#include "debug.h"
+
+HMODULE16 hFirstModule = 0;
+
+/***********************************************************************
+ *           NE_DumpModule
+ */
+void NE_DumpModule( HMODULE16 hModule )
+{
+    int i, ordinal;
+    SEGTABLEENTRY *pSeg;
+    BYTE *pstr;
+    WORD *pword;
+    NE_MODULE *pModule;
+
+    if (!(pModule = MODULE_GetPtr16( hModule )))
+    {
+        fprintf( stderr, "**** %04x is not a module handle\n", hModule );
+        return;
+    }
+
+      /* Dump the module info */
+    DUMP( "---\n" );
+    DUMP( "Module %04x:\n", hModule );
+    DUMP( "count=%d flags=%04x heap=%d stack=%d\n",
+	  pModule->count, pModule->flags,
+	  pModule->heap_size, pModule->stack_size );
+    DUMP( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
+	  pModule->cs, pModule->ip, pModule->ss, pModule->sp, pModule->dgroup,
+	  pModule->seg_count, pModule->modref_count );
+    DUMP( "os_flags=%d swap_area=%d version=%04x\n",
+	  pModule->os_flags, pModule->min_swap_area,
+	  pModule->expected_version );
+    if (pModule->flags & NE_FFLAGS_WIN32)
+        DUMP( "PE module=%08x\n", pModule->module32 );
+
+      /* Dump the file info */
+    DUMP( "---\n" );
+    DUMP( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
+
+      /* Dump the segment table */
+    DUMP( "---\n" );
+    DUMP( "Segment table:\n" );
+    pSeg = NE_SEG_TABLE( pModule );
+    for (i = 0; i < pModule->seg_count; i++, pSeg++)
+        DUMP( "%02x: pos=%d size=%d flags=%04x minsize=%d sel=%04x\n",
+	      i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
+	      pSeg->minsize, pSeg->selector );
+
+      /* Dump the resource table */
+    DUMP( "---\n" );
+    DUMP( "Resource table:\n" );
+    if (pModule->res_table)
+    {
+        pword = (WORD *)((BYTE *)pModule + pModule->res_table);
+        DUMP( "Alignment: %d\n", *pword++ );
+        while (*pword)
+        {
+            struct resource_typeinfo_s *ptr = (struct resource_typeinfo_s *)pword;
+            struct resource_nameinfo_s *pname = (struct resource_nameinfo_s *)(ptr + 1);
+            DUMP( "id=%04x count=%d\n", ptr->type_id, ptr->count );
+            for (i = 0; i < ptr->count; i++, pname++)
+                DUMP( "offset=%d len=%d id=%04x\n",
+		      pname->offset, pname->length, pname->id );
+            pword = (WORD *)pname;
+        }
+    }
+    else DUMP( "None\n" );
+
+      /* Dump the resident name table */
+    DUMP( "---\n" );
+    DUMP( "Resident-name table:\n" );
+    pstr = (char *)pModule + pModule->name_table;
+    while (*pstr)
+    {
+        DUMP( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
+	      *(WORD *)(pstr + *pstr + 1) );
+        pstr += *pstr + 1 + sizeof(WORD);
+    }
+
+      /* Dump the module reference table */
+    DUMP( "---\n" );
+    DUMP( "Module ref table:\n" );
+    if (pModule->modref_table)
+    {
+        pword = (WORD *)((BYTE *)pModule + pModule->modref_table);
+        for (i = 0; i < pModule->modref_count; i++, pword++)
+        {
+	    DUMP( "%d: %04x -> '%s'\n", i, *pword,
+		    MODULE_GetModuleName(*pword));
+        }
+    }
+    else DUMP( "None\n" );
+
+      /* Dump the entry table */
+    DUMP( "---\n" );
+    DUMP( "Entry table:\n" );
+    pstr = (char *)pModule + pModule->entry_table;
+    ordinal = 1;
+    while (*pstr)
+    {
+        DUMP( "Bundle %d-%d: %02x\n", ordinal, ordinal + *pstr - 1, pstr[1]);
+        if (!pstr[1])
+        {
+            ordinal += *pstr;
+            pstr += 2;
+        }
+        else if ((BYTE)pstr[1] == 0xff)  /* moveable */
+        {
+            i = *pstr;
+            pstr += 2;
+            while (i--)
+            {
+                DUMP( "%d: %02x:%04x (moveable)\n",
+		      ordinal++, pstr[3], *(WORD *)(pstr + 4) );
+                pstr += 6;
+            }
+        }
+        else  /* fixed */
+        {
+            i = *pstr;
+            pstr += 2;
+            while (i--)
+            {
+                DUMP( "%d: %04x (fixed)\n",
+		      ordinal++, *(WORD *)(pstr + 1) );
+                pstr += 3;
+            }
+        }
+    }
+
+    /* Dump the non-resident names table */
+    DUMP( "---\n" );
+    DUMP( "Non-resident names table:\n" );
+    if (pModule->nrname_handle)
+    {
+        pstr = (char *)GlobalLock16( pModule->nrname_handle );
+        while (*pstr)
+        {
+            DUMP( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
+                   *(WORD *)(pstr + *pstr + 1) );
+            pstr += *pstr + 1 + sizeof(WORD);
+        }
+    }
+    DUMP( "\n" );
+}
+
+
+/***********************************************************************
+ *           NE_WalkModules
+ *
+ * Walk the module list and print the modules.
+ */
+void NE_WalkModules(void)
+{
+    HMODULE16 hModule = hFirstModule;
+    fprintf( stderr, "Module Flags Name\n" );
+    while (hModule)
+    {
+        NE_MODULE *pModule = MODULE_GetPtr16( hModule );
+        if (!pModule)
+        {
+            fprintf( stderr, "**** Bad module %04x in list\n", hModule );
+            return;
+        }
+        fprintf( stderr, " %04x  %04x  %.*s\n", hModule, pModule->flags,
+                 *((char *)pModule + pModule->name_table),
+                 (char *)pModule + pModule->name_table + 1 );
+        hModule = pModule->next;
+    }
+}
+
+
+/**********************************************************************
+ *           NE_RegisterModule
+ */
+void NE_RegisterModule( NE_MODULE *pModule )
+{
+    pModule->next = hFirstModule;
+    hFirstModule = pModule->self;
+}
+
+
+/***********************************************************************
+ *           NE_GetOrdinal
+ *
+ * Lookup the ordinal for a given name.
+ */
+WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
+{
+    unsigned char buffer[256], *cpnt;
+    BYTE len;
+    NE_MODULE *pModule;
+
+    if (!(pModule = MODULE_GetPtr16( hModule ))) return 0;
+    assert( !(pModule->flags & NE_FFLAGS_WIN32) );
+
+    TRACE( module, "(%04x,'%s')\n", hModule, name );
+
+      /* First handle names of the form '#xxxx' */
+
+    if (name[0] == '#') return atoi( name + 1 );
+
+      /* Now copy and uppercase the string */
+
+    strcpy( buffer, name );
+    CharUpper32A( buffer );
+    len = strlen( buffer );
+
+      /* First search the resident names */
+
+    cpnt = (char *)pModule + pModule->name_table;
+
+      /* Skip the first entry (module name) */
+    cpnt += *cpnt + 1 + sizeof(WORD);
+    while (*cpnt)
+    {
+        if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
+        {
+            TRACE(module, "  Found: ordinal=%d\n",
+                            *(WORD *)(cpnt + *cpnt + 1) );
+            return *(WORD *)(cpnt + *cpnt + 1);
+        }
+        cpnt += *cpnt + 1 + sizeof(WORD);
+    }
+
+      /* Now search the non-resident names table */
+
+    if (!pModule->nrname_handle) return 0;  /* No non-resident table */
+    cpnt = (char *)GlobalLock16( pModule->nrname_handle );
+
+      /* Skip the first entry (module description string) */
+    cpnt += *cpnt + 1 + sizeof(WORD);
+    while (*cpnt)
+    {
+        if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
+        {
+            TRACE(module, "  Found: ordinal=%d\n",
+                            *(WORD *)(cpnt + *cpnt + 1) );
+            return *(WORD *)(cpnt + *cpnt + 1);
+        }
+        cpnt += *cpnt + 1 + sizeof(WORD);
+    }
+    return 0;
+}
+
+
+/***********************************************************************
+ *           NE_GetEntryPoint   (WPROCS.27)
+ *
+ * Return the entry point for a given ordinal.
+ */
+FARPROC16 NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
+{
+    NE_MODULE *pModule;
+    WORD curOrdinal = 1;
+    BYTE *p;
+    WORD sel, offset;
+
+    if (!(pModule = MODULE_GetPtr16( hModule ))) return 0;
+    assert( !(pModule->flags & NE_FFLAGS_WIN32) );
+
+    p = (BYTE *)pModule + pModule->entry_table;
+    while (*p && (curOrdinal + *p <= ordinal))
+    {
+          /* Skipping this bundle */
+        curOrdinal += *p;
+        switch(p[1])
+        {
+            case 0:    p += 2; break;  /* unused */
+            case 0xff: p += 2 + *p * 6; break;  /* moveable */
+            default:   p += 2 + *p * 3; break;  /* fixed */
+        }
+    }
+    if (!*p) return 0;
+
+    switch(p[1])
+    {
+        case 0:  /* unused */
+            return 0;
+        case 0xff:  /* moveable */
+            p += 2 + 6 * (ordinal - curOrdinal);
+            sel = p[3];
+            offset = *(WORD *)(p + 4);
+            break;
+        default:  /* fixed */
+            sel = p[1];
+            p += 2 + 3 * (ordinal - curOrdinal);
+            offset = *(WORD *)(p + 1);
+            break;
+    }
+
+    if (sel == 0xfe) sel = 0xffff;  /* constant entry */
+    else sel = (WORD)(DWORD)NE_SEG_TABLE(pModule)[sel-1].selector;
+    return (FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset );
+}
+
+
+/***********************************************************************
+ *           NE_SetEntryPoint
+ *
+ * Change the value of an entry point. Use with caution!
+ * It can only change the offset value, not the selector.
+ */
+BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
+{
+    NE_MODULE *pModule;
+    WORD curOrdinal = 1;
+    BYTE *p;
+
+    if (!(pModule = MODULE_GetPtr16( hModule ))) return FALSE;
+    assert( !(pModule->flags & NE_FFLAGS_WIN32) );
+
+    p = (BYTE *)pModule + pModule->entry_table;
+    while (*p && (curOrdinal + *p <= ordinal))
+    {
+          /* Skipping this bundle */
+        curOrdinal += *p;
+        switch(p[1])
+        {
+            case 0:    p += 2; break;  /* unused */
+            case 0xff: p += 2 + *p * 6; break;  /* moveable */
+            default:   p += 2 + *p * 3; break;  /* fixed */
+        }
+    }
+    if (!*p) return FALSE;
+
+    switch(p[1])
+    {
+        case 0:  /* unused */
+            return FALSE;
+        case 0xff:  /* moveable */
+            p += 2 + 6 * (ordinal - curOrdinal);
+            *(WORD *)(p + 4) = offset;
+            break;
+        default:  /* fixed */
+            p += 2 + 3 * (ordinal - curOrdinal);
+            *(WORD *)(p + 1) = offset;
+            break;
+    }
+    return TRUE;
+}
+
+
+/***********************************************************************
+ *           NE_LoadExeHeader
+ */
+static HMODULE16 NE_LoadExeHeader( HFILE32 hFile, OFSTRUCT *ofs )
+{
+    IMAGE_DOS_HEADER mz_header;
+    IMAGE_OS2_HEADER ne_header;
+    int size;
+    HMODULE16 hModule;
+    NE_MODULE *pModule;
+    BYTE *pData;
+    char *buffer, *fastload = NULL;
+    int fastload_offset = 0, fastload_length = 0;
+
+  /* Read a block from either the file or the fast-load area. */
+#define READ(offset,size,buffer) \
+       ((fastload && ((offset) >= fastload_offset) && \
+         ((offset)+(size) <= fastload_offset+fastload_length)) ? \
+        (memcpy( buffer, fastload+(offset)-fastload_offset, (size) ), TRUE) : \
+        (_llseek32( hFile, (offset), SEEK_SET), \
+         _lread32( hFile, (buffer), (size) ) == (size)))
+
+    _llseek32( hFile, 0, SEEK_SET );
+    if ((_lread32(hFile,&mz_header,sizeof(mz_header)) != sizeof(mz_header)) ||
+        (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
+        return (HMODULE16)11;  /* invalid exe */
+
+    _llseek32( hFile, mz_header.e_lfanew, SEEK_SET );
+    if (_lread32( hFile, &ne_header, sizeof(ne_header) ) != sizeof(ne_header))
+        return (HMODULE16)11;  /* invalid exe */
+
+    if (ne_header.ne_magic == IMAGE_NT_SIGNATURE) return (HMODULE16)21;  /* win32 exe */
+    if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE) return (HMODULE16)11;  /* invalid exe */
+
+    if (ne_header.ne_magic == IMAGE_OS2_SIGNATURE_LX) {
+      fprintf(stderr, "Sorry, this is an OS/2 linear executable (LX) file !\n");
+      return (HMODULE16)12;
+    }
+
+    /* We now have a valid NE header */
+
+    size = sizeof(NE_MODULE) +
+             /* loaded file info */
+           sizeof(OFSTRUCT)-sizeof(ofs->szPathName)+strlen(ofs->szPathName)+1+
+             /* segment table */
+           ne_header.n_segment_tab * sizeof(SEGTABLEENTRY) +
+             /* resource table */
+           ne_header.rname_tab_offset - ne_header.resource_tab_offset +
+             /* resident names table */
+           ne_header.moduleref_tab_offset - ne_header.rname_tab_offset +
+             /* module ref table */
+           ne_header.n_mod_ref_tab * sizeof(WORD) + 
+             /* imported names table */
+           ne_header.entry_tab_offset - ne_header.iname_tab_offset +
+             /* entry table length */
+           ne_header.entry_tab_length;
+
+    hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
+    if (!hModule) return (HMODULE16)11;  /* invalid exe */
+    FarSetOwner( hModule, hModule );
+    pModule = (NE_MODULE *)GlobalLock16( hModule );
+    memcpy( pModule, &ne_header, sizeof(ne_header) );
+    pModule->count = 0;
+    pModule->module32 = 0;
+    pModule->self = hModule;
+    pModule->self_loading_sel = 0;
+    pData = (BYTE *)(pModule + 1);
+
+    /* Clear internal Wine flags in case they are set in the EXE file */
+
+    pModule->flags &= ~(NE_FFLAGS_BUILTIN|NE_FFLAGS_WIN32|NE_FFLAGS_IMPLICIT);
+
+    /* Read the fast-load area */
+
+    if (ne_header.additional_flags & NE_AFLAGS_FASTLOAD)
+    {
+        fastload_offset=ne_header.fastload_offset<<ne_header.align_shift_count;
+        fastload_length=ne_header.fastload_length<<ne_header.align_shift_count;
+        TRACE(module, "Using fast-load area offset=%x len=%d\n",
+                        fastload_offset, fastload_length );
+        if ((fastload = HeapAlloc( SystemHeap, 0, fastload_length )) != NULL)
+        {
+            _llseek32( hFile, fastload_offset, SEEK_SET);
+            if (_lread32(hFile, fastload, fastload_length) != fastload_length)
+            {
+                HeapFree( SystemHeap, 0, fastload );
+                fprintf(stderr, "Error reading fast-load area !\n");
+                fastload = NULL;
+            }
+        }
+    }
+
+    /* Store the filename information */
+
+    pModule->fileinfo = (int)pData - (int)pModule;
+    size = sizeof(OFSTRUCT)-sizeof(ofs->szPathName)+strlen(ofs->szPathName)+1;
+    memcpy( pData, ofs, size );
+    ((OFSTRUCT *)pData)->cBytes = size - 1;
+    pData += size;
+
+    /* Get the segment table */
+
+    pModule->seg_table = (int)pData - (int)pModule;
+    buffer = HeapAlloc( SystemHeap, 0, ne_header.n_segment_tab *
+                                      sizeof(struct ne_segment_table_entry_s));
+    if (buffer)
+    {
+        int i;
+        struct ne_segment_table_entry_s *pSeg;
+
+        if (!READ( mz_header.e_lfanew + ne_header.segment_tab_offset,
+             ne_header.n_segment_tab * sizeof(struct ne_segment_table_entry_s),
+             buffer ))
+        {
+            HeapFree( SystemHeap, 0, buffer );
+            if (fastload) HeapFree( SystemHeap, 0, fastload );
+            GlobalFree16( hModule );
+            return (HMODULE16)11;  /* invalid exe */
+        }
+        pSeg = (struct ne_segment_table_entry_s *)buffer;
+        for (i = ne_header.n_segment_tab; i > 0; i--, pSeg++)
+        {
+            memcpy( pData, pSeg, sizeof(*pSeg) );
+            pData += sizeof(SEGTABLEENTRY);
+        }
+        HeapFree( SystemHeap, 0, buffer );
+    }
+    else
+    {
+        if (fastload) HeapFree( SystemHeap, 0, fastload );
+        GlobalFree16( hModule );
+        return (HMODULE16)11;  /* invalid exe */
+    }
+
+    /* Get the resource table */
+
+    if (ne_header.resource_tab_offset < ne_header.rname_tab_offset)
+    {
+        pModule->res_table = (int)pData - (int)pModule;
+        if (!READ(mz_header.e_lfanew + ne_header.resource_tab_offset,
+                  ne_header.rname_tab_offset - ne_header.resource_tab_offset,
+                  pData )) return (HMODULE16)11;  /* invalid exe */
+        pData += ne_header.rname_tab_offset - ne_header.resource_tab_offset;
+	NE_InitResourceHandler( hModule );
+    }
+    else pModule->res_table = 0;  /* No resource table */
+
+    /* Get the resident names table */
+
+    pModule->name_table = (int)pData - (int)pModule;
+    if (!READ( mz_header.e_lfanew + ne_header.rname_tab_offset,
+               ne_header.moduleref_tab_offset - ne_header.rname_tab_offset,
+               pData ))
+    {
+        if (fastload) HeapFree( SystemHeap, 0, fastload );
+        GlobalFree16( hModule );
+        return (HMODULE16)11;  /* invalid exe */
+    }
+    pData += ne_header.moduleref_tab_offset - ne_header.rname_tab_offset;
+
+    /* Get the module references table */
+
+    if (ne_header.n_mod_ref_tab > 0)
+    {
+        pModule->modref_table = (int)pData - (int)pModule;
+        if (!READ( mz_header.e_lfanew + ne_header.moduleref_tab_offset,
+                  ne_header.n_mod_ref_tab * sizeof(WORD),
+                  pData ))
+        {
+            if (fastload) HeapFree( SystemHeap, 0, fastload );
+            GlobalFree16( hModule );
+            return (HMODULE16)11;  /* invalid exe */
+        }
+        pData += ne_header.n_mod_ref_tab * sizeof(WORD);
+    }
+    else pModule->modref_table = 0;  /* No module references */
+
+    /* Get the imported names table */
+
+    pModule->import_table = (int)pData - (int)pModule;
+    if (!READ( mz_header.e_lfanew + ne_header.iname_tab_offset, 
+               ne_header.entry_tab_offset - ne_header.iname_tab_offset,
+               pData ))
+    {
+        if (fastload) HeapFree( SystemHeap, 0, fastload );
+        GlobalFree16( hModule );
+        return (HMODULE16)11;  /* invalid exe */
+    }
+    pData += ne_header.entry_tab_offset - ne_header.iname_tab_offset;
+
+    /* Get the entry table */
+
+    pModule->entry_table = (int)pData - (int)pModule;
+    if (!READ( mz_header.e_lfanew + ne_header.entry_tab_offset,
+               ne_header.entry_tab_length,
+               pData ))
+    {
+        if (fastload) HeapFree( SystemHeap, 0, fastload );
+        GlobalFree16( hModule );
+        return (HMODULE16)11;  /* invalid exe */
+    }
+    pData += ne_header.entry_tab_length;
+
+    /* Free the fast-load area */
+
+#undef READ
+    if (fastload) HeapFree( SystemHeap, 0, fastload );
+
+    /* Get the non-resident names table */
+
+    if (ne_header.nrname_tab_length)
+    {
+        pModule->nrname_handle = GLOBAL_Alloc( 0, ne_header.nrname_tab_length,
+                                               hModule, FALSE, FALSE, FALSE );
+        if (!pModule->nrname_handle)
+        {
+            GlobalFree16( hModule );
+            return (HMODULE16)11;  /* invalid exe */
+        }
+        buffer = GlobalLock16( pModule->nrname_handle );
+        _llseek32( hFile, ne_header.nrname_tab_offset, SEEK_SET );
+        if (_lread32( hFile, buffer, ne_header.nrname_tab_length )
+              != ne_header.nrname_tab_length)
+        {
+            GlobalFree16( pModule->nrname_handle );
+            GlobalFree16( hModule );
+            return (HMODULE16)11;  /* invalid exe */
+        }
+    }
+    else pModule->nrname_handle = 0;
+
+    /* Allocate a segment for the implicitly-loaded DLLs */
+
+    if (pModule->modref_count)
+    {
+        pModule->dlls_to_init = GLOBAL_Alloc(GMEM_ZEROINIT,
+                                    (pModule->modref_count+1)*sizeof(HMODULE16),
+                                    hModule, FALSE, FALSE, FALSE );
+        if (!pModule->dlls_to_init)
+        {
+            if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
+            GlobalFree16( hModule );
+            return (HMODULE16)11;  /* invalid exe */
+        }
+    }
+    else pModule->dlls_to_init = 0;
+
+    NE_RegisterModule( pModule );
+    return hModule;
+}
+
+
+/***********************************************************************
+ *           NE_LoadDLLs
+ *
+ * Load all DLLs implicitly linked to a module.
+ */
+static BOOL32 NE_LoadDLLs( NE_MODULE *pModule )
+{
+    int i;
+    WORD *pModRef = (WORD *)((char *)pModule + pModule->modref_table);
+    WORD *pDLLs = (WORD *)GlobalLock16( pModule->dlls_to_init );
+
+    for (i = 0; i < pModule->modref_count; i++, pModRef++)
+    {
+        char buffer[256];
+        BYTE *pstr = (BYTE *)pModule + pModule->import_table + *pModRef;
+        memcpy( buffer, pstr + 1, *pstr );
+        strcpy( buffer + *pstr, ".dll" );
+        TRACE(module, "Loading '%s'\n", buffer );
+        if (!(*pModRef = MODULE_FindModule16( buffer )))
+        {
+            /* If the DLL is not loaded yet, load it and store */
+            /* its handle in the list of DLLs to initialize.   */
+            HMODULE16 hDLL;
+
+            if ((hDLL = MODULE_Load( buffer, NE_FFLAGS_IMPLICIT,
+                                     NULL, NULL, 0 )) == 2)
+            {
+                /* file not found */
+                char *p;
+
+                /* Try with prepending the path of the current module */
+                GetModuleFileName16( pModule->self, buffer, sizeof(buffer) );
+                if (!(p = strrchr( buffer, '\\' ))) p = buffer;
+                memcpy( p + 1, pstr + 1, *pstr );
+                strcpy( p + 1 + *pstr, ".dll" );
+                hDLL = MODULE_Load( buffer, NE_FFLAGS_IMPLICIT, NULL, NULL, 0);
+            }
+            if (hDLL < 32)
+            {
+                /* FIXME: cleanup what was done */
+
+                fprintf( stderr, "Could not load '%s' required by '%.*s', error = %d\n",
+                         buffer, *((BYTE*)pModule + pModule->name_table),
+                         (char *)pModule + pModule->name_table + 1, hDLL );
+                return FALSE;
+            }
+            *pModRef = GetExePtr( hDLL );
+            *pDLLs++ = *pModRef;
+        }
+        else  /* Increment the reference count of the DLL */
+        {
+            NE_MODULE *pOldDLL = MODULE_GetPtr16( *pModRef );
+            if (pOldDLL) pOldDLL->count++;
+        }
+    }
+    return TRUE;
+}
+
+
+/**********************************************************************
+ *	    NE_LoadModule
+ *
+ * Implementation of LoadModule().
+ *
+ * cmd_line must contain the whole command-line, including argv[0] (and
+ * without a preceding length byte).
+ * If cmd_line is NULL, the module is loaded as a library even if it is a .exe
+ */
+HINSTANCE16 NE_LoadModule( HFILE32 hFile, OFSTRUCT *ofs, UINT16 flags,
+                           LPCSTR cmd_line, LPCSTR env, UINT32 show_cmd )
+{
+    HMODULE16 hModule;
+    HINSTANCE16 hInstance;
+    NE_MODULE *pModule;
+
+    /* Create the module structure */
+
+    if ((hModule = NE_LoadExeHeader( hFile, ofs )) < 32) return hModule;
+
+    pModule = MODULE_GetPtr16( hModule );
+    pModule->flags |= flags; /* stamp implicitly loaded modules */
+
+    /* Allocate the segments for this module */
+
+    NE_CreateSegments( hModule );
+    hInstance = MODULE_CreateInstance( hModule, NULL, (cmd_line == NULL) );
+
+    /* Load the referenced DLLs */
+
+    if (!NE_LoadDLLs( pModule ))
+        return 2;  /* File not found (FIXME: free everything) */
+
+    /* Load the segments */
+
+    NE_LoadAllSegments( pModule );
+
+    /* Fixup the functions prologs */
+
+    NE_FixupPrologs( pModule );
+
+    /* Make sure the usage count is 1 on the first loading of  */
+    /* the module, even if it contains circular DLL references */
+
+    pModule->count = 1;
+
+    /* Call initialization rountines for all loaded DLLs. Note that
+     * when we load implicitly linked DLLs this will be done by InitTask().
+     */
+
+    if ((pModule->flags & (NE_FFLAGS_LIBMODULE | NE_FFLAGS_IMPLICIT)) ==
+                                                           NE_FFLAGS_LIBMODULE)
+        NE_InitializeDLLs( hModule );
+
+    /* Create a task for this instance */
+
+    if (cmd_line && !(pModule->flags & NE_FFLAGS_LIBMODULE))
+    {
+        PDB32 *pdb;
+
+	pModule->flags |= NE_FFLAGS_GUI;
+
+        pdb = PROCESS_Create( pModule, cmd_line, env, hInstance, 0, show_cmd );
+        if (pdb && (GetNumTasks() > 1)) Yield16();
+    }
+
+    return hInstance;
+}
diff --git a/loader/ne_resource.c b/loader/ne/resource.c
similarity index 66%
rename from loader/ne_resource.c
rename to loader/ne/resource.c
index abf688c..832be3b 100644
--- a/loader/ne_resource.c
+++ b/loader/ne/resource.c
@@ -1,10 +1,12 @@
 /*
+ * NE resource functions
  *
  * Copyright 1993 Robert J. Amstadt
  * Copyright 1995 Alexandre Julliard
- *	     1997 Alex Korobka
+ * Copyright 1997 Alex Korobka
  */
 
+#include <assert.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -20,7 +22,7 @@
 #include "resource.h"
 #include "debug.h"
 
-#define  NEXT_TYPEINFO(pTypeInfo) ((NE_TYPEINFO *)((char*)((pTypeInfo) + 1) + \
+#define NEXT_TYPEINFO(pTypeInfo) ((NE_TYPEINFO *)((char*)((pTypeInfo) + 1) + \
                                    (pTypeInfo)->count * sizeof(NE_NAMEINFO)))
 
 /***********************************************************************
@@ -181,7 +183,7 @@
                                         HRSRC16 hRsrc )
 {
     int  fd;
-    NE_MODULE* pModule = MODULE_GetPtr( hModule );
+    NE_MODULE* pModule = MODULE_GetPtr16( hModule );
     if ( pModule && (fd = MODULE_OpenFile( hModule )) >= 0)
     {
 	HGLOBAL16 handle;
@@ -194,7 +196,7 @@
 	if( hMemObj )
 	    handle = GlobalReAlloc16( hMemObj, pNameInfo->length << sizeShift, 0 );
 	else
-	    handle = NE_AllocResource( hModule, hRsrc, 0 );
+	    handle = AllocResource( hModule, hRsrc, 0 );
 
 	if( handle )
 	{
@@ -213,95 +215,131 @@
  */
 BOOL32 NE_InitResourceHandler( HMODULE16 hModule )
 {
-    NE_MODULE *pModule = MODULE_GetPtr( hModule );
+    NE_MODULE *pModule = MODULE_GetPtr16( hModule );
     NE_TYPEINFO *pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->res_table + 2);
 
     TRACE(resource,"InitResourceHandler[%04x]\n", hModule );
 
     while(pTypeInfo->type_id)
     {
-	pTypeInfo->resloader = (DWORD)&NE_DefResourceHandler;
+	pTypeInfo->resloader = (FARPROC16)&NE_DefResourceHandler;
 	pTypeInfo = NEXT_TYPEINFO(pTypeInfo);
     }
     return TRUE;
 }
 
-/***********************************************************************
- *           NE_SetResourceHandler
- */
-FARPROC32 NE_SetResourceHandler( HMODULE16 hModule, SEGPTR typeId, 
-				 FARPROC32 resourceHandler )
-{
-    NE_MODULE *pModule = MODULE_GetPtr( hModule );
-    NE_TYPEINFO *pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->res_table + 2);
-    FARPROC32  prevHandler = NULL;
 
-    do
+/**********************************************************************
+ *	SetResourceHandler	(KERNEL.43)
+ */
+FARPROC16 WINAPI SetResourceHandler( HMODULE16 hModule, SEGPTR typeId,
+                                     FARPROC16 resourceHandler )
+{
+    FARPROC16 prevHandler = NULL;
+    NE_MODULE *pModule = MODULE_GetPtr16( hModule );
+    NE_TYPEINFO *pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->res_table + 2);
+
+    if (!pModule || !pModule->res_table) return NULL;
+
+    TRACE( resource, "module=%04x type=%s\n",
+           hModule, debugres_a(PTR_SEG_TO_LIN(typeId)) );
+
+    for (;;)
     {
-	pTypeInfo = NE_FindTypeSection( pModule, pTypeInfo, typeId );
-        if( pTypeInfo )
-        {
-	    prevHandler = (FARPROC32)pTypeInfo->resloader;
-	    pTypeInfo->resloader = (DWORD)resourceHandler;
-	    pTypeInfo = NEXT_TYPEINFO(pTypeInfo);
-        }
-    } while( pTypeInfo );
+	if (!(pTypeInfo = NE_FindTypeSection( pModule, pTypeInfo, typeId )))
+            break;
+        prevHandler = pTypeInfo->resloader;
+        pTypeInfo->resloader = resourceHandler;
+        pTypeInfo = NEXT_TYPEINFO(pTypeInfo);
+    }
     return prevHandler;
 }
 
-/***********************************************************************
- *           NE_FindResource
+
+/**********************************************************************
+ *	    FindResource16    (KERNEL.60)
  */
-HRSRC16 NE_FindResource( HMODULE16 hModule, SEGPTR typeId, SEGPTR resId )
+HRSRC16 WINAPI FindResource16( HMODULE16 hModule, SEGPTR name, SEGPTR type )
 {
     NE_TYPEINFO *pTypeInfo;
     HRSRC16 hRsrc;
 
-    NE_MODULE *pModule = MODULE_GetPtr( hModule );
+    NE_MODULE *pModule = MODULE_GetPtr16( hModule );
     if (!pModule || !pModule->res_table) return 0;
-    pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->res_table + 2);
 
-    if (HIWORD(typeId) || HIWORD(resId))
+    assert( !__winelib );  /* Can't use Win16 resource functions in Winelib */
+
+    TRACE( resource, "module=%04x name=%s type=%s\n", 
+           hModule, debugres_a(PTR_SEG_TO_LIN(name)),
+           debugres_a(PTR_SEG_TO_LIN(type)) );
+
+    if (HIWORD(name))  /* Check for '#xxx' name */
     {
-        DWORD id = NE_FindNameTableId( pModule, typeId, resId );
+	char *ptr = PTR_SEG_TO_LIN( name );
+	if (ptr[0] == '#')
+	    if (!(name = (SEGPTR)atoi( ptr + 1 )))
+            {
+                WARN(resource, "Incorrect resource name: %s\n", ptr);
+                return 0;
+	    }
+    }
+
+    if (HIWORD(type))  /* Check for '#xxx' type */
+    {
+	char *ptr = PTR_SEG_TO_LIN( type );
+	if (ptr[0] == '#')
+            if (!(type = (SEGPTR)atoi( ptr + 1 )))
+            {
+                WARN(resource, "Incorrect resource type: %s\n", ptr);
+                return 0;
+            }
+    }
+
+    if (HIWORD(type) || HIWORD(name))
+    {
+        DWORD id = NE_FindNameTableId( pModule, type, name );
         if (id)  /* found */
         {
-            typeId = LOWORD(id);
-            resId  = HIWORD(id);
+            type = LOWORD(id);
+            name = HIWORD(id);
         }
     }
 
-    do
+    pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->res_table + 2);
+
+    for (;;)
     {
-	pTypeInfo = NE_FindTypeSection( pModule, pTypeInfo, typeId );
-        if( pTypeInfo )
-	{
-	    hRsrc = NE_FindResourceFromType(pModule, pTypeInfo, resId);
-	    if( hRsrc )
-	    {
-		TRACE(resource, "    Found id %08lx\n", resId );
-		return hRsrc;
-	    }
-	    TRACE(resource, "    Not found, going on\n" );
-	    pTypeInfo = NEXT_TYPEINFO(pTypeInfo);
-	}
-    } while( pTypeInfo );
+	if (!(pTypeInfo = NE_FindTypeSection( pModule, pTypeInfo, type )))
+            break;
+        if ((hRsrc = NE_FindResourceFromType(pModule, pTypeInfo, name)))
+        {
+            TRACE(resource, "    Found id %08lx\n", name );
+            return hRsrc;
+        }
+        TRACE(resource, "    Not found, going on\n" );
+        pTypeInfo = NEXT_TYPEINFO(pTypeInfo);
+    }
 
     WARN(resource, "failed!\n");
     return 0;
 }
 
 
-/***********************************************************************
- *           NE_AllocResource
+/**********************************************************************
+ *	    AllocResource    (KERNEL.66)
  */
-HGLOBAL16 NE_AllocResource( HMODULE16 hModule, HRSRC16 hRsrc, DWORD size )
+HGLOBAL16 WINAPI AllocResource( HMODULE16 hModule, HRSRC16 hRsrc, DWORD size)
 {
     NE_NAMEINFO *pNameInfo=NULL;
     WORD sizeShift;
 
-    NE_MODULE *pModule = MODULE_GetPtr( hModule );
-    if (!pModule || !pModule->res_table) return 0;
+    NE_MODULE *pModule = MODULE_GetPtr16( hModule );
+    if (!pModule || !pModule->res_table || !hRsrc) return 0;
+
+    TRACE( resource, "module=%04x res=%04x size=%ld\n", hModule, hRsrc, size );
+
+    assert( !__winelib );  /* Can't use Win16 resource functions in Winelib */
+
     sizeShift = *(WORD *)((char *)pModule + pModule->res_table);
     pNameInfo = (NE_NAMEINFO*)((char*)pModule + hRsrc);
     if (size < (DWORD)pNameInfo->length << sizeShift)
@@ -310,55 +348,84 @@
 }
 
 
-/***********************************************************************
- *           NE_AccessResource
+/**********************************************************************
+ *      DirectResAlloc    (KERNEL.168)
+ *
+ * Check Schulman, p. 232 for details
  */
-int NE_AccessResource( HMODULE16 hModule, HRSRC16 hRsrc )
+HGLOBAL16 WINAPI DirectResAlloc( HINSTANCE16 hInstance, WORD wType,
+                                 UINT16 wSize )
 {
-    NE_NAMEINFO *pNameInfo=NULL;
+    TRACE(resource,"(%04x,%04x,%04x)\n",
+                     hInstance, wType, wSize );
+    if (!(hInstance = GetExePtr( hInstance ))) return 0;
+    if(wType != 0x10)	/* 0x10 is the only observed value, passed from
+                           CreateCursorIndirect. */
+        fprintf(stderr, "DirectResAlloc: wType = %x\n", wType);
+    return GLOBAL_Alloc(GMEM_MOVEABLE, wSize, hInstance, FALSE, FALSE, FALSE);
+}
+
+
+/**********************************************************************
+ *	    AccessResource16    (KERNEL.64)
+ */
+INT16 WINAPI AccessResource16( HINSTANCE16 hModule, HRSRC16 hRsrc )
+{
     HFILE32 fd;
 
-    NE_MODULE *pModule = MODULE_GetPtr( hModule );
-    if (!pModule || !pModule->res_table) return -1;
-    pNameInfo = (NE_NAMEINFO*)((char*)pModule + hRsrc);
+    NE_MODULE *pModule = MODULE_GetPtr16( hModule );
+    if (!pModule || !pModule->res_table || !hRsrc) return -1;
+
+    TRACE(resource, "module=%04x res=%04x\n", hModule, hRsrc );
+
+    assert( !__winelib );  /* Can't use Win16 resource functions in Winelib */
 
     if ((fd = _lopen32( NE_MODULE_NAME(pModule), OF_READ )) != -1)
     {
         WORD sizeShift = *(WORD *)((char *)pModule + pModule->res_table);
+        NE_NAMEINFO *pNameInfo = (NE_NAMEINFO*)((char*)pModule + hRsrc);
         _llseek32( fd, (int)pNameInfo->offset << sizeShift, SEEK_SET );
     }
     return fd;
 }
 
 
-/***********************************************************************
- *           NE_SizeofResource
+/**********************************************************************
+ *	    SizeofResource16    (KERNEL.65)
  */
-DWORD NE_SizeofResource( HMODULE16 hModule, HRSRC16 hRsrc )
+DWORD WINAPI SizeofResource16( HMODULE16 hModule, HRSRC16 hRsrc )
 {
     NE_NAMEINFO *pNameInfo=NULL;
     WORD sizeShift;
 
-    NE_MODULE *pModule = MODULE_GetPtr( hModule );
+    NE_MODULE *pModule = MODULE_GetPtr16( hModule );
     if (!pModule || !pModule->res_table) return 0;
+
+    TRACE(resource, "module=%04x res=%04x\n", hModule, hRsrc );
+
+    assert( !__winelib );  /* Can't use Win16 resource functions in Winelib */
+
     sizeShift = *(WORD *)((char *)pModule + pModule->res_table);
     pNameInfo = (NE_NAMEINFO*)((char*)pModule + hRsrc);
     return (DWORD)pNameInfo->length << sizeShift;
 }
 
 
-/***********************************************************************
- *           NE_LoadResource
+/**********************************************************************
+ *	    LoadResource16    (KERNEL.61)
  */
-HGLOBAL16 NE_LoadResource( HMODULE16 hModule,  HRSRC16 hRsrc )
+HGLOBAL16 WINAPI LoadResource16( HMODULE16 hModule, HRSRC16 hRsrc )
 {
     NE_TYPEINFO *pTypeInfo;
     NE_NAMEINFO *pNameInfo = NULL;
-    NE_MODULE *pModule = MODULE_GetPtr( hModule );
+    NE_MODULE *pModule = MODULE_GetPtr16( hModule );
     int d;
 
+    TRACE( resource, "module=%04x res=%04x\n", hModule, hRsrc );
     if (!hRsrc || !pModule || !pModule->res_table) return 0;
 
+    assert( !__winelib );  /* Can't use Win16 resource functions in Winelib */
+
     /* First, verify hRsrc (just an offset from pModule to the needed pNameInfo) */
 
     d = pModule->res_table + 2;
@@ -383,7 +450,7 @@
 
     if (pNameInfo)
     {
-	RESOURCEHANDLER16 __r16loader;
+	RESOURCEHANDLER16 loader;
 	if (pNameInfo->handle
 	    && !(GlobalFlags16(pNameInfo->handle) & GMEM_DISCARDED))
 	{
@@ -394,16 +461,16 @@
 	else
 	{
 	    if (pTypeInfo->resloader)
-	  	__r16loader = (RESOURCEHANDLER16)pTypeInfo->resloader;
+	  	loader = (RESOURCEHANDLER16)pTypeInfo->resloader;
 	    else /* this is really bad */
 	    {
 		fprintf( stderr, "[%04x]: Missing resource handler!!!...\n", hModule);
-		__r16loader = NE_DefResourceHandler;
+		loader = NE_DefResourceHandler;
 	    }
 
 	    /* Finally call resource loader */
 
-	    if ((pNameInfo->handle = __r16loader(pNameInfo->handle, hModule, hRsrc)))
+	    if ((pNameInfo->handle = loader(pNameInfo->handle, hModule, hRsrc)))
 	    {
 		pNameInfo->usage++;
 		pNameInfo->flags |= NE_SEGFLAGS_LOADED;
@@ -415,28 +482,46 @@
 }
 
 
-/***********************************************************************
- *           NE_LockResource
+/**********************************************************************
+ *	    LockResource16    (KERNEL.62)
  */
-SEGPTR NE_LockResource( HMODULE16 hModule, HGLOBAL16 handle )
+/* 16-bit version */
+SEGPTR WINAPI WIN16_LockResource16( HGLOBAL16 handle )
 {
+    TRACE( resource, "handle=%04x\n", handle );
+    if (!handle) return (SEGPTR)0;
+
     /* May need to reload the resource if discarded */
 
     return (SEGPTR)WIN16_GlobalLock16( handle );
 }
 
+/* Winelib 16-bit version */
+LPVOID WINAPI LockResource16( HGLOBAL16 handle )
+{
+    assert( !__winelib );  /* Can't use Win16 resource functions in Winelib */
 
-/***********************************************************************
- *           NE_FreeResource
+    return (LPVOID)PTR_SEG_TO_LIN( WIN16_LockResource16( handle ) );
+}
+
+
+/**********************************************************************
+ *	    FreeResource16    (KERNEL.63)
  */
-BOOL32 NE_FreeResource( HMODULE16 hModule, HGLOBAL16 handle )
+BOOL16 WINAPI FreeResource16( HGLOBAL16 handle )
 {
     NE_TYPEINFO *pTypeInfo;
     NE_NAMEINFO *pNameInfo;
     WORD count;
+    HMODULE16 hModule  = GetExePtr( handle );
+    NE_MODULE *pModule = MODULE_GetPtr16( hModule );
 
-    NE_MODULE *pModule = MODULE_GetPtr( hModule );
     if (!handle || !pModule || !pModule->res_table) return handle;
+
+    TRACE(resource, "handle=%04x\n", handle );
+
+    assert( !__winelib );  /* Can't use Win16 resource functions in Winelib */
+
     pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->res_table + 2);
     while (pTypeInfo->type_id)
     {
diff --git a/loader/ne_image.c b/loader/ne/segment.c
similarity index 86%
rename from loader/ne_image.c
rename to loader/ne/segment.c
index 5bb1088..99f78ce 100644
--- a/loader/ne_image.c
+++ b/loader/ne/segment.c
@@ -1,10 +1,11 @@
 /*
- * NE modules
+ * NE segment loading
  *
  * Copyright 1993 Robert J. Amstadt
  * Copyright 1995 Alexandre Julliard
  */
 
+#include <assert.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
@@ -160,8 +161,11 @@
     read( fd, &count, sizeof(count) );
     if (!count) return TRUE;
 
-    TRACE(fixup, "Fixups for %*.*s, segment %d, selector %04x\n",
+    TRACE(fixup, "Fixups for %.*s, segment %d, selector %04x\n",
                    *((BYTE *)pModule + pModule->name_table),
+                   (char *)pModule + pModule->name_table + 1,
+                   segnum, pSeg->selector );
+    TRACE(segment, "Fixups for %.*s, segment %d, selector %04x\n",
                    *((BYTE *)pModule + pModule->name_table),
                    (char *)pModule + pModule->name_table + 1,
                    segnum, pSeg->selector );
@@ -194,10 +198,10 @@
 	  case NE_RELTYPE_ORDINAL:
             module = pModuleTable[rep->target1-1];
 	    ordinal = rep->target2;
-            address = MODULE_GetEntryPoint( module, ordinal );
+            address = NE_GetEntryPoint( module, ordinal );
             if (!address)
             {
-                NE_MODULE *pTarget = MODULE_GetPtr( module );
+                NE_MODULE *pTarget = MODULE_GetPtr16( module );
                 if (!pTarget)
                     fprintf( stderr, "Module not found: %04x, reference %d of module %*.*s\n",
                              module, rep->target1, 
@@ -212,7 +216,7 @@
             }
             if (TRACE_ON(fixup))
             {
-                NE_MODULE *pTarget = MODULE_GetPtr( module );
+                NE_MODULE *pTarget = MODULE_GetPtr16( module );
                 TRACE( fixup, "%d: %.*s.%d=%04x:%04x %s\n", i + 1, 
                        *((BYTE *)pTarget + pTarget->name_table),
                        (char *)pTarget + pTarget->name_table + 1,
@@ -227,20 +231,19 @@
             memcpy( buffer, func_name+1, *func_name );
             buffer[*func_name] = '\0';
             func_name = buffer;
-            ordinal = MODULE_GetOrdinal( module, func_name );
-
-            address = MODULE_GetEntryPoint( module, ordinal );
+            ordinal = NE_GetOrdinal( module, func_name );
+            address = NE_GetEntryPoint( module, ordinal );
 
             if (ERR_ON(fixup) && !address)
             {
-                NE_MODULE *pTarget = MODULE_GetPtr( module );
+                NE_MODULE *pTarget = MODULE_GetPtr16( module );
                 ERR(fixup, "Warning: no handler for %.*s.%s, setting to 0:0\n",
                     *((BYTE *)pTarget + pTarget->name_table),
                     (char *)pTarget + pTarget->name_table + 1, func_name );
             }
             if (TRACE_ON(fixup))
             {
-	        NE_MODULE *pTarget = MODULE_GetPtr( module );
+	        NE_MODULE *pTarget = MODULE_GetPtr16( module );
                 TRACE( fixup, "%d: %.*s.%s=%04x:%04x %s\n", i + 1, 
                        *((BYTE *)pTarget + pTarget->name_table),
                        (char *)pTarget + pTarget->name_table + 1,
@@ -252,7 +255,7 @@
 	  case NE_RELTYPE_INTERNAL:
 	    if ((rep->target1 & 0xff) == 0xff)
 	    {
-		address  = MODULE_GetEntryPoint( pModule->self, rep->target2 );
+		address  = NE_GetEntryPoint( pModule->self, rep->target2 );
 	    }
 	    else
 	    {
@@ -310,6 +313,7 @@
                     ERR(fixup,"Additive selector to %04x.Please report\n",*sp);
 		else
                     *sp = HIWORD(address);
+                break;
             default:
                 goto unknown;
             }
@@ -383,9 +387,9 @@
         if (!NE_LoadSegment( pModule, 1 )) return FALSE;
         selfloadheader = (SELFLOADHEADER *)
                           PTR_SEG_OFF_TO_LIN(pSegTable->selector, 0);
-        selfloadheader->EntryAddrProc = MODULE_GetEntryPoint(hselfload,27);
-        selfloadheader->MyAlloc  = MODULE_GetEntryPoint(hselfload,28);
-        selfloadheader->SetOwner = MODULE_GetEntryPoint(GetModuleHandle16("KERNEL"),403);
+        selfloadheader->EntryAddrProc = NE_GetEntryPoint(hselfload,27);
+        selfloadheader->MyAlloc  = NE_GetEntryPoint(hselfload,28);
+        selfloadheader->SetOwner = NE_GetEntryPoint(GetModuleHandle16("KERNEL"),403);
         pModule->self_loading_sel = GlobalHandleToSel(GLOBAL_Alloc(GMEM_ZEROINIT, 0xFF00, pModule->self, FALSE, FALSE, FALSE));
         oldstack = thdb->cur_stack;
         thdb->cur_stack = PTR_SEG_OFF_TO_SEGPTR(pModule->self_loading_sel,
@@ -420,63 +424,6 @@
 
 
 /***********************************************************************
- *           NE_LoadDLLs
- */
-BOOL32 NE_LoadDLLs( NE_MODULE *pModule )
-{
-    int i;
-    WORD *pModRef = (WORD *)((char *)pModule + pModule->modref_table);
-    WORD *pDLLs = (WORD *)GlobalLock16( pModule->dlls_to_init );
-
-    for (i = 0; i < pModule->modref_count; i++, pModRef++)
-    {
-        char buffer[256];
-        BYTE *pstr = (BYTE *)pModule + pModule->import_table + *pModRef;
-        memcpy( buffer, pstr + 1, *pstr );
-        strcpy( buffer + *pstr, ".dll" );
-        TRACE(module, "Loading '%s'\n", buffer );
-        if (!(*pModRef = MODULE_FindModule( buffer )))
-        {
-            /* If the DLL is not loaded yet, load it and store */
-            /* its handle in the list of DLLs to initialize.   */
-            HMODULE16 hDLL;
-
-            if ((hDLL = MODULE_Load( buffer, NE_FFLAGS_IMPLICIT,
-                                     NULL, NULL, 0 )) == 2)
-            {
-                /* file not found */
-                char *p;
-
-                /* Try with prepending the path of the current module */
-                GetModuleFileName16( pModule->self, buffer, sizeof(buffer) );
-                if (!(p = strrchr( buffer, '\\' ))) p = buffer;
-                memcpy( p + 1, pstr + 1, *pstr );
-                strcpy( p + 1 + *pstr, ".dll" );
-                hDLL = MODULE_Load( buffer, NE_FFLAGS_IMPLICIT, NULL, NULL, 0);
-            }
-            if (hDLL < 32)
-            {
-                /* FIXME: cleanup what was done */
-
-                fprintf( stderr, "Could not load '%s' required by '%.*s', error = %d\n",
-                         buffer, *((BYTE*)pModule + pModule->name_table),
-                         (char *)pModule + pModule->name_table + 1, hDLL );
-                return FALSE;
-            }
-            *pModRef = MODULE_HANDLEtoHMODULE16( hDLL );
-            *pDLLs++ = *pModRef;
-        }
-        else  /* Increment the reference count of the DLL */
-        {
-            NE_MODULE *pOldDLL = MODULE_GetPtr( *pModRef );
-            if (pOldDLL) pOldDLL->count++;
-        }
-    }
-    return TRUE;
-}
-
-
-/***********************************************************************
  *           NE_FixupPrologs
  *
  * Fixup the exported functions prologs.
@@ -589,7 +536,7 @@
      * es:si  command line (always 0)
      */
 
-    if (!(pModule = MODULE_GetPtr( hModule ))) return FALSE;
+    if (!(pModule = MODULE_GetPtr16( hModule ))) return FALSE;
     pSegTable = NE_SEG_TABLE( pModule );
 
     if (!(pModule->flags & NE_FFLAGS_LIBMODULE) ||
@@ -666,7 +613,7 @@
     NE_MODULE *pModule;
     HMODULE16 *pDLL;
 
-    if (!(pModule = MODULE_GetPtr( hModule ))) return;
+    if (!(pModule = MODULE_GetPtr16( hModule ))) return;
     if (pModule->flags & NE_FFLAGS_WIN32) return;
 
     if (pModule->dlls_to_init)
@@ -694,3 +641,72 @@
 {
 	fprintf(stderr,"PatchCodeHandle(%04x),stub!\n",hSel);
 }
+
+
+/***********************************************************************
+ *           NE_Ne2MemFlags
+ *
+ * This function translates NE segment flags to GlobalAlloc flags
+ */
+static WORD NE_Ne2MemFlags(WORD flags)
+{ 
+    WORD memflags = 0;
+#if 0
+    if (flags & NE_SEGFLAGS_DISCARDABLE) 
+      memflags |= GMEM_DISCARDABLE;
+    if (flags & NE_SEGFLAGS_MOVEABLE || 
+	( ! (flags & NE_SEGFLAGS_DATA) &&
+	  ! (flags & NE_SEGFLAGS_LOADED) &&
+	  ! (flags & NE_SEGFLAGS_ALLOCATED)
+	 )
+	)
+      memflags |= GMEM_MOVEABLE;
+    memflags |= GMEM_ZEROINIT;
+#else
+    memflags = GMEM_ZEROINIT | GMEM_FIXED;
+    return memflags;
+#endif
+}
+
+/***********************************************************************
+ *           NE_AllocateSegment (WPROCS.26)
+ */
+DWORD WINAPI NE_AllocateSegment( WORD wFlags, WORD wSize, WORD wElem )
+{
+    WORD size = wSize << wElem;
+    HANDLE16 hMem = GlobalAlloc16( NE_Ne2MemFlags(wFlags), size);
+    return MAKELONG( hMem, GlobalHandleToSel(hMem) );
+}
+
+
+/***********************************************************************
+ *           NE_CreateSegments
+ */
+BOOL32 NE_CreateSegments( HMODULE16 hModule )
+{
+    SEGTABLEENTRY *pSegment;
+    NE_MODULE *pModule;
+    int i, minsize;
+
+    if (!(pModule = MODULE_GetPtr16( hModule ))) return FALSE;
+    assert( !(pModule->flags & NE_FFLAGS_WIN32) );
+
+    pSegment = NE_SEG_TABLE( pModule );
+    for (i = 1; i <= pModule->seg_count; i++, pSegment++)
+    {
+        minsize = pSegment->minsize ? pSegment->minsize : 0x10000;
+        if (i == pModule->ss) minsize += pModule->stack_size;
+	/* The DGROUP is allocated by MODULE_CreateInstance */
+        if (i == pModule->dgroup) continue;
+        pSegment->selector = GLOBAL_Alloc( NE_Ne2MemFlags(pSegment->flags),
+                                      minsize, hModule,
+                                      !(pSegment->flags & NE_SEGFLAGS_DATA),
+                                      FALSE,
+                            FALSE /*pSegment->flags & NE_SEGFLAGS_READONLY*/ );
+        if (!pSegment->selector) return FALSE;
+    }
+
+    pModule->dgroup_entry = pModule->dgroup ? pModule->seg_table +
+                            (pModule->dgroup - 1) * sizeof(SEGTABLEENTRY) : 0;
+    return TRUE;
+}
diff --git a/loader/pe_image.c b/loader/pe_image.c
index 43cc74c..12c962e 100644
--- a/loader/pe_image.c
+++ b/loader/pe_image.c
@@ -49,6 +49,7 @@
 #include "winbase.h"
 #include "callback.h"
 #include "file.h"
+#include "heap.h"
 #include "neexe.h"
 #include "peexe.h"
 #include "process.h"
@@ -59,11 +60,13 @@
 #include "task.h"
 #include "debug.h"
 
-static void PE_InitDLL(PE_MODREF* modref, DWORD type, LPVOID lpReserved);
+static void PE_InitDLL(WINE_MODREF *wm, DWORD type, LPVOID lpReserved);
 
 /* convert PE image VirtualAddress to Real Address */
 #define RVA(x) ((unsigned int)load_addr+(unsigned int)(x))
 
+#define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
+
 void dump_exports( HMODULE32 hModule )
 { 
   char		*Module;
@@ -116,44 +119,40 @@
  * If it is a ordinal:
  *	- use ordinal-pe_export->Base as offset into the functionlist
  */
-FARPROC32 PE_FindExportedFunction( PDB32 *process, HMODULE32 hModule,
-                                   LPCSTR funcName)
+FARPROC32 PE_FindExportedFunction( 
+	PDB32 *process,		/* [in] process context */
+	WINE_MODREF *wm,	/* [in] WINE modreference */
+	LPCSTR funcName )	/* [in] function name */
 {
-	IMAGE_EXPORT_DIRECTORY 		*exports;
-	unsigned			load_addr;
 	u_short				* ordinal;
 	u_long				* function;
 	u_char				** name, *ename;
 	int				i;
-	PE_MODREF			*pem;
+	PE_MODREF			*pem = &(wm->binfmt.pe);
+	IMAGE_EXPORT_DIRECTORY 		*exports = pem->pe_export;
+	unsigned int			load_addr = wm->module;
 	u_long				rva_start, rva_end, addr;
 	char				* forward;
 
-	pem = process->modref_list;
-	while (pem && (pem->module != hModule))
-		pem=pem->next;
-	if (!pem) {
-		fprintf(stderr,"No MODREF found for PE_MODULE %08x in process %p\n",hModule,process);
-		return NULL;
-	}
-	load_addr = hModule;
-	exports   = pem->pe_export;
-
 	if (HIWORD(funcName))
 		TRACE(win32,"(%s)\n",funcName);
 	else
 		TRACE(win32,"(%d)\n",(int)funcName);
 	if (!exports) {
-		fprintf(stderr,"Module %08x/MODREF %p doesn't have a exports table.\n",hModule,pem);
+		/* Not a fatal problem, some apps do
+		 * GetProcAddress(0,"RegisterPenApp") which triggers this
+		 * case.
+		 */
+		WARN(win32,"Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm->module,wm->modname,pem);
 		return NULL;
 	}
 	ordinal	= (u_short*)  RVA(exports->AddressOfNameOrdinals);
 	function= (u_long*)   RVA(exports->AddressOfFunctions);
 	name	= (u_char **) RVA(exports->AddressOfNames);
 	forward = NULL;
-	rva_start = PE_HEADER(hModule)->OptionalHeader
+	rva_start = PE_HEADER(wm->module)->OptionalHeader
 		.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
-	rva_end = rva_start + PE_HEADER(hModule)->OptionalHeader
+	rva_end = rva_start + PE_HEADER(wm->module)->OptionalHeader
 		.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
 
 	if (HIWORD(funcName)) {
@@ -188,23 +187,30 @@
                 HMODULE32 hMod;
 		char module[256];
 		char *end = strchr(forward, '.');
+
 		if (!end) return NULL;
+		assert(end-forward<256);
 		strncpy(module, forward, (end - forward));
 		module[end-forward] = 0;
-                hMod = MODULE_HANDLEtoHMODULE32( MODULE_FindModule(module) );
-		return PE_FindExportedFunction( process, hMod, end + 1);
+                hMod = MODULE_FindModule32(process,module);
+		assert(hMod);
+		return MODULE_GetProcAddress32( process, hMod, end + 1);
 	}
 	return NULL;
 }
 
-DWORD fixup_imports (PDB32 *process,PE_MODREF *pem)
+DWORD fixup_imports (PDB32 *process,WINE_MODREF *wm)
 {
     IMAGE_IMPORT_DESCRIPTOR	*pe_imp;
+    WINE_MODREF			*xwm;
+    PE_MODREF			*pem;
     int	fixup_failed		= 0;
-    unsigned int load_addr	= pem->module;
+    unsigned int load_addr	= wm->module;
     int				i;
     char			*modname;
     
+    assert(wm->type==MODULE32_PE);
+    pem = &(wm->binfmt.pe);
     if (pem->pe_export)
     	modname = (char*) RVA(pem->pe_export->Name);
     else
@@ -229,10 +235,8 @@
     /* FIXME: should terminate on 0 Characteristics */
     for (i = 0, pe_imp = pem->pe_import; pe_imp->Name; pe_imp++) {
     	HMODULE32	res;
-	PE_MODREF	*xpem,**ypem;
-
-
- 	char *name = (char *) RVA(pe_imp->Name);
+	WINE_MODREF	**ywm;
+ 	char		*name = (char *) RVA(pe_imp->Name);
 
 	/* don't use MODULE_Load, Win32 creates new task differently */
 	res = PE_LoadLibraryEx32A( name, process, 0, 0 );
@@ -240,7 +244,7 @@
 	    char buffer[1024];
 
 	    /* Try with prepending the path of the current module */
-	    if (GetModuleFileName32A( pem->module, buffer, sizeof (buffer))) {
+	    if (GetModuleFileName32A( wm->module, buffer, sizeof (buffer))) {
 	        char *p;
 
 		if (!(p = strrchr (buffer, '\\')))
@@ -251,36 +255,35 @@
 	    	ERR(win32,"cannot find the module just loaded!\n");
 	}
 	if (res <= (HMODULE32) 32) {
-	    fprintf (stderr, "Module %s not found\n", name);
+	    WARN (module, "Module %s not found\n", name);
 	    return res;
 	}
-	res = MODULE_HANDLEtoHMODULE32(res);
-	xpem = pem->next;
-	while (xpem) {
-		if (xpem->module == res)
+	xwm = wm->next;
+	while (xwm) {
+		if (xwm->module == res)
 			break;
-		xpem = xpem->next;
+		xwm = xwm->next;
 	}
-	if (xpem) {
+	if (xwm) {
 		/* It has been loaded *BEFORE* us, so we have to initialize
-		 * it before us. We cannot just link in the xpem before pem,
-		 * since xpem might reference more dlls which would be in the
+		 * it before us. We cannot just link in the xwm before wm,
+		 * since xwm might reference more dlls which would be in the
 		 * wrong order after that.
-		 * Instead we link in pem right AFTER xpem, which should keep
+		 * Instead we link in wm right AFTER xwm, which should keep
 		 * the correct order. (I am not 100% sure about that.)
 		 */
-		/* unlink pem from chain */
-		ypem = &(process->modref_list);
-		while (*ypem) {
-			if ((*ypem)==pem)
+		/* unlink wm from chain */
+		ywm = &(process->modref_list);
+		while (*ywm) {
+			if ((*ywm)==wm)
 				break;
-			ypem = &((*ypem)->next);
+			ywm = &((*ywm)->next);
 		}
-		*ypem		= pem->next;
+		*ywm		= wm->next;
 
-		/* link pem directly AFTER xpem */
-		pem->next	= xpem->next;
-		xpem->next	= pem;
+		/* link wm directly AFTER xwm */
+		wm->next	= xwm->next;
+		xwm->next	= wm;
 		
 	}
 	i++;
@@ -293,7 +296,8 @@
         HMODULE32 hImpModule;
 
 	Module = (char *) RVA(pe_imp->Name);
-        hImpModule = MODULE_HANDLEtoHMODULE32( MODULE_FindModule(Module) );
+        hImpModule = MODULE_FindModule32(process,Module);
+	assert(hImpModule); /* we have imported it, so it MUST be there */
 	TRACE(win32, "%s\n", Module);
 
 	/* FIXME: forwarder entries ... */
@@ -308,20 +312,22 @@
 		    int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
 
 		    TRACE(win32, "--- Ordinal %s,%d\n", Module, ordinal);
-		    thunk_list->u1.Function=(LPDWORD)PE_FindExportedFunction(
-                        process, hImpModule, (LPCSTR)ordinal);
+		    thunk_list->u1.Function=(LPDWORD)MODULE_GetProcAddress32(
+                        process, hImpModule, (LPCSTR)ordinal
+		    );
 		    if (!thunk_list->u1.Function) {
-			fprintf(stderr,"No implementation for %s.%d, setting to NULL\n",
+			WARN(win32,"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);
 		    TRACE(win32, "--- %s %s.%d\n", pe_name->Name, Module, pe_name->Hint);
-		    thunk_list->u1.Function=(LPDWORD)PE_FindExportedFunction(
-                        process, hImpModule, pe_name->Name);
+		    thunk_list->u1.Function=(LPDWORD)MODULE_GetProcAddress32(
+                        process, hImpModule, pe_name->Name
+		    );
 		    if (!thunk_list->u1.Function) {
-			fprintf(stderr,"No implementation for %s.%d(%s), setting to NULL\n",
+			WARN(win32,"No implementation for %s.%d(%s), setting to NULL\n",
 				Module,pe_name->Hint,pe_name->Name);
 			/* fixup_failed=1; */
 		    }
@@ -338,10 +344,11 @@
 		    int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
 
 		    TRACE(win32,"--- Ordinal %s.%d\n",Module,ordinal);
-		    thunk_list->u1.Function=(LPDWORD)PE_FindExportedFunction(
-                        process, hImpModule, (LPCSTR) ordinal);
+		    thunk_list->u1.Function=(LPDWORD)MODULE_GetProcAddress32(
+                        process, hImpModule, (LPCSTR) ordinal
+		    );
 		    if (!thunk_list->u1.Function) {
-			fprintf(stderr, "No implementation for %s.%d, setting to NULL\n",
+			WARN(win32, "No implementation for %s.%d, setting to NULL\n",
 				Module,ordinal);
 			/* fixup_failed=1; */
 		    }
@@ -349,10 +356,11 @@
 		    pe_name=(LPIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
 		    TRACE(win32,"--- %s %s.%d\n",
 		   		  pe_name->Name,Module,pe_name->Hint);
-		    thunk_list->u1.Function=(LPDWORD)PE_FindExportedFunction(
-                        process, hImpModule, pe_name->Name );
+		    thunk_list->u1.Function=(LPDWORD)MODULE_GetProcAddress32(
+                        process, hImpModule, pe_name->Name
+		    );
 		    if (!thunk_list->u1.Function) {
-		    	fprintf(stderr, "No implementation for %s.%d, setting to NULL\n",
+		    	WARN(win32, "No implementation for %s.%d, setting to NULL\n",
 				Module, pe_name->Hint);
 		    	/* fixup_failed=1; */
 		    }
@@ -392,10 +400,12 @@
     return vma_size;
 }
 
-static void do_relocations(PE_MODREF *pem)
+static void do_relocations(WINE_MODREF *wm)
 {
-    int delta = pem->module - PE_HEADER(pem->module)->OptionalHeader.ImageBase;
-    unsigned int load_addr= pem->module;
+    PE_MODREF	*pem = &(wm->binfmt.pe);
+    int delta = wm->module - PE_HEADER(wm->module)->OptionalHeader.ImageBase;
+    unsigned int load_addr= wm->module;
+
 	IMAGE_BASE_RELOCATION		*r = pem->pe_reloc;
 	int				hdelta = (delta >> 16) & 0xFFFF;
 	int				ldelta = delta & 0xFFFF;
@@ -438,13 +448,13 @@
 #endif
 				break;
 			case IMAGE_REL_BASED_HIGHADJ:
-				fprintf(stderr, "Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
+				WARN(win32, "Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
 				break;
 			case IMAGE_REL_BASED_MIPS_JMPADDR:
-				fprintf(stderr, "Is this a MIPS machine ???\n");
+				WARN(win32, "Is this a MIPS machine ???\n");
 				break;
 			default:
-				fprintf(stderr, "Unknown fixup type\n");
+				WARN(win32, "Unknown fixup type\n");
 				break;
 			}
 		}
@@ -476,7 +486,7 @@
                                     0, 0, NULL );
     if (!mapping)
     {
-        fprintf( stderr, "PE_LoadImage: CreateFileMapping error %ld\n",
+        WARN( win32, "CreateFileMapping error %ld\n",
                  GetLastError() );
         return 0;
     }
@@ -484,34 +494,33 @@
     CloseHandle( mapping );
     if (!hModule)
     {
-        fprintf( stderr, "PE_LoadImage: MapViewOfFile error %ld\n",
+        WARN( win32, "PE_LoadImage: MapViewOfFile error %ld\n",
                  GetLastError() );
         return 0;
     }
 
     if (PE_HEADER(hModule)->Signature != IMAGE_NT_SIGNATURE)
     {
-        fprintf(stderr,"image doesn't have PE signature, but 0x%08lx\n",
+        WARN(win32,"image doesn't have PE signature, but 0x%08lx\n",
                 PE_HEADER(hModule)->Signature );
         goto error;
     }
 
     if (PE_HEADER(hModule)->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
     {
-        fprintf(stderr,"trying to load PE image for unsupported architecture (");
+        MSG("Trying to load PE image for unsupported architecture (");
         switch (PE_HEADER(hModule)->FileHeader.Machine)
         {
-        case IMAGE_FILE_MACHINE_UNKNOWN: fprintf(stderr,"Unknown"); break;
-        case IMAGE_FILE_MACHINE_I860:    fprintf(stderr,"I860"); break;
-        case IMAGE_FILE_MACHINE_R3000:   fprintf(stderr,"R3000"); break;
-        case IMAGE_FILE_MACHINE_R4000:   fprintf(stderr,"R4000"); break;
-        case IMAGE_FILE_MACHINE_R10000:  fprintf(stderr,"R10000"); break;
-        case IMAGE_FILE_MACHINE_ALPHA:   fprintf(stderr,"Alpha"); break;
-        case IMAGE_FILE_MACHINE_POWERPC: fprintf(stderr,"PowerPC"); break;
-        default: fprintf(stderr,"Unknown-%04x",
+        case IMAGE_FILE_MACHINE_UNKNOWN: MSG("Unknown\n"); break;
+        case IMAGE_FILE_MACHINE_I860:    MSG("I860\n"); break;
+        case IMAGE_FILE_MACHINE_R3000:   MSG("R3000\n"); break;
+        case IMAGE_FILE_MACHINE_R4000:   MSG("R4000\n"); break;
+        case IMAGE_FILE_MACHINE_R10000:  MSG("R10000\n"); break;
+        case IMAGE_FILE_MACHINE_ALPHA:   MSG("Alpha\n"); break;
+        case IMAGE_FILE_MACHINE_POWERPC: MSG("PowerPC\n"); break;
+        default: MSG("Unknown-%04x\n",
                          PE_HEADER(hModule)->FileHeader.Machine); break;
         }
-        fprintf(stderr,")\n");
         goto error;
     }
     return hModule;
@@ -527,6 +536,7 @@
 static BOOL32 PE_MapImage( HMODULE32 *phModule, PDB32 *process,
                            OFSTRUCT *ofs, DWORD flags )
 {
+	WINE_MODREF		*wm;
 	PE_MODREF		*pem;
 	int			i, result;
 	DWORD			load_addr;
@@ -539,17 +549,21 @@
         IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER *)hModule;
         IMAGE_NT_HEADERS *nt_header = PE_HEADER(hModule);
 	
-	pem = (PE_MODREF*)HeapAlloc(process->heap,HEAP_ZERO_MEMORY,
-                                    sizeof(*pem));
+
+	wm = (WINE_MODREF*)HeapAlloc(process->heap,HEAP_ZERO_MEMORY,
+                                    sizeof(*wm));
+	wm->type= MODULE32_PE;
+	pem 	= &(wm->binfmt.pe);
+
 	/* NOTE: fixup_imports takes care of the correct order */
-	pem->next	= process->modref_list;
-	process->modref_list = pem;
+	wm->next	= process->modref_list;
+	process->modref_list = wm;
 
 	if (!(nt_header->FileHeader.Characteristics & IMAGE_FILE_DLL))
         {
 		if (process->exe_modref)
-			fprintf(stderr,"overwriting old exe_modref... arrgh\n");
-		process->exe_modref = pem;
+			WARN(win32,"overwriting old exe_modref... arrgh\n");
+		process->exe_modref = wm;
 	}
 
 	load_addr = nt_header->OptionalHeader.ImageBase;
@@ -566,10 +580,13 @@
 	/* *phModule is the module32 entry in the NE_MODULE. We need to
 	 * change it here, since it can get referenced by fixup_imports()
 	 */
-	pem->module = *phModule = (HMODULE32)load_addr;
+	wm->module = *phModule = (HMODULE32)load_addr;
 
 	TRACE(win32, "Load addr is really %lx, range %x\n",
                       load_addr, vma_size);
+
+	TRACE(segment, "Loading %s at %lx, range %x\n",
+              ofs->szPathName, load_addr, vma_size );
 	
         /* Store the NT header at the load addr
          * (FIXME: should really use mmap)
@@ -620,7 +637,7 @@
 	if(dir.Size)
 	{
 		if(pem->pe_export && (int)pem->pe_export!=RVA(dir.VirtualAddress))
-			fprintf(stderr,"wrong export directory??\n");
+			WARN(win32,"wrong export directory??\n");
 		/* always trust the directory */
 		pem->pe_export = (LPIMAGE_EXPORT_DIRECTORY) RVA(dir.VirtualAddress);
 	}
@@ -630,7 +647,7 @@
 	{
 		/* 
 		if(pem->pe_import && (int)pem->pe_import!=RVA(dir.VirtualAddress))
-			fprintf(stderr,"wrong import directory??\n");
+			WARN(win32,"wrong import directory??\n");
 		 */
 		pem->pe_import = (LPIMAGE_IMPORT_DESCRIPTOR) RVA(dir.VirtualAddress);
 	}
@@ -639,7 +656,7 @@
 	if(dir.Size)
 	{
 		if(pem->pe_resource && (int)pem->pe_resource!=RVA(dir.VirtualAddress))
-			fprintf(stderr,"wrong resource directory??\n");
+			WARN(win32,"wrong resource directory??\n");
 		pem->pe_resource = (LPIMAGE_RESOURCE_DIRECTORY) RVA(dir.VirtualAddress);
 	}
 
@@ -655,7 +672,7 @@
 	if(dir.Size)
 	{
 		if(pem->pe_reloc && (int)pem->pe_reloc!= RVA(dir.VirtualAddress))
-			fprintf(stderr,"wrong relocation list??\n");
+			WARN(win32,"wrong relocation list??\n");
 		pem->pe_reloc = (void *) RVA(dir.VirtualAddress);
 	}
 
@@ -685,20 +702,33 @@
 	if(nt_header->OptionalHeader.DataDirectory[15].Size)
 		FIXME(win32,"Unknown directory 15 ignored\n");
 
-	if(pem->pe_reloc)	do_relocations(pem);
-	if(pem->pe_export)	dump_exports(pem->module);
+	if(pem->pe_reloc)	do_relocations(wm);
+	if(pem->pe_export) {
+		dump_exports(wm->module);
+
+		wm->modname = HEAP_strdupA(process->heap,0,(char*)RVA(pem->pe_export->Name));
+	} else {
+		/* try to find out the name from the OFSTRUCT */
+		char *s;
+		modname = s = ofs->szPathName;
+		while ((s=strchr(modname,'\\')))
+			modname = s+1;
+		if ((s=strchr(modname,'.')))
+			*s='\0';
+		wm->modname = HEAP_strdupA(process->heap,0,modname);
+	}
 	if(pem->pe_import)	{
-		if (fixup_imports(process,pem)) {
-			PE_MODREF	**xpem;
+		if (fixup_imports(process,wm)) {
+			WINE_MODREF	**xwm;
 
 			/* remove entry from modref chain */
-			xpem = &(process->modref_list);
-			while (*xpem) {
-				if (*xpem==pem) {
-					*xpem = pem->next;
+			xwm = &(process->modref_list);
+			while (*xwm) {
+				if (*xwm==wm) {
+					*xwm = wm->next;
 					break;
 				}
-				xpem = &((*xpem)->next);
+				xwm = &((*xwm)->next);
 			}
 			/* FIXME: there are several more dangling references
 			 * left. Including dlls loaded by this dll before the
@@ -710,17 +740,6 @@
 		}
 	}
   		
-	if (pem->pe_export)
-		modname = (char*)RVA(pem->pe_export->Name);
-	else {
-		char *s;
-		modname = s = ofs->szPathName;
-		while ((s=strchr(modname,'\\')))
-			modname = s+1;
-		if ((s=strchr(modname,'.')))
-			*s='\0';
-	}
-
         /* Now that we got everything at the right address,
          * we can unmap the previous module */
         UnmapViewOfFile( (LPVOID)hModule );
@@ -738,71 +757,52 @@
 	OFSTRUCT	ofs;
 	HMODULE32	hModule;
 	NE_MODULE	*pModule;
-	PE_MODREF	*pem;
+	WINE_MODREF	*wm;
 
-	if ((hModule = MODULE_FindModule( name ))) {
-		/* the .DLL is either loaded or internal */
-		hModule = MODULE_HANDLEtoHMODULE32(hModule);
-		if (!HIWORD(hModule)) /* internal (or bad) */
-			return hModule;
-		/* check if this module is already mapped */
-		pem 	= process->modref_list;
-		pModule = MODULE_GetPtr(hModule);
-		while (pem) {
-			if (pem->module == hModule) {
+	if ((hModule = MODULE_FindModule32( process, name ))) {
+		
+		pModule = MODULE_GetPtr32(hModule);
+		for (wm= process->modref_list;wm;wm=wm->next)
+			if (wm->module == hModule) {
 				pModule->count++;
 				return hModule;
 			}
-			pem = pem->next;
-		}
-		if (pModule->flags & NE_FFLAGS_BUILTIN) {
-			IMAGE_DOS_HEADER	*dh;
-			IMAGE_NT_HEADERS	*nh;
-			IMAGE_SECTION_HEADER	*sh;
-
-			/* we only come here if we already have 'loaded' the
-			 * internal dll but in another process. Just create
-			 * a PE_MODREF and return.
-			 */
-			pem = (PE_MODREF*)HeapAlloc(process->heap,
-				HEAP_ZERO_MEMORY,sizeof(*pem));
-			pem->module 	     = hModule;
-			dh = (IMAGE_DOS_HEADER*)pem->module;
-			nh = (IMAGE_NT_HEADERS*)(dh+1);
-			sh = (IMAGE_SECTION_HEADER*)(nh+1);
-			pem->pe_export	     = (IMAGE_EXPORT_DIRECTORY*)(sh+2);
-			pem->next	     = process->modref_list;
-			process->modref_list = pem;
-			return hModule;
-		}
-	} else {
-
-		/* try to load builtin, enabled modules first */
-		if ((hModule = BUILTIN32_LoadModule( name, FALSE, process )))
-                    return MODULE_HANDLEtoHMODULE32( hModule );
-
-		/* try to open the specified file */
-		if (HFILE_ERROR32==(hFile=OpenFile32(name,&ofs,OF_READ))) {
-			/* Now try the built-in even if disabled */
-			if ((hModule = BUILTIN32_LoadModule( name, TRUE, process ))) {
-				fprintf( stderr, "Warning: could not load Windows DLL '%s', using built-in module.\n", name );
-                                return MODULE_HANDLEtoHMODULE32( hModule );
-			}
-			return 1;
-		}
-		if ((hModule = MODULE_CreateDummyModule( &ofs )) < 32) {
-			_lclose32(hFile);
-			return hModule;
-		}
-		pModule		= (NE_MODULE *)GlobalLock16( hModule );
-		pModule->flags	= NE_FFLAGS_WIN32;
-		pModule->module32 = PE_LoadImage( hFile );
-		CloseHandle( hFile );
-		if (pModule->module32 < 32) return 21;
+		/* Since MODULE_FindModule32 uses the modref chain too, the
+		 * module MUST have been found above. If not, something has gone
+		 * terribly wrong.
+		 */
+		assert(0);
 	}
-	/* recurse */
+	/* try to load builtin, enabled modules first */
+	if ((hModule = BUILTIN32_LoadModule( name, FALSE, process )))
+	    return hModule;
+
+	/* try to load the specified dll/exe */
+	if (HFILE_ERROR32==(hFile=OpenFile32(name,&ofs,OF_READ))) {
+		/* Now try the built-in even if disabled */
+		if ((hModule = BUILTIN32_LoadModule( name, TRUE, process ))) {
+			fprintf( stderr, "Warning: could not load external DLL '%s', using built-in module.\n", name );
+			return hModule;
+		}
+		return 1;
+	}
+	if ((hModule = MODULE_CreateDummyModule( &ofs )) < 32) {
+		_lclose32(hFile);
+		return hModule;
+	}
+	pModule		= (NE_MODULE *)GlobalLock16( hModule );
+	pModule->flags	= NE_FFLAGS_WIN32;
+	pModule->module32 = PE_LoadImage( hFile );
+	CloseHandle( hFile );
+        if (pModule->module32 < 32) 
+        {
+            FreeLibrary32( hModule);
+            return 21; /* FIXME: probably 0 */
+        }
+
+	/* (possible) recursion */
 	if (!PE_MapImage( &(pModule->module32), process, &ofs,flags)) {
-		/* should free this module and the already referenced ones */
+		/* FIXME: should free this module and its referenced ones */
 		return 0;
 	}
 	return pModule->module32;
@@ -829,7 +829,7 @@
     pModule->module32 = hModule32 = PE_LoadImage( hFile );
     if (hModule32 < 32) return 21;
 
-    hInstance = MODULE_CreateInstance( hModule16, (cmd_line == NULL) );
+    hInstance = MODULE_CreateInstance( hModule16, NULL, (cmd_line == NULL) );
     if (cmd_line &&
         !(PE_HEADER(hModule32)->FileHeader.Characteristics & IMAGE_FILE_DLL))
     {
@@ -848,9 +848,12 @@
     return hInstance;
 }
 
+/*********************************************************************
+ * PE_UnloadImage [internal]
+ */
 int PE_UnloadImage( HMODULE32 hModule )
 {
-	fprintf(stderr,"PEunloadImage() called!\n");
+	FIXME(win32,"stub.\n");
 	/* free resources, image, unmap */
 	return 1;
 }
@@ -860,10 +863,12 @@
  * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
  * (SDK)
  */
-static void PE_InitDLL(PE_MODREF *pem, DWORD type,LPVOID lpReserved)
+static void PE_InitDLL(WINE_MODREF *wm, DWORD type,LPVOID lpReserved)
 {
+    if (wm->type!=MODULE32_PE)
+    	return;
     if (type==DLL_PROCESS_ATTACH)
-	pem->flags |= PE_MODREF_PROCESS_ATTACHED;
+	wm->binfmt.pe.flags |= PE_MODREF_PROCESS_ATTACHED;
 
     /*  DLL_ATTACH_PROCESS:
      *		lpreserved is NULL for dynamic loads, not-NULL for static loads
@@ -873,14 +878,14 @@
      */
         
     /* Is this a library? And has it got an entrypoint? */
-    if ((PE_HEADER(pem->module)->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
-        (PE_HEADER(pem->module)->OptionalHeader.AddressOfEntryPoint)
+    if ((PE_HEADER(wm->module)->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
+        (PE_HEADER(wm->module)->OptionalHeader.AddressOfEntryPoint)
     ) {
-        FARPROC32 entry = (FARPROC32)RVA_PTR( pem->module,
+        FARPROC32 entry = (FARPROC32)RVA_PTR( wm->module,
                                           OptionalHeader.AddressOfEntryPoint );
         TRACE(relay, "CallTo32(entryproc=%p,module=%08x,type=%ld,res=%p)\n",
-                       entry, pem->module, type, lpReserved );
-        entry( pem->module, type, lpReserved );
+                       entry, wm->module, type, lpReserved );
+        entry( wm->module, type, lpReserved );
     }
 }
 
@@ -889,57 +894,70 @@
  * LoadLibrary) ... but it won't matter)
  */
 void PE_InitializeDLLs(PDB32 *process,DWORD type,LPVOID lpReserved) {
-	PE_MODREF	*pem;
+	WINE_MODREF	*wm;
 
-	pem = process->modref_list;
-	while (pem) {
-		if (pem->flags & PE_MODREF_NO_DLL_CALLS) {
-			pem = pem->next;
+	for (wm = process->modref_list;wm;wm=wm->next) {
+		PE_MODREF	*pem = NULL;
+		if (wm->type!=MODULE32_PE)
 			continue;
-		}
+		pem = &(wm->binfmt.pe);
+		if (pem->flags & PE_MODREF_NO_DLL_CALLS)
+			continue;
 		if (type==DLL_PROCESS_ATTACH) {
-			if (pem->flags & PE_MODREF_PROCESS_ATTACHED) {
-				pem = pem->next;
+			if (pem->flags & PE_MODREF_PROCESS_ATTACHED)
 				continue;
-			}
 		}
-		PE_InitDLL( pem, type, lpReserved );
-		pem = pem->next;
+		PE_InitDLL( wm, type, lpReserved );
 	}
 }
 
 void PE_InitTls(THDB *thdb)
 {
-	/* FIXME: tls callbacks ??? */
+	WINE_MODREF		*wm;
 	PE_MODREF		*pem;
 	IMAGE_NT_HEADERS	*peh;
 	DWORD			size,datasize;
 	LPVOID			mem;
 	LPIMAGE_TLS_DIRECTORY	pdir;
 	PDB32			*pdb = thdb->process;
-
-	pem = pdb->modref_list;
-	while (pem) {
-		peh = PE_HEADER(pem->module);
-		if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress) {
-			pem = pem->next;
+        int delta;
+	
+	for (wm = pdb->modref_list;wm;wm=wm->next) {
+		if (wm->type!=MODULE32_PE)
 			continue;
-		}
-		pdir = (LPVOID)(pem->module + peh->OptionalHeader.
+		pem = &(wm->binfmt.pe);
+		peh = PE_HEADER(wm->module);
+		delta = wm->module - peh->OptionalHeader.ImageBase;
+		if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress)
+			continue;
+		pdir = (LPVOID)(wm->module + peh->OptionalHeader.
 			DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
 		
+		
 		if (!(pem->flags & PE_MODREF_TLS_ALLOCED)) {
 			pem->tlsindex = THREAD_TlsAlloc(thdb);
-			*(pdir->AddressOfIndex)=pem->tlsindex;   
+			*(LPDWORD)AdjustPtr(pdir->AddressOfIndex,delta)
+			  =pem->tlsindex;   
 		}
 		pem->flags |= PE_MODREF_TLS_ALLOCED;
 		datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
 		size	= datasize + pdir->SizeOfZeroFill;
 		mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
-		memcpy(mem,(LPVOID) pdir->StartAddressOfRawData, datasize);
+		memcpy(mem,
+		       AdjustPtr(pdir->StartAddressOfRawData,delta), 
+		       datasize);
+
 		/* don't use TlsSetValue, we are in the wrong thread */
+		if (pdir->AddressOfCallBacks) {
+		     LPIMAGE_TLS_CALLBACK *cbs = 
+		       (LPIMAGE_TLS_CALLBACK *)
+		       AdjustPtr(pdir->AddressOfCallBacks, delta);
+
+		     if (*cbs) {
+		       FIXME(win32, "TLS Callbacks aren't going to be called\n");
+		     }
+		}
 		thdb->tls_array[pem->tlsindex] = mem;
-		pem=pem->next;
 	}
 }
 
@@ -949,13 +967,10 @@
  */
 BOOL32 WINAPI DisableThreadLibraryCalls(HMODULE32 hModule)
 {
-	PDB32	*process = PROCESS_Current();
-	PE_MODREF	*pem = process->modref_list;
+	WINE_MODREF	*wm;
 
-	while (pem) {
-		if (pem->module == hModule)
-			pem->flags|=PE_MODREF_NO_DLL_CALLS;
-		pem = pem->next;
-	}
+	for (wm=PROCESS_Current()->modref_list;wm;wm=wm->next)
+		if ((wm->module == hModule) && (wm->type==MODULE32_PE))
+			wm->binfmt.pe.flags|=PE_MODREF_NO_DLL_CALLS;
 	return TRUE;
 }
diff --git a/loader/pe_resource.c b/loader/pe_resource.c
index da06142..2d058b5 100644
--- a/loader/pe_resource.c
+++ b/loader/pe_resource.c
@@ -31,18 +31,13 @@
  */
 static PE_MODREF*
 HMODULE32toPE_MODREF(HMODULE32 hmod) {
-	NE_MODULE	*pModule;
+	WINE_MODREF	*wm;
 	PDB32		*pdb = PROCESS_Current();
-	PE_MODREF	*pem;
 
-	if (!hmod) hmod = GetTaskDS(); /* FIXME: correct? */
-	hmod = MODULE_HANDLEtoHMODULE32( hmod );
-	if (!hmod) return NULL;
-	if (!(pModule = MODULE_GetPtr( hmod ))) return 0;
-	pem = pdb->modref_list;
-	while (pem && pem->module != hmod)
-		pem=pem->next;
-	return pem;
+	wm = MODULE32_LookupHMODULE( pdb, hmod );
+	if (!wm || wm->type!=MODULE32_PE)
+		return NULL;
+	return &(wm->binfmt.pe);
 }
 
 /**********************************************************************
@@ -106,12 +101,12 @@
  *	    PE_FindResourceEx32W
  */
 HANDLE32 PE_FindResourceEx32W(
-	HINSTANCE32 hModule,LPCWSTR name,LPCWSTR type,WORD lang
+	WINE_MODREF *wm,LPCWSTR name,LPCWSTR type,WORD lang
 ) {
     LPIMAGE_RESOURCE_DIRECTORY resdirptr;
     DWORD root;
     HANDLE32 result;
-    PE_MODREF	*pem = HMODULE32toPE_MODREF(hModule);
+    PE_MODREF	*pem = &(wm->binfmt.pe);
 
     if (!pem || !pem->pe_resource)
     	return 0;
@@ -133,15 +128,11 @@
 /**********************************************************************
  *	    PE_LoadResource32
  */
-HANDLE32 PE_LoadResource32( HINSTANCE32 hModule, HANDLE32 hRsrc )
+HANDLE32 PE_LoadResource32( WINE_MODREF *wm, HANDLE32 hRsrc )
 {
-    PE_MODREF	*pem = HMODULE32toPE_MODREF(hModule);
-
-    if (!pem || !pem->pe_resource)
+    if (!hRsrc || !wm || wm->type!=MODULE32_PE)
     	return 0;
-    if (!hRsrc)
-   	 return 0;
-    return (HANDLE32) (pem->module + ((LPIMAGE_RESOURCE_DATA_ENTRY)hRsrc)->OffsetToData);
+    return (HANDLE32) (wm->module + ((LPIMAGE_RESOURCE_DATA_ENTRY)hRsrc)->OffsetToData);
 }
 
 
diff --git a/loader/resource.c b/loader/resource.c
index e3591b0..32f2a6d 100644
--- a/loader/resource.c
+++ b/loader/resource.c
@@ -5,6 +5,7 @@
  * Copyright 1995 Alexandre Julliard
  */
 
+#include <assert.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -18,6 +19,7 @@
 #include "heap.h"
 #include "neexe.h"
 #include "task.h"
+#include "process.h"
 #include "module.h"
 #include "resource.h"
 #include "debug.h"
@@ -26,65 +28,11 @@
 
 extern WORD WINE_LanguageId;
 
-/* error message when 16-bit resource function is called for Win32 module */
-static const char* NEWin32FailureString = "fails with Win32 module\n";
-/* error message when 32-bit resource function is called for Win16 module */
-static const char* PEWin16FailureString = "fails with Win16 module\n";
-
-/**********************************************************************
- *	    FindResource16    (KERNEL.60)
- */
-HRSRC16 WINAPI FindResource16( HMODULE16 hModule, SEGPTR name, SEGPTR type )
-{
-    NE_MODULE *pModule;
-
-    hModule = MODULE_HANDLEtoHMODULE16( hModule ); 
-
-    if (HIWORD(name))  /* Check for '#xxx' name */
-    {
-	char *ptr = PTR_SEG_TO_LIN( name );
-	if (ptr[0] == '#')
-	    if (!(name = (SEGPTR)atoi( ptr + 1 ))) {
-	      WARN(resource, "Incorrect resource name: %s\n", ptr);
-	      return 0;
-	    }
-    }
-
-    if (HIWORD(type))  /* Check for '#xxx' type */
-    {
-	char *ptr = PTR_SEG_TO_LIN( type );
-	if (ptr[0] == '#')
-	  if (!(type = (SEGPTR)atoi( ptr + 1 ))){
-	    WARN(resource, "Incorrect resource type: %s\n", ptr);
-	    return 0;
-	  }
-    }
-
-    TRACE(resource, "module=%04x name=%s type=%s\n", 
-		 hModule, debugres_a(PTR_SEG_TO_LIN(name)), 
-		 debugres_a(PTR_SEG_TO_LIN(type)) );
-
-    if ((pModule = MODULE_GetPtr( hModule )))
-    {
-        if (!__winelib)
-        {
-            if (pModule->flags & NE_FFLAGS_WIN32)
-                fprintf(stderr,"FindResource16: %s", NEWin32FailureString);
-            else
-                return NE_FindResource( hModule, type, name );
-        }
-        else return LIBRES_FindResource16( hModule,
-                                           (LPCSTR)PTR_SEG_TO_LIN(name),
-                                           (LPCSTR)PTR_SEG_TO_LIN(type) );
-    }
-    return 0;
-}
-
 
 /**********************************************************************
  *	    FindResource32A    (KERNEL32.128)
  */
-HANDLE32 WINAPI FindResource32A( HINSTANCE32 hModule, LPCSTR name, LPCSTR type)
+HANDLE32 WINAPI FindResource32A( HMODULE32 hModule, LPCSTR name, LPCSTR type)
 {
     return FindResourceEx32A(hModule,name,type,WINE_LanguageId);
 }
@@ -92,9 +40,9 @@
 /**********************************************************************
  *	    FindResourceEx32A    (KERNEL32.129)
  */
-HANDLE32 WINAPI FindResourceEx32A( HINSTANCE32 hModule, LPCSTR name,
-                                   LPCSTR type, WORD lang )
-{
+HANDLE32 WINAPI FindResourceEx32A( HMODULE32 hModule, LPCSTR name, LPCSTR type,
+				   WORD lang
+) {
     LPWSTR xname,xtype;
     HANDLE32 ret;
 
@@ -116,27 +64,34 @@
 /**********************************************************************
  *	    FindResourceEx32W    (KERNEL32.130)
  */
-HRSRC32 WINAPI FindResourceEx32W( HINSTANCE32 hModule, LPCWSTR name,
+HRSRC32 WINAPI FindResourceEx32W( HMODULE32 hModule, LPCWSTR name,
                                   LPCWSTR type, WORD lang )
 {
-    if (!__winelib)
-    {
-        NE_MODULE *pModule;
+    WINE_MODREF	*wm = MODULE32_LookupHMODULE(PROCESS_Current(),hModule);
+    HRSRC32	hrsrc;
 
-        if (!hModule) hModule = GetTaskDS();
-        hModule = MODULE_HANDLEtoHMODULE32( hModule );
-        TRACE(resource, "module=%08x "
-			 "type=%s%p name=%s%p\n", hModule,
-			 (HIWORD(type))? "" : "#", type, 
-			 (HIWORD(name))? "" : "#", name);
-
-        if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
-        if (!(pModule->flags & NE_FFLAGS_WIN32)) return 0;
-        return PE_FindResourceEx32W(hModule,name,type,lang);
+    TRACE(resource, "module=%08x "
+		     "type=%s%p name=%s%p\n", wm->module,
+		     (HIWORD(type))? "" : "#", type,
+		     (HIWORD(name))? "" : "#", name);
+    if (__winelib) {
+    	hrsrc = LIBRES_FindResource( hModule, name, type );
+	if (hrsrc)
+	    return hrsrc;
     }
-    else return LIBRES_FindResource32( hModule, name, type );
+    if (wm) {
+    	switch (wm->type) {
+	case MODULE32_PE:
+	    return PE_FindResourceEx32W(wm,name,type,lang);
+	default:
+	    ERR(module,"unknown module type %d\n",wm->type);
+	    break;
+	}
+    }
+    return (HRSRC32)0;
 }
 
+
 /**********************************************************************
  *	    FindResource32W    (KERNEL32.131)
  */
@@ -147,98 +102,35 @@
 
 
 /**********************************************************************
- *	    LoadResource16    (KERNEL.61)
- */
-HGLOBAL16 WINAPI LoadResource16( HMODULE16 hModule, HRSRC16 hRsrc )
-{
-    NE_MODULE *pModule;
-
-    hModule = MODULE_HANDLEtoHMODULE16( hModule );
-    TRACE(resource, "module=%04x res=%04x\n",
-                     hModule, hRsrc );
-    if (!hRsrc) return 0;
-    if ((pModule = MODULE_GetPtr( hModule )))
-    {
-        if (!__winelib)
-        {
-            if (pModule->flags & NE_FFLAGS_WIN32)
-                fprintf(stderr,"LoadResource16: %s", NEWin32FailureString);
-            else
-                return NE_LoadResource( hModule, hRsrc );
-        }
-        else return LIBRES_LoadResource( hModule, hRsrc );
-    }
-    return 0;
-}
-
-/**********************************************************************
  *	    LoadResource32    (KERNEL32.370)
+ * 'loads' a resource. The current implementation just returns a pointer
+ * into the already mapped image.
+ * RETURNS
+ *	pointer into the mapped resource of the passed module
  */
-HGLOBAL32 WINAPI LoadResource32( HINSTANCE32 hModule, HRSRC32 hRsrc )
+HGLOBAL32 WINAPI LoadResource32( 
+	HINSTANCE32 hModule,	/* [in] module handle */
+	HRSRC32 hRsrc )		/* [in] resource handle */
 {
-    if (!__winelib)
-    {
-        NE_MODULE *pModule;
+    WINE_MODREF	*wm = MODULE32_LookupHMODULE(PROCESS_Current(),hModule);
 
-        if (!hModule) hModule = GetTaskDS(); /* FIXME: see FindResource32W */
-        hModule = MODULE_HANDLEtoHMODULE32( hModule );
-        TRACE(resource, "module=%04x res=%04x\n",
-                         hModule, hRsrc );
-        if (!hRsrc) return 0;
-
-        if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
-        if (!(pModule->flags & NE_FFLAGS_WIN32))
-        {
-            fprintf(stderr,"LoadResource32: %s", PEWin16FailureString );
-            return 0;  /* FIXME? */
-        }
-        return PE_LoadResource32(hModule,hRsrc);
+    TRACE(resource, "module=%04x res=%04x\n",
+		     hModule, hRsrc );
+    if (!hRsrc) {
+    	ERR(resource,"hRsrc is 0, return 0.\n");
+	return 0;
     }
-    else return LIBRES_LoadResource( hModule, hRsrc );
-}
-
-
-/**********************************************************************
- *	    LockResource    (KERNEL.62)
- */
-/* 16-bit version */
-SEGPTR WINAPI WIN16_LockResource16(HGLOBAL16 handle)
-{
-    HMODULE16 hModule;
-    NE_MODULE *pModule;
-
-    TRACE(resource, "handle=%04x\n", handle );
-    if (!handle) return (SEGPTR)0;
-    hModule = MODULE_HANDLEtoHMODULE16( handle );
-    if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
-    if (pModule->flags & NE_FFLAGS_WIN32)
-    {
-        fprintf(stderr,"LockResource16: %s", NEWin32FailureString);
-        return 0;
-    }
-    return NE_LockResource( hModule, handle );
-}
-
-/* Winelib 16-bit version */
-LPVOID WINAPI LockResource16( HGLOBAL16 handle )
-{
-    if (!__winelib)
-    {
-        HMODULE16 hModule;
-        NE_MODULE *pModule;
-
-        TRACE(resource, "handle=%04x\n", handle );
-        if (!handle) return NULL;
-        hModule = MODULE_HANDLEtoHMODULE16( handle );
-        if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
-        if (pModule->flags & NE_FFLAGS_WIN32)
-        {
-            fprintf(stderr,"LockResource16: %s", NEWin32FailureString);
-            return 0;
-        }
-        return (LPSTR)PTR_SEG_TO_LIN( NE_LockResource( hModule, handle ) );
-    }
-    else return LIBRES_LockResource( handle );
+    if (wm)
+    	switch (wm->type) {
+	case MODULE32_PE:
+            return PE_LoadResource32(wm,hRsrc);
+	default:
+	    ERR(resource,"unknown module type %d\n",wm->type);
+	    break;
+	}
+    if (__winelib)
+    	return LIBRES_LoadResource( hModule, hRsrc );
+    return 0;
 }
 
 
@@ -252,30 +144,6 @@
 
 
 /**********************************************************************
- *	    FreeResource16    (KERNEL.63)
- */
-BOOL16 WINAPI FreeResource16( HGLOBAL16 handle )
-{
-    if (!__winelib)
-    {
-        HMODULE16 hModule;
-        NE_MODULE *pModule;
-
-        TRACE(resource, "handle=%04x\n", handle );
-        if (!handle) return FALSE;
-        hModule = MODULE_HANDLEtoHMODULE16( handle );
-        if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
-        if (pModule->flags & NE_FFLAGS_WIN32)
-        {
-            fprintf(stderr,"FreeResource16: %s", NEWin32FailureString);
-            return 0;
-        }
-        return NE_FreeResource( hModule, handle );
-    }
-    else return LIBRES_FreeResource( handle );
-}
-
-/**********************************************************************
  *	    FreeResource32    (KERNEL32.145)
  */
 BOOL32 WINAPI FreeResource32( HGLOBAL32 handle )
@@ -286,125 +154,41 @@
 
 
 /**********************************************************************
- *	    AccessResource16    (KERNEL.64)
- */
-INT16 WINAPI AccessResource16( HINSTANCE16 hModule, HRSRC16 hRsrc )
-{
-    NE_MODULE *pModule;
-
-    hModule = MODULE_HANDLEtoHMODULE16( hModule );
-    TRACE(resource, "module=%04x res=%04x\n",
-                     hModule, hRsrc );
-    if (!hRsrc) return 0;
-    if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
-    if (!__winelib)
-    {
-        if (pModule->flags & NE_FFLAGS_WIN32)
-        {
-            fprintf(stderr,"AccessResource16: %s", NEWin32FailureString);
-            return 0;
-        }
-        return NE_AccessResource( hModule, hRsrc );
-    }
-    else return LIBRES_AccessResource( hModule, hRsrc );
-}
-
-
-/**********************************************************************
  *	    AccessResource32    (KERNEL32.64)
  */
-INT32 WINAPI AccessResource32( HINSTANCE32 hModule, HRSRC32 hRsrc )
+INT32 WINAPI AccessResource32( HMODULE32 hModule, HRSRC32 hRsrc )
 {
-    hModule = MODULE_HANDLEtoHMODULE32( hModule );
-    TRACE(resource, "module=%04x res=%04x\n",
-                     hModule, hRsrc );
-    if (!hRsrc) return 0;
-    fprintf(stderr,"AccessResource32: not implemented\n");
+    FIXME(resource,"(module=%08x res=%08x),not implemented\n", hModule, hRsrc);
     return 0;
 }
 
 
 /**********************************************************************
- *	    SizeofResource16    (KERNEL.65)
- */
-DWORD WINAPI SizeofResource16( HMODULE16 hModule, HRSRC16 hRsrc )
-{
-    NE_MODULE *pModule;
-
-    hModule = MODULE_HANDLEtoHMODULE16( hModule );
-    TRACE(resource, "module=%04x res=%04x\n",
-                     hModule, hRsrc );
-    if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
-    if (!__winelib)
-    {
-        if (pModule->flags & NE_FFLAGS_WIN32)
-        {
-            fprintf(stderr,"SizeOfResource16: %s", NEWin32FailureString);
-            return 0;
-        }
-        return NE_SizeofResource( hModule, hRsrc );
-    }
-    else return LIBRES_SizeofResource( hModule, hRsrc );
-}
-
-
-/**********************************************************************
  *	    SizeofResource32    (KERNEL32.522)
  */
 DWORD WINAPI SizeofResource32( HINSTANCE32 hModule, HRSRC32 hRsrc )
 {
-    hModule = MODULE_HANDLEtoHMODULE32( hModule );
-    TRACE(resource, "module=%04x res=%04x\n",
-                     hModule, hRsrc );
-    if (!__winelib) return PE_SizeofResource32(hModule,hRsrc);
-    else
-    {
-        fprintf(stderr,"SizeofResource32: not implemented\n");
-        return 0;
-    }
-}
+    WINE_MODREF	*wm = MODULE32_LookupHMODULE(PROCESS_Current(),hModule);
 
-
-/**********************************************************************
- *	    AllocResource16    (KERNEL.66)
- */
-HGLOBAL16 WINAPI AllocResource16( HMODULE16 hModule, HRSRC16 hRsrc, DWORD size)
-{
-    NE_MODULE *pModule;
-
-    hModule = MODULE_HANDLEtoHMODULE16( hModule );
-    TRACE(resource, "module=%04x res=%04x size=%ld\n",
-                     hModule, hRsrc, size );
-    if (!hRsrc) return 0;
-    if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
-    if (!__winelib)
-    {
-        if (pModule->flags & NE_FFLAGS_WIN32)
+    TRACE(resource, "module=%08x res=%08x\n", hModule, hRsrc );
+    if (wm)
+        switch (wm->type)
         {
-            fprintf(stderr,"AllocResource16: %s", NEWin32FailureString);
-            return 0;
-        }
-        return NE_AllocResource( hModule, hRsrc, size );
-    }
-    else return LIBRES_AllocResource( hModule, hRsrc, size );
-}
-
-/**********************************************************************
- *      DirectResAlloc    (KERNEL.168)
- *
- * Check Schulman, p. 232 for details
- */
-HGLOBAL16 WINAPI DirectResAlloc( HINSTANCE16 hInstance, WORD wType,
-                                 UINT16 wSize )
-{
-    TRACE(resource,"(%04x,%04x,%04x)\n",
-                     hInstance, wType, wSize );
-    hInstance = MODULE_HANDLEtoHMODULE16(hInstance);
-    if(!hInstance)return 0;
-    if(wType != 0x10)	/* 0x10 is the only observed value, passed from
-                           CreateCursorIndirect. */
-        fprintf(stderr, "DirectResAlloc: wType = %x\n", wType);
-    return GLOBAL_Alloc(GMEM_MOVEABLE, wSize, hInstance, FALSE, FALSE, FALSE);
+	case MODULE32_PE:
+            {
+                DWORD ret;
+                ret = PE_SizeofResource32(hModule,hRsrc);
+                if (ret) 
+                    return ret;
+                break;
+            }
+	default:
+	    ERR(module,"unknown module type %d\n",wm->type);
+	    break;
+	}
+    if (__winelib)
+        fprintf(stderr,"SizeofResource32: not implemented for WINELIB\n");
+    return 0;
 }
 
 
@@ -576,14 +360,22 @@
   return hAccel;
 }
 
-/**********************************************************************
- *             DestroyAcceleratorTable   (USER32.130)
+
+/******************************************************************************
+ * DestroyAcceleratorTable [USER32.130]
+ * Destroys an accelerator table
  *
- * By mortene@pvv.org 980321
+ * NOTES
+ *    By mortene@pvv.org 980321
+ *
+ * PARAMS
+ *    handle [I] Handle to accelerator table
+ *
+ * RETURNS STD
  */
 BOOL32 WINAPI DestroyAcceleratorTable( HACCEL32 handle )
 {
-  FIXME(accel, "stub (handle 0x%x)\n", handle);
+    FIXME(accel, "(0x%x): stub\n", handle);
 
 
   /* Weird.. I thought this should work. According to the API
@@ -647,8 +439,7 @@
 	    buffer[0] = '\0';
 	    return 0;
 	}
-	fprintf(stderr,"LoadString // I dont know why , but caller give buflen=%d *p=%d !\n", buflen, *p);
-	fprintf(stderr,"LoadString // and try to obtain string '%s'\n", p + 1);
+	WARN(resource,"Dont know why caller give buflen=%d *p=%d trying to obtain string '%s'\n", buflen, *p, p + 1);
     }
     FreeResource16( hmem );
 
@@ -698,8 +489,7 @@
 	    return 0;
 	}
 #if 0
-	fprintf(stderr,"LoadString // I dont know why , but caller give buflen=%d *p=%d !\n", buflen, *p);
-	fprintf(stderr,"LoadString // and try to obtain string '%s'\n", p + 1);
+	WARN(resource,"Dont know why caller give buflen=%d *p=%d trying to obtain string '%s'\n", buflen, *p, p + 1);
 #endif
     }
 
@@ -757,7 +547,7 @@
 /**********************************************************************
  *	LoadMessage32A		(internal)
  */
-INT32 LoadMessage32A( HINSTANCE32 instance, UINT32 id, WORD lang,
+INT32 LoadMessage32A( HMODULE32 instance, UINT32 id, WORD lang,
                       LPSTR buffer, INT32 buflen )
 {
     HGLOBAL32	hmem;
@@ -824,7 +614,7 @@
 /**********************************************************************
  *	LoadMessage32W	(internal)
  */
-INT32 LoadMessage32W( HINSTANCE32 instance, UINT32 id, WORD lang,
+INT32 LoadMessage32W( HMODULE32 instance, UINT32 id, WORD lang,
                       LPWSTR buffer, INT32 buflen )
 {
     INT32 retval;
@@ -845,35 +635,12 @@
 
 
 /**********************************************************************
- *	SetResourceHandler	(KERNEL.43)
- */
-FARPROC16 WINAPI SetResourceHandler( HMODULE16 hModule, SEGPTR s,
-                                     FARPROC16 resourceHandler )
-{
-    NE_MODULE *pModule;
-
-    hModule = GetExePtr( hModule );
-
-    TRACE(resource, "module=%04x type=%s\n", 
-		 hModule, debugres_a(PTR_SEG_TO_LIN(s)) );
-
-    if ((pModule = MODULE_GetPtr( hModule )))
-    {
-	if (pModule->flags & NE_FFLAGS_WIN32)
-	    fprintf(stderr,"SetResourceHandler: %s\n", NEWin32FailureString);
-	else if (pModule->res_table)
-	    return NE_SetResourceHandler( hModule, s, resourceHandler );
-    }
-    return NULL;
-}
-
-
-/**********************************************************************
  *	EnumResourceTypesA	(KERNEL32.90)
  */
 BOOL32 WINAPI EnumResourceTypes32A( HMODULE32 hmodule,ENUMRESTYPEPROC32A lpfun,
                                     LONG lParam)
 {
+	/* FIXME: move WINE_MODREF stuff here */
     return PE_EnumResourceTypes32A(hmodule,lpfun,lParam);
 }
 
@@ -883,6 +650,7 @@
 BOOL32 WINAPI EnumResourceTypes32W( HMODULE32 hmodule,ENUMRESTYPEPROC32W lpfun,
                                     LONG lParam)
 {
+	/* FIXME: move WINE_MODREF stuff here */
     return PE_EnumResourceTypes32W(hmodule,lpfun,lParam);
 }
 
@@ -892,6 +660,7 @@
 BOOL32 WINAPI EnumResourceNames32A( HMODULE32 hmodule, LPCSTR type,
                                     ENUMRESNAMEPROC32A lpfun, LONG lParam )
 {
+	/* FIXME: move WINE_MODREF stuff here */
     return PE_EnumResourceNames32A(hmodule,type,lpfun,lParam);
 }
 /**********************************************************************
@@ -900,6 +669,7 @@
 BOOL32 WINAPI EnumResourceNames32W( HMODULE32 hmodule, LPCWSTR type,
                                     ENUMRESNAMEPROC32W lpfun, LONG lParam )
 {
+	/* FIXME: move WINE_MODREF stuff here */
     return PE_EnumResourceNames32W(hmodule,type,lpfun,lParam);
 }
 
@@ -910,6 +680,7 @@
                                         LPCSTR name, ENUMRESLANGPROC32A lpfun,
                                         LONG lParam)
 {
+	/* FIXME: move WINE_MODREF stuff here */
     return PE_EnumResourceLanguages32A(hmodule,type,name,lpfun,lParam);
 }
 /**********************************************************************
@@ -919,5 +690,6 @@
                                         LPCWSTR name, ENUMRESLANGPROC32W lpfun,
                                         LONG lParam)
 {
+	/* FIXME: move WINE_MODREF stuff here */
     return PE_EnumResourceLanguages32W(hmodule,type,name,lpfun,lParam);
 }
diff --git a/loader/task.c b/loader/task.c
index f168427..99c7611 100644
--- a/loader/task.c
+++ b/loader/task.c
@@ -208,7 +208,7 @@
 {
     int exit_code = 1;
     TDB *pTask = (TDB *)GlobalLock16( hCurrentTask );
-    NE_MODULE *pModule = MODULE_GetPtr( pTask->hModule );
+    NE_MODULE *pModule = MODULE_GetPtr16( pTask->hModule );
     SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
 
     SET_CUR_THREAD( pTask->thdb );
@@ -262,7 +262,7 @@
 
         Callbacks->CallRegisterShortProc( &context, 0 );
         /* This should never return */
-        fprintf( stderr, "TASK_CallToStart: Main program returned!\n" );
+        ERR( task, "Main program returned! (should never happen)\n" );
         TASK_KillCurrentTask( 1 );
     }
 }
@@ -331,7 +331,7 @@
 
     pTask->pdb.int20 = 0x20cd;
     pTask->pdb.dispatcher[0] = 0x9a;  /* ljmp */
-    PUT_DWORD(&pTask->pdb.dispatcher[1], (DWORD)MODULE_GetEntryPoint(
+    PUT_DWORD(&pTask->pdb.dispatcher[1], (DWORD)NE_GetEntryPoint(
            GetModuleHandle16("KERNEL"), 102 ));  /* KERNEL.102 is DOS3Call() */
     pTask->pdb.savedint22 = INT_GetHandler( 0x22 );
     pTask->pdb.savedint23 = INT_GetHandler( 0x23 );
@@ -509,7 +509,7 @@
 
     /* We should never return from this Yield() */
 
-    fprintf(stderr,"Return of the living dead %04x!!!\n", hCurrentTask);
+    ERR(task,"Return of the living dead %04x!!!\n", hCurrentTask);
     exit(1);
 }
 
@@ -660,7 +660,7 @@
 
     if (context) EAX_reg(context) = 0;
     if (!(pTask = (TDB *)GlobalLock16( hCurrentTask ))) return;
-    if (!(pModule = MODULE_GetPtr( pTask->hModule ))) return;
+    if (!(pModule = MODULE_GetPtr16( pTask->hModule ))) return;
 
     /* This is a hack to install task USER signal handler before 
      * implicitly loaded DLLs are initialized (see windows/user.c) */
@@ -681,7 +681,6 @@
          * es:bx  pointer to command-line inside PSP
          */
         EAX_reg(context) = 1;
-        EBX_reg(context) = pTask->pdb.cmdLine[0] ? 0x81 : 0x80;
         
 	if (!pTask->pdb.cmdLine[0]) EBX_reg(context) = 0x80;
 	else
@@ -857,7 +856,6 @@
     SEGPTR thunkaddr;
 
     if (!hInstance) return 0;
-    if (__winelib) return func; /* func can be called directly in Winelib */
     thunkaddr = TASK_AllocThunk( hCurrentTask );
     if (!thunkaddr) return (FARPROC16)0;
     thunk = PTR_SEG_TO_LIN( thunkaddr );
@@ -868,7 +866,7 @@
     if (((lfunc[0]==0x8c) && (lfunc[1]==0xd8)) ||
     	((lfunc[0]==0x1e) && (lfunc[1]==0x58))
     ) {
-    	fprintf(stderr,"FIXME: MakeProcInstance16 thunk would be useless for %p, overwriting with nop;nop;\n", func );
+    	FIXME(task,"thunk would be useless for %p, overwriting with nop;nop;\n", func );
 	lfunc[0]=0x90; /* nop */
 	lfunc[1]=0x90; /* nop */
     }
@@ -888,7 +886,7 @@
 void WINAPI FreeProcInstance16( FARPROC16 func )
 {
     TRACE(task, "(%08lx)\n", (DWORD)func );
-    if (!__winelib) TASK_FreeThunk( hCurrentTask, (SEGPTR)func );
+    TASK_FreeThunk( hCurrentTask, (SEGPTR)func );
 }
 
 
@@ -900,8 +898,6 @@
     HANDLE16 handle;
     BYTE *thunk = (BYTE *)PTR_SEG_TO_LIN( proc );
 
-    if (__winelib) return 0;
-
     /* Return the code segment containing 'proc'. */
     /* Not sure if this is really correct (shouldn't matter that much). */
 
@@ -1015,7 +1011,7 @@
         return;
     if (!pData->old_ss_sp)
     {
-        fprintf( stderr, "SwitchStackBack: no previous SwitchStackTo\n" );
+        WARN( task, "No previous SwitchStackTo\n" );
         return;
     }
     TRACE(task, "restoring stack %04x:%04x\n",
diff --git a/memory/environ.c b/memory/environ.c
index 8e4a28a..7fa1024 100644
--- a/memory/environ.c
+++ b/memory/environ.c
@@ -28,8 +28,8 @@
 
 static const char ENV_program_name[] = "C:\\WINDOWS\\SYSTEM\\KRNL386.EXE";
 
-/* Maximum length of an environment string (including NULL) */
-#define MAX_STR_LEN  128
+/* Maximum length of a Win16 environment string (including NULL) */
+#define MAX_WIN16_LEN  128
 
 /* Extra bytes to reserve at the end of an environment */
 #define EXTRA_ENV_SIZE (sizeof(BYTE) + sizeof(WORD) + sizeof(ENV_program_name))
@@ -68,29 +68,23 @@
 {
     extern char **environ;
     LPSTR p, *e;
-    int size, len;
+    int size;
 
     /* Compute the total size of the Unix environment */
 
     size = EXTRA_ENV_SIZE;
-    for (e = environ; *e; e++)
-    {
-        len = strlen(*e) + 1;
-        size += MIN( len, MAX_STR_LEN );
-    }
+    for (e = environ; *e; e++) size += strlen(*e) + 1;
 
     /* Now allocate the environment */
 
     if (!(p = HeapAlloc( SystemHeap, 0, size ))) return FALSE;
     pdb->env_db->environ = p;
-    pdb->env_db->env_sel = SELECTOR_AllocBlock( p, 0x10000, SEGMENT_DATA,
-                                                FALSE, FALSE );
 
     /* And fill it with the Unix environment */
 
     for (e = environ; *e; e++)
     {
-        lstrcpyn32A( p, *e, MAX_STR_LEN );
+        strcpy( p, *e );
         p += strlen(p) + 1;
     }
 
@@ -110,16 +104,24 @@
 BOOL32 ENV_InheritEnvironment( PDB32 *pdb, LPCSTR env )
 {
     DWORD size;
-    LPCSTR p;
+    LPCSTR src;
+    LPSTR dst;
 
     /* FIXME: should lock the parent environment */
     if (!env) env = pdb->parent->env_db->environ;
 
     /* Compute the environment size */
 
-    p = env;
-    while (*p) p += strlen(p) + 1;
-    size = (p - env);
+    src = env;
+    size = EXTRA_ENV_SIZE;
+    while (*src)
+    {
+        int len = strlen(src) + 1;
+        src += len;
+        if ((len > MAX_WIN16_LEN) && (pdb->flags & PDB32_WIN16_PROC))
+            len = MAX_WIN16_LEN;
+        size += len;
+    }
 
     /* Copy the environment */
 
@@ -129,8 +131,18 @@
     pdb->env_db->env_sel = SELECTOR_AllocBlock( pdb->env_db->environ,
                                                 0x10000, SEGMENT_DATA,
                                                 FALSE, FALSE );
-    memcpy( pdb->env_db->environ, env, size );
-    FILL_EXTRA_ENV( pdb->env_db->environ + size );
+    src = env;
+    dst = pdb->env_db->environ;
+    while (*src)
+    {
+        if (pdb->flags & PDB32_WIN16_PROC)
+            lstrcpyn32A( dst, src, MAX_WIN16_LEN );
+        else
+            strcpy( dst, src );
+        src += strlen(src) + 1;
+        dst += strlen(dst) + 1;
+    }
+    FILL_EXTRA_ENV( dst );
     return TRUE;
 }
 
@@ -314,7 +326,8 @@
     }
     if (!(new_env = HeapReAlloc( pdb->heap, 0, env, old_size + len )))
         goto done;
-    SELECTOR_MoveBlock( pdb->env_db->env_sel, new_env );
+    if (pdb->env_db->env_sel)
+        SELECTOR_MoveBlock( pdb->env_db->env_sel, new_env );
     p = new_env + (p - env);
     if (len > 0) memmove( p + len, p, old_size - (p - new_env) );
 
diff --git a/memory/global.c b/memory/global.c
index fdb0208..b4b4d05 100644
--- a/memory/global.c
+++ b/memory/global.c
@@ -418,7 +418,7 @@
     void *ptr;
 
     if (!VALID_HANDLE(handle)) {
-    	fprintf(stderr," Invalid handle 0x%04x passed to GlobalFree16!\n",handle);
+    	WARN(global,"Invalid handle 0x%04x passed to GlobalFree16!\n",handle);
     	return 0;
     }
     ptr = (void *)GET_ARENA_PTR(handle)->base;
@@ -452,7 +452,7 @@
 #endif  /* CONFIG_IPC */
 
 	if (!VALID_HANDLE(handle)) {
-	    fprintf(stderr,"Invalid handle 0x%04x passed to WIN16_GlobalLock16!\n",handle);
+	    WARN(global,"Invalid handle 0x%04x passed to WIN16_GlobalLock16!\n",handle);
 	    return (SEGPTR)0;
 	}
 	if (!GET_ARENA_PTR(handle)->base) return (SEGPTR)0;
@@ -501,7 +501,7 @@
 ) {
     GLOBALARENA *pArena = GET_ARENA_PTR(handle);
     if (!VALID_HANDLE(handle)) {
-	fprintf(stderr,"Invalid handle 0x%04x passed to GlobalUnlock16!\n",handle);
+	WARN(global,"Invalid handle 0x%04x passed to GlobalUnlock16!\n",handle);
 	return 0;
     }
     TRACE(global, "%04x\n", handle );
@@ -541,7 +541,7 @@
 ) {
     TRACE(global, "%04x\n", sel );
     if (!VALID_HANDLE(sel)) {
-	fprintf(stderr,"Invalid handle 0x%04x passed to GlobalHandle16!\n",sel);
+	WARN(global,"Invalid handle 0x%04x passed to GlobalHandle16!\n",sel);
 	return 0;
     }
     return MAKELONG( GET_ARENA_PTR(sel)->handle, GlobalHandleToSel(sel) );
@@ -578,7 +578,7 @@
 
     TRACE(global, "%04x\n", handle );
     if (!VALID_HANDLE(handle)) {
-	fprintf(stderr,"Invalid handle 0x%04x passed to GlobalFlags16!\n",handle);
+	WARN(global,"Invalid handle 0x%04x passed to GlobalFlags16!\n",handle);
 	return 0;
     }
     pArena = GET_ARENA_PTR(handle);
@@ -596,7 +596,7 @@
     TRACE(global, "%04x\n", handle );
     if (handle == (HGLOBAL16)-1) handle = CURRENT_DS;
     if (!VALID_HANDLE(handle)) {
-	fprintf(stderr,"Invalid handle 0x%04x passed to LockSegment16!\n",handle);
+	WARN(global,"Invalid handle 0x%04x passed to LockSegment16!\n",handle);
 	return 0;
     }
     GET_ARENA_PTR(handle)->lockCount++;
@@ -612,7 +612,7 @@
     TRACE(global, "%04x\n", handle );
     if (handle == (HGLOBAL16)-1) handle = CURRENT_DS;
     if (!VALID_HANDLE(handle)) {
-	fprintf(stderr,"Invalid handle 0x%04x passed to UnlockSegment16!\n",handle);
+	WARN(global,"Invalid handle 0x%04x passed to UnlockSegment16!\n",handle);
 	return;
     }
     GET_ARENA_PTR(handle)->lockCount--;
@@ -759,7 +759,7 @@
 {
     TRACE(global, "%04x\n", handle );
     if (!VALID_HANDLE(handle)) {
-	fprintf(stderr,"Invalid handle 0x%04x passed to GlobalPageLock!\n",handle);
+	WARN(global,"Invalid handle 0x%04x passed to GlobalPageLock!\n",handle);
 	return 0;
     }
     return ++(GET_ARENA_PTR(handle)->pageLockCount);
@@ -773,7 +773,7 @@
 {
     TRACE(global, "%04x\n", handle );
     if (!VALID_HANDLE(handle)) {
-	fprintf(stderr,"Invalid handle 0x%04x passed to GlobalPageUnlock!\n",handle);
+	WARN(global,"Invalid handle 0x%04x passed to GlobalPageUnlock!\n",handle);
 	return 0;
     }
     return --(GET_ARENA_PTR(handle)->pageLockCount);
@@ -787,7 +787,7 @@
 {
     TRACE(global, "%04x\n", handle );
     if (!VALID_HANDLE(handle)) {
-	fprintf(stderr,"Invalid handle 0x%04x passed to GlobalFix16!\n",handle);
+	WARN(global,"Invalid handle 0x%04x passed to GlobalFix16!\n",handle);
 	return;
     }
     GET_ARENA_PTR(handle)->lockCount++;
@@ -801,7 +801,7 @@
 {
     TRACE(global, "%04x\n", handle );
     if (!VALID_HANDLE(handle)) {
-	fprintf(stderr,"Invalid handle 0x%04x passed to GlobalUnfix16!\n",handle);
+	WARN(global,"Invalid handle 0x%04x passed to GlobalUnfix16!\n",handle);
 	return;
     }
     GET_ARENA_PTR(handle)->lockCount--;
@@ -814,7 +814,7 @@
 void WINAPI FarSetOwner( HGLOBAL16 handle, HANDLE16 hOwner )
 {
     if (!VALID_HANDLE(handle)) {
-	fprintf(stderr,"Invalid handle 0x%04x passed to FarSetOwner!\n",handle);
+	WARN(global,"Invalid handle 0x%04x passed to FarSetOwner!\n",handle);
 	return;
     }
     GET_ARENA_PTR(handle)->hOwner = hOwner;
@@ -827,7 +827,7 @@
 HANDLE16 WINAPI FarGetOwner( HGLOBAL16 handle )
 {
     if (!VALID_HANDLE(handle)) {
-	fprintf(stderr,"Invalid handle 0x%04x passed to FarGetOwner!\n",handle);
+	WARN(global,"Invalid handle 0x%04x passed to FarGetOwner!\n",handle);
 	return 0;
     }
     return GET_ARENA_PTR(handle)->hOwner;
@@ -845,12 +845,12 @@
     if (is_dde_handle(handle)) return DDE_GlobalHandleToSel(handle);
 #endif
     if (!VALID_HANDLE(handle)) {
-	fprintf(stderr,"Invalid handle 0x%04x passed to GlobalHandleToSel!\n",handle);
+	WARN(global,"Invalid handle 0x%04x passed to GlobalHandleToSel!\n",handle);
 	return 0;
     }
     if (!(handle & 7))
     {
-        fprintf( stderr, "Program attempted invalid selector conversion\n" );
+        WARN(global, "Program attempted invalid selector conversion\n" );
         return handle - 1;
     }
     return handle | 7;
diff --git a/memory/heap.c b/memory/heap.c
index 2c2556d..b604f7c 100644
--- a/memory/heap.c
+++ b/memory/heap.c
@@ -188,7 +188,7 @@
     HEAP *heapPtr = (HEAP *)heap;
     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
     {
-        fprintf( stderr, "Invalid heap %08x!\n", heap );
+        WARN(heap, "Invalid heap %08x!\n", heap );
         SetLastError( ERROR_INVALID_HANDLE );
         return NULL;
     }
@@ -258,7 +258,7 @@
                        size - subheap->commitSize, MEM_COMMIT,
                        PAGE_EXECUTE_READWRITE))
     {
-        fprintf( stderr, "HEAP_Commit: could not commit %08lx bytes at %08lx for heap %08lx\n",
+        WARN(heap, "Could not commit %08lx bytes at %08lx for heap %08lx\n",
                  size - subheap->commitSize,
                  (DWORD)((char *)subheap + subheap->commitSize),
                  (DWORD)subheap->heap );
@@ -282,7 +282,7 @@
     if (!VirtualFree( (char *)subheap + size,
                       subheap->commitSize - size, MEM_DECOMMIT ))
     {
-        fprintf( stderr, "HEAP_Decommit: could not decommit %08lx bytes at %08lx for heap %08lx\n",
+        WARN(heap, "Could not decommit %08lx bytes at %08lx for heap %08lx\n",
                  subheap->commitSize - size,
                  (DWORD)((char *)subheap + size),
                  (DWORD)subheap->heap );
@@ -458,13 +458,13 @@
     if (!(subheap = VirtualAlloc( NULL, totalSize,
                                   MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
     {
-        fprintf( stderr, "HEAP_CreateSubHeap: could not VirtualAlloc %08lx bytes\n",
+        WARN(heap, "Could not VirtualAlloc %08lx bytes\n",
                  totalSize );
         return NULL;
     }
     if (!VirtualAlloc(subheap, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
     {
-        fprintf( stderr, "HEAP_CreateSubHeap: could not commit %08lx bytes for sub-heap %08lx\n",
+        WARN(heap, "Could not commit %08lx bytes for sub-heap %08lx\n",
                  commitSize, (DWORD)subheap );
         VirtualFree( subheap, 0, MEM_RELEASE );
         return NULL;
@@ -479,7 +479,7 @@
                      (flags & HEAP_WINE_CODESEG) != 0, FALSE );
         if (!selector)
         {
-            fprintf( stderr, "HEAP_CreateSubHeap: could not allocate selector\n" );
+            WARN(heap, "Could not allocate selector\n" );
             VirtualFree( subheap, 0, MEM_RELEASE );
             return NULL;
         }
@@ -534,7 +534,7 @@
 
     if (!(heap->flags & HEAP_GROWABLE))
     {
-        fprintf( stderr, "HEAP_FindFreeBlock: Not enough space in heap %08lx for %08lx bytes\n",
+        WARN(heap, "Not enough space in heap %08lx for %08lx bytes\n",
                  (DWORD)heap, size );
         return NULL;
     }
@@ -586,7 +586,7 @@
     /* Check magic number */
     if (pArena->magic != ARENA_FREE_MAGIC)
     {
-        fprintf( stderr, "Heap %08lx: invalid free arena magic for %08lx\n",
+        WARN(heap, "Heap %08lx: invalid free arena magic for %08lx\n",
                  (DWORD)subheap->heap, (DWORD)pArena );
         return FALSE;
     }
@@ -594,20 +594,20 @@
     if (!(pArena->size & ARENA_FLAG_FREE) ||
         (pArena->size & ARENA_FLAG_PREV_FREE))
     {
-        fprintf( stderr, "Heap %08lx: bad flags %lx for free arena %08lx\n",
+        WARN(heap, "Heap %08lx: bad flags %lx for free arena %08lx\n",
                  (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
     }
     /* Check arena size */
     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
     {
-        fprintf( stderr, "Heap %08lx: bad size %08lx for free arena %08lx\n",
+        WARN(heap, "Heap %08lx: bad size %08lx for free arena %08lx\n",
                  (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
         return FALSE;
     }
     /* Check that next pointer is valid */
     if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
     {
-        fprintf( stderr, "Heap %08lx: bad next ptr %08lx for arena %08lx\n",
+        WARN(heap, "Heap %08lx: bad next ptr %08lx for arena %08lx\n",
                  (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
         return FALSE;
     }
@@ -615,14 +615,14 @@
     if (!(pArena->next->size & ARENA_FLAG_FREE) ||
         (pArena->next->magic != ARENA_FREE_MAGIC))
     { 
-        fprintf( stderr, "Heap %08lx: next arena %08lx invalid for %08lx\n", 
+        WARN(heap, "Heap %08lx: next arena %08lx invalid for %08lx\n", 
                  (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
         return FALSE;
     }
     /* Check that prev pointer is valid */
     if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
     {
-        fprintf( stderr, "Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
+        WARN(heap, "Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
                  (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
         return FALSE;
     }
@@ -630,7 +630,7 @@
     if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
         (pArena->prev->magic != ARENA_FREE_MAGIC))
     { 
-        fprintf( stderr, "Heap %08lx: prev arena %08lx invalid for %08lx\n", 
+        WARN(heap, "Heap %08lx: prev arena %08lx invalid for %08lx\n", 
                  (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
         return FALSE;
     }
@@ -640,7 +640,7 @@
         if (!(*(DWORD *)((char *)(pArena + 1) +
             (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
         {
-            fprintf( stderr, "Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
+            WARN(heap, "Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
                      (DWORD)subheap->heap, (DWORD)pArena );
             return FALSE;
         }
@@ -648,7 +648,7 @@
         if (*((ARENA_FREE **)((char *)(pArena + 1) +
             (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
         {
-            fprintf( stderr, "Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
+            WARN(heap, "Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
                      (DWORD)subheap->heap, (DWORD)pArena,
                      *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
             return FALSE;
@@ -668,20 +668,20 @@
     /* Check magic number */
     if (pArena->magic != ARENA_INUSE_MAGIC)
     {
-        fprintf( stderr, "Heap %08lx: invalid in-use arena magic for %08lx\n",
+        WARN(heap, "Heap %08lx: invalid in-use arena magic for %08lx\n",
                  (DWORD)subheap->heap, (DWORD)pArena );
         return FALSE;
     }
     /* Check size flags */
     if (pArena->size & ARENA_FLAG_FREE) 
     {
-        fprintf( stderr, "Heap %08lx: bad flags %lx for in-use arena %08lx\n",
+        WARN(heap, "Heap %08lx: bad flags %lx for in-use arena %08lx\n",
                  (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
     }
     /* Check arena size */
     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
     {
-        fprintf( stderr, "Heap %08lx: bad size %08lx for in-use arena %08lx\n",
+        WARN(heap, "Heap %08lx: bad size %08lx for in-use arena %08lx\n",
                  (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
         return FALSE;
     }
@@ -689,7 +689,7 @@
     if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
         (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
     {
-        fprintf( stderr, "Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
+        WARN(heap, "Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
                  (DWORD)subheap->heap, (DWORD)pArena );
         return FALSE;
     }
@@ -700,7 +700,7 @@
         /* Check prev pointer */
         if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
         {
-            fprintf(stderr, "Heap %08lx: bad back ptr %08lx for arena %08lx\n",
+            WARN(heap, "Heap %08lx: bad back ptr %08lx for arena %08lx\n",
                     (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
             return FALSE;
         }
@@ -708,14 +708,14 @@
         if (!(pPrev->size & ARENA_FLAG_FREE) ||
             (pPrev->magic != ARENA_FREE_MAGIC))
         { 
-            fprintf( stderr, "Heap %08lx: prev arena %08lx invalid for in-use %08lx\n", 
+            WARN(heap, "Heap %08lx: prev arena %08lx invalid for in-use %08lx\n", 
                      (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
             return FALSE;
         }
         /* Check that prev arena is really the previous block */
         if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
         {
-            fprintf( stderr, "Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
+            WARN(heap, "Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
                      (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
             return FALSE;
         }
@@ -775,7 +775,7 @@
     flags |= heapPtr->flags;
     if (!(flags & HEAP_WINE_SEGPTR))
     {
-        fprintf( stderr, "HEAP_GetSegptr: heap %08x is not a SEGPTR heap\n",
+        WARN(heap, "Heap %08x is not a SEGPTR heap\n",
                  heap );
         return 0;
     }
@@ -785,7 +785,7 @@
 
     if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
     {
-        fprintf( stderr, "HEAP_GetSegptr: %p is not inside heap %08x\n",
+        WARN(heap, "%p is not inside heap %08x\n",
                  ptr, heap );
         if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
         return 0;
@@ -1229,7 +1229,7 @@
 
     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
     {
-        fprintf( stderr, "Invalid heap %08x!\n", heap );
+        WARN(heap, "Invalid heap %08x!\n", heap );
         return FALSE;
     }
 
@@ -1240,7 +1240,7 @@
             ((char *)block < (char *)subheap + subheap->headerSize
                               + sizeof(ARENA_INUSE)))
         {
-            fprintf( stderr, "Heap %08lx: block %08lx is not inside heap\n",
+            WARN(heap, "Heap %08lx: block %08lx is not inside heap\n",
                      (DWORD)heap, (DWORD)block );
             return FALSE;
         }
@@ -1284,7 +1284,7 @@
               HANDLE32 heap,               /* [in]  Handle to heap to enumerate */
               LPPROCESS_HEAP_ENTRY *entry  /* [out] Pointer to structure of enumeration info */
 ) {
-    fprintf( stderr, "HeapWalk(%08x): not implemented\n", heap );
+    FIXME(heap, "(%08x): stub.\n", heap );
     return FALSE;
 }
 
@@ -1299,7 +1299,7 @@
     LPVOID p = HeapAlloc( heap, flags, size );
     if (!p)
     {
-        fprintf( stderr, "Virtual memory exhausted.\n" );
+        MSG("Virtual memory exhausted.\n" );
         exit(1);
     }
     return p;
diff --git a/memory/ldt.c b/memory/ldt.c
index 64b8dd6..4ebd231 100644
--- a/memory/ldt.c
+++ b/memory/ldt.c
@@ -182,7 +182,7 @@
         {
             if (ldt_info.base_addr >= 0xc0000000)
             {
-                fprintf( stderr, "LDT_SetEntry: invalid base addr %08lx\n",
+                WARN(ldt, "Invalid base addr %08lx\n",
                          ldt_info.base_addr );
                 return -1;
             }
@@ -212,8 +212,7 @@
         if (ret < 0)
         {
             perror("i386_set_ldt");
-            fprintf(stderr,
-		"Did you reconfigure the kernel with \"options USER_LDT\"?\n");
+            MSG("Did you reconfigure the kernel with \"options USER_LDT\"?\n");
     	    exit(1);
         }
     }
@@ -287,7 +286,7 @@
             flags[1] = (ldt_flags_copy[i] & LDT_FLAGS_READONLY) ? '-' : 'w';
             flags[2] = '-';
         }
-        fprintf(stderr,"%04x: sel=%04x base=%08lx limit=%08lx %d-bit %c%c%c\n",
+        TRACE(ldt,"%04x: sel=%04x base=%08lx limit=%08lx %d-bit %c%c%c\n",
                 i, ENTRY_TO_SELECTOR(i),
                 ldt_copy[i].base, ldt_copy[i].limit,
                 ldt_flags_copy[i] & LDT_FLAGS_32BIT ? 32 : 16,
diff --git a/memory/local.c b/memory/local.c
index 8f5213d..f20cda6 100644
--- a/memory/local.c
+++ b/memory/local.c
@@ -334,7 +334,7 @@
         /* cleared before use, so we can test for double initialization. */
         if (LOCAL_GetHeap(selector))
         {
-            fprintf( stderr, "LocalInit: Heap %04x initialized twice.\n", selector);
+            WARN(local, "Heap %04x initialized twice.\n", selector);
             LOCAL_PrintHeap(selector);
         }
     }
@@ -342,7 +342,7 @@
     if (start == 0) {
       /* Check if the segment is the DGROUP of a module */
 
-	if ((pModule = MODULE_GetPtr( selector )))
+	if ((pModule = MODULE_GetPtr16( selector )))
 	{
 	    SEGTABLEENTRY *pSeg = NE_SEG_TABLE( pModule ) + pModule->dgroup - 1;
 	    if (pModule->dgroup && (pSeg->selector == selector)) {
@@ -441,7 +441,7 @@
     ptr = PTR_SEG_OFF_TO_LIN( ds, 0 );
     pHeapInfo = LOCAL_GetHeap( ds );
     if (pHeapInfo == NULL) {
-	fprintf( stderr, "Local_GrowHeap: heap not found\n" );
+	WARN(local, "Heap not found\n" );
 	return;
     }
     end = GlobalSize16( hseg );
@@ -496,7 +496,7 @@
     if ((pArena->prev & 3) == LOCAL_ARENA_FREE)
     {
 	/* shouldn't happen */
-        fprintf( stderr, "LocalFreeArena: Trying to free block %04x twice!\n",
+        WARN(local, "Trying to free block %04x twice!\n",
                  arena );
 	LOCAL_PrintHeap( ds );
 	return arena;
@@ -619,7 +619,7 @@
     
     if (!(pInfo = LOCAL_GetHeap( ds )))
     {
-        fprintf( stderr, "LOCAL_GetFreeSpace: Local heap not found\n" );
+        WARN(local, "Local heap not found\n" );
         LOCAL_PrintHeap(ds);
         return 0;
     }
@@ -654,7 +654,7 @@
 
     if (!(pInfo = LOCAL_GetHeap( ds )))
     {
-        fprintf( stderr, "Local_Compact: Local heap not found\n" );
+        WARN(local, "Local heap not found\n" );
         LOCAL_PrintHeap(ds);
         return 0;
     }
@@ -773,7 +773,7 @@
 
     if (!(pInfo = LOCAL_GetHeap( ds )))
     {
-        fprintf( stderr, "Local_FindFreeBlock: Local heap not found\n" );
+        WARN(local, "Local heap not found\n" );
 	LOCAL_PrintHeap(ds);
 	return 0;
     }
@@ -805,7 +805,7 @@
 
     if (!(pInfo = LOCAL_GetHeap( ds )))
     {
-        fprintf( stderr, "Local_GetBlock: Local heap not found\n");
+        WARN(local, "Local heap not found\n");
 	LOCAL_PrintHeap(ds);
 	return 0;
     }
@@ -868,7 +868,7 @@
     TRACE(local, "Local_NewHTable\n" );
     if (!(pInfo = LOCAL_GetHeap( ds )))
     {
-        fprintf( stderr, "Local heap not found\n");
+        WARN(local, "Local heap not found\n");
         LOCAL_PrintHeap(ds);
         return FALSE;
     }
@@ -877,9 +877,9 @@
                                    + 2 * sizeof(WORD), LMEM_FIXED )))
         return FALSE;
     if (!(ptr = PTR_SEG_OFF_TO_LIN( ds, 0 )))
-        fprintf(stderr, "LOCAL_NewHTable: ptr == NULL after GetBlock.\n");
+        WARN(local, "ptr == NULL after GetBlock.\n");
     if (!(pInfo = LOCAL_GetHeap( ds )))
-        fprintf(stderr,"LOCAL_NewHTable: pInfo == NULL after GetBlock.\n");
+        WARN(local,"pInfo == NULL after GetBlock.\n");
 
     /* Fill the entry table */
 
@@ -907,7 +907,7 @@
 
     if (!(pInfo = LOCAL_GetHeap( ds )))
     {
-        fprintf( stderr, "LOCAL_GetNewHandleEntry: Local heap not found\n");
+        WARN(local, "Local heap not found\n");
 	LOCAL_PrintHeap(ds);
 	return 0;
     }
@@ -970,7 +970,7 @@
     }
     if (!*pTable)
     {
-        fprintf(stderr, "LOCAL_FreeHandleEntry: invalid entry %04x\n", handle);
+        WARN(local, "Invalid entry %04x\n", handle);
         LOCAL_PrintHeap( ds );
         return;
     }
@@ -1007,7 +1007,7 @@
 
     TRACE(local, "%04x ds=%04x\n", handle, ds );
     
-    if (!handle) { fprintf( stderr, "LOCAL_Free: handle is 0.\n" ); return 0; }
+    if (!handle) { WARN(local, "Handle is 0.\n" ); return 0; }
     if (HANDLE_FIXED( handle ))
     {
         if (!LOCAL_FreeArena( ds, ARENA_HEADER( handle ) )) return 0;  /* OK */
@@ -1057,7 +1057,7 @@
 	    hmem = 0;
 	if (!(handle = LOCAL_GetNewHandleEntry( ds )))
         {
-	    fprintf( stderr, "LocalAlloc: couldn't get handle\n");
+	    WARN(local, "Couldn't get handle.\n");
 	    if(hmem)
 		LOCAL_FreeArena( ds, ARENA_HEADER(hmem) );
 	    return 0;
@@ -1120,8 +1120,7 @@
         {
 	    HLOCAL16 hl;
 	    if(pEntry->addr)
-		fprintf(stderr,
-			"LOCAL_ReAlloc: Dicarded block has non-zero addr.\n");
+		WARN(local,"Dicarded block has non-zero addr.\n");
 	    TRACE(local, "ReAllocating discarded block\n");
 	    if(size <= 4) size = 5;
 	    if (!(hl = LOCAL_GetBlock( ds, size + sizeof(HLOCAL16), flags)))
@@ -1136,12 +1135,12 @@
 	}
 	if (((blockhandle = pEntry->addr) & 3) != 2)
 	{
-	    fprintf( stderr, "Local_ReAlloc(%04x,%04x): invalid handle\n",
+	    WARN(local, "(%04x,%04x): invalid handle\n",
                      ds, handle );
 	    return 0;
         }
 	if(*((HLOCAL16 *)(ptr + blockhandle) - 1) != handle) {
-	    fprintf(stderr, "Local_ReAlloc: Back ptr to handle is invalid\n");
+	    WARN(local, "Back ptr to handle is invalid\n");
 	    return 0;
         }
     }
@@ -1261,7 +1260,7 @@
         {
             if (!(hmem = LOCAL_GetBlock( ds, oldsize, flags )))
             {
-                fprintf( stderr, "LocalRealloc: can't restore saved block\n" );
+                WARN(local, "Can't restore saved block\n" );
                 HeapFree( GetProcessHeap(), 0, buffer );
                 return 0;
             }
@@ -1283,7 +1282,7 @@
         pEntry->addr = hmem + sizeof(HLOCAL16);
 	/* Back ptr should still be correct */
 	if(*(HLOCAL16 *)(ptr + hmem) != handle)
-	    fprintf(stderr, "Local_ReAlloc: back ptr is invalid.\n");
+	    WARN(local, "back ptr is invalid.\n");
 	hmem = handle;
     }
     if (size == oldsize) hmem = 0;  /* Realloc failed */
@@ -1423,7 +1422,7 @@
 
     if (!(pInfo = LOCAL_GetHeap( ds )))
     {
-        fprintf( stderr, "LOCAL_Handle(%04x): Local heap not found\n", ds );
+        WARN(local, "(%04x): Local heap not found\n", ds );
 	LOCAL_PrintHeap( ds );
 	return 0;
     }
@@ -1456,7 +1455,7 @@
 
     if (!(pInfo = LOCAL_GetHeap( ds )))
     {
-        fprintf( stderr, "LOCAL_Handle(%04x): Local heap not found\n", ds );
+        WARN(local, "(%04x): Local heap not found\n", ds );
 	LOCAL_PrintHeap( ds );
 	return 0;
     }
@@ -1602,7 +1601,7 @@
     NE_MODULE *pModule;
     WORD ds;
 
-    if (!(pModule = MODULE_GetPtr( module ))) return 0;
+    if (!(pModule = MODULE_GetPtr16( module ))) return 0;
     ds = (NE_SEG_TABLE( pModule ) + pModule->dgroup - 1)->selector;
     return MAKELONG( LOCAL_CountFree( ds ), LOCAL_HeapSize( ds ) );
 }
diff --git a/memory/selector.c b/memory/selector.c
index 0fbb9bb..218ee71 100644
--- a/memory/selector.c
+++ b/memory/selector.c
@@ -13,9 +13,6 @@
 #include "debug.h"
 
 
-#define FIRST_LDT_ENTRY_TO_ALLOC  17
-
-
 /***********************************************************************
  *           AllocSelectorArray   (KERNEL.206)
  */
@@ -179,7 +176,7 @@
         GET_FS(fs);
         if ((fs >= sel) && (fs < nextsel))
         {
-            fprintf( stderr, "SELECTOR_FreeBlock: freeing %%fs selector (%04x), not good.\n", fs );
+            WARN(selector, "Freeing %%fs selector (%04x), not good.\n", fs );
             SET_FS( 0 );
         }
         GET_GS(gs);
@@ -788,6 +785,5 @@
  */
 SEGPTR WINAPI UTLinearToSelectorOffset(LPVOID lptr)
 {
-    fprintf( stderr, "UTLinearToSelectorOffset(%p): stub\n", lptr );
     return (SEGPTR)lptr;
 }
diff --git a/memory/virtual.c b/memory/virtual.c
index fac4ee7..d2759e6 100644
--- a/memory/virtual.c
+++ b/memory/virtual.c
@@ -84,7 +84,7 @@
 
 static FILE_VIEW *VIRTUAL_FirstView;
 
-#ifdef __i386___
+#ifdef __i386__
 /* These are always the same on an i386, and it will be faster this way */
 # define page_mask  0xfff
 # define page_shift 12
@@ -552,7 +552,7 @@
     	/* FIXME: MEM_TOP_DOWN allocates the largest possible address.
 	 *  	  Is there _ANY_ way to do it with UNIX mmap()?
 	 */
-    	fprintf(stderr,"VirtualAlloc:MEM_TOP_DOWN ignored\n");
+    	WARN(virtual,"MEM_TOP_DOWN ignored\n");
     	type &= ~MEM_TOP_DOWN;
     }
     /* Compute the protection flags */
@@ -795,7 +795,7 @@
         if (pdb == PROCESS_Current())
             ret = VirtualProtect( addr, size, new_prot, old_prot );
         else
-            fprintf(stderr,"Unsupported: VirtualProtectEx on other process\n");
+            ERR(virtual,"Unsupported on other process\n");
         K32OBJ_DecCount( &pdb->header );
     }
     return ret;
@@ -892,7 +892,7 @@
         if (pdb == PROCESS_Current())
             ret = VirtualQuery( addr, info, len );
         else
-            fprintf(stderr,"Unsupported: VirtualQueryEx on other process\n");
+            ERR(virtual,"Unsupported on other process\n");
         K32OBJ_DecCount( &pdb->header );
     }
     return ret;
@@ -1288,7 +1288,7 @@
         return NULL;
 
     if (mapping->size_high || offset_high)
-        fprintf( stderr, "MapViewOfFileEx: offsets larger than 4Gb not supported\n");
+        ERR(virtual, "Offsets larger than 4Gb not supported\n");
 
     if ((offset_low >= mapping->size_low) ||
         (count > mapping->size_low - offset_low))
diff --git a/misc/Makefile.in b/misc/Makefile.in
index 319264c..ee7f5c5 100644
--- a/misc/Makefile.in
+++ b/misc/Makefile.in
@@ -19,7 +19,6 @@
 	lstr.c \
 	lzexpand.c \
 	main.c \
-	mpr.c \
 	network.c \
 	ntdll.c \
 	port.c \
diff --git a/misc/aspi.c b/misc/aspi.c
index 8be4540..bf38b29 100644
--- a/misc/aspi.c
+++ b/misc/aspi.c
@@ -307,7 +307,7 @@
   if (status < 0 || status != in_len) {
       int myerror = errno;
 
-    fprintf(stderr, "not enough bytes written to scsi device bytes=%d .. %d\n", in_len, status);
+    WARN(aspi, "Not enough bytes written to scsi device bytes=%d .. %d\n", in_len, status);
     if (status < 0) {
 	if (myerror == ENOMEM) {
 	    fprintf(stderr, "ASPI: Linux generic scsi driver\n  You probably need to re-compile your kernel with a larger SG_BIG_BUFF value (sg.h)\n  Suggest 130560\n");
diff --git a/misc/callback.c b/misc/callback.c
index 84354d5..2dcf883 100644
--- a/misc/callback.c
+++ b/misc/callback.c
@@ -6,6 +6,7 @@
 
 #include <assert.h>
 #include <stdio.h>
+#include "debug.h"
 #include "windows.h"
 #include "callback.h"
 #include "task.h"
@@ -27,7 +28,7 @@
  */
 static LONG WINAPI CALLBACK_CallRegisterProc( CONTEXT *context, INT32 offset)
 {
-    fprintf( stderr, "Cannot call a register proc in Winelib\n" );
+    ERR(relay, "Cannot call a register proc in Winelib\n" );
     assert( FALSE );
     return 0;
 }
@@ -208,7 +209,7 @@
 	    );
 	    break;
     default:
-	    fprintf(stderr,"CALLBACK_CallWOWCallback16Ex(), %ld arguments not supported.!n",cbArgs);
+	    WARN(relay,"(%ld) arguments not supported.\n",cbArgs);
 	    if (dwFlags == WCB16_CDECL)
 		HeapFree(GetProcessHeap(),0,args);
 	    return FALSE;
diff --git a/misc/comm.c b/misc/comm.c
index 169d733..333adb9 100644
--- a/misc/comm.c
+++ b/misc/comm.c
@@ -77,10 +77,10 @@
 			}
 			stat(temp, &st);
 			if (!S_ISCHR(st.st_mode)) 
-				fprintf(stderr,"comm: can't use `%s' as %s !\n", temp, option);
+				WARN(comm,"Can't use `%s' as %s !\n", temp, option);
 			else
 				if ((COM[x].devicename = malloc(strlen(temp)+1)) == NULL) 
-					fprintf(stderr,"comm: can't malloc for device info!\n");
+					WARN(comm,"Can't malloc for device info!\n");
 				else {
 					COM[x].fd = 0;
 					strcpy(COM[x].devicename, temp);
@@ -99,10 +99,10 @@
 		else {
 			stat(temp, &st);
 			if (!S_ISCHR(st.st_mode)) 
-				fprintf(stderr,"comm: can't use `%s' as %s !\n", temp, option);
+				WARN(comm,"Can't use `%s' as %s !\n", temp, option);
 			else 
 				if ((LPT[x].devicename = malloc(strlen(temp)+1)) == NULL) 
-					fprintf(stderr,"comm: can't malloc for device info!\n");
+					WARN(comm,"Can't malloc for device info!\n");
 				else {
 					LPT[x].fd = 0;
 					strcpy(LPT[x].devicename, temp);
@@ -177,7 +177,7 @@
 	
 
 		if (port-- == 0) {
-			fprintf(stderr, "comm: BUG ! COM0 can't exists!.\n");
+			ERR(comm, "BUG ! COM0 can't exists!.\n");
 			commerror = IE_BADID;
 		}
 
@@ -229,7 +229,7 @@
 				lpdcb->Parity = ODDPARITY;
 				break;			
 			default:
-				fprintf(stderr,"comm: unknown parity `%c'!\n", *ptr);
+				WARN(comm,"Unknown parity `%c'!\n", *ptr);
 				return -1;
 		}
 
@@ -247,7 +247,7 @@
 				lpdcb->StopBits = TWOSTOPBITS;
 				break;			
 			default:
-				fprintf(stderr,"comm: unknown # of stopbits `%c'!\n", *ptr);
+				WARN(comm,"Unknown # of stopbits `%c'!\n", *ptr);
 				return -1;
 		}
 	}	
@@ -278,7 +278,7 @@
 	if (!lstrncmpi32A(device,"COM",3)) {
 		port=device[3]-'0';
 		if (port--==0) {
-			fprintf(stderr,"comm:BUG! COM0 can't exists!.\n");
+			ERR(comm,"BUG! COM0 can't exists!.\n");
 			return FALSE;
 		}
 		if (!ValidCOMPort(port))
@@ -346,19 +346,19 @@
 		flag=0;
 		if (!strncmp("baud=",ptr,5)) {
 			if (!sscanf(ptr+5,"%ld",&x))
-				fprintf(stderr,"BuildCommDCB32A:Couldn't parse %s\n",ptr);
+				WARN(comm,"Couldn't parse %s\n",ptr);
 			lpdcb->BaudRate = x;
 			flag=1;
 		}
 		if (!strncmp("stop=",ptr,5)) {
 			if (!sscanf(ptr+5,"%ld",&x))
-				fprintf(stderr,"BuildCommDCB32A:Couldn't parse %s\n",ptr);
+				WARN(comm,"Couldn't parse %s\n",ptr);
 			lpdcb->StopBits = x;
 			flag=1;
 		}
 		if (!strncmp("data=",ptr,5)) {
 			if (!sscanf(ptr+5,"%ld",&x))
-				fprintf(stderr,"BuildCommDCB32A:Couldn't parse %s\n",ptr);
+				WARN(comm,"Couldn't parse %s\n",ptr);
 			lpdcb->ByteSize = x;
 			flag=1;
 		}
@@ -382,7 +382,7 @@
 			flag=1;
 		}
 		if (!flag)
-			fprintf(stderr,"BuildCommDCB32A: Unhandled specifier '%s', please report.\n",ptr);
+			ERR(comm,"Unhandled specifier '%s', please report.\n",ptr);
 		ptr=strtok(NULL," ");
 	}
 	if (lpdcb->BaudRate==110)
@@ -428,7 +428,7 @@
 		port = device[3] - '0';
 
 		if (port-- == 0) {
-			fprintf(stderr, "comm: BUG ! COM0 doesn't exist !\n");
+			ERR(comm, "BUG ! COM0 doesn't exist !\n");
 			commerror = IE_BADID;
 		}
 
@@ -636,8 +636,7 @@
 			break;
 
 		default:
-			fprintf(stderr,
-			"EscapeCommFunction fd: %d, unknown function: %d\n", 
+			WARN(comm,"(fd=%d,nFunction=%d): Unknown function\n", 
 			fd, nFunction);
 			break;				
 	}
@@ -709,8 +708,7 @@
 			ptr->suspended = 0;
 			break;
 		default:
-			fprintf(stderr,
-			"EscapeCommFunction32 fd: %d, unknown function: %d\n", 
+			WARN(comm,"(fd=%d,nFunction=%d): Unknown function\n", 
 			fd, nFunction);
 			break;				
 	}
@@ -737,8 +735,7 @@
 			break;
 		case 1:	queue = TCIFLUSH;
 			break;
-		default:fprintf(stderr,
-				"FlushComm fd: %d, UNKNOWN queue: %d\n", 
+		default:WARN(comm,"(fd=%d,fnQueue=%d):Unknown queue\n", 
 				fd, fnQueue);
 			return -1;
 		}
@@ -774,11 +771,11 @@
 		lpStat->status = 0;
 
 		rc = ioctl(fd, TIOCOUTQ, &cnt);
-		if (rc) fprintf(stderr, "Error !\n");
+		if (rc) WARN(comm, "Error !\n");
 		lpStat->cbOutQue = cnt;
 
 		rc = ioctl(fd, TIOCINQ, &cnt);
-                if (rc) fprintf(stderr, "Error !\n");
+                if (rc) WARN(comm, "Error !\n");
 		lpStat->cbInQue = cnt;
 
     		TRACE(comm, "fd %d, error %d, lpStat %d %d %d\n",
@@ -1727,9 +1724,7 @@
  */
 BOOL32 WINAPI GetCommTimeouts(INT32 fd,LPCOMMTIMEOUTS lptimeouts)
 {
-	fprintf(stderr,"GetCommTimeouts(%x,%p), empty stub.\n",
-		fd,lptimeouts
-	);
+	FIXME(comm,"(%x,%p):stub.\n",fd,lptimeouts);
 	return TRUE;
 }
 
@@ -1737,9 +1732,7 @@
  *	SetCommTimeouts		(KERNEL32.453)
  */
 BOOL32 WINAPI SetCommTimeouts(INT32 fd,LPCOMMTIMEOUTS lptimeouts) {
-	fprintf(stderr,"SetCommTimeouts(%x,%p), empty stub.\n",
-		fd,lptimeouts
-	);
+	FIXME(comm,"(%x,%p):stub.\n",fd,lptimeouts);
 	return TRUE;
 }
 
@@ -1749,7 +1742,7 @@
 BOOL16 WINAPI EnableCommNotification( INT16 fd, HWND16 hwnd,
                                       INT16 cbWriteNotify, INT16 cbOutQueue )
 {
-	fprintf(stderr, "EnableCommNotification(%d, %x, %d, %d), empty stub.\n", fd, hwnd, cbWriteNotify, cbOutQueue);
+	FIXME(comm, "(%d, %x, %d, %d):stub.\n", fd, hwnd, cbWriteNotify, cbOutQueue);
 	return TRUE;
 }
 
diff --git a/misc/commdlg.c b/misc/commdlg.c
index e7122a6..d8ec825 100644
--- a/misc/commdlg.c
+++ b/misc/commdlg.c
@@ -18,6 +18,8 @@
 #include "resource.h"
 #include "drive.h"
 #include "debug.h"
+#include "font.h"
+#include "winproc.h"
 
 static	DWORD 		CommDlgLastError = 0;
 
@@ -45,7 +47,7 @@
 	if (hFolder == 0 || hFolder2 == 0 || hFloppy == 0 || 
 	    hHDisk == 0 || hCDRom == 0)
 	{	
-	    fprintf(stderr, "FileDlg_Init // Error loading bitmaps !");
+	    WARN(commdlg, "Error loading bitmaps !\nprin");
 	    return FALSE;
 	}
 	initialized = TRUE;
@@ -611,7 +613,7 @@
   if (!FILEDLG_ScanDir(hWnd, tmpstr)) {
     *tmpstr = 0;
     if (!FILEDLG_ScanDir(hWnd, tmpstr))
-      fprintf(stderr, "FileDlg: couldn't read initial directory %s!\n",tmpstr);
+      WARN(commdlg, "Couldn't read initial directory %s!\n",tmpstr);
   }
   /* select current drive in combo 2, omit missing drives */
   for(i=0, n=-1; i<=DRIVE_GetCurrentDrive(); i++)
@@ -630,7 +632,6 @@
 /***********************************************************************
  *                              FILEDLG_WMCommand               [internal]
  */
-BOOL32 in_lst1=FALSE;
 BOOL32 in_update=FALSE;
 
 static LRESULT FILEDLG_WMCommand(HWND16 hWnd, WPARAM16 wParam, LPARAM lParam) 
@@ -652,10 +653,7 @@
     case lst1: /* file list */
       FILEDLG_StripEditControl(hWnd);
       if (notification == LBN_DBLCLK)
-	{
-	  in_lst1=TRUE;
 	goto almost_ok;
-	}
       lRet = SendDlgItemMessage16(hWnd, lst1, LB_GETCURSEL16, 0, 0);
       if (lRet == LB_ERR) return TRUE;
       if ((pstr = SEGPTR_ALLOC(512)))
@@ -759,12 +757,9 @@
 				 PTR_SEG_TO_LIN(lpofn->lpstrFilter),
 				 lRet), sizeof(tmpstr2));
       SetDlgItemText32A( hWnd, edt1, tmpstr2 );
-      if (in_lst1)
-	{
+      if (!in_update)
       /* if ScanDir succeeds, we have changed the directory */
-	  in_lst1 = FALSE;
       if (FILEDLG_ScanDir(hWnd, tmpstr)) return TRUE;
-	}
       /* if not, this must be a filename */
       *pstr2 = 0;
       if (pstr != NULL)
@@ -791,10 +786,7 @@
 	   strcat(tmpstr2, "\\");
 	strncat(tmpstr2, tmpstr, 511-strlen(tmpstr2)); tmpstr2[511]=0;
 	if (lpofn->lpstrFile)
-	  {
-	    strncpy(PTR_SEG_TO_LIN(lpofn->lpstrFile), tmpstr2,lpofn->nMaxFile-1);
-	    *((LPSTR)PTR_SEG_TO_LIN(lpofn->lpstrFile)+lpofn->nMaxFile) ='\0';
-      }
+	  lstrcpyn32A(PTR_SEG_TO_LIN(lpofn->lpstrFile), tmpstr2,lpofn->nMaxFile);
       }
       lpofn->nFileOffset = strrchr(tmpstr2,'\\') - tmpstr2 +1;
       lpofn->nFileExtension = 0;
@@ -949,10 +941,8 @@
      * FIXME : Should respond to FR_ENABLETEMPLATE and FR_ENABLEHOOK here
      * For now, only the standard dialog works.
      */
-    /*
-     * FIXME : We should do error checking on the lpFind structure here
-     * and make CommDlgExtendedError() return the error condition.
-     */
+    if (lpFind->Flags & (FR_ENABLETEMPLATE | FR_ENABLETEMPLATEHANDLE | 
+	FR_ENABLEHOOK)) FIXME(commdlg, ": unimplemented flag (ignored)\n");     
     ptr = SYSRES_GetResPtr( SYSRES_DIALOG_FIND_TEXT );
     hInst = WIN_GetWindowInstance( lpFind->hwndOwner );
     return DIALOG_CreateIndirect( hInst, ptr, TRUE, lpFind->hwndOwner,
@@ -972,10 +962,8 @@
      * FIXME : Should respond to FR_ENABLETEMPLATE and FR_ENABLEHOOK here
      * For now, only the standard dialog works.
      */
-    /*
-     * FIXME : We should do error checking on the lpFind structure here
-     * and make CommDlgExtendedError() return the error condition.
-     */
+    if (lpFind->Flags & (FR_ENABLETEMPLATE | FR_ENABLETEMPLATEHANDLE | 
+	FR_ENABLEHOOK)) FIXME(commdlg, ": unimplemented flag (ignored)\n");     
     ptr = SYSRES_GetResPtr( SYSRES_DIALOG_FIND_TEXT );
     hInst = WIN_GetWindowInstance( lpFind->hwndOwner );
     return DIALOG_CreateIndirect( hInst, ptr, TRUE, lpFind->hwndOwner,
@@ -994,10 +982,8 @@
      * FIXME : Should respond to FR_ENABLETEMPLATE and FR_ENABLEHOOK here
      * For now, only the standard dialog works.
      */
-    /*
-     * FIXME : We should do error checking on the lpFind structure here
-     * and make CommDlgExtendedError() return the error condition.
-     */
+    if (lpFind->Flags & (FR_ENABLETEMPLATE | FR_ENABLETEMPLATEHANDLE | 
+	FR_ENABLEHOOK)) FIXME(commdlg, ": unimplemented flag (ignored)\n");     
     ptr = SYSRES_GetResPtr( SYSRES_DIALOG_FIND_TEXT );
     hInst = WIN_GetWindowInstance( lpFind->hwndOwner );
     return DIALOG_CreateIndirect( hInst, ptr, TRUE, lpFind->hwndOwner,
@@ -1014,13 +1000,11 @@
     LPFINDREPLACE16 lpFind = (LPFINDREPLACE16)PTR_SEG_TO_LIN(find);
 
     /*
-     * FIXME : Should respond to FR_ENABLETEMPLATE and FR_ENABLEHOOK here
-     * For now, only the standard dialog works.
-     */
-    /*
      * FIXME : We should do error checking on the lpFind structure here
      * and make CommDlgExtendedError() return the error condition.
      */
+    if (lpFind->Flags & (FR_ENABLETEMPLATE | FR_ENABLETEMPLATEHANDLE | 
+	FR_ENABLEHOOK)) FIXME(commdlg, ": unimplemented flag (ignored)\n");     
     ptr = SYSRES_GetResPtr( SYSRES_DIALOG_REPLACE_TEXT );
     hInst = WIN_GetWindowInstance( lpFind->hwndOwner );
     return DIALOG_CreateIndirect( hInst, ptr, TRUE, lpFind->hwndOwner,
@@ -1040,10 +1024,8 @@
      * FIXME : Should respond to FR_ENABLETEMPLATE and FR_ENABLEHOOK here
      * For now, only the standard dialog works.
      */
-    /*
-     * FIXME : We should do error checking on the lpFind structure here
-     * and make CommDlgExtendedError() return the error condition.
-     */
+    if (lpFind->Flags & (FR_ENABLETEMPLATE | FR_ENABLETEMPLATEHANDLE |
+	FR_ENABLEHOOK)) FIXME(commdlg, ": unimplemented flag (ignored)\n");     
     ptr = SYSRES_GetResPtr( SYSRES_DIALOG_REPLACE_TEXT );
     hInst = WIN_GetWindowInstance( lpFind->hwndOwner );
     return DIALOG_CreateIndirect( hInst, ptr, TRUE, lpFind->hwndOwner,
@@ -1059,13 +1041,11 @@
     LPCVOID ptr;
 
     /*
-     * FIXME : Should respond to FR_ENABLETEMPLATE and FR_ENABLEHOOK here
-     * For now, only the standard dialog works.
-     */
-    /*
      * FIXME : We should do error checking on the lpFind structure here
      * and make CommDlgExtendedError() return the error condition.
      */
+    if (lpFind->Flags & (FR_ENABLETEMPLATE | FR_ENABLETEMPLATEHANDLE | 
+	FR_ENABLEHOOK)) FIXME(commdlg, ": unimplemented flag (ignored)\n");
     ptr = SYSRES_GetResPtr( SYSRES_DIALOG_REPLACE_TEXT );
     hInst = WIN_GetWindowInstance( lpFind->hwndOwner );
     return DIALOG_CreateIndirect( hInst, ptr, TRUE, lpFind->hwndOwner,
@@ -2162,7 +2142,7 @@
   if (lpp->hdcMem)
       BitBlt32(hDC,0,0,rect.right,rect.bottom,lpp->hdcMem,0,0,SRCCOPY);
   else
-    fprintf(stderr,"choose color: hdcMem is not defined\n");
+    WARN(commdlg,"choose color: hdcMem is not defined\n");
   ReleaseDC32(hwnd,hDC);
  }
 }
@@ -2700,18 +2680,42 @@
      return FALSE ;
 }
 
+static void CFn_CHOOSEFONT16to32A(LPCHOOSEFONT16 chf16, LPCHOOSEFONT32A chf32a)
+{
+  chf32a->lStructSize=sizeof(CHOOSEFONT32A);
+  chf32a->hwndOwner=chf16->hwndOwner;
+  chf32a->hDC=chf16->hDC;
+  chf32a->iPointSize=chf16->iPointSize;
+  chf32a->Flags=chf16->Flags;
+  chf32a->rgbColors=chf16->rgbColors;
+  chf32a->lCustData=chf16->lCustData;
+  chf32a->lpfnHook=NULL;
+  chf32a->lpTemplateName=PTR_SEG_TO_LIN(chf16->lpTemplateName);
+  chf32a->hInstance=chf16->hInstance;
+  chf32a->lpszStyle=PTR_SEG_TO_LIN(chf16->lpszStyle);
+  chf32a->nFontType=chf16->nFontType;
+  chf32a->nSizeMax=chf16->nSizeMax;
+  chf32a->nSizeMin=chf16->nSizeMin;
+  FONT_LogFont16To32A(PTR_SEG_TO_LIN(chf16->lpLogFont), chf32a->lpLogFont);
+}
 
 
 /***********************************************************************
- *                        ChooseFont   (COMMDLG.15)     
+ *                        ChooseFont16   (COMMDLG.15)     
  */
-BOOL16 WINAPI ChooseFont(LPCHOOSEFONT lpChFont)
+BOOL16 WINAPI ChooseFont16(LPCHOOSEFONT16 lpChFont)
 {
     HINSTANCE16 hInst;
     HANDLE16 hDlgTmpl = 0;
     BOOL16 bRet = FALSE, win32Format = FALSE;
     LPCVOID template;
     HWND32 hwndDialog;
+    CHOOSEFONT32A cf32a;
+    LOGFONT32A lf32a;
+    SEGPTR lpTemplateName;
+    
+    cf32a.lpLogFont=&lf32a;
+    CFn_CHOOSEFONT16to32A(lpChFont, &cf32a);
 
     TRACE(commdlg,"ChooseFont\n");
     if (!lpChFont) return FALSE;    
@@ -2748,17 +2752,71 @@
     }
 
     hInst = WIN_GetWindowInstance( lpChFont->hwndOwner );
-
+    
+    /* lpTemplateName is not used in the dialog */
+    lpTemplateName=lpChFont->lpTemplateName;
+    lpChFont->lpTemplateName=(SEGPTR)&cf32a;
+    
     hwndDialog = DIALOG_CreateIndirect( hInst, template, win32Format,
                                         lpChFont->hwndOwner,
                       (DLGPROC16)MODULE_GetWndProcEntry16("FormatCharDlgProc"),
                                         (DWORD)lpChFont, WIN_PROC_16 );
     if (hwndDialog) bRet = DIALOG_DoDialogBox(hwndDialog, lpChFont->hwndOwner);
     if (hDlgTmpl) FreeResource16( hDlgTmpl );
+    lpChFont->lpTemplateName=lpTemplateName;
+    FONT_LogFont32ATo16(cf32a.lpLogFont, 
+        (LPLOGFONT16)(PTR_SEG_TO_LIN(lpChFont->lpLogFont)));
     return bRet;
 }
 
 
+/***********************************************************************
+ *           ChooseFont32A   (COMDLG32.3)
+ */
+BOOL32 WINAPI ChooseFont32A(LPCHOOSEFONT32A lpChFont)
+{
+  BOOL32 bRet=FALSE;
+  HWND32 hwndDialog;
+  HINSTANCE32 hInst=WIN_GetWindowInstance( lpChFont->hwndOwner );
+  LPCVOID template = SYSRES_GetResPtr( SYSRES_DIALOG_CHOOSE_FONT );
+  if (lpChFont->Flags & (CF_SELECTSCRIPT | CF_NOVERTFONTS | CF_ENABLETEMPLATE |
+    CF_ENABLETEMPLATEHANDLE)) FIXME(commdlg, ": unimplemented flag (ignored)\n");
+  hwndDialog = DIALOG_CreateIndirect(hInst, template, TRUE, lpChFont->hwndOwner,
+            (DLGPROC16)FormatCharDlgProc32A, (LPARAM)lpChFont, WIN_PROC_32A );
+  if (hwndDialog) bRet = DIALOG_DoDialogBox(hwndDialog, lpChFont->hwndOwner);  
+  return bRet;
+}
+
+/***********************************************************************
+ *           ChooseFont32W   (COMDLG32.4)
+ */
+BOOL32 WINAPI ChooseFont32W(LPCHOOSEFONT32W lpChFont)
+{
+  BOOL32 bRet=FALSE;
+  HWND32 hwndDialog;
+  HINSTANCE32 hInst=WIN_GetWindowInstance( lpChFont->hwndOwner );
+  CHOOSEFONT32A cf32a;
+  LOGFONT32A lf32a;
+  LPCVOID template = SYSRES_GetResPtr( SYSRES_DIALOG_CHOOSE_FONT );
+  if (lpChFont->Flags & (CF_SELECTSCRIPT | CF_NOVERTFONTS | CF_ENABLETEMPLATE |
+    CF_ENABLETEMPLATEHANDLE)) FIXME(commdlg, ": unimplemented flag (ignored)\n");
+  memcpy(&cf32a, lpChFont, sizeof(cf32a));
+  memcpy(&lf32a, lpChFont->lpLogFont, sizeof(LOGFONT32A));
+  lstrcpynWtoA(lf32a.lfFaceName, lpChFont->lpLogFont->lfFaceName, LF_FACESIZE);
+  cf32a.lpLogFont=&lf32a;
+  cf32a.lpszStyle=HEAP_strdupWtoA(GetProcessHeap(), 0, lpChFont->lpszStyle);
+  lpChFont->lpTemplateName=(LPWSTR)&cf32a;
+  hwndDialog=DIALOG_CreateIndirect(hInst, template, TRUE, lpChFont->hwndOwner,
+            (DLGPROC16)FormatCharDlgProc32W, (LPARAM)lpChFont, WIN_PROC_32W );
+  if (hwndDialog)bRet=DIALOG_DoDialogBox(hwndDialog, lpChFont->hwndOwner);  
+  HeapFree(GetProcessHeap(), 0, cf32a.lpszStyle);
+  lpChFont->lpTemplateName=(LPWSTR)cf32a.lpTemplateName;
+  memcpy(lpChFont->lpLogFont, &lf32a, sizeof(CHOOSEFONT32A));
+  lstrcpynAtoW(lpChFont->lpLogFont->lfFaceName, lf32a.lfFaceName, LF_FACESIZE);
+  return bRet;
+}
+
+
 #define TEXT_EXTRAS 4
 #define TEXT_COLORS 16
 
@@ -2773,7 +2831,19 @@
 /***********************************************************************
  *                          CFn_HookCallChk                 [internal]
  */
-static BOOL32 CFn_HookCallChk(LPCHOOSEFONT lpcf)
+static BOOL32 CFn_HookCallChk(LPCHOOSEFONT16 lpcf)
+{
+ if (lpcf)
+  if(lpcf->Flags & CF_ENABLEHOOK)
+   if (lpcf->lpfnHook)
+    return TRUE;
+ return FALSE;
+}
+
+/***********************************************************************
+ *                          CFn_HookCallChk32                 [internal]
+ */
+static BOOL32 CFn_HookCallChk32(LPCHOOSEFONT32A lpcf)
 {
  if (lpcf)
   if(lpcf->Flags & CF_ENABLEHOOK)
@@ -2783,18 +2853,14 @@
 }
 
 
-/***********************************************************************
- *                FontFamilyEnumProc                       (COMMDLG.19)
+/*************************************************************************
+ *              AddFontFamily                               [internal]
  */
-INT16 WINAPI FontFamilyEnumProc( SEGPTR logfont, SEGPTR metrics,
-                                 UINT16 nFontType, LPARAM lParam )
+static INT32 AddFontFamily(LPLOGFONT32A lplf, UINT32 nFontType, 
+                           LPCHOOSEFONT32A lpcf, HWND32 hwnd)
 {
   int i;
   WORD w;
-  HWND16 hwnd=LOWORD(lParam);
-  HWND16 hDlg=GetParent16(hwnd);
-  LPCHOOSEFONT lpcf=(LPCHOOSEFONT)GetWindowLong32A(hDlg, DWL_USER); 
-  LOGFONT16 *lplf = (LOGFONT16 *)PTR_SEG_TO_LIN( logfont );
 
   TRACE(commdlg,"font=%s (nFontType=%d)\n", lplf->lfFaceName,nFontType);
 
@@ -2805,28 +2871,60 @@
    if (lplf->lfCharSet != ANSI_CHARSET)
      return 1;
   if (lpcf->Flags & CF_TTONLY)
-   if (!(nFontType & 0x0004))   /* this means 'TRUETYPE_FONTTYPE' */
+   if (!(nFontType & TRUETYPE_FONTTYPE))
      return 1;   
 
-  i=SendMessage16(hwnd,CB_ADDSTRING16,0,
-                  (LPARAM)logfont + ((char *)lplf->lfFaceName - (char *)lplf));
+  i=SendMessage32A(hwnd, CB_ADDSTRING32, 0, (LPARAM)lplf->lfFaceName);
   if (i!=CB_ERR)
   {
     w=(lplf->lfCharSet << 8) | lplf->lfPitchAndFamily;
-    SendMessage16(hwnd, CB_SETITEMDATA16,i,MAKELONG(nFontType,w));
+    SendMessage32A(hwnd, CB_SETITEMDATA32, i, MAKELONG(nFontType,w));
     return 1 ;        /* store some important font information */
   }
   else
     return 0;
 }
 
+typedef struct
+{
+  HWND32 hWnd1;
+  HWND32 hWnd2;
+  LPCHOOSEFONT32A lpcf32a;
+} CFn_ENUMSTRUCT, *LPCFn_ENUMSTRUCT;
+
+/*************************************************************************
+ *              FontFamilyEnumProc32                           [internal]
+ */
+INT32 WINAPI FontFamilyEnumProc32(LPENUMLOGFONT32A lpEnumLogFont, 
+	  LPNEWTEXTMETRIC32A metrics, UINT32 nFontType, LPARAM lParam)
+{
+  LPCFn_ENUMSTRUCT e;
+  e=(LPCFn_ENUMSTRUCT)lParam;
+  return AddFontFamily(&lpEnumLogFont->elfLogFont, nFontType, e->lpcf32a, e->hWnd1);
+}
+
+/***********************************************************************
+ *                FontFamilyEnumProc16                     (COMMDLG.19)
+ */
+INT16 WINAPI FontFamilyEnumProc16( SEGPTR logfont, SEGPTR metrics,
+                                   UINT16 nFontType, LPARAM lParam )
+{
+  HWND16 hwnd=LOWORD(lParam);
+  HWND16 hDlg=GetParent16(hwnd);
+  LPCHOOSEFONT16 lpcf=(LPCHOOSEFONT16)GetWindowLong32A(hDlg, DWL_USER); 
+  LOGFONT16 *lplf = (LOGFONT16 *)PTR_SEG_TO_LIN( logfont );
+  LOGFONT32A lf32a;
+  FONT_LogFont16To32A(lplf, &lf32a);
+  return AddFontFamily(&lf32a, nFontType, (LPCHOOSEFONT32A)lpcf->lpTemplateName,
+                       hwnd);
+}
+
 /*************************************************************************
  *              SetFontStylesToCombo2                           [internal]
  *
  * Fill font style information into combobox  (without using font.c directly)
  */
-static int SetFontStylesToCombo2(HWND16 hwnd, HDC16 hdc, LPLOGFONT16 lplf,
-                                 LPTEXTMETRIC16 lptm)
+static int SetFontStylesToCombo2(HWND32 hwnd, HDC32 hdc, LPLOGFONT32A lplf)
 {
    #define FSTYLES 4
    struct FONTSTYLE
@@ -2836,21 +2934,22 @@
    static struct FONTSTYLE fontstyles[FSTYLES]={ 
           { 0,FW_NORMAL,"Regular"},{0,FW_BOLD,"Bold"},
           { 1,FW_NORMAL,"Italic"}, {1,FW_BOLD,"Bold Italic"}};
-   HFONT16 hf;                      
+   HFONT16 hf;
+   TEXTMETRIC16 tm;
    int i,j;
 
    for (i=0;i<FSTYLES;i++)
    {
      lplf->lfItalic=fontstyles[i].italic;
      lplf->lfWeight=fontstyles[i].weight;
-     hf=CreateFontIndirect16(lplf);
+     hf=CreateFontIndirect32A(lplf);
      hf=SelectObject32(hdc,hf);
-     GetTextMetrics16(hdc,lptm);
+     GetTextMetrics16(hdc,&tm);
      hf=SelectObject32(hdc,hf);
      DeleteObject32(hf);
 
-     if (lptm->tmWeight==fontstyles[i].weight &&
-         lptm->tmItalic==fontstyles[i].italic)    /* font successful created ? */
+     if (tm.tmWeight==fontstyles[i].weight &&
+         tm.tmItalic==fontstyles[i].italic)    /* font successful created ? */
      {
        char *str = SEGPTR_STRDUP(fontstyles[i].stname);
        j=SendMessage16(hwnd,CB_ADDSTRING16,0,(LPARAM)SEGPTR_GET(str) );
@@ -2862,56 +2961,50 @@
      }
    }  
   return 0;
- }
+}
 
 /*************************************************************************
+ *              AddFontSizeToCombo3                           [internal]
+ */
+static int AddFontSizeToCombo3(HWND32 hwnd, UINT32 h, LPCHOOSEFONT32A lpcf)
+{
+    int j;
+    char buffer[20];
+
+    if (  (!(lpcf->Flags & CF_LIMITSIZE))  ||
+        ((lpcf->Flags & CF_LIMITSIZE) && (h >= lpcf->nSizeMin) && (h <= lpcf->nSizeMax)))
+    {
+        sprintf(buffer, "%2d", h);
+	j=SendMessage32A(hwnd, CB_FINDSTRINGEXACT32, -1, (LPARAM)buffer);
+	if (j==CB_ERR)
+	{
+    	    j=SendMessage32A(hwnd, CB_ADDSTRING32, 0, (LPARAM)buffer);	
+    	    if (j!=CB_ERR) j = SendMessage32A(hwnd, CB_SETITEMDATA32, j, h); 
+    	    if (j==CB_ERR) return 1;
+	}
+    }
+    return 0;
+} 
+ 
+/*************************************************************************
  *              SetFontSizesToCombo3                           [internal]
  */
-static int SetFontSizesToCombo3(HWND16 hwnd, LPLOGFONT16 lplf, LPCHOOSEFONT lpcf)
+static int SetFontSizesToCombo3(HWND32 hwnd, LPCHOOSEFONT32A lpcf)
 {
   static const int sizes[]={8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72,0};
-  int h,i,j;
-  char *buffer;
-  
-  if (!(buffer = SEGPTR_ALLOC(20))) return 1;
-  for (i=0;sizes[i] && !lplf->lfHeight;i++)
-  {
-   h=lplf->lfHeight ? lplf->lfHeight : sizes[i];
+  int i;
 
-   if (  (!(lpcf->Flags & CF_LIMITSIZE))  ||
-           ((lpcf->Flags & CF_LIMITSIZE) && (h >= lpcf->nSizeMin) && (h <= lpcf->nSizeMax)))
-   {
-      sprintf(buffer,"%2d",h);
-      j=SendMessage16(hwnd,CB_FINDSTRING16,-1,(LPARAM)SEGPTR_GET(buffer));
-      if (j==CB_ERR)
-      {
-        j=SendMessage16(hwnd,CB_ADDSTRING16,0,(LPARAM)SEGPTR_GET(buffer));
-        if (j!=CB_ERR) j = SendMessage16(hwnd, CB_SETITEMDATA16, j, h); 
-        if (j==CB_ERR)
-        {
-            SEGPTR_FREE(buffer);
-            return 1;
-        }
-      }
-   }  
-  }  
-  SEGPTR_FREE(buffer);
- return 0;
+  for (i=0; sizes[i]; i++)
+    if (AddFontSizeToCombo3(hwnd, sizes[i], lpcf)) return 1;
+  return 0;
 }
 
-
 /***********************************************************************
- *                 FontStyleEnumProc                     (COMMDLG.18)
+ *                 AddFontStyle                          [internal]
  */
-INT16 WINAPI FontStyleEnumProc( SEGPTR logfont, SEGPTR metrics,
-                                UINT16 nFontType, LPARAM lParam )
+INT32 AddFontStyle(LPLOGFONT32A lplf, UINT32 nFontType, 
+    LPCHOOSEFONT32A lpcf, HWND32 hcmb2, HWND32 hcmb3, HWND32 hDlg)
 {
-  HWND16 hcmb2=LOWORD(lParam);
-  HWND16 hcmb3=HIWORD(lParam);
-  HWND16 hDlg=GetParent16(hcmb3);
-  LPCHOOSEFONT lpcf=(LPCHOOSEFONT)GetWindowLong32A(hDlg, DWL_USER); 
-  LOGFONT16 *lplf = (LOGFONT16 *)PTR_SEG_TO_LIN(logfont);
-  TEXTMETRIC16 *lptm = (TEXTMETRIC16 *)PTR_SEG_TO_LIN(metrics);
   int i;
   
   TRACE(commdlg,"(nFontType=%d)\n",nFontType);
@@ -2922,48 +3015,83 @@
 	       lplf->lfWeight,lplf->lfItalic,lplf->lfUnderline,
 	       lplf->lfStrikeOut,lplf->lfCharSet, lplf->lfOutPrecision,
 	       lplf->lfClipPrecision,lplf->lfQuality, lplf->lfPitchAndFamily);
+  if (nFontType & RASTER_FONTTYPE)
+  {
+    if (AddFontSizeToCombo3(hcmb3, lplf->lfHeight, lpcf)) return 0;
+  } else if (SetFontSizesToCombo3(hcmb3, lpcf)) return 0;
 
-  if (SetFontSizesToCombo3(hcmb3, lplf ,lpcf))
-   return 0;
-
-  if (!SendMessage16(hcmb2,CB_GETCOUNT16,0,0))
+  if (!SendMessage32A(hcmb2, CB_GETCOUNT32, 0, 0))
   {
        HDC32 hdc= (lpcf->Flags & CF_PRINTERFONTS && lpcf->hDC) ? lpcf->hDC : GetDC32(hDlg);
-       i=SetFontStylesToCombo2(hcmb2,hdc,lplf,lptm);
+       i=SetFontStylesToCombo2(hcmb2,hdc,lplf);
        if (!(lpcf->Flags & CF_PRINTERFONTS && lpcf->hDC))
          ReleaseDC32(hDlg,hdc);
        if (i)
-        return 0;  
+        return 0;
   }
   return 1 ;
+
+}    
+
+/***********************************************************************
+ *                 FontStyleEnumProc16                     (COMMDLG.18)
+ */
+INT16 WINAPI FontStyleEnumProc16( SEGPTR logfont, SEGPTR metrics,
+                                  UINT16 nFontType, LPARAM lParam )
+{
+  HWND16 hcmb2=LOWORD(lParam);
+  HWND16 hcmb3=HIWORD(lParam);
+  HWND16 hDlg=GetParent16(hcmb3);
+  LPCHOOSEFONT16 lpcf=(LPCHOOSEFONT16)GetWindowLong32A(hDlg, DWL_USER); 
+  LOGFONT16 *lplf = (LOGFONT16 *)PTR_SEG_TO_LIN(logfont);
+  LOGFONT32A lf32a;
+  FONT_LogFont16To32A(lplf, &lf32a);
+  return AddFontStyle(&lf32a, nFontType, (LPCHOOSEFONT32A)lpcf->lpTemplateName,
+                      hcmb2, hcmb3, hDlg);
 }
 
+/***********************************************************************
+ *                 FontStyleEnumProc32                     [internal]
+ */
+INT32 WINAPI FontStyleEnumProc32( LPENUMLOGFONT32A lpFont, 
+          LPNEWTEXTMETRIC32A metrics, UINT32 nFontType, LPARAM lParam )
+{
+  LPCFn_ENUMSTRUCT s=(LPCFn_ENUMSTRUCT)lParam;
+  HWND32 hcmb2=s->hWnd1;
+  HWND32 hcmb3=s->hWnd2;
+  HWND32 hDlg=GetParent32(hcmb3);
+  return AddFontStyle(&lpFont->elfLogFont, nFontType, s->lpcf32a, hcmb2,
+                      hcmb3, hDlg);
+}
 
 /***********************************************************************
  *           CFn_WMInitDialog                            [internal]
  */
-LRESULT CFn_WMInitDialog(HWND16 hDlg, WPARAM16 wParam, LPARAM lParam)
+LRESULT CFn_WMInitDialog(HWND32 hDlg, WPARAM32 wParam, LPARAM lParam,
+                         LPCHOOSEFONT32A lpcf)
 {
   HDC32 hdc;
   int i,j,res,init=0;
   long l;
-  LPLOGFONT16 lpxx;
-  HCURSOR16 hcursor=SetCursor16(LoadCursor16(0,IDC_WAIT16));
-  LPCHOOSEFONT lpcf;
+  LPLOGFONT32A lpxx;
+  HCURSOR32 hcursor=SetCursor32(LoadCursor32A(0,IDC_WAIT32A));
 
   SetWindowLong32A(hDlg, DWL_USER, lParam); 
-  lpcf=(LPCHOOSEFONT)lParam;
-  lpxx=PTR_SEG_TO_LIN(lpcf->lpLogFont);
+  lpxx=lpcf->lpLogFont;
   TRACE(commdlg,"WM_INITDIALOG lParam=%08lX\n", lParam);
 
-  if (lpcf->lStructSize != sizeof(CHOOSEFONT))
+  if (lpcf->lStructSize != sizeof(CHOOSEFONT32A))
   {
     ERR(commdlg,"structure size failure !!!\n");
     EndDialog32 (hDlg, 0); 
     return FALSE;
   }
   if (!hBitmapTT)
-    hBitmapTT = LoadBitmap16(0, MAKEINTRESOURCE16(OBM_TRTYPE));
+    hBitmapTT = LoadBitmap32A(0, MAKEINTRESOURCE32A(OBM_TRTYPE));
+
+  /* This font will be deleted by WM_COMMAND */
+  SendDlgItemMessage32A(hDlg,stc6,WM_SETFONT,
+     CreateFont32A(0, 0, 1, 1, 400, 0, 0, 0, 0, 0, 0, 0, 0, NULL),FALSE);
 			 
   if (!(lpcf->Flags & CF_SHOWHELP) || !IsWindow32(lpcf->hwndOwner))
     ShowWindow32(GetDlgItem32(hDlg,pshHelp),SW_HIDE);
@@ -2974,14 +3102,13 @@
     for (res=1,i=0;res && i<TEXT_COLORS;i++)
     {
       /* FIXME: load color name from resource:  res=LoadString(...,i+....,buffer,.....); */
-      char *name = SEGPTR_ALLOC(20);
+      char name[20];
       strcpy( name, "[color name]" );
-      j=SendDlgItemMessage16(hDlg,cmb4,CB_ADDSTRING16,0,(LPARAM)SEGPTR_GET(name));
-      SEGPTR_FREE(name);
-      SendDlgItemMessage16(hDlg,cmb4, CB_SETITEMDATA16,j,textcolors[j]);
+      j=SendDlgItemMessage32A(hDlg, cmb4, CB_ADDSTRING32, 0, (LPARAM)name);
+      SendDlgItemMessage32A(hDlg, cmb4, CB_SETITEMDATA16, j, textcolors[j]);
       /* look for a fitting value in color combobox */
       if (textcolors[j]==lpcf->rgbColors)
-        SendDlgItemMessage16(hDlg,cmb4, CB_SETCURSEL16,j,0);
+        SendDlgItemMessage32A(hDlg,cmb4, CB_SETCURSEL32,j,0);
     }
   }
   else
@@ -2995,50 +3122,52 @@
   hdc= (lpcf->Flags & CF_PRINTERFONTS && lpcf->hDC) ? lpcf->hDC : GetDC32(hDlg);
   if (hdc)
   {
-    if (!EnumFontFamilies16(hdc, NULL,FontFamilyEnumProc,
-                            (LPARAM)GetDlgItem32(hDlg,cmb1)))
+    CFn_ENUMSTRUCT s;
+    s.hWnd1=GetDlgItem32(hDlg,cmb1);
+    s.lpcf32a=lpcf;
+    if (!EnumFontFamilies32A(hdc, NULL, FontFamilyEnumProc32, (LPARAM)&s))
       TRACE(commdlg,"EnumFontFamilies returns 0\n");
     if (lpcf->Flags & CF_INITTOLOGFONTSTRUCT)
     {
       /* look for fitting font name in combobox1 */
-      j=SendDlgItemMessage16(hDlg,cmb1,CB_FINDSTRING16,-1,(LONG)lpxx->lfFaceName);
+      j=SendDlgItemMessage32A(hDlg,cmb1,CB_FINDSTRING32,-1,(LONG)lpxx->lfFaceName);
       if (j!=CB_ERR)
       {
-        SendDlgItemMessage16(hDlg,cmb1,CB_SETCURSEL16,j,0);
-	SendMessage16(hDlg,WM_COMMAND,cmb1,
-                      MAKELONG(GetDlgItem32(hDlg,cmb1),CBN_SELCHANGE));
+        SendDlgItemMessage32A(hDlg, cmb1, CB_SETCURSEL32, j, 0);
+	SendMessage32A(hDlg, WM_COMMAND, MAKEWPARAM(cmb1, CBN_SELCHANGE),
+                       GetDlgItem32(hDlg,cmb1));
         init=1;
         /* look for fitting font style in combobox2 */
         l=MAKELONG(lpxx->lfWeight > FW_MEDIUM ? FW_BOLD:FW_NORMAL,lpxx->lfItalic !=0);
         for (i=0;i<TEXT_EXTRAS;i++)
         {
-          if (l==SendDlgItemMessage16(hDlg,cmb2, CB_GETITEMDATA16,i,0))
-            SendDlgItemMessage16(hDlg,cmb2,CB_SETCURSEL16,i,0);
+          if (l==SendDlgItemMessage32A(hDlg, cmb2, CB_GETITEMDATA32, i, 0))
+            SendDlgItemMessage32A(hDlg, cmb2, CB_SETCURSEL32, i, 0);
         }
       
         /* look for fitting font size in combobox3 */
-        j=SendDlgItemMessage16(hDlg,cmb3,CB_GETCOUNT16,0,0);
+        j=SendDlgItemMessage32A(hDlg, cmb3, CB_GETCOUNT32, 0, 0);
         for (i=0;i<j;i++)
         {
-          if (lpxx->lfHeight==(int)SendDlgItemMessage16(hDlg,cmb3, CB_GETITEMDATA16,i,0))
-            SendDlgItemMessage16(hDlg,cmb3,CB_SETCURSEL16,i,0);
+          if (lpxx->lfHeight==(int)SendDlgItemMessage32A(hDlg,cmb3, CB_GETITEMDATA32,i,0))
+            SendDlgItemMessage32A(hDlg,cmb3,CB_SETCURSEL32,i,0);
         }
       }
-      if (!init)
-      {
-        SendDlgItemMessage16(hDlg,cmb1,CB_SETCURSEL16,0,0);
-	SendMessage16(hDlg,WM_COMMAND,cmb1,
-                      MAKELONG(GetDlgItem32(hDlg,cmb1),CBN_SELCHANGE));      
-      }
     }
+    if (!init)
+    {
+      SendDlgItemMessage32A(hDlg,cmb1,CB_SETCURSEL32,0,0);
+      SendMessage32A(hDlg, WM_COMMAND, MAKEWPARAM(cmb1, CBN_SELCHANGE),
+                       GetDlgItem32(hDlg,cmb1));
+    }    
     if (lpcf->Flags & CF_USESTYLE && lpcf->lpszStyle)
     {
-      j=SendDlgItemMessage16(hDlg,cmb2,CB_FINDSTRING16,-1,(LONG)lpcf->lpszStyle);
+      j=SendDlgItemMessage32A(hDlg,cmb2,CB_FINDSTRING32,-1,(LONG)lpcf->lpszStyle);
       if (j!=CB_ERR)
       {
-        j=SendDlgItemMessage16(hDlg,cmb2,CB_SETCURSEL16,j,0);
-        SendMessage16(hDlg,WM_COMMAND,cmb2,
-                      MAKELONG(GetDlgItem32(hDlg,cmb2),CBN_SELCHANGE));
+        j=SendDlgItemMessage32A(hDlg,cmb2,CB_SETCURSEL32,j,0);
+        SendMessage32A(hDlg,WM_COMMAND,cmb2,
+                       MAKELONG(GetDlgItem32(hDlg,cmb2),CBN_SELCHANGE));
       }
     }
   }
@@ -3051,24 +3180,21 @@
 
   if (!(lpcf->Flags & CF_PRINTERFONTS && lpcf->hDC))
     ReleaseDC32(hDlg,hdc);
-  res=TRUE;
-  if (CFn_HookCallChk(lpcf))
-    res=CallWindowProc16(lpcf->lpfnHook,hDlg,WM_INITDIALOG,wParam,lParam);
-  SetCursor16(hcursor);   
-  return res;
+  SetCursor32(hcursor);   
+  return TRUE;
 }
 
 
 /***********************************************************************
  *           CFn_WMMeasureItem                           [internal]
  */
-LRESULT CFn_WMMeasureItem(HWND16 hDlg, WPARAM16 wParam, LPARAM lParam)
+LRESULT CFn_WMMeasureItem(HWND32 hDlg, WPARAM32 wParam, LPARAM lParam)
 {
-  BITMAP16 bm;
-  LPMEASUREITEMSTRUCT16 lpmi=PTR_SEG_TO_LIN((LPMEASUREITEMSTRUCT16)lParam);
+  BITMAP32 bm;
+  LPMEASUREITEMSTRUCT32 lpmi=(LPMEASUREITEMSTRUCT32)lParam;
   if (!hBitmapTT)
-    hBitmapTT = LoadBitmap16(0, MAKEINTRESOURCE16(OBM_TRTYPE));
-  GetObject16( hBitmapTT, sizeof(bm), &bm );
+    hBitmapTT = LoadBitmap32A(0, MAKEINTRESOURCE32A(OBM_TRTYPE));
+  GetObject32A( hBitmapTT, sizeof(bm), &bm );
   lpmi->itemHeight=bm.bmHeight;
   /* FIXME: use MAX of bm.bmHeight and tm.tmHeight .*/
   return 0;
@@ -3078,45 +3204,52 @@
 /***********************************************************************
  *           CFn_WMDrawItem                              [internal]
  */
-LRESULT CFn_WMDrawItem(HWND16 hDlg, WPARAM16 wParam, LPARAM lParam)
+LRESULT CFn_WMDrawItem(HWND32 hDlg, WPARAM32 wParam, LPARAM lParam)
 {
-  HBRUSH16 hBrush;
-  char *buffer;
-  BITMAP16 bm;
-  COLORREF cr;
-  RECT16 rect;
+  HBRUSH32 hBrush;
+  char buffer[40];
+  BITMAP32 bm;
+  COLORREF cr, oldText=0, oldBk=0;
+  RECT32 rect;
 #if 0  
-  HDC16 hMemDC;
+  HDC32 hMemDC;
   int nFontType;
-  HBITMAP16 hBitmap; /* for later TT usage */
+  HBITMAP32 hBitmap; /* for later TT usage */
 #endif  
-  LPDRAWITEMSTRUCT16 lpdi = (LPDRAWITEMSTRUCT16)PTR_SEG_TO_LIN(lParam);
+  LPDRAWITEMSTRUCT32 lpdi = (LPDRAWITEMSTRUCT32)lParam;
 
   if (lpdi->itemID == 0xFFFF) 			/* got no items */
-    DrawFocusRect16(lpdi->hDC, &lpdi->rcItem);
+    DrawFocusRect32(lpdi->hDC, &lpdi->rcItem);
   else
   {
    if (lpdi->CtlType == ODT_COMBOBOX)
    {
-     hBrush = SelectObject32(lpdi->hDC, GetStockObject32(LTGRAY_BRUSH));
-     SelectObject32(lpdi->hDC, hBrush);
-     FillRect16(lpdi->hDC, &lpdi->rcItem, hBrush);
+     if (lpdi->itemState ==ODS_SELECTED)
+     {
+       hBrush=GetSysColorBrush32(COLOR_HIGHLIGHT);
+       oldText=SetTextColor32(lpdi->hDC, GetSysColor32(COLOR_HIGHLIGHTTEXT));
+       oldBk=SetBkColor32(lpdi->hDC, GetSysColor32(COLOR_HIGHLIGHT));
+     }  else
+     {
+       hBrush = SelectObject32(lpdi->hDC, GetStockObject32(LTGRAY_BRUSH));
+       SelectObject32(lpdi->hDC, hBrush);
+     }
+     FillRect32(lpdi->hDC, &lpdi->rcItem, hBrush);
    }
    else
      return TRUE;	/* this should never happen */
 
    rect=lpdi->rcItem;
-   buffer = SEGPTR_ALLOC(40);
    switch (lpdi->CtlID)
    {
     case cmb1:	/* TRACE(commdlg,"WM_Drawitem cmb1\n"); */
-		SendMessage16(lpdi->hwndItem, CB_GETLBTEXT16, lpdi->itemID,
-			(LPARAM)SEGPTR_GET(buffer));	          
-		GetObject16( hBitmapTT, sizeof(bm), &bm );
-		TextOut16(lpdi->hDC, lpdi->rcItem.left + bm.bmWidth + 10,
-                          lpdi->rcItem.top, buffer, lstrlen16(buffer));
+		SendMessage32A(lpdi->hwndItem, CB_GETLBTEXT32, lpdi->itemID,
+			       (LPARAM)buffer);	          
+		GetObject32A( hBitmapTT, sizeof(bm), &bm );
+		TextOut32A(lpdi->hDC, lpdi->rcItem.left + bm.bmWidth + 10,
+                           lpdi->rcItem.top, buffer, lstrlen32A(buffer));
 #if 0
-		nFontType = SendMessage16(lpdi->hwndItem, CB_GETITEMDATA16, lpdi->itemID,0L);
+		nFontType = SendMessage32A(lpdi->hwndItem, CB_GETITEMDATA32, lpdi->itemID,0L);
 		  /* FIXME: draw bitmap if truetype usage */
 		if (nFontType&TRUETYPE_FONTTYPE)
 		{
@@ -3131,18 +3264,18 @@
 		break;
     case cmb2:
     case cmb3:	/* TRACE(commdlg,"WM_DRAWITEN cmb2,cmb3\n"); */
-		SendMessage16(lpdi->hwndItem, CB_GETLBTEXT16, lpdi->itemID,
-			(LPARAM)SEGPTR_GET(buffer));
-		TextOut16(lpdi->hDC, lpdi->rcItem.left,
-                          lpdi->rcItem.top, buffer, lstrlen16(buffer));
+		SendMessage32A(lpdi->hwndItem, CB_GETLBTEXT32, lpdi->itemID,
+		               (LPARAM)buffer);
+		TextOut32A(lpdi->hDC, lpdi->rcItem.left,
+                           lpdi->rcItem.top, buffer, lstrlen32A(buffer));
 		break;
 
     case cmb4:	/* TRACE(commdlg,"WM_DRAWITEM cmb4 (=COLOR)\n"); */
-		SendMessage16(lpdi->hwndItem, CB_GETLBTEXT16, lpdi->itemID,
-    		    (LPARAM)SEGPTR_GET(buffer));
-		TextOut16(lpdi->hDC, lpdi->rcItem.left +  25+5,
-                          lpdi->rcItem.top, buffer, lstrlen16(buffer));
-		cr = SendMessage16(lpdi->hwndItem, CB_GETITEMDATA16, lpdi->itemID,0L);
+		SendMessage32A(lpdi->hwndItem, CB_GETLBTEXT32, lpdi->itemID,
+    		               (LPARAM)buffer);
+		TextOut32A(lpdi->hDC, lpdi->rcItem.left +  25+5,
+                           lpdi->rcItem.top, buffer, lstrlen32A(buffer));
+		cr = SendMessage32A(lpdi->hwndItem, CB_GETITEMDATA32, lpdi->itemID,0L);
 		hBrush = CreateSolidBrush32(cr);
 		if (hBrush)
 		{
@@ -3161,9 +3294,11 @@
 
     default:	return TRUE;	/* this should never happen */
    }
-   SEGPTR_FREE(buffer);
-   if (lpdi->itemState ==ODS_SELECTED)
-     InvertRect16(lpdi->hDC, &rect);
+   if (lpdi->itemState == ODS_SELECTED)
+   {
+     SetTextColor32(lpdi->hDC, oldText);
+     SetBkColor32(lpdi->hDC, oldBk);
+   }
  }
  return TRUE;
 }
@@ -3171,14 +3306,13 @@
 /***********************************************************************
  *           CFn_WMCtlColor                              [internal]
  */
-LRESULT CFn_WMCtlColor(HWND16 hDlg, WPARAM16 wParam, LPARAM lParam)
+LRESULT CFn_WMCtlColorStatic(HWND32 hDlg, WPARAM32 wParam, LPARAM lParam,
+                             LPCHOOSEFONT32A lpcf)
 {
-  LPCHOOSEFONT lpcf=(LPCHOOSEFONT)GetWindowLong32A(hDlg, DWL_USER); 
-
   if (lpcf->Flags & CF_EFFECTS)
-   if (HIWORD(lParam)==CTLCOLOR_STATIC && GetDlgCtrlID32(LOWORD(lParam))==stc6)
+   if (GetDlgCtrlID32(lParam)==stc6)
    {
-     SetTextColor32(wParam,lpcf->rgbColors);
+     SetTextColor32((HDC32)wParam, lpcf->rgbColors);
      return GetStockObject32(WHITE_BRUSH);
    }
   return 0;
@@ -3187,37 +3321,39 @@
 /***********************************************************************
  *           CFn_WMCommand                               [internal]
  */
-LRESULT CFn_WMCommand(HWND16 hDlg, WPARAM16 wParam, LPARAM lParam)
+LRESULT CFn_WMCommand(HWND32 hDlg, WPARAM32 wParam, LPARAM lParam,
+                      LPCHOOSEFONT32A lpcf)
 {
-  HFONT16 hFont;
+  HFONT32 hFont;
   int i,j;
   long l;
-  HDC16 hdc;
-  LPCHOOSEFONT lpcf=(LPCHOOSEFONT)GetWindowLong32A(hDlg, DWL_USER); 
-  LPLOGFONT16 lpxx=PTR_SEG_TO_LIN(lpcf->lpLogFont);
+  HDC32 hdc;
+  LPLOGFONT32A lpxx=lpcf->lpLogFont;
   
-  TRACE(commdlg,"WM_COMMAND lParam=%08lX\n", lParam);
-  switch (wParam)
+  TRACE(commdlg,"WM_COMMAND wParam=%08lX lParam=%08lX\n", (LONG)wParam, lParam);
+  switch (LOWORD(wParam))
   {
-	case cmb1:if (HIWORD(lParam)==CBN_SELCHANGE)
+	case cmb1:if (HIWORD(wParam)==CBN_SELCHANGE)
 		  {
 		    hdc=(lpcf->Flags & CF_PRINTERFONTS && lpcf->hDC) ? lpcf->hDC : GetDC32(hDlg);
 		    if (hdc)
 		    {
-                      SendDlgItemMessage16(hDlg,cmb2,CB_RESETCONTENT16,0,0); 
-		      SendDlgItemMessage16(hDlg,cmb3,CB_RESETCONTENT16,0,0);
-		      i=SendDlgItemMessage16(hDlg,cmb1,CB_GETCURSEL16,0,0);
+                      SendDlgItemMessage32A(hDlg, cmb2, CB_RESETCONTENT16, 0, 0); 
+		      SendDlgItemMessage32A(hDlg, cmb3, CB_RESETCONTENT16, 0, 0);
+		      i=SendDlgItemMessage32A(hDlg, cmb1, CB_GETCURSEL16, 0, 0);
 		      if (i!=CB_ERR)
 		      {
-		        HCURSOR16 hcursor=SetCursor16(LoadCursor16(0,IDC_WAIT16));
-                        char *str = SEGPTR_ALLOC(256);
-                        SendDlgItemMessage16(hDlg,cmb1,CB_GETLBTEXT16,i,
-                                             (LPARAM)SEGPTR_GET(str));
+		        HCURSOR32 hcursor=SetCursor32(LoadCursor32A(0,IDC_WAIT32A));
+			CFn_ENUMSTRUCT s;
+                        char str[256];
+                        SendDlgItemMessage32A(hDlg, cmb1, CB_GETLBTEXT32, i,
+                                              (LPARAM)str);
 	                TRACE(commdlg,"WM_COMMAND/cmb1 =>%s\n",str);
-       		        EnumFontFamilies16(hdc,str,FontStyleEnumProc,
-		             MAKELONG(GetDlgItem32(hDlg,cmb2),GetDlgItem32(hDlg,cmb3)));
-		        SetCursor16(hcursor);
-                        SEGPTR_FREE(str);
+			s.hWnd1=GetDlgItem32(hDlg, cmb2);
+			s.hWnd2=GetDlgItem32(hDlg, cmb3);
+			s.lpcf32a=lpcf;
+       		        EnumFontFamilies32A(hdc, str, FontStyleEnumProc32, (LPARAM)&s);
+		        SetCursor32(hcursor);
 		      }
 		      if (!(lpcf->Flags & CF_PRINTERFONTS && lpcf->hDC))
  		        ReleaseDC32(hDlg,hdc);
@@ -3232,18 +3368,18 @@
 	case chx1:
 	case chx2:
 	case cmb2:
-	case cmb3:if (HIWORD(lParam)==CBN_SELCHANGE || HIWORD(lParam)== BN_CLICKED )
+	case cmb3:if (HIWORD(wParam)==CBN_SELCHANGE || HIWORD(wParam)== BN_CLICKED )
 	          {
-                    char *str = SEGPTR_ALLOC(256);
+                    char str[256];
                     TRACE(commdlg,"WM_COMMAND/cmb2,3 =%08lX\n", lParam);
-		    i=SendDlgItemMessage16(hDlg,cmb1,CB_GETCURSEL16,0,0);
+		    i=SendDlgItemMessage32A(hDlg,cmb1,CB_GETCURSEL32,0,0);
 		    if (i==CB_ERR)
                       i=GetDlgItemText32A( hDlg, cmb1, str, 256 );
                     else
                     {
-		      SendDlgItemMessage16(hDlg,cmb1,CB_GETLBTEXT16,i,
-                                           (LPARAM)SEGPTR_GET(str));
-		      l=SendDlgItemMessage16(hDlg,cmb1,CB_GETITEMDATA16,i,0);
+		      SendDlgItemMessage32A(hDlg,cmb1,CB_GETLBTEXT32,i,
+		                            (LPARAM)str);
+		      l=SendDlgItemMessage32A(hDlg,cmb1,CB_GETITEMDATA32,i,0);
 		      j=HIWORD(l);
 		      lpcf->nFontType = LOWORD(l);
 		      /* FIXME:   lpcf->nFontType |= ....  SIMULATED_FONTTYPE and so */
@@ -3253,19 +3389,18 @@
 		      lpxx->lfCharSet=j>>8;
                     }
                     strcpy(lpxx->lfFaceName,str);
-                    SEGPTR_FREE(str);
-		    i=SendDlgItemMessage16(hDlg,cmb2,CB_GETCURSEL16,0,0);
+		    i=SendDlgItemMessage32A(hDlg, cmb2, CB_GETCURSEL32, 0, 0);
 		    if (i!=CB_ERR)
 		    {
-		      l=SendDlgItemMessage16(hDlg,cmb2,CB_GETITEMDATA16,i,0);
+		      l=SendDlgItemMessage32A(hDlg, cmb2, CB_GETITEMDATA32, i, 0);
 		      if (0!=(lpxx->lfItalic=HIWORD(l)))
 		        lpcf->nFontType |= ITALIC_FONTTYPE;
 		      if ((lpxx->lfWeight=LOWORD(l)) > FW_MEDIUM)
 		        lpcf->nFontType |= BOLD_FONTTYPE;
 		    }
-		    i=SendDlgItemMessage16(hDlg,cmb3,CB_GETCURSEL16,0,0);
+		    i=SendDlgItemMessage32A(hDlg, cmb3, CB_GETCURSEL32, 0, 0);
 		    if (i!=CB_ERR)
-		      lpxx->lfHeight=-LOWORD(SendDlgItemMessage16(hDlg,cmb3,CB_GETITEMDATA16,i,0));
+		      lpxx->lfHeight=-LOWORD(SendDlgItemMessage32A(hDlg, cmb3, CB_GETITEMDATA32, i, 0));
 		    else
 		      lpxx->lfHeight=0;
 		    lpxx->lfStrikeOut=IsDlgButtonChecked32(hDlg,chx1);
@@ -3276,14 +3411,18 @@
 		    lpxx->lfQuality=DEFAULT_QUALITY;
                     lpcf->iPointSize= -10*lpxx->lfHeight;
 
-		    hFont=CreateFontIndirect16(lpxx);
+		    hFont=CreateFontIndirect32A(lpxx);
 		    if (hFont)
-		      SendDlgItemMessage16(hDlg,stc6,WM_SETFONT,hFont,TRUE);
-		    /* FIXME: Delete old font ...? */  
+		    {
+		      HFONT32 oldFont=SendDlgItemMessage32A(hDlg, stc6, 
+		          WM_GETFONT, 0, 0);
+		      SendDlgItemMessage32A(hDlg,stc6,WM_SETFONT,hFont,TRUE);
+		      DeleteObject32(oldFont);
+		    }
                   }
                   break;
 
-	case cmb4:i=SendDlgItemMessage16(hDlg,cmb4,CB_GETCURSEL16,0,0);
+	case cmb4:i=SendDlgItemMessage32A(hDlg, cmb4, CB_GETCURSEL32, 0, 0);
 		  if (i!=CB_ERR)
 		  {
 		   lpcf->rgbColors=textcolors[i];
@@ -3293,9 +3432,9 @@
 	
 	case psh15:i=RegisterWindowMessage32A( HELPMSGSTRING );
 		  if (lpcf->hwndOwner)
-		    SendMessage16(lpcf->hwndOwner,i,0,(LPARAM)lpcf);
-		  if (CFn_HookCallChk(lpcf))
-		    CallWindowProc16(lpcf->lpfnHook,hDlg,WM_COMMAND,psh15,(LPARAM)lpcf);
+		    SendMessage32A(lpcf->hwndOwner, i, 0, (LPARAM)GetWindowLong32A(hDlg, DWL_USER));
+/*		  if (CFn_HookCallChk(lpcf))
+		    CallWindowProc16(lpcf->lpfnHook,hDlg,WM_COMMAND,psh15,(LPARAM)lpcf);*/
 		  break;
 
 	case IDOK:if (  (!(lpcf->Flags & CF_LIMITSIZE))  ||
@@ -3308,7 +3447,7 @@
                    char buffer[80];
 	           sprintf(buffer,"Select a font size between %d and %d points.",
                            lpcf->nSizeMin,lpcf->nSizeMax);
-	           MessageBox16(hDlg,buffer,NULL,MB_OK);
+	           MessageBox32A(hDlg, buffer, NULL, MB_OK);
 	          } 
 		  return(TRUE);
 	case IDCANCEL:EndDialog32(hDlg, FALSE);
@@ -3317,20 +3456,30 @@
       return(FALSE);
 }
 
+static LRESULT CFn_WMDestroy(HWND32 hwnd, WPARAM32 wParam, LPARAM lParam)
+{
+  DeleteObject32(SendDlgItemMessage32A(hwnd, stc6, WM_GETFONT, 0, 0));
+  return TRUE;
+}
+
 
 /***********************************************************************
- *           FormatCharDlgProc   (COMMDLG.16)
+ *           FormatCharDlgProc16   (COMMDLG.16)
              FIXME: 1. some strings are "hardcoded", but it's better load from sysres
                     2. some CF_.. flags are not supported
                     3. some TType extensions
  */
-LRESULT WINAPI FormatCharDlgProc(HWND16 hDlg, UINT16 message, WPARAM16 wParam,
-                                 LPARAM lParam)
+LRESULT WINAPI FormatCharDlgProc16(HWND16 hDlg, UINT16 message, WPARAM16 wParam,
+                                   LPARAM lParam)
 {
-  LPCHOOSEFONT lpcf=(LPCHOOSEFONT)GetWindowLong32A(hDlg, DWL_USER);  
+  LPCHOOSEFONT16 lpcf;
+  LPCHOOSEFONT32A lpcf32a;
+  UINT32 uMsg32;
+  WPARAM32 wParam32;
+  LRESULT res=0;  
   if (message!=WM_INITDIALOG)
   {
-   int res=0;
+   lpcf=(LPCHOOSEFONT16)GetWindowLong32A(hDlg, DWL_USER);   
    if (!lpcf)
       return FALSE;
    if (CFn_HookCallChk(lpcf))
@@ -3339,233 +3488,376 @@
     return res;
   }
   else
-    return CFn_WMInitDialog(hDlg,wParam,lParam);
-  switch (message)
+  {
+    lpcf=(LPCHOOSEFONT16)lParam;
+    lpcf32a=(LPCHOOSEFONT32A)lpcf->lpTemplateName;
+    if (!CFn_WMInitDialog(hDlg, wParam, lParam, lpcf32a)) 
+    {
+      TRACE(commdlg, "CFn_WMInitDialog returned FALSE\n");
+      return FALSE;
+    }  
+    if (CFn_HookCallChk(lpcf))
+      return CallWindowProc16(lpcf->lpfnHook,hDlg,WM_INITDIALOG,wParam,lParam);
+  }
+  WINPROC_MapMsg16To32A(message, wParam, &uMsg32, &wParam32, &lParam);
+  lpcf32a=(LPCHOOSEFONT32A)lpcf->lpTemplateName;
+  switch (uMsg32)
     {
       case WM_MEASUREITEM:
-                        return CFn_WMMeasureItem(hDlg,wParam,lParam);
+                        res=CFn_WMMeasureItem(hDlg, wParam32, lParam);
+			break;
       case WM_DRAWITEM:
-                        return CFn_WMDrawItem(hDlg,wParam,lParam);
-      case WM_CTLCOLOR:
-                        return CFn_WMCtlColor(hDlg,wParam,lParam);
+                        res=CFn_WMDrawItem(hDlg, wParam32, lParam);
+			break;
+      case WM_CTLCOLORSTATIC:
+                        res=CFn_WMCtlColorStatic(hDlg, wParam32, lParam, lpcf32a);
+			break;
       case WM_COMMAND:
-                        return CFn_WMCommand(hDlg,wParam,lParam);
+                        res=CFn_WMCommand(hDlg, wParam32, lParam, lpcf32a);
+			break;
+      case WM_DESTROY:
+                        res=CFn_WMDestroy(hDlg, wParam32, lParam);
+			break;
       case WM_CHOOSEFONT_GETLOGFONT: 
                          TRACE(commdlg,"WM_CHOOSEFONT_GETLOGFONT lParam=%08lX\n",
 				      lParam);
 			 FIXME(commdlg, "current logfont back to caller\n");
                         break;
     }
-  return FALSE;
+  WINPROC_UnmapMsg16To32A(uMsg32, wParam32, lParam, res);    
+  return res;
 }
 
-
-#define GET_XXX_FILENAME(xxx) 						\
-BOOL32 WINAPI xxx##32A( LPOPENFILENAME32A ofn )				\
-{									\
-	BOOL16 ret;							\
-	LPOPENFILENAME16 ofn16 = SEGPTR_ALLOC(sizeof(OPENFILENAME16));	\
-									\
-	memset(ofn16,'\0',sizeof(*ofn16));				\
-	ofn16->lStructSize = sizeof(*ofn16);				\
-	ofn16->hwndOwner = ofn->hwndOwner;				\
-	/* FIXME: OPENFILENAME16 got only 16 bit for HINSTANCE... */	\
-	ofn16->hInstance = MODULE_HANDLEtoHMODULE16(ofn->hInstance);	\
-	if (ofn->lpstrFilter) {						\
-		LPSTR	s,x;						\
-									\
-		/* filter is a list...  title\0ext\0......\0\0 */	\
-		s = (LPSTR)ofn->lpstrFilter;				\
-		while (*s)						\
-			s = s+strlen(s)+1;				\
-		s++;							\
-		x = (LPSTR)SEGPTR_ALLOC(s-ofn->lpstrFilter);		\
-		memcpy(x,ofn->lpstrFilter,s-ofn->lpstrFilter);		\
-		ofn16->lpstrFilter = SEGPTR_GET(x);			\
-	}								\
-	if (ofn->lpstrCustomFilter) {					\
-		LPSTR	s,x;						\
-									\
-		/* filter is a list...  title\0ext\0......\0\0 */	\
-		s = (LPSTR)ofn->lpstrCustomFilter;			\
-		while (*s)						\
-			s = s+strlen(s)+1;				\
-		x = SEGPTR_ALLOC(s-ofn->lpstrCustomFilter);		\
-		s++;							\
-		memcpy(x,ofn->lpstrCustomFilter,s-ofn->lpstrCustomFilter);\
-		ofn16->lpstrCustomFilter = SEGPTR_GET(x);		\
-	}								\
-	ofn16->nMaxCustFilter = ofn->nMaxCustFilter;			\
-	ofn16->nFilterIndex = ofn->nFilterIndex;			\
-	if (ofn->nMaxFile)                                              \
-	ofn16->lpstrFile = SEGPTR_GET(SEGPTR_ALLOC(ofn->nMaxFile));	\
-	ofn16->nMaxFile = ofn->nMaxFile;				\
-	if (ofn16->lpstrFileTitle)					\
-		ofn16->lpstrFileTitle= SEGPTR_GET(SEGPTR_STRDUP(ofn->lpstrFileTitle));\
-	ofn16->nMaxFileTitle = ofn->nMaxFileTitle;			\
-        if (ofn16->nMaxFileTitle)                                       \
-                ofn16->lpstrFileTitle = SEGPTR_GET(SEGPTR_ALLOC(ofn->nMaxFileTitle));\
-	if (ofn->lpstrInitialDir)					\
-		ofn16->lpstrInitialDir = SEGPTR_GET(SEGPTR_STRDUP(ofn->lpstrInitialDir));\
-	if (ofn->lpstrTitle)						\
-		ofn16->lpstrTitle = SEGPTR_GET(SEGPTR_STRDUP(ofn->lpstrTitle));\
-	ofn16->Flags = ofn->Flags|OFN_WINE32;				\
-	ofn16->nFileOffset = ofn->nFileOffset;				\
-	ofn16->nFileExtension = ofn->nFileExtension;			\
-	if (ofn->lpstrDefExt)						\
-		ofn16->lpstrDefExt = SEGPTR_GET(SEGPTR_STRDUP(ofn->lpstrDefExt));\
-	ofn16->lCustData = ofn->lCustData;				\
-	ofn16->lpfnHook = (WNDPROC16)ofn->lpfnHook;			\
-									\
-	if (ofn->lpTemplateName)					\
-		ofn16->lpTemplateName = SEGPTR_GET(SEGPTR_STRDUP(ofn->lpTemplateName));\
-									\
-	ret = xxx##16(SEGPTR_GET(ofn16));				\
-									\
-	ofn->nFileOffset = ofn16->nFileOffset;				\
-	ofn->nFileExtension = ofn16->nFileExtension;			\
-	if (ofn16->lpstrFilter)						\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrFilter));	\
-	if (ofn16->lpTemplateName)					\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpTemplateName));	\
-	if (ofn16->lpstrDefExt)						\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrDefExt));	\
-	if (ofn16->lpstrTitle)						\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrTitle));		\
-	if (ofn16->lpstrInitialDir)					\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrInitialDir));	\
-	if (ofn16->lpstrCustomFilter)					\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrCustomFilter));	\
-									\
-	if (ofn16->lpstrFile) {                                         \
-	strcpy(ofn->lpstrFile,PTR_SEG_TO_LIN(ofn16->lpstrFile));	\
-	SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrFile));			\
-	}                                                               \
-									\
-	if (ofn16->lpstrFileTitle) {         				\
-                strcpy(ofn->lpstrFileTitle,PTR_SEG_TO_LIN(ofn16->lpstrFileTitle));\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrFileTitle));	\
-	}                                                               \
-	SEGPTR_FREE(ofn16);						\
-	return ret;							\
-}									\
-									\
-BOOL32 WINAPI xxx##32W( LPOPENFILENAME32W ofn )				\
-{									\
-	BOOL16 ret;							\
-	LPOPENFILENAME16 ofn16 = SEGPTR_ALLOC(sizeof(OPENFILENAME16));	\
-									\
-	memset(ofn16,'\0',sizeof(*ofn16));				\
-	ofn16->lStructSize = sizeof(*ofn16);				\
-	ofn16->hwndOwner = ofn->hwndOwner;				\
-	/* FIXME: OPENFILENAME16 got only 16 bit for HINSTANCE... */	\
-	ofn16->hInstance = MODULE_HANDLEtoHMODULE16(ofn->hInstance);	\
-	if (ofn->lpstrFilter) {						\
-		LPWSTR	s;						\
-		LPSTR	x,y;						\
-		int	n;						\
-									\
-		/* filter is a list...  title\0ext\0......\0\0 */	\
-		s = (LPWSTR)ofn->lpstrFilter;				\
-		while (*s)						\
-			s = s+lstrlen32W(s)+1;				\
-		s++;							\
-		n = s - ofn->lpstrFilter; /* already divides by 2. ptr magic */\
-		x = y = (LPSTR)SEGPTR_ALLOC(n);				\
-		s = (LPWSTR)ofn->lpstrFilter;				\
-		while (*s) {						\
-			lstrcpyWtoA(x,s);				\
-			x+=lstrlen32A(x)+1;				\
-			s+=lstrlen32W(s)+1;				\
-		}							\
-		*x=0;							\
-		ofn16->lpstrFilter = SEGPTR_GET(y);			\
-	}								\
-	if (ofn->lpstrCustomFilter) {					\
-		LPWSTR	s;						\
-		LPSTR	x,y;						\
-		int	n;						\
-									\
-		/* filter is a list...  title\0ext\0......\0\0 */	\
-		s = (LPWSTR)ofn->lpstrCustomFilter;			\
-		while (*s)						\
-			s = s+lstrlen32W(s)+1;				\
-		s++;							\
-		n = s - ofn->lpstrCustomFilter;				\
-		x = y = (LPSTR)SEGPTR_ALLOC(n);				\
-		s = (LPWSTR)ofn->lpstrCustomFilter;			\
-		while (*s) {						\
-			lstrcpyWtoA(x,s);				\
-			x+=lstrlen32A(x)+1;				\
-			s+=lstrlen32W(s)+1;				\
-		}							\
-		*x=0;							\
-		ofn16->lpstrCustomFilter = SEGPTR_GET(y);		\
-	}								\
-	ofn16->nMaxCustFilter = ofn->nMaxCustFilter;			\
-	ofn16->nFilterIndex = ofn->nFilterIndex;			\
-        if (ofn->nMaxFile)                                              \
-	ofn16->lpstrFile = SEGPTR_GET(SEGPTR_ALLOC(ofn->nMaxFile));	\
-	ofn16->nMaxFile = ofn->nMaxFile;				\
-	if (ofn16->lpstrFileTitle)					\
-		ofn16->lpstrFileTitle= SEGPTR_GET(SEGPTR_STRDUP_WtoA(ofn->lpstrFileTitle));\
-	ofn16->nMaxFileTitle = ofn->nMaxFileTitle;			\
-        if (ofn->nMaxFileTitle)                                         \
-		ofn16->lpstrFileTitle = SEGPTR_GET(SEGPTR_ALLOC(ofn->nMaxFileTitle));\
-	if (ofn->lpstrInitialDir)					\
-		ofn16->lpstrInitialDir = SEGPTR_GET(SEGPTR_STRDUP_WtoA(ofn->lpstrInitialDir));\
-	if (ofn->lpstrTitle)						\
-		ofn16->lpstrTitle = SEGPTR_GET(SEGPTR_STRDUP_WtoA(ofn->lpstrTitle));\
-	ofn16->Flags = ofn->Flags|OFN_WINE32|OFN_UNICODE;		\
-	ofn16->nFileOffset = ofn->nFileOffset;				\
-	ofn16->nFileExtension = ofn->nFileExtension;			\
-	if (ofn->lpstrDefExt)						\
-		ofn16->lpstrDefExt = SEGPTR_GET(SEGPTR_STRDUP_WtoA(ofn->lpstrDefExt));\
-	ofn16->lCustData = ofn->lCustData;				\
-	ofn16->lpfnHook = (WNDPROC16)ofn->lpfnHook;			\
-	if (ofn->lpTemplateName) {					\
-		ofn16->lpTemplateName = SEGPTR_GET(SEGPTR_STRDUP_WtoA(ofn->lpTemplateName));\
-	}								\
-	ret = xxx##16(SEGPTR_GET(ofn16));				\
-									\
-	ofn->nFileOffset = ofn16->nFileOffset;				\
-	ofn->nFileExtension = ofn16->nFileExtension;			\
-	if (ofn16->lpstrFilter)						\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrFilter));	\
-	if (ofn16->lpTemplateName)					\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpTemplateName));	\
-	if (ofn16->lpstrDefExt)						\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrDefExt));	\
-	if (ofn16->lpstrTitle)						\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrTitle));		\
-	if (ofn16->lpstrInitialDir)					\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrInitialDir));	\
-	if (ofn16->lpstrCustomFilter)					\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrCustomFilter));	\
-									\
-	if (ofn16->lpstrFile) {                                         \
-	lstrcpyAtoW(ofn->lpstrFile,PTR_SEG_TO_LIN(ofn16->lpstrFile));	\
-	SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrFile));			\
-	}                                                               \
-									\
-	if (ofn16->lpstrFileTitle) {					\
-                lstrcpyAtoW(ofn->lpstrFileTitle,PTR_SEG_TO_LIN(ofn16->lpstrFileTitle));\
-		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrFileTitle));	\
-	}                                                               \
-	SEGPTR_FREE(ofn16);						\
-	return ret;							\
-}
-
-GET_XXX_FILENAME(GetOpenFileName)
-GET_XXX_FILENAME(GetSaveFileName)
-
 /***********************************************************************
- *           ChooseFontA   (COMDLG32.3)
+ *           FormatCharDlgProc32A   [internal]
  */
-DWORD WINAPI ChooseFont32A(PCHOOSEFONT32A pChoosefont)
+LRESULT WINAPI FormatCharDlgProc32A(HWND32 hDlg, UINT32 uMsg, WPARAM32 wParam,
+                                    LPARAM lParam)
 {
-	FIXME(commdlg,"empty stub!\n");
+  LPCHOOSEFONT32A lpcf;
+  LRESULT res=FALSE;
+  if (uMsg!=WM_INITDIALOG)
+  {
+   lpcf=(LPCHOOSEFONT32A)GetWindowLong32A(hDlg, DWL_USER);   
+   if (!lpcf)
+     return FALSE;
+   if (CFn_HookCallChk32(lpcf))
+     res=CallWindowProc32A(lpcf->lpfnHook, hDlg, uMsg, wParam, lParam);
+   if (res)
+     return res;
+  }
+  else
+  {
+    lpcf=(LPCHOOSEFONT32A)lParam;
+    if (!CFn_WMInitDialog(hDlg, wParam, lParam, lpcf)) 
+    {
+      TRACE(commdlg, "CFn_WMInitDialog returned FALSE\n");
+      return FALSE;
+    }  
+    if (CFn_HookCallChk32(lpcf))
+      return CallWindowProc32A(lpcf->lpfnHook,hDlg,WM_INITDIALOG,wParam,lParam);
+  }
+  switch (uMsg)
+    {
+      case WM_MEASUREITEM:
+                        return CFn_WMMeasureItem(hDlg, wParam, lParam);
+      case WM_DRAWITEM:
+                        return CFn_WMDrawItem(hDlg, wParam, lParam);
+      case WM_CTLCOLORSTATIC:
+                        return CFn_WMCtlColorStatic(hDlg, wParam, lParam, lpcf);
+      case WM_COMMAND:
+                        return CFn_WMCommand(hDlg, wParam, lParam, lpcf);
+      case WM_DESTROY:
+                        return CFn_WMDestroy(hDlg, wParam, lParam);
+      case WM_CHOOSEFONT_GETLOGFONT:
+                         TRACE(commdlg,"WM_CHOOSEFONT_GETLOGFONT lParam=%08lX\n",
+				      lParam);
+			 FIXME(commdlg, "current logfont back to caller\n");
+                        break;
+    }
+  return res;
+}
 
-	CommDlgLastError = CDERR_DIALOGFAILURE;
-	return NULL;
+/***********************************************************************
+ *           FormatCharDlgProc32W   [internal]
+ */
+LRESULT WINAPI FormatCharDlgProc32W(HWND32 hDlg, UINT32 uMsg, WPARAM32 wParam,
+                                    LPARAM lParam)
+{
+  LPCHOOSEFONT32W lpcf32w;
+  LPCHOOSEFONT32A lpcf32a;
+  LRESULT res=FALSE;
+  if (uMsg!=WM_INITDIALOG)
+  {
+   lpcf32w=(LPCHOOSEFONT32W)GetWindowLong32A(hDlg, DWL_USER);   
+   if (!lpcf32w)
+     return FALSE;
+   if (CFn_HookCallChk32((LPCHOOSEFONT32A)lpcf32w))
+     res=CallWindowProc32W(lpcf32w->lpfnHook, hDlg, uMsg, wParam, lParam);
+   if (res)
+     return res;
+  }
+  else
+  {
+    lpcf32w=(LPCHOOSEFONT32W)lParam;
+    lpcf32a=(LPCHOOSEFONT32A)lpcf32w->lpTemplateName;
+    if (!CFn_WMInitDialog(hDlg, wParam, lParam, lpcf32a)) 
+    {
+      TRACE(commdlg, "CFn_WMInitDialog returned FALSE\n");
+      return FALSE;
+    }  
+    if (CFn_HookCallChk32((LPCHOOSEFONT32A)lpcf32w))
+      return CallWindowProc32W(lpcf32w->lpfnHook,hDlg,WM_INITDIALOG,wParam,lParam);
+  }
+  lpcf32a=(LPCHOOSEFONT32A)lpcf32w->lpTemplateName;
+  switch (uMsg)
+    {
+      case WM_MEASUREITEM:
+                        return CFn_WMMeasureItem(hDlg, wParam, lParam);
+      case WM_DRAWITEM:
+                        return CFn_WMDrawItem(hDlg, wParam, lParam);
+      case WM_CTLCOLORSTATIC:
+                        return CFn_WMCtlColorStatic(hDlg, wParam, lParam, lpcf32a);
+      case WM_COMMAND:
+                        return CFn_WMCommand(hDlg, wParam, lParam, lpcf32a);
+      case WM_DESTROY:
+                        return CFn_WMDestroy(hDlg, wParam, lParam);
+      case WM_CHOOSEFONT_GETLOGFONT: 
+                         TRACE(commdlg,"WM_CHOOSEFONT_GETLOGFONT lParam=%08lX\n",
+				      lParam);
+			 FIXME(commdlg, "current logfont back to caller\n");
+                        break;
+    }
+  return res;
+}
+
+
+static BOOL32 Commdlg_GetFileName32A( BOOL16 (*dofunction)(),
+                                      LPOPENFILENAME32A ofn )
+{
+	BOOL16 ret;
+	LPOPENFILENAME16 ofn16 = SEGPTR_ALLOC(sizeof(OPENFILENAME16));
+
+	memset(ofn16,'\0',sizeof(*ofn16));
+	ofn16->lStructSize = sizeof(*ofn16);
+	ofn16->hwndOwner = ofn->hwndOwner;
+	/* FIXME: OPENFILENAME16 got only 16 bit for HINSTANCE... */
+	ofn16->hInstance = MODULE_HANDLEtoHMODULE16(ofn->hInstance);
+	if (ofn->lpstrFilter) {
+		LPSTR	s,x;
+
+		/* filter is a list...  title\0ext\0......\0\0 */
+		s = (LPSTR)ofn->lpstrFilter;
+		while (*s)
+			s = s+strlen(s)+1;
+		s++;
+		x = (LPSTR)SEGPTR_ALLOC(s-ofn->lpstrFilter);
+		memcpy(x,ofn->lpstrFilter,s-ofn->lpstrFilter);
+		ofn16->lpstrFilter = SEGPTR_GET(x);
+	}
+	if (ofn->lpstrCustomFilter) {
+		LPSTR	s,x;
+
+		/* filter is a list...  title\0ext\0......\0\0 */
+		s = (LPSTR)ofn->lpstrCustomFilter;
+		while (*s)
+			s = s+strlen(s)+1;
+		x = SEGPTR_ALLOC(s-ofn->lpstrCustomFilter);
+		s++;
+		memcpy(x,ofn->lpstrCustomFilter,s-ofn->lpstrCustomFilter);
+		ofn16->lpstrCustomFilter = SEGPTR_GET(x);
+	}
+	ofn16->nMaxCustFilter = ofn->nMaxCustFilter;
+	ofn16->nFilterIndex = ofn->nFilterIndex;
+	if (ofn->nMaxFile)
+	    ofn16->lpstrFile = SEGPTR_GET(SEGPTR_ALLOC(ofn->nMaxFile));
+	ofn16->nMaxFile = ofn->nMaxFile;
+	ofn16->nMaxFileTitle = ofn->nMaxFileTitle;
+        if (ofn16->nMaxFileTitle)
+	    ofn16->lpstrFileTitle = SEGPTR_GET(SEGPTR_ALLOC(ofn->nMaxFileTitle));
+	if (ofn->lpstrInitialDir)
+	    ofn16->lpstrInitialDir = SEGPTR_GET(SEGPTR_STRDUP(ofn->lpstrInitialDir));
+	if (ofn->lpstrTitle)
+	    ofn16->lpstrTitle = SEGPTR_GET(SEGPTR_STRDUP(ofn->lpstrTitle));
+	ofn16->Flags = ofn->Flags|OFN_WINE32;
+	ofn16->nFileOffset = ofn->nFileOffset;
+	ofn16->nFileExtension = ofn->nFileExtension;
+	if (ofn->lpstrDefExt)
+	    ofn16->lpstrDefExt = SEGPTR_GET(SEGPTR_STRDUP(ofn->lpstrDefExt));
+	ofn16->lCustData = ofn->lCustData;
+	ofn16->lpfnHook = (WNDPROC16)ofn->lpfnHook;
+
+	if (ofn->lpTemplateName)
+	    ofn16->lpTemplateName = SEGPTR_GET(SEGPTR_STRDUP(ofn->lpTemplateName));
+
+	ret = dofunction(SEGPTR_GET(ofn16));
+
+	ofn->nFileOffset = ofn16->nFileOffset;
+	ofn->nFileExtension = ofn16->nFileExtension;
+	if (ofn16->lpstrFilter)
+	    SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrFilter));
+	if (ofn16->lpTemplateName)
+	    SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpTemplateName));
+	if (ofn16->lpstrDefExt)
+	    SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrDefExt));
+	if (ofn16->lpstrTitle)
+	    SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrTitle));
+	if (ofn16->lpstrInitialDir)
+	    SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrInitialDir));
+	if (ofn16->lpstrCustomFilter)
+	    SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrCustomFilter));
+
+	if (ofn16->lpstrFile) 
+	  {
+	    strcpy(ofn->lpstrFile,PTR_SEG_TO_LIN(ofn16->lpstrFile));
+	    SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrFile));
+	  }
+
+	if (ofn16->lpstrFileTitle) 
+	  {
+	    strcpy(ofn->lpstrFileTitle,PTR_SEG_TO_LIN(ofn16->lpstrFileTitle));
+	    SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrFileTitle));
+	  }
+	SEGPTR_FREE(ofn16);
+	return ret;
+}
+
+static BOOL32 Commdlg_GetFileName32W( BOOL16 (*dofunction)(), 
+                                      LPOPENFILENAME32W ofn )
+{
+	BOOL16 ret;
+	LPOPENFILENAME16 ofn16 = SEGPTR_ALLOC(sizeof(OPENFILENAME16));
+
+	memset(ofn16,'\0',sizeof(*ofn16));
+	ofn16->lStructSize = sizeof(*ofn16);
+	ofn16->hwndOwner = ofn->hwndOwner;
+	/* FIXME: OPENFILENAME16 got only 16 bit for HINSTANCE... */
+	ofn16->hInstance = MODULE_HANDLEtoHMODULE16(ofn->hInstance);
+	if (ofn->lpstrFilter) {
+		LPWSTR	s;
+		LPSTR	x,y;
+		int	n;
+
+		/* filter is a list...  title\0ext\0......\0\0 */
+		s = (LPWSTR)ofn->lpstrFilter;
+		while (*s)
+			s = s+lstrlen32W(s)+1;
+		s++;
+		n = s - ofn->lpstrFilter; /* already divides by 2. ptr magic */
+		x = y = (LPSTR)SEGPTR_ALLOC(n);
+		s = (LPWSTR)ofn->lpstrFilter;
+		while (*s) {
+			lstrcpyWtoA(x,s);
+			x+=lstrlen32A(x)+1;
+			s+=lstrlen32W(s)+1;
+		}
+		*x=0;
+		ofn16->lpstrFilter = SEGPTR_GET(y);
+}
+	if (ofn->lpstrCustomFilter) {
+		LPWSTR	s;
+		LPSTR	x,y;
+		int	n;
+
+		/* filter is a list...  title\0ext\0......\0\0 */
+		s = (LPWSTR)ofn->lpstrCustomFilter;
+		while (*s)
+			s = s+lstrlen32W(s)+1;
+		s++;
+		n = s - ofn->lpstrCustomFilter;
+		x = y = (LPSTR)SEGPTR_ALLOC(n);
+		s = (LPWSTR)ofn->lpstrCustomFilter;
+		while (*s) {
+			lstrcpyWtoA(x,s);
+			x+=lstrlen32A(x)+1;
+			s+=lstrlen32W(s)+1;
+		}
+		*x=0;
+		ofn16->lpstrCustomFilter = SEGPTR_GET(y);
+	}
+	ofn16->nMaxCustFilter = ofn->nMaxCustFilter;
+	ofn16->nFilterIndex = ofn->nFilterIndex;
+        if (ofn->nMaxFile) 
+	   ofn16->lpstrFile = SEGPTR_GET(SEGPTR_ALLOC(ofn->nMaxFile));
+	ofn16->nMaxFile = ofn->nMaxFile;
+	ofn16->nMaxFileTitle = ofn->nMaxFileTitle;
+        if (ofn->nMaxFileTitle)
+		ofn16->lpstrFileTitle = SEGPTR_GET(SEGPTR_ALLOC(ofn->nMaxFileTitle));
+	if (ofn->lpstrInitialDir)
+		ofn16->lpstrInitialDir = SEGPTR_GET(SEGPTR_STRDUP_WtoA(ofn->lpstrInitialDir));
+	if (ofn->lpstrTitle)
+		ofn16->lpstrTitle = SEGPTR_GET(SEGPTR_STRDUP_WtoA(ofn->lpstrTitle));
+	ofn16->Flags = ofn->Flags|OFN_WINE32|OFN_UNICODE;
+	ofn16->nFileOffset = ofn->nFileOffset;
+	ofn16->nFileExtension = ofn->nFileExtension;
+	if (ofn->lpstrDefExt)
+		ofn16->lpstrDefExt = SEGPTR_GET(SEGPTR_STRDUP_WtoA(ofn->lpstrDefExt));
+	ofn16->lCustData = ofn->lCustData;
+	ofn16->lpfnHook = (WNDPROC16)ofn->lpfnHook;
+	if (ofn->lpTemplateName) 
+		ofn16->lpTemplateName = SEGPTR_GET(SEGPTR_STRDUP_WtoA(ofn->lpTemplateName));
+	ret = dofunction(SEGPTR_GET(ofn16));
+
+	ofn->nFileOffset = ofn16->nFileOffset;
+	ofn->nFileExtension = ofn16->nFileExtension;
+	if (ofn16->lpstrFilter)
+		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrFilter));
+	if (ofn16->lpTemplateName)
+		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpTemplateName));
+	if (ofn16->lpstrDefExt)
+		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrDefExt));
+	if (ofn16->lpstrTitle)
+		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrTitle));
+	if (ofn16->lpstrInitialDir)
+		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrInitialDir));
+	if (ofn16->lpstrCustomFilter)
+		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrCustomFilter));
+
+	if (ofn16->lpstrFile) {
+	lstrcpyAtoW(ofn->lpstrFile,PTR_SEG_TO_LIN(ofn16->lpstrFile));
+	SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrFile));
+	}
+
+	if (ofn16->lpstrFileTitle) {
+                lstrcpyAtoW(ofn->lpstrFileTitle,PTR_SEG_TO_LIN(ofn16->lpstrFileTitle));
+		SEGPTR_FREE(PTR_SEG_TO_LIN(ofn16->lpstrFileTitle));
+	}
+	SEGPTR_FREE(ofn16);
+	return ret;
+}
+
+/***********************************************************************
+ *            GetOpenFileName32A  (COMDLG32.10)
+ */
+BOOL32 WINAPI GetOpenFileName32A( LPOPENFILENAME32A ofn )
+{
+   BOOL16 (WINAPI * dofunction)(SEGPTR ofn16) = GetOpenFileName16;
+   return Commdlg_GetFileName32A(dofunction,ofn);
+}
+
+/***********************************************************************
+ *            GetOpenFileName32W (COMDLG32.11)
+ */
+BOOL32 WINAPI GetOpenFileName32W( LPOPENFILENAME32W ofn )
+{
+   BOOL16 (WINAPI * dofunction)(SEGPTR ofn16) = GetOpenFileName16;
+   return Commdlg_GetFileName32W(dofunction,ofn);
+}
+
+/***********************************************************************
+ *            GetSaveFileName32A  (COMDLG32.12)
+ */
+BOOL32 WINAPI GetSaveFileName32A( LPOPENFILENAME32A ofn )
+{
+   BOOL16 (WINAPI * dofunction)(SEGPTR ofn16) = GetSaveFileName16;
+   return Commdlg_GetFileName32A(dofunction,ofn);
+}
+
+/***********************************************************************
+ *            GetSaveFileName32W  (COMDLG32.13)
+ */
+BOOL32 WINAPI GetSaveFileName32W( LPOPENFILENAME32W ofn )
+{
+   BOOL16 (WINAPI * dofunction)(SEGPTR ofn16) = GetSaveFileName16;
+   return Commdlg_GetFileName32W(dofunction,ofn);
 }
diff --git a/misc/crtdll.c b/misc/crtdll.c
index 2c00a32..e9f1dd3 100644
--- a/misc/crtdll.c
+++ b/misc/crtdll.c
@@ -67,6 +67,8 @@
 UINT32 CRTDLL_winminor_dll;     /* CRTDLL.330 */
 UINT32 CRTDLL_winver_dll;       /* CRTDLL.331 */
 
+BYTE CRTDLL_iob[32*3];  /* FIXME */
+
 typedef VOID (*new_handler_type)(VOID);
 
 static new_handler_type new_handler;
@@ -177,6 +179,21 @@
   return (DWORD)file;
 }
 
+static FILE *xlat_file_ptr(void *ptr)
+{
+    unsigned long dif;
+    
+    /* CRT sizeof(FILE) == 32 */
+    dif = ((char *)ptr - (char *)CRTDLL_iob) / 32;
+    switch(dif)
+    {
+	case 0: return stdin;
+	case 1: return stdout;
+	case 2: return stderr;
+    }
+    return (FILE*)ptr;
+}
+
 /*******************************************************************
  *         _global_unwind2  (CRTDLL.129)
  */
@@ -246,9 +263,10 @@
 /*********************************************************************
  *                  fread     (CRTDLL.377)
  */
-DWORD __cdecl CRTDLL_fread(LPVOID ptr, INT32 size, INT32 nmemb, LPVOID file)
+DWORD __cdecl CRTDLL_fread(LPVOID ptr, INT32 size, INT32 nmemb, LPVOID vfile)
 {
   size_t ret=1;
+  FILE *file=xlat_file_ptr(vfile);
 #if 0
   int i=0;
   void *temp=ptr;
@@ -293,7 +311,7 @@
 {
   long ret;
 
-  ret=fseek(stream,offset,whence);
+  ret=fseek(xlat_file_ptr(stream),offset,whence);
   TRACE(crtdll, "file %p to 0x%08lx pos %s\n",
 	       stream,offset,(whence==SEEK_SET)?"SEEK_SET":
 	       (whence==SEEK_CUR)?"SEEK_CUR":
@@ -311,7 +329,7 @@
 {
   long ret;
 
-  ret=ftell(stream);
+  ret=ftell(xlat_file_ptr(stream));
   TRACE(crtdll, "file %p at 0x%08lx\n",
 	       stream,ret);
   return ret;
@@ -320,9 +338,10 @@
 /*********************************************************************
  *                  fwrite     (CRTDLL.386)
  */
-DWORD __cdecl CRTDLL_fwrite(LPVOID ptr, INT32 size, INT32 nmemb, LPVOID file)
+DWORD __cdecl CRTDLL_fwrite(LPVOID ptr, INT32 size, INT32 nmemb, LPVOID vfile)
 {
   size_t ret;
+  FILE *file=xlat_file_ptr(vfile);
 
   ret=fwrite(ptr,size,nmemb,file);
   TRACE(crtdll, "0x%08x items of size %d from %p to file %p\n",
@@ -342,7 +361,7 @@
   /* this doesn't work:"void value not ignored as it ought to be" 
   return setbuf(file,buf); 
   */
-  setbuf(file,buf);
+  setbuf(xlat_file_ptr(file),buf);
   return 0;
 }
 
@@ -393,7 +412,7 @@
     INT32 res;
 
     va_start( valist, format );
-    res = vfprintf( file, format, valist );
+    res = vfprintf( xlat_file_ptr(file), format, valist );
     va_end( valist );
     return res;
 }
@@ -403,7 +422,7 @@
  */
 INT32 __cdecl CRTDLL_vfprintf( FILE *file, LPSTR format, va_list args )
 {
-    return vfprintf( file, format, args );
+    return vfprintf( xlat_file_ptr(file), format, args );
 }
 
 /*********************************************************************
@@ -511,7 +530,7 @@
 {
     int ret;
 
-    ret = fflush(stream);
+    ret = fflush(xlat_file_ptr(stream));
     TRACE(crtdll,"%p returnd %d\n",stream,ret);
     if(ret)
       WARN(crtdll, " Failed!\n");
@@ -559,7 +578,7 @@
 INT32 __cdecl CRTDLL_fputc( INT32 c, FILE *stream )
 {
     TRACE(crtdll, "%c to file %p\n",c,stream);
-    return fputc(c,stream);
+    return fputc(c,xlat_file_ptr(stream));
 }
 
 
@@ -569,7 +588,7 @@
 INT32 __cdecl CRTDLL_fputs( LPCSTR s, FILE *stream )
 {
     TRACE(crtdll, "%s to file %p\n",s,stream);
-    return fputs(s,stream);
+    return fputs(s,xlat_file_ptr(stream));
 }
 
 
@@ -589,14 +608,14 @@
 INT32 __cdecl CRTDLL_putc(INT32 c, FILE *stream)
 {
     TRACE(crtdll, " %c to file %p\n",c,stream);
-    return fputc(c,stream);
+    return fputc(c,xlat_file_ptr(stream));
 }
 /*********************************************************************
  *                  fgetc       (CRTDLL.366)
  */
 INT32 __cdecl CRTDLL_fgetc( FILE *stream )
 {
-  int ret= fgetc(stream);
+  int ret= fgetc(xlat_file_ptr(stream));
   TRACE(crtdll, "got %d\n",ret);
   return ret;
 }
@@ -607,7 +626,7 @@
  */
 INT32 __cdecl CRTDLL_getc( FILE *stream )
 {
-  int ret= fgetc(stream);
+  int ret= fgetc(xlat_file_ptr(stream));
   TRACE(crtdll, "got %d\n",ret);
   return ret;
 }
@@ -646,7 +665,7 @@
   char * ret;
   char * control_M;
   
-  ret=fgets(s, size,stream);
+  ret=fgets(s, size,xlat_file_ptr(stream));
   /*FIXME: Control with CRTDLL_setmode */
   control_M= strrchr(s,'\r');
   /*delete CR if we read a DOS File */
@@ -937,10 +956,13 @@
  */
 INT32 __cdecl CRTDLL_fclose( FILE *stream )
 {
-    int unix_handle=fileno(stream);
+    int unix_handle;
     HFILE32 dos_handle=1;
     HFILE32 ret=EOF;
 
+    stream=xlat_file_ptr(stream);
+    unix_handle=fileno(stream);
+
     if (unix_handle<4) ret= fclose(stream);
     else {
       while(FILE_GetUnixHandle(dos_handle) != unix_handle) dos_handle++;
@@ -1090,7 +1112,7 @@
 {
     int ret;
     
-    ret=feof(stream);
+    ret=feof(xlat_file_ptr(stream));
     TRACE(crtdll,"(%p) %s\n",stream,(ret)?"true":"false");
     return ret;
 }
@@ -1686,7 +1708,7 @@
  */
 VOID __cdecl CRTDLL_signal(int sig, sig_handler_type ptr)
 {
-    FIXME(crtdll, "(%d %p): STUB!\n", sig, ptr);
+    FIXME(crtdll, "(%d %p):stub.\n", sig, ptr);
 }
 
 /*********************************************************************
diff --git a/misc/ddeml.c b/misc/ddeml.c
index 87b1f84..5d59940 100644
--- a/misc/ddeml.c
+++ b/misc/ddeml.c
@@ -11,40 +11,52 @@
 #include "ddeml.h"
 #include "debug.h"
 
+/* FIXME: What are these values? */
+#define DMLERR_NO_ERROR		0
 
 static LONG     DDE_current_handle;
 
 
-/*****************************************************************
+/******************************************************************************
  *            DdeInitialize16   (DDEML.2)
  */
 UINT16 WINAPI DdeInitialize16( LPDWORD pidInst, PFNCALLBACK16 pfnCallback,
                                DWORD afCmd, DWORD ulRes)
 {
-    FIXME( ddeml, "empty stub\n" );
-    return 0;
+    return (UINT16)DdeInitialize32A(pidInst,(PFNCALLBACK32)pfnCallback,
+                                    afCmd, ulRes);
 }
 
 
-/*****************************************************************
+/******************************************************************************
  *            DdeInitialize32A   (USER32.106)
  */
 UINT32 WINAPI DdeInitialize32A( LPDWORD pidInst, PFNCALLBACK32 pfnCallback,
                                 DWORD afCmd, DWORD ulRes )
 {
-    FIXME( ddeml, "empty stub\n" );
-    return 0;
+    return DdeInitialize32W(pidInst,pfnCallback,afCmd,ulRes);
 }
 
 
-/*****************************************************************
- *            DdeInitialize32W   (USER32.107)
+/******************************************************************************
+ * DdeInitialize32W [USER32.107]
+ * Registers an application with the DDEML
+ *
+ * PARAMS
+ *    pidInst     [I] Pointer to instance identifier
+ *    pfnCallback [I] Pointer to callback function
+ *    afCmd       [I] Set of command and filter flags
+ *    ulRes       [I] Reserved
+ *
+ * RETURNS
+ *    Success: DMLERR_NO_ERROR
+ *    Failure: DMLERR_DLL_USAGE, DMLERR_INVALIDPARAMETER, DMLERR_SYS_ERROR
  */
 UINT32 WINAPI DdeInitialize32W( LPDWORD pidInst, PFNCALLBACK32 pfnCallback,
                                 DWORD afCmd, DWORD ulRes )
 {
-    FIXME( ddeml, "empty stub\n" );
-    return 0;
+    FIXME(ddeml, "(%p,%p,%ld,%ld): stub\n",pidInst,pfnCallback,afCmd,ulRes);
+    return DMLERR_NO_ERROR;
 }
 
 
@@ -58,24 +70,56 @@
 
 
 /*****************************************************************
- *            DdeUninitialize32   (USER32.119)
+ * DdeUninitialize32 [USER32.119]  Frees DDEML resources
+ *
+ * PARAMS
+ *    idInst [I] Instance identifier
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
  */
 BOOL32 WINAPI DdeUninitialize32( DWORD idInst )
 {
-    FIXME( ddeml, "empty stub\n" );
+    FIXME(ddeml, "(%ld): stub\n", idInst);
     return TRUE;
 }
 
+
 /*****************************************************************
- *            DdeConnectList (DDEML.4)
+ * DdeConnectList16 [DDEML.4]
  */
-HCONVLIST WINAPI DdeConnectList( DWORD idInst, HSZ hszService, HSZ hszTopic,
-        HCONVLIST hConvList, LPCONVCONTEXT16 pCC )
+HCONVLIST WINAPI DdeConnectList16( DWORD idInst, HSZ hszService, HSZ hszTopic,
+                 HCONVLIST hConvList, LPCONVCONTEXT16 pCC )
 {
-    FIXME( ddeml, "empty stub\n" );
-    return 0;
+    return DdeConnectList32(idInst, hszService, hszTopic, hConvList, 
+                            (LPCONVCONTEXT32)pCC);
 }
 
+
+/******************************************************************************
+ * DdeConnectList32 [USER32.93]  Establishes conversation with DDE servers
+ *
+ * PARAMS
+ *    idInst     [I] Instance identifier
+ *    hszService [I] Handle to service name string
+ *    hszTopic   [I] Handle to topic name string
+ *    hConvList  [I] Handle to conversation list
+ *    pCC        [I] Pointer to structure with context data
+ *
+ * RETURNS
+ *    Success: Handle to new conversation list
+ *    Failure: 0
+ */
+HCONVLIST WINAPI DdeConnectList32( DWORD idInst, HSZ hszService, HSZ hszTopic,
+                 HCONVLIST hConvList, LPCONVCONTEXT32 pCC )
+{
+    FIXME(ddeml, "(%ld,%ld,%ld,%ld,%p): stub\n", idInst, hszService, hszTopic,
+          hConvList,pCC);
+    return 1;
+}
+
+
 /*****************************************************************
  *            DdeQueryNextServer (DDEML.5)
  */
@@ -88,12 +132,27 @@
 /*****************************************************************
  *            DdeDisconnectList (DDEML.6)
  */
-BOOL16 WINAPI DdeDisconnectList( HCONVLIST hConvList )
+BOOL16 WINAPI DdeDisconnectList16( HCONVLIST hConvList )
 {
-    FIXME( ddeml, "empty stub\n" );
-    return 0;
+    return (BOOL16)DdeDisconnectList32(hConvList);
 }
 
+
+/******************************************************************************
+ * DdeDisconnectList32 [USER32.98]  Destroys list and terminates conversations
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
+ */
+BOOL32 WINAPI DdeDisconnectList32(
+    HCONVLIST hConvList) /* [in] Handle to conversation list */
+{
+    FIXME(ddeml, "(%ld): stub\n", hConvList);
+    return TRUE;
+}
+
+
 /*****************************************************************
  *            DdeConnect16   (DDEML.7)
  */
@@ -111,7 +170,7 @@
 HCONV WINAPI DdeConnect32( DWORD idInst, HSZ hszService, HSZ hszTopic,
                            LPCONVCONTEXT32 pCC )
 {
-    FIXME( ddeml, "empty stub\n" );
+    FIXME( ddeml, "(...): stub\n");
     return 0;
 }
 
@@ -172,22 +231,29 @@
 
 
 /*****************************************************************
- *            DdeCreateStringHandle32A   (USER32.95)
+ * DdeCreateStringHandle32A [USER32.95]
  */
 HSZ WINAPI DdeCreateStringHandle32A( DWORD idInst, LPCSTR psz, INT32 codepage )
 {
-    FIXME( ddeml, "empty stub\n" );
+    FIXME(ddeml, "(...): stub\n" );
     DDE_current_handle++;
     return DDE_current_handle;
 }
 
 
-/*****************************************************************
- *            DdeCreateStringHandle32W   (USER32.96)
+/******************************************************************************
+ * DdeCreateStringHandle32W [USER32.96]  Creates handle to identify string
+ *
+ * RETURNS
+ *    Success: String handle
+ *    Failure: 0
  */
-HSZ WINAPI DdeCreateStringHandle32W( DWORD idInst, LPCWSTR psz, INT32 codepage)
+HSZ WINAPI DdeCreateStringHandle32W(
+    DWORD idInst,   /* [in] Instance identifier */
+    LPCWSTR psz,    /* [in] Pointer to string */
+    INT32 codepage) /* [in] Code page identifier */
 {
-    FIXME( ddeml, "empty stub\n" );
+    FIXME(ddeml, "(%ld,%s,%d): stub\n",idInst,debugstr_w(psz),codepage);
     DDE_current_handle++;
     return DDE_current_handle;
 }
@@ -285,15 +351,33 @@
     return 0;
 }
 
+
 /*****************************************************************
- *            DdePostAdvise (DDEML.13)
+ * DdePostAdvise16 [DDEML.13]
  */
-BOOL16 WINAPI DdePostAdvise( DWORD idInst, HSZ hszTopic, HSZ hszItem )
+BOOL16 WINAPI DdePostAdvise16( DWORD idInst, HSZ hszTopic, HSZ hszItem )
 {
-    FIXME( ddeml, "empty stub\n" );
-    return 0;
+    return (BOOL16)DdePostAdvise32(idInst, hszTopic, hszItem);
 }
 
+
+/******************************************************************************
+ * DdePostAdvise32 [USER32.110]  Send transaction to DDE callback function.
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
+ */
+BOOL32 WINAPI DdePostAdvise32(
+    DWORD idInst, /* [in] Instance identifier */
+    HSZ hszTopic, /* [in] Handle to topic name string */
+    HSZ hszItem)  /* [in] Handle to item name string */
+{
+    FIXME(ddeml, "(%ld,%ld,%ld): stub\n",idInst,hszTopic,hszItem);
+    return TRUE;
+}
+
+
 /*****************************************************************
  *            DdeAddData (DDEML.15)
  */
@@ -304,16 +388,37 @@
     return 0;
 }
 
-/*****************************************************************
- *            DdeGetData (DDEML.16)
+
+/******************************************************************************
+ * DdeGetData32 [USER32.102]  Copies data from DDE object ot local buffer
+ *
+ * RETURNS
+ *    Size of memory object associated with handle
  */
-DWORD WINAPI DdeGetData( HDDEDATA hData, LPBYTE pDst, DWORD cbMax, 
-                         DWORD cbOff )
+DWORD WINAPI DdeGetData32(
+    HDDEDATA hData, /* [in] Handle to DDE object */
+    LPBYTE pDst,    /* [in] Pointer to destination buffer */
+    DWORD cbMax,    /* [in] Amount of data to copy */
+    DWORD cbOff)    /* [in] Offset to beginning of data */
 {
-    FIXME( ddeml, "empty stub\n" );
-    return 0;
+    FIXME(ddeml, "(%ld,%p,%ld,%ld): stub\n",hData,pDst,cbMax,cbOff);
+    return cbMax;
 }
 
+
+/*****************************************************************
+ * DdeGetData16 [DDEML.16]
+ */
+DWORD WINAPI DdeGetData16(
+    HDDEDATA hData,
+    LPBYTE pDst,
+    DWORD cbMax, 
+    DWORD cbOff)
+{
+    return DdeGetData32(hData, pDst, cbMax, cbOff);
+}
+
+
 /*****************************************************************
  *            DdeAccessData (DDEML.17)
  */
@@ -351,14 +456,24 @@
 }
 
 
-/*****************************************************************
- *            DdeNameService32  (USER32.109)
+/******************************************************************************
+ * DdeNameService32 [USER32.109]  {Un}registers service name of DDE server
+ *
+ * PARAMS
+ *    idInst [I] Instance identifier
+ *    hsz1   [I] Handle to service name string
+ *    hsz2   [I] Reserved
+ *    afCmd  [I] Service name flags
+ *
+ * RETURNS
+ *    Success: Non-zero
+ *    Failure: 0
  */
 HDDEDATA WINAPI DdeNameService32( DWORD idInst, HSZ hsz1, HSZ hsz2,
-                                  UINT32 afCmd )
+                UINT32 afCmd )
 {
-    FIXME( ddeml, "empty stub\n" );
-    return 0;
+    FIXME(ddeml, "(%ld,%ld,%ld,%d): stub\n",idInst,hsz1,hsz2,afCmd);
+    return 1;
 }
 
 
@@ -371,15 +486,22 @@
 }
 
 
-/*****************************************************************
- *            DdeGetLastError32  (USER32.103)
+/******************************************************************************
+ * DdeGetLastError32 [USER32.103]  Gets most recent error code
+ *
+ * PARAMS
+ *    idInst [I] Instance identifier
+ *
+ * RETURNS
+ *    Last error code
  */
 UINT32 WINAPI DdeGetLastError32( DWORD idInst )
 {
-    FIXME( ddeml, "empty stub\n" );
+    FIXME(ddeml, "(%ld): stub\n",idInst);
     return 0;
 }
 
+
 /*****************************************************************
  *            DdeCmpStringHandles (DDEML.36)
  */
diff --git a/misc/error.c b/misc/error.c
index 3a36237..4ae65a7 100644
--- a/misc/error.c
+++ b/misc/error.c
@@ -140,8 +140,7 @@
 */
 VOID WINAPI LogError(UINT16 uErr, LPVOID lpvInfo)
 {
-	fprintf(stddeb, "LogError(%s, %p)\n", 
-		GetErrorString(uErr), lpvInfo);
+	MSG("(%s, %p)\n", GetErrorString(uErr), lpvInfo);
 }
 
 
@@ -153,6 +152,5 @@
 	/* FIXME: is it possible to get the module name/function
 	 * from the lpfn param?
 	 */
-	fprintf(stddeb, "LogParamError(%s, %p, %p)\n", 
-		GetParamErrorString(uErr), lpfn, lpvParam);
+	MSG("(%s, %p, %p)\n", GetParamErrorString(uErr), lpfn, lpvParam);
 }
diff --git a/misc/imagelist.c b/misc/imagelist.c
index 474de9e..17f6d2c 100644
--- a/misc/imagelist.c
+++ b/misc/imagelist.c
@@ -1452,9 +1452,9 @@
         /* create new bitmap(s) */
         cxNew = (himl->cCurImage + himl->cGrow - 1) * himl->cx;
 
-        fprintf (stderr, " - Number of images: %d / %d (Old/New)\n",
+        TRACE(imagelist, " - Number of images: %d / %d (Old/New)\n",
                  himl->cCurImage, himl->cCurImage - 1);
-        fprintf (stderr, " - Max. number of images: %d / %d (Old/New)\n",
+        TRACE(imagelist, " - Max. number of images: %d / %d (Old/New)\n",
                  himl->cMaxImage, himl->cCurImage + himl->cGrow - 1);
         
         hbmNewImage =
diff --git a/misc/lstr.c b/misc/lstr.c
index 05b7fb3..98d8748 100644
--- a/misc/lstr.c
+++ b/misc/lstr.c
@@ -159,7 +159,7 @@
     *p = '\0';
     if ((p > buffer) && (p[-1] == '\n')) p[1] = '\0'; /* Remove trailing \n */
     module = MODULE_GetModuleName( GetCurrentTask() );
-    fprintf( stderr, "OutputDebugString: %s says '%s'\n",
+    TRACE(resource, "%s says '%s'\n",
              module ? module : "???", buffer );
     HeapFree( GetProcessHeap(), 0, buffer );
 }
@@ -646,8 +646,18 @@
 		}
 		*t='\0';
 	}
-	if (!nolinefeed && t[-1]!='\n')
-		ADD_TO_T('\n');
+	if (nolinefeed) {
+	    /* remove linefeed */
+	    if(t>target && t[-1]=='\n') {
+		*--t=0;
+		if(t>target && t[-1]=='\r')
+		    *--t=0;
+	    }
+	} else {
+	    /* add linefeed */
+	    if(t==target || t[-1]!='\n')
+		ADD_TO_T('\n'); /* FIXME: perhaps add \r too? */
+	}
 	talloced = strlen(target)+1;
 	if (nSize && talloced<nSize) {
 		target = (char*)HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,target,nSize);
@@ -816,8 +826,18 @@
 		}
 		*t='\0';
 	}
-	if (!nolinefeed && t[-1]!='\n')
-		ADD_TO_T('\n');
+	if (nolinefeed) {
+	    /* remove linefeed */
+	    if(t>target && t[-1]=='\n') {
+		*--t=0;
+		if(t>target && t[-1]=='\r')
+		    *--t=0;
+	    }
+	} else {
+	    /* add linefeed */
+	    if(t==target || t[-1]!='\n')
+		ADD_TO_T('\n'); /* FIXME: perhaps add \r too? */
+	}
 	talloced = strlen(target)+1;
 	if (nSize && talloced<nSize)
 		target = (char*)HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,target,nSize);
diff --git a/misc/lzexpand.c b/misc/lzexpand.c
index 7440e9d..dcf6675 100644
--- a/misc/lzexpand.c
+++ b/misc/lzexpand.c
@@ -248,7 +248,7 @@
 	/* now mangle the basename */
 	if (!*s) {
 		/* FIXME: hmm. shouldn't happen? */
-		fprintf(stddeb,__FILE__":GetExpandedFileName(), specified a directory or what? (%s)\n",in);
+		WARN(file,"Specified a directory or what? (%s)\n",in);
 		_lclose32(fd);
 		return 1;
 	}
diff --git a/misc/main.c b/misc/main.c
index 1d843ec..eea58b9 100644
--- a/misc/main.c
+++ b/misc/main.c
@@ -146,7 +146,7 @@
  */
 void MAIN_Usage( char *name )
 {
-    fprintf( stderr, USAGE, name );
+    MSG( USAGE, name );
     exit(1);
 }
 
@@ -281,9 +281,9 @@
 	}
         Options.language++;
     }
-    fprintf( stderr, "Invalid language specified '%s'. Supported languages are: ", arg );
-    for (p = Languages; p->name; p++) fprintf( stderr, "%s ", p->name );
-    fprintf( stderr, "\n" );
+    MSG( "Invalid language specified '%s'. Supported languages are: ", arg );
+    for (p = Languages; p->name; p++) MSG( "%s ", p->name );
+    MSG( "\n" );
     exit(1);
 }
 
@@ -299,8 +299,8 @@
     else if (!lstrcmpi32A("standard", arg)) Options.mode = MODE_STANDARD;
     else
     {
-        fprintf(stderr, "Invalid mode '%s' specified.\n", arg);
-        fprintf(stderr, "Valid modes are: 'standard', 'enhanced' (default).\n");
+        MSG( "Invalid mode '%s' specified.\n", arg);
+        MSG( "Valid modes are: 'standard', 'enhanced' (default).\n");
 	exit(1);
     }
 }
@@ -339,7 +339,7 @@
 
     if (!(display = TSXOpenDisplay( display_name )))
     {
-	fprintf( stderr, "%s: Can't open display: %s\n",
+	MSG( "%s: Can't open display: %s\n",
 		 argv[0], display_name ? display_name : "(none specified)" );
 	exit(1);
     }
@@ -387,7 +387,7 @@
     if (MAIN_GetResource( db, ".debugmsg", &value))
       {
 #ifndef DEBUG_RUNTIME
-	fprintf(stderr,"%s: Option \"-debugmsg\" not implemented.\n" \
+	MSG("%s: Option \"-debugmsg\" not implemented.\n" \
           "    Recompile with DEBUG_RUNTIME in include/debugtools.h defined.\n",
 	  argv[0]);
 	exit(1);
@@ -395,23 +395,23 @@
 	if (ParseDebugOptions((char*)value.addr)==FALSE)
 	  {
 	    int i;
-	    fprintf(stderr,"%s: Syntax: -debugmsg [class]+xxx,...  or "
+	    MSG("%s: Syntax: -debugmsg [class]+xxx,...  or "
 		    "-debugmsg [class]-xxx,...\n",argv[0]);
-	    fprintf(stderr,"Example: -debugmsg +all,warn-heap"
+	    MSG("Example: -debugmsg +all,warn-heap"
 		    "turn on all messages except warning heap messages\n");
 
-	    fprintf(stderr,"Available message classes:\n");
+	    MSG("Available message classes:\n");
 	    for(i=0;i<DEBUG_CLASS_COUNT;i++)
-	      fprintf(stderr, "%-9s", debug_cl_name[i]);
-	    fprintf(stderr,"\n\n");
+	      MSG( "%-9s", debug_cl_name[i]);
+	    MSG("\n\n");
 
-	    fprintf(stderr,"Available message types:\n");
-	    fprintf(stderr,"%-9s ","all");
+	    MSG("Available message types:\n");
+	    MSG("%-9s ","all");
 	    for(i=0;i<DEBUG_CHANNEL_COUNT;i++)
 	      if(debug_ch_name[i])
-		fprintf(stderr,"%-9s%c",debug_ch_name[i],
+		MSG("%-9s%c",debug_ch_name[i],
 			(((i+2)%8==0)?'\n':' '));
-	    fprintf(stderr,"\n\n");
+	    MSG("\n\n");
 	    exit(1);
 	  }
 #endif
@@ -424,7 +424,7 @@
           if (!__winelib) Options.dllFlags = xstrdup((char *)value.addr);
           else
           {
-              fprintf( stderr, "-dll not supported in Winelib\n" );
+              MSG("-dll not supported in Winelib\n" );
               exit(1);
           }
       }
@@ -472,7 +472,7 @@
     class_hints = TSXAllocClassHint();
     if (!size_hints || !wm_hints || !class_hints)
     {
-        fprintf( stderr, "Not enough memory for window manager hints.\n" );
+        MSG("Not enough memory for window manager hints.\n" );
         exit(1);
     }
     size_hints->min_width = size_hints->max_width = width;
@@ -557,11 +557,11 @@
     mcheck(NULL);
     if (!(trace = getenv("MALLOC_TRACE")))
     {       
-        fprintf( stderr, "MALLOC_TRACE not set. No trace generated\n" );
+        MSG( "MALLOC_TRACE not set. No trace generated\n" );
     }
     else
     {
-        fprintf( stderr, "malloc trace goes to %s\n", trace );
+        MSG( "malloc trace goes to %s\n", trace );
         mtrace();
     }
 #endif
@@ -584,7 +584,7 @@
 
     if (Options.desktopGeometry && Options.managed)
     {
-        fprintf( stderr, "%s: -managed and -desktop options cannot be used together\n",
+        MSG( "%s: -managed and -desktop options cannot be used together\n",
                  Options.programName );
         exit(1);
     }
@@ -600,7 +600,7 @@
 	TSXFree( depth_list );
 	if (i >= depth_count)
 	{
-	    fprintf( stderr, "%s: Depth %d not supported on this screen.\n",
+	    MSG( "%s: Depth %d not supported on this screen.\n",
 		              Options.programName, screenDepth );
 	    exit(1);
 	}
@@ -796,7 +796,7 @@
                 LPANIMATIONINFO lpAnimInfo = (LPANIMATIONINFO)lpvParam;
  
                 /* Do nothing */
-                fprintf(stderr, "SystemParametersInfo: SPI_SETANIMATION ignored.\n");
+                WARN(system, "SPI_SETANIMATION ignored.\n");
                 lpAnimInfo->cbSize = sizeof(ANIMATIONINFO);
                 uParam = sizeof(ANIMATIONINFO);
                 break;
@@ -982,7 +982,7 @@
 		case SPI_SETKEYBOARDDELAY:
 		case SPI_SETKEYBOARDSPEED:
 	        case SPI_GETHIGHCONTRAST:
-			fprintf(stderr, "SystemParametersInfo: option %d ignored.\n", uAction);
+			WARN(system, "Option %d ignored.\n", uAction);
 			break;
 
                 case SPI_GETWORKAREA:
@@ -992,7 +992,7 @@
                     break;
 
 		default:
-			fprintf(stderr, "SystemParametersInfo: unknown option %d.\n", uAction);
+			WARN(system, "Unknown option %d.\n", uAction);
 			break;
 	}
 	return 1;
diff --git a/misc/mpr.c b/misc/mpr.c
deleted file mode 100644
index dce6dc1..0000000
--- a/misc/mpr.c
+++ /dev/null
@@ -1,71 +0,0 @@
-/* MPR.dll
- *
- * Copyright 1996 Marcus Meissner
- */
-
-#include <stdio.h>
-#include "win.h"
-#include "debug.h"
-#include "wnet.h"
-
-
-/**************************************************************************
- * WNetCachePassword [MPR.52]  Saves password in cache
- *
- * RETURNS
- *    Success: WN_SUCCESS
- *    Failure: WNACCESS_DENIED, WN_BAD_PASSWORD, WN_BADVALUE, WN_NET_ERROR,
- *             WN_NOT_SUPPORTED, WN_OUT_OF_MEMORY
- */
-DWORD WINAPI WNetCachePassword(
-    LPSTR pbResource, /* [in] Name of workgroup, computer, or resource */
-    WORD cbResource,  /* [in] Size of name */
-    LPSTR pbPassword, /* [in] Buffer containing password */
-    WORD cbPassword,  /* [in] Size of password */
-    BYTE nType)       /* [in] Type of password to cache */
-{
-    FIXME(mpr,"(%s,%d,%s,%d,%d): stub\n", pbResource,cbResource,
-          pbPassword,cbPassword,nType);
-    return WN_SUCCESS;
-}
-
-
-/**************************************************************************
- * WNetGetCachedPassword [MPR.???]  Retrieves password from cache
- *
- * RETURNS
- *    Success: WN_SUCCESS
- *    Failure: WNACCESS_DENIED, WN_BAD_PASSWORD, WN_BAD_VALUE, WN_NET_ERROR,
- *             WN_NOT_SUPPORTED, WN_OUT_OF_MEMORY
- */
-DWORD WINAPI WNetGetCachedPassword(
-    LPSTR pbResource,   /* [in]  Name of workgroup, computer, or resource */
-    WORD cbResource,    /* [in]  Size of name */
-    LPSTR pbPassword,   /* [out] Buffer to receive password */
-    LPWORD pcbPassword, /* [out] Receives size of password */
-    BYTE nType)         /* [in]  Type of password to retrieve */
-{
-    FIXME(mpr,"(%s,%d,%p,%d,%d): stub\n",
-          pbResource,cbResource,pbPassword,*pcbPassword,nType);
-    return WN_ACCESS_DENIED;
-}
-
-
-/**************************************************************************
- * MultinetGetConnectionPerformance32A [MPR.???]
- *
- * RETURNS
- *    Success: NO_ERROR
- *    Failure: ERROR_NOT_SUPPORTED, ERROR_NOT_CONNECTED,
- *             ERROR_NO_NET_OR_BAD_PATH, ERROR_BAD_DEVICE,
- *             ERROR_BAD_NET_NAME, ERROR_INVALID_PARAMETER, 
- *             ERROR_NO_NETWORK, ERROR_EXTENDED_ERROR
- */
-DWORD WINAPI MultinetGetConnectionPerformance32A(
-    LPNETRESOURCE32A lpNetResource,                /* [in] Specifies resource */
-    LPNETCONNECTINFOSTRUCT lpNetConnectInfoStruct) /* [in] Pointer to struct */
-{
-    FIXME(mpr,"(%p,%p): stub\n",lpNetResource,lpNetConnectInfoStruct);
-    return WN_NOT_SUPPORTED;
-}
-
diff --git a/misc/network.c b/misc/network.c
index 7af8b4c..1df5a1c 100644
--- a/misc/network.c
+++ b/misc/network.c
@@ -1,5 +1,9 @@
 /*
  * Network functions
+ *
+ * This is the MPR.DLL stuff from Win32,  as well as the USER
+ * stuff by the same names in Win 3.x.  
+ *
  */
 
 #include <ctype.h>
@@ -10,9 +14,114 @@
 #include "drive.h"
 #include "wnet.h"
 #include "debug.h"
+#include "win.h"
+
+/********************************************************************
+ *  WNetAddConnection16 [USER.517]  Directs a local device to net
+ * 
+ * Redirects a local device (either a disk drive or printer port)
+ * to a shared device on a remote server.
+ */
+UINT16 WINAPI WNetAddConnection16(LPSTR lpNetPath, LPSTR lpPassWord,
+                                LPSTR lpLocalName)
+{	
+   return WNetAddConnection32A(lpNetPath, lpPassWord, lpLocalName);
+}
+
+/* [MPR.50] */
+
+UINT32 WNetAddConnection32A(LPSTR NetPath, LPSTR PassWord,
+			    LPSTR LocalName)
+{
+   FIXME(wnet, "('%s', %p, '%s'): stub\n",
+	 NetPath, PassWord, LocalName);
+   return WN_NO_NETWORK;
+}
+
+/* [MPR.51] */
+
+UINT32 WNetAddConnection32W(LPWSTR NetPath, 
+			    LPWSTR PassWord,
+			    LPWSTR LocalName)
+{
+   FIXME(wnet, " stub!\n");
+   return WN_NO_NETWORK;
+}
+
+/* **************************************************************** 
+ * WNetAddConnection2_32A [MPR.46] 
+ */
+
+UINT32
+WNetAddConnection2_32A(LPNETRESOURCE32A netresource, /* [in] */
+		       LPCSTR password,        /* [in] */     
+		       LPCSTR username,        /* [in] */
+		       DWORD flags             /* [in] */  )
+{
+   FIXME(wnet, "(%p,%s,%s,0x%08lx), stub!\n", netresource,
+	 password, username, (unsigned long) flags);
+   SetLastError(WN_NO_NETWORK);
+   return WN_NO_NETWORK;
+}
+
+/* ****************************************************************
+ * WNetAddConnection2W [MPR.47]
+ */
+
+UINT32
+WNetAddConnection2_32W(LPNETRESOURCE32W netresource, /* [in] */
+		       LPCWSTR password,        /* [in] */     
+		       LPCWSTR username,        /* [in] */
+		       DWORD flags              /* [in] */  )
+{
+   FIXME(wnet, ", stub!\n");
+   SetLastError(WN_NO_NETWORK);
+   return WN_NO_NETWORK;
+}
+
+/* ****************************************************************
+ * WNetAddConnection3_32A [MPR.48]
+ */
+
+UINT32 WNetAddConnection3_32A(HWND32 owner,
+		      LPNETRESOURCE32A netresource,
+		      LPCSTR password,
+		      LPCSTR username,
+		      DWORD flags)
+{
+   TRACE(wnet, "owner = 0x%x\n", owner);
+   return WNetAddConnection2_32A(netresource, 
+				 password, username, flags);
+}
+
+/* ****************************************************************
+ * WNetAddConnection3W [MPR.49]
+ */
+
+UINT32 WNetAddConnection3_32W(HWND32 owner,
+			      LPNETRESOURCE32W netresource,
+			      LPCWSTR username,
+			      LPCWSTR password,
+			      DWORD flags)
+{
+   TRACE(wnet,"owner = 0x%x\n", owner);
+   return WNetAddConnection2_32W(netresource, username, password,
+				 flags); 
+} 
+
+
+/********************************************************************
+ *   WNetCancelConnection	[USER.518]  undirects a local device
+ */
+UINT16 WINAPI WNetCancelConnection(LPSTR lpName, BOOL16 bForce)
+{
+    FIXME(wnet, "('%s', %04X): stub\n", lpName, bForce);
+    return WN_NO_NETWORK;
+}
+
 
 /**************************************************************************
- *              WNetErrorText       [USER.499]
+ *              WNetErrorText16       [USER.499]
  */
 int WINAPI WNetErrorText(WORD nError,LPSTR lpszText,WORD cbText)
 {
@@ -21,7 +130,7 @@
 }
 
 /**************************************************************************
- *              WNetOpenJob       [USER.501]
+ *              WNetOpenJob16       [USER.501]
  */
 int WINAPI WNetOpenJob(LPSTR szQueue,LPSTR szJobTitle,WORD nCopies,LPWORD pfh)
 {
@@ -120,8 +229,15 @@
 	return WN_NET_ERROR;
 }
 
-/**************************************************************************
- *				WNetGetConnection	[USER.512]
+
+/********************************************************************
+ * WNetGetConnection16 [USER.512] reverse-resolves a local device
+ *
+ * RETURNS
+ * - WN_BAD_LOCALNAME     lpLocalName makes no sense
+ * - WN_NOT_CONNECTED     drive is a local drive
+ * - WN_MORE_DATA         buffer isn't big enough
+ * - WN_SUCCESS           success (net path in buffer)  
  */
 int WINAPI WNetGetConnection16(LPCSTR lpLocalName, 
                                LPSTR lpRemoteName, UINT16 *cbRemoteName)
@@ -155,6 +271,19 @@
 }
 
 /**************************************************************************
+ *				WNetGetConnectionA	[MPR.70]
+ */
+DWORD WINAPI
+WNetGetConnection32A(LPCSTR localname,LPSTR remotename,LPDWORD buflen)
+{
+	UINT16	x;
+	DWORD	ret = WNetGetConnection16(localname,remotename,&x);
+	*buflen = x;
+	return ret;
+}
+
+
+/**************************************************************************
  *				WNetGetCaps		[USER.513]
  */
 int WINAPI WNetGetCaps(WORD capability)
@@ -255,27 +384,6 @@
 }
 
 /**************************************************************************
- *				WNetAddConnection	[USER.517]
- */
-UINT16 WINAPI WNetAddConnection(LPSTR lpNetPath, LPSTR lpPassWord,
-                                LPSTR lpLocalName)
-{
-	FIXME(wnet, "('%s', %p, '%s'): stub\n",
-	      lpNetPath,lpPassWord,lpLocalName);
-	return WN_NO_NETWORK;
-}
-
-
-/**************************************************************************
- *				WNetCancelConnection	[USER.518]
- */
-UINT16 WINAPI WNetCancelConnection(LPSTR lpName, BOOL16 bForce)
-{
-    FIXME(wnet, "('%s', %04X): stub\n", lpName, bForce);
-    return WN_NO_NETWORK;
-}
-
-/**************************************************************************
  *              WNetGetError       [USER.519]
  */
 int WINAPI WNetGetError(LPWORD nError)
@@ -311,8 +419,8 @@
 	return WN_NO_NETWORK;
 }
 
-/**************************************************************************
- *              WnetConnectDialog       [USER.525]
+/********************************************************************
+ *              WNetConnectDialog       [USER.525]
  */
 UINT16 WINAPI WNetConnectDialog(HWND16 hWndParent, WORD iType)
 {
@@ -338,6 +446,8 @@
 	return WN_SUCCESS;
 }
 
+
+
 /**************************************************************************
  *              WNetViewQueueDialog       [USER.528]
  */
@@ -358,15 +468,30 @@
 	return WN_NO_NETWORK;
 }
 
-/**************************************************************************
- *              WNetGetDirectoryType       [USER.530]
+/*********************************************************************
+ *  WNetGetDirectoryType [USER.530]  Decides whether resource is local
+ *
+ * RETURNS
+ *    on success,  puts one of the following in *lpType:
+ * - WNDT_NETWORK   on a network
+ * - WNDT_LOCAL     local
  */
-int WINAPI WNetGetDirectoryType(LPSTR lpName,void *lpType)
+int WINAPI WNetGetDirectoryType16(LPSTR lpName, LPINT16 lpType)
 {
 	FIXME(wnet, "('%s',%p): stub\n",lpName,lpType);
+	*lpType = 0;
 	return WN_NO_NETWORK;
 }
 
+/*****************************************************************
+ *              WNetGetDirectoryTypeA     [MPR.109]
+ */
+
+UINT32 WINAPI WNetGetDirectoryType32A(LPSTR lpName,void *lpType)
+{
+   return WNetGetDirectoryType16(lpName, lpType);
+}
+
 /**************************************************************************
  *              WNetDirectoryNotify       [USER.531]
  */
@@ -387,16 +512,6 @@
 	return WN_NO_NETWORK;
 }
 
-/**************************************************************************
- *				WNetAddConnection2	[USER.???]
- */
-UINT16 WINAPI WNetAddConnection2(LPSTR lpNetPath, LPSTR lpPassWord, 
-                                 LPSTR lpLocalName, LPSTR lpUserName)
-{
-	FIXME(wnet, "('%s', %p, '%s', '%s'): stub\n",
-	      lpNetPath, lpPassWord, lpLocalName, lpUserName);
-	return WN_NO_NETWORK;
-}
 
 /**************************************************************************
  *				WNetCloseEnum		[USER.???]
@@ -440,17 +555,9 @@
 	return WN_NO_NETWORK;
 }
 
-/**************************************************************************
- *				WNetGetConnectionA	[MPR.92]
- */
-DWORD WINAPI
-WNetGetConnection32A(LPCSTR localname,LPSTR remotename,LPDWORD buflen)
-{
-	UINT16	x;
-	DWORD	ret = WNetGetConnection16(localname,remotename,&x);
-	*buflen = x;
-	return ret;
-}
+/* ****************************************************************
+ *    WNetGetResourceInformationA [MPR.80]
+ * */
 
 DWORD WINAPI 
 WNetGetResourceInformation32A(
@@ -459,3 +566,63 @@
 	FIXME(wnet,"(%p,%p,%p,%p): stub!\n",netres,buf,buflen,systemstr);
 	return WN_NO_NETWORK;
 }
+
+/**************************************************************************
+ * WNetCachePassword [MPR.52]  Saves password in cache
+ *
+ * RETURNS
+ *    Success: WN_SUCCESS
+ *    Failure: WNACCESS_DENIED, WN_BAD_PASSWORD, WN_BADVALUE, WN_NET_ERROR,
+ *             WN_NOT_SUPPORTED, WN_OUT_OF_MEMORY
+ */
+DWORD WINAPI WNetCachePassword(
+    LPSTR pbResource, /* [in] Name of workgroup, computer, or resource */
+    WORD cbResource,  /* [in] Size of name */
+    LPSTR pbPassword, /* [in] Buffer containing password */
+    WORD cbPassword,  /* [in] Size of password */
+    BYTE nType)       /* [in] Type of password to cache */
+{
+    FIXME(mpr,"(%s,%d,%s,%d,%d): stub\n", pbResource,cbResource,
+          pbPassword,cbPassword,nType);
+    return WN_SUCCESS;
+}
+
+
+
+/*****************************************************************
+ * WNetGetCachedPassword [MPR.69]  Retrieves password from cache
+ *
+ * RETURNS
+ *    Success: WN_SUCCESS
+ *    Failure: WNACCESS_DENIED, WN_BAD_PASSWORD, WN_BAD_VALUE, 
+ *             WN_NET_ERROR, WN_NOT_SUPPORTED, WN_OUT_OF_MEMORY
+ */
+DWORD WINAPI WNetGetCachedPassword(
+    LPSTR pbResource,   /* [in]  Name of workgroup, computer, or resource */
+    WORD cbResource,    /* [in]  Size of name */
+    LPSTR pbPassword,   /* [out] Buffer to receive password */
+    LPWORD pcbPassword, /* [out] Receives size of password */
+    BYTE nType)         /* [in]  Type of password to retrieve */
+{
+    FIXME(mpr,"(%s,%d,%p,%d,%d): stub\n",
+          pbResource,cbResource,pbPassword,*pcbPassword,nType);
+    return WN_ACCESS_DENIED;
+}
+
+/* ****************************************************************
+ *     MultinetGetConnectionPerformanceA [MPR.25]
+ *
+ * RETURNS
+ *    Success: NO_ERROR
+ *    Failure: ERROR_NOT_SUPPORTED, ERROR_NOT_CONNECTED,
+ *             ERROR_NO_NET_OR_BAD_PATH, ERROR_BAD_DEVICE,
+ *             ERROR_BAD_NET_NAME, ERROR_INVALID_PARAMETER, 
+ *             ERROR_NO_NETWORK, ERROR_EXTENDED_ERROR
+ */
+DWORD WINAPI MultinetGetConnectionPerformance32A(
+	LPNETRESOURCE32A lpNetResource,
+	LPNETCONNECTINFOSTRUCT lpNetConnectInfoStruct
+) {
+	FIXME(mpr,"(%p,%p): stub\n",lpNetResource,lpNetConnectInfoStruct);
+	return 1;
+}
diff --git a/misc/ntdll.c b/misc/ntdll.c
index e52e201..7744f95 100644
--- a/misc/ntdll.c
+++ b/misc/ntdll.c
@@ -36,8 +36,11 @@
 
 /**************************************************************************
  *                 RtlCreateAcl				[NTDLL]
+ *
+ * NOTES
+ *    This should return NTSTATUS
  */
-DWORD /* NTSTATUS */ WINAPI RtlCreateAcl(LPACL acl,DWORD size,DWORD rev)
+DWORD WINAPI RtlCreateAcl(LPACL acl,DWORD size,DWORD rev)
 {
 	if (rev!=ACL_REVISION)
 		return STATUS_INVALID_PARAMETER;
diff --git a/misc/printdrv.c b/misc/printdrv.c
index 2466010..7389ed3 100644
--- a/misc/printdrv.c
+++ b/misc/printdrv.c
@@ -39,16 +39,16 @@
                                LPDWORD lpType, LPBYTE lpPrinterData,
                                int cbData, LPDWORD lpNeeded)
 {
-    fprintf(stderr,"In DrvGetPrinterData ");
+    FIXME(print, "stub.\n");
     if (HIWORD(lpPrinter))
-	    fprintf(stderr,"printer %s ",lpPrinter);
+	    TRACE(print,"printer %s\n",lpPrinter);
     else
-	    fprintf(stderr,"printer %p ",lpPrinter);
+	    TRACE(print,"printer %p\n",lpPrinter);
     if (HIWORD(lpProfile))
-	    fprintf(stderr,"profile %s ",lpProfile);
+	    TRACE(print,"profile %s\n",lpProfile);
     else
-	    fprintf(stderr,"profile %p ",lpProfile);
-    fprintf(stderr,"lpType %p\n",lpType);
+	    TRACE(print,"profile %p\n",lpProfile);
+    TRACE(print,"lpType %p\n",lpType);
     return 0;
 }
 
@@ -58,16 +58,16 @@
                                LPDWORD lpType, LPBYTE lpPrinterData,
                                DWORD dwSize)
 {
-    fprintf(stderr,"In DrvSetPrinterData ");
+    FIXME(print, "stub.\n");
     if (HIWORD(lpPrinter))
-	    fprintf(stderr,"printer %s ",lpPrinter);
+	    TRACE(print,"printer %s\n",lpPrinter);
     else
-	    fprintf(stderr,"printer %p ",lpPrinter);
+	    TRACE(print,"printer %p\n",lpPrinter);
     if (HIWORD(lpProfile))
-	    fprintf(stderr,"profile %s ",lpProfile);
+	    TRACE(print,"profile %s\n",lpProfile);
     else
-	    fprintf(stderr,"profile %p ",lpProfile);
-    fprintf(stderr,"lpType %p\n",lpType);
+	    TRACE(print,"profile %p\n",lpProfile);
+    TRACE(print,"lpType %p\n",lpType);
     return 0;
 }
 
@@ -75,7 +75,7 @@
 INT32 WINAPI DeviceCapabilities32A(LPCSTR printer,LPCSTR target,WORD z,
                                    LPSTR a,LPDEVMODE32A b)
 {
-    fprintf(stderr,"DeviceCapabilitiesA(%s,%s,%d,%p,%p)\n",printer,target,z,a,b);
+    FIXME(print,"(%s,%s,%d,%p,%p):stub.\n",printer,target,z,a,b);
     return 1;   	
 }
 
@@ -83,7 +83,7 @@
                                 LPSTR pDeviceName, LPDEVMODE32A pDevModeOutput,
                                   LPDEVMODE32A pDevModeInput,DWORD fMode )
 {
-    fprintf(stderr,"DocumentPropertiesA(%d,%d,%s,%p,%p,%ld)\n",
+    FIXME(print,"(%d,%d,%s,%p,%p,%ld):stub.\n",
 	hWnd,hPrinter,pDeviceName,pDevModeOutput,pDevModeInput,fMode
     );
     return 1;
@@ -92,7 +92,7 @@
 BOOL32 WINAPI OpenPrinter32A(LPSTR lpPrinterName,HANDLE32 *phPrinter,
 			     LPPRINTER_DEFAULTS32A pDefault)
 {
-    fprintf(stderr,"OpenPrinter32A(%s,%p,%p), stub\n",
+    FIXME(print,"(%s,%p,%p):stub.\n",
 	    lpPrinterName, phPrinter, pDefault);
     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
     return FALSE;
@@ -102,7 +102,7 @@
 			       DWORD cbBuf, LPDWORD lpdwNeeded,
 			       LPDWORD lpdwReturned)
 {
-    fprintf(stderr,"EnumPrinters32A nearly empty stub\n");
+    FIXME(print,"Nearly empty stub\n");
     *lpdwReturned=0;
     return TRUE;
 }
diff --git a/misc/registry.c b/misc/registry.c
index b73c7f5..537c4ed 100644
--- a/misc/registry.c
+++ b/misc/registry.c
@@ -250,7 +250,7 @@
 
 	ADD_ROOT_KEY(key_local_machine);
 	if (RegCreateKey16(HKEY_LOCAL_MACHINE,"\\SOFTWARE\\Classes",&cl_r_hkey)!=ERROR_SUCCESS) {
-		fprintf(stderr,"couldn't create HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes. This is impossible.\n");
+		ERR(reg,"couldn't create HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes. This is impossible.\n");
 		exit(1);
 	}
 	key_classes_root = lookup_hkey(cl_r_hkey);
@@ -439,7 +439,7 @@
 
 	F=fopen(fn,"w");
 	if (F==NULL) {
-		fprintf(stddeb,__FILE__":_savereg:Couldn't open %s for writing: %s\n",
+		WARN(reg,"Couldn't open %s for writing: %s\n",
 			fn,strerror(errno)
 		);
 		return FALSE;
@@ -447,7 +447,7 @@
 	if (!_savesubreg(F,lpkey,all)) {
 		fclose(F);
 		unlink(fn);
-		fprintf(stddeb,__FILE__":_savereg:Failed to save keys, perhaps no more diskspace for %s?\n",fn);
+		WARN(reg,"Failed to save keys, perhaps no more diskspace for %s?\n",fn);
 		return FALSE;
 	}
 	fclose(F);
@@ -519,7 +519,7 @@
 		free(tmp);
 		free(fn);
 	} else
-		fprintf(stderr,"SHELL_SaveRegistry:failed to get homedirectory of UID %d.\n",getuid());
+		WARN(reg,"Failed to get homedirectory of UID %d.\n",getuid());
 }
 
 /************************ LOAD Registry Function ****************************/
@@ -669,7 +669,7 @@
 				continue;
 			}
 			if (*s!='u') {
-				fprintf(stderr,"_wine_read_USTRING:Non unicode escape sequence \\%c found in |%s|\n",*s,buf);
+				WARN(reg,"Non unicode escape sequence \\%c found in |%s|\n",*s,buf);
 				*ws++='\\';
 				*ws++=*s++;
 			} else {
@@ -679,7 +679,7 @@
 				s++;
 				memcpy(xbuf,s,4);xbuf[4]='\0';
 				if (!sscanf(xbuf,"%x",&wc))
-					fprintf(stderr,"_wine_read_USTRING:strange escape sequence %s found in |%s|\n",xbuf,buf);
+					WARN(reg,"Strange escape sequence %s found in |%s|\n",xbuf,buf);
 				s+=4;
 				*ws++	=(unsigned short)wc;
 			}
@@ -716,7 +716,7 @@
 		}
 		if (i>level) {
 			if (lpxkey==NULL) {
-				fprintf(stderr,"_load_subkey:Got a subhierarchy without resp. key?\n");
+				WARN(reg,"Got a subhierarchy without resp. key?\n");
 				return 0;
 			}
 			_wine_loadsubkey(F,lpxkey,level+1,buf,buflen,optflag);
@@ -739,12 +739,12 @@
 				int		len,lastmodified,type;
 
 				if (*s!='=') {
-					fprintf(stderr,"_wine_load_subkey:unexpected character: %c\n",*s);
+					WARN(reg,"Unexpected character: %c\n",*s);
 					break;
 				}
 				s++;
 				if (2!=sscanf(s,"%d,%d,",&type,&lastmodified)) {
-					fprintf(stderr,"_wine_load_subkey: haven't understood possible value in |%s|, skipping.\n",*buf);
+					WARN(reg,"Haven't understood possible value in |%s|, skipping.\n",*buf);
 					break;
 				}
 				/* skip the 2 , */
@@ -764,16 +764,16 @@
 						if (*s>='0' && *s<='9')
 							data[i]=(*s-'0')<<4;
 						if (*s>='a' && *s<='f')
-							data[i]=(*s-'a')<<4;
+							data[i]=(*s-'a'+'\xa')<<4;
 						if (*s>='A' && *s<='F')
-							data[i]=(*s-'A')<<4;
+							data[i]=(*s-'A'+'\xa')<<4;
 						s++;
 						if (*s>='0' && *s<='9')
 							data[i]|=*s-'0';
 						if (*s>='a' && *s<='f')
-							data[i]|=*s-'a';
+							data[i]|=*s-'a'+'\xa';
 						if (*s>='A' && *s<='F')
-							data[i]|=*s-'A';
+							data[i]|=*s-'A'+'\xa';
 						s++;
 					}
 				}
@@ -1173,7 +1173,7 @@
 	if (4!=_lread32(hfd,magic,4))
 		return;
 	if (strcmp(magic,"CREG")) {
-		fprintf(stddeb,"%s is not a w95 registry.\n",fn);
+		WARN(reg,"%s is not a w95 registry.\n",fn);
 		return;
 	}
 	if (4!=_lread32(hfd,&version,4))
@@ -1479,7 +1479,7 @@
 		_wine_loadreg(key_local_machine,fn,REG_OPTION_TAINTED);
 		free(fn);
 	} else
-		fprintf(stderr,"SHELL_LoadRegistry:failed to get homedirectory of UID %d.\n",getuid());
+		WARN(reg,"Failed to get homedirectory of UID %d.\n",getuid());
 	if (ERROR_SUCCESS==RegCreateKey16(HKEY_CURRENT_USER,KEY_REGISTRY,&hkey)) {
 		DWORD	junk,type,len;
 		char	data[5];
@@ -2266,7 +2266,7 @@
 	} else
 		xhkey=hkey;
 	if (dwType!=REG_SZ) {
-		fprintf(stddeb,"RegSetValueX called with dwType=%ld!\n",dwType);
+		TRACE(reg,"RegSetValueX called with dwType=%ld!\n",dwType);
 		dwType=REG_SZ;
 	}
 	if (cbData!=2*lstrlen32W(lpszData)+2) {
@@ -2799,13 +2799,25 @@
 	return RegDeleteValue32A(hkey,lpszValue);
 }
 
-/* RegFlushKey			[ADVAPI32.143] [KERNEL.227] */
-DWORD WINAPI RegFlushKey(HKEY hkey)
+
+/******************************************************************************
+ * RegFlushKey [KERNEL.227] [ADVAPI32.143]
+ * Writes key to registry
+ *
+ * PARAMS
+ *    hkey [I] Handle of key to write
+ *
+ * RETURNS
+ *    Success: ERROR_SUCCESS
+ *    Failure: Error code
+ */
+DWORD WINAPI RegFlushKey( HKEY hkey )
 {
-	FIXME(reg, "(%x), STUB.\n", hkey);
-	return SHELL_ERROR_SUCCESS;
+    FIXME(reg, "(%x): stub\n", hkey);
+    return ERROR_SUCCESS;
 }
 
+
 /* FIXME: lpcchXXXX ... is this counting in WCHARS or in BYTEs ?? */
 
 /* RegQueryInfoKeyW		[ADVAPI32.153] */
@@ -2940,8 +2952,29 @@
 /* RegConnectRegistryA		[ADVAPI32.127] */
 DWORD WINAPI RegConnectRegistry32A(LPCSTR machine,HKEY hkey,LPHKEY reskey)
 {
-	fprintf(stderr,"RegConnectRegistry32A(%s,%08x,%p), STUB.\n",
-		machine,hkey,reskey
-	);
+	FIXME(reg,"(%s,%08x,%p):stub.\n",machine,hkey,reskey);
 	return ERROR_FILE_NOT_FOUND; /* FIXME */
 }
+
+
+/******************************************************************************
+ * RegGetKeySecurity [ADVAPI32.144]
+ * Retrieves a copy of security descriptor protecting the registry key
+ *
+ * NOTES
+ *    pSecurityDescriptor should be PSECURITY_DESCRIPTOR
+ *
+ * RETURNS
+ *    Success: ERROR_SUCCESS
+ *    Failure: Error code
+ */
+LONG WINAPI RegGetKeySecurity( HKEY hKey, 
+                               SECURITY_INFORMATION SecurityInformation,
+                               LPVOID pSecurityDescriptor,
+                               LPDWORD lpcbSecurityDescriptor )
+{
+    FIXME(reg, "(%d,%ld,%p,%p): stub\n", hKey, SecurityInformation,
+          pSecurityDescriptor, lpcbSecurityDescriptor);
+    return ERROR_SUCCESS;
+}
+
diff --git a/misc/shellord.c b/misc/shellord.c
index 8cbfa40..a21ab8a 100644
--- a/misc/shellord.c
+++ b/misc/shellord.c
@@ -34,7 +34,7 @@
  *	 		 SHELL32_2   			[SHELL32.2]
  */
 DWORD WINAPI SHELL32_2(HWND32 hwnd,DWORD x2,DWORD x3,DWORD x4,DWORD x5,DWORD x6) {
-	fprintf(stderr,"SHELL32_2(0x%04x,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx),stub!\n",
+	FIXME(shell,"(0x%04x,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx):stub.\n",
 		hwnd,x2,x3,x4,x5,x6
 	);
 	return 0;
@@ -286,7 +286,7 @@
  *	 		 SHELL32_58   			[SHELL32.58]
  */
 DWORD WINAPI SHELL32_58(LPCSTR src,DWORD x2,LPSTR target,DWORD pathlen) {
-	fprintf(stderr,"SHELL32_58(%s,0x%08lx,%p,%ld),STUB!\n",
+	FIXME(shell,"(%s,0x%08lx,%p,%ld):stub.\n",
 		src,x2,target,pathlen
 	);
 	if (!src)
@@ -298,7 +298,7 @@
  *	 		 SHELL32_62   			[SHELL32.62]
  */
 DWORD WINAPI SHELL32_62(DWORD x,DWORD y,DWORD z,DWORD a) {
-	fprintf(stderr,"SHELL32_62(%08lx,%08lx,%08lx,%08lx),stub!\n",x,y,z,a);
+	FIXME(shell,"(%08lx,%08lx,%08lx,%08lx):stub.\n",x,y,z,a);
 	return 0xffffffff;
 }
 
@@ -306,7 +306,7 @@
  *                      SHELL32_63                     [SHELL32.63]
  */
 DWORD WINAPI SHELL32_63(HWND32 howner, LPSTR targetbuf, DWORD len, DWORD x, LPCSTR suffix, LPCSTR y, LPCSTR cmd) {
-    fprintf(stderr,"SHELL32_63(%04x,%p,%ld,%08lx,%s,%s,%s),stub!\n",
+    FIXME(shell,"(%04x,%p,%ld,%08lx,%s,%s,%s):stub.\n",
 	    howner,targetbuf,len,x,suffix,y,cmd
     );
     /* puts up a Open Dialog and requests input into targetbuf */
@@ -319,7 +319,7 @@
  *                      SHELL32_68                     [SHELL32.68]
  */
 DWORD WINAPI SHELL32_68(DWORD x,DWORD y,DWORD z) {
-	fprintf(stderr,"SHELL32_68(0x%08lx,0x%08lx,0x%08lx),stub!\n",
+	FIXME(shell,"(0x%08lx,0x%08lx,0x%08lx):stub.\n",
 		x,y,z
 	);
 	return 0;
@@ -330,7 +330,7 @@
  */
 BOOL32 WINAPI SHELL32_71(LPDWORD x,LPDWORD y) {
 
-	fprintf(stderr,"SHELL32_71(%p,%p),stub!\n",x,y);
+	FIXME(shell,"(%p,%p):stub.\n",x,y);
 	return TRUE;
 }
 
@@ -339,14 +339,14 @@
  * dunno. something with icons
  */
 void WINAPI SHELL32_72(LPSTR x,DWORD y,DWORD z) {
-	fprintf(stderr,"SHELL32_72(%s,%08lx,%08lx),stub!\n",x,y,z);
+	FIXME(shell,"(%s,%08lx,%08lx):stub.\n",x,y,z);
 }
 
 /*************************************************************************
  *			 SHELL32_89   			[SHELL32.89]
  */
 DWORD WINAPI SHELL32_89(DWORD x1,DWORD x2,DWORD x3) {
-	fprintf(stderr,"SHELL32_89(0x%08lx,0x%08lx,0x%08lx),stub!\n",
+	FIXME(shell,"(0x%08lx,0x%08lx,0x%08lx):stub.\n",
 		x1,x2,x3
 	);
 	return 0;
@@ -357,7 +357,7 @@
  * unknown
  */
 void WINAPI SHELL32_119(LPVOID x) {
-    fprintf(stderr,"SHELL32_119(%p(%s)),stub\n",x,(char *)x);
+    FIXME(shell,"(%p(%s)):stub.\n",x,(char *)x);
 }
 
 /*************************************************************************
@@ -365,7 +365,7 @@
  * unknown
  */
 void WINAPI SHELL32_175(DWORD x1,DWORD x2,DWORD x3,DWORD x4) {
-    fprintf(stderr,"SHELL32_175(0x%08lx,0x%08lx,0x%08lx,0x%08lx),stub\n",
+    FIXME(shell,"(0x%08lx,0x%08lx,0x%08lx,0x%08lx):stub.\n",
     	x1,x2,x3,x4
     );
 }
@@ -375,7 +375,7 @@
  * unknown
  */
 void WINAPI SHELL32_181(DWORD x,DWORD y) {
-    fprintf(stderr,"SHELL32_181(0x%08lx,0x%08lx)\n",x,y);
+    FIXME(shell,"(0x%08lx,0x%08lx):stub.\n",x,y);
 }
 
 /*************************************************************************
@@ -383,7 +383,7 @@
  * unknown
  */
 BOOL32 WINAPI SHELL32_75(LPDWORD x,LPDWORD y) {
-    fprintf(stderr,"SHELL32_75(%p,%p),stub\n",x,y);
+    FIXME(shell,"(%p,%p):stub.\n",x,y);
     return TRUE;
 }
 
@@ -391,7 +391,7 @@
  *	 		 SHELL32_77   			[SHELL32.77]
  */
 DWORD WINAPI SHELL32_77(DWORD x,DWORD y,DWORD z) {
-	fprintf(stderr,"SHELL32_77(%08lx,%08lx,%08lx),stub!\n",x,y,z);
+	FIXME(shell,"(%08lx,%08lx,%08lx):stub.\n",x,y,z);
 	return 0;
 }
 
@@ -400,20 +400,24 @@
  * create_directory_and_notify(...)
  */
 DWORD WINAPI SHELL32_79(LPCSTR dir,LPVOID xvoid) {
-	fprintf(stderr,"mkdir %s,%p\n",dir,xvoid);
+	TRACE(shell,"mkdir %s,%p\n",dir,xvoid);
 	if (!CreateDirectory32A(dir,xvoid))
 		return FALSE;
 	/* SHChangeNotify(8,1,dir,0); */
 	return TRUE;
 }
 
-static FARPROC32 _find_moduleproc(LPSTR dllname,HMODULE32 *xhmod,LPSTR name) {
+typedef DWORD (* WINAPI GetClassPtr)(REFCLSID,REFIID,LPVOID);
+
+static GetClassPtr SH_find_moduleproc(LPSTR dllname,HMODULE32 *xhmod,
+                                      LPSTR name)
+{
 	HMODULE32	hmod;
 	FARPROC32	dllunload,nameproc;
 
 	if (xhmod) *xhmod = 0;
 	if (!lstrcmpi32A(SHELL32_34(dllname),"shell32.dll"))
-		return (FARPROC32)SHELL32_DllGetClassObject;
+		return (GetClassPtr)SHELL32_DllGetClassObject;
 
 	hmod = LoadLibraryEx32A(dllname,0,LOAD_WITH_ALTERED_SEARCH_PATH);
 	if (!hmod)
@@ -427,17 +431,17 @@
 		return NULL;
 	}
 	/* register unloadable dll with unloadproc ... */
-	return nameproc;
+	return (GetClassPtr)nameproc;
 }
 
-static DWORD _get_instance(REFCLSID clsid,LPSTR dllname,
+static DWORD SH_get_instance(REFCLSID clsid,LPSTR dllname,
 	LPVOID	unknownouter,REFIID refiid,LPVOID inst
 ) {
-	DWORD	WINAPI	(*dllgetclassob)(REFCLSID,REFIID,LPVOID);
+        GetClassPtr     dllgetclassob;
 	DWORD		hres;
 	LPCLASSFACTORY	classfac;
 
-	dllgetclassob = (DWORD(*)(REFCLSID,REFIID,LPVOID))_find_moduleproc(dllname,NULL,"DllGetClassObject");
+	dllgetclassob = SH_find_moduleproc(dllname,NULL,"DllGetClassObject");
 	if (!dllgetclassob)
 		return 0x80070000|GetLastError();
 
@@ -455,6 +459,7 @@
 	classfac->lpvtbl->fnRelease(classfac);
 	return 0;
 }
+
 /*************************************************************************
  *				SHELL32_102	[SHELL32.102]
  * unknown
@@ -476,29 +481,29 @@
 		    return 0x80040154;
 		strcpy(xclsid,aclsid);
 	}
-	fprintf(stderr,"SHELL32_102(%p,%s,%p,%s,%p)\n",
+	TRACE(shell,"(%p,%s,%p,%s,%p)\n",
 		aclsid,xclsid,unknownouter,xiid,inst
 	);
 
 	sprintf(buffer,"CLSID\\%s\\InProcServer32",xclsid);
 	if (RegOpenKeyEx32A(HKEY_CLASSES_ROOT,buffer,0,0x02000000,&inprockey))
-		return _get_instance(clsid,"shell32.dll",unknownouter,refiid,inst);
+		return SH_get_instance(clsid,"shell32.dll",unknownouter,refiid,inst);
 	pathlen=sizeof(path);
 	if (RegQueryValue32A(inprockey,NULL,path,&pathlen)) {
 		RegCloseKey(inprockey);
-		return _get_instance(clsid,"shell32.dll",unknownouter,refiid,inst);
+		return SH_get_instance(clsid,"shell32.dll",unknownouter,refiid,inst);
 	}
-	fprintf(stderr,"	-> server dll is %s\n",path);
+	TRACE(shell, "Server dll is %s\n",path);
 	tmodellen=sizeof(tmodel);
 	type=REG_SZ;
 	if (RegQueryValueEx32A(inprockey,"ThreadingModel",NULL,&type,tmodel,&tmodellen)) {
 		RegCloseKey(inprockey);
-		return _get_instance(clsid,"shell32.dll",unknownouter,refiid,inst);
+		return SH_get_instance(clsid,"shell32.dll",unknownouter,refiid,inst);
 	}
-	fprintf(stderr,"	-> threading model is %s\n",tmodel);
-	hres=_get_instance(clsid,path,unknownouter,refiid,inst);
+	TRACE(shell, "Threading model is %s\n",tmodel);
+	hres=SH_get_instance(clsid,path,unknownouter,refiid,inst);
 	if (hres<0)
-		hres=_get_instance(clsid,"shell32.dll",unknownouter,refiid,inst);
+		hres=SH_get_instance(clsid,"shell32.dll",unknownouter,refiid,inst);
 	RegCloseKey(inprockey);
 	return hres;
 }
@@ -518,7 +523,7 @@
 	/* FIXME: the varargs handling doesn't. */
 	FormatMessage32A(0x500,buf2,0,0,&buf3,256,&args);
 
-	fprintf(stderr,"SHELL32_183(%08lx,%08lx,%08lx(%s),%08lx(%s),%08lx,%p),stub!\n",
+	FIXME(shell,"(%08lx,%08lx,%08lx(%s),%08lx(%s),%08lx,%p):stub.\n",
 		(DWORD)hmod,(DWORD)hwnd,id,buf2,x,buf,type,arglist
 	);
 	/*MessageBox32A(hwnd,buf3,buf,id|0x10000);*/
@@ -553,7 +558,7 @@
 DWORD WINAPI SHELL32_100(DWORD pol) {
 	HKEY	xhkey;
 
-	fprintf(stderr,"SHELL32_100(%08lx),stub!\n",pol);
+	FIXME(shell,"(%08lx):stub.\n",pol);
 	if (RegOpenKey32A(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Policies",&xhkey))
 		return 0;
 	/* FIXME: do nothing for now, just return 0 (== "allowed") */
@@ -583,7 +588,7 @@
  *                      SHELL32_158                    [SHELL32.158]
  */
 LPSTR WINAPI SHELL32_158(LPSTR path,DWORD y,DWORD z) {
-    fprintf(stderr,"SHELL32_158(%s,%08lx,%08lx)\n",path,y,z);
+    TRACE(shell,"(%s,%08lx,%08lx)\n",path,y,z);
     path = SHELL32_31(path);
     return *path?(path+1):path;
 }
@@ -595,7 +600,7 @@
 DWORD WINAPI SHELL32_165(DWORD x,LPCSTR path) {
 	if (SHELL32_79(path,(LPVOID)x))
 		return 0;
-	fprintf(stderr,"SHELL32_165(%08lx,%s),stub!\n",x,path);
+	FIXME(shell,"(%08lx,%s):stub.\n",x,path);
 	return 0;
 }
 
@@ -654,3 +659,4 @@
 		return 0;
 	return SHELL32_195(x);
 }
+
diff --git a/misc/system.c b/misc/system.c
index 65646bc..99fbcfb 100644
--- a/misc/system.c
+++ b/misc/system.c
@@ -16,6 +16,7 @@
 #include "callback.h"
 #include "windows.h"
 #include "miscemu.h"
+#include "debug.h"
 
 typedef struct
 {
@@ -115,10 +116,10 @@
         return MAKELONG( drivetype, drivetype );
 
     case 2:  /* Enable one-drive logic */
-        fprintf( stderr, "InquireSystem(2): set single-drive %d not supported\n", arg );
+        FIXME(system, "Case %d: set single-drive %d not supported\n", code, arg );
         return 0;
     }
-    fprintf( stderr, "InquireSystem: unknown code %d\n", code );
+    WARN(system, "Unknown code %d\n", code );
     return 0;
 }
 
diff --git a/misc/ver.c b/misc/ver.c
index da9f8e5..851b37b 100644
--- a/misc/ver.c
+++ b/misc/ver.c
@@ -297,7 +297,7 @@
 	if (magic[0] == 'P' && magic[1] == 'E')
 		return IMAGE_NT_SIGNATURE;
 	magic[2]='\0';
-	fprintf(stderr,"misc/ver.c:read_ne_header:can't handle %s files.\n",magic);
+	WARN(ver,"Can't handle %s files.\n",magic);
 	return 0;
 }
 
@@ -447,7 +447,7 @@
 	resdir = pehd.OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
 	TRACE(ver,"(.,%p,%p,....)\n",typeid,resid);
 	if (!resdir.Size) {
-		fprintf(stderr,"misc/ver.c:find_pe_resource() no resource directory found in PE file.\n");
+		WARN(ver,"No resource directory found in PE file.\n");
 		return 0;
 	}
 	imagesize = pehd.OptionalHeader.SizeOfImage;
@@ -474,8 +474,10 @@
 		LZSeek32(lzfd,sections[i].PointerToRawData,SEEK_SET);
 		if (	sections[i].SizeOfRawData!=
 			LZRead32(lzfd,image+sections[i].VirtualAddress,sections[i].SizeOfRawData)
-		)
-			continue;
+		) {
+			HeapFree(GetProcessHeap(),0,image);
+			return 0;
+		}
 	}
 	resourcedir = (LPIMAGE_RESOURCE_DIRECTORY)(image+resdir.VirtualAddress);
 	xresdir = GetResDirEntryW(resourcedir,typeid,(DWORD)resourcedir,FALSE);
@@ -620,7 +622,7 @@
 			isuni = 1;
 			vffi = (VS_FIXEDFILEINFO*)(buf+0x28);
 		} else {
-			fprintf(stderr,"vffi->dwSignature is 0x%08lx, but not 0x%08lx!\n",
+			WARN(ver,"vffi->dwSignature is 0x%08lx, but not 0x%08lx!\n",
 				vffi->dwSignature,VS_FFI_SIGNATURE
 			);
 			return 0;
@@ -898,7 +900,6 @@
     return ret;
 }
 
-/* VerInstallFileA				[VERSION.7] */
 static LPBYTE
 _fetch_versioninfo(LPSTR fn,VS_FIXEDFILEINFO **vffi) {
     DWORD	alloclen;
@@ -922,7 +923,7 @@
 	    if ((*vffi)->dwSignature == 0x004f0049) /* hack to detect unicode */
 	    	*vffi = (VS_FIXEDFILEINFO*)(buf+0x28);
 	    if ((*vffi)->dwSignature != VS_FFI_SIGNATURE)
-	    	fprintf(stderr,"_fetch_versioninfo:bad VS_FIXEDFILEINFO signature 0x%08lx\n",(*vffi)->dwSignature);
+	    	WARN(ver,"Bad VS_FIXEDFILEINFO signature 0x%08lx\n",(*vffi)->dwSignature);
 	    return buf;
 	}
     }
@@ -940,9 +941,10 @@
     }
 }
 
-/* VerInstallFile32A
- */
 
+/******************************************************************************
+ * VerInstallFile32A [VERSION.7]
+ */
 DWORD WINAPI VerInstallFile32A(
 	UINT32 flags,LPCSTR srcfilename,LPCSTR destfilename,LPCSTR srcdir,
  	LPCSTR destdir,LPCSTR curdir,LPSTR tmpfile,UINT32 *tmpfilelen )
@@ -954,7 +956,7 @@
     LPBYTE	buf1,buf2;
     OFSTRUCT	ofs;
 
-    fprintf(stddeb,"VerInstallFile(%x,%s,%s,%s,%s,%s,%p,%d)\n",
+    TRACE(ver,"(%x,%s,%s,%s,%s,%s,%p,%d)\n",
 	    flags,srcfilename,destfilename,srcdir,destdir,curdir,tmpfile,*tmpfilelen
     );
     xret = 0;
@@ -1106,6 +1108,7 @@
     return xret;
 }
 
+
 /* VerInstallFileW				[VERSION.8] */
 DWORD WINAPI VerInstallFile32W(
 	UINT32 flags,LPCWSTR srcfilename,LPCWSTR destfilename,LPCWSTR srcdir,
@@ -1302,7 +1305,7 @@
 		b=_find_dataW(block,wstr,*(WORD*)block);
 		HeapFree(GetProcessHeap(),0,wstr);
 		if (!b) {
-			fprintf(stderr,"key %s not found in versionresource.\n",s);
+			WARN(ver,"key %s not found in versionresource.\n",s);
 			*buflen=0;
 			free (s);
 			return 0;
@@ -1320,7 +1323,7 @@
 		struct	dbA	*db;
 		b=_find_dataA(block,s,*(WORD*)block);
 		if (!b) {
-			fprintf(stderr,"key %s not found in versionresource.\n",s);
+			WARN(ver,"key %s not found in versionresource.\n",s);
 			*buflen=0;
 			free (s);
 			return 0;
@@ -1364,7 +1367,7 @@
 		b=_find_dataW(block,wstr,*(WORD*)block);
 		HeapFree(GetProcessHeap(),0,wstr);
 		if (!b) {
-			fprintf(stderr,"key %s not found in versionresource.\n",s);
+			WARN(ver,"key %s not found in versionresource.\n",s);
 			*buflen=0;
 			free (s);
 			return 0;
@@ -1384,7 +1387,7 @@
 		struct	dbA	*db;
 		b=_find_dataA(block,s,*(WORD*)block);
 		if (!b) {
-			fprintf(stderr,"key %s not found in versionresource.\n",subblock);
+			WARN(ver,"key %s not found in versionresource.\n",subblock);
 			*buflen=0;
 			free (s);
 			return 0;
diff --git a/misc/w32skrnl.c b/misc/w32skrnl.c
index f05cc99..df9d65a 100644
--- a/misc/w32skrnl.c
+++ b/misc/w32skrnl.c
@@ -12,10 +12,10 @@
 
 LPSTR WINAPI GetWin32sDirectory(void)
 {
-    static char *sysdir;
+    static char sysdir[0x80];
     LPSTR text;
 
-    sysdir = getenv("winsysdir");
+    GetEnvironmentVariable32A("winsysdir", sysdir, 0x80);
     if (!sysdir) return NULL;
     strcat(sysdir, "\\WIN32S");
     text = HeapAlloc(GetProcessHeap(), 0, strlen(sysdir)+1);
diff --git a/misc/win32s16.c b/misc/win32s16.c
index d602aef..fde1b28 100644
--- a/misc/win32s16.c
+++ b/misc/win32s16.c
@@ -6,13 +6,14 @@
  */
 
 #include "windows.h"
+#include "debug.h"
 #include <string.h>
 #include <stdlib.h>
 #include <stdio.h>
 
 void BootTask()
 {
-	fprintf(stderr, "BootTask(): should only be used by WIN32S.EXE.\n");
+	MSG("BootTask(): should only be used by WIN32S.EXE.\n");
 }
 
 /***********************************************************************
@@ -22,6 +23,6 @@
  */
 SEGPTR WINAPI StackLinearToSegmented(WORD w1, WORD w2)
 {
-	fprintf(stderr, "StackLinearToSegmented(), stub !\n");
+	FIXME(dll,"(%d,%d):stub.\n",w1,w2);
 	return (SEGPTR)NULL;
 }
diff --git a/misc/windebug.c b/misc/windebug.c
index 9e54dfc..5e74cf4 100644
--- a/misc/windebug.c
+++ b/misc/windebug.c
@@ -9,6 +9,7 @@
 #include <stdlib.h>
 #include "windows.h"
 #include "module.h"
+#include "debug.h"
 
 /***********************************************************************
  *           WinNotify       (WINDEBUG.3)
@@ -16,7 +17,7 @@
  */
 void WinNotify(CONTEXT *context)
 {
-	fprintf(stderr, "WinNotify(AX=%04x): stub !\n", AX_reg(context));
+	FIXME(dll, "(AX=%04x):stub.\n", AX_reg(context));
 	switch (AX_reg(context))
 	{
 		case 0x000D:
diff --git a/misc/winsock.c b/misc/winsock.c
index 79a7a10..505adfd 100644
--- a/misc/winsock.c
+++ b/misc/winsock.c
@@ -57,7 +57,7 @@
 
 #define DEBUG_SOCKADDR 0
 #define dump_sockaddr(a) \
-        fprintf(stderr, "sockaddr_in: family %d, address %s, port %d\n", \
+        DUMP("sockaddr_in: family %d, address %s, port %d\n", \
                         ((struct sockaddr_in *)a)->sin_family, \
                         inet_ntoa(((struct sockaddr_in *)a)->sin_addr), \
                         ntohs(((struct sockaddr_in *)a)->sin_port))
@@ -116,7 +116,7 @@
         for(i=0; _ws_sock_ops[i]; i++)
             if( _ws_sock_ops[i] == *optname ) break;
         if( _ws_sock_ops[i] ) *optname = _px_sock_ops[i];
-        else fprintf(stderr, "convert_sockopt() unknown optname %d\n", *optname);
+        else WARN(winsock, "Unknown optname %d\n", *optname);
         break;
      case WS_IPPROTO_TCP:
         *optname = IPPROTO_TCP;
@@ -136,7 +136,7 @@
 	    LPWSINFO pwsi = _wsi_list;
 	    while( pwsi && pwsi->tid != hTask ) pwsi = pwsi->next;
 	    if( pwsi )
-		fprintf(stderr,"loose wsi struct! pwsi=0x%08x, task=0x%04x\n", 
+		WARN(winsock,"(pwsi=0x%08x,task=0x%04x):Loose wsi struct! \n", 
 					(unsigned)pwsi, hTask );
 	    return pwsi; 
 	}
@@ -326,7 +326,7 @@
 	_WSHeap = HeapCreate(HEAP_ZERO_MEMORY, 8120, 32768);
 	if( !(_ws_stub = WS_ALLOC(0x10)) )
 	{
-	    fprintf(stderr,"Fatal: failed to create WinSock heap\n");
+	    ERR(winsock,"Fatal: failed to create WinSock heap\n");
 	    return 0;
 	}
     }
@@ -919,7 +919,7 @@
 		break;
 
 	case WS_IOW('f',125,u_long): 
-		fprintf(stderr,"Warning: WS1.1 shouldn't be using async I/O\n");
+		WARN(winsock,"Warning: WS1.1 shouldn't be using async I/O\n");
 		pwsi->err = WSAEINVAL; 
 		return SOCKET_ERROR;
 
@@ -1033,7 +1033,7 @@
 		    len, flags);
 #if DEBUG_SOCKADDR
     if( from ) dump_sockaddr(from);
-    else fprintf(stderr, "\tfrom = NULL\n");
+    else DUMP("from = NULL\n");
 #endif
 
     if( _check_ws(pwsi, pws) )
@@ -1396,7 +1396,7 @@
 
     if (errno == EPERM) /* raw socket denied */
     {
-        fprintf(stderr, "WS_SOCKET: not enough privileges\n");
+        WARN(winsock, "WS_SOCKET: not enough privileges\n");
         pwsi->err = WSAESOCKTNOSUPPORT;
     } else pwsi->err = wsaErrno();
   }
@@ -2648,7 +2648,7 @@
        /* just in case we ever get here and there are no problems */
 	case 0:			return 0;
         default:
-		fprintf(stderr, "winsock: unknown errno %d!\n", errno);
+		WARN(winsock, "Unknown errno %d!\n", errno);
 		return WSAEOPNOTSUPP;
     }
 }
@@ -2673,7 +2673,7 @@
 
 	case 0:			return 0;
         default:
-		fprintf(stderr, "winsock: unknown h_errno %d!\n", h_errno);
+		WARN(winsock,"Unknown h_errno %d!\n", h_errno);
 		return WSAEOPNOTSUPP;
     }
 }
diff --git a/misc/winsock_dns.c b/misc/winsock_dns.c
index d01b8f7..dc9b298 100644
--- a/misc/winsock_dns.c
+++ b/misc/winsock_dns.c
@@ -301,7 +301,7 @@
 		case WSMSG_ASYNC_SERVBYPORT:
 		     fixup_wsse((struct ws_servent*)buffer, p_aop->b.ptr_base); break;
 		default:
-                     if( p_aop->flags ) fprintf(stderr,"Received unknown async request!\n");
+                     if( p_aop->flags ) WARN(winsock,"Received unknown async request!\n");
                      return AOP_CONTROL_REMOVE;
             }
 	}
diff --git a/misc/wsprintf.c b/misc/wsprintf.c
index 540dc4a..fcfd589 100644
--- a/misc/wsprintf.c
+++ b/misc/wsprintf.c
@@ -23,6 +23,7 @@
 
 typedef enum
 {
+    WPR_UNKNOWN,
     WPR_CHAR,
     WPR_WCHAR,
     WPR_STRING,
@@ -108,8 +109,9 @@
     case 'x':
         res->type = WPR_HEXA;
         break;
-    default:
-        fprintf( stderr, "wvsprintf32A: unknown format '%c'\n", *p );
+    default: /* unknown format char */
+        res->type = WPR_UNKNOWN;
+        p--;  /* print format as normal char */
         break;
     }
     return (INT32)(p - format) + 1;
@@ -180,7 +182,8 @@
         res->type = WPR_HEXA;
         break;
     default:
-        fprintf( stderr, "wvsprintf32W: unknown format '%c'\n", (CHAR)*p );
+        res->type = WPR_UNKNOWN;
+        p--;  /* print format as normal char */
         break;
     }
     return (INT32)(p - format) + 1;
@@ -282,6 +285,8 @@
             else
                 cur_arg = (DWORD)VA_ARG16( args, UINT16 );
             break;
+        case WPR_UNKNOWN:
+            continue;
         }
         len = WPRINTF_GetLen( &format, &cur_arg, number, maxlen - 1 );
         if (!(format.flags & WPRINTF_LEFTALIGN))
@@ -317,6 +322,8 @@
             if (len) memcpy( p, number, len );
             p += len;
             break;
+        case WPR_UNKNOWN:
+            continue;
         }
         if (format.flags & WPRINTF_LEFTALIGN)
             for (i = format.precision; i < format.width; i++, maxlen--)
@@ -389,6 +396,8 @@
             p += len;
             (void)va_arg( args, INT32 ); /* Go to the next arg */
             break;
+        case WPR_UNKNOWN:
+            continue;
         }
         if (format.flags & WPRINTF_LEFTALIGN)
             for (i = format.precision; i < format.width; i++, maxlen--)
@@ -461,6 +470,8 @@
             for (i = 0; i < len; i++) *p++ = (WCHAR)number[i];
             (void)va_arg( args, INT32 ); /* Go to the next arg */
             break;
+        case WPR_UNKNOWN:
+            continue;
         }
         if (format.flags & WPRINTF_LEFTALIGN)
             for (i = format.precision; i < format.width; i++, maxlen--)
diff --git a/misc/xmalloc.c b/misc/xmalloc.c
index a228f71..8ff7b38 100644
--- a/misc/xmalloc.c
+++ b/misc/xmalloc.c
@@ -17,6 +17,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include "xmalloc.h"
+#include "debug.h"
 
 void *xmalloc( int size )
 {
@@ -25,7 +26,7 @@
     res = malloc (size ? size : 1);
     if (res == NULL)
     {
-        fprintf (stderr, "Virtual memory exhausted.\n");
+        MSG("Virtual memory exhausted.\n");
         exit (1);
     }
     return res;
@@ -37,7 +38,7 @@
     void *res = realloc (ptr, size);
     if ((res == NULL) && size)
     {
-        fprintf (stderr, "Virtual memory exhausted.\n");
+        MSG("Virtual memory exhausted.\n");
         exit (1);
     }
     return res;
@@ -49,7 +50,7 @@
     char *res = strdup( str );
     if (!res)
     {
-        fprintf (stderr, "Virtual memory exhausted.\n");
+        MSG("Virtual memory exhausted.\n");
         exit (1);
     }
     return res;
diff --git a/miscemu/instr.c b/miscemu/instr.c
index 46cd421..1b6570d 100644
--- a/miscemu/instr.c
+++ b/miscemu/instr.c
@@ -9,14 +9,19 @@
 #include "ldt.h"
 #include "miscemu.h"
 #include "sig_context.h"
+#include "debug.h"
 
 
 #define STACK_sig(context) \
-   ((GET_SEL_FLAGS(SS_sig(context)) & LDT_FLAGS_32BIT) ? \
-                   ESP_sig(context) : SP_sig(context))
+   (IS_SELECTOR_32BIT(SS_sig(context)) ? ESP_sig(context) : SP_sig(context))
+
+#define MAKE_PTR(seg,off) \
+   (IS_SELECTOR_SYSTEM(seg) ? (void *)(off) : PTR_SEG_OFF_TO_LIN(seg,off))
 
 #define STACK_PTR(context) \
-    (PTR_SEG_OFF_TO_LIN(SS_sig(context),STACK_sig(context)))
+   (IS_SELECTOR_SYSTEM(SS_sig(context)) ? (void *)ESP_sig(context) : \
+    (PTR_SEG_OFF_TO_LIN(SS_sig(context),STACK_sig(context))))
+
 
 /***********************************************************************
  *           INSTR_ReplaceSelector
@@ -191,6 +196,7 @@
     if (segprefix != -1) seg = segprefix;
 
     /* Make sure the segment and offset are valid */
+    if (IS_SELECTOR_SYSTEM(seg)) return (BYTE *)(base + (index << ss));
     if (((seg & 7) != 7) || IS_SELECTOR_FREE(seg)) return NULL;
     if (GET_SEL_LIMIT(seg) < (base + (index << ss))) return NULL;
     return (BYTE *)PTR_SEG_OFF_TO_LIN( seg, (base + (index << ss)) );
@@ -291,8 +297,8 @@
     int prefix, segprefix, prefixlen, len, repX, long_op, long_addr;
     BYTE *instr;
 
-    long_op = long_addr = (GET_SEL_FLAGS(CS_sig(context)) & LDT_FLAGS_32BIT) != 0;
-    instr = (BYTE *) PTR_SEG_OFF_TO_LIN( CS_sig(context), EIP_sig(context) );
+    long_op = long_addr = IS_SELECTOR_32BIT(CS_sig(context));
+    instr = (BYTE *)MAKE_PTR(CS_sig(context),EIP_sig(context));
 
     /* First handle any possible prefix */
 
@@ -456,14 +462,14 @@
 		  void *data;
 		  if (outp)
                   {
-		      data = PTR_SEG_OFF_TO_LIN (seg,
+		      data = MAKE_PTR(seg,
                                long_addr ? ESI_sig(context) : SI_sig(context));
 		      if (long_addr) ESI_sig(context) += step;
 		      else SI_sig(context) += step;
                   }
 		  else
                   {
-		      data = PTR_SEG_OFF_TO_LIN (seg,
+		      data = MAKE_PTR(seg,
                                long_addr ? EDI_sig(context) : DI_sig(context));
 		      if (long_addr) EDI_sig(context) += step;
 		      else DI_sig(context) += step;
@@ -554,7 +560,7 @@
         case 0xcd: /* int <XX> */
             if (long_op)
             {
-                fprintf(stderr, "int xx from 32-bit code is not supported.\n");
+                ERR(int, "int xx from 32-bit code is not supported.\n");
                 break;  /* Unable to emulate it */
             }
             else
@@ -643,7 +649,7 @@
   	    EIP_sig(context) += prefixlen + 1;
             return TRUE;
     }
-    fprintf(stderr, "Unexpected Windows program segfault"
+    MSG("Unexpected Windows program segfault"
                     " - opcode = %x\n", *instr);
     return FALSE;  /* Unable to emulate it */
 }
diff --git a/miscemu/main.c b/miscemu/main.c
index 6110790..e7c6e9f 100644
--- a/miscemu/main.c
+++ b/miscemu/main.c
@@ -10,6 +10,7 @@
 #include "miscemu.h"
 #include "module.h"
 #include "options.h"
+#include "debug.h"
 
 
 /***********************************************************************
@@ -72,7 +73,7 @@
     {
         if (!BUILTIN_ParseDLLOptions( Options.dllFlags ))
         {
-            fprintf( stderr, "%s: Syntax: -dll +xxx,... or -dll -xxx,...\n",
+            MSG("%s: Syntax: -dll +xxx,... or -dll -xxx,...\n",
                      argv[0] );
             BUILTIN_PrintDLLs();
             exit(1);
@@ -92,13 +93,13 @@
     {
         if ((handle = WinExec32( argv[i], SW_SHOWNORMAL )) < 32)
         {
-            fprintf(stderr, "wine: can't exec '%s': ", argv[i]);
+            MSG("wine: can't exec '%s': ", argv[i]);
             switch (handle)
             {
-            case 2: fprintf( stderr, "file not found\n" ); break;
-            case 11: fprintf( stderr, "invalid exe file\n" ); break;
-            case 21: fprintf( stderr, "win32 executable\n" ); break;
-            default: fprintf( stderr, "error=%d\n", handle ); break;
+            case 2: MSG("file not found\n" ); break;
+            case 11: MSG("invalid exe file\n" ); break;
+            case 21: MSG("win32 executable\n" ); break; /* FIXME: Obsolete? */
+            default: MSG("error=%d\n", handle ); break;
             }
             return 1;
         }
@@ -113,13 +114,13 @@
 
     if (!GetNumTasks())
     {
-        fprintf( stderr, "wine: no executable file found.\n" );
+        MSG("wine: no executable file found.\n" );
         return 0;
     }
 
     if (Options.debug) DEBUG_AddModuleBreakpoints();
 
     Yield16();  /* Start the first task */
-    fprintf( stderr, "WinMain: Should never happen: returned from Yield()\n" );
+    MSG("WinMain: Should never happen: returned from Yield16()\n" );
     return 0;
 }
diff --git a/msdos/dosmem.c b/msdos/dosmem.c
index 4482cf9..6048ec5 100644
--- a/msdos/dosmem.c
+++ b/msdos/dosmem.c
@@ -208,7 +208,7 @@
                                   PAGE_EXECUTE_READWRITE );
     if (!DOSMEM_dosmem)
     {
-        fprintf( stderr, "Could not allocate DOS memory.\n" );
+        WARN(dosmem, "Could not allocate DOS memory.\n" );
         return FALSE;
     }
     DOSMEM_BiosSeg = GLOBAL_CreateBlock(GMEM_FIXED,DOSMEM_dosmem+0x400,0x100,
@@ -219,26 +219,6 @@
     return TRUE;
 }
 
-void DOSMEM_InitExports(HMODULE16 hKernel)
-{
-#define SET_ENTRY_POINT(num,addr) \
-    MODULE_SetEntryPoint( hKernel, (num), GLOBAL_CreateBlock( GMEM_FIXED, \
-                                  DOSMEM_dosmem+(addr), 0x10000, hKernel, \
-                                  FALSE, FALSE, FALSE, NULL ))
-
-    SET_ENTRY_POINT( 183, 0x00000 );  /* KERNEL.183: __0000H */
-    SET_ENTRY_POINT( 174, 0xa0000 );  /* KERNEL.174: __A000H */
-    SET_ENTRY_POINT( 181, 0xb0000 );  /* KERNEL.181: __B000H */
-    SET_ENTRY_POINT( 182, 0xb8000 );  /* KERNEL.182: __B800H */
-    SET_ENTRY_POINT( 195, 0xc0000 );  /* KERNEL.195: __C000H */
-    SET_ENTRY_POINT( 179, 0xd0000 );  /* KERNEL.179: __D000H */
-    SET_ENTRY_POINT( 190, 0xe0000 );  /* KERNEL.190: __E000H */
-    SET_ENTRY_POINT( 173, 0xf0000 );  /* KERNEL.173: __ROMBIOS */
-    SET_ENTRY_POINT( 194, 0xf0000 );  /* KERNEL.194: __F000H */
-    MODULE_SetEntryPoint(hKernel, 193,DOSMEM_BiosSeg); /* KERNEL.193: __0040H */
-
-#undef SET_ENTRY_POINT
-}
 
 /***********************************************************************
  *           DOSMEM_Tick
@@ -272,7 +252,7 @@
 #ifdef __DOSMEM_DEBUG__
        if( (dm->size & DM_BLOCK_DEBUG) != DM_BLOCK_DEBUG )
        {
-	    fprintf(stderr,"DOSMEM_GetBlock: MCB overrun! [prev = 0x%08x]\n", 4 + (UINT32)prev);
+	    WARN(dosmem,"MCB overrun! [prev = 0x%08x]\n", 4 + (UINT32)prev);
 	    return NULL;
        }
        prev = dm;
diff --git a/msdos/dpmi.c b/msdos/dpmi.c
index 5aea153..a452592 100644
--- a/msdos/dpmi.c
+++ b/msdos/dpmi.c
@@ -16,10 +16,14 @@
 #include "msdos.h"
 #include "toolhelp.h"
 #include "debug.h"
+#include "selectors.h"
+#include "thread.h"
+#include "stackframe.h"
+#include "callback.h"
 
 #define DOS_GET_DRIVE(reg) ((reg) ? (reg) - 1 : DRIVE_GetCurrentDrive())
 
-void CreateBPB(int drive, BYTE *data);  /* defined in int21.c */
+void CreateBPB(int drive, BYTE *data, BOOL16 limited);  /* defined in int21.c */
 
 
 /* Structure for real-mode callbacks */
@@ -46,6 +50,14 @@
 
 
 
+typedef struct tagRMCB {
+    DWORD address;
+    struct tagRMCB *next;
+
+} RMCB;
+
+static RMCB *FirstRMCB = NULL;
+
 /**********************************************************************
  *	    INT_GetRealModeContext
  */
@@ -189,7 +201,7 @@
                             setword(&dataptr[2], 0x02); /* removable */
                             setword(&dataptr[4], 80); /* # of cylinders */
                         }
-                        CreateBPB(drive, &dataptr[7]);
+                        CreateBPB(drive, &dataptr[7], FALSE);
                         break;
                     default:
                         SET_CFLAG(context);
@@ -223,6 +235,130 @@
 }
 
 
+static void CallRMProcFar( CONTEXT *context )
+{
+    REALMODECALL *p = (REALMODECALL *)PTR_SEG_OFF_TO_LIN( ES_reg(context), DI_reg(context) );
+    CONTEXT context16;
+    THDB *thdb = THREAD_Current();
+    WORD argsize, sel;
+    LPVOID addr;
+    SEGPTR seg_addr;
+
+    TRACE(int31, "RealModeCall: EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx\n",
+	p->eax, p->ebx, p->ecx, p->edx);
+    TRACE(int31, "              ESI=%08lx EDI=%08lx ES=%04x DS=%04x CS:IP=%04x:%04x, %d WORD arguments\n",
+	p->esi, p->edi, p->es, p->ds, p->cs, p->ip, CX_reg(context) );
+
+    if (!(p->cs) && !(p->ip)) { /* remove this check
+                                   if Int21/6501 case map function
+                                   has been implemented */
+	SET_CFLAG(context);
+	return;
+    }
+    INT_GetRealModeContext(p, &context16);
+
+    addr = DOSMEM_MapRealToLinear(MAKELONG(p->ip, p->cs));
+    sel = SELECTOR_AllocBlock( addr, 0x10000, SEGMENT_CODE, FALSE, FALSE );
+    seg_addr = PTR_SEG_OFF_TO_SEGPTR( sel, 0 );
+
+    CS_reg(&context16) = HIWORD(seg_addr);
+    IP_reg(&context16) = LOWORD(seg_addr);
+    EBP_reg(&context16) = OFFSETOF( thdb->cur_stack )
+                               + (WORD)&((STACK16FRAME*)0)->bp;
+
+    argsize = CX_reg(context)*sizeof(WORD);
+    memcpy( ((LPBYTE)THREAD_STACK16(thdb))-argsize,
+    (LPBYTE)PTR_SEG_OFF_TO_LIN(SS_reg(context), SP_reg(context))+6, argsize );
+
+    Callbacks->CallRegisterShortProc(&context16, argsize);
+
+    UnMapLS(seg_addr);
+    INT_SetRealModeContext(p, &context16);
+}
+
+
+void WINAPI RMCallbackProc( FARPROC16 pmProc, REALMODECALL *rmc )
+{
+    CONTEXT ctx;
+    INT_GetRealModeContext(rmc, &ctx);
+    Callbacks->CallRegisterShortProc(&ctx, 0);
+}
+
+
+static void AllocRMCB( CONTEXT *context )
+{
+    RMCB *NewRMCB = HeapAlloc(GetProcessHeap(), 0, sizeof(RMCB));
+    REALMODECALL *p = (REALMODECALL *)PTR_SEG_OFF_TO_LIN( ES_reg(context), DI_reg(context) );
+    UINT16 uParagraph;
+
+    FIXME(int31, "EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx\n", p->eax, p->ebx, p->ecx, p->edx);
+    FIXME(int31, "           ESI=%08lx EDI=%08lx ES=%04x DS=%04x CS:IP=%04x:%04x\n", p->esi, p->edi, p->es, p->ds, p->cs, p->ip);
+    FIXME(int31, "           Function to call: %04x:%04x\n",
+         (WORD)DS_reg(context), SI_reg(context) );
+
+    if (NewRMCB)
+    {
+	LPVOID RMCBmem = DOSMEM_GetBlock(20, &uParagraph);
+	LPBYTE p = RMCBmem;
+
+	*p++ = 0x68; /* pushl */
+	*(FARPROC16 *)p =
+	PTR_SEG_OFF_TO_LIN(ES_reg(context), SI_reg(context)); /* pmode proc to call */
+	p+=4;
+	*p++ = 0x68; /* pushl */
+	*(LPVOID *)p =
+	PTR_SEG_OFF_TO_LIN(ES_reg(context), DI_reg(context));
+	p+=4;
+	*p++ = 0x9a; /* lcall */
+	*(FARPROC16 *)p = (FARPROC16)RMCallbackProc; /* FIXME ? */
+	p+=4;
+	GET_CS(*(WORD *)p);
+	p+=2;
+	*p++=0xc3; /* retf */
+	NewRMCB->address = MAKELONG(0, uParagraph);
+	NewRMCB->next = FirstRMCB;
+	FirstRMCB = NewRMCB;
+	CX_reg(context) = uParagraph;
+	DX_reg(context) = 0;
+    }
+    else
+    {
+	AX_reg(context) = 0x8015; /* callback unavailable */
+	SET_CFLAG(context);
+    }
+}
+
+
+static void FreeRMCB( CONTEXT *context )
+{
+    RMCB *CurrRMCB = FirstRMCB;
+    RMCB *PrevRMCB = NULL;
+
+    FIXME(int31, "callback address: %04x:%04x\n",
+          CX_reg(context), DX_reg(context));
+
+    while (CurrRMCB && (CurrRMCB->address != MAKELONG(DX_reg(context), CX_reg(context))))
+    {
+	PrevRMCB = CurrRMCB;
+	CurrRMCB = CurrRMCB->next;
+    }
+    if (CurrRMCB)
+    {
+	if (PrevRMCB)
+	PrevRMCB->next = CurrRMCB->next;
+	    else
+	FirstRMCB = CurrRMCB->next;
+	DOSMEM_FreeBlock(DOSMEM_MapRealToLinear(CurrRMCB->address));
+	HeapFree(GetProcessHeap(), 0, CurrRMCB);
+    }
+    else
+    {
+	AX_reg(context) = 0x8024; /* invalid callback address */
+	SET_CFLAG(context);
+    }
+}
+
+
 /**********************************************************************
  *	    INT_Int31Handler
  *
@@ -280,7 +416,7 @@
                 break;
             }
             if (entryPoint) 
-                AX_reg(context) = LOWORD(MODULE_GetEntryPoint( 
+                AX_reg(context) = LOWORD(NE_GetEntryPoint( 
                                                  GetModuleHandle16( "KERNEL" ),
                                                  entryPoint ));
         }
@@ -382,15 +518,8 @@
         break;
 
     case 0x0301:  /* Call real mode procedure with far return */
-        {
-            REALMODECALL *p = (REALMODECALL *)PTR_SEG_OFF_TO_LIN( ES_reg(context), DI_reg(context) );
-            FIXME(int31, "RealModeCall: EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx\n",
-		p->eax, p->ebx, p->ecx, p->edx);
-            FIXME(int31, "              ESI=%08lx EDI=%08lx ES=%04x DS=%04x CS:IP=%04x:%04x\n",
-		p->esi, p->edi, p->es, p->ds, p->cs, p->ip );
-            SET_CFLAG(context);
-        }
-        break;
+	CallRMProcFar( context );
+	break;
 
     case 0x0302:  /* Call real mode procedure with interrupt return */
         {
@@ -402,22 +531,11 @@
         break;
 
     case 0x0303:  /* Allocate Real Mode Callback Address */
-        {
-            REALMODECALL *p = (REALMODECALL *)PTR_SEG_OFF_TO_LIN( ES_reg(context), DI_reg(context) );
-            FIXME(int31, "AllocRMCB: EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx\n", p->eax, p->ebx, p->ecx, p->edx);
-	    FIXME(int31, "           ESI=%08lx EDI=%08lx ES=%04x DS=%04x CS:IP=%04x:%04x\n", p->esi, p->edi, p->es, p->ds, p->cs, p->ip);
-	    FIXME(int31, "           Function to call: %04x:%04x\n",
-		(WORD)DS_reg(context), SI_reg(context) );
-            SET_CFLAG(context);
-        }
-        break;
+	AllocRMCB( context );
+	break;
 
     case 0x0304:  /* Free Real Mode Callback Address */
-	{
-	    FIXME(int31, "FreeRMCB: callback address: %04x:%04x\n",
-		  CX_reg(context), DX_reg(context));
-	    SET_CFLAG(context);
-	}
+	FreeRMCB( context );
 	break;
 
     case 0x0400:  /* Get DPMI version */
diff --git a/msdos/int13.c b/msdos/int13.c
index 761b2ad..68719d2 100644
--- a/msdos/int13.c
+++ b/msdos/int13.c
@@ -67,7 +67,7 @@
 
                         if ( (floppy_fd = DRIVE_OpenDevice( drive_nr, O_NONBLOCK)) == -1)
                         {
-                                fprintf(stderr, "INT 0x13 (GET DRIVE PARAMETERS): can't determine floppy geometry !\n");
+                                WARN(int, "(GET DRIVE PARAMETERS): Can't determine floppy geometry !\n");
                                 BX_reg(context) = 0;
                                 CX_reg(context) = 0;
                                 DH_reg(context) = 0;
diff --git a/msdos/int21.c b/msdos/int21.c
index 8a7c0a2..5ccf18f 100644
--- a/msdos/int21.c
+++ b/msdos/int21.c
@@ -83,7 +83,7 @@
 {
     if (!(DosHeapHandle = GlobalAlloc16(GMEM_FIXED,sizeof(struct DosHeap))))
     {
-        fprintf( stderr, "INT21_Init: Out of memory\n");
+        WARN(int21, "Out of memory\n");
         return FALSE;
     }
     heap = (struct DosHeap *) GlobalLock16(DosHeapHandle);
@@ -100,7 +100,8 @@
 }
 
 
-void CreateBPB(int drive, BYTE *data)
+void CreateBPB(int drive, BYTE *data, BOOL16 limited)
+/* limited == TRUE is used with INT 0x21/0x440d */
 {
 	if (drive > 1) {
 		setword(data, 512);
@@ -114,9 +115,11 @@
 		setword(&data[0x0d], 56);
 		setword(&data[0x0f], 2);
 		setword(&data[0x11], 0);
-		setword(&data[0x1f], 800);
-		data[0x21] = 5;
-		setword(&data[0x22], 1);
+		if (!limited) {
+		    setword(&data[0x1f], 800);
+		    data[0x21] = 5;
+		    setword(&data[0x22], 1);
+		}
 	} else { /* 1.44mb */
 		setword(data, 512);
 		data[2] = 2;
@@ -129,9 +132,11 @@
 		setword(&data[0x0d], 18);
 		setword(&data[0x0f], 2);
 		setword(&data[0x11], 0);
-		setword(&data[0x1f], 80);
-		data[0x21] = 7;
-		setword(&data[0x22], 2);
+		if (!limited) {
+		    setword(&data[0x1f], 80);
+		    data[0x21] = 7;
+		    setword(&data[0x22], 2);
+		}
 	}	
 }
 
@@ -215,6 +220,8 @@
      * bit 6 - file has NOT been written..FIXME: correct?
      * bit 8 - generate int24 if no diskspace on write/ read past end of file
      * bit 11 - media not removable
+     * bit 14 - don't set file date/time on closing
+     * bit 15 - file is remote
      */
     RESET_CFLAG(context);
 }
@@ -244,7 +251,7 @@
 
 		case 0x60: /* get device parameters */
 			   /* used by w4wgrp's winfile */
-			memset(dataptr, 0, 0x26);
+			memset(dataptr, 0, 0x20); /* DOS 6.22 uses 0x20 bytes */
 			dataptr[0] = 0x04;
 			dataptr[6] = 0; /* media type */
 			if (drive > 1) 
@@ -259,7 +266,7 @@
 				setword(&dataptr[2], 0x02); /* removable */
 				setword(&dataptr[4], 80); /* # of cylinders */
 			}
-			CreateBPB(drive, &dataptr[7]);			
+			CreateBPB(drive, &dataptr[7], TRUE);
 			RESET_CFLAG(context);
 			break;
 
@@ -589,7 +596,7 @@
     }
     if ((int)dta->count + count > 0xffff)
     {
-        fprintf( stderr, "Too many directory entries in %s\n", dta->unixPath );
+        WARN(int21, "Too many directory entries in %s\n", dta->unixPath );
         HeapFree( GetProcessHeap(), 0, dta->unixPath );
         dta->unixPath = NULL;
         return 0;
@@ -1632,6 +1639,7 @@
 	    *(WORD*)(dataptr+1) = 41;
 	    *(WORD*)(dataptr+3) = WINE_LanguageId;
 	    *(WORD*)(dataptr+5) = CodePage;
+	    *(DWORD*)(dataptr+0x19) = NULL; /* FIXME: ptr to case map routine */
 	    break;
 	case 0x06:
 	    TRACE(int21,"\tget pointer to collating sequence table\n");
diff --git a/msdos/int2f.c b/msdos/int2f.c
index c2d2564..fb8cf67 100644
--- a/msdos/int2f.c
+++ b/msdos/int2f.c
@@ -133,14 +133,14 @@
 	break;
 
     case 0x84:  /* Get device API entry point */
-        addr = (DWORD)MODULE_GetEntryPoint( GetModuleHandle16("WPROCS"),
-                                            VXD_BASE + BX_reg(context) );
+        addr = (DWORD)NE_GetEntryPoint( GetModuleHandle16("WPROCS"),
+                                        VXD_BASE + BX_reg(context) );
         if (!addr)  /* not supported */
         {
-	    fprintf( stderr,"Application attempted to access VxD %04x\n",
+	    WARN(int,"Application attempted to access VxD %04x\n",
                      BX_reg(context) );
-	    fprintf( stderr,"This device is not known to Wine.");
-	    fprintf( stderr,"Expect a failure now\n");
+	    WARN(int,"This device is not known to Wine.");
+	    WARN(int,"Expect a failure now\n");
         }
 	ES_reg(context) = SELECTOROF(addr);
 	DI_reg(context) = OFFSETOF(addr);
@@ -217,7 +217,7 @@
             break;
 
         default:
-            fprintf(stderr, "Unimplemented MSCDEX function 0x%02.2X.\n", AL_reg(context));
+            FIXME(int, "Unimplemented MSCDEX function 0x%02.2X.\n", AL_reg(context));
             break;
     }
 }
diff --git a/msdos/ioports.c b/msdos/ioports.c
index b4924bd..4233fff 100644
--- a/msdos/ioports.c
+++ b/msdos/ioports.c
@@ -236,7 +236,7 @@
             b = cmosimage[cmosaddress & 0x3f];
             break;
         default:
-            fprintf( stderr, "Direct I/O read attempted from port %x\n", port);
+            WARN( int, "Direct I/O read attempted from port %x\n", port);
             b = 0xff;
             break;
         }
@@ -274,7 +274,7 @@
                 case 2: outw( LOWORD(value), port ); break;
                 case 4: outl( value, port ); break;
                 default:
-                    fprintf( stderr, "IO_outport: invalid count %d\n", count);
+                    WARN(int, "Invalid count %d\n", count);
             }
             iopl(0);
             return;
@@ -295,8 +295,7 @@
             cmosimage[cmosaddress & 0x3f] = b;
             break;
         default:
-            fprintf( stderr, "Direct I/O write attempted "
-                     "to port %x\n", port );
+            WARN(int, "Direct I/O write attempted to port %x\n", port );
             break;
         }
 	port++;
diff --git a/msdos/vxd.c b/msdos/vxd.c
index bc922e3..60a120d 100644
--- a/msdos/vxd.c
+++ b/msdos/vxd.c
@@ -12,7 +12,7 @@
 
 
 #define VXD_BARF(context,name) \
-    fprintf( stderr, "vxd %s: unknown/not implemented parameters:\n" \
+    DUMP( "vxd %s: unknown/not implemented parameters:\n" \
                      "vxd %s: AX %04x, BX %04x, CX %04x, DX %04x, " \
                      "SI %04x, DI %04x, DS %04x, ES %04x\n", \
              (name), (name), AX_reg(context), BX_reg(context), \
diff --git a/multimedia/audio.c b/multimedia/audio.c
index 780e035..c192a5c 100644
--- a/multimedia/audio.c
+++ b/multimedia/audio.c
@@ -1541,7 +1541,8 @@
 			lpWIHdr->dwBufferLength);
 		if (bytesRead==-1)
 			perror("read from audio device");
-		fprintf(stderr,"bytesread = %d (%ld)\n",bytesRead,lpWIHdr->dwBufferLength);
+		TRACE(mciwave,"bytesread=%d (%ld)\n",
+                    bytesRead,lpWIHdr->dwBufferLength);
 		lpWIHdr->dwBytesRecorded = bytesRead;
 		WInDev[wDevID].dwTotalRecorded += lpWIHdr->dwBytesRecorded;
 		lpWIHdr->dwFlags &= ~WHDR_INQUEUE;
@@ -1804,7 +1805,7 @@
 DWORD wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser, 
 					DWORD dwParam1, DWORD dwParam2)
 {
-	fprintf(stderr,"wodMessage(%u, %04X, %08lX, %08lX, %08lX);\n",
+	FIXME(mciwave,"(%u, %04X, %08lX, %08lX, %08lX):stub\n",
 			wDevID, wMsg, dwUser, dwParam1, dwParam2);
 	return MMSYSERR_NOTENABLED;
 }
@@ -1815,7 +1816,7 @@
 DWORD widMessage(WORD wDevID, WORD wMsg, DWORD dwUser, 
 					DWORD dwParam1, DWORD dwParam2)
 {
-	fprintf(stderr,"widMessage(%u, %04X, %08lX, %08lX, %08lX);\n",
+	FIXME(mciwave,"(%u, %04X, %08lX, %08lX, %08lX):stub\n",
 			wDevID, wMsg, dwUser, dwParam1, dwParam2);
 	return MMSYSERR_NOTENABLED;
 }
diff --git a/multimedia/dsound.c b/multimedia/dsound.c
index c541d27..4d4ac1c 100644
--- a/multimedia/dsound.c
+++ b/multimedia/dsound.c
@@ -103,7 +103,7 @@
 	char xbuf[50];
 
 	WINE_StringFromCLSID(riid,xbuf);
-	fprintf(stderr,"IDirectSound(%p)->QueryInterface(%s,%p)\n",this,xbuf,ppobj);
+	TRACE(dsound,"(%p,%s,%p)\n",this,xbuf,ppobj);
 	return E_FAIL;
 }
 
@@ -134,9 +134,10 @@
 	int	i;
 
 	if (TRACE_ON(dsound)) {
-	    fprintf(stderr,"IDirectSoundNotify(%p)->SetNotificationPositions(0x%08lx,%p)\n",this,howmuch,notify);
+	    TRACE(dsound,"(%p,0x%08lx,%p)\n",this,howmuch,notify);
 	    for (i=0;i<howmuch;i++)
-		    fprintf(stderr,"	notify at %ld to 0x%08lx\n",notify[i].dwOffset,(DWORD)notify[i].hEventNotify);
+		    TRACE(dsound,"notify at %ld to 0x%08lx\n",
+                            notify[i].dwOffset,(DWORD)notify[i].hEventNotify);
 	}
 	this->dsb->notifies = HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,this->dsb->notifies,(this->dsb->nrofnotifies+howmuch)*sizeof(DSBPOSITIONNOTIFY));
 	memcpy(	this->dsb->notifies+this->dsb->nrofnotifies,
@@ -163,10 +164,9 @@
 ) {
 
 	memcpy(&(this->wfx),wfex,sizeof(this->wfx));
-	TRACE(dsound,"(%p)->SetFormat(%p)\n",
-		       this,wfex);
-	TRACE(dsound,"	[formattag=0x%04x,chans=%d,samplerate=%ld"
-		   "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d]\n",
+	TRACE(dsound,"(%p,%p)\n", this,wfex);
+	TRACE(dsound,"(formattag=0x%04x,chans=%d,samplerate=%ld"
+		   "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
 		   wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
 		   wfex->nAvgBytesPerSec, wfex->nBlockAlign, 
 		   wfex->wBitsPerSample, wfex->cbSize);
@@ -177,7 +177,7 @@
 static HRESULT WINAPI IDirectSoundBuffer_SetVolume(
 	LPDIRECTSOUNDBUFFER this,LONG vol
 ) {
-	fprintf(stderr,"(%p)->SetVolume(%ld)\n",this,vol);
+	TRACE(dsound,"(%p,%ld)\n",this,vol);
 	this->volume = vol;
 	this->volfac = ((double)vol+10000.0)/10000.0;
 	return 0;
@@ -186,7 +186,7 @@
 static HRESULT WINAPI IDirectSoundBuffer_GetVolume(
 	LPDIRECTSOUNDBUFFER this,LPLONG vol
 ) {
-	TRACE(dsound,"(%p)->GetVolume(%p)\n",this,vol);
+	TRACE(dsound,"(%p,%p)\n",this,vol);
 	*vol = this->volume;
 	return 0;
 }
@@ -194,7 +194,7 @@
 static HRESULT WINAPI IDirectSoundBuffer_SetFrequency(
 	LPDIRECTSOUNDBUFFER this,DWORD freq
 ) {
-	TRACE(dsound,"(%p)->SetFrequency(%ld)\n",this,freq);
+	TRACE(dsound,"(%p,%ld)\n",this,freq);
 	this->wfx.nSamplesPerSec = freq;
 	this->wfx.nAvgBytesPerSec = freq*this->wfx.nChannels*(this->wfx.wBitsPerSample/8);
 	return 0;
@@ -203,7 +203,7 @@
 static HRESULT WINAPI IDirectSoundBuffer_Play(
 	LPDIRECTSOUNDBUFFER this,DWORD reserved1,DWORD reserved2,DWORD flags
 ) {
-	TRACE(dsound,"(%p)->Play(%08lx,%08lx,%08lx)\n",
+	TRACE(dsound,"(%p,%08lx,%08lx,%08lx)\n",
 		this,reserved1,reserved2,flags
 	);
 	this->playpos = 0;
@@ -213,7 +213,7 @@
 }
 
 static HRESULT WINAPI IDirectSoundBuffer_Stop(LPDIRECTSOUNDBUFFER this) {
-	TRACE(dsound,"(%p)->Stop()\n",this);
+	TRACE(dsound,"(%p)\n",this);
 	this->playing = 0;
 	this->writepos = 0; /* hmm */
 	return 0;
@@ -247,7 +247,7 @@
 static HRESULT WINAPI IDirectSoundBuffer_GetCurrentPosition(
 	LPDIRECTSOUNDBUFFER this,LPDWORD playpos,LPDWORD writepos
 ) {
-	TRACE(dsound,"(%p)->GetCurrentPosition(%p,%p)\n",this,playpos,writepos);
+	TRACE(dsound,"(%p,%p,%p)\n",this,playpos,writepos);
 	if (playpos) *playpos = this->playpos;
 	if (writepos) *writepos = this->writepos;
 	return 0;
@@ -256,7 +256,7 @@
 static HRESULT WINAPI IDirectSoundBuffer_GetStatus(
 	LPDIRECTSOUNDBUFFER this,LPDWORD status
 ) {
-	TRACE(dsound,"(%p)->GetStatus(%p)\n",this,status);
+	TRACE(dsound,"(%p,%p)\n",this,status);
 	*status = 0;
 	if (this->playing)
 		*status |= DSBSTATUS_PLAYING;
@@ -268,7 +268,7 @@
 static HRESULT WINAPI IDirectSoundBuffer_GetFormat(
 	LPDIRECTSOUNDBUFFER this,LPWAVEFORMATEX lpwf,DWORD wfsize,LPDWORD wfwritten
 ) {
-	TRACE(dsound,"(%p)->GetFormat(%p,%ld,%p)\n",this,lpwf,wfsize,wfwritten);
+	TRACE(dsound,"(%p,%p,%ld,%p)\n",this,lpwf,wfsize,wfwritten);
 	if (wfsize>sizeof(this->wfx)) wfsize = sizeof(this->wfx);
 	memcpy(lpwf,&(this->wfx),wfsize);
 	if (wfwritten) *wfwritten = wfsize;
@@ -279,7 +279,7 @@
 	LPDIRECTSOUNDBUFFER this,DWORD writecursor,DWORD writebytes,LPVOID lplpaudioptr1,LPDWORD audiobytes1,LPVOID lplpaudioptr2,LPDWORD audiobytes2,DWORD flags
 ) {
 
-	TRACE(dsound,"(%p)->Lock(%ld,%ld,%p,%p,%p,%p,0x%08lx)\n",
+	TRACE(dsound,"(%p,%ld,%ld,%p,%p,%p,%p,0x%08lx)\n",
 		this,
 		writecursor,
 		writebytes,
@@ -317,7 +317,7 @@
 static HRESULT WINAPI IDirectSoundBuffer_SetCurrentPosition(
 	LPDIRECTSOUNDBUFFER this,DWORD newpos
 ) {
-	TRACE(dsound,"(%p)->SetCurrentPosition(%ld)\n",this,newpos);
+	TRACE(dsound,"(%p,%ld)\n",this,newpos);
 	this->playpos = newpos;
 	return 0;
 }
@@ -325,7 +325,7 @@
 static HRESULT WINAPI IDirectSoundBuffer_SetPan(
 	LPDIRECTSOUNDBUFFER this,LONG newpan
 ) {
-	TRACE(dsound,"(%p)->SetPan(%ld)\n",this,newpan);
+	TRACE(dsound,"(%p,%ld)\n",this,newpan);
 	this->pan = newpan;
 	return 0;
 }
@@ -333,7 +333,7 @@
 static HRESULT WINAPI IDirectSoundBuffer_GetPan(
 	LPDIRECTSOUNDBUFFER this,LPLONG pan
 ) {
-	TRACE(dsound,"(%p)->GetPan(%p)\n",this,pan);
+	TRACE(dsound,"(%p,%p)\n",this,pan);
 	*pan = this->pan;
 	return 0;
 }
@@ -341,18 +341,14 @@
 static HRESULT WINAPI IDirectSoundBuffer_Unlock(
 	LPDIRECTSOUNDBUFFER this,LPVOID p1,DWORD x1,LPVOID p2,DWORD x2
 ) {
-	TRACE(dsound,"(%p)->Unlock(%p,%ld,%p,%ld)\n",
-		this,p1,x1,p2,x2
-	);
+	FIXME(dsound,"(%p,%p,%ld,%p,%ld):stub\n", this,p1,x1,p2,x2);
 	return 0;
 }
 
 static HRESULT WINAPI IDirectSoundBuffer_GetFrequency(
 	LPDIRECTSOUNDBUFFER this,LPDWORD freq
 ) {
-	TRACE(dsound,"(%p)->GetFrequency(%p)\n",
-		this,freq
-	);
+	TRACE(dsound,"(%p,%p)\n",this,freq);
 	*freq = this->wfx.nSamplesPerSec;
 	return 0;
 }
@@ -360,7 +356,7 @@
 static HRESULT WINAPI IDirectSoundBuffer_Initialize(
 	LPDIRECTSOUNDBUFFER this,LPDIRECTSOUND dsound,LPDSBUFFERDESC dbsd
 ) {
-	fprintf(stderr,"(%p)->Initialize(%p,%p)\n",this,dsound,dbsd);
+	FIXME(dsound,"(%p,%p,%p):stub\n",this,dsound,dbsd);
 	return DSERR_ALREADYINITIALIZED;
 }
 
@@ -392,7 +388,7 @@
 		return 0;
 	}
 	WINE_StringFromCLSID(riid,xbuf);
-	fprintf(stderr,"(%p)->QueryInterface(%s,%p)\n",this,xbuf,ppobj);
+	TRACE(dsound,"(%p,%s,%p)\n",this,xbuf,ppobj);
 	return E_FAIL;
 }
 
@@ -426,9 +422,7 @@
 static HRESULT WINAPI IDirectSound_SetCooperativeLevel(
 	LPDIRECTSOUND this,HWND32 hwnd,DWORD level
 ) {
-	TRACE(dsound,"(%p)->SetCooperativeLevel(%08lx,%ld)\n",
-		this,(DWORD)hwnd,level
-	);
+	FIXME(dsound,"(%p,%08lx,%ld):stub\n",this,(DWORD)hwnd,level);
 	return 0;
 }
 
@@ -437,12 +431,12 @@
 	LPDIRECTSOUND this,LPDSBUFFERDESC dsbd,LPLPDIRECTSOUNDBUFFER ppdsb,LPUNKNOWN lpunk
 ) {
 	if (TRACE_ON(dsound)) {
-		fprintf(stderr,"IDirectSound(%p)->CreateSoundBuffer(%p,%p,%p)\n",this,dsbd,ppdsb,lpunk);
-		fprintf(stderr,"[size=%ld,",dsbd->dwSize);
-		fprintf(stderr,"flags = 0x%08lx,",dsbd->dwFlags);
+		TRACE(dsound,"(%p,%p,%p,%p)\n",this,dsbd,ppdsb,lpunk);
+		TRACE(dsound,"(size=%ld)\n",dsbd->dwSize);
+		TRACE(dsound,"(flags=0x%08lx\n",dsbd->dwFlags);
 		_dump_DSBCAPS(dsbd->dwFlags);
-		fprintf(stderr,"bufferbytes = %ld,",dsbd->dwBufferBytes);
-		fprintf(stderr,"lpwfxFormat = %p]\n",dsbd->lpwfxFormat);
+		TRACE(dsound,"(bufferbytes=%ld)\n",dsbd->dwBufferBytes);
+		TRACE(dsound,"(lpwfxFormat=%p)\n",dsbd->lpwfxFormat);
 	}
 	*ppdsb = (LPDIRECTSOUNDBUFFER)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDirectSoundBuffer));
 	(*ppdsb)->ref =1;
@@ -469,7 +463,7 @@
 static HRESULT WINAPI IDirectSound_DuplicateSoundBuffer(
 	LPDIRECTSOUND this,LPDIRECTSOUNDBUFFER pdsb,LPLPDIRECTSOUNDBUFFER ppdsb
 ) {
-	TRACE(dsound,"IDirectSound(%p)->DuplicateSoundBuffer(%p,%p)\n",this,pdsb,ppdsb);
+	TRACE(dsound,"(%p,%p,%p)\n",this,pdsb,ppdsb);
 
 	*ppdsb = (LPDIRECTSOUNDBUFFER)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDirectSoundBuffer));
 	(*ppdsb)->ref =1;
@@ -491,8 +485,8 @@
 
 
 static HRESULT WINAPI IDirectSound_GetCaps(LPDIRECTSOUND this,LPDSCAPS caps) {
-	TRACE(dsound,"IDirectSound(%p)->GetCaps(%p)\n",this,caps);
-	TRACE(dsound,"	flags = 0x%08lx\n",caps->dwFlags);
+	TRACE(dsound,"(%p,%p)\n",this,caps);
+	TRACE(dsound,"(flags=0x%08lx)\n",caps->dwFlags);
 
 	caps->dwSize = sizeof(*caps);
 	caps->dwFlags = DSCAPS_PRIMARYSTEREO|DSCAPS_PRIMARY16BIT|DSCAPS_EMULDRIVER|DSCAPS_SECONDARYSTEREO|DSCAPS_SECONDARY16BIT;
@@ -521,7 +515,7 @@
 static HRESULT WINAPI IDirectSound_SetSpeakerConfig(
 	LPDIRECTSOUND this,DWORD config
 ) {
-	fprintf(stderr,"IDirectSound(%p)->SetSpeakerConfig(0x%08lx)\n",this,config);
+	FIXME(dsound,"(%p,0x%08lx):stub\n",this,config);
 	return 0;
 }
 
@@ -531,7 +525,7 @@
 	char xbuf[50];
 
 	WINE_StringFromCLSID(riid,xbuf);
-	fprintf(stderr,"IDirectSound(%p)->QueryInterface(%s,%p)\n",this,xbuf,ppobj);
+	TRACE(dsound,"(%p,%s,%p)\n",this,xbuf,ppobj);
 	return E_FAIL;
 }
 
@@ -556,7 +550,7 @@
 
 	switch (wfex->wFormatTag) {
 	default:
-		fprintf(stderr,"unknown WAVE_FORMAT tag %d\n",wfex->wFormatTag);
+		WARN(dsound,"unknown WAVE_FORMAT tag %d\n",wfex->wFormatTag);
 		return DSERR_BADFORMAT;
 	case WAVE_FORMAT_PCM:
 		break;
@@ -571,7 +565,7 @@
 		return -1;
 	}
 	if ((xx&format)!=format) {/* format unsupported */
-		fprintf(stderr,"SNDCTL_DSP_GETFMTS: format not supported\n"); 
+		WARN(dsound,"SNDCTL_DSP_GETFMTS: format not supported\n"); 
 		return -1;
 	}
 	nformat = format;
@@ -580,7 +574,7 @@
 		return -1;
 	}
 	if (nformat!=format) {/* didn't work */
-		fprintf(stderr,"SNDCTL_DSP_GETFMTS: format not set\n"); 
+		WARN(dsound,"SNDCTL_DSP_GETFMTS: format not set\n"); 
 		return -1;
 	}
 
@@ -594,7 +588,7 @@
 		perror("ioctl SNDCTL_DSP_SPEED");
 		return -1;
 	}
-	fprintf(stderr,"freq %ld channels %d bits %d\n",
+	TRACE(dsound,"(freq=%ld,channels=%d,bits=%d)\n",
 		wfex->nSamplesPerSec,wfex->nChannels,wfex->wBitsPerSample
 	);
 	return 0;
@@ -619,7 +613,7 @@
 #define CHECK_EVENT							\
 	if (nextevent && (dsb->playpos == nextevent->dwOffset)) {	\
 		SetEvent(nextevent->hEventNotify);			\
-		fprintf(stderr,"signalled event %d\n",nextevent->hEventNotify);\
+		TRACE(dsound,"signalled event %d\n",nextevent->hEventNotify);\
 		nextevent = DSOUND_nextevent(dsb);			\
 	}
 		
@@ -633,10 +627,11 @@
 
 	if (xdiff<0) xdiff=-xdiff;
 	if (xdiff>1500) {
-		fprintf(stderr,"mixing in buffer of different frequency (%ld vs %ld), argh!\n",dsb->wfx.nSamplesPerSec,dsound->wfx.nSamplesPerSec);
+		WARN(dsound,"mixing in buffer of different frequency (%ld vs %ld), argh!\n",
+                        dsb->wfx.nSamplesPerSec,dsound->wfx.nSamplesPerSec);
 	}
 	nextevent = DSOUND_nextevent(dsb);
-/*	fprintf(stderr,"%d.%d.%d.%d\n",dsound->wfx.wBitsPerSample,dsb->wfx.wBitsPerSample,dsound->wfx.nChannels,dsb->wfx.nChannels);*/
+/*	TRACE(dsound,"(%d.%d.%d.%d)\n",dsound->wfx.wBitsPerSample,dsb->wfx.wBitsPerSample,dsound->wfx.nChannels,dsb->wfx.nChannels);*/
 
 	if (dsound->wfx.wBitsPerSample == 8) {
 		char	*playbuf8 = (char*)playbuf;
@@ -766,14 +761,14 @@
 DSOUND_thread(LPVOID arg) {
 	int	res,i,curleft,playing,haveprimary = 0;
 
-	fprintf(stderr,"dsound is at pid %d\n",getpid());
+	TRACE(dsound,"dsound is at pid %d\n",getpid());
 	while (1) {
 		if (!dsound) {
-			fprintf(stderr,"DSOUND thread giving up.\n");
+			WARN(dsound,"DSOUND thread giving up.\n");
 			ExitThread(0);
 		}
 		if (getppid()==1) {
-			fprintf(stderr,"DSOUND father died? Giving up.\n");
+			WARN(dsound,"DSOUND father died? Giving up.\n");
 			ExitThread(0);
 		}
 		/* RACE: dsound could be deleted */
@@ -849,7 +844,7 @@
 HRESULT WINAPI DirectSoundCreate(LPGUID lpGUID,LPDIRECTSOUND *ppDS,IUnknown *pUnkOuter ) {
 	int xx;
 	if (lpGUID)
-		fprintf(stderr,"DirectSoundCreate(%p,%p,%p)\n",lpGUID,ppDS,pUnkOuter);
+		TRACE(dsound,"(%p,%p,%p)\n",lpGUID,ppDS,pUnkOuter);
 #ifdef HAVE_OSS
 	if (audiofd>=0)
 		return DSERR_ALLOCATED;
@@ -863,7 +858,7 @@
 	if (-1==ioctl(audiofd,SNDCTL_DSP_SETFRAGMENT,&xx))
 		perror("ioctl SETFRAGMENT");
 /*
-	fprintf(stderr,"SETFRAGMENT. count is now %d, fragsize is %d\n",
+	TRACE(dsound,"SETFRAGMENT. count is now %d, fragsize is %d\n",
 		(xx>>16)+1,xx&0xffff
 	);
  */
@@ -896,3 +891,42 @@
 	return DSERR_NODRIVER;
 #endif
 }
+
+
+/*******************************************************************************
+ * DllGetClassObject [DSOUND.4]
+ * Retrieves class object from a DLL object
+ *
+ * NOTES
+ *    Docs say returns STDAPI
+ *
+ * PARAMS
+ *    rclsid [I] CLSID for the class object
+ *    riid   [I] Reference to identifier of interface for class object
+ *    ppv    [O] Address of variable to receive interface pointer for riid
+ *
+ * RETURNS
+ *    Success: S_OK
+ *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
+ *             E_UNEXPECTED
+ */
+DWORD WINAPI DllGetClassObject( REFCLSID rclsid, REFIID riid, LPVOID *ppv )
+{
+    FIXME(dsound, "(%p,%p,%p): stub\n", rclsid, riid, ppv);
+    return S_OK;
+}
+
+
+/*******************************************************************************
+ * DllCanUnloadNow [DSOUND.3]  Determines whether the DLL is in use.
+ *
+ * RETURNS
+ *    Success: S_OK
+ *    Failure: S_FALSE
+ */
+DWORD WINAPI DllCanUnloadNow(void)
+{
+    FIXME(dsound, "(void): stub\n");
+    return S_FALSE;
+}
+
diff --git a/multimedia/joystick.c b/multimedia/joystick.c
index 6a8d2e6..7873daa 100644
--- a/multimedia/joystick.c
+++ b/multimedia/joystick.c
@@ -145,7 +145,7 @@
 		joy_cnt++;
     }
     TRACE(mmsys, "returning %d\n", joy_cnt);
-    if (!joy_cnt) fprintf(stderr, "No joystick found - "
+    if (!joy_cnt) ERR(mmsys, "No joystick found - "
 			  "perhaps get joystick-0.8.0.tar.gz and load"
 			  "it as module or use Linux >= 2.1.45 to be "
 			  "able to use joysticks.\n");
@@ -409,6 +409,6 @@
  */
 MMRESULT16 WINAPI joySetCalibration16(UINT16 wID)
 {
-    fprintf(stderr, "EMPTY STUB !!! joySetCalibration(%04X);\n", wID);
+    FIXME(mmsys, "(%04X): stub.\n", wID);
     return JOYERR_NOCANDO;
 }
diff --git a/multimedia/mcianim.c b/multimedia/mcianim.c
index dc915a3..e56f503 100644
--- a/multimedia/mcianim.c
+++ b/multimedia/mcianim.c
@@ -196,7 +196,7 @@
 		case MCI_FORMAT_TMSF:
 			for (wTrack = 0; wTrack < AnimDev[wDevID].nTracks; wTrack++) {
 /*				dwTime += AnimDev[wDevID].lpdwTrackLen[wTrack - 1];
-				printf("Adding trk#%u curpos=%u \n", dwTime);
+				TRACE(mcianim, "Adding trk#%u curpos=%u \n", dwTime);
 				if (dwTime >= dwFrame) break; */
 				if (AnimDev[wDevID].lpdwTrackPos[wTrack - 1] >= dwFrame) break;
 				}
@@ -361,11 +361,11 @@
 				lpParms->dwReturn = MCI_FORMAT_MILLISECONDS;
 			 	return 0;
 			default:
-				fprintf(stderr,"ANIM_mciStatus // unknown command %08lX !\n", lpParms->dwItem);
+				WARN(mcianim,"Unknown command %08lX !\n", lpParms->dwItem);
 				return MCIERR_UNRECOGNIZED_COMMAND;
 			}
 		}
-    fprintf(stderr,"ANIM_mciStatus // not MCI_STATUS_ITEM !\n");
+    WARN(mcianim,"Not MCI_STATUS_ITEM !\n");
  	return 0;
 }
 
@@ -500,8 +500,8 @@
 	TRACE(mcianim,"(%u, %08lX, %p);\n", wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 /*
-	printf("ANIM_mciSet // dwTimeFormat=%08lX\n", lpParms->dwTimeFormat);
-	printf("ANIM_mciSet // dwAudio=%08lX\n", lpParms->dwAudio);
+	TRACE(mcianim,"(dwTimeFormat=%08lX)\n", lpParms->dwTimeFormat);
+	TRACE(mcianim,"(dwAudio=%08lX)\n", lpParms->dwAudio);
 */
 	if (dwFlags & MCI_SET_TIME_FORMAT) {
 		switch (lpParms->dwTimeFormat) {
@@ -515,7 +515,7 @@
 				TRACE(mcianim,"MCI_FORMAT_TMSF !\n");
 				break;
 			default:
-				fprintf(stderr,"ANIM_mciSet // bad time format !\n");
+				WARN(mcianim,"Bad time format !\n");
 				return MCIERR_BAD_TIME_FORMAT;
 			}
 		AnimDev[wDevID].dwTimeFormat = lpParms->dwTimeFormat;
diff --git a/multimedia/mcicda.c b/multimedia/mcicda.c
index 48e6ea1..77ce44b 100644
--- a/multimedia/mcicda.c
+++ b/multimedia/mcicda.c
@@ -582,7 +582,7 @@
 		case MCI_FORMAT_TMSF:
 			for (wTrack = 0; wTrack < CDADev[wDevID].nTracks; wTrack++) {
 /*				dwTime += CDADev[wDevID].lpdwTrackLen[wTrack - 1];
-				printf("Adding trk#%u curpos=%u \n", dwTime);
+				TRACE(cdaudio, "Adding trk#%u curpos=%u \n", dwTime);
 				if (dwTime >= dwFrame) break; */
 				if (CDADev[wDevID].lpdwTrackPos[wTrack - 1] >= dwFrame) break;
 				}
@@ -938,8 +938,8 @@
     	TRACE(cdaudio,"(%04X, %08lX, %p);\n", wDevID, dwFlags, lpParms);
 	if (lpParms == NULL) return MCIERR_INTERNAL;
 /*
-	printf("CDAUDIO_mciSet // dwTimeFormat=%08lX\n", lpParms->dwTimeFormat);
-	printf("CDAUDIO_mciSet // dwAudio=%08lX\n", lpParms->dwAudio);
+	TRACE(cdaudio,"dwTimeFormat=%08lX\n", lpParms->dwTimeFormat);
+	TRACE(cdaudio,"dwAudio=%08lX\n", lpParms->dwAudio);
 */
 	if (dwFlags & MCI_SET_TIME_FORMAT) {
 		switch (lpParms->dwTimeFormat) {
diff --git a/multimedia/mixer.c b/multimedia/mixer.c
index 1233531..4b554e6 100644
--- a/multimedia/mixer.c
+++ b/multimedia/mixer.c
@@ -150,18 +150,18 @@
 			lpml->fdwLine	|= MIXERLINE_LINEF_SOURCE;
 			break;
 		default:
-			fprintf(stderr,"MIX_GetLineInfo:mixertype %d not handle.\n",i);
+			ERR(mmaux,"Mixertype %d not handle.\n",i);
 			break;
 		}
 		break;
 	case MIXER_GETLINEINFOF_LINEID:
-		fprintf(stderr,"MIX_GetLineInfo: _LINEID (%ld) not implemented yet.\n",lpml->dwLineID);
+		FIXME(mmaux,"_LINEID (%ld) not implemented yet.\n",lpml->dwLineID);
 		break;
 	case MIXER_GETLINEINFOF_COMPONENTTYPE:
-		fprintf(stderr,"MIX_GetLineInfo: _COMPONENTTYPE not implemented yet.\n");
+		FIXME(mmaux," _COMPONENTTYPE not implemented yet.\n");
 		break;
 	case MIXER_GETLINEINFOF_TARGETTYPE:
-		fprintf(stderr,"MIX_GetLineInfo: _TARGETTYPE not implemented yet.\n");
+		FIXME(mmaux,"_TARGETTYPE not implemented yet.\n");
 		break;
 	}
 	lpml->Target.dwType = MIXERLINE_TARGETTYPE_AUX;
diff --git a/multimedia/mmio.c b/multimedia/mmio.c
index c7117a0..b1f6941 100644
--- a/multimedia/mmio.c
+++ b/multimedia/mmio.c
@@ -375,8 +375,9 @@
 UINT16 WINAPI mmioSetBuffer(HMMIO16 hmmio, LPSTR pchBuffer, 
                             LONG cchBuffer, UINT16 uFlags)
 {
-	FIXME(mmio, "empty stub \n");
-	return 0;
+	FIXME(mmio, "(hmmio=%d, pchBuf=%p, cchBuf=%d, uFlags=%#08x): stub\n",
+	      hmmio, pchBuffer, cchBuffer, uFlags);
+	return MMIOERR_OUTOFMEMORY;
 }
 
 /**************************************************************************
diff --git a/multimedia/time.c b/multimedia/time.c
index 1afcce4..a1ae385 100644
--- a/multimedia/time.c
+++ b/multimedia/time.c
@@ -380,7 +380,7 @@
   /* FIXME all this function should have to be is
        long result;
        struct timeval time;
-       dprintf_mmtime(stddeb, "timeGetTime(); !\n");
+       TRACE(mmtime,"timeGetTime(); !\n");
        gettimeofday(&time, 0);
        result = (((long)time.tv_sec * (long)1000) + ((long)time.tv_usec / (long)1000));
 
diff --git a/objects/bitmap.c b/objects/bitmap.c
index 71fc644..241eaf3 100644
--- a/objects/bitmap.c
+++ b/objects/bitmap.c
@@ -81,7 +81,7 @@
 	break;
 
     default:
-	fprintf(stderr,"GetBitsPadding: unknown depth %d, please report.\n", bpp );
+	WARN(bitmap,"Unknown depth %d, please report.\n", bpp );
         return -1;
     }
     return pad;
@@ -115,7 +115,7 @@
 	return 2 * ((bmWidth+3) >> 2);
 
     default:
-	fprintf(stderr,"GetBitsPadding: unknown depth %d, please report.\n", bpp );
+	WARN(bitmap,"Unknown depth %d, please report.\n", bpp );
     }
     return -1;
 }
@@ -130,8 +130,19 @@
 }
 
 
-/***********************************************************************
- *           CreateBitmap32    (GDI32.25)
+/******************************************************************************
+ * CreateBitmap32 [GDI32.25]  Creates a bitmap with the specified info
+ *
+ * PARAMS
+ *    width  [I] bitmap width
+ *    height [I] bitmap height
+ *    planes [I] Number of color planes
+ *    bpp    [I] Number of bits to identify a color
+ *    bits   [I] Pointer to array containing color data
+ *
+ * RETURNS
+ *    Success: Handle to bitmap
+ *    Failure: NULL
  */
 HBITMAP32 WINAPI CreateBitmap32( INT32 width, INT32 height, UINT32 planes,
                                  UINT32 bpp, LPCVOID bits )
@@ -142,8 +153,7 @@
     planes = (BYTE)planes;
     bpp    = (BYTE)bpp;
 
-    TRACE(gdi, "%dx%d, %d colors\n", 
-                 width, height, 1 << (planes*bpp) );
+    TRACE(gdi, "%dx%d, %d colors\n", width, height, 1 << (planes*bpp) );
 
       /* Check parameters */
     if (!height || !width || planes != 1) return 0;
@@ -190,17 +200,31 @@
 }
 
 
-/***********************************************************************
- *           CreateCompatibleBitmap32    (GDI32.30)
+/******************************************************************************
+ * CreateCompatibleBitmap32 [GDI32.30]  Creates a bitmap compatible with the DC
+ *
+ * PARAMS
+ *    hdc    [I] Handle to device context
+ *    width  [I] Width of bitmap
+ *    height [I] Height of bitmap
+ *
+ * RETURNS
+ *    Success: Handle to bitmap
+ *    Failure: NULL
  */
-HBITMAP32 WINAPI CreateCompatibleBitmap32(HDC32 hdc, INT32 width, INT32 height)
+HBITMAP32 WINAPI CreateCompatibleBitmap32( HDC32 hdc, INT32 width, INT32 height)
 {
     HBITMAP32 hbmpRet = 0;
     DC *dc;
 
-    TRACE(gdi, "(%04x,%d,%d) = \n", 
-                 hdc, width, height );
+    TRACE(gdi, "(%04x,%d,%d) = \n", hdc, width, height );
     if (!(dc = DC_GetDCPtr( hdc ))) return 0;
+    if ((width >0x1000) || (height > 0x1000))
+      {
+	FIXME(gdi,"got bad width %d or height %d, please look for reason\n",
+	       width, height );
+	return 0;
+      }
     hbmpRet = CreateBitmap32( width, height, 1, dc->w.bitsPerPixel, NULL );
     TRACE(gdi,"\t\t%04x\n", hbmpRet);
     return hbmpRet;
@@ -217,10 +241,15 @@
 }
 
 
-/***********************************************************************
- *           CreateBitmapIndirect32    (GDI32.26)
+/******************************************************************************
+ * CreateBitmapIndirect32 [GDI32.26]  Creates a bitmap with the specifies info
+ *
+ * RETURNS
+ *    Success: Handle to bitmap
+ *    Failure: NULL
  */
-HBITMAP32 WINAPI CreateBitmapIndirect32( const BITMAP32 * bmp )
+HBITMAP32 WINAPI CreateBitmapIndirect32(
+    const BITMAP32 * bmp) /* [in] Pointer to the bitmap data */
 {
     return CreateBitmap32( bmp->bmWidth, bmp->bmHeight, bmp->bmPlanes,
                            bmp->bmBitsPixel, bmp->bmBits );
@@ -249,9 +278,16 @@
 
 
 /***********************************************************************
- *           GetBitmapBits32    (GDI32.143)
+ * GetBitmapBits32 [GDI32.143]  Copies bitmap bits of bitmap to buffer
+ * 
+ * RETURNS
+ *    Success: Number of bytes copied
+ *    Failure: 0
  */
-LONG WINAPI GetBitmapBits32( HBITMAP32 hbitmap, LONG count, LPVOID buffer )
+LONG WINAPI GetBitmapBits32(
+    HBITMAP32 hbitmap, /* [in]  Handle to bitmap */
+    LONG count,        /* [in]  Number of bytes to copy */
+    LPVOID buffer)     /* [out] Pointer to buffer to receive bits */
 {
     BITMAPOBJ * bmp;
     LONG height, old_height;
@@ -261,7 +297,7 @@
     
     /* KLUDGE! */
     if (count < 0) {
-	fprintf(stderr, "Negative number of bytes (%ld) passed to GetBitmapBits???\n", count );
+	WARN(bitmap, "(%ld): Negative number of bytes passed???\n", count );
 	count = -count;
     }
     bmp = (BITMAPOBJ *) GDI_GetObjPtr( hbitmap, BITMAP_MAGIC );
@@ -356,6 +392,9 @@
 	    }
             tbuf += pad;
 	}
+        break;
+    default:
+        FIXME(bitmap, "Unhandled bits:%d\n", bmp->bitmap.bmBitsPixel);
     }
     XDestroyImage( image );
     LeaveCriticalSection( &X11DRV_CritSection );
@@ -374,10 +413,17 @@
 }
 
 
-/***********************************************************************
- *           SetBitmapBits32    (GDI32.303)
+/******************************************************************************
+ * SetBitmapBits32 [GDI32.303]  Sets bits of color data for a bitmap
+ *
+ * RETURNS
+ *    Success: Number of bytes used in setting the bitmap bits
+ *    Failure: 0
  */
-LONG WINAPI SetBitmapBits32( HBITMAP32 hbitmap, LONG count, LPCVOID buffer )
+LONG WINAPI SetBitmapBits32(
+    HBITMAP32 hbitmap, /* [in] Handle to bitmap */
+    LONG count,        /* [in] Number of bytes in bitmap array */
+    LPCVOID buffer)    /* [in] Address of array with bitmap bits */
 {
     struct XPutImage_descr descr;
     BITMAPOBJ * bmp;
@@ -388,7 +434,7 @@
     
     /* KLUDGE! */
     if (count < 0) {
-	fprintf(stderr, "Negative number of bytes (%ld) passed to SetBitmapBits???\n", count );
+	WARN(bitmap, "(%ld): Negative number of bytes passed???\n", count );
 	count = -count;
     }
     bmp = (BITMAPOBJ *) GDI_GetObjPtr( hbitmap, BITMAP_MAGIC );
@@ -491,17 +537,19 @@
     return height * bmp->bitmap.bmWidthBytes;
 }
 
+/***********************************************************************
+ * LoadImage16 [USER.389]
+ *
+ */
 HANDLE16 WINAPI LoadImage16( HINSTANCE16 hinst, LPCSTR name, UINT16 type,
                              INT16 desiredx, INT16 desiredy, UINT16 loadflags)
 {
 	if (HIWORD(name)) {
-		fprintf(stddeb,"LoadImage16(0x%04x,%s,%d,%d,%d,0x%08x)\n",
-			hinst,(char *)PTR_SEG_TO_LIN(name),type,desiredx,desiredy,loadflags
-		);
+	    TRACE(resource,"(0x%04x,%s,%d,%d,%d,0x%08x)\n",
+                hinst,(char *)PTR_SEG_TO_LIN(name),type,desiredx,desiredy,loadflags);
 	} else {
-		fprintf(stddeb,"LoadImage16(0x%04x,%p,%d,%d,%d,0x%08x)\n",
-			hinst,name,type,desiredx,desiredy,loadflags
-		);
+	    TRACE(resource,"LoadImage16(0x%04x,%p,%d,%d,%d,0x%08x)\n",
+                hinst,name,type,desiredx,desiredy,loadflags);
 	}
 	switch (type) {
 	case IMAGE_BITMAP:
@@ -514,8 +562,10 @@
 	return 0;
 	
 }
+
 /**********************************************************************
  *	    LoadImage32A    (USER32.365)
+ * 
  * FIXME: implementation still lacks nearly all features, see LR_*
  * defines in windows.h
  */
@@ -543,8 +593,35 @@
 	return 0;
 }
 
+/**********************************************************************
+ *	    LoadImage32W    (USER32.366)
+ * 
+ * FIXME: implementation still lacks nearly all features, see LR_*
+ * defines in windows.h
+ */
+
+
+/******************************************************************************
+ * LoadImage32W [USER32.366]  Loads an icon, cursor, or bitmap
+ *
+ * PARAMS
+ *    hinst     [I] Handle of instance that contains image
+ *    name      [I] Name of image
+ *    type      [I] Type of image
+ *    desiredx  [I] Desired width
+ *    desiredy  [I] Desired height
+ *    loadflags [I] Load flags
+ *
+ * RETURNS
+ *    Success: Handle to newly loaded image
+ *    Failure: NULL
+ *
+ * BUGS
+ *    Implementation still lacks nearly all features, see LR_*
+ *    defines in windows.h
+ */
 HANDLE32 WINAPI LoadImage32W( HINSTANCE32 hinst, LPCWSTR name, UINT32 type,
-                              INT32 desiredx, INT32 desiredy, UINT32 loadflags)
+                INT32 desiredx, INT32 desiredy, UINT32 loadflags )
 {
 	if (HIWORD(name)) {
 		TRACE(resource,"(0x%04x,%p,%d,%d,%d,0x%08x)\n",
@@ -555,20 +632,25 @@
 			hinst,name,type,desiredx,desiredy,loadflags
 		);
 	}
-	switch (type) {
-	case IMAGE_BITMAP:
-		return LoadBitmap32W(hinst,name);
-	case IMAGE_ICON:
-		return LoadIcon32W(hinst,name);
-	case IMAGE_CURSOR:
-		return LoadCursor32W(hinst,name);
-	}
-	return 0;
+
+    switch (type) {
+        case IMAGE_BITMAP:
+            return LoadBitmap32W(hinst,name);
+        case IMAGE_ICON:
+            return LoadIcon32W(hinst,name);
+        case IMAGE_CURSOR:
+            return LoadCursor32W(hinst,name);
+    }
+    return NULL;
 }
 
+
 /**********************************************************************
  *          CopyBitmap32 (not an API)
  *
+ * NOTES
+ *    If it is not an API, why is it declared with WINAPI?
+ *
  */
 HBITMAP32 WINAPI CopyBitmap32 (HBITMAP32 hnd)
 {
@@ -583,8 +665,20 @@
     return res;
 }
 
-/**********************************************************************
- *	    CopyImage32    (USER32.61)
+
+/******************************************************************************
+ * CopyImage32 [USER32.61]  Creates new image and copies attributes to it
+ *
+ * PARAMS
+ *    hnd      [I] Handle to image to copy
+ *    type     [I] Type of image to copy
+ *    desiredx [I] Desired width of new image
+ *    desiredy [I] Desired height of new image
+ *    flags    [I] Copy flags
+ *
+ * RETURNS
+ *    Success: Handle to newly created image
+ *    Failure: NULL
  *
  * FIXME: implementation still lacks nearly all features, see LR_*
  * defines in windows.h
@@ -607,6 +701,9 @@
 
 /**********************************************************************
  *	    LoadBitmap16    (USER.175)
+ *
+ * NOTES
+ *    Can this call LoadBitmap32?
  */
 HBITMAP16 WINAPI LoadBitmap16( HINSTANCE16 instance, SEGPTR name )
 {
@@ -647,10 +744,17 @@
     return hbitmap;
 }
 
-/**********************************************************************
- *	    LoadBitmap32W   (USER32.358)
+
+/******************************************************************************
+ * LoadBitmap32W [USER32.358]  Loads bitmap from the executable file
+ *
+ * RETURNS
+ *    Success: Handle to specified bitmap
+ *    Failure: NULL
  */
-HBITMAP32 WINAPI LoadBitmap32W( HINSTANCE32 instance, LPCWSTR name )
+HBITMAP32 WINAPI LoadBitmap32W(
+    HINSTANCE32 instance, /* [in] Handle to application instance */
+    LPCWSTR name)         /* [in] Address of bitmap resource name */
 {
     HBITMAP32 hbitmap = 0;
     HDC32 hdc;
@@ -754,7 +858,6 @@
 }
     
 
-
 /***********************************************************************
  *           CreateDiscardableBitmap16    (GDI.156)
  */
@@ -765,11 +868,17 @@
 }
 
 
-/***********************************************************************
- *           CreateDiscardableBitmap32    (GDI32.38)
+/******************************************************************************
+ * CreateDiscardableBitmap32 [GDI32.38]  Creates a discardable bitmap
+ *
+ * RETURNS
+ *    Success: Handle to bitmap
+ *    Failure: NULL
  */
-HBITMAP32 WINAPI CreateDiscardableBitmap32( HDC32 hdc, INT32 width,
-                                            INT32 height )
+HBITMAP32 WINAPI CreateDiscardableBitmap32(
+    HDC32 hdc,    /* [in] Handle to device context */
+    INT32 width,  /* [in] Bitmap width */
+    INT32 height) /* [in] Bitmap height */
 {
     return CreateCompatibleBitmap32( hdc, width, height );
 }
@@ -777,6 +886,9 @@
 
 /***********************************************************************
  *           GetBitmapDimensionEx16    (GDI.468)
+ *
+ * NOTES
+ *    Can this call GetBitmapDimensionEx32?
  */
 BOOL16 WINAPI GetBitmapDimensionEx16( HBITMAP16 hbitmap, LPSIZE16 size )
 {
@@ -788,10 +900,16 @@
 }
 
 
-/***********************************************************************
- *           GetBitmapDimensionEx32    (GDI32.144)
+/******************************************************************************
+ * GetBitmapDimensionEx32 [GDI32.144]  Retrieves dimensions of a bitmap
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
  */
-BOOL32 WINAPI GetBitmapDimensionEx32( HBITMAP32 hbitmap, LPSIZE32 size )
+BOOL32 WINAPI GetBitmapDimensionEx32(
+    HBITMAP32 hbitmap, /* [in]  Handle to bitmap */
+    LPSIZE32 size)     /* [out] Address of struct receiving dimensions */
 {
     BITMAPOBJ * bmp = (BITMAPOBJ *) GDI_GetObjPtr( hbitmap, BITMAP_MAGIC );
     if (!bmp) return FALSE;
@@ -829,11 +947,18 @@
 }
 
 
-/***********************************************************************
- *           SetBitmapDimensionEx32    (GDI32.304)
+/******************************************************************************
+ * SetBitmapDimensionEx32 [GDI32.304]  Assignes dimensions to a bitmap
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
  */
-BOOL32 WINAPI SetBitmapDimensionEx32( HBITMAP32 hbitmap, INT32 x, INT32 y,
-                                      LPSIZE32 prevSize )
+BOOL32 WINAPI SetBitmapDimensionEx32(
+    HBITMAP32 hbitmap, /* [in]  Handle to bitmap */
+    INT32 x,           /* [in]  Bitmap width */
+    INT32 y,           /* [in]  Bitmap height */
+    LPSIZE32 prevSize) /* [out] Address of structure for orig dims */
 {
     BITMAPOBJ * bmp = (BITMAPOBJ *) GDI_GetObjPtr( hbitmap, BITMAP_MAGIC );
     if (!bmp) return FALSE;
diff --git a/objects/clipping.c b/objects/clipping.c
index 1736092..7025d74 100644
--- a/objects/clipping.c
+++ b/objects/clipping.c
@@ -29,7 +29,7 @@
 
     if (!dc->w.hVisRgn)
     {
-        fprintf( stderr, "UpdateGCRegion: hVisRgn is zero. Please report this.\n" );
+        ERR(region, "hVisRgn is zero. Please report this.\n" );
         exit(1);
     }
 
@@ -463,7 +463,7 @@
     TRACE(clipping, "%04x\n", hdc );
     if (!dc->w.hVisRgn)
     {
-        fprintf( stderr, "SaveVisRgn: hVisRgn is zero. Please report this.\n" );
+        ERR(region, "hVisRgn is zero. Please report this.\n" );
         exit(1);
     }
     if( dc->w.flags & DC_DIRTY ) UPDATE_DIRTY_DC(dc);
diff --git a/objects/color.c b/objects/color.c
index 9f37ebc..50779dc 100644
--- a/objects/color.c
+++ b/objects/color.c
@@ -288,7 +288,7 @@
 
     COLOR_sysPal = (PALETTEENTRY*)xmalloc(sizeof(PALETTEENTRY)*cs->size);
 
-    TRACE(palette,"\tbuilding private map - %i palette entries\n", cs->size);
+    TRACE(palette,"Building private map - %i palette entries\n", cs->size);
 
       /* Allocate system palette colors */ 
 
@@ -347,7 +347,7 @@
    else if (COLOR_max < 20) COLOR_max = 20;
    TRACE(palette,"%d colors configured.\n", COLOR_max);
    
-   TRACE(palette,"\tbuilding shared map - %i palette entries\n", cs->size);
+   TRACE(palette,"Building shared map - %i palette entries\n", cs->size);
 
    /* Be nice and allocate system colors as read-only */
 
@@ -402,7 +402,7 @@
 
         sysPixel[i] = color.pixel;
 
-        TRACE(palette,"\tsyscolor(%lx) -> pixel %i\n",
+        TRACE(palette,"syscolor(%lx) -> pixel %i\n",
 		      *(COLORREF*)(__sysPalTemplate+i), (int)color.pixel);
 
         /* Set EGA mapping if color in the first or last eight */
@@ -419,7 +419,7 @@
      {
 	int c_min = 0, c_max = cs->size, c_val;
 
-	TRACE(palette,"\tdynamic colormap... \n");
+	TRACE(palette,"Dynamic colormap... \n");
 
 	/* comment this out if you want to debug palette init */
 
@@ -453,7 +453,7 @@
 	  if( !TSXAllocColorCells(display, cs->colorMap, False,
                                 plane_masks, 0, pixDynMapping, c_min) )
 	    {
-	      fprintf(stderr,"Inexplicable failure during colorcell allocation.\n");
+	      WARN(palette,"Inexplicable failure during colorcell allocation.\n");
 	      c_min = 0;
 	    }
 
@@ -470,7 +470,7 @@
 	   * to maintain compatibility
 	   */
 	  cs->size = 256;
-	  TRACE(palette,"\tvirtual colorspace - screendepth %i\n", screenDepth);
+	  TRACE(palette,"Virtual colorspace - screendepth %i\n", screenDepth);
 	}
    else cs->size = NB_RESERVED_COLORS;	/* system palette only - however we can alloc a bunch
 			                 * of colors and map to them */
@@ -529,7 +529,7 @@
            else
              COLOR_PaletteToPixel[i] = i;
 
-      TRACE(palette,"\tindex %i -> pixel %i\n", i, COLOR_PaletteToPixel[i]);
+      TRACE(palette,"index %i -> pixel %i\n", i, COLOR_PaletteToPixel[i]);
 
       if( COLOR_PixelToPalette )
           COLOR_PixelToPalette[COLOR_PaletteToPixel[i]] = i;
@@ -798,7 +798,7 @@
   else if( spec_type == 1 ) /* PALETTEINDEX */
     if( (i = color & 0x0000ffff) >= size ) 
       {
-	fprintf(stderr, "\tRGB(%lx) : idx %d is out of bounds, assuming NULL\n", color, i);
+	WARN(palette, "RGB(%lx) : idx %d is out of bounds, assuming NULL\n", color, i);
 	color = *(COLORREF*)palPalEntry;
       }
     else color = *(COLORREF*)(palPalEntry + i);
@@ -888,7 +888,7 @@
 
             if( (idx = color & 0xffff) >= palPtr->logpalette.palNumEntries)
             {
-                fprintf(stderr, "\tRGB(%lx) : idx %d is out of bounds, assuming black\n", color, idx);
+                WARN(palette, "RGB(%lx) : idx %d is out of bounds, assuming black\n", color, idx);
 		GDI_HEAP_UNLOCK( hPal );
                 return 0;
             }
@@ -941,7 +941,7 @@
 
 	if( !palPtr ) return 0;
 	else if( !palPtr->mapping ) 
-            WARN(palette, "\tpalette %04x is not realized\n", dc->w.hPalette);
+            WARN(palette, "Palette %04x is not realized\n", dc->w.hPalette);
 
 	switch(spec_type)	/* we have to peruse DC and system palette */
     	{
@@ -960,24 +960,24 @@
 	    	index = COLOR_PaletteLookupPixel( COLOR_sysPal, 256, 
 						  COLOR_PaletteToPixel, color, FALSE);
 
-		/* TRACE(palette,"\tRGB(%lx) -> pixel %i\n", color, index);
+		/* TRACE(palette,"RGB(%lx) -> pixel %i\n", color, index);
 		 */
 	    	break;
        	    case 1:  /* PALETTEINDEX */
 		index = color & 0xffff;
 
 	        if( index >= palPtr->logpalette.palNumEntries )
-		    fprintf(stderr, "\tRGB(%lx) : index %i is out of bounds\n", color, index); 
+		    WARN(palette, "RGB(%lx) : index %i is out of bounds\n", color, index); 
 		else if( palPtr->mapping ) index = palPtr->mapping[index];
 
-		/*  TRACE(palette,"\tPALETTEINDEX(%04x) -> pixel %i\n", (WORD)color, index);
+		/*  TRACE(palette,"PALETTEINDEX(%04x) -> pixel %i\n", (WORD)color, index);
 		 */
 		break;
             case 2:  /* PALETTERGB */
 		index = COLOR_PaletteLookupPixel( palPtr->logpalette.palPalEntry, 
                                              palPtr->logpalette.palNumEntries,
                                              palPtr->mapping, color, FALSE);
-		/* TRACE(palette,"\tPALETTERGB(%lx) -> pixel %i\n", color, index);
+		/* TRACE(palette,"PALETTERGB(%lx) -> pixel %i\n", color, index);
 		 */
 		break;
 	}
@@ -1020,7 +1020,7 @@
             index = *(WORD*)(palPtr->logpalette.palPalEntry + uStart);
             if( index > 255 || (index >= COLOR_gapStart && index <= COLOR_gapEnd) ) 
             {
-                fprintf(stderr,"PC_EXPLICIT: idx %d out of system palette, assuming black.\n", index); 
+                WARN(palette,"PC_EXPLICIT: idx %d out of system palette, assuming black.\n", index); 
                 index = 0;
             }
             break;
@@ -1077,7 +1077,7 @@
         if( !prevMapping || palPtr->mapping[uStart] != index ) iRemapped++;
         palPtr->mapping[uStart] = index;
 
-        TRACE(palette,"\tentry %i (%lx) -> pixel %i\n", uStart, 
+        TRACE(palette,"entry %i (%lx) -> pixel %i\n", uStart, 
 				*(COLORREF*)(palPtr->logpalette.palPalEntry + uStart), index);
 	
     }
diff --git a/objects/cursoricon.c b/objects/cursoricon.c
index 84170bf..36918ef 100644
--- a/objects/cursoricon.c
+++ b/objects/cursoricon.c
@@ -44,6 +44,7 @@
 #include "keyboard.h"
 
 extern UINT16 COLOR_GetSystemPaletteSize();
+extern void _XInitImageFuncPtrs(XImage *);
 
 Cursor CURSORICON_XCursor = None;    /* Current X cursor */
 static HCURSOR32 hActiveCursor = 0;  /* Active cursor */
@@ -63,7 +64,7 @@
 
     if (dir->idCount < 1)
     {
-        fprintf( stderr, "Icon: empty directory!\n" );
+        WARN(icon, "Empty directory!\n" );
         return NULL;
     }
     if (dir->idCount == 1) return &dir->idEntries[0].icon;  /* No choice... */
@@ -168,7 +169,7 @@
 
     if (dir->idCount < 1)
     {
-        fprintf( stderr, "Cursor: empty directory!\n" );
+        WARN(cursor, "Empty directory!\n" );
         return NULL;
     }
     if (dir->idCount == 1) return &dir->idEntries[0].cursor; /* No choice... */
@@ -278,7 +279,7 @@
  *        Convert to mono when cFlag is LR_MONOCHROME. Do something
  *        with cbSize parameter as well.
  */
-static HGLOBAL16 CURSORICON_CreateFromResource( HINSTANCE32 hInstance, HGLOBAL16 hObj, LPBYTE bits,
+static HGLOBAL16 CURSORICON_CreateFromResource( HINSTANCE16 hInstance, HGLOBAL16 hObj, LPBYTE bits,
 	 					UINT32 cbSize, BOOL32 bIcon, DWORD dwVersion, 
 						INT32 width, INT32 height, UINT32 cFlag )
 {
@@ -400,7 +401,7 @@
 	CURSORICONINFO *info;
 
 	/* Make it owned by the module */
-	if (hInstance) FarSetOwner( hObj, MODULE_HANDLEtoHMODULE16(hInstance));
+	if (hInstance) FarSetOwner( hObj, GetExePtr(hInstance) );
 
 	info = (CURSORICONINFO *)GlobalLock16( hObj );
 	info->ptHotSpot.x   = hotspot.x;
@@ -571,7 +572,7 @@
 	    if( !pRsrcEntry->ResourceHandle ) 
 	    {
 		LPBYTE bits = (LPBYTE)LockResource32( handle );
-		h = CURSORICON_CreateFromResource( hInstance, 0, bits, dirEntry.icon.dwBytesInRes, 
+		h = CURSORICON_CreateFromResource( 0, 0, bits, dirEntry.icon.dwBytesInRes, 
 					!fCursor, 0x00030000, width, height, LR_DEFAULTCOLOR );
 		pRsrcEntry->ResourceHandle = h;
 	    }
@@ -1099,7 +1100,8 @@
         while(hwnd)
         {
             Window win = WIN_GetXWindow( hwnd );
-            if (win) XDefineCursor( display, win, cursor );
+            if (win && win!=DefaultRootWindow(display))
+                XDefineCursor( display, win, cursor );
             hwnd = GetWindow32( hwnd, GW_HWNDNEXT );
         }
     }
@@ -1555,31 +1557,54 @@
     return hObj;
 }
 
+
 /**********************************************************************
  *          DrawIconEx16		(USER.394)
  */
-
 BOOL16 WINAPI DrawIconEx16 (HDC16 hdc, INT16 xLeft, INT16 yTop, HICON16 hIcon,
 			    INT16 cxWidth, INT16 cyWidth, UINT16 istep,
 			    HBRUSH16 hbr, UINT16 flags)
 {
-  return DrawIconEx32 (hdc, xLeft, yTop, hIcon, cxWidth, cyWidth,
-		       istep, hbr, flags);
+    return DrawIconEx32(hdc, xLeft, yTop, hIcon, cxWidth, cyWidth,
+                        istep, hbr, flags);
 }
 
-/**********************************************************************
- *          DrawIconEx32		(USER32.160)
- */
 
-BOOL32 WINAPI DrawIconEx32 (HDC32 hdc, INT32 x0, INT32 y0, HICON32 hIcon,
-			    INT32 cxWidth, INT32 cyWidth, UINT32 istep,
-			    HBRUSH32 hbr, UINT32 flags)
+/******************************************************************************
+ * DrawIconEx32 [USER32.160]  Draws an icon or cursor on device context
+ *
+ * NOTES
+ *    Why is this using SM_CXICON instead of SM_CXCURSOR?
+ *
+ * PARAMS
+ *    hdc     [I] Handle to device context
+ *    x0      [I] X coordinate of upper left corner
+ *    y0      [I] Y coordinate of upper left corner
+ *    hIcon   [I] Handle to icon to draw
+ *    cxWidth [I] Width of icon
+ *    cyWidth [I] Height of icon
+ *    istep   [I] Index of frame in animated cursor
+ *    hbr     [I] Handle to background brush
+ *    flags   [I] Icon-drawing flags
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
+ */
+BOOL32 WINAPI DrawIconEx32( HDC32 hdc, INT32 x0, INT32 y0, HICON32 hIcon,
+                            INT32 cxWidth, INT32 cyWidth, UINT32 istep, 
+                            HBRUSH32 hbr, UINT32 flags )
 {
     CURSORICONINFO *ptr = (CURSORICONINFO *)GlobalLock16 (hIcon);
     HDC32 hMemDC = CreateCompatibleDC32 (hdc);
     BOOL32 result = FALSE;
 
-    FIXME(icon, "part stub.\n");
+    if (istep)
+        FIXME(icon, "Ignoring istep=%d\n", istep);
+    if (hbr)
+        FIXME(icon, "Ignoring hbr=%x\n", hbr);
+    if (flags & DI_COMPAT)
+        FIXME(icon, "Ignoring flag DI_COMPAT\n");
 
     if (hMemDC && ptr)
     {
diff --git a/objects/dc.c b/objects/dc.c
index 8db9adc..6c71c18 100644
--- a/objects/dc.c
+++ b/objects/dc.c
@@ -428,7 +428,7 @@
 		   GCFont, &val );
 	return TRUE;
     } 
-    fprintf( stderr, "DC_SetupGCForText: physical font failure\n" );
+    WARN(dc, "Physical font failure\n" );
     return FALSE;
 }
 
@@ -911,7 +911,7 @@
  */
 HDC16 WINAPI ResetDC16( HDC16 hdc, const DEVMODE16 *devmode )
 {
-    fprintf( stderr, "ResetDC16: empty stub!\n" );
+    FIXME(dc, "stub\n" );
     return hdc;
 }
 
@@ -921,7 +921,7 @@
  */
 HDC32 WINAPI ResetDC32A( HDC32 hdc, const DEVMODE32A *devmode )
 {
-    fprintf( stderr, "ResetDC32A: empty stub!\n" );
+    FIXME(dc, "stub\n" );
     return hdc;
 }
 
@@ -931,7 +931,7 @@
  */
 HDC32 WINAPI ResetDC32W( HDC32 hdc, const DEVMODE32W *devmode )
 {
-    fprintf( stderr, "ResetDC32A: empty stub!\n" );
+    FIXME(dc, "stub\n" );
     return hdc;
 }
 
diff --git a/objects/dib.c b/objects/dib.c
index 7dd033f..a5ae6e3 100644
--- a/objects/dib.c
+++ b/objects/dib.c
@@ -77,7 +77,8 @@
     for( i = 0; bitmapDepthTable[i] ; i++ )
 	 if( bitmapDepthTable[i] == depth )
 	     return (4 * ((width * ximageDepthTable[i] + 31)/32));
-    fprintf(stderr, "DIB: unsupported depth %d.\n", depth );
+    
+    WARN(bitmap, "(%d): Unsupported depth\n", depth );
     return (4 * width);
 }
 
@@ -101,7 +102,7 @@
 	case 24: words = (width * 3 + 3)/4; break;
 
 	default:
-        	fprintf(stderr, "DIB: unsupported depth %d.\n", depth );
+            WARN(bitmap, "(%d): Unsupported depth\n", depth );
 	/* fall through */
 	case 32:
 	        words = width;
@@ -161,8 +162,7 @@
         *bpp    = core->bcBitCount;
         return 0;
     }
-    fprintf( stderr, "DIB_GetBitmapInfo: wrong size (%ld) for header\n",
-             header->biSize );
+    WARN(bitmap, "(%ld): wrong size for header\n", header->biSize );
     return -1;
 }
 
@@ -825,7 +825,7 @@
                              descr->width, descr->xSrc, descr->dc, bmpImage);
 	break;
     default:
-        fprintf( stderr, "Invalid depth %d for SetDIBits!\n", descr->infoBpp );
+        WARN(bitmap, "(%d): Invalid depth\n", descr->infoBpp );
         break;
     }
     if (colorMapping) HeapFree( GetProcessHeap(), 0, colorMapping );
@@ -886,8 +886,21 @@
 }
 
 
-/***********************************************************************
- *           SetDIBits32   (GDI32.312)
+/******************************************************************************
+ * SetDIBits32 [GDI32.312]  Sets pixels in a bitmap using colors from DIB
+ *
+ * PARAMS
+ *    hdc       [I] Handle to device context
+ *    hbitmap   [I] Handle to bitmap
+ *    startscan [I] Starting scan line
+ *    lines     [I] Number of scan lines
+ *    bits      [I] Array of bitmap bits
+ *    info      [I] Address of structure with data
+ *    coloruse  [I] Type of color indexes to use
+ *
+ * RETURNS
+ *    Success: Number of scan lines copied
+ *    Failure: 0
  */
 INT32 WINAPI SetDIBits32( HDC32 hdc, HBITMAP32 hbitmap, UINT32 startscan,
                           UINT32 lines, LPCVOID bits, const BITMAPINFO *info,
@@ -1124,14 +1137,23 @@
 }
 
 
-/***********************************************************************
- *           GetDIBits32    (GDI32.170)
+/******************************************************************************
+ * GetDIBits32 [GDI32.170]  Retrieves bits of bitmap and copies to buffer
+ *
+ * RETURNS
+ *    Success: Number of scan lines copied from bitmap
+ *    Failure: 0
  *
  * http://www.microsoft.com/msdn/sdk/platforms/doc/sdk/win32/func/src/f30_14.htm
  */
-INT32 WINAPI GetDIBits32( HDC32 hdc, HBITMAP32 hbitmap, UINT32 startscan,
-                          UINT32 lines, LPSTR bits, BITMAPINFO * info,
-                          UINT32 coloruse )
+INT32 WINAPI GetDIBits32(
+    HDC32 hdc,         /* [in]  Handle to device context */
+    HBITMAP32 hbitmap, /* [in]  Handle to bitmap */
+    UINT32 startscan,  /* [in]  First scan line to set in dest bitmap */
+    UINT32 lines,      /* [in]  Number of scan lines to copy */
+    LPSTR bits,        /* [out] Address of array for bitmap bits */
+    BITMAPINFO * info, /* [out] Address of structure with bitmap data */
+    UINT32 coloruse)   /* [in]  RGB or palette index */
 {
     DC * dc;
     BITMAPOBJ * bmp;
@@ -1292,9 +1314,8 @@
 		}
 		break;
 	   default:
-	   	fprintf(stderr,"GetDIBits*: unsupported depth %d\n",
-			info->bmiHeader.biBitCount
-		);
+	   	WARN(bitmap,"Unsupported depth %d\n",
+                   info->bmiHeader.biBitCount);
 	   	break;
 	}
 
@@ -1386,7 +1407,7 @@
         }
         else
         {
-            fprintf( stderr, "CreateDIBitmap: wrong size (%ld) for data\n",
+            WARN(bitmap, "(%ld): wrong size for data\n",
                      data->bmiHeader.biSize );
             return 0;
         }
@@ -1422,11 +1443,11 @@
 {
   HBITMAP32 res = 0;
 
-  fprintf(stderr,
-	  "CreateDIBSection(%d,[w=%ld,h=%ld],%d,%p,0x%08x,%ld),semistub\n",
+  FIXME(bitmap,
+	  "(%d,[w=%ld,h=%ld],%d,%p,0x%08x,%ld),semistub\n",
 	  hdc,bmi->bmiHeader.biWidth,bmi->bmiHeader.biHeight,
-	  usage,bits,section,offset
-	);
+	  usage,bits,section,offset);
+
   if (bmi->bmiHeader.biHeight < 0 ) bmi->bmiHeader.biHeight = -bmi->bmiHeader.biHeight;
   if (bmi->bmiHeader.biWidth < 0 ) bmi->bmiHeader.biWidth = -bmi->bmiHeader.biWidth;
   /* FIXME.  The following line isn't quite right.  */
@@ -1439,8 +1460,10 @@
             /* FIXME: this is wrong! (bmBits is always NULL) */
             if (bits) *bits = bmp.bmBits;
 	    /* hmpf */
-	    fprintf(stderr,"allocating %ld bytes of memory\n",bmi->bmiHeader.biWidth*bmi->bmiHeader.biHeight*4);
-	    if (bits) *bits = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,bmi->bmiHeader.biWidth*bmi->bmiHeader.biHeight*4);
+	    TRACE(bitmap,"allocating %ld bytes of memory\n",
+                bmi->bmiHeader.biWidth*bmi->bmiHeader.biHeight*4);
+	    if (bits) *bits = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
+                bmi->bmiHeader.biWidth*bmi->bmiHeader.biHeight*4);
             return res;
 	}
     }
diff --git a/objects/enhmetafile.c b/objects/enhmetafile.c
index 9745666..d6b784f 100644
--- a/objects/enhmetafile.c
+++ b/objects/enhmetafile.c
@@ -22,7 +22,7 @@
 {
   HENHMETAFILE32 hmf = 0;
   ENHMETAHEADER h;
-  char *p;
+  BYTE *p;
   DWORD read;
   HFILE32 hf = CreateFile32A(lpszMetaFile, GENERIC_READ, 0, 0, 
 			     OPEN_EXISTING, 0, 0);
@@ -31,7 +31,7 @@
   if (read!=sizeof(ENHMETAHEADER)) return 0;
   SetFilePointer(hf, 0, NULL, FILE_BEGIN); 
   /*  hmf = CreateFileMapping32A( hf, NULL, NULL, NULL, NULL, "temp"); */
-  hmf = GlobalAlloc32(GHND, h.nBytes);
+  hmf = GlobalAlloc32(GPTR, h.nBytes);
   p = GlobalLock32(hmf);
   if (!ReadFile(hf, p, h.nBytes, &read, NULL)) return 0;
   GlobalUnlock32(hmf);
@@ -54,6 +54,7 @@
   LPENHMETAHEADER p = GlobalLock32(hmf);
   if (!buf) return sizeof(ENHMETAHEADER);
   memmove(buf, p, MIN(sizeof(ENHMETAHEADER), bufsize));
+  GlobalUnlock32(hmf);
   return MIN(sizeof(ENHMETAHEADER), bufsize);
 }
 
@@ -105,6 +106,32 @@
   return MIN(size,p->nDescription);
 }
 
+/****************************************************************************
+ *    SetEnhMetaFileBits (GDI32.315)
+ *
+ *  Creates an enhanced metafile by copying _bufsize_ bytes from _buf_.
+ */
+HENHMETAFILE32 WINAPI SetEnhMetaFileBits(UINT32 bufsize, const BYTE *buf)
+{
+  HENHMETAFILE32 hmf = GlobalAlloc32(GPTR, bufsize);
+  LPENHMETAHEADER h = GlobalLock32(hmf);
+  memmove(h, buf, bufsize);
+  GlobalUnlock32(hmf);
+  return hmf;
+}
+
+/*****************************************************************************
+ *  GetEnhMetaFileBits (GDI32.175)
+ *
+ */
+UINT32 WINAPI GetEnhMetaFileBits(
+    HENHMETAFILE32 hmf, 
+    UINT32 bufsize, 
+    LPBYTE buf  
+) {
+  return 0;
+}
+
 /*****************************************************************************
  *           PlayEnhMetaFileRecord  (GDI32.264)
  *
@@ -142,11 +169,9 @@
       }
     case EMR_EOF:
       break;
-
     case EMR_GDICOMMENT:
       /* application defined and processed */
       break;
-
     case EMR_SETMAPMODE:
       {
 	DWORD mode = mr->dParm[0];
@@ -212,7 +237,6 @@
 	IntersectClipRect32(hdc, left, top, right, bottom);
 	break;
       }
-
     case EMR_SELECTOBJECT:
       {
 	DWORD obj = mr->dParm[0];
@@ -226,7 +250,6 @@
 	(handletable->objectHandle)[obj] = 0;
 	break;
       }
-
     case EMR_SETWINDOWORGEX:
       {
 	DWORD x = mr->dParm[0], y = mr->dParm[1];
@@ -251,7 +274,6 @@
 	SetViewportExtEx32(hdc, x, y, NULL);
 	break;
       }
-
     case EMR_CREATEPEN:
       {
 	DWORD obj = mr->dParm[0];
@@ -264,7 +286,7 @@
 	DWORD obj = mr->dParm[0];
 	DWORD style = mr->dParm[1], brush = mr->dParm[2];
 	LOGBRUSH32 *b = (LOGBRUSH32 *) &mr->dParm[3];
-	/* FIXME: other args not handled */
+	FIXME(metafile, "Some ExtCreatePen args not handled\n");
 	(handletable->objectHandle)[obj] = 
 	  ExtCreatePen32(style, brush, b, 0, NULL);
 	break;
@@ -283,7 +305,6 @@
 	  CreateFontIndirect32W((LOGFONT32W *) &(mr->dParm[1]));
 	break;
 	}
-
     case EMR_MOVETOEX:
       {
 	DWORD x = mr->dParm[0], y = mr->dParm[1];
@@ -310,14 +331,23 @@
 	Ellipse32(hdc, left, top, right, bottom);
 	break;
       }
-
     case EMR_POLYGON16:
       {
-	/* FIXME: 0-3 : a bounding rectangle? */
+	/* 0-3 : a bounding rectangle? */
 	INT32 count = mr->dParm[4];
+	FIXME(metafile, "Some Polygon16 args not handled\n");
 	Polygon16(hdc, (POINT16 *)&mr->dParm[5], count);
 	break;
       }
+    case EMR_POLYLINE16:
+      {
+	/* 0-3 : a bounding rectangle? */
+	INT32 count = mr->dParm[4];
+	FIXME(metafile, "Some Polyline16 args not handled\n");
+	Polyline16(hdc, (POINT16 *)&mr->dParm[5], count);
+	break;
+      }
+
 #if 0
     case EMR_POLYPOLYGON16:
       {
@@ -338,6 +368,7 @@
 	/* 10-16: ??? */
 	LPWSTR str = (LPWSTR)& mr->dParm[17];
 	/* trailing info: dx array? */
+	FIXME(metafile, "Many ExtTextOut args not handled\n");
 	ExtTextOut32W(hdc, x, y, flags, /* lpRect */ NULL, 
 		      str, count, /* lpDx */ NULL); 
 	break;
@@ -413,27 +444,61 @@
   INT32 count = ((LPENHMETAHEADER) p)->nHandles;
   HANDLETABLE32 *ht = (HANDLETABLE32 *)GlobalAlloc32(GPTR, 
 				    sizeof(HANDLETABLE32)*count);
+  BOOL32 ret = FALSE;
+  if (lpRect) {
+    LPENHMETAHEADER h = (LPENHMETAHEADER) p;
+    FLOAT xscale = (h->rclBounds.right-h->rclBounds.left)/(lpRect->right-lpRect->left);
+    FLOAT yscale = (h->rclBounds.bottom-h->rclBounds.top)/(lpRect->bottom-lpRect->top);
+    XFORM xform = {xscale, 0, 0, yscale, 0, 0};
+    /*    xform.eDx = lpRect->left;
+	  xform.eDy = lpRect->top; */
+    FIXME(metafile, "play into rect doesn't work\n");
+    if (!SetWorldTransform(hdc, &xform)) {
+      WARN(metafile, "World transform failed!\n");
+    }
+  }
+
   ht->objectHandle[0] = hmf;
   while (1) {
     PlayEnhMetaFileRecord(hdc, ht, p, count);
     if (p->iType == EMR_EOF) break;
     p = (void *) p + p->nSize; /* casted so that arithmetic is in bytes */
   }
-  return FALSE;
+  GlobalUnlock32(hmf);
+  return TRUE;
 }
 
 /*****************************************************************************
  *  DeleteEnhMetaFile (GDI32.68)
+ *
+ *  Deletes an enhanced metafile and frees the associated storage.
  */
 BOOL32 WINAPI DeleteEnhMetaFile(HENHMETAFILE32 hmf) {
   return !GlobalFree32(hmf);
 }
 
 /*****************************************************************************
- *  CopyEnhMetaFileA (GDI32.21)
+ *  CopyEnhMetaFileA (GDI32.21)  Duplicate an enhanced metafile
+ *
+ *   
  */
-HENHMETAFILE32 WINAPI CopyEnhMetaFile32A(HENHMETAFILE32 hmf, LPCSTR file) {
-  return 0;
+HENHMETAFILE32 WINAPI CopyEnhMetaFile32A(
+    HENHMETAFILE32 hmf, 
+    LPCSTR file)
+{
+  if (!file) {
+    LPENHMETAHEADER h = GlobalLock32(hmf);
+    HENHMETAFILE32 hmf2 = GlobalAlloc32(GPTR, h->nBytes);
+    LPENHMETAHEADER h2 = GlobalLock32(hmf2);
+    if (!h2) return 0;
+    memmove(h2, h, h->nBytes);
+    GlobalUnlock32(hmf2);
+    GlobalUnlock32(hmf);
+    return hmf2;
+  } else {
+    FIXME(metafile, "write to file not implemented\n");
+    return 0;
+  }
 }
 
 
diff --git a/objects/font.c b/objects/font.c
index 76948e8..7117e7e 100644
--- a/objects/font.c
+++ b/objects/font.c
@@ -221,12 +221,21 @@
 	    fontPtr = (FONTOBJ *) GDI_HEAP_LOCK( hFont );
 	    memcpy( &fontPtr->logfont, font, sizeof(LOGFONT16) );
 
-	    TRACE(font,"(%i %i) '%s' %s %s => %04x\n",
+	    TRACE(font,"(%i %i %i %i) '%s' %s %s => %04x\n",
 				 font->lfHeight, font->lfWidth, 
+		                 font->lfEscapement, font->lfOrientation,
 				 font->lfFaceName ? font->lfFaceName : "NULL",
 				 font->lfWeight > 400 ? "Bold" : "",
 				 font->lfItalic ? "Italic" : "",
 				 hFont);
+
+	    if (font->lfEscapement != font->lfOrientation) {
+	      /* this should really depend on whether GM_ADVANCED is set */
+	      fontPtr->logfont.lfOrientation = fontPtr->logfont.lfEscapement;
+	      WARN(font, 
+       "orientation angle %f set to escapement angle %f for new font %04x\n", 
+	   font->lfOrientation/10., font->lfEscapement/10., hFont);
+	    }
 	    GDI_HEAP_UNLOCK( hFont );
 	}
     }
@@ -1052,19 +1061,32 @@
 BOOL32 WINAPI GetCharABCWidths32A(HDC32 hdc, UINT32 firstChar, UINT32 lastChar,
                                   LPABC32 abc )
 {
-    /* No TrueType fonts in Wine so far */
-    FIXME(font, "(%04x,%04x,%04x,%p): stub\n", hdc, firstChar, lastChar, abc );
-    return FALSE;
+    return GetCharABCWidths32W( hdc, firstChar, lastChar, abc );
 }
 
 
-/***********************************************************************
- *           GetCharABCWidths32W   (GDI32.152)
+/******************************************************************************
+ * GetCharABCWidths32W [GDI32.152]  Retrieves widths of characters in range
+ *
+ * PARAMS
+ *    hdc       [I] Handle of device context
+ *    firstChar [I] First character in range to query
+ *    lastChar  [I] Last character in range to query
+ *    abc       [O] Address of character-width structure
+ *
+ * NOTES
+ *    Only works with TrueType fonts
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
  */
-BOOL32 WINAPI GetCharABCWidths32W(HDC32 hdc, UINT32 firstChar, UINT32 lastChar,
-                                  LPABC32 abc )
+BOOL32 WINAPI GetCharABCWidths32W( HDC32 hdc, UINT32 firstChar, UINT32 lastChar,
+                                   LPABC32 abc )
 {
-    return GetCharABCWidths32A( hdc, firstChar, lastChar, abc );
+    /* No TrueType fonts in Wine so far */
+    FIXME(font, "(%04x,%04x,%04x,%p): stub\n", hdc, firstChar, lastChar, abc);
+    return FALSE;
 }
 
 
diff --git a/objects/gdiobj.c b/objects/gdiobj.c
index 8d060b0..ae4ad7e 100644
--- a/objects/gdiobj.c
+++ b/objects/gdiobj.c
@@ -471,7 +471,7 @@
 	  result = PALETTE_GetObject( (PALETTEOBJ *)ptr, count, buffer );
 	  break;
       default:
-          fprintf( stderr, "GetObject32: magic %04x not implemented\n",
+          FIXME(gdi, "Magic %04x not implemented\n",
                    ptr->wMagic );
           break;
     }
@@ -527,8 +527,8 @@
 	  result = OBJ_METADC;
 	  break;
 
-	  default:
-	  fprintf( stderr, "GetObjectType: magic %04x not implemented\n",
+      default:
+	  FIXME(gdi, "Magic %04x not implemented\n",
 			   ptr->wMagic );
 	  break;
     }
@@ -561,7 +561,7 @@
     case OBJ_BITMAP:	return dc->w.hBitmap;
     default:
     	/* the SDK only mentions those above */
-    	fprintf(stderr,"GetCurrentObject(%08x,%d), unknown type.\n",hdc,type);
+    	WARN(gdi,"(%08x,%d): unknown type.\n",hdc,type);
 	return 0;
     }
 }
@@ -699,7 +699,7 @@
         break;
 
     default:
-        fprintf( stderr, "EnumObjects16: invalid type %d\n", nObjType );
+        WARN(gdi, "(%d): Invalid type\n", nObjType );
         break;
     }
     return retval;
@@ -775,7 +775,7 @@
 
     default:
         /* FIXME: implement Win32 types */
-        fprintf( stderr, "EnumObjects32: invalid type %d\n", nObjType );
+        WARN( gdi, "(%d): Invalid type\n", nObjType );
         break;
     }
     return retval;
@@ -867,7 +867,7 @@
     case 0x0103:  /* LocalHeap */
         return GDI_HeapSel;
     default:
-        fprintf(stderr, "GdiSeeGdiDo: wReqType %04x (unknown)", wReqType);
+        WARN(gdi, "(wReqType=%04x): Unknown\n", wReqType);
         return (DWORD)-1;
     }
 }
diff --git a/objects/metafile.c b/objects/metafile.c
index ea424bc..6e3d0b8 100644
--- a/objects/metafile.c
+++ b/objects/metafile.c
@@ -186,7 +186,7 @@
     METAHEADER *mh2;
     HFILE32 hFile;
     
-    TRACE(metafile,"%s\n", lpFilename);
+    TRACE(metafile,"(%08x,%s)\n", hSrcMetaFile, lpFilename);
     
     mh = (METAHEADER *)GlobalLock16(hSrcMetaFile);
     
@@ -213,7 +213,8 @@
 	memcpy(mh2,mh, mh->mtSize * 2);
 	GlobalUnlock16(handle);
         }
-    
+
+    GlobalUnlock16(hSrcMetaFile);
     return handle;
 }
 
@@ -295,6 +296,8 @@
     
     TRACE(metafile,"(%04x %04x)\n",hdc,hmf);
     if (!mh) return FALSE;
+
+    /* save the current pen, brush and font */
     if (!(dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC ))) return 0;
     hPen = dc->w.hPen;
     hBrush = dc->w.hBrush;
@@ -311,10 +314,11 @@
     while (offset < mh->mtSize * 2)
     {
         mr = (METARECORD *)((char *)mh + offset);
-	TRACE(metafile,"offset = %04x size = %08lx\n",
-			 offset, mr->rdSize);
+	TRACE(metafile,"offset=%04x,size=%08lx\n",
+            offset, mr->rdSize);
 	if (!mr->rdSize) {
-		fprintf(stderr,"METAFILE entry got size 0 at offset %d, total mf length is %ld\n",offset,mh->mtSize*2);
+            TRACE(metafile,"Entry got size 0 at offset %d, total mf length is %ld\n",
+                offset,mh->mtSize*2);
 		break; /* would loop endlessly otherwise */
 	}
 	offset += mr->rdSize * 2;
@@ -423,6 +427,68 @@
     return result;
 }
 
+BOOL32 WINAPI EnumMetaFile32( 
+			     HDC32 hdc, 
+			     HMETAFILE32 hmf,
+			     MFENUMPROC32 lpEnumFunc, 
+			     LPARAM lpData 
+) {
+    METAHEADER *mh = (METAHEADER *)GlobalLock16(hmf);
+    METARECORD *mr;
+    HANDLETABLE32 *ht;
+    BOOL32 result = TRUE;
+    int i, offset = 0;
+    DC *dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
+    HPEN32 hPen;
+    HBRUSH32 hBrush;
+    HFONT32 hFont;
+
+    TRACE(metafile,"(%08x,%08x,%p,%p)\n",
+		     hdc, hmf, lpEnumFunc, lpData);
+    if (!mh) return 0;
+
+    /* save the current pen, brush and font */
+    if (!dc) return 0;
+    hPen = dc->w.hPen;
+    hBrush = dc->w.hBrush;
+    hFont = dc->w.hFont;
+    GDI_HEAP_UNLOCK(hdc);
+
+
+    ht = (HANDLETABLE32 *) GlobalAlloc32(GPTR, 
+			    sizeof(HANDLETABLE32) * mh->mtNoObjects);
+    
+    /* loop through metafile records */
+    offset = mh->mtHeaderSize * 2;
+    
+    while (offset < (mh->mtSize * 2))
+    {
+	mr = (METARECORD *)((char *)mh + offset);
+        if (!lpEnumFunc( hdc, ht, mr, mh->mtNoObjects, (LONG)lpData ))
+	{
+	    result = FALSE;
+	    break;
+	}
+	
+	offset += (mr->rdSize * 2);
+    }
+
+    /* restore pen, brush and font */
+    SelectObject32(hdc, hBrush);
+    SelectObject32(hdc, hPen);
+    SelectObject32(hdc, hFont);
+
+    /* free objects in handle table */
+    for(i = 0; i < mh->mtNoObjects; i++)
+      if(*(ht->objectHandle + i) != 0)
+        DeleteObject32(*(ht->objectHandle + i));
+
+    /* free handle table */
+    GlobalFree32(ht);
+    GlobalUnlock16(hmf);
+    return result;
+}
+
 static BOOL32 MF_Meta_CreateRegion( METARECORD *mr, HRGN32 hrgn );
 
 /******************************************************************
@@ -893,7 +959,16 @@
      UINT32 handles  
     )
 {
-  PlayMetaFileRecord16(hdc, handletable, metarecord, handles);
+  HANDLETABLE16 * ht = (void *)GlobalAlloc32(GPTR, 
+                               handles*sizeof(HANDLETABLE16));
+  int i = 0;
+  TRACE(metafile, "(%08x,%p,%p,%d)\n", hdc, handletable, metarecord, handles); 
+  for (i=0; i<handles; i++)  
+    ht->objectHandle[i] =  handletable->objectHandle[i];
+  PlayMetaFileRecord16(hdc, ht, metarecord, handles);
+  for (i=0; i<handles; i++) 
+    handletable->objectHandle[i] = ht->objectHandle[i];
+  GlobalFree32(ht);
   return TRUE;
 }
 
@@ -961,11 +1036,39 @@
 {
   HMETAFILE32 hmf = GlobalAlloc16(GHND, size);
   BYTE *p = GlobalLock16(hmf) ;
+  TRACE(metafile, "(%d,%p) returning %08x\n", size, lpData, hmf);
+  if (!hmf || !p) return 0;
   memcpy(p, lpData, size);
   GlobalUnlock16(hmf);
   return hmf;
 }
 
+/*****************************************************************
+ *  GetMetaFileBitsEx     (GDI32.198)  Get raw metafile data
+ * 
+ *  Copies the data from metafile _hmf_ into the buffer _buf_.
+ *  If _buf_ is zero, returns size of buffer required. Otherwise,
+ *  returns number of bytes copied.
+ */
+UINT32 WINAPI GetMetaFileBitsEx( 
+     HMETAFILE32 hmf, /* metafile */
+     UINT32 nSize, /* size of buf */ 
+     LPVOID buf   /* buffer to receive raw metafile data */  
+) {
+  METAHEADER *h = GlobalLock16(hmf);
+  TRACE(metafile, "(%08x,%d,%p)\n", hmf, nSize, buf);
+  if (!h) return 0;  /* FIXME: error code */
+  if (!buf) {
+    GlobalUnlock16(hmf);
+    TRACE(metafile,"returning size %d\n", h->mtSize);
+    return h->mtSize;
+  }
+  memmove(buf, h, MIN(nSize, h->mtSize));
+  GlobalUnlock16(hmf);
+  return MIN(nSize, h->mtSize);
+}
+
+
 /******************************************************************
  *         MF_Meta_CreateRegion
  *
@@ -1008,20 +1111,20 @@
     for(band  = 0, start = &(mr->rdParam[11]); band < mr->rdParam[5];
  					        band++, start = end + 1) {
         if(*start / 2 != (*start + 1) / 2) {
- 	    fprintf(stderr, "META_CREATEREGION: delimiter not even.\n");
+ 	    WARN(metafile, "Delimiter not even.\n");
 	    DeleteObject32( hrgn2 );
  	    return FALSE;
         }
 
 	end = start + *start + 3;
 	if(end > (WORD *)mr + mr->rdSize) {
-	    WARN(metafile, "META_CREATEREGION: end points outside record.\n");
+	    WARN(metafile, "End points outside record.\n");
 	    DeleteObject32( hrgn2 );
 	    return FALSE;
         }
 
 	if(*start != *end) {
-	    WARN(metafile, "META_CREATEREGION: mismatched delimiters.\n");
+	    WARN(metafile, "Mismatched delimiters.\n");
 	    DeleteObject32( hrgn2 );
 	    return FALSE;
 	}
@@ -1384,7 +1487,7 @@
     METARECORD *mr;
     
     if((!flags && rect) || (flags && !rect))
-	fprintf(stderr, "MF_ExtTextOut: Inconsistent flags and rect\n");
+	WARN(metafile, "Inconsistent flags and rect\n");
     len = sizeof(METARECORD) + (((count + 1) >> 1) * 2) + 2 * sizeof(short)
 	    + sizeof(UINT16);
     if(rect)
diff --git a/objects/oembitmap.c b/objects/oembitmap.c
index f7b83ce..9f2cd4b 100644
--- a/objects/oembitmap.c
+++ b/objects/oembitmap.c
@@ -410,7 +410,7 @@
     if (!CALL_LARGE_STACK( OBM_CreateBitmaps, &descr ))
     {
         LeaveCriticalSection( &X11DRV_CritSection );
-        fprintf( stderr, "Error creating OEM bitmap %d\n", OBM_FIRST+id );
+        WARN(bitmap, "Error creating OEM bitmap %d\n", OBM_FIRST+id );
         return 0;
     }
     LeaveCriticalSection( &X11DRV_CritSection );
@@ -462,7 +462,7 @@
     if (!CALL_LARGE_STACK( OBM_CreateBitmaps, &descr ))
     {
         LeaveCriticalSection( &X11DRV_CritSection );
-        fprintf( stderr, "Error creating OEM cursor/icon %d\n", id );
+        WARN(cursor, "Error creating OEM cursor/icon %d\n", id );
         return 0;
     }
     LeaveCriticalSection( &X11DRV_CritSection );
diff --git a/objects/pen.c b/objects/pen.c
index 79ca82c..e9ee9a8 100644
--- a/objects/pen.c
+++ b/objects/pen.c
@@ -85,10 +85,10 @@
     LOGPEN32 logpen;
 
     if ((style & PS_STYLE_MASK) == PS_USERSTYLE)
-	fprintf(stderr, "ExtCreatePen: PS_USERSTYLE not handled\n");
+	FIXME(gdi, "PS_USERSTYLE not handled\n");
     if ((style & PS_TYPE_MASK) == PS_GEOMETRIC)
 	if (brush->lbHatch)
-	    fprintf(stderr, "ExtCreatePen: Hatches not implemented\n");
+	    FIXME(gdi, "Hatches not implemented\n");
 
     logpen.lopnStyle = style & ~PS_TYPE_MASK;
     logpen.lopnWidth.x = (style & PS_GEOMETRIC) ? width : 1;
diff --git a/objects/region.c b/objects/region.c
index 8572d56..9f771ed 100644
--- a/objects/region.c
+++ b/objects/region.c
@@ -536,15 +536,15 @@
 		   lpXform, dwCount, rgndata, hrgn);
     if(!hrgn)
     {
-        fprintf(stderr, "ExtCreateRegion can't create a region!\n");
+        WARN(region, "Can't create a region!\n");
 	return 0;
     }
     if(lpXform)
-        fprintf(stderr, "ExtCreateRegion: Xform not implemented - ignoring\n");
+        WARN(region, "Xform not implemented - ignoring\n");
     
     if(rgndata->rdh.iType != RDH_RECTANGLES)
     {
-        fprintf(stderr, "ExtCreateRegion: type not RDH_RECTANGLES\n");
+        WARN(region, "Type not RDH_RECTANGLES\n");
 	GDI_HEAP_UNLOCK( hrgn );
 	DeleteObject32( hrgn );
 	return 0;
@@ -1923,7 +1923,7 @@
             tmpSLLBlock = HeapAlloc( SystemHeap, 0, sizeof(ScanLineListBlock));
 	    if(!tmpSLLBlock)
 	    {
-	        fprintf(stderr, "REGION_InsertEdgeInET(): Can't alloc SLLB\n");
+	        WARN(region, "Can't alloc SLLB\n");
 		return;
 	    }
             (*SLLBlock)->next = tmpSLLBlock;
@@ -2371,8 +2371,7 @@
                 if (iPts == NUMPTSTOBUFFER) {
                     tmpPtBlock = HeapAlloc( SystemHeap, 0, sizeof(POINTBLOCK));
 		    if(!tmpPtBlock) {
-		        fprintf(stderr, 
-				"CreatePolyPolygonRgn(): can't alloc tPB\n");
+		        WARN(region, "Can't alloc tPB\n");
 			return 0;
 		    }
                     curPtBlock->next = tmpPtBlock;
@@ -2423,8 +2422,7 @@
                         tmpPtBlock = HeapAlloc( SystemHeap, 0,
 					       sizeof(POINTBLOCK) );
 			if(!tmpPtBlock) {
-			    fprintf(stderr, 
-				"CreatePolyPolygonRgn(): can't alloc tPB\n");
+			    WARN(region, "Can't alloc tPB\n");
 			    return 0;
 			}
                         curPtBlock->next = tmpPtBlock;
diff --git a/ole/compobj.c b/ole/compobj.c
index fc6346b..ce44806 100644
--- a/ole/compobj.c
+++ b/ole/compobj.c
@@ -288,7 +288,7 @@
 	(LPVOID)args,
 	(LPDWORD)idstr
     )) {
-    	fprintf(stderr,"CallTo16 IMalloc16 failed\n");
+    	WARN(ole,"CallTo16 IMalloc16 failed\n");
     	return E_FAIL;
     }
     return WINE_StringFromCLSID(id,PTR_SEG_TO_LIN(*idstr));
@@ -395,7 +395,7 @@
  *           LookupETask (COMPOBJ.94)
  */
 OLESTATUS WINAPI LookupETask(LPVOID p1,LPVOID p2) {
-	fprintf(stderr,"LookupETask(%p,%p),stub!\n",p1,p2);
+	FIXME(ole,"(%p,%p),stub!\n",p1,p2);
 	return 0;
 }
 
@@ -403,7 +403,7 @@
  *           LookupETask (COMPOBJ.201)
  */
 OLESTATUS WINAPI CallObjectInWOW(LPVOID p1,LPVOID p2) {
-	fprintf(stderr,"CallObjectInWOW(%p,%p),stub!\n",p1,p2);
+	FIXME(ole,"(%p,%p),stub!\n",p1,p2);
 	return 0;
 }
 
@@ -539,7 +539,7 @@
  *           CoInitializeWOW (OLE32.27)
  */
 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y) {
-    fprintf(stderr,"CoInitializeWOW(0x%08lx,0x%08lx),stub!\n",x,y);
+    FIXME(ole,"(0x%08lx,0x%08lx),stub!\n",x,y);
     return 0;
 }
 
@@ -551,6 +551,6 @@
     BOOL16 fLock,		/* [in] do lock */
     BOOL16 fLastUnlockReleases	/* [in] ? */
 ) {
-    fprintf(stderr,"CoLockObjectExternal(%p,%d,%d),stub!\n",pUnk,fLock,fLastUnlockReleases);
+    FIXME(ole,"(%p,%d,%d),stub!\n",pUnk,fLock,fLastUnlockReleases);
     return S_OK;
 }
diff --git a/ole/folders.c b/ole/folders.c
index 7903e89..6d159f5 100644
--- a/ole/folders.c
+++ b/ole/folders.c
@@ -19,14 +19,14 @@
  */
 
 static ULONG WINAPI IEnumIDList_AddRef(LPENUMIDLIST this) {
-	fprintf(stderr,"IEnumIDList(%p)->AddRef()\n",this);
+	TRACE(ole,"(%p)->()\n",this);
 	return ++(this->ref);
 }
 
 static ULONG WINAPI IEnumIDList_Release(LPENUMIDLIST this) {
-	fprintf(stderr,"IEnumIDList(%p)->Release()\n",this);
+	TRACE(ole,"(%p)->()\n",this);
 	if (!--(this->ref)) {
-		fprintf(stderr,"	-> freeing IEnumIDList(%p)\n",this);
+		WARN(ole," freeing IEnumIDList(%p)\n",this);
 		HeapFree(GetProcessHeap(),0,this);
 		return 0;
 	}
@@ -36,7 +36,7 @@
 static HRESULT WINAPI IEnumIDList_Next(
 	LPENUMIDLIST this,ULONG celt,LPITEMIDLIST *rgelt,ULONG *pceltFetched
 ) {
-	fprintf(stderr,"IEnumIDList(%p)->Next(%ld,%p,%p),stub!\n",
+	FIXME(ole,"(%p)->(%ld,%p,%p),stub!\n",
 		this,celt,rgelt,pceltFetched
 	);
 	*pceltFetched = 0; /* we don't have any ... */
@@ -66,9 +66,9 @@
  * IShellFolder implementation
  */
 static ULONG WINAPI IShellFolder_Release(LPSHELLFOLDER this) {
-	fprintf(stderr,"IShellFolder(%p)->Release()\n",this);
+	TRACE(ole,"(%p)->()\n",this);
 	if (!--(this->ref)) {
-		fprintf(stderr,"	-> freeing IShellFolder(%p)\n",this);
+		WARN(ole," freeing IShellFolder(%p)\n",this);
 		HeapFree(GetProcessHeap(),0,this);
 		return 0;
 	}
@@ -76,14 +76,14 @@
 }
 
 static ULONG WINAPI IShellFolder_AddRef(LPSHELLFOLDER this) {
-	fprintf(stderr,"IShellFolder(%p)->AddRef()\n",this);
+	TRACE(ole,"(%p)->()\n",this);
 	return ++(this->ref);
 }
 
 static HRESULT WINAPI IShellFolder_GetAttributesOf(
 	LPSHELLFOLDER this,UINT32 cidl,LPCITEMIDLIST *apidl,DWORD *rgfInOut
 ) {
-	fprintf(stderr,"IShellFolder(%p)->GetAttributesOf(%d,%p,%p),stub!\n",
+	FIXME(ole,"(%p)->(%d,%p,%p),stub!\n",
 		this,cidl,apidl,rgfInOut
 	);
 	return 0;
@@ -95,7 +95,7 @@
 	char	xclsid[50];
 
 	WINE_StringFromCLSID(riid,xclsid);
-	fprintf(stderr,"IShellFolder(%p)->BindToObject(%p,%p,%s,%p),stub!\n",
+	FIXME(ole,"(%p)->(%p,%p,%s,%p),stub!\n",
 		this,pidl,pbcReserved,xclsid,ppvOut
 	);
 	*ppvOut = IShellFolder_Constructor();
@@ -107,7 +107,7 @@
 	LPOLESTR32 lpszDisplayName,DWORD *pchEaten,LPITEMIDLIST *ppidl,
 	DWORD *pdwAttributes
 ) {
-	fprintf(stderr,"IShellFolder(%p)->ParseDisplayName(%08x,%p,%p,%p,%p,%p),stub!\n",
+	FIXME(ole,"(%p)->(%08x,%p,%p,%p,%p,%p),stub!\n",
 		this,hwndOwner,pbcReserved,lpszDisplayName,pchEaten,ppidl,pdwAttributes
 	);
 	*(DWORD*)pbcReserved = 0;
@@ -118,7 +118,7 @@
 	LPSHELLFOLDER this,HWND32 hwndOwner,DWORD grfFlags,
 	LPENUMIDLIST* ppenumIDList
 ) {
-	fprintf(stderr,"IShellFolder(%p)->EnumObjects(0x%04x,0x%08lx,%p),stub!\n",
+	FIXME(ole,"(%p)->(0x%04x,0x%08lx,%p),stub!\n",
 		this,hwndOwner,grfFlags,ppenumIDList
 	);
 	*ppenumIDList = IEnumIDList_Constructor();
@@ -131,7 +131,7 @@
 	char	xclsid[50];
 
 	WINE_StringFromCLSID(riid,xclsid);
-	fprintf(stderr,"IShellFolder(%p)->CreateViewObject(0x%04x,%s,%p),stub!\n",
+	FIXME(ole,"(%p)->(0x%04x,%s,%p),stub!\n",
 		this,hwndOwner,xclsid,ppv
 	);
 	*(DWORD*)ppv = 0;
diff --git a/ole/ifs.c b/ole/ifs.c
index 6f24584..2980ed1 100644
--- a/ole/ifs.c
+++ b/ole/ifs.c
@@ -137,29 +137,25 @@
 LPMALLOC16
 IMalloc16_Constructor() {
 	LPMALLOC16	this;
+        HMODULE16	hcomp = GetModuleHandle16("COMPOBJ");
 
 	this = (LPMALLOC16)SEGPTR_NEW(IMalloc16);
-	if (__winelib) {
-		this->lpvtbl = &mvt16;
-	} else {
-		HMODULE16	hcomp = GetModuleHandle16("COMPOBJ");
-		if (!msegvt16) {
-			this->lpvtbl = msegvt16 = SEGPTR_NEW(IMalloc16_VTable);
+        if (!msegvt16) {
+            this->lpvtbl = msegvt16 = SEGPTR_NEW(IMalloc16_VTable);
 
-#define FN(x) this->lpvtbl->fn##x = (void*)WIN32_GetProcAddress16(hcomp,"IMalloc16_"#x);assert(this->lpvtbl->fn##x);
-			FN(QueryInterface)
-			FN(AddRef)
-			FN(Release)
-			FN(Alloc)
-			FN(Realloc)
-			FN(Free)
-			FN(GetSize)
-			FN(DidAlloc)
-			FN(HeapMinimize)
-			msegvt16 = (LPMALLOC16_VTABLE)SEGPTR_GET(msegvt16);
+#define FN(x) this->lpvtbl->fn##x = (void*)WIN32_GetProcAddress16(hcomp,"IMalloc16_"#x);assert(this->lpvtbl->fn##x)
+            FN(QueryInterface);
+            FN(AddRef);
+            FN(Release);
+            FN(Alloc);
+            FN(Realloc);
+            FN(Free);
+            FN(GetSize);
+            FN(DidAlloc);
+            FN(HeapMinimize);
+            msegvt16 = (LPMALLOC16_VTABLE)SEGPTR_GET(msegvt16);
 #undef FN
-		}
-		this->lpvtbl = msegvt16;
+            this->lpvtbl = msegvt16;
 	}
 	this->ref = 1;
 	/* FIXME: implement multiple heaps */
diff --git a/ole/moniker.c b/ole/moniker.c
index 17365cd..7904ab8 100644
--- a/ole/moniker.c
+++ b/ole/moniker.c
@@ -28,6 +28,6 @@
 	LPCOLESTR16 lpszPathName,	/* [in] pathname */
 	LPMONIKER * ppmk		/* [out] new moniker object */
 ) {
-	fprintf(stderr,"CreateFileMoniker(%s,%p),stub!\n",lpszPathName,ppmk);
+	FIXME(ole,"(%s,%p),stub!\n",lpszPathName,ppmk);
 	return E_FAIL;
 }
diff --git a/ole/ole2.c b/ole/ole2.c
index d6e4232..577c41d 100644
--- a/ole/ole2.c
+++ b/ole/ole2.c
@@ -66,7 +66,7 @@
  *           OleInitializeWOW (OLE32.27)
  */
 HRESULT WINAPI OleInitializeWOW(DWORD x) {
-        fprintf(stderr,"OleInitializeWOW(0x%08lx),stub!\n",x);
+        FIXME(ole,"(0x%08lx),stub!\n",x);
         return 0;
 }
 
@@ -74,7 +74,7 @@
  *           GetRunningObjectTable (OLE2.30)
  */
 HRESULT WINAPI GetRunningObjectTable16(DWORD reserved, LPVOID *pprot) {
-	fprintf(stderr,"GetRunningObjectTable(%ld,%p),stub!\n",reserved,pprot);
+	FIXME(ole,"(%ld,%p),stub!\n",reserved,pprot);
 	return E_FAIL;
 }
 
@@ -85,7 +85,7 @@
 	HWND16 hwnd,
 	LPDROPTARGET pDropTarget
 ) {
-	fprintf(stderr,"RegisterDragDrop(0x%04x,%p),stub!\n",hwnd,pDropTarget);
+	FIXME(ole,"(0x%04x,%p),stub!\n",hwnd,pDropTarget);
 	return S_OK;
 }
 
diff --git a/ole/ole2disp.c b/ole/ole2disp.c
index 38d3399..169f30c 100644
--- a/ole/ole2disp.c
+++ b/ole/ole2disp.c
@@ -7,6 +7,7 @@
 #include "windows.h"
 #include "ole.h"
 #include "ole2.h"
+#include "oleauto.h"
 #include "interfaces.h"
 #include "heap.h"
 #include "ldt.h"
@@ -16,20 +17,18 @@
    represents BSTR as a 16:16 far pointer, and the strings
    as ISO-8859 */
 
-typedef DWORD	BSTR;
-
-static BSTR BSTR_AllocBytes(int n)
+static BSTR16 BSTR_AllocBytes(int n)
 {
     void *ptr = SEGPTR_ALLOC(n);
-    return SEGPTR_GET(ptr);
+    return (BSTR16)SEGPTR_GET(ptr);
 }
 
-static void BSTR_Free(BSTR in)
+static void BSTR_Free(BSTR16 in)
 {
     SEGPTR_FREE( PTR_SEG_TO_LIN(in) );
 }
 
-static void* BSTR_GetAddr(BSTR in)
+static void* BSTR_GetAddr(BSTR16 in)
 {
     return in ? PTR_SEG_TO_LIN(in) : 0;
 }
@@ -37,31 +36,50 @@
 /***********************************************************************
  *           SysAllocString         [OLE2DISP.2]
  */
-BSTR WINAPI SysAllocString(char *in)
+BSTR16 WINAPI SysAllocString16(LPOLESTR16 in)
 {
-	BSTR out=BSTR_AllocBytes(strlen(in)+1);
+	BSTR16 out=BSTR_AllocBytes(strlen(in)+1);
 	if(!out)return 0;
 	strcpy(BSTR_GetAddr(out),in);
 	return out;
 }
 
 /***********************************************************************
+ *           SysAllocString         [OLEAUT32.2]
+ */
+BSTR32 WINAPI SysAllocString32(LPOLESTR32 in)
+{
+	return HEAP_strdupW(GetProcessHeap(),0,in);
+}
+
+/***********************************************************************
  *           SysReAllocString       [OLE2DISP.3]
  */
-int WINAPI SysReAllocString(BSTR *old,char *in)
+INT16 WINAPI SysReAllocString16(LPBSTR16 old,LPOLESTR16 in)
 {
-	BSTR new=SysAllocString(in);
+	BSTR16 new=SysAllocString16(in);
 	BSTR_Free(*old);
 	*old=new;
 	return 1;
 }
 
 /***********************************************************************
+ *           SysReAllocString       [OLEAUT32.3]
+ */
+INT32 WINAPI SysReAllocString32(LPBSTR32 old,LPOLESTR32 in)
+{
+	BSTR32 new=SysAllocString32(in);
+	HeapFree(GetProcessHeap(),0,*old);
+	*old=new;
+	return 1;
+}
+
+/***********************************************************************
  *           SysAllocStringLen      [OLE2DISP.4]
  */
-BSTR WINAPI SysAllocStringLen(char *in, int len)
+BSTR16 WINAPI SysAllocStringLen16(char *in, int len)
 {
-	BSTR out=BSTR_AllocBytes(len+1);
+	BSTR16 out=BSTR_AllocBytes(len+1);
 	if(!out)return 0;
 	strcpy(BSTR_GetAddr(out),in);
 	return out;
@@ -70,9 +88,9 @@
 /***********************************************************************
  *           SysReAllocStringLen    [OLE2DISP.5]
  */
-int WINAPI SysReAllocStringLen(BSTR *old,char *in,int len)
+int WINAPI SysReAllocStringLen16(BSTR16 *old,char *in,int len)
 {
-	BSTR new=SysAllocStringLen(in,len);
+	BSTR16 new=SysAllocStringLen16(in,len);
 	BSTR_Free(*old);
 	*old=new;
 	return 1;
@@ -81,25 +99,29 @@
 /***********************************************************************
  *           SysFreeString          [OLE2DISP.6]
  */
-void WINAPI SysFreeString(BSTR in)
+void WINAPI SysFreeString16(BSTR16 in)
 {
 	BSTR_Free(in);
 }
 
 /***********************************************************************
+ *           SysFreeString          [OLEAUT32.6]
+ */
+void WINAPI SysFreeString32(BSTR32 in)
+{
+	HeapFree(GetProcessHeap(),0,in);
+}
+
+/***********************************************************************
  *           SysStringLen           [OLE2DISP.7]
  */
-int WINAPI SysStringLen(BSTR str)
+int WINAPI SysStringLen16(BSTR16 str)
 {
 	return strlen(BSTR_GetAddr(str));
 }
 
-OLESTATUS WINAPI CreateDispTypeInfo(
-    INTERFACEDATA * pidata,
-    LCID lcid,
-    LPVOID * * pptinfo) /* ITypeInfo */
-{
-	fprintf(stderr,"CreateDispTypeInfo(%p,%ld,%p),stub\n",pidata,lcid,pptinfo);
+OLESTATUS WINAPI CreateDispTypeInfo(INTERFACEDATA * pidata,LCID lcid,LPVOID/*ITypeInfo*/ * * pptinfo) {
+	FIXME(ole,"(%p,%ld,%p),stub\n",pidata,lcid,pptinfo);
 	return 0;
 }
 
@@ -108,6 +130,6 @@
 ) {
 	char	buf[80];
 	WINE_StringFromCLSID(rclsid,buf);
-	fprintf(stderr,"RegisterActiveObject(%p,%s,0x%08lx,%p),stub\n",punk,buf,dwFlags,pdwRegister);
+	FIXME(ole,"RegisterActiveObject(%p,%s,0x%08lx,%p),stub\n",punk,buf,dwFlags,pdwRegister);
 	return 0;
 }
diff --git a/ole/ole2nls.c b/ole/ole2nls.c
index a0d5608..ec8d038 100644
--- a/ole/ole2nls.c
+++ b/ole/ole2nls.c
@@ -528,120 +528,105 @@
 
     case LANG_En:
     	switch (LCType) {
-LOCVAL(LOCALE_ILANGUAGE,"9")
-LOCVAL(LOCALE_SLANGUAGE,"English")
-LOCVAL(LOCALE_SENGLANGUAGE,"English")
-LOCVAL(LOCALE_SABBREVLANGNAME,"en")
-LOCVAL(LOCALE_SNATIVELANGNAME,"English")
-LOCVAL(LOCALE_ICOUNTRY,"11")
-LOCVAL(LOCALE_SCOUNTRY,"United States")
-LOCVAL(LOCALE_SENGCOUNTRY,"United States")
-LOCVAL(LOCALE_SABBREVCTRYNAME,"US")
-LOCVAL(LOCALE_SNATIVECTRYNAME,"United States")
-LOCVAL(LOCALE_IDEFAULTLANGUAGE,"9")
-LOCVAL(LOCALE_IDEFAULTCOUNTRY,"49")
-LOCVAL(LOCALE_IDEFAULTCODEPAGE,"437")
-/* Dunno
-LOCVAL(LOCALE_IDEFAULTANSICODEPAGE)
-*/
-LOCVAL(LOCALE_SLIST,";")
-LOCVAL(LOCALE_IMEASURE,"0")
-LOCVAL(LOCALE_SDECIMAL,".")
-LOCVAL(LOCALE_STHOUSAND,",")
+LOCVAL(LOCALE_ILANGUAGE, "0409")
+LOCVAL(LOCALE_SLANGUAGE, "English (United States)")
+LOCVAL(LOCALE_SENGLANGUAGE, "English")
+LOCVAL(LOCALE_SABBREVLANGNAME, "ENU")
+LOCVAL(LOCALE_SNATIVELANGNAME, "English")
+LOCVAL(LOCALE_ICOUNTRY, "1")
+LOCVAL(LOCALE_SCOUNTRY, "United States")
+LOCVAL(LOCALE_SENGCOUNTRY, "United States")
+LOCVAL(LOCALE_SABBREVCTRYNAME, "USA")
+LOCVAL(LOCALE_SNATIVECTRYNAME, "United States")
+LOCVAL(LOCALE_IDEFAULTLANGUAGE, "0409")
+LOCVAL(LOCALE_IDEFAULTCOUNTRY, "1")
+LOCVAL(LOCALE_IDEFAULTCODEPAGE, "437")
+LOCVAL(LOCALE_IDEFAULTANSICODEPAGE, "1252")
+LOCVAL(LOCALE_SLIST, ",")
+LOCVAL(LOCALE_IMEASURE, "1")
+LOCVAL(LOCALE_SDECIMAL, ".")
+LOCVAL(LOCALE_STHOUSAND, ",")
 LOCVAL(LOCALE_SGROUPING, "3;0")
-LOCVAL(LOCALE_IDIGITS,"2")
-LOCVAL(LOCALE_ILZERO,"1")
-/*
-LOCVAL(LOCALE_INEGNUMBER)
-Is this "0123456789" ??
-LOCVAL(LOCALE_SNATIVEDIGITS)
-*/
-LOCVAL(LOCALE_SCURRENCY,"DM")
+LOCVAL(LOCALE_IDIGITS, "2")
+LOCVAL(LOCALE_ILZERO, "1")
+LOCVAL(LOCALE_INEGNUMBER, "1")
+LOCVAL(LOCALE_SNATIVEDIGITS, "0123456789")
+LOCVAL(LOCALE_SCURRENCY, "$")
 LOCVAL(LOCALE_SINTLSYMBOL, "USD")
 LOCVAL(LOCALE_SMONDECIMALSEP, ".")
-LOCVAL(LOCALE_SMONTHOUSANDSEP, ".")
+LOCVAL(LOCALE_SMONTHOUSANDSEP, ",")
 LOCVAL(LOCALE_SMONGROUPING, "3;0")
-LOCVAL(LOCALE_ICURRDIGITS,"2")
-LOCVAL(LOCALE_IINTLCURRDIGITS,"2")
-LOCVAL(LOCALE_ICURRENCY,"3")
-LOCVAL(LOCALE_INEGCURR,"8")
-LOCVAL(LOCALE_SDATE,".")
-LOCVAL(LOCALE_STIME,":")
-LOCVAL(LOCALE_SSHORTDATE,"MM/dd/yy")
-LOCVAL(LOCALE_SLONGDATE,"ddd, MMMM d\'th\', yyyy")
+LOCVAL(LOCALE_ICURRDIGITS, "2")
+LOCVAL(LOCALE_IINTLCURRDIGITS, "2")
+LOCVAL(LOCALE_ICURRENCY, "0")
+LOCVAL(LOCALE_INEGCURR, "0")
+LOCVAL(LOCALE_SDATE, "/")
+LOCVAL(LOCALE_STIME, ":")
+LOCVAL(LOCALE_SSHORTDATE, "M/d/yy")
+LOCVAL(LOCALE_SLONGDATE, "dddd, MMMM dd, yyyy")
 LOCVAL(LOCALE_STIMEFORMAT, "h:mm:ss tt")
-LOCVAL(LOCALE_IDATE,"1")
-/*
-LOCVAL(LOCALE_ILDATE)
-*/
-LOCVAL(LOCALE_ITIME,"1")
-/*
-LOCVAL(LOCALE_ITIMEMARKPOSN)
-LOCVAL(LOCALE_ICENTURY)
-*/
-LOCVAL(LOCALE_ITLZERO,"1")
-/*
-LOCVAL(LOCALE_IDAYLZERO)
-LOCVAL(LOCALE_IMONLZERO)
-*/
-LOCVAL(LOCALE_S1159,"AM")
-LOCVAL(LOCALE_S2359,"PM")
-LOCVAL(LOCALE_ICALENDARTYPE,"1")
-/*
-LOCVAL(LOCALE_IOPTIONALCALENDAR)
-LOCVAL(LOCALE_IFIRSTDAYOFWEEK)
-LOCVAL(LOCALE_IFIRSTWEEKOFYEAR)
-*/
-LOCVAL(LOCALE_SDAYNAME1,"Monday")
-LOCVAL(LOCALE_SDAYNAME2,"Tuesday")
-LOCVAL(LOCALE_SDAYNAME3,"Wednesday")
-LOCVAL(LOCALE_SDAYNAME4,"Thursday")
-LOCVAL(LOCALE_SDAYNAME5,"Friday")
-LOCVAL(LOCALE_SDAYNAME6,"Saturday")
-LOCVAL(LOCALE_SDAYNAME7,"Sunday")
-LOCVAL(LOCALE_SABBREVDAYNAME1,"Mon")
-LOCVAL(LOCALE_SABBREVDAYNAME2,"Tue")
-LOCVAL(LOCALE_SABBREVDAYNAME3,"Wed")
-LOCVAL(LOCALE_SABBREVDAYNAME4,"Thu")
-LOCVAL(LOCALE_SABBREVDAYNAME5,"Fri")
-LOCVAL(LOCALE_SABBREVDAYNAME6,"Sat")
-LOCVAL(LOCALE_SABBREVDAYNAME7,"Sun")
-LOCVAL(LOCALE_SMONTHNAME1,"January")
-LOCVAL(LOCALE_SMONTHNAME2,"February")
-LOCVAL(LOCALE_SMONTHNAME3,"March")
-LOCVAL(LOCALE_SMONTHNAME4,"April")
-LOCVAL(LOCALE_SMONTHNAME5,"May")
-LOCVAL(LOCALE_SMONTHNAME6,"June")
-LOCVAL(LOCALE_SMONTHNAME7,"July")
-LOCVAL(LOCALE_SMONTHNAME8,"August")
-LOCVAL(LOCALE_SMONTHNAME9,"September")
-LOCVAL(LOCALE_SMONTHNAME10,"October")
-LOCVAL(LOCALE_SMONTHNAME11,"November")
-LOCVAL(LOCALE_SMONTHNAME12,"December")
-LOCVAL(LOCALE_SMONTHNAME13,"")
-LOCVAL(LOCALE_SABBREVMONTHNAME1,"Jan")
-LOCVAL(LOCALE_SABBREVMONTHNAME2,"Feb")
-LOCVAL(LOCALE_SABBREVMONTHNAME3,"Mar")
-LOCVAL(LOCALE_SABBREVMONTHNAME4,"Apr")
-LOCVAL(LOCALE_SABBREVMONTHNAME5,"May")
-LOCVAL(LOCALE_SABBREVMONTHNAME6,"Jun")
-LOCVAL(LOCALE_SABBREVMONTHNAME7,"Jul")
-LOCVAL(LOCALE_SABBREVMONTHNAME8,"Aug")
-LOCVAL(LOCALE_SABBREVMONTHNAME9,"Sep")
-LOCVAL(LOCALE_SABBREVMONTHNAME10,"Oct")
-LOCVAL(LOCALE_SABBREVMONTHNAME11,"Nov")
-LOCVAL(LOCALE_SABBREVMONTHNAME12,"Dec")
-LOCVAL(LOCALE_SABBREVMONTHNAME13,"")
-LOCVAL(LOCALE_SPOSITIVESIGN,"")
-LOCVAL(LOCALE_SNEGATIVESIGN,"-")
-/*
-LOCVAL(LOCALE_IPOSSIGNPOSN)
-LOCVAL(LOCALE_INEGSIGNPOSN)
-LOCVAL(LOCALE_IPOSSYMPRECEDES)
-LOCVAL(LOCALE_IPOSSEPBYSPACE)
-LOCVAL(LOCALE_INEGSYMPRECEDES)
-LOCVAL(LOCALE_INEGSEPBYSPACE)
-*/
+LOCVAL(LOCALE_IDATE, "0")
+LOCVAL(LOCALE_ILDATE, "0")
+LOCVAL(LOCALE_ITIME, "0")
+LOCVAL(LOCALE_ITIMEMARKPOSN, "0")
+LOCVAL(LOCALE_ICENTURY, "0")
+LOCVAL(LOCALE_ITLZERO, "0")
+LOCVAL(LOCALE_IDAYLZERO, "0")
+LOCVAL(LOCALE_IMONLZERO, "0")
+LOCVAL(LOCALE_S1159, "AM")
+LOCVAL(LOCALE_S2359, "PM")
+LOCVAL(LOCALE_ICALENDARTYPE, "1")
+LOCVAL(LOCALE_IOPTIONALCALENDAR, "0")
+LOCVAL(LOCALE_IFIRSTDAYOFWEEK, "6")
+LOCVAL(LOCALE_IFIRSTWEEKOFYEAR, "0")
+LOCVAL(LOCALE_SDAYNAME1, "Monday")
+LOCVAL(LOCALE_SDAYNAME2, "Tuesday")
+LOCVAL(LOCALE_SDAYNAME3, "Wednesday")
+LOCVAL(LOCALE_SDAYNAME4, "Thursday")
+LOCVAL(LOCALE_SDAYNAME5, "Friday")
+LOCVAL(LOCALE_SDAYNAME6, "Saturday")
+LOCVAL(LOCALE_SDAYNAME7, "Sunday")
+LOCVAL(LOCALE_SABBREVDAYNAME1, "Mon")
+LOCVAL(LOCALE_SABBREVDAYNAME2, "Tue")
+LOCVAL(LOCALE_SABBREVDAYNAME3, "Wed")
+LOCVAL(LOCALE_SABBREVDAYNAME4, "Thu")
+LOCVAL(LOCALE_SABBREVDAYNAME5, "Fri")
+LOCVAL(LOCALE_SABBREVDAYNAME6, "Sat")
+LOCVAL(LOCALE_SABBREVDAYNAME7, "Sun")
+LOCVAL(LOCALE_SMONTHNAME1, "January")
+LOCVAL(LOCALE_SMONTHNAME2, "February")
+LOCVAL(LOCALE_SMONTHNAME3, "March")
+LOCVAL(LOCALE_SMONTHNAME4, "April")
+LOCVAL(LOCALE_SMONTHNAME5, "May")
+LOCVAL(LOCALE_SMONTHNAME6, "June")
+LOCVAL(LOCALE_SMONTHNAME7, "July")
+LOCVAL(LOCALE_SMONTHNAME8, "August")
+LOCVAL(LOCALE_SMONTHNAME9, "September")
+LOCVAL(LOCALE_SMONTHNAME10, "October")
+LOCVAL(LOCALE_SMONTHNAME11, "November")
+LOCVAL(LOCALE_SMONTHNAME12, "December")
+LOCVAL(LOCALE_SMONTHNAME13, "")
+LOCVAL(LOCALE_SABBREVMONTHNAME1, "Jan")
+LOCVAL(LOCALE_SABBREVMONTHNAME2, "Feb")
+LOCVAL(LOCALE_SABBREVMONTHNAME3, "Mar")
+LOCVAL(LOCALE_SABBREVMONTHNAME4, "Apr")
+LOCVAL(LOCALE_SABBREVMONTHNAME5, "May")
+LOCVAL(LOCALE_SABBREVMONTHNAME6, "Jun")
+LOCVAL(LOCALE_SABBREVMONTHNAME7, "Jul")
+LOCVAL(LOCALE_SABBREVMONTHNAME8, "Aug")
+LOCVAL(LOCALE_SABBREVMONTHNAME9, "Sep")
+LOCVAL(LOCALE_SABBREVMONTHNAME10, "Oct")
+LOCVAL(LOCALE_SABBREVMONTHNAME11, "Nov")
+LOCVAL(LOCALE_SABBREVMONTHNAME12, "Dec")
+LOCVAL(LOCALE_SABBREVMONTHNAME13, "")
+LOCVAL(LOCALE_SPOSITIVESIGN, "")
+LOCVAL(LOCALE_SNEGATIVESIGN, "-")
+LOCVAL(LOCALE_IPOSSIGNPOSN, "3")
+LOCVAL(LOCALE_INEGSIGNPOSN, "0")
+LOCVAL(LOCALE_IPOSSYMPRECEDES, "1")
+LOCVAL(LOCALE_IPOSSEPBYSPACE, "0")
+LOCVAL(LOCALE_INEGSYMPRECEDES, "1")
+LOCVAL(LOCALE_INEGSEPBYSPACE, "0")
 	default: found=0;break;
 	}
     break;  /* LANG(En) */
@@ -1005,111 +990,6 @@
 	}
     break;  /* LANG(It) */
 
-    case 0x0409:
-    	switch (LCType) {
-LOCVAL(LOCALE_ILANGUAGE, "0409")
-LOCVAL(LOCALE_SLANGUAGE, "English (United States)")
-LOCVAL(LOCALE_SENGLANGUAGE, "English")
-LOCVAL(LOCALE_SABBREVLANGNAME, "ENU")
-LOCVAL(LOCALE_SNATIVELANGNAME, "English")
-LOCVAL(LOCALE_ICOUNTRY, "1")
-LOCVAL(LOCALE_SCOUNTRY, "United States")
-LOCVAL(LOCALE_SENGCOUNTRY, "United States")
-LOCVAL(LOCALE_SABBREVCTRYNAME, "USA")
-LOCVAL(LOCALE_SNATIVECTRYNAME, "United States")
-LOCVAL(LOCALE_IDEFAULTLANGUAGE, "0409")
-LOCVAL(LOCALE_IDEFAULTCOUNTRY, "1")
-LOCVAL(LOCALE_IDEFAULTCODEPAGE, "437")
-LOCVAL(LOCALE_IDEFAULTANSICODEPAGE, "1252")
-LOCVAL(LOCALE_SLIST, ",")
-LOCVAL(LOCALE_IMEASURE, "1")
-LOCVAL(LOCALE_SDECIMAL, ".")
-LOCVAL(LOCALE_STHOUSAND, ",")
-LOCVAL(LOCALE_SGROUPING, "3;0")
-LOCVAL(LOCALE_IDIGITS, "2")
-LOCVAL(LOCALE_ILZERO, "1")
-LOCVAL(LOCALE_INEGNUMBER, "1")
-LOCVAL(LOCALE_SNATIVEDIGITS, "0123456789")
-LOCVAL(LOCALE_SCURRENCY, "$")
-LOCVAL(LOCALE_SINTLSYMBOL, "USD")
-LOCVAL(LOCALE_SMONDECIMALSEP, ".")
-LOCVAL(LOCALE_SMONTHOUSANDSEP, ",")
-LOCVAL(LOCALE_SMONGROUPING, "3;0")
-LOCVAL(LOCALE_ICURRDIGITS, "2")
-LOCVAL(LOCALE_IINTLCURRDIGITS, "2")
-LOCVAL(LOCALE_ICURRENCY, "0")
-LOCVAL(LOCALE_INEGCURR, "0")
-LOCVAL(LOCALE_SDATE, "/")
-LOCVAL(LOCALE_STIME, ":")
-LOCVAL(LOCALE_SSHORTDATE, "M/d/yy")
-LOCVAL(LOCALE_SLONGDATE, "dddd, MMMM dd, yyyy")
-LOCVAL(LOCALE_STIMEFORMAT, "h:mm:ss tt")
-LOCVAL(LOCALE_IDATE, "0")
-LOCVAL(LOCALE_ILDATE, "0")
-LOCVAL(LOCALE_ITIME, "0")
-LOCVAL(LOCALE_ITIMEMARKPOSN, "0")
-LOCVAL(LOCALE_ICENTURY, "0")
-LOCVAL(LOCALE_ITLZERO, "0")
-LOCVAL(LOCALE_IDAYLZERO, "0")
-LOCVAL(LOCALE_IMONLZERO, "0")
-LOCVAL(LOCALE_S1159, "AM")
-LOCVAL(LOCALE_S2359, "PM")
-LOCVAL(LOCALE_ICALENDARTYPE, "1")
-LOCVAL(LOCALE_IOPTIONALCALENDAR, "0")
-LOCVAL(LOCALE_IFIRSTDAYOFWEEK, "6")
-LOCVAL(LOCALE_IFIRSTWEEKOFYEAR, "0")
-LOCVAL(LOCALE_SDAYNAME1, "Monday")
-LOCVAL(LOCALE_SDAYNAME2, "Tuesday")
-LOCVAL(LOCALE_SDAYNAME3, "Wednesday")
-LOCVAL(LOCALE_SDAYNAME4, "Thursday")
-LOCVAL(LOCALE_SDAYNAME5, "Friday")
-LOCVAL(LOCALE_SDAYNAME6, "Saturday")
-LOCVAL(LOCALE_SDAYNAME7, "Sunday")
-LOCVAL(LOCALE_SABBREVDAYNAME1, "Mon")
-LOCVAL(LOCALE_SABBREVDAYNAME2, "Tue")
-LOCVAL(LOCALE_SABBREVDAYNAME3, "Wed")
-LOCVAL(LOCALE_SABBREVDAYNAME4, "Thu")
-LOCVAL(LOCALE_SABBREVDAYNAME5, "Fri")
-LOCVAL(LOCALE_SABBREVDAYNAME6, "Sat")
-LOCVAL(LOCALE_SABBREVDAYNAME7, "Sun")
-LOCVAL(LOCALE_SMONTHNAME1, "January")
-LOCVAL(LOCALE_SMONTHNAME2, "February")
-LOCVAL(LOCALE_SMONTHNAME3, "March")
-LOCVAL(LOCALE_SMONTHNAME4, "April")
-LOCVAL(LOCALE_SMONTHNAME5, "May")
-LOCVAL(LOCALE_SMONTHNAME6, "June")
-LOCVAL(LOCALE_SMONTHNAME7, "July")
-LOCVAL(LOCALE_SMONTHNAME8, "August")
-LOCVAL(LOCALE_SMONTHNAME9, "September")
-LOCVAL(LOCALE_SMONTHNAME10, "October")
-LOCVAL(LOCALE_SMONTHNAME11, "November")
-LOCVAL(LOCALE_SMONTHNAME12, "December")
-LOCVAL(LOCALE_SMONTHNAME13, "")
-LOCVAL(LOCALE_SABBREVMONTHNAME1, "Jan")
-LOCVAL(LOCALE_SABBREVMONTHNAME2, "Feb")
-LOCVAL(LOCALE_SABBREVMONTHNAME3, "Mar")
-LOCVAL(LOCALE_SABBREVMONTHNAME4, "Apr")
-LOCVAL(LOCALE_SABBREVMONTHNAME5, "May")
-LOCVAL(LOCALE_SABBREVMONTHNAME6, "Jun")
-LOCVAL(LOCALE_SABBREVMONTHNAME7, "Jul")
-LOCVAL(LOCALE_SABBREVMONTHNAME8, "Aug")
-LOCVAL(LOCALE_SABBREVMONTHNAME9, "Sep")
-LOCVAL(LOCALE_SABBREVMONTHNAME10, "Oct")
-LOCVAL(LOCALE_SABBREVMONTHNAME11, "Nov")
-LOCVAL(LOCALE_SABBREVMONTHNAME12, "Dec")
-LOCVAL(LOCALE_SABBREVMONTHNAME13, "")
-LOCVAL(LOCALE_SPOSITIVESIGN, "")
-LOCVAL(LOCALE_SNEGATIVESIGN, "-")
-LOCVAL(LOCALE_IPOSSIGNPOSN, "3")
-LOCVAL(LOCALE_INEGSIGNPOSN, "0")
-LOCVAL(LOCALE_IPOSSYMPRECEDES, "1")
-LOCVAL(LOCALE_IPOSSEPBYSPACE, "0")
-LOCVAL(LOCALE_INEGSYMPRECEDES, "1")
-LOCVAL(LOCALE_INEGSEPBYSPACE, "0")
-	default: found=0;break;
-	}
-    break; /* LANG(0x0409) (U.S. English) */
-
     case 0x0809:
     	switch (LCType) {
 LOCVAL(LOCALE_ILANGUAGE, "0809")
@@ -1879,7 +1759,7 @@
 }
 
 /***********************************************************************
- *           SetLocalInfoA       (KERNEL32.499)
+ *           SetLocaleInfoA       [KERNEL32.499]
  */
 BOOL16 WINAPI SetLocaleInfoA(DWORD lcid, DWORD lctype, LPCSTR data)
 {
@@ -1888,7 +1768,7 @@
 }
 
 /***********************************************************************
- *           IsValidLocale       (KERNEL32.361)
+ *           IsValidLocale       [KERNEL32.361]
  */
 BOOL32 WINAPI IsValidLocale(LCID lcid,DWORD flags)
 {
@@ -1897,7 +1777,7 @@
 }
 
 /***********************************************************************
- *              EnumSystemLocales32W                (KERNEL32.93)
+ *              EnumSystemLocales32W                [KERNEL32.93]
  */
 BOOL32 WINAPI EnumSystemLocales32W( LOCALE_ENUMPROC32W lpfnLocaleEnum,
                                     DWORD flags )
@@ -1940,7 +1820,7 @@
 }
 
 /***********************************************************************
- *              EnumSystemLocales32A                (KERNEL32.92)
+ *              EnumSystemLocales32A                [KERNEL32.92]
  */
 BOOL32 WINAPI EnumSystemLocales32A(LOCALE_ENUMPROC32A lpfnLocaleEnum,
                                    DWORD flags)
@@ -1975,7 +1855,7 @@
 }
 
 /***********************************************************************
- *              GetStringTypeA                (OLE2NLS.7)
+ *              GetStringTypeA                [OLE2NLS.7]
  */
 BOOL16 WINAPI GetStringType16(LCID locale,DWORD dwInfoType,LPCSTR src,
                               INT16 cchSrc,LPWORD chartype)
@@ -1983,7 +1863,7 @@
 	return GetStringTypeEx32A(locale,dwInfoType,src,cchSrc,chartype);
 }
 /***********************************************************************
- *              GetStringTypeA                (KERNEL32.277)
+ *              GetStringTypeA                [KERNEL32.277]
  */
 BOOL32 WINAPI GetStringType32A(LCID locale,DWORD dwInfoType,LPCSTR src,
                                INT32 cchSrc,LPWORD chartype)
@@ -1991,7 +1871,7 @@
 	return GetStringTypeEx32A(locale,dwInfoType,src,cchSrc,chartype);
 }
 /***********************************************************************
- *              GetStringTypeExA                (KERNEL32.276)
+ *              GetStringTypeExA                [KERNEL32.276]
  */
 BOOL32 WINAPI GetStringTypeEx32A(LCID locale,DWORD dwInfoType,LPCSTR src,
                                  INT32 cchSrc,LPWORD chartype)
@@ -2026,8 +1906,10 @@
 	return TRUE;
 }
 
-/***********************************************************************
- *              GetStringTypeW                (KERNEL32.279)
+/*********************************************************************
+ *  GetStringTypeW [KERNEL32.279]
+ *
+ * NOTES
  * Yes, this is missing LCID locale. MS fault.
  */
 BOOL32 WINAPI GetStringType32W(DWORD dwInfoType,LPCWSTR src,INT32 cchSrc,
@@ -2036,8 +1918,8 @@
 	return GetStringTypeEx32W(0/*defaultlocale*/,dwInfoType,src,cchSrc,chartype);
 }
 
-/***********************************************************************
- *              GetStringTypeW                (KERNEL32.278)
+/*********************************************************************
+ *   GetStringTypeW   [KERNEL32.278]
  * FIXME: unicode chars are assumed chars
  */
 BOOL32 WINAPI GetStringTypeEx32W(LCID locale,DWORD dwInfoType,LPCWSTR src,
@@ -2073,7 +1955,9 @@
 	return TRUE;
 }
 
-/* VerLanguageName				[VER.10] */
+/*****************************************************************
+ * VerLanguageName16   [VER.10] 
+ */
 DWORD WINAPI VerLanguageName16(UINT16 langid,LPSTR langname,UINT16 langnamelen)
 {
 	int	i;
@@ -2098,14 +1982,18 @@
 	return strlen(languages[i].langname);
 }
 
-/* VerLanguageNameA				[VERSION.9] */
+/*****************************************************************
+ * VerLanguageName32A				[VERSION.9] 
+ */
 DWORD WINAPI VerLanguageName32A(UINT32 langid,LPSTR langname,
                                 UINT32 langnamelen)
 {
 	return VerLanguageName16(langid,langname,langnamelen);
 }
 
-/* VerLanguageNameW				[VERSION.10] */
+/*****************************************************************
+ * VerLanguageName32W				[VERSION.10] 
+ */
 DWORD WINAPI VerLanguageName32W(UINT32 langid,LPWSTR langname,
                                 UINT32 langnamelen)
 {
@@ -2207,8 +2095,8 @@
 
 /*****************************************************************
  *
- *  OLE_GetFormatA()
- *  OLE_GetFormatW()
+ *  OLE_GetFormatA() [internal]
+
 
  This function implements stuff for GetDateFormat() and 
  GetTimeFormat().
@@ -2257,7 +2145,7 @@
    const char ** dgfmt = _dgfmt - 1; 
 
    /* report, for debugging */
-   TRACE(ole, "func(%#lx,%#lx, time(d=%d,h=%d,m=%d,s=%d), fmt:\'%s\' (at %p), %p (%9s), len=%d)\n", locale, flags,
+   TRACE(ole, "func(%8lx,%8lx, time(d=%d,h=%d,m=%d,s=%d), fmt:\'%s\' (at %p), %p (%9s), len=%d)\n", locale, flags,
 	 xtime->wDay, xtime->wHour, xtime->wMinute, xtime->wSecond,
 	 format, format, date, date, datelen);
   
@@ -2430,39 +2318,233 @@
    return outpos;
 }
 
+/*  OLE_GetFormatW  [internal]  */
+
 INT32 WINAPI OLE_GetFormatW(LCID locale, DWORD flags,
 			    LPSYSTEMTIME xtime,
 			    LPCWSTR format,
-			    LPWSTR timestr, INT32 timelen)
+			    LPWSTR output, INT32 outlen)
 {
-   FIXME(ole, "(unicode GetDateFormat) STUB\n");
-   return 0;
+   INT32   inpos, outpos;
+   int     count, type, inquote;
+   int     Overflow; /* loop check */
+   int usedate, usetime;
+   WCHAR   buf[40];
+   int     buflen;
+   char    abuf[40];
+   WCHAR   arg0[] = {0}, arg1[] = {'%','d',0};
+   WCHAR   arg2[] = {'%','0','2','d',0};
+   WCHAR  *argarr[] = {arg0, arg1, arg2};
+   int     datevars, timevars;
+
+   /* make a debug report */
+   lstrcpynWtoA(abuf, format, sizeof(format));
+   TRACE(ole, "args: %8lx, %8lx, time(d=%d,h=%d,m=%d,s=%d), fmt:\'%s\' (at %p), %p with max len %d\n",
+	 locale, flags, 
+	 xtime->wDay, xtime->wHour, xtime->wMinute, xtime->wSecond,
+	 abuf, format, output, outlen);
+   
+
+   /* initialize state variables */
+   inpos = outpos = 0;
+   count = 0;
+   inquote = Overflow = 0;
+   /* this is really just a sanity check */
+   output[0] = buf[0] = 0;
+   abuf[0] = '\0';
+   /* for compatibility with official Windows behavior */
+   usedate = flags & DATE_DATEVARSONLY;
+   usetime = flags & TIME_TIMEVARSONLY;
+   
+   /* this loop is the core of the function */
+   for (inpos = 0; /* we have several break points */ ; inpos++) {
+      if (inquote) {
+	 if (format[inpos] == (WCHAR) '\'') {
+	    if (format[inpos+1] == '\'') {
+	       inpos++;
+	       output[outpos++] = '\'';
+	    } else {
+	       inquote = 0;
+	       continue;
+	    }
+	 } else if (format[inpos] == 0) {
+	    output[outpos++] = 0;
+	    if (outpos > outlen) Overflow = 1;
+	    break;  /*  normal exit (within a quote) */
+	 } else {
+	    output[outpos++] = format[inpos]; /* copy input */
+	    if (outpos > outlen) {
+	       Overflow = 1;
+	       output[outpos-1] = 0; 
+	       break;
+	    }
+	 }
+      } else if (  (count && (format[inpos] != type))
+		   || ( (count==4 && type =='y') ||
+			(count==4 && type =='M') ||
+			(count==4 && type =='d') ||
+			(count==2 && type =='g') ||
+			(count==2 && type =='h') ||
+			(count==2 && type =='H') ||
+			(count==2 && type =='m') ||
+			(count==2 && type =='s') ||
+			(count==2 && type =='t') )  ) {
+	 if        (type == 'd') {
+	    if        (count == 3) {
+	       GetLocaleInfo32W(locale,
+			     LOCALE_SDAYNAME1 + xtime->wDayOfWeek -1,
+			     buf, sizeof(buf)/sizeof(WCHAR) );
+	    } else if (count == 3) {
+	       GetLocaleInfo32W(locale,
+				LOCALE_SABBREVDAYNAME1 +
+				xtime->wDayOfWeek -1,
+				buf, sizeof(buf)/sizeof(WCHAR) );
+	    } else {
+	       wsnprintf32W(buf, 5, argarr[count], xtime->wDay );
+	    };
+	 } else if (type == 'M') {
+	    if        (count == 4) {
+	       GetLocaleInfo32W(locale,  LOCALE_SMONTHNAME1 +
+				xtime->wMonth -1, buf,
+				sizeof(buf)/sizeof(WCHAR) );
+	    } else if (count == 3) {
+	       GetLocaleInfo32W(locale,  LOCALE_SABBREVMONTHNAME1 +
+				xtime->wMonth -1, buf,
+				sizeof(buf)/sizeof(WCHAR) );
+	    } else {
+	       wsnprintf32W(buf, 5, argarr[count], xtime->wMonth);
+	    }
+	 } else if (type == 'y') {
+	    if        (count == 4) {
+	       wsnprintf32W(buf, 6, argarr[1] /* "%d" */,
+			 xtime->wYear);
+	    } else if (count == 3) {
+	       lstrcpynAtoW(buf, "yyy", 5);
+	    } else {
+	       wsnprintf32W(buf, 6, argarr[count],
+			    xtime->wYear % 100);
+	    }
+	 } else if (type == 'g') {
+	    if        (count == 2) {
+	       FIXME(ole, "LOCALE_ICALENDARTYPE unimplemented\n");
+	       lstrcpynAtoW(buf, "AD", 5);
+	    } else {
+	       /* Win API sez we copy it verbatim */
+	       lstrcpynAtoW(buf, "g", 5);
+	    }
+	 } else if (type == 'h') {
+	    /* hours 1:00-12:00 --- is this right? */
+	    wsnprintf32W(buf, 5, argarr[count], 
+			 (xtime->wHour-1)%12 +1);
+	 } else if (type == 'H') {
+	    wsnprintf32W(buf, 5, argarr[count], 
+			 xtime->wHour);
+	 } else if (type == 'm') {
+	    wsnprintf32W(buf, 5, argarr[count],
+			 xtime->wMinute);
+	 } else if (type == 's') {
+	    wsnprintf32W(buf, 5, argarr[count],
+			 xtime->wSecond);
+	 } else if (type == 't') {
+	    GetLocaleInfo32W(locale, (xtime->wHour < 12) ?
+			     LOCALE_S1159 : LOCALE_S2359,
+			     buf, sizeof(buf) );
+	    if        (count == 1) {
+	       buf[1] = 0;
+	    }
+}
+
+	 /* no matter what happened,  we need to check this next 
+	    character the next time we loop through */
+	 inpos--;
+
+	 /* cat buf onto the output */
+	 outlen = lstrlen32W(buf);
+	 if (outpos + buflen < outlen) {
+	    output[outpos] = 0;  /* a "hook" for strcat */
+	    lstrcat32W(output, buf);
+	    outpos += buflen;
+	 } else {
+	    output[outpos] = 0;
+	    lstrcatn32W(output, buf, outlen - outpos);
+	    output[outlen - 1] = 0;
+	    Overflow = 1;
+	    break; /* Abnormal exit */
+	 }
+
+	 /* reset the variables we used this time */
+	 count = 0;
+	 type = '\0';
+      } else if (format[inpos] == 0) {
+	 /* we can't check for this at the beginning,  because that 
+	 would keep us from printing a format spec that ended the 
+	 string */
+	 output[outpos] = 0;
+	 break;  /*  NORMAL EXIT  */
+      } else if (count) {
+	 /* how we keep track of the middle of a format spec */
+	 count++;
+	 continue;
+      } else if ( (datevars && (format[inpos]=='d' ||
+				format[inpos]=='M' ||
+				format[inpos]=='y' ||
+				format[inpos]=='g')  ) ||
+		  (timevars && (format[inpos]=='H' ||
+				format[inpos]=='h' ||
+				format[inpos]=='m' ||
+				format[inpos]=='s' ||
+				format[inpos]=='t') )    ) {
+	 type = format[inpos];
+	 count = 1;
+	 continue;
+      } else if (format[inpos] == '\'') {
+	 inquote = 1;
+	 continue;
+      } else {
+	 /* unquoted literals */
+	 output[outpos++] = format[inpos];
+      }
+   }
+
+   if (Overflow) {
+      SetLastError(ERROR_INSUFFICIENT_BUFFER);
+      WARN(ole, " buffer overflow\n");
+   };
+
+   /* final string terminator and sanity check */
+   outpos++;
+   if (outpos > outlen-1) outpos = outlen-1;
+   output[outpos] = '0';
+
+   lstrcpynWtoA(abuf, output, sizeof(abuf) );
+   TRACE(ole, " returning string \'%s\'\n", abuf);
+	
+   return (!Overflow) ? outlen : 0;
    
 }
 
 
 /*****************************************************************
+ *  GetDateFormat32A() [KERNEL32.310] Makes an ASCII string of the date
  *
- *  GetDateFormat32A()
-
-  This function uses format to format the date,  or,  if format
-  is NULL, uses the default for the locale.  format is a string
-  of literal fields and characters as follows:
-
-  d    single-digit (no leading zero) day (of month)
-  dd   two-digit day (of month)
-  ddd  short day-of-week name
-  dddd long day-of-week name
-  M    single-digit month
-  MM   two-digit month
-  MMM  short month name
-  MMMM full month name
-  y    two-digit year, no leading 0
-  yy   two-digit year
-  yyyy four-digit year
-  gg   era string
-
- * ***********************/
+ * This function uses format to format the date,  or,  if format
+ * is NULL, uses the default for the locale.  format is a string
+ * of literal fields and characters as follows:
+ *
+ * - d    single-digit (no leading zero) day (of month)
+ * - dd   two-digit day (of month)
+ * - ddd  short day-of-week name
+ * - dddd long day-of-week name
+ * - M    single-digit month
+ * - MM   two-digit month
+ * - MMM  short month name
+ * - MMMM full month name
+ * - y    two-digit year, no leading 0
+ * - yy   two-digit year
+ * - yyyy four-digit year
+ * - gg   era string
+ *
+ */
 
 INT32 WINAPI GetDateFormat32A(LCID locale,DWORD flags,
 			      LPSYSTEMTIME xtime,
@@ -2521,11 +2603,11 @@
 }
 
 /* ****************************************************************
- *  GetDateFormat32W()
-
+ * GetDateFormat32W() [KERNEL32.311] Makes a Unicode string of the date
+ *
  * Acts the same as GetDateFormat32A(),  except that it's Unicode.
  * Accepts & returns sizes as counts of Unicode characters.
-
+ *
  */
 INT32 WINAPI GetDateFormat32W(LCID locale,DWORD flags,
 			      LPSYSTEMTIME xtime,
@@ -2534,37 +2616,67 @@
 {
    short datearr[] = {'1','9','9','4','-','1','-','1',0};
 
-   FIXME(ole, "STUB\n");   
+   FIXME(ole, "STUB (should call OLE_GetFormatW)\n");   
    lstrcpyn32W(date, datearr, datelen);
    return (  datelen < 9) ? datelen : 9;
    
    
 }
 
+
+/**************************************************************************
+ *              GetNumberFormat32A	(KERNEL32.355)
+ */
+INT32 WINAPI GetNumberFormat32A(LCID locale, DWORD dwflags,
+			       LPCSTR lpvalue,  char *lpFormat,
+			       LPSTR lpNumberStr, int cchNumber)
+/* NOTE: type of lpFormat should be CONST NUMBERFORMAT */
+
+{
+ int n;
+
+ FIXME(file,"%s: stub, no reformating done\n",lpvalue);
+
+ n = strlen(lpvalue);
+ if (cchNumber) { 
+   strncpy(lpNumberStr,lpvalue,cchNumber);
+   if (cchNumber <= n) {
+     lpNumberStr[cchNumber-1] = 0;
+     n = cchNumber-1;
+   }
+ }
+ return n;
+}
+ 
+
+
 /*****************************************************************
  *
- * GetTimeFormat32A() 
-
- Formats date according to format,  or locale default if format is
- NULL. The format consists of literal characters and fields as follows:
-
- h  hours with no leading zero (12-hour)
- hh hours with full two digits
- H  hours with no leading zero (24-hour)
- HH hours with full two digits
- m  minutes with no leading zero
- mm minutes with full two digits
- s  seconds with no leading zero
- ss seconds with full two digits
- t  time marker (A or P)
- tt time marker (AM, PM)
-
+ * GetTimeFormat32A() [KERNEL32.422] Makes an ASCII string of the time
+ *
+ * Formats date according to format,  or locale default if format is
+ * NULL. The format consists of literal characters and fields as follows:
+ *
+ * h  hours with no leading zero (12-hour)
+ * hh hours with full two digits
+ * H  hours with no leading zero (24-hour)
+ * HH hours with full two digits
+ * m  minutes with no leading zero
+ * mm minutes with full two digits
+ * s  seconds with no leading zero
+ * ss seconds with full two digits
+ * t  time marker (A or P)
+ * tt time marker (AM, PM)
+ *
  */
 
-INT32 WINAPI GetTimeFormat32A(LCID locale,DWORD flags,
-			      LPSYSTEMTIME xtime,
-			      LPCSTR format, 
-			      LPSTR timestr,INT32 timelen) 
+INT32 WINAPI 
+GetTimeFormat32A(LCID locale,        /* in  */
+		 DWORD flags,        /* in  */
+		 LPSYSTEMTIME xtime, /* in  */ 
+		 LPCSTR format,      /* in  */
+		 LPSTR timestr,      /* out */
+		 INT32 timelen       /* in  */) 
 {
    LPCSTR realformat;
    char fmt_buf[40];
@@ -2585,40 +2697,78 @@
    if (!locale) {
       locale = GetSystemDefaultLCID();
    }
-
-
    return OLE_GetFormatA(locale, flags, xtime, realformat, timestr, timelen);
-
 }
 
+
 /* ****************************************************************
- *  GetTimeFormat32W()
+ *  GetTimeFormat32W()  [KERNEL32.423] Makes a Unicode string of the time
  * 
+
  *
  */
 
-INT32 WINAPI GetTimeFormat32W(LCID locale,DWORD flags,
+INT32 WINAPI 
+GetTimeFormat32W(LCID locale,DWORD flags,
 			      LPSYSTEMTIME xtime,
 			      LPCWSTR format, 
 			      LPWSTR timestr,INT32 timelen) 
 {
-   char buf[40];
+   char debugbuf[40];
+   WCHAR buf[20];
+   LPCWSTR realformat;
+   SYSTEMTIME t;
+   LPSYSTEMTIME realtime;
+   WCHAR * fmt_buf = NULL;
+   int fmt_buf_size = 0; /* units of WCHARs */
+   INT32 retval;
    
-   lstrcpynWtoA(buf, format, (sizeof(buf))/2);
-   
+   lstrcpynWtoA(debugbuf, format, (sizeof(buf))/2);
    TRACE(ole, "GetTimeFormatW len %d flags 0x%lX format >%s<\n",
-		timelen, flags, buf);
-   FIXME(ole, "STUB");
-   SetLastError(ERROR_INSUFFICIENT_BUFFER);
-   return 0;
+		timelen, flags, debugbuf);
 
+   /* Enforce the Windows behavior */
+   flags |= ~LOCALE_TIMEDATEBOTH;
+   flags |= TIME_TIMEVARSONLY;
 
+   /* take care of the format or locale not being given */
+   if (format) {
+      realformat = format;
+   } else if (locale) {
+      /* allocate memory */
+      fmt_buf = malloc((fmt_buf_size+=7) * sizeof(WCHAR));
+      if (!fmt_buf) {
+	 SetLastError(ERROR_INSUFFICIENT_BUFFER);
+	 WARN(ole, "could not allocate %d chars of memory\n", fmt_buf_size); 
+	 return 0;
+      };
+      while(!GetLocaleInfo32W(locale, LOCALE_STIMEFORMAT,
+			      fmt_buf, fmt_buf_size)) {
+	 fmt_buf = realloc(fmt_buf, 
+			   (fmt_buf_size += 10) * sizeof(WCHAR));
+	 if (!fmt_buf) {
+	    SetLastError(ERROR_OUTOFMEMORY);
+	    WARN(ole, "could not allocate %d chars of memory\n", fmt_buf_size); 
+	    return 0;
+	 };
+      };
+      realformat = fmt_buf;
+   } else {
+      FIXME(ole,  "caller gave no locale,  no format;  what should we do?\n");
+      SetLastError(ERROR_BAD_FORMAT);
+   };
+   if (!locale) {
+      locale = GetSystemDefaultLCID();
 }
 
+   realtime = xtime;
+   if (!realtime) {
+      realtime = &t;
+      GetSystemTime(realtime);
+   };
 
 
-
-
-
-
-
+   retval = OLE_GetFormatW(locale, flags, realtime, realformat, timestr,  timelen);
+   if (fmt_buf) free(fmt_buf);
+   return retval;
+}
diff --git a/ole/storage.c b/ole/storage.c
index 19f4fbd..d7fcdc6 100644
--- a/ole/storage.c
+++ b/ole/storage.c
@@ -54,12 +54,12 @@
 STORAGE_get_big_block(HFILE32 hf,int n,BYTE *block) {
 	assert(n>=-1);
 	if (-1==_llseek32(hf,(n+1)*BIGSIZE,SEEK_SET)) {
-		fprintf(stderr,"STORAGE_get_big_block: seek failed (%ld)\n",GetLastError());
+		WARN(ole," seek failed (%ld)\n",GetLastError());
 		return FALSE;
 	}
 	assert((n+1)*BIGSIZE==_llseek32(hf,0,SEEK_CUR));
 	if (BIGSIZE!=_lread32(hf,block,BIGSIZE)) {
-		fprintf(stderr,"STORAGE_get_big_block(%d): read didn't (%ld)\n",n,GetLastError());
+		WARN(ole,"(block size %d): read didn't read (%ld)\n",n,GetLastError());
 		assert(0);
 		return FALSE;
 	}
@@ -70,12 +70,12 @@
 STORAGE_put_big_block(HFILE32 hf,int n,BYTE *block) {
 	assert(n>=-1);
 	if (-1==_llseek32(hf,(n+1)*BIGSIZE,SEEK_SET)) {
-		fprintf(stderr,"STORAGE_put_big_block: seek failed (%ld)\n",GetLastError());
+		WARN(ole," seek failed (%ld)\n",GetLastError());
 		return FALSE;
 	}
 	assert((n+1)*BIGSIZE==_llseek32(hf,0,SEEK_CUR));
 	if (BIGSIZE!=_lwrite32(hf,block,BIGSIZE)) {
-		fprintf(stderr,"STORAGE_put_big_block: write failed (%ld)\n",GetLastError());
+		WARN(ole," write failed (%ld)\n",GetLastError());
 		return FALSE;
 	}
 	return TRUE;
@@ -291,22 +291,22 @@
 	lstrcpyWtoA(name,stde->pps_rawname);
 	if (!stde->pps_sizeofname)
 		return;
-	fprintf(stderr,"name: %s\n",name);
-	fprintf(stderr,"type: %d\n",stde->pps_type);
-	fprintf(stderr,"prev pps: %ld\n",stde->pps_prev);
-	fprintf(stderr,"next pps: %ld\n",stde->pps_next);
-	fprintf(stderr,"dir pps: %ld\n",stde->pps_dir);
-	fprintf(stderr,"guid: %s\n",xguid);
+	DUMP("name: %s\n",name);
+	DUMP("type: %d\n",stde->pps_type);
+	DUMP("prev pps: %ld\n",stde->pps_prev);
+	DUMP("next pps: %ld\n",stde->pps_next);
+	DUMP("dir pps: %ld\n",stde->pps_dir);
+	DUMP("guid: %s\n",xguid);
 	if (stde->pps_type !=2) {
 		time_t	t;
 
 		t = DOSFS_FileTimeToUnixTime(&(stde->pps_ft1),NULL);
-		fprintf(stderr,"ts1: %s\n",ctime(&t));
+		DUMP("ts1: %s\n",ctime(&t));
 		t = DOSFS_FileTimeToUnixTime(&(stde->pps_ft2),NULL);
-		fprintf(stderr,"ts2: %s\n",ctime(&t));
+		DUMP("ts2: %s\n",ctime(&t));
 	}
-	fprintf(stderr,"startblock: %ld\n",stde->pps_sb);
-	fprintf(stderr,"size: %ld\n",stde->pps_size);
+	DUMP("startblock: %ld\n",stde->pps_sb);
+	DUMP("size: %ld\n",stde->pps_size);
 }
 
 static BOOL32 
@@ -585,7 +585,7 @@
 	char    xrefiid[50];
 
 	WINE_StringFromCLSID((LPCLSID)refiid,xrefiid);
-	TRACE(relay,"(%p)->QueryInterface(%s,%p)\n",this,xrefiid,obj);
+	TRACE(relay,"(%p)->(%s,%p)\n",this,xrefiid,obj);
 	if (!memcmp(&IID_IUnknown,refiid,sizeof(IID_IUnknown))) {
 		*obj = this;
 		return 0;
@@ -613,7 +613,7 @@
 HRESULT WINAPI IStream16_Seek(
 	LPSTREAM16 this,LARGE_INTEGER offset,DWORD whence,ULARGE_INTEGER *newpos
 ) {
-	TRACE(relay,"(%p)->Seek([%ld.%ld],%ld,%p)\n",this,offset.HighPart,offset.LowPart,whence,newpos);
+	TRACE(relay,"(%p)->([%ld.%ld],%ld,%p)\n",this,offset.HighPart,offset.LowPart,whence,newpos);
 
 	switch (whence) {
 	/* unix SEEK_xx should be the same as win95 ones */
@@ -657,7 +657,7 @@
 	ULONG	*bytesread=pcbRead,xxread;
 	int	blocknr;
 
-	TRACE(relay,"(%p)->Read(%p,%ld,%p)\n",this,pv,cb,pcbRead);
+	TRACE(relay,"(%p)->(%p,%ld,%p)\n",this,pv,cb,pcbRead);
 	if (!pcbRead) bytesread=&xxread;
 	*bytesread = 0;
 
@@ -670,7 +670,7 @@
 			int	cc;
 
 			if (!STORAGE_get_small_block(this->hf,blocknr,block)) {
-				fprintf(stderr,"small block read failed!!!!\n");
+			   WARN(ole,"small block read failed!!!\n");
 				return E_FAIL;
 			}
 			cc = cb; 
@@ -690,7 +690,7 @@
 			int	cc;
 
 			if (!STORAGE_get_big_block(this->hf,blocknr,block)) {
-				fprintf(stderr,"big block read failed!!!!\n");
+				WARN(ole,"big block read failed!!!\n");
 				return E_FAIL;
 			}
 			cc = cb; 
@@ -718,7 +718,7 @@
 	if (!pcbWrite) byteswritten=&xxwritten;
 	*byteswritten = 0;
 
-	TRACE(relay,"(%p)->Write(%p,%ld,%p)\n",this,pv,cb,pcbWrite);
+	TRACE(relay,"(%p)->(%p,%ld,%p)\n",this,pv,cb,pcbWrite);
 	/* do we need to junk some blocks? */
 	newsize	= this->offset.LowPart+cb;
 	oldsize	= this->stde.pps_size;
@@ -1028,7 +1028,7 @@
 	char    xrefiid[50];
 
 	WINE_StringFromCLSID((LPCLSID)refiid,xrefiid);
-	TRACE(relay,"(%p)->QueryInterface(%s,%p)\n",this,xrefiid,obj);
+	TRACE(relay,"(%p)->(%s,%p)\n",this,xrefiid,obj);
 	if (!memcmp(&IID_IUnknown,refiid,sizeof(IID_IUnknown))) {
 		*obj = this;
 		return 0;
@@ -1075,7 +1075,7 @@
 	char    xrefiid[50];
 
 	WINE_StringFromCLSID((LPCLSID)refiid,xrefiid);
-	TRACE(relay,"(%p)->QueryInterface(%s,%p)\n",this,xrefiid,obj);
+	TRACE(relay,"(%p)->(%s,%p)\n",this,xrefiid,obj);
 
 	if (!memcmp(&IID_IUnknown,refiid,sizeof(IID_IUnknown))) {
 		*obj = this;
@@ -1099,13 +1099,13 @@
 HRESULT WINAPI IStorage16_Stat(
         LPSTORAGE16 this,STATSTG *pstatstg, DWORD grfStatFlag
 ) {
-	fprintf(stderr,"IStorage16(%p)->Stat(%p,0x%08lx)\n",
+	TRACE(ole,"(%p)->(%p,0x%08lx)\n",
 		this,pstatstg,grfStatFlag
 	);
 	pstatstg->pwcsName=SEGPTR_GET(SEGPTR_STRDUP_WtoA(this->stde.pps_rawname));
 	pstatstg->type = this->stde.pps_type;
 	pstatstg->cbSize.LowPart = this->stde.pps_size;
-	pstatstg->mtime = this->stde.pps_ft1; /* FIXME */
+	pstatstg->mtime = this->stde.pps_ft1; /* FIXME */ /* why? */
 	pstatstg->atime = this->stde.pps_ft2; /* FIXME */
 	pstatstg->ctime = this->stde.pps_ft2; /* FIXME */
 	pstatstg->grfMode	= 0; /* FIXME */
@@ -1119,7 +1119,7 @@
 HRESULT WINAPI IStorage16_Commit(
         LPSTORAGE16 this,DWORD commitflags
 ) {
-	fprintf(stderr,"IStorage16(%p)->Commit(0x%08lx),STUB!\n",
+	FIXME(ole,"(%p)->(0x%08lx),STUB!\n",
 		this,commitflags
 	);
 	return OLE_OK;
@@ -1132,7 +1132,7 @@
 		WINE_StringFromCLSID(rgiidExclude,xguid);
 	else
 		strcpy(xguid,"<no guid>");
-	fprintf(stderr,"IStorage16(%p)->CopyTo(0x%08lx,%s,%p,%p),stub!\n",
+	FIXME(ole,"IStorage16(%p)->(0x%08lx,%s,%p,%p),stub!\n",
 		this,ciidExclude,xguid,SNB16Exclude,pstgDest
 	);
 	return OLE_OK;
@@ -1151,11 +1151,11 @@
 
 	READ_HEADER;
 
-	fprintf(stderr,"IStorage16(%p)->CreateStorage(%s,0x%08lx,0x%08lx,0x%08lx,%p)\n",
+	TRACE(ole,"(%p)->(%s,0x%08lx,0x%08lx,0x%08lx,%p)\n",
 		this,pwcsName,grfMode,dwStgFormat,reserved2,ppstg
 	);
 	if (grfMode & STGM_TRANSACTED)
-		fprintf(stderr,"IStorage::CreateStorage:We do not support transacted Compound Storage. Using direct mode.\n");
+		FIXME(ole,"We do not support transacted Compound Storage. Using direct mode.\n");
 	_create_istorage16(ppstg);
 	lpstg = (LPSTORAGE16)PTR_SEG_TO_LIN(*ppstg);
 	lpstg->hf		= this->hf;
@@ -1168,7 +1168,7 @@
 		stde.pps_dir = ppsent;
 		x = this->ppsent;
 	} else {
-		/* FIXME: use prev chain too ? */
+		FIXME(ole," use prev chain too ?\n");
 		x=stde.pps_dir;
 		if (1!=STORAGE_get_pps_entry(lpstg->hf,x,&stde))
 			return E_FAIL;
@@ -1203,11 +1203,11 @@
 	int		ppsent,x;
 	struct storage_pps_entry	stde;
 
-	fprintf(stderr,"IStorage16(%p)->CreateStream(%s,0x%08lx,0x%08lx,0x%08lx,%p)\n",
+	TRACE(ole,"(%p)->(%s,0x%08lx,0x%08lx,0x%08lx,%p)\n",
 		this,pwcsName,grfMode,reserved1,reserved2,ppstm
 	);
 	if (grfMode & STGM_TRANSACTED)
-		fprintf(stderr,"IStorage::CreateStream:We do not support transacted Compound Storage. Using direct mode.\n");
+		FIXME(ole,"We do not support transacted Compound Storage. Using direct mode.\n");
 	_create_istream16(ppstm);
 	lpstr = (LPSTREAM16)PTR_SEG_TO_LIN(*ppstm);
 	lpstr->hf		= FILE_Dup(this->hf);
@@ -1251,11 +1251,11 @@
 	WCHAR		name[33];
 	int		newpps;
 
-	TRACE(relay,"(%p)->OpenStorage(%s,%p,0x%08lx,%p,0x%08lx,%p)\n",
+	TRACE(relay,"(%p)->(%s,%p,0x%08lx,%p,0x%08lx,%p)\n",
 		this,pwcsName,pstgPrio,grfMode,snbExclude,reserved,ppstg
 	);
 	if (grfMode & STGM_TRANSACTED)
-		fprintf(stderr,"IStorage::OpenStorage:We do not support transacted Compound Storage. Using direct mode.\n");
+		FIXME(ole,"We do not support transacted Compound Storage. Using direct mode.\n");
 	_create_istorage16(ppstg);
 	lpstg = (LPSTREAM16)PTR_SEG_TO_LIN(*ppstg);
 	lpstg->hf = FILE_Dup(this->hf);
@@ -1281,11 +1281,11 @@
 	WCHAR		name[33];
 	int		newpps;
 
-	TRACE(relay,"(%p)->OpenStream(%s,%p,0x%08lx,0x%08lx,%p)\n",
+	TRACE(relay,"(%p)->(%s,%p,0x%08lx,0x%08lx,%p)\n",
 		this,pwcsName,reserved1,grfMode,reserved2,ppstm
 	);
 	if (grfMode & STGM_TRANSACTED)
-		fprintf(stderr,"IStorage::OpenStream:We do not support transacted Compound Storage. Using direct mode.\n");
+		FIXME(ole,"We do not support transacted Compound Storage. Using direct mode.\n");
 	_create_istream16(ppstm);
 	lpstr = (LPSTREAM16)PTR_SEG_TO_LIN(*ppstm);
 	lpstr->hf = FILE_Dup(this->hf);
@@ -1377,7 +1377,7 @@
 	char    xrefiid[50];
 
 	WINE_StringFromCLSID((LPCLSID)refiid,xrefiid);
-	TRACE(relay,"(%p)->QueryInterface(%s,%p)\n",this,xrefiid,obj);
+	TRACE(relay,"(%p)->(%s,%p)\n",this,xrefiid,obj);
 
 	if (!memcmp(&IID_IUnknown,refiid,sizeof(IID_IUnknown))) {
 		*obj = this;
@@ -1401,7 +1401,7 @@
 HRESULT WINAPI IStorage32_CreateStream(
 	LPSTORAGE32 this,LPCOLESTR32 pwcsName,DWORD grfMode,DWORD reserved1,DWORD reserved2, IStream32 **ppstm
 ) {
-	fprintf(stderr,"IStorage32(%p)->CreateStream(%p,0x%08lx,0x%08lx,0x%08lx,%p)\n",
+	TRACE(ole,"(%p)->(%p,0x%08lx,0x%08lx,0x%08lx,%p)\n",
 		this,pwcsName,grfMode,reserved1,reserved2,ppstm
 	);
 	*ppstm = (IStream32*)HeapAlloc(GetProcessHeap(),0,sizeof(IStream32));
@@ -1414,7 +1414,7 @@
 HRESULT WINAPI IStorage32_OpenStream(
 	LPSTORAGE32 this,LPCOLESTR32 pwcsName, void *reserved1, DWORD grfMode, DWORD reserved2, IStream32 **ppstm
 ) {
-	fprintf(stderr,"IStorage32(%p)->OpenStream(%p,%p,0x%08lx,0x%08lx,%p)\n",
+	TRACE(ole,"(%p)->(%p,%p,0x%08lx,0x%08lx,%p)\n",
 		this,pwcsName,reserved1,grfMode,reserved2,ppstm
 	);
 	*ppstm = (IStream32*)HeapAlloc(GetProcessHeap(),0,sizeof(IStream32));
@@ -1453,13 +1453,13 @@
 	LPSTORAGE16	lpstg;
 	struct storage_pps_entry	stde;
 
-	fprintf(stderr,"StgCreateDocfile(%s,0x%08lx,0x%08lx,%p)\n",
+	TRACE(ole,"(%s,0x%08lx,0x%08lx,%p)\n",
 		pwcsName,grfMode,reserved,ppstgOpen
 	);
 	_create_istorage16(ppstgOpen);
 	hf = CreateFile32A(pwcsName,GENERIC_READ|GENERIC_WRITE,0,NULL,CREATE_NEW,0,0);
 	if (hf==INVALID_HANDLE_VALUE32) {
-		fprintf(stderr,"couldn't open file for storage:%ld\n",GetLastError());
+		WARN(ole,"couldn't open file for storage:%ld\n",GetLastError());
 		return E_FAIL;
 	}
 	lpstg = (LPSTORAGE16)PTR_SEG_TO_LIN(*ppstgOpen);
@@ -1489,7 +1489,7 @@
 OLESTATUS WINAPI StgCreateDocFile32(
 	LPCOLESTR32 pwcsName,DWORD grfMode,DWORD reserved,IStorage32 **ppstgOpen
 ) {
-	fprintf(stderr,"StgCreateDocfile(%p,0x%08lx,0x%08lx,%p)\n",
+	TRACE(ole,"(%p,0x%08lx,0x%08lx,%p)\n",
 		pwcsName,grfMode,reserved,ppstgOpen
 	);
 	*ppstgOpen = (IStorage32*)HeapAlloc(GetProcessHeap(),0,sizeof(IStorage32));
@@ -1503,7 +1503,7 @@
 	OFSTRUCT	ofs;
 	BYTE		magic[24];
 
-	fprintf(stderr,"StgIsStorageFile(%s)",fn);
+	TRACE(ole,"(\'%s\')",fn);
 	hf = OpenFile32(fn,&ofs,OF_SHARE_DENY_NONE);
 	if (hf==HFILE_ERROR32)
 		return STG_E_FILENOTFOUND;
@@ -1527,12 +1527,14 @@
 		_lclose32(hf);
 		return STG_E_OLDFORMAT;
 	}
-	fprintf(stderr," -> Invalid header.\n");
+	WARN(ole," -> Invalid header.\n");
 	_lclose32(hf);
 	return STG_E_INVALIDHEADER;
 }
 
-OLESTATUS WINAPI StgIsStorageFile32(LPCOLESTR32 fn) {
+OLESTATUS WINAPI 
+StgIsStorageFile32(LPCOLESTR32 fn) 
+{
 	LPOLESTR16	xfn = HEAP_strdupWtoA(GetProcessHeap(),0,fn);
 	OLESTATUS	ret = StgIsStorageFile16(xfn);
 
@@ -1551,7 +1553,7 @@
 	LPSTORAGE16	lpstg;
 	struct storage_pps_entry	stde;
 
-	fprintf(stderr,"StgOpenStorage(%s,%p,0x%08lx,%p,%ld,%p)\n",
+	TRACE(ole,"(%s,%p,0x%08lx,%p,%ld,%p)\n",
 		pwcsName,pstgPriority,grfMode,snbExclude,reserved,ppstgOpen
 	);
 	_create_istorage16(ppstgOpen);
@@ -1584,11 +1586,13 @@
 	const OLECHAR32 * pwcsName,IStorage32 *pstgPriority,DWORD grfMode,
 	SNB32 snbExclude,DWORD reserved, IStorage32 **ppstgOpen
 ) {
-	fprintf(stderr,"StgOpenStorage32(%p,%p,0x%08lx,%p,%ld,%p),stub!\n",
-		pwcsName,pstgPriority,grfMode,snbExclude,reserved,ppstgOpen
-	);
+	FIXME(ole,"StgOpenStorage32(%p,%p,0x%08lx,%p,%ld,%p),stub!\n",
+	      pwcsName,pstgPriority,grfMode,snbExclude,reserved,
+	      ppstgOpen);
 	*ppstgOpen = (IStorage32*)HeapAlloc(GetProcessHeap(),0,sizeof(IStorage32));
 	(*ppstgOpen)->ref = 1;
 	(*ppstgOpen)->lpvtbl = &stvt32;
 	return OLE_OK;
 }
+
+
diff --git a/ole/typelib.c b/ole/typelib.c
index 4ad759d..9e529fe 100644
--- a/ole/typelib.c
+++ b/ole/typelib.c
@@ -8,36 +8,115 @@
 #include <string.h>
 #include <assert.h>
 #include "wintypes.h"
+#include "heap.h"
 #include "windows.h"
+#include "winreg.h"
 #include "winerror.h"
 #include "ole.h"
 #include "ole2.h"
+#include "oleauto.h"
 #include "compobj.h"
 #include "debug.h"
 
 /****************************************************************************
  *	QueryPathOfRegTypeLib			(TYPELIB.14)
+ * the path is "Classes\Typelib\<guid>\<major>.<minor>\<lcid>\win16\"
  * RETURNS
  *	path of typelib
  */
 HRESULT WINAPI
-QueryPathOfRegTypeLib(	
+QueryPathOfRegTypeLib16(	
 	REFGUID guid,	/* [in] referenced guid */
 	WORD wMaj,	/* [in] major version */
 	WORD wMin,	/* [in] minor version */
 	LCID lcid,	/* [in] locale id */
-	LPSTR path	/* [out] path of typelib */
+	LPBSTR16 path	/* [out] path of typelib */
 ) {
 	char	xguid[80];
+	char	typelibkey[100],pathname[260];
+	DWORD	plen;
 
-	if (HIWORD(guid))
+	if (HIWORD(guid)) {
 		WINE_StringFromCLSID(guid,xguid);
-	else
+		sprintf(typelibkey,"SOFTWARE\\Classes\\Typelib\\%s\\%d.%d\\%ld\\win16",
+			xguid,wMaj,wMin,lcid&0xff
+		);
+	} else {
 		sprintf(xguid,"<guid 0x%08lx>",(DWORD)guid);
-	FIXME(ole,"(%s,%d,%d,0x%04lx,%p),stub!\n",xguid,wMaj,wMin,lcid,path);
-	return E_FAIL;
+		FIXME(ole,"(%s,%d,%d,0x%04x,%p),can't handle non-string guids.\n",xguid,wMaj,wMin,lcid,path);
+		return E_FAIL;
+	}
+	plen = sizeof(pathname);
+	if (RegQueryValue16(HKEY_LOCAL_MACHINE,typelibkey,pathname,&plen)) {
+		FIXME(ole,"key %s not found\n",typelibkey);
+		return E_FAIL;
+	}
+	*path = SysAllocString16(pathname);
+	return S_OK;
 }
 
+/****************************************************************************
+ *	QueryPathOfRegTypeLib			(OLEAUT32.164)
+ * RETURNS
+ *	path of typelib
+ */
+HRESULT WINAPI
+QueryPathOfRegTypeLib32(	
+	REFGUID guid,	/* [in] referenced guid */
+	WORD wMaj,	/* [in] major version */
+	WORD wMin,	/* [in] minor version */
+	LCID lcid,	/* [in] locale id */
+	LPBSTR32 path	/* [out] path of typelib */
+) {
+	char	xguid[80];
+	char	typelibkey[100],pathname[260];
+	DWORD	plen;
+
+
+	if (HIWORD(guid)) {
+		WINE_StringFromCLSID(guid,xguid);
+		sprintf(typelibkey,"SOFTWARE\\Classes\\Typelib\\%s\\%d.%d\\%ld\\win32",
+			xguid,wMaj,wMin,lcid&0xff
+		);
+	} else {
+		sprintf(xguid,"<guid 0x%08lx>",(DWORD)guid);
+		FIXME(ole,"(%s,%d,%d,0x%04x,%p),stub!\n",xguid,wMaj,wMin,lcid,path);
+		return E_FAIL;
+	}
+	plen = sizeof(pathname);
+	if (RegQueryValue16(HKEY_LOCAL_MACHINE,typelibkey,pathname,&plen)) {
+		FIXME(ole,"key %s not found\n",typelibkey);
+		return E_FAIL;
+	}
+	*path = HEAP_strdupAtoW(GetProcessHeap(),0,pathname);
+	return S_OK;
+}
+
+/******************************************************************************
+ * LoadTypeLib [TYPELIB.3]  Loads and registers a type library
+ *
+ * NOTES
+ *    Docs: OLECHAR FAR* szFile
+ *    Docs: iTypeLib FAR* FAR* pptLib
+ *
+ * RETURNS
+ *    Success: S_OK
+ *    Failure: Status
+ */
+HRESULT WINAPI LoadTypeLib(
+    void *szFile,   /* [in] Name of file to load from */
+    void * *pptLib) /* [out] Pointer to pointer to loaded type library */
+{
+    FIXME(ole, "(%s,%p): stub\n",debugstr_a(szFile),pptLib);
+    return E_FAIL;
+}
+
+
+/****************************************************************************
+ *	OABuildVersion				(TYPELIB.15)
+ * RETURNS
+ *	path of typelib
+ */
 DWORD WINAPI OABuildVersion()
 {
 	return MAKELONG(0xbd3, 0x3);
diff --git a/programs/clock/main.c b/programs/clock/main.c
index 7df6002..5d86501 100644
--- a/programs/clock/main.c
+++ b/programs/clock/main.c
@@ -274,7 +274,7 @@
 	class.hCursor       = LoadCursor (0, IDC_ARROW);
 	class.hbrBackground = GetStockObject (GRAY_BRUSH);
 	class.lpszMenuName  = "\0";
-	class.lpszClassName = (SEGPTR)className;
+	class.lpszClassName = className;
     }
     if (!RegisterClass (&class))
 	return FALSE;
diff --git a/programs/notepad/main.c b/programs/notepad/main.c
index 4b434a2..8cd5fcd 100644
--- a/programs/notepad/main.c
+++ b/programs/notepad/main.c
@@ -149,7 +149,7 @@
 	class.hCursor       = LoadCursor (0, IDC_ARROW);
 	class.hbrBackground = GetStockObject (WHITE_BRUSH);
 	class.lpszMenuName  = 0;
-	class.lpszClassName = (SEGPTR)className;
+	class.lpszClassName = className;
     }
 
     if (!RegisterClass (&class))
diff --git a/programs/progman/dialog.c b/programs/progman/dialog.c
index 76efc95..5157d92 100644
--- a/programs/progman/dialog.c
+++ b/programs/progman/dialog.c
@@ -573,7 +573,7 @@
 {
   LoadString(Globals.hInstance, ids, *p, MAX_STRING_LEN);
   *p += strlen(*p) + 1;
-  lstrcpy(*p, (SEGPTR) filter);
+  lstrcpy(*p, filter);
   *p += strlen(*p) + 1;
   **p = '\0';
 }
diff --git a/programs/progman/grpfile.c b/programs/progman/grpfile.c
index bb4a5e5..01c83de 100644
--- a/programs/progman/grpfile.c
+++ b/programs/progman/grpfile.c
@@ -631,7 +631,7 @@
     {
       PROGRAM *program = LocalLock(hProgram);
       CURSORICONINFO *iconinfo = LocalLock(program->hIcon);
-      SEGPTR XorBits, AndBits;
+      LPVOID XorBits, AndBits;
       INT sizeXor = iconinfo->nHeight * iconinfo->nWidthBytes;
       INT sizeAnd = iconinfo->nHeight * ((iconinfo->nWidth + 15) / 16 * 2);
       DumpIcon(LocalLock(program->hIcon), 0, &XorBits, &AndBits);
diff --git a/programs/winhelp/hlp2sgml.c b/programs/winhelp/hlp2sgml.c
index 2294c85..ba7827a 100644
--- a/programs/winhelp/hlp2sgml.c
+++ b/programs/winhelp/hlp2sgml.c
@@ -264,7 +264,7 @@
   return 0;
 }
 
-LONG _hread32( HFILE hFile, SEGPTR buffer, LONG count )
+LONG _hread32( HFILE hFile, LPVOID buffer, LONG count )
 {
   return fread(buffer, 1, count, file);
 }
diff --git a/relay32/Makefile.in b/relay32/Makefile.in
index 52e1e6a..b42f3c4 100644
--- a/relay32/Makefile.in
+++ b/relay32/Makefile.in
@@ -14,6 +14,7 @@
 	ddraw.spec \
 	dinput.spec \
 	dplay.spec \
+	dplayx.spec \
 	dsound.spec \
 	gdi32.spec \
 	kernel32.spec \
@@ -22,6 +23,7 @@
 	msvfw32.spec \
 	ntdll.spec \
 	ole32.spec \
+	oleaut32.spec \
 	olecli32.spec \
 	olesvr32.spec \
 	shell32.spec \
diff --git a/relay32/advapi32.spec b/relay32/advapi32.spec
index 7c2edcc..53a9508 100644
--- a/relay32/advapi32.spec
+++ b/relay32/advapi32.spec
@@ -23,17 +23,17 @@
 0019 stub ClearEventLogA
 0020 stub ClearEventLogW
 0021 stub CloseEventLog
-0022 stub CloseServiceHandle
-0023 stub ControlService
+0022 stdcall CloseServiceHandle(long) CloseServiceHandle
+0023 stdcall ControlService(long long ptr) ControlService
 0024 stdcall CopySid(long ptr ptr) CopySid
 0025 stub CreatePrivateObjectSecurity
 0026 stub CreateProcessAsUserA
 0027 stub CreateProcessAsUserW
-0028 stub CreateServiceA
+0028 stdcall CreateServiceA(long ptr ptr long long long long ptr ptr ptr ptr ptr ptr) CreateServiceA
 0029 stub CreateServiceW
 0030 stub DeleteAce
-0031 stub DeleteService
-0032 stub DeregisterEventSource
+0031 stdcall DeleteService(long) DeleteService
+0032 stdcall DeregisterEventSource(long) DeregisterEventSource
 0033 stub DestroyPrivateObjectSecurity
 0034 stub DuplicateToken
 0035 stub EnumDependentServicesA
@@ -94,7 +94,7 @@
 0090 stub LookupPrivilegeNameA
 0091 stub LookupPrivilegeNameW
 0092 stdcall LookupPrivilegeValueA(ptr ptr ptr) LookupPrivilegeValue32A
-0093 stub LookupPrivilegeValueW
+0093 stdcall LookupPrivilegeValueW(ptr ptr ptr) LookupPrivilegeValue32W
 0094 stub MakeAbsoluteSD
 0095 stub MakeSelfRelativeSD
 0096 stub MapGenericMask
@@ -111,10 +111,10 @@
 0107 stub OpenEventLogA
 0108 stub OpenEventLogW
 0109 stdcall OpenProcessToken(long long ptr) OpenProcessToken
-0110 stdcall OpenSCManagerA(ptr ptr long) OpenSCManagerA
-0111 stdcall OpenSCManagerW(ptr ptr long) OpenSCManagerW
-0112 stub OpenServiceA
-0113 stub OpenServiceW
+0110 stdcall OpenSCManagerA(ptr ptr long) OpenSCManager32A
+0111 stdcall OpenSCManagerW(ptr ptr long) OpenSCManager32W
+0112 stdcall OpenServiceA(long str long) OpenService32A
+0113 stdcall OpenServiceW(long wstr long) OpenService32W
 0114 stdcall OpenThreadToken(long long long ptr) OpenThreadToken
 0115 stub PrivilegeCheck
 0116 stub PrivilegedServiceAuditAlarmA
@@ -145,7 +145,7 @@
 0141 stdcall RegEnumValueA(long long ptr ptr ptr ptr ptr ptr) RegEnumValue32A
 0142 stdcall RegEnumValueW(long long ptr ptr ptr ptr ptr ptr) RegEnumValue32W
 0143 stdcall RegFlushKey(long) RegFlushKey
-0144 stub RegGetKeySecurity
+0144 stdcall RegGetKeySecurity(long long ptr ptr) RegGetKeySecurity
 0145 stub RegLoadKeyA
 0146 stub RegLoadKeyW
 0147 stub RegNotifyChangeKeyValue
@@ -175,8 +175,8 @@
 0171 stdcall RegSetValueW(long wstr long ptr long) RegSetValue32W
 0172 stub RegUnLoadKeyA
 0173 stub RegUnLoadKeyW
-0174 stub RegisterEventSourceA
-0175 stub RegisterEventSourceW
+0174 stdcall RegisterEventSourceA(ptr ptr) RegisterEventSource32A
+0175 stdcall RegisterEventSourceW(ptr ptr) RegisterEventSource32W
 0176 stub RegisterServiceCtrlHandlerA
 0177 stub RegisterServiceCtrlHandlerW
 0178 stub ReportEventA
@@ -196,10 +196,10 @@
 0192 stub SetServiceStatus
 0193 stub SetThreadToken
 0194 stub SetTokenInformation
-0195 stub StartServiceA
+0195 stdcall StartServiceA(long long ptr) StartService32A
 0196 stdcall StartServiceCtrlDispatcherA(ptr) StartServiceCtrlDispatcher32A
 0197 stdcall StartServiceCtrlDispatcherW(ptr) StartServiceCtrlDispatcher32W
-0198 stub StartServiceW
+0198 stdcall StartServiceW(long long ptr) StartService32W
 0199 stub UnlockServiceDatabase
 0200 stub LsaOpenPolicy
 0201 stub LsaLookupSids
diff --git a/relay32/builtin32.c b/relay32/builtin32.c
index baa32d7..593cc10 100644
--- a/relay32/builtin32.c
+++ b/relay32/builtin32.c
@@ -9,6 +9,7 @@
 #include <string.h>
 #include "builtin32.h"
 #include "module.h"
+#include "heap.h"
 #include "task.h"
 #include "process.h"
 #include "debug.h"
@@ -46,6 +47,7 @@
 extern const BUILTIN32_DESCRIPTOR DDRAW_Descriptor;
 extern const BUILTIN32_DESCRIPTOR DINPUT_Descriptor;
 extern const BUILTIN32_DESCRIPTOR DPLAY_Descriptor;
+extern const BUILTIN32_DESCRIPTOR DPLAYX_Descriptor;
 extern const BUILTIN32_DESCRIPTOR DSOUND_Descriptor;
 extern const BUILTIN32_DESCRIPTOR GDI32_Descriptor;
 extern const BUILTIN32_DESCRIPTOR KERNEL32_Descriptor;
@@ -54,6 +56,7 @@
 extern const BUILTIN32_DESCRIPTOR MSVFW32_Descriptor;
 extern const BUILTIN32_DESCRIPTOR NTDLL_Descriptor;
 extern const BUILTIN32_DESCRIPTOR OLE32_Descriptor;
+extern const BUILTIN32_DESCRIPTOR OLEAUT32_Descriptor;
 extern const BUILTIN32_DESCRIPTOR OLECLI32_Descriptor;
 extern const BUILTIN32_DESCRIPTOR OLESVR32_Descriptor;
 extern const BUILTIN32_DESCRIPTOR SHELL32_Descriptor;
@@ -76,6 +79,7 @@
     { &DDRAW_Descriptor,    NULL, TRUE  },
     { &DINPUT_Descriptor,   NULL, TRUE  },
     { &DPLAY_Descriptor,    NULL, TRUE  },
+    { &DPLAYX_Descriptor,   NULL, TRUE  },
     { &DSOUND_Descriptor,   NULL, TRUE  },
     { &GDI32_Descriptor,    NULL, TRUE  },
     { &KERNEL32_Descriptor, NULL, TRUE  },
@@ -84,6 +88,7 @@
     { &MSVFW32_Descriptor,  NULL, FALSE },
     { &NTDLL_Descriptor,    NULL, TRUE  },
     { &OLE32_Descriptor,    NULL, FALSE },
+    { &OLEAUT32_Descriptor, NULL, FALSE },
     { &OLECLI32_Descriptor, NULL, FALSE },
     { &OLESVR32_Descriptor, NULL, FALSE },
     { &SHELL32_Descriptor,  NULL, TRUE  },
@@ -93,7 +98,7 @@
     { &W32SKRNL_Descriptor, NULL, TRUE  },
     { &WINMM_Descriptor,    NULL, TRUE  },
     { &WINSPOOL_Descriptor, NULL, TRUE  },
-    { &WOW32_Descriptor,    NULL, TRUE },
+    { &WOW32_Descriptor,    NULL, TRUE  },
     { &WSOCK32_Descriptor,  NULL, TRUE  },
     /* Last entry */
     { NULL, NULL, FALSE }
@@ -122,6 +127,7 @@
     LPSTR *names;
     DEBUG_ENTRY_POINT *debug;
     REG_ENTRY_POINT *regs;
+    WINE_MODREF *wm;
     PE_MODREF *pem;
     INT32 i, size;
     BYTE *addr;
@@ -212,7 +218,7 @@
 
     /* Build the exports section data */
 
-    exp->Name                  = (BYTE *)dll->descr->name - addr;  /*??*/
+    exp->Name                  = ((BYTE *)dll->descr->name) - addr;  /*??*/
     exp->Base                  = dll->descr->base;
     exp->NumberOfFunctions     = dll->descr->nb_funcs;
     exp->NumberOfNames         = dll->descr->nb_names;
@@ -276,12 +282,16 @@
             *names = (LPSTR)((BYTE *)dll->descr->names[i] - addr);
 
     /* Create a modref */
+    wm = (WINE_MODREF *)HeapAlloc( pdb->heap, HEAP_ZERO_MEMORY, sizeof(*wm) );
+    wm->type = MODULE32_PE;
+    pem = &(wm->binfmt.pe);
+    wm->module		= (HMODULE32)addr;
+    wm->next		= pdb->modref_list;
+    pdb->modref_list	= wm;
+    wm->modname		= HEAP_strdupA(pdb->heap,0,dll->descr->name);
 
-    pem = (PE_MODREF *)HeapAlloc( pdb->heap, HEAP_ZERO_MEMORY, sizeof(*pem) );
-    pem->module = (HMODULE32)addr;
-    pem->pe_export = exp;
-    pem->next = pdb->modref_list;
-    pdb->modref_list = pem;
+    pem->pe_export	= exp;
+    pem->flags		= PE_MODREF_INTERNAL;
 
     /* Create a Win16 dummy module */
 
diff --git a/relay32/comdlg32.spec b/relay32/comdlg32.spec
index 14de9bd..696d149 100644
--- a/relay32/comdlg32.spec
+++ b/relay32/comdlg32.spec
@@ -5,7 +5,7 @@
  1 stub ChooseColorA
  2 stub ChooseColorW
  3 stdcall ChooseFontA(ptr) ChooseFont32A
- 4 stub ChooseFontW
+ 4 stdcall ChooseFontW(ptr) ChooseFont32W
  5 stdcall CommDlgExtendedError() CommDlgExtendedError
  6 stdcall FindTextA(ptr) FindText32A
  7 stdcall FindTextW(ptr) FindText32W
diff --git a/relay32/crtdll.spec b/relay32/crtdll.spec
index 01274c5..2c4b15d 100644
--- a/relay32/crtdll.spec
+++ b/relay32/crtdll.spec
@@ -137,7 +137,7 @@
 133 stub _heapwalk
 134 stub _hypot
 135 cdecl _initterm(ptr ptr) CRTDLL__initterm
-136 stub _iob
+136 extern _iob CRTDLL_iob
 137 cdecl _isatty(long) CRTDLL__isatty
 138 cdecl _isctype(long long) CRTDLL__isctype
 139 stub _ismbbalnum
diff --git a/relay32/dplayx.spec b/relay32/dplayx.spec
new file mode 100644
index 0000000..7a7cd75
--- /dev/null
+++ b/relay32/dplayx.spec
@@ -0,0 +1,9 @@
+name dplayx
+type win32
+
+  1 stub DirectPlayCreate
+  2 stub DirectPlayEnumerateA
+  3 stub DirectPlayEnumerateW
+  4 stub DirectPlayLobbyCreateA
+  5 stub DirectPlayLobbyCreateW
+  9 stub DirectPlayEnumerate
diff --git a/relay32/dsound.spec b/relay32/dsound.spec
index cfb19a7..f0d79ee 100644
--- a/relay32/dsound.spec
+++ b/relay32/dsound.spec
@@ -4,8 +4,8 @@
 0 stdcall DirectSoundCreate(ptr ptr ptr) DirectSoundCreate
 1 stdcall DirectSoundEnumerateA(ptr ptr) DirectSoundEnumerate32A
 2 stub DirectSoundEnumerateW
-3 stub DllCanUnloadNow
-4 stub DllGetClassObject
+3 stdcall DllCanUnloadNow() DllCanUnloadNow
+4 stdcall DllGetClassObject(ptr ptr ptr) DllGetClassObject
 5 stub DirectSoundCaptureCreate
 6 stub DirectSoundCaptureEnumerateA
 7 stub DirectSoundCaptureEnumerateW
diff --git a/relay32/gdi32.spec b/relay32/gdi32.spec
index a741b2d..a447b8d 100644
--- a/relay32/gdi32.spec
+++ b/relay32/gdi32.spec
@@ -14,7 +14,7 @@
  10 stdcall BitBlt(long long long long long long long long long) BitBlt32
  11 stub CancelDC
  12 stub CheckColorsInGamut
- 13 stub ChoosePixelFormat
+ 13 stdcall ChoosePixelFormat(long ptr) ChoosePixelFormat
  14 stdcall Chord(long long long long long long long long long) Chord32
  15 stdcall CloseEnhMetaFile(long) CloseEnhMetaFile32
  16 stdcall CloseFigure(long) CloseFigure32
@@ -22,7 +22,7 @@
  18 stub ColorMatchToTarget
  19 stdcall CombineRgn(long long long long) CombineRgn32
  20 stub CombineTransform
- 21 stub CopyEnhMetaFileA
+ 21 stdcall CopyEnhMetaFileA(long str) CopyEnhMetaFile32A
  22 stub CopyEnhMetaFileW
  23 stdcall CopyMetaFileA(long str) CopyMetaFile32A
  24 stdcall CopyMetaFileW(long wstr) CopyMetaFile32W
@@ -75,7 +75,7 @@
  68 stdcall DeleteEnhMetaFile(long) DeleteEnhMetaFile
  69 stdcall DeleteMetaFile(long) DeleteMetaFile32
  70 stdcall DeleteObject(long)	DeleteObject32
- 71 stub DescribePixelFormat
+ 71 stdcall DescribePixelFormat(long long long ptr) DescribePixelFormat
  72 stub DeviceCapabilitiesExA
  73 stub DeviceCapabilitiesExW
  74 stub DrawEscape
@@ -92,7 +92,7 @@
  85 stdcall EnumFontsW(long wstr ptr long) EnumFonts32W
  86 stub EnumICMProfilesA
  87 stub EnumICMProfilesW
- 88 stub EnumMetaFile
+ 88 stdcall EnumMetaFile(long long ptr ptr) EnumMetaFile32
  89 stdcall EnumObjects(long long ptr long) EnumObjects32
  90 stdcall EqualRgn(long long) EqualRgn32
  91 stdcall Escape(long long long ptr ptr) Escape32
@@ -179,7 +179,7 @@
 172 stub GetDeviceGammaRamp
 173 stub GetETM
 174 stdcall GetEnhMetaFileA(ptr) GetEnhMetaFile32A
-175 stub GetEnhMetaFileBits
+175 stdcall GetEnhMetaFileBits(long long ptr) GetEnhMetaFileBits
 176 stdcall GetEnhMetaFileDescriptionA(long long ptr) GetEnhMetaFileDescription32A
 177 stub GetEnhMetaFileDescriptionW
 178 stdcall GetEnhMetaFileHeader(long long ptr) GetEnhMetaFileHeader
@@ -202,7 +202,7 @@
 195 stub GetLogColorSpaceW
 196 stdcall GetMapMode(long) GetMapMode32
 197 stdcall GetMetaFileA(str) GetMetaFile32A
-198 stub GetMetaFileBitsEx
+198 stdcall GetMetaFileBitsEx(long long ptr) GetMetaFileBitsEx
 199 stdcall GetMetaFileW(wstr) GetMetaFile32W
 200 stub GetMetaRgn
 201 stub GetMiterLimit
@@ -216,7 +216,7 @@
 209 stdcall GetPaletteEntries(long long long ptr) GetPaletteEntries32
 210 stdcall GetPath(long ptr ptr long) GetPath32
 211 stdcall GetPixel(long long long) GetPixel32
-212 stub GetPixelFormat
+212 stdcall GetPixelFormat(long) GetPixelFormat
 213 stdcall GetPolyFillMode(long) GetPolyFillMode32
 214 stdcall GetROP2(long) GetROP232
 215 stub GetRandomRgn
@@ -272,11 +272,11 @@
 265 stdcall PlayMetaFile(long long) PlayMetaFile32
 266 stdcall PlayMetaFileRecord(long ptr ptr long) PlayMetaFileRecord32
 267 stub PlgBlt
-268 stub PolyBezier
+268 stdcall PolyBezier(long ptr long) PolyBezier32
 269 stub PolyBezierTo
 270 stub PolyDraw
 271 stdcall PolyPolygon(long ptr ptr long) PolyPolygon32
-272 stub PolyPolyline
+272 stdcall PolyPolyline(long ptr ptr long) PolyPolyline32
 273 stub PolyTextOutA
 274 stub PolyTextOutW
 275 stdcall Polygon(long ptr long) Polygon32
@@ -320,7 +320,7 @@
 313 stdcall SetDIBitsToDevice(long long long long long long long long long
                                ptr ptr long) SetDIBitsToDevice32
 314 stub SetDeviceGammaRamp
-315 stub SetEnhMetaFileBits
+315 stdcall SetEnhMetaFileBits(long ptr) SetEnhMetaFileBits
 316 stub SetFontEnumeration
 317 stdcall SetGraphicsMode(long long) SetGraphicsMode
 318 stub SetICMMode
@@ -333,7 +333,7 @@
 325 stub SetMiterLimit
 326 stdcall SetPaletteEntries(long long long ptr) SetPaletteEntries32
 327 stdcall SetPixel(long long long long) SetPixel32
-328 stub SetPixelFormat
+328 stdcall SetPixelFormat(long long ptr) SetPixelFormat
 329 stdcall SetPixelV(long long long long) SetPixelV32
 330 stdcall SetPolyFillMode(long long) SetPolyFillMode32
 331 stdcall SetROP2(long long) SetROP232
@@ -361,7 +361,7 @@
                           ptr ptr long long) StretchDIBits32
 352 stub StrokeAndFillPath
 353 stub StrokePath
-354 stub SwapBuffers
+354 stdcall SwapBuffers(long) SwapBuffers
 355 stdcall TextOutA(long long long str long) TextOut32A
 356 stdcall TextOutW(long long long wstr long) TextOut32W
 357 stub UnloadNetworkFonts
diff --git a/relay32/kernel32.spec b/relay32/kernel32.spec
index b4cbeb2..5a996b4 100644
--- a/relay32/kernel32.spec
+++ b/relay32/kernel32.spec
@@ -175,8 +175,8 @@
 161 stdcall CreateFileW(wstr long long ptr long long long) CreateFile32W
 162 stub CreateIoCompletionPort
 163 stub CreateKernelThread
-164 stub CreateMailslotA
-165 stub CreateMailslotW
+164 stdcall CreateMailslotA(ptr long long ptr) CreateMailslot32A
+165 stdcall CreateMailslotW(ptr long long ptr) CreateMailslot32W
 166 stdcall CreateMutexA(ptr long str) CreateMutex32A
 167 stdcall CreateMutexW(ptr long wstr) CreateMutex32W
 168 stdcall CreateNamedPipeA(str long long long long long long ptr) CreateNamedPipeA
@@ -252,9 +252,9 @@
 238 stdcall FileTimeToDosDateTime(ptr ptr ptr) FileTimeToDosDateTime
 239 stdcall FileTimeToLocalFileTime(ptr ptr) FileTimeToLocalFileTime
 240 stdcall FileTimeToSystemTime(ptr ptr) FileTimeToSystemTime
-241 stub FillConsoleOutputAttribute
-242 stub FillConsoleOutputCharacterA
-243 stub FillConsoleOutputCharacterW
+241 stdcall FillConsoleOutputAttribute(long long long long ptr) FillConsoleOutputAttribute
+242 stdcall FillConsoleOutputCharacterA(long long long long ptr) FillConsoleOutputCharacterA
+243 stdcall FillConsoleOutputCharacterW(long long long long ptr) FillConsoleOutputCharacterW
 244 stdcall FindAtomA(str) FindAtom32A
 245 stdcall FindAtomW(wstr) FindAtom32W
 247 stub FindCloseChangeNotification
@@ -302,8 +302,8 @@
 288 stdcall GetCommTimeouts(long ptr) GetCommTimeouts
 289 stdcall GetCommandLineA() GetCommandLine32A
 290 stdcall GetCommandLineW() GetCommandLine32W
-291 stub GetCompressedFileSizeA
-292 stub GetCompressedFileSizeW
+291 stdcall GetCompressedFileSizeA(long ptr) GetCompressedFileSize32A
+292 stdcall GetCompressedFileSizeW(long ptr) GetCompressedFileSize32W
 293 stdcall GetComputerNameA(ptr ptr) GetComputerName32A
 294 stdcall GetComputerNameW(ptr ptr) GetComputerName32W
 295 stdcall GetConsoleCP() GetConsoleCP
@@ -321,8 +321,8 @@
 307 stdcall GetCurrentProcessId() GetCurrentProcessId
 308 stdcall GetCurrentThread() GetCurrentThread
 309 stdcall GetCurrentThreadId() GetCurrentThreadId
-310 stdcall GetDateFormatA(long long ptr ptr ptr long) GetDateFormat32A
-311 stub GetDateFormatW
+310 stdcall GetDateFormatA(long long ptr str ptr long) GetDateFormat32A
+311 stdcall GetDateFormatW(long long ptr wstr ptr long) GetDateFormat32W
 312 stub GetDaylightFlag
 313 stub GetDefaultCommConfigA
 314 stub GetDefaultCommConfigW
@@ -336,7 +336,7 @@
 322 stdcall GetEnvironmentVariableA(str ptr long) GetEnvironmentVariable32A
 323 stdcall GetEnvironmentVariableW(wstr ptr long) GetEnvironmentVariable32W
 324 stub GetErrorMode
-325 stub GetExitCodeProcess
+325 stdcall GetExitCodeProcess(long ptr) GetExitCodeProcess
 326 stdcall GetExitCodeThread(long ptr) GetExitCodeThread
 327 stdcall GetFileAttributesA(str) GetFileAttributes32A
 328 stdcall GetFileAttributesW(wstr) GetFileAttributes32W
@@ -358,7 +358,7 @@
 344 stdcall GetLogicalDriveStringsA(long ptr) GetLogicalDriveStrings32A
 345 stdcall GetLogicalDriveStringsW(long ptr) GetLogicalDriveStrings32W
 346 stdcall GetLogicalDrives() GetLogicalDrives
-347 stub GetMailslotInfo
+347 stdcall GetMailslotInfo(long ptr ptr ptr ptr) GetMailslotInfo
 348 stdcall GetModuleFileNameA(long ptr long) GetModuleFileName32A
 349 stdcall GetModuleFileNameW(long ptr long) GetModuleFileName32W
 350 stdcall GetModuleHandleA(str) GetModuleHandle32A
@@ -434,7 +434,7 @@
 420 stdcall GetThreadTimes(long ptr ptr ptr ptr) GetThreadTimes
 421 stdcall GetTickCount() GetTickCount
 422 stdcall GetTimeFormatA(long long ptr str ptr long) GetTimeFormat32A
-423 stub GetTimeFormatW
+423 stdcall GetTimeFormatW(long long ptr wstr ptr long) GetTimeFormat32W
 424 stdcall GetTimeZoneInformation(ptr) GetTimeZoneInformation
 425 stdcall GetUserDefaultLCID() GetUserDefaultLCID
 426 stdcall GetUserDefaultLangID() GetUserDefaultLangID
@@ -580,7 +580,7 @@
 566 stub QueueUserAPC
 567 register RaiseException() EXC_RaiseException
 568 stdcall ReadConsoleA(long ptr long ptr ptr) ReadConsole32A
-569 stub ReadConsoleInputA
+569 stdcall ReadConsoleInputA(long ptr long ptr) ReadConsoleInputA
 570 stub ReadConsoleInputW
 571 stub ReadConsoleOutputA
 572 stub ReadConsoleOutputAttribute
@@ -632,8 +632,8 @@
 618 stdcall SetCommMask(long ptr) SetCommMask
 619 stdcall SetCommState(long ptr) SetCommState32
 620 stdcall SetCommTimeouts(long ptr) SetCommTimeouts
-621 stub SetComputerNameA
-622 stub SetComputerNameW
+621 stdcall SetComputerNameA(str) SetComputerName32A
+622 stdcall SetComputerNameW(wstr) SetComputerName32W
 623 stdcall SetConsoleActiveScreenBuffer(long) SetConsoleActiveScreenBuffer
 624 stub SetConsoleCP
 625 stdcall SetConsoleCtrlHandler(ptr long) SetConsoleCtrlHandler
@@ -641,11 +641,11 @@
 627 stdcall SetConsoleCursorPosition(long long) SetConsoleCursorPosition
 628 stdcall SetConsoleMode(long long) SetConsoleMode
 629 stub SetConsoleOutputCP
-630 stub SetConsoleScreenBufferSize
-631 stub SetConsoleTextAttribute
+630 stdcall SetConsoleScreenBufferSize(long long) SetConsoleScreenBufferSize
+631 stdcall SetConsoleTextAttribute(long long) SetConsoleTextAttribute32
 632 stdcall SetConsoleTitleA(str) SetConsoleTitle32A
 633 stdcall SetConsoleTitleW(wstr) SetConsoleTitle32W
-634 stub SetConsoleWindowInfo
+634 stdcall SetConsoleWindowInfo(long long ptr) SetConsoleWindowInfo
 635 stdcall SetCurrentDirectoryA(str) SetCurrentDirectory32A
 636 stdcall SetCurrentDirectoryW(wstr) SetCurrentDirectory32W
 637 stub SetDaylightFlag
@@ -731,7 +731,7 @@
 717 stdcall VirtualQueryEx(long ptr ptr long) VirtualQueryEx
 718 stdcall VirtualUnlock(ptr long) VirtualUnlock
 719 stub WaitCommEvent
-720 stub WaitForDebugEvent
+720 stdcall WaitForDebugEvent(ptr long) WaitForDebugEvent
 721 stdcall WaitForMultipleObjects(long ptr long long) WaitForMultipleObjects
 722 stdcall WaitForMultipleObjectsEx(long ptr long long long) WaitForMultipleObjectsEx
 723 stdcall WaitForSingleObject(long long) WaitForSingleObject
diff --git a/relay32/mpr.spec b/relay32/mpr.spec
index 2be81b5..ce8e821 100644
--- a/relay32/mpr.spec
+++ b/relay32/mpr.spec
@@ -24,13 +24,13 @@
 0043 stub PwdGetPasswordStatusW
 0044 stub PwdSetPasswordStatusA
 0045 stub PwdSetPasswordStatusW
-0046 stub WNetAddConnection2A
-0047 stub WNetAddConnection2W
-0048 stub WNetAddConnection3A
-0049 stub WNetAddConnection3W
-0050 stub WNetAddConnectionA
-0051 stub WNetAddConnectionW
-0052 stdcall WNetCachePassword(ptr long ptr long long) WNetCachePassword
+0046 stdcall WNetAddConnection2A(ptr str str long) WNetAddConnection2_32A
+0047 stdcall WNetAddConnection2W(ptr wstr wstr long) WNetAddConnection2_32W
+0048 stdcall WNetAddConnection3A(long ptr str str long) WNetAddConnection3_32A
+0049 stdcall WNetAddConnection3W(long ptr wstr wstr long) WNetAddConnection3_32W
+0050 stdcall WNetAddConnectionA(str str str) WNetAddConnection32A
+0051 stdcall WNetAddConnectionW(wstr wstr wstr) WNetAddConnection32W
+0052 stdcall WNetCachePassword(str long str long long) WNetCachePassword
 0053 stub WNetCancelConnection2A
 0054 stub WNetCancelConnection2W
 0055 stub WNetCancelConnectionA
diff --git a/relay32/oleaut32.spec b/relay32/oleaut32.spec
new file mode 100644
index 0000000..a315b0a
--- /dev/null
+++ b/relay32/oleaut32.spec
@@ -0,0 +1,292 @@
+name oleaut32
+type win32
+
+1 stub DllGetClassObject
+2 stdcall SysAllocString(wstr) SysAllocString32
+3 stdcall SysReAllocString(ptr wstr) SysReAllocString32
+4 stub SysAllocStringLen
+5 stub SysReAllocStringLen
+6 stdcall SysFreeString(wstr) SysFreeString32
+7 stub SysStringLen
+8 stub VariantInit
+9 stub VariantClear
+10 stub VariantCopy
+11 stub VariantCopyInd
+12 stub VariantChangeType
+13 stub VariantTimeToDosDateTime
+14 stub DosDateTimeToVariantTime
+15 stub SafeArrayCreate
+16 stub SafeArrayDestroy
+17 stub SafeArrayGetDim
+18 stub SafeArrayGetElemsize
+19 stub SafeArrayGetUBound
+20 stub SafeArrayGetLBound
+21 stub SafeArrayLock
+22 stub SafeArrayUnlock
+23 stub SafeArrayAccessData
+24 stub SafeArrayUnaccessData
+25 stub SafeArrayGetElement
+26 stub SafeArrayPutElement
+27 stub SafeArrayCopy
+28 stub DispGetParam
+29 stub DispGetIDsOfNames
+30 stub DispInvoke
+31 stub CreateDispTypeInfo
+32 stub CreateStdDispatch
+33 stub RegisterActiveObject
+34 stub RevokeActiveObject
+35 stub GetActiveObject
+36 stub SafeArrayAllocDescriptor
+37 stub SafeArrayAllocData
+38 stub SafeArrayDestroyDescriptor
+39 stub SafeArrayDestroyData
+40 stub SafeArrayRedim
+41 stub OACreateTypeLib2
+46 stub VarParseNumFromStr
+47 stub VarNumFromParseNum
+48 stub VarI2FromUI1
+49 stub VarI2FromI4
+50 stub VarI2FromR4
+51 stub VarI2FromR8
+52 stub VarI2FromCy
+53 stub VarI2FromDate
+54 stub VarI2FromStr
+55 stub VarI2FromDisp
+56 stub VarI2FromBool
+58 stub VarI4FromUI1
+59 stub VarI4FromI2
+60 stub VarI4FromR4
+61 stub VarI4FromR8
+62 stub VarI4FromCy
+63 stub VarI4FromDate
+64 stub VarI4FromStr
+65 stub VarI4FromDisp
+66 stub VarI4FromBool
+68 stub VarR4FromUI1
+69 stub VarR4FromI2
+70 stub VarR4FromI4
+71 stub VarR4FromR8
+72 stub VarR4FromCy
+73 stub VarR4FromDate
+74 stub VarR4FromStr
+75 stub VarR4FromDisp
+76 stub VarR4FromBool
+78 stub VarR8FromUI1
+79 stub VarR8FromI2
+80 stub VarR8FromI4
+81 stub VarR8FromR4
+82 stub VarR8FromCy
+83 stub VarR8FromDate
+84 stub VarR8FromStr
+85 stub VarR8FromDisp
+86 stub VarR8FromBool
+88 stub VarDateFromUI1
+89 stub VarDateFromI2
+90 stub VarDateFromI4
+91 stub VarDateFromR4
+92 stub VarDateFromR8
+93 stub VarDateFromCy
+94 stub VarDateFromStr
+95 stub VarDateFromDisp
+96 stub VarDateFromBool
+98 stub VarCyFromUI1
+99 stub VarCyFromI2
+100 stub VarCyFromI4
+101 stub VarCyFromR4
+102 stub VarCyFromR8
+103 stub VarCyFromDate
+104 stub VarCyFromStr
+105 stub VarCyFromDisp
+106 stub VarCyFromBool
+108 stub VarBstrFromUI1
+109 stub VarBstrFromI2
+110 stub VarBstrFromI4
+111 stub VarBstrFromR4
+112 stub VarBstrFromR8
+113 stub VarBstrFromCy
+114 stub VarBstrFromDate
+115 stub VarBstrFromDisp
+116 stub VarBstrFromBool
+118 stub VarBoolFromUI1
+119 stub VarBoolFromI2
+120 stub VarBoolFromI4
+121 stub VarBoolFromR4
+122 stub VarBoolFromR8
+123 stub VarBoolFromDate
+124 stub VarBoolFromCy
+125 stub VarBoolFromStr
+126 stub VarBoolFromDisp
+130 stub VarUI1FromI2
+131 stub VarUI1FromI4
+132 stub VarUI1FromR4
+133 stub VarUI1FromR8
+134 stub VarUI1FromCy
+135 stub VarUI1FromDate
+136 stub VarUI1FromStr
+137 stub VarUI1FromDisp
+138 stub VarUI1FromBool
+146 stub DispCallFunc
+147 stub VariantChangeTypeEx
+148 stub SafeArrayPtrOfIndex
+149 stub SysStringByteLen
+150 stub SysAllocStringByteLen
+160 stub CreateTypeLib
+161 stub LoadTypeLib
+162 stub LoadRegTypeLib
+163 stub RegisterTypeLib
+164 stdcall QueryPathOfRegTypeLib(ptr long long long ptr) QueryPathOfRegTypeLib32
+165 stub LHashValOfNameSys
+166 stub LHashValOfNameSysA
+170 stub OaBuildVersion
+171 stub ClearCustData
+180 stub CreateTypeLib2
+183 stub LoadTypeLibEx
+184 stub SystemTimeToVariantTime
+185 stub VariantTimeToSystemTime
+186 stub UnRegisterTypeLib
+190 stub VarDecFromUI1
+191 stub VarDecFromI2
+192 stub VarDecFromI4
+193 stub VarDecFromR4
+194 stub VarDecFromR8
+195 stub VarDecFromDate
+196 stub VarDecFromCy
+197 stub VarDecFromStr
+198 stub VarDecFromDisp
+199 stub VarDecFromBool
+200 stub GetErrorInfo
+201 stub SetErrorInfo
+202 stub CreateErrorInfo
+205 stub VarI2FromI1
+206 stub VarI2FromUI2
+207 stub VarI2FromUI4
+208 stub VarI2FromDec
+209 stub VarI4FromI1
+210 stub VarI4FromUI2
+211 stub VarI4FromUI4
+212 stub VarI4FromDec
+213 stub VarR4FromI1
+214 stub VarR4FromUI2
+215 stub VarR4FromUI4
+216 stub VarR4FromDec
+217 stub VarR8FromI1
+218 stub VarR8FromUI2
+219 stub VarR8FromUI4
+220 stub VarR8FromDec
+221 stub VarDateFromI1
+222 stub VarDateFromUI2
+223 stub VarDateFromUI4
+224 stub VarDateFromDec
+225 stub VarCyFromI1
+226 stub VarCyFromUI2
+227 stub VarCyFromUI4
+228 stub VarCyFromDec
+229 stub VarBstrFromI1
+230 stub VarBstrFromUI2
+231 stub VarBstrFromUI4
+232 stub VarBstrFromDec
+233 stub VarBoolFromI1
+234 stub VarBoolFromUI2
+235 stub VarBoolFromUI4
+236 stub VarBoolFromDec
+237 stub VarUI1FromI1
+238 stub VarUI1FromUI2
+239 stub VarUI1FromUI4
+240 stub VarUI1FromDec
+241 stub VarDecFromI1
+242 stub VarDecFromUI2
+243 stub VarDecFromUI4
+244 stub VarI1FromUI1
+245 stub VarI1FromI2
+246 stub VarI1FromI4
+247 stub VarI1FromR4
+248 stub VarI1FromR8
+249 stub VarI1FromDate
+250 stub VarI1FromCy
+251 stub VarI1FromStr
+252 stub VarI1FromDisp
+253 stub VarI1FromBool
+254 stub VarI1FromUI2
+255 stub VarI1FromUI4
+256 stub VarI1FromDec
+257 stub VarUI2FromUI1
+258 stub VarUI2FromI2
+259 stub VarUI2FromI4
+260 stub VarUI2FromR4
+261 stub VarUI2FromR8
+262 stub VarUI2FromDate
+263 stub VarUI2FromCy
+264 stub VarUI2FromStr
+265 stub VarUI2FromDisp
+266 stub VarUI2FromBool
+267 stub VarUI2FromI1
+268 stub VarUI2FromUI4
+269 stub VarUI2FromDec
+270 stub VarUI4FromUI1
+271 stub VarUI4FromI2
+272 stub VarUI4FromI4
+273 stub VarUI4FromR4
+274 stub VarUI4FromR8
+275 stub VarUI4FromDate
+276 stub VarUI4FromCy
+277 stub VarUI4FromStr
+278 stub VarUI4FromDisp
+279 stub VarUI4FromBool
+280 stub VarUI4FromI1
+281 stub VarUI4FromUI2
+282 stub VarUI4FromDec
+283 stub BSTR_UserSize
+284 stub BSTR_UserMarshal
+285 stub BSTR_UserUnmarshal
+286 stub BSTR_UserFree
+287 stub VARIANT_UserSize
+288 stub VARIANT_UserMarshal
+289 stub VARIANT_UserUnmarshal
+290 stub VARIANT_UserFree
+291 stub LPSAFEARRAY_UserSize
+292 stub LPSAFEARRAY_UserMarshal
+293 stub LPSAFEARRAY_UserUnmarshal
+294 stub LPSAFEARRAY_UserFree
+295 stub LPSAFEARRAY_Size
+296 stub LPSAFEARRAY_Marshal
+297 stub LPSAFEARRAY_Unmarshal
+320 stub DllRegisterServer
+321 stub DllUnregisterServer
+330 stub VarDateFromUdate
+331 stub VarUdateFromDate
+332 stub GetAltMonthNames
+380 stub UserHWND_from_local
+381 stub UserHWND_to_local
+382 stub UserHWND_free_inst
+383 stub UserHWND_free_local
+384 stub UserBSTR_from_local
+385 stub UserBSTR_to_local
+386 stub UserBSTR_free_inst
+387 stub UserBSTR_free_local
+388 stub UserVARIANT_from_local
+389 stub UserVARIANT_to_local
+390 stub UserVARIANT_free_inst
+391 stub UserVARIANT_free_local
+392 stub UserEXCEPINFO_from_local
+393 stub UserEXCEPINFO_to_local
+394 stub UserEXCEPINFO_free_inst
+395 stub UserEXCEPINFO_free_local
+396 stub UserMSG_from_local
+397 stub UserMSG_to_local
+398 stub UserMSG_free_inst
+399 stub UserMSG_free_local
+410 stub DllCanUnloadNow
+411 stub SafeArrayCreateVector
+412 stub SafeArrayCopyData
+413 stub VectorFromBstr
+414 stub BstrFromVector
+415 stub OleIconToCursor
+416 stub OleCreatePropertyFrameIndirect
+417 stub OleCreatePropertyFrame
+418 stub OleLoadPicture
+419 stub OleCreatePictureIndirect
+420 stub OleCreateFontIndirect
+421 stub OleTranslateColor
+422 stub OleLoadPictureFile
+423 stub OleSavePictureFile
+424 stub OleLoadPicturePath
diff --git a/relay32/relay386.c b/relay32/relay386.c
index 5177ac2..8203e40 100644
--- a/relay32/relay386.c
+++ b/relay32/relay386.c
@@ -190,8 +190,8 @@
 
 void RELAY_CallFrom32Regs( CONTEXT context )
 {
-    void (CALLBACK *entry_point)(CONTEXT *) = 
-	 *(void (CALLBACK **)(CONTEXT *)) (ESP_reg(&context) - 4);
+    typedef void (CALLBACK *entry_point_t)(CONTEXT *);
+    entry_point_t entry_point = *(entry_point_t*) (ESP_reg(&context) - 4);
 
     if (!TRACE_ON(relay))
     {
diff --git a/relay32/user32.spec b/relay32/user32.spec
index 1b3e611..e73bd80 100644
--- a/relay32/user32.spec
+++ b/relay32/user32.spec
@@ -79,8 +79,8 @@
  76 stdcall CreateIconFromResource (ptr long long long) CreateIconFromResource32
  77 stdcall CreateIconFromResourceEx(ptr long long long long long long) CreateIconFromResourceEx32
  78 stdcall CreateIconIndirect(ptr) CreateIconIndirect
- 79 stub CreateMDIWindowA
- 80 stub CreateMDIWindowW
+ 79 stdcall CreateMDIWindowA(ptr ptr long long long long long long long long) CreateMDIWindowA
+ 80 stdcall CreateMDIWindowW(ptr ptr long long long long long long long long) CreateMDIWindowW
  81 stdcall CreateMenu() CreateMenu32
  82 stdcall CreatePopupMenu() CreatePopupMenu32
  83 stdcall CreateWindowExA(long str str long long long long long 
@@ -95,16 +95,16 @@
  90 stdcall DdeClientTransaction(ptr long long long long long long ptr) DdeClientTransaction32
  91 stub DdeCmpStringHandles
  92 stdcall DdeConnect(long long long ptr) DdeConnect32
- 93 stub DdeConnectList
+ 93 stdcall DdeConnectList(long long long long ptr) DdeConnectList32
  94 stub DdeCreateDataHandle
  95 stdcall DdeCreateStringHandleA(long ptr long) DdeCreateStringHandle32A
  96 stdcall DdeCreateStringHandleW(long ptr long) DdeCreateStringHandle32W
  97 stdcall DdeDisconnect(long) DdeDisconnect32
- 98 stub DdeDisconnectList
+ 98 stdcall DdeDisconnectList(long) DdeDisconnectList32
  99 stub DdeEnableCallback
 100 stdcall DdeFreeDataHandle(long) DdeFreeDataHandle32
 101 stdcall DdeFreeStringHandle(long long) DdeFreeStringHandle32
-102 stub DdeGetData
+102 stdcall DdeGetData(long ptr long long) DdeGetData32
 103 stdcall DdeGetLastError(long) DdeGetLastError32
 104 stub DdeGetQualityOfService
 105 stub DdeImpersonateClient
@@ -112,7 +112,7 @@
 107 stdcall DdeInitializeW(ptr ptr long long) DdeInitialize32W
 108 stdcall DdeKeepStringHandle(long long) DdeKeepStringHandle32
 109 stdcall DdeNameService(long long long long) DdeNameService32
-110 stub DdePostAdvise
+110 stdcall DdePostAdvise(long long long) DdePostAdvise32
 111 stub DdeQueryConvInfo
 112 stub DdeQueryNextServer
 113 stub DdeQueryStringA
@@ -282,7 +282,7 @@
 277 stdcall GetOpenClipboardWindow() GetOpenClipboardWindow32
 278 stdcall GetParent(long) GetParent32
 279 stdcall GetPriorityClipboardFormat(ptr long) GetPriorityClipboardFormat32
-280 stub GetProcessWindowStation
+280 stdcall GetProcessWindowStation() GetProcessWindowStation
 281 stdcall GetPropA(long ptr) GetProp32A
 282 stdcall GetPropW(long ptr) GetProp32W
 283 stdcall GetQueueStatus(long) GetQueueStatus32
@@ -297,7 +297,7 @@
 292 stdcall GetSystemMetrics(long) GetSystemMetrics32
 293 stdcall GetTabbedTextExtentA(long str long long ptr) GetTabbedTextExtent32A
 294 stdcall GetTabbedTextExtentW(long wstr long long ptr) GetTabbedTextExtent32W
-295 stub GetThreadDesktop
+295 stdcall GetThreadDesktop(long) GetThreadDesktop
 296 stdcall GetTopWindow(long) GetTopWindow32
 297 stdcall GetUpdateRect(long ptr long) GetUpdateRect32
 298 stdcall GetUpdateRgn(long long long) GetUpdateRgn32
@@ -477,7 +477,7 @@
 472 stdcall SetCursor(long) SetCursor32
 473 stub SetCursorContents
 474 stdcall SetCursorPos(long long) SetCursorPos32
-475 stub SetDebugErrorLevel
+475 stdcall SetDebugErrorLevel(long) SetDebugErrorLevel
 476 stdcall SetDeskWallPaper(str) SetDeskWallPaper32
 477 stdcall SetDlgItemInt(long long long long) SetDlgItemInt32
 478 stdcall SetDlgItemTextA(long long str) SetDlgItemText32A
@@ -597,10 +597,10 @@
 591 stub EnumDesktopWindows
 592 stdcall EnumDisplaySettingsA(str long ptr) EnumDisplaySettings32A
 593 stub EnumDisplaySettingsW
-594 stub GetWindowRgn
+594 stdcall GetWindowRgn(long long) GetWindowRgn32
 595 stub MapVirtualKeyExW
 596 stub RegisterServicesProcess
-597 stub SetWindowRgn
+597 stdcall SetWindowRgn(long long long) SetWindowRgn32
 598 stub ToUnicodeEx
 599 stdcall DrawCaptionTempA(long long ptr long long str long) DrawCaptionTemp32A
 600 stub RegisterNetworkCapabilities
@@ -609,3 +609,4 @@
 603 stub IsHungAppWindow
 604 stub ChangeDisplaySettingsA
 605 stub ChangeDisplaySettingsW
+606 stdcall SetWindowText(long str) SetWindowText32A
diff --git a/scheduler/process.c b/scheduler/process.c
index ce6fc50..361875e 100644
--- a/scheduler/process.c
+++ b/scheduler/process.c
@@ -261,6 +261,7 @@
     {
 	size = 0x10000;
 	commit = 0;
+        pdb->flags |= PDB32_WIN16_PROC;  /* This is a Win16 process */
     }
     if (!(pdb->heap = HeapCreate( HEAP_GROWABLE, size, commit ))) goto error;
     pdb->heap_list = pdb->heap;
@@ -668,3 +669,28 @@
 	/* I don't think that Wine needs to do anything in that function */
 	return 1; /* success */
 }
+
+/***********************************************************************
+ * GetExitCodeProcess [KERNEL32.325]
+ *
+ * Gets termination status of specified process
+ * 
+ * RETURNS
+ *   Success: TRUE
+ *   Failure: FALSE
+ * 
+ * FIXME
+ *   Should call SetLastError (but doesn't).
+ */
+BOOL32 WINAPI GetExitCodeProcess(
+    HANDLE32 hProcess,  /* [I] handle to the process */
+    LPDWORD lpExitCode) /* [O] address to receive termination status */
+{
+    PDB32 *process;
+
+    if (!(process = PROCESS_GetPtr( hProcess, PROCESS_QUERY_INFORMATION )))
+        return FALSE;
+    if (lpExitCode) *lpExitCode = process->exit_code;
+    K32OBJ_DecCount( &process->header );
+    return TRUE;
+}
diff --git a/win32/advapi.c b/win32/advapi.c
index d84a2f1..cee2675 100644
--- a/win32/advapi.c
+++ b/win32/advapi.c
@@ -35,16 +35,26 @@
 }
 
 
-/***********************************************************************
- *           OpenProcessToken   [ADVAPI32.197]
+/******************************************************************************
+ * OpenProcessToken [ADVAPI32.109]
+ * Opens the access token associated with a process
+ *
+ * PARAMS
+ *    ProcessHandle [I] Handle to process
+ *    DesiredAccess [I] Desired access to process
+ *    TokenHandle   [O] Pointer to handle of open access token
+ *
+ * RETURNS STD
  */
-BOOL32 WINAPI OpenProcessToken(HANDLE32 process,DWORD desiredaccess,
-                               HANDLE32 *thandle)
+BOOL32 WINAPI OpenProcessToken( HANDLE32 ProcessHandle, DWORD DesiredAccess,
+                                HANDLE32 *TokenHandle )
 {
-	FIXME(advapi,"(%08x,%08lx,%p):stub!\n",process,desiredaccess,thandle);
-	return TRUE;
+    FIXME(advapi,"(%08x,%08lx,%p): stub\n",ProcessHandle,DesiredAccess,
+          TokenHandle);
+    return TRUE;
 }
 
+
 /***********************************************************************
  *           OpenThreadToken		[ADVAPI32.114]
  */
@@ -56,15 +66,45 @@
 	return TRUE;
 }
 
-/***********************************************************************
- *           LookupPrivilegeValueA   [ADVAPI32.90]
+
+/******************************************************************************
+ * LookupPrivilegeValue32A                                        [ADVAPI32.92]
  */
-BOOL32 WINAPI LookupPrivilegeValue32A(LPCSTR system,LPCSTR name,LPVOID bla)
+BOOL32 WINAPI LookupPrivilegeValue32A( LPCSTR lpSystemName, 
+                                       LPCSTR lpName, LPVOID lpLuid)
 {
-	FIXME(advapi,"(%s,%s,%p): stub\n",system,name,bla);
-	return TRUE;
+    LPWSTR lpSystemNameW = HEAP_strdupAtoW(GetProcessHeap(), 0, lpSystemName);
+    LPWSTR lpNameW = HEAP_strdupAtoW(GetProcessHeap(), 0, lpName);
+    BOOL32 ret = LookupPrivilegeValue32W( lpSystemNameW, lpNameW, lpLuid);
+    HeapFree(GetProcessHeap(), 0, lpNameW);
+    HeapFree(GetProcessHeap(), 0, lpSystemNameW);
+    return ret;
 }
 
+
+/******************************************************************************
+ * LookupPrivilegeValue32W                                        [ADVAPI32.93]
+ * Retrieves LUID used on a system to represent the privilege name.
+ *
+ * NOTES
+ *    lpLuid should be PLUID
+ *
+ * PARAMS
+ *    lpSystemName [I] Address of string specifying the system
+ *    lpName       [I] Address of string specifying the privilege
+ *    lpLuid       [I] Address of locally unique identifier
+ *
+ * RETURNS STD
+ */
+BOOL32 WINAPI LookupPrivilegeValue32W( LPCWSTR lpSystemName,
+                                       LPCWSTR lpName, LPVOID lpLuid )
+{
+    FIXME(advapi,"(%s,%s,%p): stub\n",debugstr_w(lpSystemName), 
+                  debugstr_w(lpName), lpLuid);
+    return TRUE;
+}
+
+
 /***********************************************************************
  *           AdjustTokenPrivileges   [ADVAPI32.10]
  */
@@ -87,25 +127,245 @@
 	return TRUE;
 }
 
-/*SC_HANDLE*/
-DWORD WINAPI OpenSCManagerA(LPCSTR machine,LPCSTR dbname,DWORD desiredaccess)
+
+/******************************************************************************
+ * OpenSCManager32A [ADVAPI32.110]
+ */
+HANDLE32 WINAPI OpenSCManager32A( LPCSTR lpMachineName, LPCSTR lpDatabaseName,
+                                  DWORD dwDesiredAccess )
 {
-	FIXME(advapi,"(%s,%s,%08lx): stub\n",machine,dbname,desiredaccess);
-	return 0;
+    LPWSTR lpMachineNameW = HEAP_strdupAtoW(GetProcessHeap(),0,lpMachineName);
+    LPWSTR lpDatabaseNameW = HEAP_strdupAtoW(GetProcessHeap(),0,lpDatabaseName);
+    DWORD ret = OpenSCManager32W(lpMachineNameW,lpDatabaseNameW,
+                                 dwDesiredAccess);
+    HeapFree(GetProcessHeap(),0,lpDatabaseNameW);
+    HeapFree(GetProcessHeap(),0,lpMachineNameW);
+    return ret;
 }
 
-DWORD WINAPI OpenSCManagerW(LPCWSTR machine,LPCWSTR dbname,DWORD desiredaccess)
+
+/******************************************************************************
+ * OpenSCManager32W [ADVAPI32.111]
+ * Establishes a connection to the service control manager and opens database
+ *
+ * NOTES
+ *    This should return a SC_HANDLE
+ *
+ * PARAMS
+ *    lpMachineName   [I] Pointer to machine name string
+ *    lpDatabaseName  [I] Pointer to database name string
+ *    dwDesiredAccess [I] Type of access
+ *
+ * RETURNS
+ *    Success: Handle to service control manager database
+ *    Failure: NULL
+ */
+HANDLE32 WINAPI OpenSCManager32W( LPCWSTR lpMachineName, LPCWSTR lpDatabaseName,
+                                  DWORD dwDesiredAccess )
 {
-	LPSTR	machineA = HEAP_strdupWtoA(GetProcessHeap(),0,machine);
-	LPSTR	dbnameA = HEAP_strdupWtoA(GetProcessHeap(),0,dbname);
-	FIXME(advapi,"(%s,%s,%08lx): stub\n",machineA,dbnameA,desiredaccess);
-	HeapFree(GetProcessHeap(),0,machineA);
-	HeapFree(GetProcessHeap(),0,dbnameA);
-	return 0;
+    FIXME(advapi,"(%s,%s,%08lx): stub\n", debugstr_w(lpMachineName), 
+          debugstr_w(lpDatabaseName), dwDesiredAccess);
+    return 1;
 }
 
+
 BOOL32 WINAPI AllocateLocallyUniqueId(LPLUID lpluid) {
 	lpluid->LowPart = time(NULL);
 	lpluid->HighPart = 0;
 	return TRUE;
 }
+
+
+/******************************************************************************
+ * ControlService [ADVAPI32.23]
+ * Sends a control code to a Win32-based service.
+ *
+ * NOTES
+ *    hService should be SC_HANDLE
+ *
+ * RETURNS STD
+ */
+BOOL32 WINAPI ControlService( HANDLE32 hService, DWORD dwControl, 
+                              LPSERVICE_STATUS lpServiceStatus )
+{
+    FIXME(advapi, "(%d,%ld,%p): stub\n",hService,dwControl,lpServiceStatus);
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * CloseServiceHandle [ADVAPI32.22]
+ * Close handle to service or service control manager
+ *
+ * PARAMS
+ *    hSCObject [I] Handle to service or service control manager database
+ *
+ * NOTES
+ *    hSCObject should be SC_HANDLE
+ *
+ * RETURNS STD
+ */
+BOOL32 WINAPI CloseServiceHandle( HANDLE32 hSCObject )
+{
+    FIXME(advapi, "(%d): stub\n", hSCObject);
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * OpenService32A [ADVAPI32.112]
+ */
+HANDLE32 WINAPI OpenService32A( HANDLE32 hSCManager, LPCSTR lpServiceName,
+                                DWORD dwDesiredAccess )
+{
+    LPWSTR lpServiceNameW = HEAP_strdupAtoW(GetProcessHeap(),0,lpServiceName);
+    DWORD ret = OpenService32W( hSCManager, lpServiceNameW, dwDesiredAccess);
+    HeapFree(GetProcessHeap(),0,lpServiceNameW);
+    return ret;
+}
+
+
+/******************************************************************************
+ * OpenService32W [ADVAPI32.113]
+ * Opens a handle to an existing service
+ *
+ * NOTES
+ *    The return value should be SC_HANDLE
+ *    hSCManager should be SC_HANDLE
+ *
+ * RETURNS
+ *    Success: Handle to the service
+ *    Failure: NULL
+ */
+HANDLE32 WINAPI OpenService32W( HANDLE32 hSCManager, LPCWSTR lpServiceName,
+                                DWORD dwDesiredAccess )
+{
+    FIXME(advapi, "(%d,%p,%ld): stub\n",hSCManager, lpServiceName,
+          dwDesiredAccess);
+    return 1;
+}
+
+
+/******************************************************************************
+ * CreateServiceA [ADVAPI32.28]
+ */
+DWORD WINAPI CreateServiceA( DWORD hSCManager, LPCSTR lpServiceName,
+                             LPCSTR lpDisplayName, DWORD dwDesiredAccess, 
+                             DWORD dwServiceType, DWORD dwStartType, 
+                             DWORD dwErrorControl, LPCSTR lpBinaryPathName,
+                             LPCSTR lpLoadOrderGroup, LPDWORD lpdwTagId, 
+                             LPCSTR lpDependencies, LPCSTR lpServiceStartName, 
+                             LPCSTR lpPassword )
+{
+    FIXME(advapi, "(%ld,%s,%s,...): stub\n", 
+          hSCManager, debugstr_a(lpServiceName), debugstr_a(lpDisplayName));
+    return 1;
+}
+
+
+/******************************************************************************
+ * DeleteService [ADVAPI32.31]
+ *
+ * PARAMS
+ *    hService [I] Handle to service
+ *
+ * RETURNS STD
+ *
+ * NOTES
+ *    hService should be SC_HANDLE
+ */
+BOOL32 WINAPI DeleteService( HANDLE32 hService )
+{
+    FIXME(advapi, "(%d): stub\n",hService);
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * StartService32A [ADVAPI32.195]
+ *
+ * NOTES
+ *    How do we convert lpServiceArgVectors to use the 32W version?
+ */
+BOOL32 WINAPI StartService32A( HANDLE32 hService, DWORD dwNumServiceArgs,
+                               LPCSTR *lpServiceArgVectors )
+{
+    FIXME(advapi, "(%d,%ld,%p): stub\n",hService,dwNumServiceArgs,lpServiceArgVectors);
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * StartService32W [ADVAPI32.198]
+ * Starts a service
+ *
+ * PARAMS
+ *    hService            [I] Handle of service
+ *    dwNumServiceArgs    [I] Number of arguments
+ *    lpServiceArgVectors [I] Address of array of argument string pointers
+ *
+ * RETURNS STD
+ *
+ * NOTES
+ *    hService should be SC_HANDLE
+ */
+BOOL32 WINAPI StartService32W( HANDLE32 hService, DWORD dwNumServiceArgs,
+                               LPCWSTR *lpServiceArgVectors )
+{
+    FIXME(advapi, "(%d,%ld,%p): stub\n",hService,dwNumServiceArgs,
+          lpServiceArgVectors);
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * DeregisterEventSource [ADVAPI32.32]
+ * Closes a handle to the specified event log
+ *
+ * PARAMS
+ *    hEventLog [I] Handle to event log
+ *
+ * RETURNS STD
+ */
+BOOL32 WINAPI DeregisterEventSource( HANDLE32 hEventLog )
+{
+    FIXME(advapi, "(%d): stub\n",hEventLog);
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * RegisterEventSource32A [ADVAPI32.174]
+ */
+HANDLE32 WINAPI RegisterEventSource32A( LPCSTR lpUNCServerName, 
+                                        LPCSTR lpSourceName )
+{
+    LPWSTR lpUNCServerNameW = HEAP_strdupAtoW(GetProcessHeap(),0,lpUNCServerName);
+    LPWSTR lpSourceNameW = HEAP_strdupAtoW(GetProcessHeap(),0,lpSourceName);
+    HANDLE32 ret = RegisterEventSource32W(lpUNCServerNameW,lpSourceNameW);
+    HeapFree(GetProcessHeap(),0,lpSourceNameW);
+    HeapFree(GetProcessHeap(),0,lpUNCServerNameW);
+    return ret;
+}
+
+
+/******************************************************************************
+ * RegisterEventSource32W [ADVAPI32.175]
+ * Returns a registered handle to an event log
+ *
+ * PARAMS
+ *    lpUNCServerName [I] Server name for source
+ *    lpSourceName    [I] Source name for registered handle
+ *
+ * RETURNS
+ *    Success: Handle
+ *    Failure: NULL
+ */
+HANDLE32 WINAPI RegisterEventSource32W( LPCWSTR lpUNCServerName, 
+                                        LPCWSTR lpSourceName )
+{
+    FIXME(advapi, "(%s,%s): stub\n", debugstr_w(lpUNCServerName),
+          debugstr_w(lpSourceName));
+    return 1;
+}
+
diff --git a/win32/code_page.c b/win32/code_page.c
index a43c226..f730121 100644
--- a/win32/code_page.c
+++ b/win32/code_page.c
@@ -13,14 +13,20 @@
 #include "debug.h"
 
 
-/***********************************************************************
- *           GetACP               (KERNEL32.148)
+/******************************************************************************
+ * GetACP [KERNEL32.276]  Gets current ANSI code-page identifier.
+ *
+ * RETURNS
+ *    Current ANSI code-page identifier, default if no current defined
  */
 UINT32 WINAPI GetACP(void)
 {
+    /* This introduces too many messages */
+/*    FIXME(win32, "(void): stub\n"); */
     return 1252;    /* Windows 3.1 ISO Latin */
 }
 
+
 /***********************************************************************
  *           GetCPInfo            (KERNEL32.154)
  */
@@ -82,7 +88,34 @@
 
 
 /***********************************************************************
- *              MultiByteToWideChar                (KERNEL32.392)
+ *              MultiByteToWideChar                (KERNEL32.534)
+ *
+ * PARAMS
+ *   page [in]   Codepage character set to convert from
+ *   flags [in]  Character mapping flags
+ *   src [in]     Source string buffer
+ *   srclen [in]  Length of source string buffer
+ *   dst [in]     Destination buffer
+ *   dstlen [in]  Length of destination buffer
+ *
+ * NOTES
+ *   The returned length includes the null terminator character.
+ *
+ * RETURNS
+ *   Success: If dstlen > 0, number of characters written to destination
+ *            buffer.  If dstlen == 0, number of characters needed to do
+ *            conversion.
+ *   Failure: 0. Occurs if not enough space is available.
+ *
+ * ERRORS
+ *   ERROR_INSUFFICIENT_BUFFER
+ *   ERROR_INVALID_FLAGS (not yet implemented)
+ *   ERROR_INVALID_PARAMETER (not yet implemented)
+ *
+ * BUGS
+ *   Does not properly handle codepage conversions.
+ *   Does not properly handle flags.
+ *
  */
 INT32 WINAPI MultiByteToWideChar(UINT32 page, DWORD flags,
 			         LPCSTR src, INT32 srclen,
@@ -91,25 +124,56 @@
     int ret;
 
     if (srclen == -1)
-	srclen = lstrlen32A(src);
+	srclen = lstrlen32A(src)+1;
     if (!dstlen || !dst)
 	return srclen;
 
     ret = srclen;
-    while (srclen > 0 && dstlen > 0) {
+    while (srclen && dstlen) {
 	*dst = (WCHAR)(unsigned char)*src;
-	if (!*src)
-	    return ret;
 	dst++;    src++;
 	dstlen--; srclen--;
     }
-    if ((dstlen == 0) && *src) {
+    if (!dstlen && srclen) {
 	SetLastError(ERROR_INSUFFICIENT_BUFFER);
 	return 0;
     }
     return ret;
 }
 
+/***********************************************************************
+ *              WideCharToMultiByte                (KERNEL32.727)
+ *
+ * PARAMS
+ *   page [in]    Codepage character set to convert to
+ *   flags [in]   Character mapping flags
+ *   src [in]     Source string buffer
+ *   srclen [in]  Length of source string buffer
+ *   dst [in]     Destination buffer
+ *   dstlen [in]  Length of destination buffer
+ *   defchar [in] Default character to use for conversion if no exact
+ *		    conversion can be made
+ *   used [out]   Set if default character was used in the conversion
+ *
+ * NOTES
+ *   The returned length includes the null terminator character.
+ *
+ * RETURNS
+ *   Success: If dstlen > 0, number of characters written to destination
+ *            buffer.  If dstlen == 0, number of characters needed to do
+ *            conversion.
+ *   Failure: 0. Occurs if not enough space is available.
+ *
+ * ERRORS
+ *   ERROR_INSUFFICIENT_BUFFER
+ *   ERROR_INVALID_FLAGS (not yet implemented)
+ *   ERROR_INVALID_PARAMETER (not yet implemented)
+ *
+ * BUGS
+ *   Does not properly handle codepage conversions.
+ *   Does not properly handle flags.
+ *
+ */
 INT32 WINAPI WideCharToMultiByte(UINT32 page, DWORD flags, LPCWSTR src,
 				 INT32 srclen,LPSTR dst, INT32 dstlen,
 				 LPCSTR defchar, BOOL32 *used)
diff --git a/win32/console.c b/win32/console.c
index 1ab7d84..89d70dc 100644
--- a/win32/console.c
+++ b/win32/console.c
@@ -48,6 +48,14 @@
 } CONSOLE;
 
 
+/* This probably belongs somewhere else */
+typedef struct _CONSOLE_CURSOR_INFO {
+    DWORD  dwSize;   /* Between 1 & 100 for percentage of cell filled */
+    BOOL32 bVisible; /* Visibility of cursor */
+} CONSOLE_CURSOR_INFO, *LPCONSOLE_CURSOR_INFO;
+
+
+
 static void CONSOLE_Destroy( K32OBJ *obj );
 static BOOL32 CONSOLE_Write(K32OBJ *ptr, LPCVOID lpBuffer, 
 			    DWORD nNumberOfChars,  LPDWORD lpNumberOfChars, 
@@ -72,7 +80,9 @@
 
 
 
-
+/***********************************************************************
+ * CONSOLE_Destroy
+ */
 static void CONSOLE_Destroy(K32OBJ *obj)
 {
 	CONSOLE *console = (CONSOLE *)obj;
@@ -91,7 +101,12 @@
 }
 
 
-/* lpOverlapped is ignored */
+/***********************************************************************
+ * CONSOLE_Read
+ *
+ * NOTES
+ *    lpOverlapped is ignored
+ */
 static BOOL32 CONSOLE_Read(K32OBJ *ptr, LPVOID lpBuffer, DWORD nNumberOfChars,
 			LPDWORD lpNumberOfChars, LPOVERLAPPED lpOverlapped)
 {
@@ -112,7 +127,12 @@
 }
 
 
-/* lpOverlapped is ignored */
+/***********************************************************************
+ * CONSOLE_Write
+ *
+ * NOTES
+ *    lpOverlapped is ignored
+ */
 static BOOL32 CONSOLE_Write(K32OBJ *ptr, LPCVOID lpBuffer, 
 			    DWORD nNumberOfChars,
 			    LPDWORD lpNumberOfChars, LPOVERLAPPED lpOverlapped)
@@ -145,29 +165,51 @@
 }
 
 
-
-
-/***********************************************************************
- *           SetConsoleCtrlHandler               (KERNEL32.459)
+/******************************************************************************
+ * SetConsoleCtrlHandler [KERNEL32.459]  Adds function to calling process list
+ *
+ * PARAMS
+ *    func [I] Address of handler function
+ *    add  [I] Handler to add or remove
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
  */
-BOOL32 WINAPI SetConsoleCtrlHandler(HANDLER_ROUTINE * func,  BOOL32 a)
+BOOL32 WINAPI SetConsoleCtrlHandler( HANDLER_ROUTINE *func, BOOL32 add )
 {
-	return 0;
+    FIXME(console, "(%p,%i): stub\n",func,add);
+    return TRUE;
 }
 
-/***********************************************************************
- *           CreateConsoleScreenBuffer   (KERNEL32.151)
+
+/******************************************************************************
+ * CreateConsoleScreenBuffer [KERNEL32.151]  Creates a console screen buffer
+ *
+ * PARAMS
+ *    dwDesiredAccess    [I] Access flag
+ *    dwShareMode        [I] Buffer share mode
+ *    sa                 [I] Security attributes
+ *    dwFlags            [I] Type of buffer to create
+ *    lpScreenBufferData [I] Reserved
+ *
+ * NOTES
+ *    Should call SetLastError
+ *
+ * RETURNS
+ *    Success: Handle to new console screen buffer
+ *    Failure: INVALID_HANDLE_VALUE
  */
 HANDLE32 WINAPI CreateConsoleScreenBuffer( DWORD dwDesiredAccess,
-                                           DWORD dwShareMode,
-                                           LPSECURITY_ATTRIBUTES lpSecurityAttributes,
-                                           DWORD dwFlags,
-                                           LPVOID lpScreenBufferData)
+                DWORD dwShareMode, LPSECURITY_ATTRIBUTES sa,
+                DWORD dwFlags, LPVOID lpScreenBufferData )
 {
-	FIXME(console, "(...): stub !\n");
-	return INVALID_HANDLE_VALUE32;
+    FIXME(console, "(%ld,%ld,%p,%ld,%p): stub\n",dwDesiredAccess,
+          dwShareMode, sa, dwFlags, lpScreenBufferData);
+    return 1;
 }
 
+
 /***********************************************************************
  *           GetConsoleScreenBufferInfo   (KERNEL32.190)
  */
@@ -188,15 +230,22 @@
     return TRUE;
 }
 
-/***********************************************************************
- *           SetConsoleActiveScreenBuffer   (KERNEL32.623)
+
+/******************************************************************************
+ * SetConsoleActiveScreenBuffer [KERNEL32.623]  Sets buffer to current console
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
  */
-BOOL32 WINAPI SetConsoleActiveScreenBuffer(HANDLE32 hConsoleOutput)
+BOOL32 WINAPI SetConsoleActiveScreenBuffer(
+    HANDLE32 hConsoleOutput) /* [in] Handle to console screen buffer */
 {
-	FIXME(console, "(%x): stub!\n", hConsoleOutput);
-	return 0;
+    FIXME(console, "(%x): stub\n", hConsoleOutput);
+    return FALSE;
 }
 
+
 /***********************************************************************
  *            GetLargestConsoleWindowSize   (KERNEL32.226)
  */
@@ -433,14 +482,18 @@
 }
 
 
-/***********************************************************************
- *            GetConsoleCP   (KERNEL32.226)
+/******************************************************************************
+ * GetConsoleCP [KERNEL32.295]  Returns the OEM code page for the console
+ *
+ * RETURNS
+ *    Code page code
  */
 UINT32 WINAPI GetConsoleCP(VOID)
 {
     return GetACP();
 }
 
+
 /***********************************************************************
  *            GetConsoleOutputCP   (KERNEL32.189)
  */
@@ -460,15 +513,25 @@
 	return TRUE;
 }
 
-/***********************************************************************
- *            SetConsoleMode   (KERNEL32.628)
+
+/******************************************************************************
+ * SetConsoleMode [KERNEL32.628]  Sets input mode of console's input buffer
+ *
+ * PARAMS
+ *    hcon [I] Handle to console input or screen buffer
+ *    mode [I] Input or output mode to set
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
  */
-BOOL32 WINAPI SetConsoleMode(HANDLE32 hcon,DWORD mode)
+BOOL32 WINAPI SetConsoleMode( HANDLE32 hcon, DWORD mode )
 {
-	FIXME(console,"(%08x,%08lx): stub\n",hcon,mode);
-	return TRUE;
+    FIXME(console,"(%08x,%08lx): stub\n",hcon,mode);
+    return TRUE;
 }
 
+
 /***********************************************************************
  *            GetConsoleTitleA   (KERNEL32.191)
  */
@@ -485,21 +548,31 @@
 	return 0;
 }
 
-/***********************************************************************
- *            GetConsoleTitleW   (KERNEL32.192)
+
+/******************************************************************************
+ * GetConsoleTitle32W [KERNEL32.192]  Retrieves title string for console
+ *
+ * PARAMS
+ *    title [O] Address of buffer for title
+ *    size  [I] Size of buffer
+ *
+ * RETURNS
+ *    Success: Length of string copied
+ *    Failure: 0
  */
-DWORD WINAPI GetConsoleTitle32W(LPWSTR title,DWORD size)
+DWORD WINAPI GetConsoleTitle32W( LPWSTR title, DWORD size )
 {
-	PDB32 *pdb = PROCESS_Current();
-	CONSOLE *console= (CONSOLE *)pdb->console;
-	if(console && console->title) 
-	  {
-	    lstrcpynAtoW(title,console->title,size);
-	    return (lstrlen32W(title));
-	  }
-	return 0;
+    PDB32 *pdb = PROCESS_Current();
+    CONSOLE *console= (CONSOLE *)pdb->console;
+    if(console && console->title) 
+    {
+        lstrcpynAtoW(title,console->title,size);
+        return (lstrlen32W(title));
+    }
+    return 0;
 }
 
+
 /***********************************************************************
  *            WriteConsoleA   (KERNEL32.729)
  */
@@ -514,6 +587,7 @@
 			 lpNumberOfCharsWritten, NULL);
 }
 
+
 /***********************************************************************
  *            WriteConsoleOutputA   (KERNEL32.732)
  */
@@ -523,7 +597,8 @@
                                      COORD dwBufferCoord,
                                      LPSMALL_RECT lpWriteRegion)
 {
-	return FALSE;
+    FIXME(console, "(...):stub\n");
+    return FALSE;
 }
 
 /***********************************************************************
@@ -545,9 +620,9 @@
 			 lpNumberOfCharsWritten, NULL);
 	HeapFree( GetProcessHeap(), 0, xstring );
 	return ret;
-
 }
 
+
 /***********************************************************************
  *            ReadConsoleA   (KERNEL32.419)
  */
@@ -610,6 +685,31 @@
 
 }
 
+
+/******************************************************************************
+ * ReadConsoleInputA [KERNEL32.569]  Reads data from a console
+ *
+ * PARAMS
+ *    hConsoleInput        [I] Handle to console input buffer
+ *    lpBuffer             [O] Address of buffer for read data
+ *    nLength              [I] Number of records to read
+ *    lpNumberOfEventsRead [O] Address of number of records read
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
+ */
+BOOL32 WINAPI ReadConsoleInputA( HANDLE32 hConsoleInput,
+                                 LPINPUT_RECORD lpBuffer,
+                                 DWORD nLength, LPDWORD lpNumberOfEventsRead)
+{
+    FIXME(console, "(%d,%p,%ld,%p): stub\n",hConsoleInput, lpBuffer, nLength,
+          lpNumberOfEventsRead);
+    return ReadConsole32A(hConsoleInput, lpBuffer, nLength, 
+                          lpNumberOfEventsRead, 0);
+}
+
+
 /***********************************************************************
  *            SetConsoleTitle32A   (KERNEL32.476)
  */
@@ -622,7 +722,7 @@
 	LPSTR titlestring; 
 	BOOL32 ret=FALSE;
 
-	TRACE(console,"SetConsoleTitle(%s)\n",title);
+	TRACE(console,"(%s)\n",title);
 	
 	console = (CONSOLE *)pdb->console;
 	if (!console)
@@ -645,8 +745,19 @@
 	return ret;
 }
 
-/***********************************************************************
- *            SetConsoleTitle32W   (KERNEL32.477)
+
+/******************************************************************************
+ * SetConsoleTitle32W [KERNEL32.477]  Sets title bar string for console
+ *
+ * PARAMS
+ *    title [I] Address of new title
+ *
+ * NOTES
+ *    This should not be calling the A version
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
  */
 BOOL32 WINAPI SetConsoleTitle32W( LPCWSTR title )
 {
@@ -658,6 +769,7 @@
     return ret;
 }
 
+
 /***********************************************************************
  *            FlushConsoleInputBuffer   (KERNEL32.132)
  */
@@ -667,26 +779,43 @@
     return TRUE;
 }
 
-BOOL32 WINAPI SetConsoleCursorPosition(HANDLE32 hcons,COORD c)
+
+/******************************************************************************
+ * SetConsoleCursorPosition [KERNEL32.627]
+ * Sets the cursor position in console
+ *
+ * PARAMS
+ *    hConsoleOutput   [I] Handle of console screen buffer
+ *    dwCursorPosition [I] New cursor position coordinates
+ *
+ * RETURNS STD
+ */
+BOOL32 WINAPI SetConsoleCursorPosition( HANDLE32 hConsoleOutput, 
+                                        COORD dwCursorPosition )
 {
+    TRACE(console, "%d (%d x %d)\n", hConsoleOutput, dwCursorPosition.x, 
+          dwCursorPosition.y);
     /* x are columns, y rows */
-    if (!c.y) {
+    if (!dwCursorPosition.y) {
     	fprintf(stderr,"\r");
-	if (c.x)
-		fprintf(stderr,"%c[%dC", 0x1B, c.x); /* note: 0x1b == ESC */
+	if (dwCursorPosition.x)
+            /* note: 0x1B == ESC */
+            fprintf(stderr,"%c[%dC", 0x1B, dwCursorPosition.x);
 	return TRUE;
     }
-    /* handle rest of the cases */
+    FIXME(console, "Unhandled case: y=%d\n", dwCursorPosition.y);
     return FALSE;
 }
 
+
 /***********************************************************************
  *            GetNumberOfConsoleInputEvents   (KERNEL32.246)
  */
 BOOL32 WINAPI GetNumberOfConsoleInputEvents(HANDLE32 hcon,LPDWORD nrofevents)
 {
-	*nrofevents = 0;
-	return TRUE;
+    *nrofevents = 0;
+    FIXME(console,"(%x): stub\n", hcon);
+    return TRUE;
 }
 
 /***********************************************************************
@@ -694,11 +823,12 @@
  */
 BOOL32 WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
 {
+    FIXME(console,"(%p): stub\n", nrofbuttons);
     *nrofbuttons = 2;
-    FIXME(console,"(%p): STUB returning 2\n", nrofbuttons);
     return TRUE;
 }
 
+
 /***********************************************************************
  *            PeekConsoleInputA   (KERNEL32.550)
  */
@@ -710,10 +840,12 @@
     pirBuffer = NULL;
     cInRecords = 0;
     *lpcRead = 0;
-    FIXME(console,"(...): STUB returning TRUE\n");
-	return TRUE;
+    FIXME(console,"(%d,%p,%ld,%p): stub\n",hConsoleInput, pirBuffer,
+          cInRecords, lpcRead);
+    return TRUE;
 }
 
+
 /***********************************************************************
  *            PeekConsoleInputW   (KERNEL32.551)
  */
@@ -725,45 +857,169 @@
     pirBuffer = NULL;
     cInRecords = 0;
     *lpcRead = 0;
-    FIXME(console,"(...): STUB returning TRUE\n");
+    FIXME(console,"(%d,%p,%ld,%p): stub\n", hConsoleInput, pirBuffer,
+          cInRecords, lpcRead);
     return TRUE;
 }
 
-/***********************************************************************
- *            GetConsoleCursorInfo32   (KERNEL32.296)
+
+/******************************************************************************
+ * GetConsoleCursorInfo32 [KERNEL32.296]  Gets size and visibility of console
+ *
+ * PARAMS
+ *    hcon  [I] Handle to console screen buffer
+ *    cinfo [O] Address of cursor information
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
  */
-BOOL32 WINAPI GetConsoleCursorInfo32(HANDLE32 hcon, LPDWORD cinfo)
+BOOL32 WINAPI GetConsoleCursorInfo32( HANDLE32 hcon,
+                                      LPCONSOLE_CURSOR_INFO cinfo )
 {
-  cinfo[0] = 10; /* 10% of character box is cursor.  */
-  cinfo[1] = TRUE;  /* Cursor is visible.  */
-  FIXME(console, "(%x,%p): STUB!\n", hcon, cinfo);
-  return TRUE;
+    FIXME(console, "(%x,%p): stub\n", hcon, cinfo);
+    if (!cinfo) return FALSE;
+    cinfo->dwSize = 10;      /* 10% of character box is cursor.  */
+    cinfo->bVisible = TRUE;  /* Cursor is visible.  */
+    return TRUE;
 }
 
-/***********************************************************************
- *            SetConsoleCursorInfo32   (KERNEL32.626)
+
+/******************************************************************************
+ * SetConsoleCursorInfo32 [KERNEL32.626]  Sets size and visibility of cursor
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
  */
-BOOL32 WINAPI SetConsoleCursorInfo32(HANDLE32 hcon, LPDWORD cinfo)
+BOOL32 WINAPI SetConsoleCursorInfo32( 
+    HANDLE32 hcon,                /* [in] Handle to console screen buffer */
+    LPCONSOLE_CURSOR_INFO cinfo)  /* [in] Address of cursor information */
 {
-  FIXME(console, "(%#x,%p): STUB!\n", hcon, cinfo);
-  return TRUE;
+    FIXME(console, "(%x,%ld,%i): stub\n", hcon,cinfo->dwSize,cinfo->bVisible);
+    return TRUE;
 }
 
-/***********************************************************************
- *            SetConsoleWindowInfo32   (KERNEL32.634)
+
+/******************************************************************************
+ * SetConsoleWindowInfo [KERNEL32.634]  Sets size and position of console
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
  */
-BOOL32 WINAPI SetConsoleWindowInfo32(HANDLE32 hcon, BOOL32 flag, LPSMALL_RECT window)
+BOOL32 WINAPI SetConsoleWindowInfo(
+    HANDLE32 hcon,       /* [in] Handle to console screen buffer */
+    BOOL32 bAbsolute,    /* [in] Coordinate type flag */
+    LPSMALL_RECT window) /* [in] Address of new window rectangle */
 {
-  FIXME(console, "(%x,%d,%p): STUB!\n", hcon, flag, window);
-  return TRUE;
+    FIXME(console, "(%x,%d,%p): stub\n", hcon, bAbsolute, window);
+    return TRUE;
 }
 
-/***********************************************************************
- *               (KERNEL32.631)
+
+/******************************************************************************
+ * SetConsoleTextAttribute32 [KERNEL32.631]  Sets colors for text
+ *
+ * Sets the foreground and background color attributes of characters
+ * written to the screen buffer.
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
  */
-BOOL32 WINAPI SetConsoleTextAttribute32(HANDLE32 hcon, DWORD attributes)
+BOOL32 WINAPI SetConsoleTextAttribute32(
+    HANDLE32 hcon,    /* [in] Handle to console screen buffer */
+    DWORD attributes) /* [in] Text and background colors */
 {
-  FIXME(console, "(%#x,%#lx): STUB!\n", hcon, attributes);
-  return TRUE;
+    FIXME(console, "(%x,%lx): stub\n", hcon, attributes);
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * SetConsoleScreenBufferSize [KERNEL32.630]  Changes size of console 
+ *
+ * PARAMS
+ *    hConsoleOutput [I] Handle to console screen buffer
+ *    dwSize         [I] New size in character rows and cols
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
+ */
+BOOL32 WINAPI SetConsoleScreenBufferSize( HANDLE32 hConsoleOutput, 
+                                          COORD dwSize )
+{
+    FIXME(console, "(%d,%dx%d): stub\n",hConsoleOutput,dwSize.x,dwSize.y);
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * FillConsoleOutputCharacterA [KERNEL32.242]
+ */
+BOOL32 WINAPI FillConsoleOutputCharacterA(
+    HANDLE32 hConsoleOutput,
+    CHAR cCharacter,
+    DWORD nLength,
+    COORD dwWriteCoord,
+    LPDWORD lpNumberOfCharsWritten)
+{
+    FIXME(console, "(%d,%c,%ld,%dx%d,%p): stub\n", hConsoleOutput,cCharacter,
+          nLength,dwWriteCoord.x,dwWriteCoord.y,lpNumberOfCharsWritten);
+    *lpNumberOfCharsWritten = 0;
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * FillConsoleOutputCharacterW [KERNEL32.243]  Writes characters to console
+ *
+ * PARAMS
+ *    hConsoleOutput    [I] Handle to screen buffer
+ *    cCharacter        [I] Character to write
+ *    nLength           [I] Number of cells to write to
+ *    dwCoord           [I] Coords of first cell
+ *    lpNumCharsWritten [O] Pointer to number of cells written
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
+ */
+BOOL32 WINAPI FillConsoleOutputCharacterW( HANDLE32 hConsoleOutput,
+                                           WCHAR cCharacter, DWORD nLength,
+                                           COORD dwCoord, 
+                                           LPDWORD lpNumCharsWritten )
+{
+    FIXME(console, "(%d,%c,%ld,%dx%d,%p): stub\n", hConsoleOutput,
+          cCharacter,nLength,dwCoord.x,dwCoord.y,lpNumCharsWritten);
+    *lpNumCharsWritten = 0;
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * FillConsoleOutputAttribute [KERNEL32.241]  Sets attributes for console
+ *
+ * PARAMS
+ *    hConsoleOutput    [I] Handle to screen buffer
+ *    wAttribute        [I] Color attribute to write
+ *    nLength           [I] Number of cells to write to
+ *    dwCoord           [I] Coords of first cell
+ *    lpNumAttrsWritten [O] Pointer to number of cells written
+ *
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
+ */
+BOOL32 WINAPI FillConsoleOutputAttribute( HANDLE32 hConsoleOutput, 
+              WORD wAttribute, DWORD nLength, COORD dwCoord, 
+              LPDWORD lpNumAttrsWritten)
+{
+    FIXME(console, "(%d,%d,%ld,%dx%d,%p): stub\n", hConsoleOutput,
+          wAttribute,nLength,dwCoord.x,dwCoord.y,lpNumAttrsWritten);
+    *lpNumAttrsWritten = nLength;
+    return TRUE;
 }
 
diff --git a/win32/file.c b/win32/file.c
index c0eb932..c999fb3 100644
--- a/win32/file.c
+++ b/win32/file.c
@@ -283,17 +283,20 @@
  */
 VOID WINAPI SetFileApisToANSI(void)
 {
-    /*FIXME(file,"(): stub!\n");*/
+    /*FIXME(file,"(): stub\n");*/
 }
 
 
-/**************************************************************************
- *              AreFileApisANSI   (KERNEL32.105)
+/******************************************************************************
+ * AreFileApisANSI [KERNEL32.105]  Determines if file functions are using ANSI
+ *
+ * RETURNS
+ *    TRUE:  Set of file functions is using ANSI code page
+ *    FALSE: Set of file functions is using OEM code page
  */
 BOOL32 WINAPI AreFileApisANSI(void)
 {
-    FIXME(file,"(): stub!\n");
+    FIXME(file,"(void): stub\n");
     return TRUE;
 }
 
-
diff --git a/win32/newfns.c b/win32/newfns.c
index 3e6b9fd..ed0aa9d 100644
--- a/win32/newfns.c
+++ b/win32/newfns.c
@@ -14,6 +14,7 @@
 #include "windows.h"
 #include "winnt.h"
 #include "winerror.h"
+#include "heap.h"
 #include "debug.h"
 
 /****************************************************************************
@@ -108,7 +109,10 @@
 				  DWORD nDafaultTimeOut,
 				  LPSECURITY_ATTRIBUTES lpSecurityAttributes)
 {
-  FIXME (win32, "CreateNamedPipeA: stub\n");
+  FIXME (win32, "(Name=%s, OpenMode=%#08x, dwPipeMode=%#08x, MaxInst=%d, OutBSize=%d, InBuffSize=%d, DefTimeOut=%d, SecAttr=%p): stub\n",
+	 debugstr_a(lpName), dwOpenMode, dwPipeMode, nMaxInstances,
+	 nOutBufferSize, nInBufferSize, nDafaultTimeOut, 
+	 lpSecurityAttributes);
   /* if (nMaxInstances > PIPE_UNLIMITED_INSTANCES) {
     SetLastError (ERROR_INVALID_PARAMETER);
     return INVALID_HANDLE_VALUE;
@@ -127,7 +131,10 @@
 				  DWORD nDafaultTimeOut,
 				  LPSECURITY_ATTRIBUTES lpSecurityAttributes)
 {
-  FIXME (win32, "CreateNamedPipeW: stub\n");
+  FIXME (win32, "(Name=%s, OpenMode=%#08x, dwPipeMode=%#08x, MaxInst=%d, OutBSize=%d, InBuffSize=%d, DefTimeOut=%d, SecAttr=%p): stub\n",
+	 debugstr_w(lpName), dwOpenMode, dwPipeMode, nMaxInstances,
+	 nOutBufferSize, nInBufferSize, nDafaultTimeOut, 
+	 lpSecurityAttributes);
 
   SetLastError (ERROR_UNKNOWN);
   return INVALID_HANDLE_VALUE32;
@@ -163,26 +170,190 @@
     return TRUE;
 }
 
-/**************************************************************************
- *              GetNumberFormat32A	(KERNEL32.355)
+
+/******************************************************************************
+ * CreateMailslot32A [KERNEL32.164]
  */
-INT32 WINAPI GetNumberFormat32A(LCID locale, DWORD dwflags,
-			       LPCSTR lpvalue,  char *lpFormat,
-			       LPSTR lpNumberStr, int cchNumber)
-/* NOTE: type of lpFormat should be CONST NUMBERFORMAT */
-
+HANDLE32 WINAPI CreateMailslot32A( LPCSTR lpName, DWORD nMaxMessageSize,
+                                   DWORD lReadTimeout, LPSECURITY_ATTRIBUTES sa)
 {
- int n;
-
- FIXME(file,"%s: stub, no reformating done\n",lpvalue);
-
- n = strlen(lpvalue);
- if (cchNumber) { 
-   strncpy(lpNumberStr,lpvalue,cchNumber);
-   if (cchNumber <= n) {
-     lpNumberStr[cchNumber-1] = 0;
-     n = cchNumber-1;
-   }
- }
- return n;
+    FIXME(win32, "(%s,%ld,%ld,%p): stub\n", debugstr_a(lpName),
+          nMaxMessageSize, lReadTimeout, sa);
+    return 1;
 }
+
+
+/******************************************************************************
+ * CreateMailslot32W [KERNEL32.165]  Creates a mailslot with specified name
+ * 
+ * PARAMS
+ *    lpName          [I] Pointer to string for mailslot name
+ *    nMaxMessageSize [I] Maximum message size
+ *    lReadTimeout    [I] Milliseconds before read time-out
+ *    sa              [I] Pointer to security structure
+ *
+ * RETURNS
+ *    Success: Handle to mailslot
+ *    Failure: INVALID_HANDLE_VALUE
+ */
+HANDLE32 WINAPI CreateMailslot32W( LPCWSTR lpName, DWORD nMaxMessageSize,
+                                   DWORD lReadTimeout, LPSECURITY_ATTRIBUTES sa )
+{
+    FIXME(win32, "(%s,%ld,%ld,%p): stub\n", debugstr_w(lpName), 
+          nMaxMessageSize, lReadTimeout, sa);
+    return 1;
+}
+
+
+/******************************************************************************
+ * GetMailslotInfo [KERNEL32.347]  Retrieves info about specified mailslot
+ *
+ * PARAMS
+ *    hMailslot        [I] Mailslot handle
+ *    lpMaxMessageSize [O] Address of maximum message size
+ *    lpNextSize       [O] Address of size of next message
+ *    lpMessageCount   [O] Address of number of messages
+ *    lpReadTimeout    [O] Address of read time-out
+ * 
+ * RETURNS
+ *    Success: TRUE
+ *    Failure: FALSE
+ */
+BOOL32 WINAPI GetMailslotInfo( HANDLE32 hMailslot, LPDWORD lpMaxMessageSize,
+                               LPDWORD lpNextSize, LPDWORD lpMessageCount,
+                               LPDWORD lpReadTimeout )
+{
+    FIXME(win32, "(%d): stub\n",hMailslot);
+    *lpMaxMessageSize = NULL;
+    *lpNextSize = NULL;
+    *lpMessageCount = NULL;
+    *lpReadTimeout = NULL;
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * GetCompressedFileSize32A [KERNEL32.291]
+ *
+ * NOTES
+ *    This should call the W function below
+ */
+DWORD WINAPI GetCompressedFileSize32A(
+    LPCSTR lpFileName,
+    LPDWORD lpFileSizeHigh)
+{
+    FIXME(win32, "(...): stub\n");
+    return 0xffffffff;
+}
+
+
+/******************************************************************************
+ * GetCompressedFileSize32W [KERNEL32.292]  
+ * 
+ * RETURNS
+ *    Success: Low-order doubleword of number of bytes
+ *    Failure: 0xffffffff
+ */
+DWORD WINAPI GetCompressedFileSize32W(
+    LPCWSTR lpFileName,     /* [in]  Pointer to name of file */
+    LPDWORD lpFileSizeHigh) /* [out] Receives high-order doubleword of size */
+{
+    FIXME(win32, "(%s,%p): stub\n",debugstr_w(lpFileName),lpFileSizeHigh);
+    return 0xffffffff;
+}
+
+
+/******************************************************************************
+ * GetProcessWindowStation [USER32.280]  Returns handle of window station
+ *
+ * NOTES
+ *    Docs say the return value is HWINSTA
+ *
+ * RETURNS
+ *    Success: Handle to window station associated with calling process
+ *    Failure: NULL
+ */
+DWORD WINAPI GetProcessWindowStation(void)
+{
+    FIXME(win32, "(void): stub\n");
+    return 1;
+}
+
+
+/******************************************************************************
+ * GetThreadDesktop [USER32.295]  Returns handle to desktop
+ *
+ * NOTES
+ *    Docs say the return value is HDESK
+ *
+ * PARAMS
+ *    dwThreadId [I] Thread identifier
+ *
+ * RETURNS
+ *    Success: Handle to desktop associated with specified thread
+ *    Failure: NULL
+ */
+DWORD WINAPI GetThreadDesktop( DWORD dwThreadId )
+{
+    FIXME(win32, "(%ld): stub\n",dwThreadId);
+    return 1;
+}
+
+
+/******************************************************************************
+ * SetDebugErrorLevel [USER32.475]
+ * Sets the minimum error level for generating debugging events
+ *
+ * PARAMS
+ *    dwLevel [I] Debugging error level
+ */
+VOID WINAPI SetDebugErrorLevel( DWORD dwLevel )
+{
+    FIXME(win32, "(%ld): stub\n", dwLevel);
+}
+
+
+/******************************************************************************
+ * WaitForDebugEvent [KERNEL32.720]
+ * Waits for a debugging event to occur in a process being debugged
+ *
+ * PARAMS
+ *    lpDebugEvent   [I] Address of structure for event information
+ *    dwMilliseconds [I] Number of milliseconds to wait for event
+ *
+ * RETURNS STD
+ */
+BOOL32 WINAPI WaitForDebugEvent( LPDEBUG_EVENT lpDebugEvent, 
+                                 DWORD dwMilliseconds )
+{
+    FIXME(win32, "(%p,%ld): stub\n", lpDebugEvent, dwMilliseconds);
+    return TRUE;
+}
+
+
+/******************************************************************************
+ * SetComputerName32A [KERNEL32.621]  
+ */
+BOOL32 WINAPI SetComputerName32A( LPCSTR lpComputerName )
+{
+    LPWSTR lpComputerNameW = HEAP_strdupAtoW(GetProcessHeap(),0,lpComputerName);
+    BOOL32 ret = SetComputerName32W(lpComputerNameW);
+    HeapFree(GetProcessHeap(),0,lpComputerNameW);
+    return ret;
+}
+
+
+/******************************************************************************
+ * SetComputerName32W [KERNEL32.622]
+ *
+ * PARAMS
+ *    lpComputerName [I] Address of new computer name
+ * 
+ * RETURNS STD
+ */
+BOOL32 WINAPI SetComputerName32W( LPCWSTR lpComputerName )
+{
+    FIXME(win32, "(%s): stub\n", debugstr_w(lpComputerName));
+    return TRUE;
+}
+
diff --git a/win32/ordinals.c b/win32/ordinals.c
index 7d94d54..6aa184a 100644
--- a/win32/ordinals.c
+++ b/win32/ordinals.c
@@ -20,16 +20,18 @@
 static CRITICAL_SECTION Win16Mutex;
 static SEGPTR segWin16Mutex = NULL;
 
+
 /***********************************************
  *           GetPWinLock    (KERNEL32.93)
  * Return the infamous Win16Mutex.
  */
 VOID WINAPI GetPWinLock(CRITICAL_SECTION **lock)
 {
-        fprintf(stderr,"GetPWinlock(%p)\n",lock);
-        *lock = &Win16Mutex;
+    FIXME(win32, "(%p)\n",lock);
+    *lock = &Win16Mutex;
 }
 
+
 /**********************************************************************
  *           WOW32_1        (KERNEL32.88)
  */
diff --git a/windows/defwnd.c b/windows/defwnd.c
index 5ce2179..0411b64 100644
--- a/windows/defwnd.c
+++ b/windows/defwnd.c
@@ -443,7 +443,8 @@
 
 
 /***********************************************************************
- *           DefWindowProc32A   (USER32.126)
+ *  DefWindowProc32A [USER32.126] 
+ *
  */
 LRESULT WINAPI DefWindowProc32A( HWND32 hwnd, UINT32 msg, WPARAM32 wParam,
                                  LPARAM lParam )
@@ -504,10 +505,19 @@
 
 
 /***********************************************************************
- *           DefWindowProc32W   (USER32.127)
- */
-LRESULT WINAPI DefWindowProc32W( HWND32 hwnd, UINT32 msg, WPARAM32 wParam,
-                                 LPARAM lParam )
+ * DefWindowProc32W [USER32.127] Calls default window message handler
+ * 
+ * Calls default window procedure for messages not processed 
+ *  by application.
+ *
+ *  RETURNS
+ *     Return value is dependent upon the message.
+*/
+LRESULT WINAPI DefWindowProc32W( 
+    HWND32 hwnd,      /* [in] window procedure recieving message */
+    UINT32 msg,       /* [in] message identifier */
+    WPARAM32 wParam,  /* [in] first message parameter */
+    LPARAM lParam )   /* [in] second message parameter */
 {
     LRESULT result;
 
diff --git a/windows/driver.c b/windows/driver.c
index 317831f..a051bd9 100644
--- a/windows/driver.c
+++ b/windows/driver.c
@@ -119,9 +119,9 @@
     lpnewdrv->dis.hDriver = hDrvr;
     lstrcpy32A( lpnewdrv->dis.szAliasName, lpDriverName );
     lpnewdrv->count = 1;
-    ordinal = MODULE_GetOrdinal( lpnewdrv->dis.hModule, "DRIVERPROC" );
+    ordinal = NE_GetOrdinal( lpnewdrv->dis.hModule, "DRIVERPROC" );
     if (!ordinal ||
-        !(lpnewdrv->lpDrvProc = (DRIVERPROC16)MODULE_GetEntryPoint(
+        !(lpnewdrv->lpDrvProc = (DRIVERPROC16)NE_GetEntryPoint(
                                              lpnewdrv->dis.hModule, ordinal )))
     {
 	FreeModule16( lpnewdrv->dis.hModule );
diff --git a/windows/event.c b/windows/event.c
index 94e1e52..93a8d03 100644
--- a/windows/event.c
+++ b/windows/event.c
@@ -1219,8 +1219,7 @@
 FARPROC16 WINAPI GetMouseEventProc(void)
 {
     HMODULE16 hmodule = GetModuleHandle16("USER");
-    return MODULE_GetEntryPoint( hmodule,
-                                 MODULE_GetOrdinal( hmodule, "Mouse_Event" ) );
+    return NE_GetEntryPoint( hmodule, NE_GetOrdinal( hmodule, "Mouse_Event" ));
 }
 
 
diff --git a/windows/hook.c b/windows/hook.c
index a9e1089..9c8c0ca 100644
--- a/windows/hook.c
+++ b/windows/hook.c
@@ -1168,7 +1168,7 @@
 FARPROC16 WINAPI SetWindowsHook16( INT16 id, HOOKPROC16 proc )
 {
     HANDLE16 handle;
-    HINSTANCE16 hInst = __winelib ? 0 : FarGetOwner( HIWORD(proc) );
+    HINSTANCE16 hInst = FarGetOwner( HIWORD(proc) );
 
     /* WH_MSGFILTER is the only task-specific hook for SetWindowsHook() */
     HTASK16 hTask = (id == WH_MSGFILTER) ? GetCurrentTask() : 0;
@@ -1191,12 +1191,10 @@
  */
 HHOOK WINAPI SetWindowsHook32A( INT32 id, HOOKPROC32 proc )
 {
-    HINSTANCE16 hInst = __winelib ? 0 : FarGetOwner( HIWORD(proc) );
-
     /* WH_MSGFILTER is the only task-specific hook for SetWindowsHook() */
     HTASK16 hTask = (id == WH_MSGFILTER) ? GetCurrentTask() : 0;
 
-    HANDLE16 handle = HOOK_SetHook( id, proc, HOOK_WIN32A, hInst, hTask );
+    HANDLE16 handle = HOOK_SetHook( id, proc, HOOK_WIN32A, 0, hTask );
     return (handle) ? (HHOOK)MAKELONG( handle, HOOK_MAGIC ) : 0;
 }
 
@@ -1208,12 +1206,10 @@
  */
 HHOOK WINAPI SetWindowsHook32W( INT32 id, HOOKPROC32 proc )
 {
-    HINSTANCE16 hInst = __winelib ? 0 : FarGetOwner( HIWORD(proc) );
-
     /* WH_MSGFILTER is the only task-specific hook for SetWindowsHook() */
     HTASK16 hTask = (id == WH_MSGFILTER) ? GetCurrentTask() : 0;
 
-    HANDLE16 handle = HOOK_SetHook( id, proc, HOOK_WIN32W, hInst, hTask );
+    HANDLE16 handle = HOOK_SetHook( id, proc, HOOK_WIN32W, 0, hTask );
     return (handle) ? (HHOOK)MAKELONG( handle, HOOK_MAGIC ) : 0;
 }
 
@@ -1241,7 +1237,7 @@
     if (dwThreadID == GetCurrentThreadId())
       hTask = GetCurrentTask();
     else
-      hTask = LOWORD(dwThreadID);
+      hTask = LOWORD(dwThreadID);  /* FIXME! */
 
     handle = HOOK_SetHook( id, proc, HOOK_WIN32A, hInst, hTask );
     return (handle) ? (HHOOK)MAKELONG( handle, HOOK_MAGIC ) : (HHOOK)NULL;
@@ -1260,7 +1256,7 @@
     if (dwThreadID == GetCurrentThreadId())
       hTask = GetCurrentTask();
     else
-      hTask = LOWORD(dwThreadID);
+      hTask = LOWORD(dwThreadID);  /* FIXME! */
 
     handle = HOOK_SetHook( id, proc, HOOK_WIN32W, hInst, hTask );
     return (handle) ? (HHOOK)MAKELONG( handle, HOOK_MAGIC ) : (HHOOK)NULL;
diff --git a/windows/mdi.c b/windows/mdi.c
index ac848c3..394b4c3 100644
--- a/windows/mdi.c
+++ b/windows/mdi.c
@@ -1466,12 +1466,51 @@
 
 
 /**********************************************************************
- *              CreateMDIWindowA (USER32.79)
+ * CreateMDIWindowA [USER32.79]
  */
+HWND32 WINAPI CreateMDIWindowA(
+    LPCSTR lpClassName,
+    LPCSTR lpWindowName,
+    DWORD dwStyle,
+    INT32 X,
+    INT32 Y,
+    INT32 nWidth,
+    INT32 nHeight,
+    HWND32 hWndParent,
+    HINSTANCE32 hInstance,
+    LPARAM lParam)
+{
+    FIXME(mdi, "(%s,%s,%ld,...): stub\n",debugstr_a(lpClassName),
+          debugstr_a(lpWindowName),dwStyle);
+    return (HWND32)NULL;
+}
 
-/**********************************************************************
- *              CreateMDIWindowW (USER32.80)
+
+/******************************************************************************
+ * CreateMDIWindowW [USER32.80]  Creates a MDI child window
+ *
+ * RETURNS
+ *    Success: Handle to created window
+ *    Failure: NULL
  */
+HWND32 WINAPI CreateMDIWindowW(
+    LPCWSTR lpClassName,   /* [in] Pointer to registered child class name */
+    LPCWSTR lpWindowName,  /* [in] Pointer to window name */
+    DWORD dwStyle,         /* [in] Window style */
+    INT32 X,               /* [in] Horizontal position of window */
+    INT32 Y,               /* [in] Vertical position of window */
+    INT32 nWidth,          /* [in] Width of window */
+    INT32 nHeight,         /* [in] Height of window */
+    HWND32 hWndParent,     /* [in] Handle to parent window */
+    HINSTANCE32 hInstance, /* [in] Handle to application instance */
+    LPARAM lParam)         /* [in] Application-defined value */
+{
+    FIXME(mdi, "(%s,%s,%ld,%d,%d,%d,%d,%x,%d,%ld): stub\n",
+          debugstr_w(lpClassName),debugstr_w(lpWindowName),dwStyle,X,Y,
+          nWidth,nHeight,hWndParent,hInstance,lParam);
+    return (HWND32)NULL;
+}
+
 
 /**********************************************************************
  *             TranslateMDISysAccel32   (USER32.555)
diff --git a/windows/queue.c b/windows/queue.c
index 1bf2270..7ecd256 100644
--- a/windows/queue.c
+++ b/windows/queue.c
@@ -816,7 +816,8 @@
  */
 DWORD WINAPI WaitForInputIdle (HANDLE32 hProcess, DWORD dwTimeOut)
 {
-  FIXME (msg, "WaitForInputIdle: stub\n");
+  FIXME (msg, "(hProcess=%d, dwTimeOut=%d): stub\n", hProcess, dwTimeOut);
+
   return WAIT_TIMEOUT;
 }
 
diff --git a/windows/user.c b/windows/user.c
index 249cfa7..f0d920e 100644
--- a/windows/user.c
+++ b/windows/user.c
@@ -20,6 +20,7 @@
 #include "debug.h"
 #include "toolhelp.h"
 #include "message.h"
+#include "module.h"
 #include "miscemu.h"
 #include "shell.h"
 
diff --git a/windows/win.c b/windows/win.c
index c251cba..5563a76 100644
--- a/windows/win.c
+++ b/windows/win.c
@@ -743,7 +743,11 @@
             if (!(wndPtr->flags & WIN_NEED_SIZE))
             {
                 /* send it anyway */
-
+	        if (((wndPtr->rectClient.right-wndPtr->rectClient.left) <0)
+		    ||((wndPtr->rectClient.bottom-wndPtr->rectClient.top)<0))
+		  WARN(win,"sending bogus WM_SIZE message 0x%08lx\n",
+			MAKELONG(wndPtr->rectClient.right-wndPtr->rectClient.left,
+				 wndPtr->rectClient.bottom-wndPtr->rectClient.top));
                 SendMessage32A( hwnd, WM_SIZE, SIZE_RESTORED,
                                 MAKELONG(wndPtr->rectClient.right-wndPtr->rectClient.left,
                                          wndPtr->rectClient.bottom-wndPtr->rectClient.top));
@@ -1408,7 +1412,8 @@
     	if (HIWORD(wndPtr->wIDmenu))
     		fprintf(stderr,"GetWindowWord32(GWW_ID) discards high bits of 0x%08x!\n",wndPtr->wIDmenu);
     	return (WORD)wndPtr->wIDmenu;
-    case GWW_HWNDPARENT: return wndPtr->parent ? wndPtr->parent->hwndSelf : 0;
+    case GWW_HWNDPARENT: return wndPtr->parent ?
+			wndPtr->parent->hwndSelf : wndPtr->owner->hwndSelf;
     case GWW_HINSTANCE:  
     	if (HIWORD(wndPtr->hInstance))
     		fprintf(stderr,"GetWindowWord32(GWW_HINSTANCE) discards high bits of 0x%08x!\n",wndPtr->hInstance);
diff --git a/windows/winpos.c b/windows/winpos.c
index e992acc..516f6e8 100644
--- a/windows/winpos.c
+++ b/windows/winpos.c
@@ -238,6 +238,41 @@
 
 
 /***********************************************************************
+ *           GetWindowRgn32 
+ */
+BOOL32 WINAPI GetWindowRgn32 ( HWND32 hwnd, HRGN32 hrgn )
+
+{
+  RECT32    rect;
+  WND * wndPtr = WIN_FindWndPtr( hwnd ); 
+  if (!wndPtr) return (ERROR);
+
+  FIXME (win, "GetWindowRgn32: doesn't really do regions\n"); 
+  
+  memset (&rect, 0, sizeof(rect));
+
+  GetWindowRect32 ( hwnd, &rect );
+
+  FIXME (win, "Check whether a valid region here\n");
+
+  SetRectRgn32 ( hrgn, rect.left, rect.top, rect.right, rect.bottom );
+
+  return (SIMPLEREGION);
+}
+
+/***********************************************************************
+ *           SetWindowRgn32 
+ */
+BOOL32 WINAPI SetWindowRgn32 ( HWND32 hwnd, HRGN32 hrgn,BOOL32 bRedraw)
+
+{
+
+  FIXME (win, "SetWindowRgn32: stub\n"); 
+  return TRUE;
+}
+
+
+/***********************************************************************
  *           GetClientRect16   (USER.33)
  */
 void WINAPI GetClientRect16( HWND16 hwnd, LPRECT16 rect ) 
diff --git a/windows/winproc.c b/windows/winproc.c
index 66df775..517272b 100644
--- a/windows/winproc.c
+++ b/windows/winproc.c
@@ -251,7 +251,9 @@
         if (((WINDOWPROC *)proc)->type == WIN_PROC_16)
             return (WNDPROC16)&((WINDOWPROC *)proc)->thunk;
         else
-            return (WNDPROC16)&((WINDOWPROC *)proc)->jmp;
+            /* return (WNDPROC16)&((WINDOWPROC *)proc)->jmp; */
+            /* Some Win16 programs want to get back the proc they set */
+            return (WNDPROC16)((WINDOWPROC *)proc)->thunk.t_from16.proc;
     }
 }