scons: Play nice with MS Embedded Visual C++.
diff --git a/SConstruct b/SConstruct
index e7c10fc..5f7b6dd 100644
--- a/SConstruct
+++ b/SConstruct
@@ -85,7 +85,7 @@
 # TODO: auto-detect as much as possible
 
 if platform == 'winddk':
-	env.Tool('winddk', ['.'])
+	env.Tool('winddk', ['scons'])
 	
 	env.Append(CPPPATH = [
 		env['SDK_INC_PATH'],
@@ -94,6 +94,9 @@
 		env['CRT_INC_PATH'],
 	])
 
+if platform == 'wince':
+	env.Tool('evc', ['scons'])
+
 common.generate(env)
 
 
diff --git a/common.py b/common.py
index d3c0261..c040c6d 100644
--- a/common.py
+++ b/common.py
@@ -34,7 +34,7 @@
 
 if default_platform in ('linux', 'freebsd', 'darwin'):
 	default_dri = 'yes'
-elif default_platform in ('winddk', 'windows'):
+elif default_platform in ('winddk', 'windows', 'wince'):
 	default_dri = 'no'
 else:
 	default_dri = 'no'
@@ -58,7 +58,7 @@
 	opts.Add(EnumOption('machine', 'use machine-specific assembly code', default_machine,
 											 allowed_values=('generic', 'x86', 'x86_64')))
 	opts.Add(EnumOption('platform', 'target platform', default_platform,
-											 allowed_values=('linux', 'cell', 'windows', 'winddk')))
+											 allowed_values=('linux', 'cell', 'windows', 'winddk', 'wince')))
 	opts.Add(BoolOption('llvm', 'use LLVM', 'no'))
 	opts.Add(BoolOption('dri', 'build DRI drivers', default_dri))
 
@@ -149,7 +149,7 @@
 	platform = env['platform']
 	x86 = env['machine'] == 'x86'
 	gcc = env['platform'] in ('linux', 'freebsd', 'darwin')
-	msvc = env['platform'] in ('windows', 'winddk')
+	msvc = env['platform'] in ('windows', 'winddk', 'wince')
 
 	# C preprocessor options
 	cppdefines = []
@@ -196,6 +196,19 @@
 		]
 		if debug:
 			cppdefines += [('DBG', 1)]
+	if platform == 'wince':
+		cppdefines += [
+			('_WIN32_WCE', '500'), 
+			'WCE_PLATFORM_STANDARDSDK_500',
+			'_i386_',
+			('UNDER_CE', '500'),
+			'UNICODE',
+			'_UNICODE',
+			'_X86_',
+			'x86',
+			'_USRDLL',
+			'TEST_EXPORTS' ,
+		]
 	if platform == 'windows':
 		cppdefines += ['PIPE_SUBSYSTEM_USER']
 	if platform == 'winddk':
@@ -264,6 +277,11 @@
 				'/hotpatch', # prepares an image for hotpatching.
 				#'/Z7', #enable old-style debug info
 			]
+		if platform == 'wince':
+			cflags += [
+				'/Gs8192',
+				'/GF', # enable read-only string pooling
+			]
 		# Put debugging information in a separate .pdb file for each object file as
 		# descrived in the scons manpage
 		env['CCPDBFLAGS'] = '/Zi /Fd${TARGET}.pdb'
