From 0a98de9709ec744b8dd2047d2db98c2eed60b0bb Mon Sep 17 00:00:00 2001
From: Clinton Stimpson <clinton@elemtech.com>
Date: Wed, 30 Oct 2013 21:46:28 -0600
Subject: [PATCH] KWSys: Port to use wide character Windows APIs throughout.

Change-Id: Icb357202c5591819b9f44b4e4f1376e7c4f7b7b3
---
 CMakeLists.txt        |  11 ++
 Directory.cxx         |  17 +--
 DynamicLoader.cxx     |  19 +--
 ProcessWin32.c        |  78 +++++++-----
 SystemInformation.cxx |  32 ++---
 SystemTools.cxx       | 284 +++++++++++++++++++++++++++++-------------
 SystemTools.hxx.in    |   7 ++
 7 files changed, 296 insertions(+), 152 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1fbbe45..03b1dd6 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -132,18 +132,29 @@ ENDIF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
 # Enforce component dependencies.
 IF(KWSYS_USE_SystemTools)
   SET(KWSYS_USE_Directory 1)
+  SET(KWSYS_USE_FStream 1)
+  SET(KWSYS_USE_Encoding 1)
 ENDIF(KWSYS_USE_SystemTools)
 IF(KWSYS_USE_Glob)
   SET(KWSYS_USE_Directory 1)
   SET(KWSYS_USE_SystemTools 1)
   SET(KWSYS_USE_RegularExpression 1)
+  SET(KWSYS_USE_FStream 1)
+  SET(KWSYS_USE_Encoding 1)
 ENDIF(KWSYS_USE_Glob)
 IF(KWSYS_USE_Process)
   SET(KWSYS_USE_System 1)
+  SET(KWSYS_USE_Encoding 1)
 ENDIF(KWSYS_USE_Process)
 IF(KWSYS_USE_SystemInformation)
   SET(KWSYS_USE_Process 1)
 ENDIF(KWSYS_USE_SystemInformation)
+IF(KWSYS_USE_System)
+  SET(KWSYS_USE_Encoding 1)
+ENDIF(KWSYS_USE_System)
+IF(KWSYS_USE_Directory)
+  SET(KWSYS_USE_Encoding 1)
+ENDIF(KWSYS_USE_Directory)
 IF(KWSYS_USE_FStream)
   SET(KWSYS_USE_Encoding 1)
 ENDIF(KWSYS_USE_FStream)
diff --git a/Directory.cxx b/Directory.cxx
index b884747..d54e607 100644
--- a/Directory.cxx
+++ b/Directory.cxx
@@ -14,6 +14,8 @@
 
 #include KWSYS_HEADER(Configure.hxx)
 
+#include KWSYS_HEADER(Encoding.hxx)
+
 #include KWSYS_HEADER(stl/string)
 #include KWSYS_HEADER(stl/vector)
 
@@ -22,6 +24,7 @@
 #if 0
 # include "Directory.hxx.in"
 # include "Configure.hxx.in"
+# include "Encoding.hxx.in"
 # include "kwsys_stl.hxx.in"
 # include "kwsys_stl_string.hxx.in"
 # include "kwsys_stl_vector.hxx.in"
@@ -120,10 +123,10 @@ bool Directory::Load(const char* name)
     buf = new char[n + 2 + 1];
     sprintf(buf, "%s/*", name);
     }
-  struct _finddata_t data;      // data of current file
+  struct _wfinddata_t data;      // data of current file
 
   // Now put them into the file array
-  srchHandle = _findfirst(buf, &data);
+  srchHandle = _wfindfirst((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
   delete [] buf;
 
   if ( srchHandle == -1 )
@@ -134,9 +137,9 @@ bool Directory::Load(const char* name)
   // Loop through names
   do
     {
-    this->Internal->Files.push_back(data.name);
+    this->Internal->Files.push_back(Encoding::ToNarrow(data.name));
     }
-  while ( _findnext(srchHandle, &data) != -1 );
+  while ( _wfindnext(srchHandle, &data) != -1 );
   this->Internal->Path = name;
   return _findclose(srchHandle) != -1;
 }
@@ -160,10 +163,10 @@ unsigned long Directory::GetNumberOfFilesInDirectory(const char* name)
     buf = new char[n + 2 + 1];
     sprintf(buf, "%s/*", name);
     }
-  struct _finddata_t data;      // data of current file
+  struct _wfinddata_t data;      // data of current file
 
   // Now put them into the file array
-  srchHandle = _findfirst(buf, &data);
+  srchHandle = _wfindfirst((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
   delete [] buf;
 
   if ( srchHandle == -1 )
@@ -177,7 +180,7 @@ unsigned long Directory::GetNumberOfFilesInDirectory(const char* name)
     {
     count++;
     }
-  while ( _findnext(srchHandle, &data) != -1 );
+  while ( _wfindnext(srchHandle, &data) != -1 );
   _findclose(srchHandle);
   return count;
 }
diff --git a/DynamicLoader.cxx b/DynamicLoader.cxx
index fd83752..44cf6af 100644
--- a/DynamicLoader.cxx
+++ b/DynamicLoader.cxx
@@ -186,13 +186,12 @@ namespace KWSYS_NAMESPACE
 DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname)
 {
   DynamicLoader::LibraryHandle lh;
-#ifdef UNICODE
-  wchar_t libn[MB_CUR_MAX];
-  mbstowcs(libn, libname, MB_CUR_MAX);
-  lh = LoadLibrary(libn);
-#else
-  lh = LoadLibrary(libname);
-#endif
+  int length = MultiByteToWideChar(CP_UTF8, 0, libname, -1, NULL, 0);
+  wchar_t* wchars = new wchar_t[length+1];
+  wchars[0] = '\0';
+  MultiByteToWideChar(CP_UTF8, 0, libname, -1, wchars, length);
+  lh = LoadLibraryW(wchars);
+  delete [] wchars;
   return lh;
 }
 
