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/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",