diff --git a/scons/evc.py b/scons/evc.py
new file mode 100644
index 0000000..22a9260
--- /dev/null
+++ b/scons/evc.py
@@ -0,0 +1,108 @@
+"""evc
+
+Tool-specific initialization for Microsoft eMbedded Visual C++.
+
+"""
+
+#
+# Copyright (c) 2001-2007 The SCons Foundation
+# Copyright (c) 2008 Tungsten Graphics, Inc.
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+
+import os.path
+import re
+import string
+
+import SCons.Action
+import SCons.Builder
+import SCons.Errors
+import SCons.Platform.win32
+import SCons.Tool
+import SCons.Util
+import SCons.Warnings
+
+import msvc_sa
+import mslib_sa
+import mslink_sa
+
+def get_evc_paths(env, version=None):
+    """Return a 3-tuple of (INCLUDE, LIB, PATH) as the values
+    of those three environment variables that should be set
+    in order to execute the MSVC tools properly."""
+    
+    exe_paths = []
+    lib_paths = []
+    include_paths = []
+
+    # mymic the batch files located in Microsoft eMbedded C++ 4.0\EVC\WCExxx\BIN
+    os_version = os.environ.get('OSVERSION', 'WCE500')
+    platform = os.environ.get('PLATFORM', 'STANDARDSDK_500')
+    wce_root = os.environ.get('WCEROOT', 'C:\\Program Files\\Microsoft eMbedded C++ 4.0')
+    sdk_root = os.environ.get('SDKROOT', 'C:\\Windows CE Tools')
+
+    target_cpu = 'x86'
+    cfg = 'none'
+
+    exe_paths.append( os.path.join(wce_root, 'COMMON', 'EVC', 'bin') )
+    exe_paths.append( os.path.join(wce_root, 'EVC', os_version, 'bin') )
+    include_paths.append( os.path.join(sdk_root, os_version, platform, 'include', target_cpu) )
+    include_paths.append( os.path.join(sdk_root, os_version, platform, 'MFC', 'include') )
+    include_paths.append( os.path.join(sdk_root, os_version, platform, 'ATL', 'include') )
+    lib_paths.append( os.path.join(sdk_root, os_version, platform, 'lib', target_cpu) )
+    lib_paths.append( os.path.join(sdk_root, os_version, platform, 'MFC', 'lib', target_cpu) )
+    lib_paths.append( os.path.join(sdk_root, os_version, platform, 'ATL', 'lib', target_cpu) )
+    
+    include_path = string.join( include_paths, os.pathsep )
+    lib_path = string.join(lib_paths, os.pathsep )
+    exe_path = string.join(exe_paths, os.pathsep )
+    return (include_path, lib_path, exe_path)
+
+def generate(env):
+
+    msvc_sa.generate(env)
+    mslib_sa.generate(env)
+    mslink_sa.generate(env)
+
+    if not env.has_key('ENV'):
+        env['ENV'] = {}
+    
+    try:
+        include_path, lib_path, exe_path = get_evc_paths(env)
+
+        # since other tools can set these, we just make sure that the
+        # relevant stuff from WINDDK is in there somewhere.
+        env.PrependENVPath('INCLUDE', include_path)
+        env.PrependENVPath('LIB', lib_path)
+        env.PrependENVPath('PATH', exe_path)
+    except (SCons.Util.RegError, SCons.Errors.InternalError):
+        pass
+
+def exists(env):
+    if not msvc_sa.exits(env):
+        return 0
+    if not mslib_sa.exits(env):
+        return 0
+    if not mslink_sa.exits(env):
+        return 0
+    return 1
+
+# vim:set ts=4 sw=4 et:
diff --git a/scons/mslib_sa.py b/scons/mslib_sa.py
new file mode 100644
index 0000000..da51c57
--- /dev/null
+++ b/scons/mslib_sa.py
@@ -0,0 +1,49 @@
+"""mslib_sa
+
+Tool-specific initialization for lib (MicroSoft library archiver).
+
+Based on SCons.Tool.mslib, without the MSVC detection.
+
+"""
+
+#
+# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+
+import SCons.Defaults
+import SCons.Tool
+import SCons.Util
+
+def generate(env):
+    """Add Builders and construction variables for lib to an Environment."""
+    SCons.Tool.createStaticLibBuilder(env)
+
+    env['AR']          = 'lib'
+    env['ARFLAGS']     = SCons.Util.CLVar('/nologo')
+    env['ARCOM']       = "${TEMPFILE('$AR $ARFLAGS /OUT:$TARGET $SOURCES')}"
+    env['LIBPREFIX']   = ''
+    env['LIBSUFFIX']   = '.lib'
+
+def exists(env):
+    return env.Detect('lib')
+
+# vim:set ts=4 sw=4 et:
diff --git a/scons/mslink_sa.py b/scons/mslink_sa.py
new file mode 100644
index 0000000..53331de
--- /dev/null
+++ b/scons/mslink_sa.py
@@ -0,0 +1,211 @@
+"""mslink_sa
+
+Tool-specific initialization for the Microsoft linker.
+
+Based on SCons.Tool.mslink, without the MSVS detection.
+
+"""
+
+#
+# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+
+import os.path
+
+import SCons.Action
+import SCons.Defaults
+import SCons.Errors
+import SCons.Platform.win32
+import SCons.Tool
+import SCons.Tool.msvc
+import SCons.Util
+
+def pdbGenerator(env, target, source, for_signature):
+    try:
+        return ['/PDB:%s' % target[0].attributes.pdb, '/DEBUG']
+    except (AttributeError, IndexError):
+        return None
+
+def windowsShlinkTargets(target, source, env, for_signature):
+    listCmd = []
+    dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX')
+    if dll: listCmd.append("/out:%s"%dll.get_string(for_signature))
+
+    implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX')
+    if implib: listCmd.append("/implib:%s"%implib.get_string(for_signature))
+
+    return listCmd
+
+def windowsShlinkSources(target, source, env, for_signature):
+    listCmd = []
+
+    deffile = env.FindIxes(source, "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX")
+    for src in source:
+        if src == deffile:
+            # Treat this source as a .def file.
+            listCmd.append("/def:%s" % src.get_string(for_signature))
+        else:
+            # Just treat it as a generic source file.
+            listCmd.append(src)
+    return listCmd
+
+def windowsLibEmitter(target, source, env):
+    SCons.Tool.msvc.validate_vars(env)
+
+    extratargets = []
+    extrasources = []
+
+    dll = env.FindIxes(target, "SHLIBPREFIX", "SHLIBSUFFIX")
+    no_import_lib = env.get('no_import_lib', 0)
+
+    if not dll:
+        raise SCons.Errors.UserError, "A shared library should have exactly one target with the suffix: %s" % env.subst("$SHLIBSUFFIX")
+
+    insert_def = env.subst("$WINDOWS_INSERT_DEF")
+    if not insert_def in ['', '0', 0] and \
+       not env.FindIxes(source, "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX"):
+
+        # append a def file to the list of sources
+        extrasources.append(
+            env.ReplaceIxes(dll,
+                            "SHLIBPREFIX", "SHLIBSUFFIX",
+                            "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX"))
+
+    if env.has_key('PDB') and env['PDB']:
+        pdb = env.arg2nodes('$PDB', target=target, source=source)[0]
+        extratargets.append(pdb)
+        target[0].attributes.pdb = pdb
+
+    if not no_import_lib and \
+       not env.FindIxes(target, "LIBPREFIX", "LIBSUFFIX"):
+        # Append an import library to the list of targets.
+        extratargets.append(
+            env.ReplaceIxes(dll,
+                            "SHLIBPREFIX", "SHLIBSUFFIX",
+                            "LIBPREFIX", "LIBSUFFIX"))
+        # and .exp file is created if there are exports from a DLL
+        extratargets.append(
+            env.ReplaceIxes(dll,
+                            "SHLIBPREFIX", "SHLIBSUFFIX",
+                            "WINDOWSEXPPREFIX", "WINDOWSEXPSUFFIX"))
+
+    return (target+extratargets, source+extrasources)
+
+def prog_emitter(target, source, env):
+    SCons.Tool.msvc.validate_vars(env)
+
+    extratargets = []
+
+    exe = env.FindIxes(target, "PROGPREFIX", "PROGSUFFIX")
+    if not exe:
+        raise SCons.Errors.UserError, "An executable should have exactly one target with the suffix: %s" % env.subst("$PROGSUFFIX")
+
+    if env.has_key('PDB') and env['PDB']:
+        pdb = env.arg2nodes('$PDB', target=target, source=source)[0]
+        extratargets.append(pdb)
+        target[0].attributes.pdb = pdb
+
+    return (target+extratargets,source)
+
+def RegServerFunc(target, source, env):
+    if env.has_key('register') and env['register']:
+        ret = regServerAction([target[0]], [source[0]], env)
+        if ret:
+            raise SCons.Errors.UserError, "Unable to register %s" % target[0]
+        else:
+            print "Registered %s sucessfully" % target[0]
+        return ret
+    return 0
+
+regServerAction = SCons.Action.Action("$REGSVRCOM", "$REGSVRCOMSTR")
+regServerCheck = SCons.Action.Action(RegServerFunc, None)
+shlibLinkAction = SCons.Action.Action('${TEMPFILE("$SHLINK $SHLINKFLAGS $_SHLINK_TARGETS $( $_LIBDIRFLAGS $) $_LIBFLAGS $_PDB $_SHLINK_SOURCES")}')
+compositeLinkAction = shlibLinkAction + regServerCheck
+
+def generate(env):
+    """Add Builders and construction variables for ar to an Environment."""
+    SCons.Tool.createSharedLibBuilder(env)
+    SCons.Tool.createProgBuilder(env)
+
+    env['SHLINK']      = '$LINK'
+    env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS /dll')
+    env['_SHLINK_TARGETS'] = windowsShlinkTargets
+    env['_SHLINK_SOURCES'] = windowsShlinkSources
+    env['SHLINKCOM']   =  compositeLinkAction
+    env.Append(SHLIBEMITTER = [windowsLibEmitter])
+    env['LINK']        = 'link'
+    env['LINKFLAGS']   = SCons.Util.CLVar('/nologo')
+    env['_PDB'] = pdbGenerator
+    env['LINKCOM'] = '${TEMPFILE("$LINK $LINKFLAGS /OUT:$TARGET.windows $( $_LIBDIRFLAGS $) $_LIBFLAGS $_PDB $SOURCES.windows")}'
+    env.Append(PROGEMITTER = [prog_emitter])
+    env['LIBDIRPREFIX']='/LIBPATH:'
+    env['LIBDIRSUFFIX']=''
+    env['LIBLINKPREFIX']=''
+    env['LIBLINKSUFFIX']='$LIBSUFFIX'
+
+    env['WIN32DEFPREFIX']        = ''
+    env['WIN32DEFSUFFIX']        = '.def'
+    env['WIN32_INSERT_DEF']      = 0
+    env['WINDOWSDEFPREFIX']      = '${WIN32DEFPREFIX}'
+    env['WINDOWSDEFSUFFIX']      = '${WIN32DEFSUFFIX}'
+    env['WINDOWS_INSERT_DEF']    = '${WIN32_INSERT_DEF}'
+
+    env['WIN32EXPPREFIX']        = ''
+    env['WIN32EXPSUFFIX']        = '.exp'
+    env['WINDOWSEXPPREFIX']      = '${WIN32EXPPREFIX}'
+    env['WINDOWSEXPSUFFIX']      = '${WIN32EXPSUFFIX}'
+
+    env['WINDOWSSHLIBMANIFESTPREFIX'] = ''
+    env['WINDOWSSHLIBMANIFESTSUFFIX'] = '${SHLIBSUFFIX}.manifest'
+    env['WINDOWSPROGMANIFESTPREFIX']  = ''
+    env['WINDOWSPROGMANIFESTSUFFIX']  = '${PROGSUFFIX}.manifest'
+
+    env['REGSVRACTION'] = regServerCheck
+    env['REGSVR'] = os.path.join(SCons.Platform.win32.get_system_root(),'System32','regsvr32')
+    env['REGSVRFLAGS'] = '/s '
+    env['REGSVRCOM'] = '$REGSVR $REGSVRFLAGS ${TARGET.windows}'
+
+    # For most platforms, a loadable module is the same as a shared
+    # library.  Platforms which are different can override these, but
+    # setting them the same means that LoadableModule works everywhere.
+    SCons.Tool.createLoadableModuleBuilder(env)
+    env['LDMODULE'] = '$SHLINK'
+    env['LDMODULEPREFIX'] = '$SHLIBPREFIX'
+    env['LDMODULESUFFIX'] = '$SHLIBSUFFIX'
+    env['LDMODULEFLAGS'] = '$SHLINKFLAGS'
+    # We can't use '$SHLINKCOM' here because that will stringify the
+    # action list on expansion, and will then try to execute expanded
+    # strings, with the upshot that it would try to execute RegServerFunc
+    # as a command.
+    env['LDMODULECOM'] = compositeLinkAction
+
+def exists(env):
+    platform = env.get('PLATFORM', '')
+    if platform in ('win32', 'cygwin'):
+        # Only explicitly search for a 'link' executable on Windows
+        # systems.  Some other systems (e.g. Ubuntu Linux) have an
+        # executable named 'link' and we don't want that to make SCons
+        # think Visual Studio is installed.
+        return env.Detect('link')
+    return None
+
+# vim:set ts=4 sw=4 et:
diff --git a/winddk.py b/scons/msvc_sa.py
similarity index 69%
rename from winddk.py
rename to scons/msvc_sa.py
index 58de183..136d305 100644
--- a/winddk.py
+++ b/scons/msvc_sa.py
@@ -1,18 +1,13 @@
-"""winddk
+"""msvc_sa
 