@@ -238,13 +237,7 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
 #else
   const char *rsym = sym;
 #endif
-#ifdef UNICODE
-  wchar_t wsym[MB_CUR_MAX];
-  mbstowcs(wsym, rsym, MB_CUR_MAX);
-  result = GetProcAddress(lib, wsym);
-#else
   result = (void*)GetProcAddress(lib, rsym);
-#endif
 #if defined(__BORLANDC__) || defined(__WATCOMC__)
   delete[] rsym;
 #endif
diff --git a/ProcessWin32.c b/ProcessWin32.c
index c836f9b..c8ec754 100644
--- a/ProcessWin32.c
+++ b/ProcessWin32.c
@@ -12,12 +12,14 @@
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Process.h)
 #include KWSYS_HEADER(System.h)
+#include KWSYS_HEADER(Encoding.h)
 
 /* Work-around CMake dependency scanning limitation.  This must
    duplicate the above list of headers.  */
 #if 0
 # include "Process.h.in"
 # include "System.h.in"
+# include "Encoding_c.h.in"
 #endif
 
 /*
@@ -88,9 +90,10 @@ typedef LARGE_INTEGER kwsysProcessTime;
 typedef struct kwsysProcessCreateInformation_s
 {
   /* Windows child startup control data.  */
-  STARTUPINFO StartupInfo;
+  STARTUPINFOW StartupInfo;
 } kwsysProcessCreateInformation;
 
+
 /*--------------------------------------------------------------------------*/
 typedef struct kwsysProcessPipeData_s kwsysProcessPipeData;
 static DWORD WINAPI kwsysProcessPipeThreadRead(LPVOID ptd);
@@ -197,14 +200,14 @@ struct kwsysProcess_s
   int State;
 
   /* The command lines to execute.  */
-  char** Commands;
+  wchar_t** Commands;
   int NumberOfCommands;
 
   /* The exit code of each command.  */
   DWORD* CommandExitCodes;
 
   /* The working directory for the child process.  */
-  char* WorkingDirectory;
+  wchar_t* WorkingDirectory;
 
   /* Whether to create the child as a detached process.  */
   int OptionDetach;
@@ -299,7 +302,7 @@ struct kwsysProcess_s
 
   /* Real working directory of our own process.  */
   DWORD RealWorkingDirectoryLength;
-  char* RealWorkingDirectory;
+  wchar_t* RealWorkingDirectory;
 };
 
 /*--------------------------------------------------------------------------*/
@@ -546,7 +549,7 @@ int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
 int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
 {
   int newNumberOfCommands;
-  char** newCommands;
+  wchar_t** newCommands;
 
   /* Make sure we have a command to add.  */
   if(!cp || !command || !*command)
@@ -554,9 +557,10 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
     return 0;
     }
 
+
   /* Allocate a new array for command pointers.  */
   newNumberOfCommands = cp->NumberOfCommands + 1;
-  if(!(newCommands = (char**)malloc(sizeof(char*) * newNumberOfCommands)))
+  if(!(newCommands = (wchar_t**)malloc(sizeof(wchar_t*) * newNumberOfCommands)))
     {
     /* Out of memory.  */
     return 0;
@@ -585,8 +589,8 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
   /* Allocate enough space for the command.  We do not need an extra
      byte for the terminating null because we allocated a space for
      the first argument that we will not use.  */
-  newCommands[cp->NumberOfCommands] = (char*)malloc(length);
-  if(!newCommands[cp->NumberOfCommands])
+  char* new_cmd = malloc(length);
+  if(!new_cmd)
     {
     /* Out of memory.  */
     free(newCommands);
@@ -595,9 +599,13 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
 
   /* Construct the command line in the allocated buffer.  */
   kwsysProcessComputeCommandLine(cp, command,
-                                 newCommands[cp->NumberOfCommands]);
+                                 new_cmd);
+
+  newCommands[cp->NumberOfCommands] = kwsysEncoding_DupToWide(new_cmd);
+  free(new_cmd);
   }
 
+
   /* Save the new array of commands.  */
   free(cp->Commands);
   cp->Commands = newCommands;
@@ -633,22 +641,26 @@ int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
     }
   if(dir && dir[0])
     {
+    wchar_t* wdir = kwsysEncoding_DupToWide(dir);
     /* We must convert the working directory to a full path.  */
-    DWORD length = GetFullPathName(dir, 0, 0, 0);
+    DWORD length = GetFullPathNameW(wdir, 0, 0, 0);
     if(length > 0)
       {
-      cp->WorkingDirectory = (char*)malloc(length);
-      if(!cp->WorkingDirectory)
+      wchar_t* work_dir = malloc(length*sizeof(wchar_t));
+      if(!work_dir)
         {
+        free(wdir);
         return 0;
         }
-      if(!GetFullPathName(dir, length, cp->WorkingDirectory, 0))
+      if(!GetFullPathNameW(wdir, length, work_dir, 0))
         {
-        free(cp->WorkingDirectory);
-        cp->WorkingDirectory = 0;
+        free(work_dir);
+        free(wdir);
         return 0;
         }
+      cp->WorkingDirectory = work_dir;
       }
+    free(wdir);
     }
   return 1;
 }
@@ -879,13 +891,13 @@ void kwsysProcess_Execute(kwsysProcess* cp)
      to make pipe file paths evaluate correctly.  */
   if(cp->WorkingDirectory)
     {
-    if(!GetCurrentDirectory(cp->RealWorkingDirectoryLength,
+    if(!GetCurrentDirectoryW(cp->RealWorkingDirectoryLength,
                             cp->RealWorkingDirectory))
       {
       kwsysProcessCleanup(cp, 1);
       return;
       }
-    SetCurrentDirectory(cp->WorkingDirectory);
+    SetCurrentDirectoryW(cp->WorkingDirectory);
     }
 
   /* Initialize startup info data.  */
@@ -1003,7 +1015,7 @@ void kwsysProcess_Execute(kwsysProcess* cp)
   /* Restore the working directory.  */
   if(cp->RealWorkingDirectory)
     {
-    SetCurrentDirectory(cp->RealWorkingDirectory);
+    SetCurrentDirectoryW(cp->RealWorkingDirectory);
     free(cp->RealWorkingDirectory);
     cp->RealWorkingDirectory = 0;
     }
@@ -1507,10 +1519,10 @@ int kwsysProcessInitialize(kwsysProcess* cp)
   /* Allocate space to save the real working directory of this process.  */
   if(cp->WorkingDirectory)
     {
-    cp->RealWorkingDirectoryLength = GetCurrentDirectory(0, 0);
+    cp->RealWorkingDirectoryLength = GetCurrentDirectoryW(0, 0);
     if(cp->RealWorkingDirectoryLength > 0)
       {
-      cp->RealWorkingDirectory = (char*)malloc(cp->RealWorkingDirectoryLength);
+      cp->RealWorkingDirectory = malloc(cp->RealWorkingDirectoryLength * sizeof(wchar_t));
       if(!cp->RealWorkingDirectory)
         {
         return 0;
@@ -1547,9 +1559,11 @@ int kwsysProcessCreate(kwsysProcess* cp, int index,
   else if(cp->PipeFileSTDIN)
     {
     /* Create a handle to read a file for stdin.  */
-    HANDLE fin = CreateFile(cp->PipeFileSTDIN, GENERIC_READ|GENERIC_WRITE,
+    wchar_t* wstdin = kwsysEncoding_DupToWide(cp->PipeFileSTDIN);
+    HANDLE fin = CreateFileW(wstdin, GENERIC_READ|GENERIC_WRITE,
                             FILE_SHARE_READ|FILE_SHARE_WRITE,
                             0, OPEN_EXISTING, 0, 0);
+    free(wstdin);
     if(fin == INVALID_HANDLE_VALUE)
       {
       return 0;
@@ -1655,7 +1669,7 @@ int kwsysProcessCreate(kwsysProcess* cp, int index,
 
   /* Create the child in a suspended state so we can wait until all
      children have been created before running any one.  */
-  if(!CreateProcess(0, cp->Commands[index], 0, 0, TRUE, CREATE_SUSPENDED, 0,
+  if(!CreateProcessW(0, cp->Commands[index], 0, 0, TRUE, CREATE_SUSPENDED, 0,
                     0, &si->StartupInfo, &cp->ProcessInformation[index]))
     {
     return 0;
@@ -1729,6 +1743,7 @@ void kwsysProcessDestroy(kwsysProcess* cp, int event)
 int kwsysProcessSetupOutputPipeFile(PHANDLE phandle, const char* name)
 {
   HANDLE fout;
+  wchar_t* wname;
   if(!name)
     {
     return 1;
@@ -1738,8 +1753,10 @@ int kwsysProcessSetupOutputPipeFile(PHANDLE phandle, const char* name)
   kwsysProcessCleanupHandle(phandle);
 
   /* Create a handle to write a file for the pipe.  */
-  fout = CreateFile(name, GENERIC_WRITE, FILE_SHARE_READ, 0,
+  wname = kwsysEncoding_DupToWide(name);
+  fout = CreateFileW(wname, GENERIC_WRITE, FILE_SHARE_READ, 0,
                     CREATE_ALWAYS, 0, 0);
+  free(wname);
   if(fout == INVALID_HANDLE_VALUE)
     {
     return 0;
@@ -1883,10 +1900,13 @@ void kwsysProcessCleanup(kwsysProcess* cp, int error)
       {
       /* Format the error message.  */
       DWORD original = GetLastError();
-      DWORD length = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
+      wchar_t err_msg[KWSYSPE_PIPE_BUFFER_SIZE];
+      DWORD length = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
                                    FORMAT_MESSAGE_IGNORE_INSERTS, 0, original,
                                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-                                   cp->ErrorMessage, KWSYSPE_PIPE_BUFFER_SIZE, 0);
+                                   err_msg, KWSYSPE_PIPE_BUFFER_SIZE, 0);
+      WideCharToMultiByte(CP_UTF8, 0, err_msg, -1, cp->ErrorMessage,
+                          KWSYSPE_PIPE_BUFFER_SIZE, NULL, NULL);
       if(length < 1)
         {
         /* FormatMessage failed.  Use a default message.  */
@@ -1924,7 +1944,7 @@ void kwsysProcessCleanup(kwsysProcess* cp, int error)
     /* Restore the working directory.  */
     if(cp->RealWorkingDirectory)
       {
-      SetCurrentDirectory(cp->RealWorkingDirectory);
+      SetCurrentDirectoryW(cp->RealWorkingDirectory);
       }
     }
 
@@ -2222,7 +2242,7 @@ static void kwsysProcessSetExitException(kwsysProcess* cp, int code)
     case STATUS_NO_MEMORY:
     default:
       cp->ExitException = kwsysProcess_Exception_Other;
-      sprintf(cp->ExitExceptionString, "Exit code 0x%x\n", code);
+      _snprintf(cp->ExitExceptionString, KWSYSPE_PIPE_BUFFER_SIZE, "Exit code 0x%x\n", code);
       break;
     }
 }
@@ -2430,7 +2450,7 @@ static int kwsysProcess_List__New_NT4(kwsysProcess_List* self)
      loaded in this program.  This does not actually increment the
      reference count to the module so we do not need to close the
      handle.  */
-  HMODULE hNT = GetModuleHandle("ntdll.dll");
+  HMODULE hNT = GetModuleHandleW(L"ntdll.dll");
   if(hNT)
     {
     /* Get pointers to the needed API functions.  */
@@ -2534,7 +2554,7 @@ static int kwsysProcess_List__New_Snapshot(kwsysProcess_List* self)
      loaded in this program.  This does not actually increment the
      reference count to the module so we do not need to close the
      handle.  */
-  HMODULE hKernel = GetModuleHandle("kernel32.dll");
+  HMODULE hKernel = GetModuleHandleW(L"kernel32.dll");
   if(hKernel)
     {
     self->P_CreateToolhelp32Snapshot =
diff --git a/SystemInformation.cxx b/SystemInformation.cxx
index 2672730..e652c27 100644
--- a/SystemInformation.cxx
+++ b/SystemInformation.cxx
@@ -2454,8 +2454,8 @@ bool SystemInformationImplementation::RetrieveCPUClockSpeed()
   if (!retrieved)
     {
     HKEY hKey = NULL;
-    LONG err = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
-      "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
+    LONG err = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
+      L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
       KEY_READ, &hKey);
 
     if (ERROR_SUCCESS == err)
@@ -2464,7 +2464,7 @@ bool SystemInformationImplementation::RetrieveCPUClockSpeed()
       DWORD data = 0;
       DWORD dwSize = sizeof(DWORD);
 
-      err = RegQueryValueEx(hKey, "~MHz", 0,
+      err = RegQueryValueExW(hKey, L"~MHz", 0,
         &dwType, (LPBYTE) &data, &dwSize);
 
       if (ERROR_SUCCESS == err)
@@ -5017,19 +5017,19 @@ bool SystemInformationImplementation::QueryOSInformation()
 
   this->OSName = "Windows";
 
-  OSVERSIONINFOEX osvi;
+  OSVERSIONINFOEXW osvi;
   BOOL bIsWindows64Bit;
   BOOL bOsVersionInfoEx;
   char operatingSystem[256];
 
   // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
-  ZeroMemory (&osvi, sizeof (OSVERSIONINFOEX));
-  osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEX);
-  bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi);
+  ZeroMemory (&osvi, sizeof (OSVERSIONINFOEXW));
+  osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW);
+  bOsVersionInfoEx = GetVersionExW ((OSVERSIONINFOW*)&osvi);
   if (!bOsVersionInfoEx)
     {
-    osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
-    if (!GetVersionEx ((OSVERSIONINFO *) &osvi))
+    osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFOW);
+    if (!GetVersionExW((OSVERSIONINFOW*)&osvi))
       {
       return false;
       }
@@ -5115,19 +5115,19 @@ bool SystemInformationImplementation::QueryOSInformation()
 #endif        // VER_NT_WORKSTATION
         {
         HKEY hKey;
-        char szProductType[80];
+        wchar_t szProductType[80];
         DWORD dwBufLen;
 
         // Query the registry to retrieve information.
-        RegOpenKeyEx (HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_QUERY_VALUE, &hKey);
-        RegQueryValueEx (hKey, "ProductType", NULL, NULL, (LPBYTE) szProductType, &dwBufLen);
+        RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_QUERY_VALUE, &hKey);
+        RegQueryValueExW(hKey, L"ProductType", NULL, NULL, (LPBYTE) szProductType, &dwBufLen);
         RegCloseKey (hKey);
 
-        if (lstrcmpi ("WINNT", szProductType) == 0)
+        if (lstrcmpiW(L"WINNT", szProductType) == 0)
           {
           this->OSRelease += " Professional";
           }
-        if (lstrcmpi ("LANMANNT", szProductType) == 0)
+        if (lstrcmpiW(L"LANMANNT", szProductType) == 0)
           {
           // Decide between Windows 2000 Advanced Server and Windows .NET Enterprise Server.
           if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
@@ -5139,7 +5139,7 @@ bool SystemInformationImplementation::QueryOSInformation()
             this->OSRelease += " Server";
             }
           }
-        if (lstrcmpi ("SERVERNT", szProductType) == 0)
+        if (lstrcmpiW(L"SERVERNT", szProductType) == 0)
           {
           // Decide between Windows 2000 Advanced Server and Windows .NET Enterprise Server.
           if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
@@ -5172,7 +5172,7 @@ bool SystemInformationImplementation::QueryOSInformation()
         LPFNPROC DLLProc;
 
         // Load the Kernel32 DLL.
-        hKernelDLL = LoadLibrary ("kernel32");
+        hKernelDLL = LoadLibraryW(L"kernel32");
         if (hKernelDLL != NULL)  {
           // Only XP and .NET Server support IsWOW64Process so... Load dynamically!
           DLLProc = (LPFNPROC) GetProcAddress (hKernelDLL, "IsWow64Process");
diff --git a/SystemTools.cxx b/SystemTools.cxx
index 749002d..8611130 100644
--- a/SystemTools.cxx
+++ b/SystemTools.cxx
@@ -20,6 +20,8 @@
 #include KWSYS_HEADER(RegularExpression.hxx)
 #include KWSYS_HEADER(SystemTools.hxx)
 #include KWSYS_HEADER(Directory.hxx)
+#include KWSYS_HEADER(FStream.hxx)
+#include KWSYS_HEADER(Encoding.hxx)
 
 #include KWSYS_HEADER(ios/iostream)
 #include KWSYS_HEADER(ios/fstream)
@@ -32,6 +34,8 @@
 #if 0
 # include "SystemTools.hxx.in"
 # include "Directory.hxx.in"
+# include "FStream.hxx.in"
+# include "Encoding.hxx.in"
 # include "kwsys_ios_iostream.h.in"
 # include "kwsys_ios_fstream.h.in"
 # include "kwsys_ios_sstream.h.in"
@@ -75,6 +79,9 @@
 // Windows API.
 #if defined(_WIN32)
 # include <windows.h>
+# ifndef INVALID_FILE_ATTRIBUTES
+#  define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
+# endif
 #elif defined (__CYGWIN__)
 # include <windows.h>
 # undef _WIN32
@@ -183,22 +190,25 @@ static inline char *realpath(const char *path, char *resolved_path)
 #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
 inline int Mkdir(const char* dir)
 {
-  return _mkdir(dir);
+  return _wmkdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str());
 }
 inline int Rmdir(const char* dir)
 {
-  return _rmdir(dir);
+  return _wrmdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str());
 }
 inline const char* Getcwd(char* buf, unsigned int len)
 {
-  if(const char* ret = _getcwd(buf, len))
+  std::vector<wchar_t> w_buf(len);
+  if(const wchar_t* ret = _wgetcwd(&w_buf[0], len))
     {
     // make sure the drive letter is capital
-    if(strlen(buf) > 1 && buf[1] == ':')
+    if(wcslen(&w_buf[0]) > 1 && w_buf[1] == L':')
       {
-      buf[0] = toupper(buf[0]);
+      w_buf[0] = towupper(w_buf[0]);
       }
-    return ret;
+    std::string tmp = KWSYS_NAMESPACE::Encoding::ToNarrow(&w_buf[0]);
+    strcpy(buf, tmp.c_str());
+    return buf;
     }
   return 0;
 }
@@ -207,16 +217,18 @@ inline int Chdir(const char* dir)
   #if defined(__BORLANDC__)
   return chdir(dir);
   #else
-  return _chdir(dir);
+  return _wchdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str());
   #endif
 }
 inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
 {
-  char *ptemp;
-  char fullpath[MAX_PATH];
-  if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
+  kwsys_stl::wstring tmp = KWSYS_NAMESPACE::Encoding::ToWide(path);
+  wchar_t *ptemp;
+  wchar_t fullpath[MAX_PATH];
+  if( GetFullPathNameW(tmp.c_str(), sizeof(fullpath)/sizeof(fullpath[0]),
+                       fullpath, &ptemp) )
     {
-    resolved_path = fullpath;
+    resolved_path = KWSYS_NAMESPACE::Encoding::ToNarrow(fullpath);
     KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
     }
   else
@@ -591,6 +603,15 @@ const char* SystemTools::GetExecutableExtension()
 #endif
 }
 
+FILE* SystemTools::Fopen(const char* file, const char* mode)
+{
+#ifdef _WIN32
+  return _wfopen(Encoding::ToWide(file).c_str(),
+                 Encoding::ToWide(mode).c_str());
+#else
+  return fopen(file, mode);
+#endif
+}
 
 bool SystemTools::MakeDirectory(const char* path)
 {
@@ -740,7 +761,7 @@ static DWORD SystemToolsMakeRegistryMode(DWORD mode,
                                          SystemTools::KeyWOW64 view)
 {
   // only add the modes when on a system that supports Wow64.
-  static FARPROC wow64p = GetProcAddress(GetModuleHandle("kernel32"),
+  static FARPROC wow64p = GetProcAddress(GetModuleHandleW(L"kernel32"),
                                          "IsWow64Process");
   if(wow64p == NULL)
     {
@@ -774,8 +795,8 @@ SystemTools::GetRegistrySubKeys(const char *key,
     }
 
   HKEY hKey;
-  if(RegOpenKeyEx(primaryKey,
-                  second.c_str(),
+  if(RegOpenKeyExW(primaryKey,
+                  Encoding::ToWide(second).c_str(),
                   0,
                   SystemToolsMakeRegistryMode(KEY_READ, view),
                   &hKey) != ERROR_SUCCESS)
@@ -784,13 +805,13 @@ SystemTools::GetRegistrySubKeys(const char *key,
     }
   else
     {
-    char name[1024];
+    wchar_t name[1024];
     DWORD dwNameSize = sizeof(name)/sizeof(name[0]);
 
     DWORD i = 0;
-    while (RegEnumKey(hKey, i, name, dwNameSize) == ERROR_SUCCESS)
+    while (RegEnumKeyW(hKey, i, name, dwNameSize) == ERROR_SUCCESS)
       {
-      subkeys.push_back(name);
+      subkeys.push_back(Encoding::ToNarrow(name));
       ++i;
       }
 
@@ -829,8 +850,8 @@ bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value,
     }
 
   HKEY hKey;
-  if(RegOpenKeyEx(primaryKey,
-                  second.c_str(),
+  if(RegOpenKeyExW(primaryKey,
+                  Encoding::ToWide(second).c_str(),
                   0,
                   SystemToolsMakeRegistryMode(KEY_READ, view),
                   &hKey) != ERROR_SUCCESS)
@@ -841,9 +862,9 @@ bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value,
     {
     DWORD dwType, dwSize;
     dwSize = 1023;
-    char data[1024];
-    if(RegQueryValueEx(hKey,
-                       (LPTSTR)valuename.c_str(),
+    wchar_t data[1024];
+    if(RegQueryValueExW(hKey,
+                       Encoding::ToWide(valuename).c_str(),
                        NULL,
                        &dwType,
                        (BYTE *)data,
@@ -851,16 +872,17 @@ bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value,
       {
       if (dwType == REG_SZ)
         {
-        value = data;
+        value = Encoding::ToNarrow(data);
         valueset = true;
         }
       else if (dwType == REG_EXPAND_SZ)
         {
-        char expanded[1024];
+        wchar_t expanded[1024];
         DWORD dwExpandedSize = sizeof(expanded)/sizeof(expanded[0]);
-        if(ExpandEnvironmentStrings(data, expanded, dwExpandedSize))
+        if(ExpandEnvironmentStringsW(data, expanded,
+            dwExpandedSize))
           {
-          value = expanded;
+          value = Encoding::ToNarrow(expanded);
           valueset = true;
           }
         }
@@ -901,9 +923,9 @@ bool SystemTools::WriteRegistryValue(const char *key, const char *value,
 
   HKEY hKey;
   DWORD dwDummy;
-  char lpClass[] = "";
-  if(RegCreateKeyEx(primaryKey,
-                    second.c_str(),
+  wchar_t lpClass[] = L"";
+  if(RegCreateKeyExW(primaryKey,
+                    Encoding::ToWide(second).c_str(),
                     0,
                     lpClass,
                     REG_OPTION_NON_VOLATILE,
@@ -915,12 +937,13 @@ bool SystemTools::WriteRegistryValue(const char *key, const char *value,
     return false;
     }
 
-  if(RegSetValueEx(hKey,
-                   (LPTSTR)valuename.c_str(),
+  std::wstring wvalue = Encoding::ToWide(value);
+  if(RegSetValueExW(hKey,
+                   Encoding::ToWide(valuename).c_str(),
                    0,
                    REG_SZ,
-                   (CONST BYTE *)value,
-                   (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
+                   (CONST BYTE *)wvalue.c_str(),
+                   (DWORD)(sizeof(wchar_t) * (wvalue.size() + 1))) == ERROR_SUCCESS)
     {
     return true;
     }
@@ -952,8 +975,8 @@ bool SystemTools::DeleteRegistryValue(const char *key, KeyWOW64 view)
     }
 
   HKEY hKey;
-  if(RegOpenKeyEx(primaryKey,
-                  second.c_str(),
+  if(RegOpenKeyExW(primaryKey,
+                  Encoding::ToWide(second).c_str(),
                   0,
                   SystemToolsMakeRegistryMode(KEY_WRITE, view),
                   &hKey) != ERROR_SUCCESS)
@@ -983,7 +1006,7 @@ bool SystemTools::SameFile(const char* file1, const char* file2)
 #ifdef _WIN32
   HANDLE hFile1, hFile2;
 
-  hFile1 = CreateFile( file1,
+  hFile1 = CreateFileW( Encoding::ToWide(file1).c_str(),
                       GENERIC_READ,
                       FILE_SHARE_READ ,
                       NULL,
@@ -991,7 +1014,7 @@ bool SystemTools::SameFile(const char* file1, const char* file2)
                       FILE_FLAG_BACKUP_SEMANTICS,
                       NULL
     );
-  hFile2 = CreateFile( file2,
+  hFile2 = CreateFileW( Encoding::ToWide(file2).c_str(),
                       GENERIC_READ,
                       FILE_SHARE_READ,
                       NULL,
@@ -1041,10 +1064,13 @@ bool SystemTools::SameFile(const char* file1, const char* file2)
 
 //----------------------------------------------------------------------------
 #if defined(_WIN32) || defined(__CYGWIN__)
+static bool WindowsFileExists(const wchar_t* filename)
+{
+  return GetFileAttributesW(filename) != INVALID_FILE_ATTRIBUTES;
+}
 static bool WindowsFileExists(const char* filename)
 {
-  WIN32_FILE_ATTRIBUTE_DATA fd;
-  return GetFileAttributesExA(filename, GetFileExInfoStandard, &fd) != 0;
+  return GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES;
 }
 #endif
 
@@ -1064,7 +1090,7 @@ bool SystemTools::FileExists(const char* filename)
     }
   return access(filename, R_OK) == 0;
 #elif defined(_WIN32)
-  return WindowsFileExists(filename);
+  return WindowsFileExists(Encoding::ToWide(filename).c_str());
 #else
   return access(filename, R_OK) == 0;
 #endif
@@ -1107,7 +1133,7 @@ bool SystemTools::Touch(const char* filename, bool create)
 {
   if(create && !SystemTools::FileExists(filename))
     {
-    FILE* file = fopen(filename, "a+b");
+    FILE* file = Fopen(filename, "a+b");
     if(file)
       {
       fclose(file);
@@ -1116,7 +1142,8 @@ bool SystemTools::Touch(const char* filename, bool create)
     return false;
     }
 #if defined(_WIN32) && !defined(__CYGWIN__)
-  HANDLE h = CreateFile(filename, FILE_WRITE_ATTRIBUTES,
+  HANDLE h = CreateFileW(Encoding::ToWide(filename).c_str(),
+                        FILE_WRITE_ATTRIBUTES,
                         FILE_SHARE_WRITE, 0, OPEN_EXISTING,
                         FILE_FLAG_BACKUP_SEMANTICS, 0);
   if(!h)
@@ -1220,11 +1247,13 @@ bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
   // Windows version.  Get the modification time from extended file attributes.
   WIN32_FILE_ATTRIBUTE_DATA f1d;
   WIN32_FILE_ATTRIBUTE_DATA f2d;
-  if(!GetFileAttributesEx(f1, GetFileExInfoStandard, &f1d))
+  if(!GetFileAttributesExW(Encoding::ToWide(f1).c_str(),
+                           GetFileExInfoStandard, &f1d))
     {
     return false;
     }
-  if(!GetFileAttributesEx(f2, GetFileExInfoStandard, &f2d))
+  if(!GetFileAttributesExW(Encoding::ToWide(f2).c_str(),
+                           GetFileExInfoStandard, &f2d))
     {
     return false;
     }
@@ -1932,6 +1961,39 @@ bool SystemTools::CopyFileIfDifferent(const char* source,
 bool SystemTools::FilesDiffer(const char* source,
                               const char* destination)
 {
+
+#if defined(_WIN32)
+  WIN32_FILE_ATTRIBUTE_DATA statSource;
+  if (GetFileAttributesExW(Encoding::ToWide(source).c_str(),
+                           GetFileExInfoStandard,
+                           &statSource) == 0)
+    {
+    return true;
+    }
+
+  WIN32_FILE_ATTRIBUTE_DATA statDestination;
+  if (GetFileAttributesExW(Encoding::ToWide(destination).c_str(),
+                           GetFileExInfoStandard,
+                           &statDestination) == 0)
+    {
+    return true;
+    }
+
+  if(statSource.nFileSizeHigh != statDestination.nFileSizeHigh ||
+     statSource.nFileSizeLow != statDestination.nFileSizeLow)
+    {
+    return true;
+    }
+
+  if(statSource.nFileSizeHigh == 0 && statSource.nFileSizeLow == 0)
+    {
+    return false;
+    }
+  off_t nleft = ((__int64)statSource.nFileSizeHigh << 32) +
+                statSource.nFileSizeLow;
+
+#else
+
   struct stat statSource;
   if (stat(source, &statSource) != 0)
     {
@@ -1953,15 +2015,19 @@ bool SystemTools::FilesDiffer(const char* source,
     {
     return false;
     }
+  off_t nleft = statSource.st_size;
+#endif
 
-#if defined(_WIN32) || defined(__CYGWIN__)
-  kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
-                                         kwsys_ios::ios::in));
-  kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
-                                                   kwsys_ios::ios::in));
+#if defined(_WIN32)
+  kwsys::ifstream finSource(source,
+                            (kwsys_ios::ios::binary |
+                             kwsys_ios::ios::in));
+  kwsys::ifstream finDestination(destination,
+                                 (kwsys_ios::ios::binary |
+                                  kwsys_ios::ios::in));
 #else
-  kwsys_ios::ifstream finSource(source);
-  kwsys_ios::ifstream finDestination(destination);
+  kwsys::ifstream finSource(source);
+  kwsys::ifstream finDestination(destination);
 #endif
   if(!finSource || !finDestination)
     {
@@ -1971,7 +2037,6 @@ bool SystemTools::FilesDiffer(const char* source,
   // Compare the files a block at a time.
   char source_buf[KWSYS_ST_BUFFER];
   char dest_buf[KWSYS_ST_BUFFER];
-  off_t nleft = statSource.st_size;
   while(nleft > 0)
     {
     // Read a block from each file.
@@ -2044,10 +2109,10 @@ bool SystemTools::CopyFileAlways(const char* source, const char* destination)
   // Open files
 
 #if defined(_WIN32) || defined(__CYGWIN__)
-  kwsys_ios::ifstream fin(source,
-                    kwsys_ios::ios::binary | kwsys_ios::ios::in);
+  kwsys::ifstream fin(source,
+                kwsys_ios::ios::binary | kwsys_ios::ios::in);
 #else
-  kwsys_ios::ifstream fin(source);
+  kwsys::ifstream fin(source);
 #endif
   if(!fin)
     {
@@ -2344,7 +2409,11 @@ bool SystemTools::RemoveFile(const char* source)
   /* Win32 unlink is stupid --- it fails if the file is read-only  */
   SystemTools::SetPermissions(source, S_IWRITE);
 #endif
+#ifdef _WIN32
+  bool res = _wunlink(Encoding::ToWide(source).c_str()) != 0 ? false : true;
+#else
   bool res = unlink(source) != 0 ? false : true;
+#endif
 #ifdef _WIN32
   if ( !res )
     {
@@ -2789,12 +2858,15 @@ bool SystemTools::FileIsDirectory(const char* name)
     }
 
   // Now check the file node type.
+#if defined( _WIN32 )
+  DWORD attr = GetFileAttributesW(Encoding::ToWide(name).c_str());
+  if (attr != INVALID_FILE_ATTRIBUTES)
+    {
+    return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
+#else
   struct stat fs;
   if(stat(name, &fs) == 0)
     {
-#if defined( _WIN32 ) && !defined(__CYGWIN__)
-    return ((fs.st_mode & _S_IFDIR) != 0);
-#else
     return S_ISDIR(fs.st_mode);
 #endif
     }
@@ -3279,11 +3351,12 @@ static int GetCasePathName(const kwsys_stl::string & pathIn,
     kwsys_stl::string test_str = casePath;
     test_str += path_components[idx];
 
-    WIN32_FIND_DATA findData;
-    HANDLE hFind = ::FindFirstFile(test_str.c_str(), &findData);
+    WIN32_FIND_DATAW findData;
+    HANDLE hFind = ::FindFirstFileW(Encoding::ToWide(test_str).c_str(),
+      &findData);
     if (INVALID_HANDLE_VALUE != hFind)
       {
-      casePath += findData.cFileName;
+      casePath += Encoding::ToNarrow(findData.cFileName);
       ::FindClose(hFind);
       }
     else
@@ -3733,8 +3806,7 @@ bool SystemTools::FileHasSignature(const char *filename,
     return false;
     }
 
-  FILE *fp;
-  fp = fopen(filename, "rb");
+  FILE *fp = Fopen(filename, "rb");
   if (!fp)
     {
     return false;
@@ -3767,8 +3839,7 @@ SystemTools::DetectFileType(const char *filename,
     return SystemTools::FileTypeUnknown;
     }
 
-  FILE *fp;
-  fp = fopen(filename, "rb");
+  FILE *fp = Fopen(filename, "rb");
   if (!fp)
     {
     return SystemTools::FileTypeUnknown;
@@ -3958,9 +4029,8 @@ bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
 {
 #if defined(WIN32) && !defined(__CYGWIN__)
   const int size = int(strlen(path)) +1; // size of return
-  char *buffer = new char[size];  // create a buffer
   char *tempPath = new char[size];  // create a buffer
-  int ret;
+  DWORD ret;
 
   // if the path passed in has quotes around it, first remove the quotes
   if (path[0] == '"' && path[strlen(path)-1] == '"')
@@ -3973,19 +4043,20 @@ bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
     strcpy(tempPath,path);
     }
 
+  kwsys_stl::wstring wtempPath = Encoding::ToWide(tempPath);
+  kwsys_stl::vector<wchar_t> buffer(wtempPath.size()+1);
   buffer[0] = 0;
-  ret = GetShortPathName(tempPath, buffer, size);
+  ret = GetShortPathNameW(Encoding::ToWide(tempPath).c_str(),
+    &buffer[0], static_cast<DWORD>(wtempPath.size()));
 
-  if(buffer[0] == 0 || ret > size)
+  if(buffer[0] == 0 || ret > wtempPath.size())
     {
-    delete [] buffer;
     delete [] tempPath;
     return false;
     }
   else
     {
-    shortPath = buffer;
-    delete [] buffer;
+    shortPath = Encoding::ToNarrow(&buffer[0]);
     delete [] tempPath;
     return true;
     }
@@ -4212,12 +4283,45 @@ bool SystemTools::GetPermissions(const char* file, mode_t& mode)
     return false;
     }
 
+#if defined(_WIN32)
+  DWORD attr = GetFileAttributesW(Encoding::ToWide(file).c_str());
+  if(attr == INVALID_FILE_ATTRIBUTES)
+    {
+    return false;
+    }
+  if((attr & FILE_ATTRIBUTE_READONLY) != 0)
+    {
+    mode = (_S_IREAD  | (_S_IREAD  >> 3) | (_S_IREAD  >> 6));
+    }
+  else
+    {
+    mode = (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6)) |
+           (_S_IREAD  | (_S_IREAD  >> 3) | (_S_IREAD  >> 6));
+    }
+  if((attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
+    {
+    mode |= S_IFDIR | (_S_IEXEC  | (_S_IEXEC  >> 3) | (_S_IEXEC  >> 6));
+    }
+  else
+    {
+    mode |= S_IFREG;
+    }
+  const char* ext = strrchr(file, '.');
+  if(ext && (Strucmp(ext, ".exe") == 0 ||
+    Strucmp(ext, ".com") == 0 ||
+    Strucmp(ext, ".cmd") == 0 ||
+    Strucmp(ext, ".bat") == 0))
+    {
+    mode |= (_S_IEXEC  | (_S_IEXEC  >> 3) | (_S_IEXEC  >> 6));
+    }
+#else
   struct stat st;
   if ( stat(file, &st) < 0 )
     {
     return false;
     }
   mode = st.st_mode;
+#endif
   return true;
 }
 
@@ -4231,7 +4335,11 @@ bool SystemTools::SetPermissions(const char* file, mode_t mode)
     {
     return false;
     }
+#ifdef _WIN32
+  if ( _wchmod(Encoding::ToWide(file).c_str(), mode) < 0 )
+#else
   if ( chmod(file, mode) < 0 )
+#endif
     {
     return false;
     }
@@ -4336,7 +4444,9 @@ void SystemTools::ConvertWindowsCommandLineToUnixArguments(
 
   (*argv)[0] = new char [1024];
 #ifdef _WIN32
-  ::GetModuleFileName(0, (*argv)[0], 1024);
+  wchar_t tmp[1024];
+  ::GetModuleFileNameW(0, tmp, 1024);
+  strcpy((*argv)[0], Encoding::ToNarrow(tmp).c_str());
 #else
   (*argv)[0][0] = '\0';
 #endif
@@ -4396,14 +4506,14 @@ kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
 #ifdef _WIN32
   char buffer[256];
 
-  OSVERSIONINFOEX osvi;
+  OSVERSIONINFOEXA osvi;
   BOOL bOsVersionInfoEx;
 
   // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
   // If that fails, try using the OSVERSIONINFO structure.
 
-  ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
-  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
+  ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXA));
+  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXA);
 
   bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi);
   if (!bOsVersionInfoEx)
@@ -4546,21 +4656,21 @@ kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
         {
         HKEY hKey;
         #define BUFSIZE 80
-        char szProductType[BUFSIZE];
+        wchar_t szProductType[BUFSIZE];
         DWORD dwBufLen=BUFSIZE;
         LONG lRet;
 
-        lRet = RegOpenKeyEx(
+        lRet = RegOpenKeyExW(
           HKEY_LOCAL_MACHINE,
-          "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
+          L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
           0, KEY_QUERY_VALUE, &hKey);
         if (lRet != ERROR_SUCCESS)
           {
           return 0;
           }
 
-        lRet = RegQueryValueEx(hKey, "ProductType", NULL, NULL,
-                               (LPBYTE) szProductType, &dwBufLen);
+        lRet = RegQueryValueExW(hKey, L"ProductType", NULL, NULL,
+                                (LPBYTE) szProductType, &dwBufLen);
 
         if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))
           {
@@ -4569,15 +4679,15 @@ kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
 
         RegCloseKey(hKey);
 
-        if (lstrcmpi("WINNT", szProductType) == 0)
+        if (lstrcmpiW(L"WINNT", szProductType) == 0)
           {
           res += " Workstation";
           }
-        if (lstrcmpi("LANMANNT", szProductType) == 0)
+        if (lstrcmpiW(L"LANMANNT", szProductType) == 0)
           {
           res += " Server";
           }
-        if (lstrcmpi("SERVERNT", szProductType) == 0)
+        if (lstrcmpiW(L"SERVERNT", szProductType) == 0)
           {
           res += " Advanced Server";
           }
@@ -4593,16 +4703,16 @@ kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
       // Display service pack (if any) and build number.
 
       if (osvi.dwMajorVersion == 4 &&
-          lstrcmpi(osvi.szCSDVersion, "Service Pack 6") == 0)
+          lstrcmpiA(osvi.szCSDVersion, "Service Pack 6") == 0)
         {
         HKEY hKey;
         LONG lRet;
 
         // Test for SP6 versus SP6a.
 
-        lRet = RegOpenKeyEx(
+        lRet = RegOpenKeyExW(
           HKEY_LOCAL_MACHINE,
-          "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
+          L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
           0, KEY_QUERY_VALUE, &hKey);
 
         if (lRet == ERROR_SUCCESS)
diff --git a/SystemTools.hxx.in b/SystemTools.hxx.in
index 85bdecc..9457a4e 100644
--- a/SystemTools.hxx.in
+++ b/SystemTools.hxx.in
@@ -24,6 +24,8 @@
 
 // Required for va_list
 #include <stdarg.h>
+// Required for FILE*
+#include <stdio.h>
 #if @KWSYS_NAMESPACE@_STL_HAVE_STD && !defined(va_list)
 // Some compilers move va_list into the std namespace and there is no way to
 // tell that this has been done. Playing with things being included before or
@@ -492,6 +494,11 @@ public:
    *  -----------------------------------------------------------------
    */
 
+  /**
+   * Open a file considering unicode.
+   */
+  static FILE* Fopen(const char* file, const char* mode);
+
   /**
    * Make a new directory if it is not there.  This function
    * can make a full path even if none of the directories existed
-- 
GitLab