-Tool-specific initialization for Microsoft Windows DDK.
+Tool-specific initialization for Microsoft Visual C/C++.
 
-Based on engine.SCons.Tool.msvc.
-
-There normally shouldn't be any need to import this module directly.
-It will usually be imported through the generic SCons.Tool.Tool()
-selection method.
+Based on SCons.Tool.msvc, without the MSVS detection.
 
 """
 
 #
-# Copyright (c) 2001-2007 The SCons Foundation
-# Copyright (c) 2008 Tungsten Graphics, Inc.
+# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
 #
 # Permission is hereby granted, free of charge, to any person obtaining
 # a copy of this software and associated documentation files (the
@@ -43,52 +38,12 @@
 import SCons.Errors
 import SCons.Platform.win32
 import SCons.Tool
-import SCons.Tool.mslib
-import SCons.Tool.mslink
 import SCons.Util
 import SCons.Warnings
 
 CSuffixes = ['.c', '.C']
 CXXSuffixes = ['.cc', '.cpp', '.cxx', '.c++', '.C++']
 
-def get_winddk_paths(env, version=None):
-    """Return a 3-tuple of (INCLUDE, LIB, PATH) as the values
-    of those three environment variables that should be set
-    in order to execute the MSVC tools properly."""
-    
-    WINDDKdir = None
-    exe_paths = []
-    lib_paths = []
-    include_paths = []
-
-    if 'BASEDIR' in os.environ:
-        WINDDKdir = os.environ['BASEDIR']
-    else:
-        WINDDKdir = "C:\\WINDDK\\3790.1830"
-
-    exe_paths.append( os.path.join(WINDDKdir, 'bin') )
-    exe_paths.append( os.path.join(WINDDKdir, 'bin', 'x86') )
-    include_paths.append( os.path.join(WINDDKdir, 'inc', 'wxp') )
-    lib_paths.append( os.path.join(WINDDKdir, 'lib') )
-
-    target_os = 'wxp'
-    target_cpu = 'i386'
-    
-    env['SDK_INC_PATH'] = os.path.join(WINDDKdir, 'inc', target_os) 
-    env['CRT_INC_PATH'] = os.path.join(WINDDKdir, 'inc', 'crt') 
-    env['DDK_INC_PATH'] = os.path.join(WINDDKdir, 'inc', 'ddk', target_os) 
-    env['WDM_INC_PATH'] = os.path.join(WINDDKdir, 'inc', 'ddk', 'wdm', target_os) 
-
-    env['SDK_LIB_PATH'] = os.path.join(WINDDKdir, 'lib', target_os, target_cpu) 
-    env['CRT_LIB_PATH'] = os.path.join(WINDDKdir, 'lib', 'crt', target_cpu) 
-    env['DDK_LIB_PATH'] = os.path.join(WINDDKdir, 'lib', target_os, target_cpu)
-    env['WDM_LIB_PATH'] = os.path.join(WINDDKdir, 'lib', target_os, target_cpu)
-                                     
-    include_path = string.join( include_paths, os.pathsep )
-    lib_path = string.join(lib_paths, os.pathsep )
-    exe_path = string.join(exe_paths, os.pathsep )
-    return (include_path, lib_path, exe_path)
-
 def validate_vars(env):
     """Validate the PCH and PCHSTOP construction variables."""
     if env.has_key('PCH') and env['PCH']:
@@ -207,30 +162,12 @@
     env['PCHCOM'] = '$CXX $CXXFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Fo${TARGETS[1]} /Yc$PCHSTOP /Fp${TARGETS[0]} $CCPDBFLAGS $PCHPDBFLAGS'
     env['BUILDERS']['PCH'] = pch_builder
 
-    env['AR']          = 'lib'
-    env['ARFLAGS']     = SCons.Util.CLVar('/nologo')
-    env['ARCOM']       = "${TEMPFILE('$AR $ARFLAGS /OUT:$TARGET $SOURCES')}"
-    env['LIBPREFIX']   = ''
-    env['LIBSUFFIX']   = '.lib'
-
-    SCons.Tool.mslink.generate(env)
-
     if not env.has_key('ENV'):
         env['ENV'] = {}
-    
-    try:
-        include_path, lib_path, exe_path = get_winddk_paths(env)
-
-        # since other tools can set these, we just make sure that the
-        # relevant stuff from WINDDK is in there somewhere.
-        env.PrependENVPath('INCLUDE', include_path)
-        env.PrependENVPath('LIB', lib_path)
-        env.PrependENVPath('PATH', exe_path)
-    except (SCons.Util.RegError, SCons.Errors.InternalError):
-        pass
-
+    if not env['ENV'].has_key('SystemRoot'):    # required for dlls in the winsxs folders
+        env['ENV']['SystemRoot'] = SCons.Platform.win32.get_system_root()
 
 def exists(env):
     return env.Detect('cl')
 
-# vim:set sw=4 et:
+# vim:set ts=4 sw=4 et:
diff --git a/scons/winddk.py b/scons/winddk.py
new file mode 100644
index 0000000..be81d12
--- /dev/null
+++ b/scons/winddk.py
@@ -0,0 +1,114 @@
+"""winddk
+
+Tool-specific initialization for Microsoft Windows DDK.
+
+"""
+
+#
+# Copyright (c) 2001-2007 The SCons Foundation
+# Copyright (c) 2008 Tungsten Graphics, Inc.
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+
+import os.path
+import re
+import string
+
+import SCons.Action
+import SCons.Builder
+import SCons.Errors
+import SCons.Platform.win32
+import SCons.Tool
+import SCons.Util
+import SCons.Warnings
+
+import msvc_sa
+import mslib_sa
+import mslink_sa
+
+def get_winddk_paths(env, version=None):
+    """Return a 3-tuple of (INCLUDE, LIB, PATH) as the values
+    of those three environment variables that should be set
+    in order to execute the MSVC tools properly."""
+    
+    WINDDKdir = None
+    exe_paths = []
+    lib_paths = []
+    include_paths = []
+
+    if 'BASEDIR' in os.environ:
+        WINDDKdir = os.environ['BASEDIR']
+    else:
+        WINDDKdir = "C:\\WINDDK\\3790.1830"
+
+    exe_paths.append( os.path.join(WINDDKdir, 'bin') )
+    exe_paths.append( os.path.join(WINDDKdir, 'bin', 'x86') )
+    include_paths.append( os.path.join(WINDDKdir, 'inc', 'wxp') )
+    lib_paths.append( os.path.join(WINDDKdir, 'lib') )
+
+    target_os = 'wxp'
+    target_cpu = 'i386'
+    
+    env['SDK_INC_PATH'] = os.path.join(WINDDKdir, 'inc', target_os) 
+    env['CRT_INC_PATH'] = os.path.join(WINDDKdir, 'inc', 'crt') 
+    env['DDK_INC_PATH'] = os.path.join(WINDDKdir, 'inc', 'ddk', target_os) 
+    env['WDM_INC_PATH'] = os.path.join(WINDDKdir, 'inc', 'ddk', 'wdm', target_os) 
+
+    env['SDK_LIB_PATH'] = os.path.join(WINDDKdir, 'lib', target_os, target_cpu) 
+    env['CRT_LIB_PATH'] = os.path.join(WINDDKdir, 'lib', 'crt', target_cpu) 
+    env['DDK_LIB_PATH'] = os.path.join(WINDDKdir, 'lib', target_os, target_cpu)
+    env['WDM_LIB_PATH'] = os.path.join(WINDDKdir, 'lib', target_os, target_cpu)
+                                     
+    include_path = string.join( include_paths, os.pathsep )
+    lib_path = string.join(lib_paths, os.pathsep )
+    exe_path = string.join(exe_paths, os.pathsep )
+    return (include_path, lib_path, exe_path)
+
+def generate(env):
+
+    msvc_sa.generate(env)
+    mslib_sa.generate(env)
+    mslink_sa.generate(env)
+
+    if not env.has_key('ENV'):
+        env['ENV'] = {}
+    
+    try:
+        include_path, lib_path, exe_path = get_winddk_paths(env)
+
+        # since other tools can set these, we just make sure that the
+        # relevant stuff from WINDDK is in there somewhere.
+        env.PrependENVPath('INCLUDE', include_path)
+        env.PrependENVPath('LIB', lib_path)
+        env.PrependENVPath('PATH', exe_path)
+    except (SCons.Util.RegError, SCons.Errors.InternalError):
+        pass
+
+def exists(env):
+    if not msvc_sa.exits(env):
+        return 0
+    if not mslib_sa.exits(env):
+        return 0
+    if not mslink_sa.exits(env):
+        return 0
+    return 1
+
+# vim:set ts=4 sw=4 et: