Commits

Anonymous committed aa051a0

ENH: merges from the main tree

  • Participants
  • Parent commits 83b5a8d
  • Branches ParaView-1-8
  • Tags ParaView-1-8-0, ParaView-1-8-1 4
    1. ParaView-1-8-2
    2. ParaView-1-8-3
    3. ParaView-1-8-4
    4. ParaView-1-8-5

Comments (0)

Files changed (1)

GCC_XML/KWSys/SystemTools.cxx

 
   Program:   KWSys - Kitware System Library
   Module:    $RCSfile$
-  Language:  C++
-  Date:      $Date$
-  Version:   $Revision$
 
-  Copyright (c) 2002 Kitware, Inc., Insight Consortium.  All rights reserved.
-  See http://www.cmake.org/HTML/Copyright.html for details.
+  Copyright (c) Kitware, Inc., Insight Consortium.  All rights reserved.
+  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
 
-     This software is distributed WITHOUT ANY WARRANTY; without even 
-     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
+     This software is distributed WITHOUT ANY WARRANTY; without even
+     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
      PURPOSE.  See the above copyright notices for more information.
 
 =========================================================================*/
+#include "kwsysPrivate.h"
+#include KWSYS_HEADER(SystemTools.hxx)
+#include KWSYS_HEADER(Directory.hxx)
+
+#include KWSYS_HEADER(ios/iostream)
+#include KWSYS_HEADER(ios/fstream)
+#include KWSYS_HEADER(ios/sstream)
+
 #ifdef _MSC_VER
 # pragma warning (disable: 4786)
 #endif
 
-#include <SystemTools.hxx>
-#include <RegularExpression.hxx>
-#include <Directory.hxx>
-
-#include <fstream>
-
 #include <stdio.h>
 #include <sys/stat.h>
 #include <ctype.h>
 #include <stdlib.h>
 #include <sys/param.h>
 #include <sys/wait.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+#include <termios.h>
 #endif
 
-#if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__))
+#if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__))
+#include <io.h>
+#include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
 #include <windows.h>
 #include <direct.h>
 {
   return _mkdir(dir);
 }
+inline int Rmdir(const char* dir)
+{
+  return _rmdir(dir);
+}
 inline const char* Getcwd(char* buf, unsigned int len)
 {
   return _getcwd(buf, len);
   return _chdir(dir);
   #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) )
+    {
+    resolved_path = fullpath;
+    KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
+    }
+}
 #else
 #include <sys/types.h>
 #include <fcntl.h>
 {
   return mkdir(dir, 00777);
 }
+inline int Rmdir(const char* dir)
+{
+  return rmdir(dir);
+}
 inline const char* Getcwd(char* buf, unsigned int len)
 {
   return getcwd(buf, len);
 {
   return chdir(dir);
 }
+inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
+{
+# ifdef MAXPATHLEN
+  char resolved_name[MAXPATHLEN];
+# else
+#  ifdef PATH_MAX
+  char resolved_name[PATH_MAX];
+#  else
+  char resolved_name[5024];
+#  endif  //PATH_MAX
+# endif //MAXPATHLEN
+
+  realpath(path, resolved_name);
+  resolved_path = resolved_name;
+}
 #endif
 
+#if !defined(_WIN32) && defined(__COMO__)
+// Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
+extern "C"
+{
+extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
+extern int pclose (FILE *__stream) __THROW;
+extern char *realpath (__const char *__restrict __name,
+                       char *__restrict __resolved) __THROW;
+extern char *strdup (__const char *__s) __THROW;
+extern int putenv (char *__string) __THROW;
+}
+#endif
 
 /* Implement floattime() for various platforms */
 // Taken from Python 2.1.3
 namespace KWSYS_NAMESPACE
 {
 
+class SystemToolsTranslationMap : 
+    public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
+{
+};
+
 double
 SystemTools::GetTime(void)
 {
   {
 #if defined(HAVE_FTIME)
   struct TIMEB t;
-  FTIME(&t);
+  ::FTIME(&t);
   return (double)t.time + (double)t.millitm * (double)0.001;
 #else /* !HAVE_FTIME */
   time_t secs;
 }
 
 // adds the elements of the env variable path to the arg passed in
-void SystemTools::GetPath(kwsys_std::vector<kwsys_std::string>& path)
+void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
 {
 #if defined(_WIN32) && !defined(__CYGWIN__)
   const char* pathSep = ";";
 #else
   const char* pathSep = ":";
 #endif
-  kwsys_std::string pathEnv = getenv("PATH");
+  if(!env)
+    {
+    env = "PATH";
+    }
+  const char* cpathEnv = SystemTools::GetEnv(env);
+  if ( !cpathEnv )
+    {
+    return;
+    }
+
+  kwsys_stl::string pathEnv = cpathEnv;
+   
   // A hack to make the below algorithm work.  
   if(pathEnv[pathEnv.length()-1] != ':')
     {
     pathEnv += pathSep;
     }
-  kwsys_std::string::size_type start =0;
+  kwsys_stl::string::size_type start =0;
   bool done = false;
   while(!done)
     {
-    kwsys_std::string::size_type endpos = pathEnv.find(pathSep, start);
-    if(endpos != kwsys_std::string::npos)
+    kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
+    if(endpos != kwsys_stl::string::npos)
       {
       path.push_back(pathEnv.substr(start, endpos-start));
       start = endpos+1;
       done = true;
       }
     }
-  for(kwsys_std::vector<kwsys_std::string>::iterator i = path.begin();
+  for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
       i != path.end(); ++i)
     {
     SystemTools::ConvertToUnixSlashes(*i);
     }
 }
 
+const char* SystemTools::GetEnv(const char* key)
+{
+  return getenv(key);
+}
+
+bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
+{
+  const char* v = getenv(key);
+  if(v)
+    {
+    result = v;
+    return true;
+    }
+  else
+    {
+    return false;
+    }
+}
 
 const char* SystemTools::GetExecutableExtension()
 {
     {
     return true;
     }
-  kwsys_std::string dir = path;
+  kwsys_stl::string dir = path;
   if(dir.size() == 0)
     {
     return false;
     }
   SystemTools::ConvertToUnixSlashes(dir);
 
-  kwsys_std::string::size_type pos = dir.find(':');
-  if(pos == kwsys_std::string::npos)
+  kwsys_stl::string::size_type pos = dir.find(':');
+  if(pos == kwsys_stl::string::npos)
     {
     pos = 0;
     }
-  kwsys_std::string topdir;
-  while((pos = dir.find('/', pos)) != kwsys_std::string::npos)
+  kwsys_stl::string topdir;
+  while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
     {
     topdir = dir.substr(0, pos);
     Mkdir(topdir.c_str());
 
 // replace replace with with as many times as it shows up in source.
 // write the result into source.
-void SystemTools::ReplaceString(kwsys_std::string& source,
+void SystemTools::ReplaceString(kwsys_stl::string& source,
                                    const char* replace,
                                    const char* with)
 {
+  const char *src = source.c_str();
+  char *searchPos = const_cast<char *>(strstr(src,replace));
+  
   // get out quick if string is not found
-  kwsys_std::string::size_type start = source.find(replace);
-  if(start ==  kwsys_std::string::npos)
+  if (!searchPos)
     {
     return;
     }
-  kwsys_std::string rest;
-  kwsys_std::string::size_type lengthReplace = strlen(replace);
-  kwsys_std::string::size_type lengthWith = strlen(with);
-  while(start != kwsys_std::string::npos)
+
+  // perform replacements until done
+  size_t replaceSize = strlen(replace);
+  char *orig = strdup(src);
+  char *currentPos = orig;
+  searchPos = searchPos - src + orig;
+  
+  // initialize the result
+  source.erase(source.begin(),source.end());
+  do
     {
-    rest = source.substr(start+lengthReplace);
-    source = source.substr(0, start);
+    *searchPos = '\0';
+    source += currentPos;
+    currentPos = searchPos + replaceSize;
+    // replace
     source += with;
-    source += rest;
-    start = source.find(replace, start + lengthWith );
+    searchPos = strstr(currentPos,replace);
     }
+  while (searchPos);
+
+  // copy any trailing text
+  source += currentPos;
+  free(orig);
 }
 
 // Read a registry value.
 //      =>  will return the data of the "Root" value of the key
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
-bool SystemTools::ReadRegistryValue(const char *key, kwsys_std::string &value)
+bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value)
 {
 
-  kwsys_std::string primary = key;
-  kwsys_std::string second;
-  kwsys_std::string valuename;
+  kwsys_stl::string primary = key;
+  kwsys_stl::string second;
+  kwsys_stl::string valuename;
  
   size_t start = primary.find("\\");
-  if (start == kwsys_std::string::npos)
+  if (start == kwsys_stl::string::npos)
     {
     return false;
     }
 
   size_t valuenamepos = primary.find(";");
-  if (valuenamepos != kwsys_std::string::npos)
+  if (valuenamepos != kwsys_stl::string::npos)
     {
     valuename = primary.substr(valuenamepos+1);
     }
   second = primary.substr(start+1, valuenamepos-start-1);
   primary = primary.substr(0, start);
   
-  HKEY primaryKey;
+  HKEY primaryKey = HKEY_CURRENT_USER;
   if (primary == "HKEY_CURRENT_USER")
     {
     primaryKey = HKEY_CURRENT_USER;
       if (dwType == REG_SZ)
         {
         value = data;
+        RegCloseKey(hKey);
         return true;
         }
       }
   return false;
 }
 #else
-bool SystemTools::ReadRegistryValue(const char *, kwsys_std::string &)
+bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &)
 {
   return false;
 }
 #if defined(_WIN32) && !defined(__CYGWIN__)
 bool SystemTools::WriteRegistryValue(const char *key, const char *value)
 {
-  kwsys_std::string primary = key;
-  kwsys_std::string second;
-  kwsys_std::string valuename;
+  kwsys_stl::string primary = key;
+  kwsys_stl::string second;
+  kwsys_stl::string valuename;
  
   size_t start = primary.find("\\");
-  if (start == kwsys_std::string::npos)
+  if (start == kwsys_stl::string::npos)
     {
     return false;
     }
 
   size_t valuenamepos = primary.find(";");
-  if (valuenamepos != kwsys_std::string::npos)
+  if (valuenamepos != kwsys_stl::string::npos)
     {
     valuename = primary.substr(valuenamepos+1);
     }
   second = primary.substr(start+1, valuenamepos-start-1);
   primary = primary.substr(0, start);
   
-  HKEY primaryKey;
+  HKEY primaryKey = HKEY_CURRENT_USER;
   if (primary == "HKEY_CURRENT_USER")
     {
     primaryKey = HKEY_CURRENT_USER;
 #if defined(_WIN32) && !defined(__CYGWIN__)
 bool SystemTools::DeleteRegistryValue(const char *key)
 {
-  kwsys_std::string primary = key;
-  kwsys_std::string second;
-  kwsys_std::string valuename;
+  kwsys_stl::string primary = key;
+  kwsys_stl::string second;
+  kwsys_stl::string valuename;
  
   size_t start = primary.find("\\");
-  if (start == kwsys_std::string::npos)
+  if (start == kwsys_stl::string::npos)
     {
     return false;
     }
 
   size_t valuenamepos = primary.find(";");
-  if (valuenamepos != kwsys_std::string::npos)
+  if (valuenamepos != kwsys_stl::string::npos)
     {
     valuename = primary.substr(valuenamepos+1);
     }
   second = primary.substr(start+1, valuenamepos-start-1);
   primary = primary.substr(0, start);
   
-  HKEY primaryKey;
+  HKEY primaryKey = HKEY_CURRENT_USER;
   if (primary == "HKEY_CURRENT_USER")
     {
     primaryKey = HKEY_CURRENT_USER;
     if(RegDeleteValue(hKey, 
                       (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
       {
+      RegCloseKey(hKey);
       return true;
       }
     }
 }
 #endif
 
-// replace replace with with as many times as it shows up in source.
-// write the result into source.
-#if defined(_WIN32) && !defined(__CYGWIN__)
-void SystemTools::ExpandRegistryValues(kwsys_std::string& source)
-{
-  // Regular expression to match anything inside [...] that begins in HKEY.
-  // Note that there is a special rule for regular expressions to match a
-  // close square-bracket inside a list delimited by square brackets.
-  // The "[^]]" part of this expression will match any character except
-  // a close square-bracket.  The ']' character must be the first in the
-  // list of characters inside the [^...] block of the expression.
-  RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
-  
-  // check for black line or comment
-  while (regEntry.find(source))
-    {
-    // the arguments are the second match
-    kwsys_std::string key = regEntry.match(1);
-    kwsys_std::string val;
-    if (ReadRegistryValue(key.c_str(), val))
-      {
-      kwsys_std::string reg = "[";
-      reg += key + "]";
-      SystemTools::ReplaceString(source, reg.c_str(), val.c_str());
-      }
-    else
-      {
-      kwsys_std::string reg = "[";
-      reg += key + "]";
-      SystemTools::ReplaceString(source, reg.c_str(), "/registry");
-      }
-    }
-}
-#else
-void SystemTools::ExpandRegistryValues(kwsys_std::string&)
-{
-}
-#endif  
-
-
-kwsys_std::string SystemTools::EscapeQuotes(const char* str)
-{
-  kwsys_std::string result = "";
-  for(const char* ch = str; *ch != '\0'; ++ch)
-    {
-    if(*ch == '"')
-      {
-      result += '\\';
-      }
-    result += *ch;
-    }
-  return result;
-}
-
 bool SystemTools::SameFile(const char* file1, const char* file2)
 {
 #ifdef _WIN32
    GetFileInformationByHandle( hFile2, &fiBuf2 );
    CloseHandle(hFile1);
    CloseHandle(hFile2);
-   return (fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
+   return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
+           fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
            fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
 #else
   struct stat fileStat1, fileStat2;
 // return true if the file exists
 bool SystemTools::FileExists(const char* filename)
 {
-  struct stat fs;
-  if (stat(filename, &fs) != 0) 
+#ifdef _MSC_VER
+# define access _access
+#endif
+#ifndef R_OK
+# define R_OK 04
+#endif
+  if ( access(filename, R_OK) != 0 )
     {
     return false;
     }
 
 // Return a capitalized string (i.e the first letter is uppercased, all other
 // are lowercased)
-kwsys_std::string SystemTools::Capitalized(const kwsys_std::string& s)
+kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
 {
-  kwsys_std::string n;
+  kwsys_stl::string n;
+  if(s.size() == 0)
+    {
+    return n;
+    }
   n.resize(s.size());
-  n[0] = toupper(s[0]);
+  n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
   for (size_t i = 1; i < s.size(); i++)
     {
-    n[i] = tolower(s[i]);
+    n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
     }
   return n;
 }
 
 
 // Return a lower case string 
-kwsys_std::string SystemTools::LowerCase(const kwsys_std::string& s)
+kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
 {
-  kwsys_std::string n;
+  kwsys_stl::string n;
   n.resize(s.size());
   for (size_t i = 0; i < s.size(); i++)
     {
-    n[i] = tolower(s[i]);
+    n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
     }
   return n;
 }
 
 // Return a lower case string 
-kwsys_std::string SystemTools::UpperCase(const kwsys_std::string& s)
+kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
 {
-  kwsys_std::string n;
+  kwsys_stl::string n;
   n.resize(s.size());
   for (size_t i = 0; i < s.size(); i++)
     {
-    n[i] = toupper(s[i]);
+    n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
     }
   return n;
 }
 
 
 // convert windows slashes to unix slashes 
-void SystemTools::ConvertToUnixSlashes(kwsys_std::string& path)
+void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
 {
-  kwsys_std::string::size_type pos = 0;
-  while((pos = path.find('\\', pos)) != kwsys_std::string::npos)
+  kwsys_stl::string::size_type pos = 0;
+  while((pos = path.find('\\', pos)) != kwsys_stl::string::npos)
     {
-    path[pos] = '/';
+    // make sure we don't convert an escaped space to a unix slash
+    if(pos < path.size()-1)
+      {
+      if(path[pos+1] != ' ')
+        {
+        path[pos] = '/';
+        }
+      }
     pos++;
     }
   // Remove all // from the path just like most unix shells
-  int start_find = 0;
+  int start_find;
 
 #ifdef _WIN32
   // However, on windows if the first characters are both slashes,
   // then keep them that way, so that network paths can be handled.
   start_find = 1;
+#else
+  start_find = 0;
 #endif
 
-  while((pos = path.find("//", start_find)) != kwsys_std::string::npos)
+  while((pos = path.find("//", start_find)) != kwsys_stl::string::npos)
     {
     SystemTools::ReplaceString(path, "//", "/");
     }
   
   // remove any trailing slash
-  if(path.size() && path[path.size()-1] == '/')
+  if(path.size() > 1 && path[path.size()-1] == '/')
     {
     path = path.substr(0, path.size()-1);
     }
     {
     if (getenv("HOME"))
       {
-      path = kwsys_std::string(getenv("HOME")) + path.substr(1);
+      path = kwsys_stl::string(getenv("HOME")) + path.substr(1);
       }
     }
-  
-  // if there is a /tmp_mnt in a path get rid of it!
-  // stupid sgi's 
-  if(path.find("/tmp_mnt") == 0)
-    {
-    path = path.substr(8);
-    }
 }
 
-
 // change // to /, and escape any spaces in the path
-kwsys_std::string SystemTools::ConvertToUnixOutputPath(const char* path)
+kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
 {
-  kwsys_std::string ret = path;
+  kwsys_stl::string ret = path;
   
   // remove // except at the beginning might be a cygwin drive
-  kwsys_std::string::size_type pos = 1;
-  while((pos = ret.find("//", pos)) != kwsys_std::string::npos)
+  kwsys_stl::string::size_type pos = 1;
+  while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
     {
     ret.erase(pos, 1);
     }
   // now escape spaces if there is a space in the path
-  if(ret.find(" ") != kwsys_std::string::npos)
+  if(ret.find(" ") != kwsys_stl::string::npos)
     {
-    kwsys_std::string result = "";
+    kwsys_stl::string result = "";
     char lastch = 1;
     for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
       {
   return ret;
 }
 
-
-
-kwsys_std::string SystemTools::EscapeSpaces(const char* str)
-{
-#if defined(_WIN32) && !defined(__CYGWIN__)
-  kwsys_std::string result;
-  
-  // if there are spaces
-  kwsys_std::string temp = str;
-  if (temp.find(" ") != kwsys_std::string::npos && 
-      temp.find("\"")==kwsys_std::string::npos)
-    {
-    result = "\"";
-    result += str;
-    result += "\"";
-    return result;
-    }
-  return str;
-#else
-  kwsys_std::string result = "";
-  for(const char* ch = str; *ch != '\0'; ++ch)
-    {
-    if(*ch == ' ')
-      {
-      result += '\\';
-      }
-    result += *ch;
-    }
-  return result;
-#endif
-}
-
-kwsys_std::string SystemTools::ConvertToOutputPath(const char* path)
+kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
 {
 #if defined(_WIN32) && !defined(__CYGWIN__)
   return SystemTools::ConvertToWindowsOutputPath(path);
 #endif
 }
 
-
 // remove double slashes not at the start
-kwsys_std::string SystemTools::ConvertToWindowsOutputPath(const char* path)
+kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
 {  
-  kwsys_std::string ret = path;
-  kwsys_std::string::size_type pos = 0;
+  kwsys_stl::string ret = path;
+  kwsys_stl::string::size_type pos = 0;
   // first convert all of the slashes
-  while((pos = ret.find('/', pos)) != kwsys_std::string::npos)
+  while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
     {
     ret[pos] = '\\';
     pos++;
       return ret;
       }
     }
-  while((pos = ret.find("\\\\", pos)) != kwsys_std::string::npos)
+  while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
     {
     ret.erase(pos, 1);
     }
   // now double quote the path if it has spaces in it
   // and is not already double quoted
-  if(ret.find(" ") != kwsys_std::string::npos
+  if(ret.find(" ") != kwsys_stl::string::npos
      && ret[0] != '\"')
     {
-    kwsys_std::string result;
+    kwsys_stl::string result;
     result = "\"" + ret + "\"";
     ret = result;
     }
 }
 
 bool SystemTools::CopyFileIfDifferent(const char* source,
-                                        const char* destination)
+                                      const char* destination)
 {
   if(SystemTools::FilesDiffer(source, destination))
     {
-    SystemTools::CopyFileAlways(source, destination);
-    return true;
+    return SystemTools::CopyFileAlways(source, destination);
     }
-  return false;
+  return true;
 }
 
   
     }
 
 #if defined(_WIN32) || defined(__CYGWIN__)
-  kwsys_std::ifstream finSource(source, 
-                          kwsys_std::ios::binary | kwsys_std::ios::in);
-  kwsys_std::ifstream finDestination(destination, 
-                               kwsys_std::ios::binary | kwsys_std::ios::in);
+  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));
 #else
-  kwsys_std::ifstream finSource(source);
-  kwsys_std::ifstream finDestination(destination);
+  kwsys_ios::ifstream finSource(source);
+  kwsys_ios::ifstream finDestination(destination);
 #endif
   if(!finSource || !finDestination)
     {
  */
 bool SystemTools::CopyFileAlways(const char* source, const char* destination)
 {
+  // If files are the same do not copy
+  if ( SystemTools::SameFile(source, destination) )
+    {
+    return true;
+    }
+
+  mode_t perm = 0;
+  bool perms = SystemTools::GetPermissions(source, perm);
+
   const int bufferSize = 4096;
   char buffer[bufferSize];
 
   // If destination is a directory, try to create a file with the same
   // name as the source in that directory.
 
-  kwsys_std::string new_destination;
+  kwsys_stl::string new_destination;
   if(SystemTools::FileExists(destination) &&
      SystemTools::FileIsDirectory(destination))
     {
     new_destination = destination;
     SystemTools::ConvertToUnixSlashes(new_destination);
     new_destination += '/';
-    kwsys_std::string source_name = source;
+    kwsys_stl::string source_name = source;
     new_destination += SystemTools::GetFilenameName(source_name);
     destination = new_destination.c_str();
     }
 
   // Create destination directory
 
-  kwsys_std::string destination_dir = destination;
+  kwsys_stl::string destination_dir = destination;
   destination_dir = SystemTools::GetFilenamePath(destination_dir);
   SystemTools::MakeDirectory(destination_dir.c_str());
 
   // Open files
 
 #if defined(_WIN32) || defined(__CYGWIN__)
-  kwsys_std::ifstream fin(source, 
-                    kwsys_std::ios::binary | kwsys_std::ios::in);
+  kwsys_ios::ifstream fin(source, 
+                    kwsys_ios::ios::binary | kwsys_ios::ios::in);
 #else
-  kwsys_std::ifstream fin(source);
+  kwsys_ios::ifstream fin(source);
 #endif
   if(!fin)
     {
     return false;
     }
 
+  // try and remove the destination file so that read only destination files
+  // can be written to.
+  // If the remove fails continue so that files in read only directories
+  // that do not allow file removal can be modified.
+  SystemTools::RemoveFile(destination);
+
 #if defined(_WIN32) || defined(__CYGWIN__)
-  kwsys_std::ofstream fout(destination, 
-                     kwsys_std::ios::binary | kwsys_std::ios::out | kwsys_std::ios::trunc);
+  kwsys_ios::ofstream fout(destination, 
+                     kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
 #else
-  kwsys_std::ofstream fout(destination, 
-                     kwsys_std::ios::out | kwsys_std::ios::trunc);
+  kwsys_ios::ofstream fout(destination, 
+                     kwsys_ios::ios::out | kwsys_ios::ios::trunc);
 #endif
   if(!fout)
     {
     {
     return false;
     }
+  if ( perms )
+    {
+    if ( !SystemTools::SetPermissions(destination, perm) )
+      {
+      return false;
+      }
+    }
   return true;
 }
 
 
 int SystemTools::Strucmp(const char *s1, const char *s2)
 {
-//  return strcasecmp(s1,s2);
-//
 // lifted from Graphvis http://www.graphviz.org 
   while ((*s1 != '\0') 
-         && (tolower(*(unsigned char *)s1) == tolower(*(unsigned char *)s2)))
+         && (tolower(*s1) == tolower(*s2)))
     {
       s1++;
       s2++;
     }
  
-  return tolower(*(unsigned char *) s1) - tolower(*(unsigned char *) s2);
+  return tolower(*s1) - tolower(*s2);
 
 }
 
 }
 
 
-kwsys_std::string SystemTools::GetLastSystemError()
+kwsys_stl::string SystemTools::GetLastSystemError()
 {
   int e = errno;
   return strerror(e);
   return unlink(source) != 0 ? false : true;
 }
 
+bool SystemTools::RemoveADirectory(const char* source)
+{
+  Directory dir;
+  dir.Load(source);
+  size_t fileNum;
+  for (fileNum = 0; fileNum <  dir.GetNumberOfFiles(); ++fileNum)
+    {
+    if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
+        strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
+      {
+      kwsys_stl::string fullPath = source;
+      fullPath += "/";
+      fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
+      if(SystemTools::FileIsDirectory(fullPath.c_str()))
+        {
+        if (!SystemTools::RemoveADirectory(fullPath.c_str()))
+          {
+          return false;
+          }
+        }
+      else
+        {
+        if(!SystemTools::RemoveFile(fullPath.c_str()))
+          {
+          return false;
+          }
+        }
+      }
+    }
+
+  return (Rmdir(source) == 0);
+}
 
 /**
  * Find the file the given name.  Searches the given path and then
  * the system search path.  Returns the full path to the file if it is
  * found.  Otherwise, the empty string is returned.
  */
-kwsys_std::string SystemTools::FindFile(const char* name, 
-                                       const kwsys_std::vector<kwsys_std::string>& userPaths)
+kwsys_stl::string SystemTools
+::FindFile(const char* name, 
+           const kwsys_stl::vector<kwsys_stl::string>& userPaths)
 {
-  // Add the system search path to our path.
-  kwsys_std::vector<kwsys_std::string> path = userPaths;
+  // Add the system search path to our path first
+  kwsys_stl::vector<kwsys_stl::string> path; 
+  SystemTools::GetPath(path, "CMAKE_FILE_PATH");
   SystemTools::GetPath(path);
-
-  kwsys_std::string tryPath;
-  for(kwsys_std::vector<kwsys_std::string>::const_iterator p = path.begin();
+  // now add the additional paths
+  path.insert(path.end(), userPaths.begin(), userPaths.end());
+  // now look for the file
+  kwsys_stl::string tryPath;
+  for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
       p != path.end(); ++p)
     {
     tryPath = *p;
  * the system search path.  Returns the full path to the executable if it is
  * found.  Otherwise, the empty string is returned.
  */
-kwsys_std::string SystemTools::FindProgram(const char* name,
-                                       const kwsys_std::vector<kwsys_std::string>& userPaths,
-                                       bool no_system_path)
+kwsys_stl::string SystemTools::FindProgram(
+  const char* name,
+  const kwsys_stl::vector<kwsys_stl::string>& userPaths,
+  bool no_system_path)
 {
   if(!name)
     {
     {
     return SystemTools::CollapseFullPath(name);
     }
-  kwsys_std::string tryPath = name;
+  kwsys_stl::string tryPath = name;
   tryPath += SystemTools::GetExecutableExtension();
   if(SystemTools::FileExists(tryPath.c_str()) &&
      !SystemTools::FileIsDirectory(tryPath.c_str()))
     {
     return SystemTools::CollapseFullPath(tryPath.c_str());
     }
-
+  kwsys_stl::vector<kwsys_stl::string> path;
+  SystemTools::GetPath(path, "CMAKE_PROGRAM_PATH");
   // Add the system search path to our path.
-  kwsys_std::vector<kwsys_std::string> path = userPaths;
   if (!no_system_path)
     {
     SystemTools::GetPath(path);
     }
-
-  for(kwsys_std::vector<kwsys_std::string>::const_iterator p = path.begin();
+  
+  // now add the additional paths
+  path.insert(path.end(), userPaths.begin(), userPaths.end());
+  
+  for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
       p != path.end(); ++p)
     {
     tryPath = *p;
  * the system search path.  Returns the full path to the library if it is
  * found.  Otherwise, the empty string is returned.
  */
-kwsys_std::string SystemTools::FindLibrary(const char* name,
-                                       const kwsys_std::vector<kwsys_std::string>& userPaths)
+kwsys_stl::string SystemTools
+::FindLibrary(const char* name,
+              const kwsys_stl::vector<kwsys_stl::string>& userPaths)
 {
   // See if the executable exists as written.
   if(SystemTools::FileExists(name) &&
     }
   
   // Add the system search path to our path.
-  kwsys_std::vector<kwsys_std::string> path = userPaths;
+  kwsys_stl::vector<kwsys_stl::string> path;
   SystemTools::GetPath(path);
-  
-  kwsys_std::string tryPath;
-  for(kwsys_std::vector<kwsys_std::string>::const_iterator p = path.begin();
+   // now add the additional paths
+  path.insert(path.end(), userPaths.begin(), userPaths.end());
+  kwsys_stl::string tryPath;
+  for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
       p != path.end(); ++p)
     {
-#if defined(_WIN32) && !defined(__CYGWIN__)
+#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
     tryPath = *p;
     tryPath += "/";
     tryPath += name;
     tryPath += ".lib";
-    if(SystemTools::FileExists(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath.c_str()) 
+       && !SystemTools::FileIsDirectory(tryPath.c_str()))
       {
       return SystemTools::CollapseFullPath(tryPath.c_str());
       }
     tryPath += "/lib";
     tryPath += name;
     tryPath += ".so";
-    if(SystemTools::FileExists(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath.c_str()) 
+       && !SystemTools::FileIsDirectory(tryPath.c_str()))
       {
       return SystemTools::CollapseFullPath(tryPath.c_str());
       }
     tryPath += "/lib";
     tryPath += name;
     tryPath += ".a";
-    if(SystemTools::FileExists(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath.c_str()) 
+       && !SystemTools::FileIsDirectory(tryPath.c_str()))
       {
       return SystemTools::CollapseFullPath(tryPath.c_str());
       }
     tryPath += "/lib";
     tryPath += name;
     tryPath += ".sl";
-    if(SystemTools::FileExists(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath.c_str()) 
+       && !SystemTools::FileIsDirectory(tryPath.c_str()))
       {
       return SystemTools::CollapseFullPath(tryPath.c_str());
       }
     tryPath += "/lib";
     tryPath += name;
     tryPath += ".dylib";
-    if(SystemTools::FileExists(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath.c_str()) 
+       && !SystemTools::FileIsDirectory(tryPath.c_str()))
+      {
+      return SystemTools::CollapseFullPath(tryPath.c_str());
+      }
+    tryPath = *p;
+    tryPath += "/lib";
+    tryPath += name;
+    tryPath += ".dll";
+    if(SystemTools::FileExists(tryPath.c_str()) 
+       && !SystemTools::FileIsDirectory(tryPath.c_str()))
       {
       return SystemTools::CollapseFullPath(tryPath.c_str());
       }
   return Chdir(dir);
 }
 
-kwsys_std::string SystemTools::GetCurrentWorkingDirectory()
+kwsys_stl::string SystemTools::GetCurrentWorkingDirectory()
 {
   char buf[2048];
-  kwsys_std::string path = Getcwd(buf, 2048);
-  return path;
+  const char* cwd = Getcwd(buf, 2048);
+  kwsys_stl::string path;
+  if ( cwd )
+    {
+    path = cwd;
+    }
+
+  return SystemTools::CollapseFullPath(path.c_str());
 }
 
-kwsys_std::string SystemTools::GetProgramPath(const char* in_name)
+kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
 {
-  kwsys_std::string dir, file;
+  kwsys_stl::string dir, file;
   SystemTools::SplitProgramPath(in_name, dir, file);
   return dir;
 }
 
 bool SystemTools::SplitProgramPath(const char* in_name,
-                                   kwsys_std::string& dir,
-                                   kwsys_std::string& file,
+                                   kwsys_stl::string& dir,
+                                   kwsys_stl::string& file,
                                    bool)
 {
   dir = in_name;
   
   if(!SystemTools::FileIsDirectory(dir.c_str()))
     {
-    kwsys_std::string::size_type slashPos = dir.rfind("/");
-    if(slashPos != kwsys_std::string::npos)
+    kwsys_stl::string::size_type slashPos = dir.rfind("/");
+    if(slashPos != kwsys_stl::string::npos)
       {
       file = dir.substr(slashPos+1);
       dir = dir.substr(0, slashPos);
       dir = "";
       }
     }
-  if((dir != "") && !SystemTools::FileIsDirectory(dir.c_str()))
+  if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
     {
-    kwsys_std::string oldDir = in_name;
+    kwsys_stl::string oldDir = in_name;
     SystemTools::ConvertToUnixSlashes(oldDir);
     dir = in_name;
     return false;
   return true;
 }
 
-kwsys_std::string SystemTools::CollapseFullPath(const char* in_relative)
+bool SystemTools::FindProgramPath(const char* argv0, 
+                                  kwsys_stl::string& pathOut,
+                                  kwsys_stl::string& errorMsg,
+                                  const char* exeName,
+                                  const char* buildDir,         
+                                  const char* installPrefix )
+{
+  kwsys_stl::vector<kwsys_stl::string> failures;
+  kwsys_stl::string self = argv0;
+  SystemTools::ConvertToUnixSlashes(self);
+  failures.push_back(argv0);
+  self = SystemTools::FindProgram(self.c_str());
+  if(!SystemTools::FileExists(self.c_str()))
+    {
+    if(buildDir)
+      {
+      kwsys_stl::string intdir = ".";
+#ifdef  CMAKE_INTDIR
+      intdir = CMAKE_INTDIR;
+#endif
+      self = buildDir;
+      self += "/bin/";
+      self += intdir;
+      self += "/";
+      self += exeName;
+      self += SystemTools::GetExecutableExtension();
+      }
+    }
+  if(installPrefix)
+    {
+    if(!SystemTools::FileExists(self.c_str()))
+      {
+      failures.push_back(self);
+      self = installPrefix;
+      self += "/bin/";
+      self +=  exeName;
+      }
+    }
+  if(!SystemTools::FileExists(self.c_str()))
+    {
+    failures.push_back(self);
+    kwsys_ios::ostringstream msg;
+    msg << "Can not find the command line program " << exeName << "\n";
+    msg << "  argv[0] = \"" << argv0 << "\"\n";
+    msg << "  Attempted paths:\n";
+    kwsys_stl::vector<kwsys_stl::string>::iterator i;
+    for(i=failures.begin(); i != failures.end(); ++i)
+      {
+      msg << "    \"" << i->c_str() << "\"\n";
+      }
+    errorMsg = msg.str();
+    return false;
+    }
+  pathOut = self;
+  return true;
+}
+
+
+kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
 {
   return SystemTools::CollapseFullPath(in_relative, 0);
 }
 
-kwsys_std::string SystemTools::CollapseFullPath(const char* in_relative,
-                                            const char* in_base)
+void SystemTools::AddTranslationPath(const char * a, const char * b)
 {
-  kwsys_std::string dir, file;
-  SystemTools::SplitProgramPath(in_relative, dir, file, false);
-  
-  // Save original working directory.
-  kwsys_std::string orig = SystemTools::GetCurrentWorkingDirectory();
+  kwsys_stl::string path_a = a;
+  kwsys_stl::string path_b = b;
+  SystemTools::ConvertToUnixSlashes(path_a);
+  SystemTools::ConvertToUnixSlashes(path_b);
+  // First check this is a directory path, since we don't want the table to
+  // grow too fat
+  if( SystemTools::FileIsDirectory( path_a.c_str() ) )
+    {
+    // Make sure the path is a full path and does not contain no '..'
+    if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..") 
+        == kwsys_stl::string::npos )
+      {
+      // Before inserting make sure path ends with '/'
+      path_a += '/'; path_b += '/';
+      if( !(path_a == path_b) )
+        {
+        SystemTools::TranslationMap->insert(
+          SystemToolsTranslationMap::value_type(path_a, path_b));
+        }
+      }
+    }
+}
+
+void SystemTools::AddKeepPath(const char* dir)
+{
+  kwsys_stl::string cdir = SystemTools::CollapseFullPath(dir);
+  SystemTools::AddTranslationPath(cdir.c_str(), dir);
+}
+
+void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
+{
+  // In case a file was specified we still have to go through this:
+  // Now convert any path found in the table back to the one desired:
+  kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
+  for(it  = SystemTools::TranslationMap->begin();
+      it != SystemTools::TranslationMap->end();
+      ++it )
+    {
+    // We need to check of the path is a substring of the other path
+    // But also check that the last character is a '/' otherwise we could
+    // have some weird case such as /tmp/VTK and /tmp/VTK-bin
+    if(path.size() > 1 && path[path.size()-1] != '/')
+      {
+      // Do not append '/' on a program name:
+      if( SystemTools::FileIsDirectory( path.c_str() ) )
+        {
+        path += "/";
+        }
+      }
+    if(path.find( it->first ) == 0)
+      {
+      path = path.replace( 0, it->first.size(), it->second);
+      }
+    }
+}
+
+kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative,
+                                                const char* in_base)
+{
+  static int initialized = 0;
+
+  kwsys_stl::string orig;
   
   // Change to base of relative path.
   if(in_base)
     {
+    // Save original working directory.
+    orig = SystemTools::GetCurrentWorkingDirectory();
     Chdir(in_base);
     }
   
-#ifdef _WIN32
-  // Follow relative path.
-  if(dir != "")
+  kwsys_stl::string dir, file;
+  SystemTools::SplitProgramPath(in_relative, dir, file, false);
+  if(dir.size() == 0 && 
+      in_relative && strlen(in_relative) > 0 &&
+      in_relative[0] == '/')
+     {
+     dir = "/";
+     }
+
+  // Resolve relative path.
+  kwsys_stl::string newDir;
+  if(!(dir == ""))
     {
-    Chdir(dir.c_str());
-    }
-  
-  // Get the resulting directory.
-  kwsys_std::string newDir = SystemTools::GetCurrentWorkingDirectory();
-  
-  // Add the file back on to the directory.
-  SystemTools::ConvertToUnixSlashes(newDir);
-#else
-# ifdef MAXPATHLEN
-  char resolved_name[MAXPATHLEN];
-# else
-#  ifdef PATH_MAX
-  char resolved_name[PATH_MAX];
-#  else
-  char resolved_name[5024];
-#  endif
-# endif
-  
-  // Resolve relative path.
-  kwsys_std::string newDir;
-  if(dir != "")
-    {
-    realpath(dir.c_str(), resolved_name);
-    newDir = resolved_name;
+    Realpath(dir.c_str(), newDir);    
     }
   else
     {
     newDir = SystemTools::GetCurrentWorkingDirectory();
     }
-#endif
-  
-  // Restore original working directory.
-  Chdir(orig.c_str());
+
+  if(in_base)
+    {
+    // Restore original working directory.
+    Chdir(orig.c_str());
+    }
   
   // Construct and return the full path.
-  kwsys_std::string newPath = newDir;
-  if(file != "")
+  kwsys_stl::string newPath = newDir;
+  if(!(file == ""))
     {
-    newPath += "/";
+    if(!(newDir.size() == 1 && newDir[0] ==  '/'))
+      {
+      newPath += "/";
+      }
     newPath += file;
     }
+
+  // If the table has never been initialized, add default path:
+  if(!initialized)
+    {
+    initialized = 1;
+    //Also add some good default one:
+    // This one should always be there it fix a bug on sgi
+    SystemTools::AddTranslationPath("/tmp_mnt/", "/");
+  
+    //This is a good default also:
+    SystemTools::AddKeepPath("/tmp/");
+    }
+
+  // Now we need to update the translation table with this potentially new path
+  SystemTools::AddTranslationPath(newPath.c_str(), in_relative);
+  SystemTools::CheckTranslationPath(newPath);
+
   return newPath;
 }
 
-bool SystemTools::Split(const char* str, kwsys_std::vector<kwsys_std::string>& lines)
+bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
 {
-  kwsys_std::string data(str);
-  kwsys_std::string::size_type lpos = 0;
+  kwsys_stl::string data(str);
+  kwsys_stl::string::size_type lpos = 0;
   while(lpos < data.length())
     {
-    kwsys_std::string::size_type rpos = data.find_first_of("\n", lpos);
-    if(rpos == kwsys_std::string::npos)
+    kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
+    if(rpos == kwsys_stl::string::npos)
       {
       // Line ends at end of string without a newline.
       lines.push_back(data.substr(lpos));
  * Return path of a full filename (no trailing slashes).
  * Warning: returned path is converted to Unix slashes format.
  */
-kwsys_std::string SystemTools::GetFilenamePath(const kwsys_std::string& filename)
+kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
 {
-  kwsys_std::string fn = filename;
+  kwsys_stl::string fn = filename;
   SystemTools::ConvertToUnixSlashes(fn);
   
-  kwsys_std::string::size_type slash_pos = fn.rfind("/");
-  if(slash_pos != kwsys_std::string::npos)
+  kwsys_stl::string::size_type slash_pos = fn.rfind("/");
+  if(slash_pos != kwsys_stl::string::npos)
     {
     return fn.substr(0, slash_pos);
     }
 /**
  * Return file name of a full filename (i.e. file name without path).
  */
-kwsys_std::string SystemTools::GetFilenameName(const kwsys_std::string& filename)
+kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
 {
-  kwsys_std::string fn = filename;
+  kwsys_stl::string fn = filename;
   SystemTools::ConvertToUnixSlashes(fn);
   
-  kwsys_std::string::size_type slash_pos = fn.rfind("/");
-  if(slash_pos != kwsys_std::string::npos)
+  kwsys_stl::string::size_type slash_pos = fn.rfind("/");
+  if(slash_pos != kwsys_stl::string::npos)
     {
     return fn.substr(slash_pos + 1);
     }
  * Return file extension of a full filename (dot included).
  * Warning: this is the longest extension (for example: .tar.gz)
  */
-kwsys_std::string SystemTools::GetFilenameExtension(const kwsys_std::string& filename)
+kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
 {
-  kwsys_std::string name = SystemTools::GetFilenameName(filename);
-  kwsys_std::string::size_type dot_pos = name.find(".");
-  if(dot_pos != kwsys_std::string::npos)
+  kwsys_stl::string name = SystemTools::GetFilenameName(filename);
+  kwsys_stl::string::size_type dot_pos = name.find(".");
+  if(dot_pos != kwsys_stl::string::npos)
     {
     return name.substr(dot_pos);
     }
     }
 }
 
+/**
+ * Return file extension of a full filename (dot included).
+ * Warning: this is the shortest extension (for example: .tar.gz)
+ */
+kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
+{
+  kwsys_stl::string name = SystemTools::GetFilenameName(filename);
+  kwsys_stl::string::size_type dot_pos = name.rfind(".");
+  if(dot_pos != kwsys_stl::string::npos)
+    {
+    return name.substr(dot_pos);
+    }
+  else
+    {
+    return "";
+    }
+}
 
 /**
  * Return file name without extension of a full filename (i.e. without path).
  * Warning: it considers the longest extension (for example: .tar.gz)
  */
-kwsys_std::string SystemTools::GetFilenameWithoutExtension(const kwsys_std::string& filename)
+kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
 {
-  kwsys_std::string name = SystemTools::GetFilenameName(filename);
-  kwsys_std::string::size_type dot_pos = name.find(".");
-  if(dot_pos != kwsys_std::string::npos)
+  kwsys_stl::string name = SystemTools::GetFilenameName(filename);
+  kwsys_stl::string::size_type dot_pos = name.find(".");
+  if(dot_pos != kwsys_stl::string::npos)
     {
     return name.substr(0, dot_pos);
     }
  * Warning: it considers the last extension (for example: removes .gz
  * from .tar.gz)
  */
-kwsys_std::string
-SystemTools::GetFilenameWithoutLastExtension(const kwsys_std::string& filename)
+kwsys_stl::string
+SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
 {
-  kwsys_std::string name = SystemTools::GetFilenameName(filename);
-  kwsys_std::string::size_type dot_pos = name.rfind(".");
-  if(dot_pos != kwsys_std::string::npos)
+  kwsys_stl::string name = SystemTools::GetFilenameName(filename);
+  kwsys_stl::string::size_type dot_pos = name.rfind(".");
+  if(dot_pos != kwsys_stl::string::npos)
     {
     return name.substr(0, dot_pos);
     }
 
 bool SystemTools::FileIsFullPath(const char* in_name)
 {
-  kwsys_std::string name = in_name;
-#if defined(_WIN32)
+  kwsys_stl::string name = in_name;
+#if defined(_WIN32) || defined(__CYGWIN__)
   // On Windows, the name must be at least two characters long.
   if(name.length() < 2)
     {
   return false;
 }
 
-void SystemTools::Glob(const char *directory, const char *regexp,
-                         kwsys_std::vector<kwsys_std::string>& files)
-{
-  Directory d;
-  RegularExpression reg(regexp);
-  
-  if (d.Load(directory))
-    {
-    size_t numf;
-        unsigned int i;
-    numf = d.GetNumberOfFiles();
-    for (i = 0; i < numf; i++)
-      {
-      kwsys_std::string fname = d.GetFile(i);
-      if (reg.find(fname))
-        {
-        files.push_back(fname);
-        }
-      }
-    }
-}
-
-
-void SystemTools::GlobDirs(const char *fullPath,
-                             kwsys_std::vector<kwsys_std::string>& files)
-{
-  kwsys_std::string path = fullPath;
-  kwsys_std::string::size_type pos = path.find("/*");
-  if(pos == kwsys_std::string::npos)
-    {
-    files.push_back(fullPath);
-    return;
-    }
-  kwsys_std::string startPath = path.substr(0, pos);
-  kwsys_std::string finishPath = path.substr(pos+2);
-
-  Directory d;
-  if (d.Load(startPath.c_str()))
-    {
-    for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
-      {
-      if((kwsys_std::string(d.GetFile(i)) != ".")
-         && (kwsys_std::string(d.GetFile(i)) != ".."))
-        {
-        kwsys_std::string fname = startPath;
-        fname +="/";
-        fname += d.GetFile(i);
-        if(SystemTools::FileIsDirectory(fname.c_str()))
-          {
-          fname += finishPath;
-          SystemTools::GlobDirs(fname.c_str(), files);
-          }
-        }
-      }
-    }
-}
-
-bool SystemTools::GetShortPath(const char* path, kwsys_std::string& shortPath)
+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
 #endif
 }
 
-bool SystemTools::SimpleGlob(const kwsys_std::string& glob, 
-                               kwsys_std::vector<kwsys_std::string>& files, 
-                               int type /* = 0 */)
+void SystemTools::SplitProgramFromArgs(const char* path, 
+                                       kwsys_stl::string& program, kwsys_stl::string& args)
 {
-  files.clear();
-  if ( glob[glob.size()-1] != '*' )
-    {
-    return false;
-    }
-  kwsys_std::string path = SystemTools::GetFilenamePath(glob);
-  kwsys_std::string ppath = SystemTools::GetFilenameName(glob);
-  ppath = ppath.substr(0, ppath.size()-1);
-  if ( path.size() == 0 )
-    {
-    path = "/";
-    }
-
-  bool res = false;
-  Directory d;
-  if (d.Load(path.c_str()))
-    {
-    for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
-      {
-      if((kwsys_std::string(d.GetFile(i)) != ".")
-         && (kwsys_std::string(d.GetFile(i)) != ".."))
-        {
-        kwsys_std::string fname = path;
-        if ( path[path.size()-1] != '/' )
-          {
-          fname +="/";
-          }
-        fname += d.GetFile(i);
-        kwsys_std::string sfname = d.GetFile(i);
-        if ( type > 0 && SystemTools::FileIsDirectory(fname.c_str()) )
-          {
-          continue;
-          }
-        if ( type < 0 && !SystemTools::FileIsDirectory(fname.c_str()) )
-          {
-          continue;
-          }
-        if ( sfname.size() >= ppath.size() && 
-             sfname.substr(0, ppath.size()) == 
-             ppath )
-          {
-          files.push_back(fname);
-          res = true;
-          }
-        }
-      }
-    }
-  return res;
-}
-
-
-void SystemTools::SplitProgramFromArgs(const char* path, 
-                                         kwsys_std::string& program, kwsys_std::string& args)
-{
+  // see if this is a full path to a program
+  // if so then set program to path and args to nothing
   if(SystemTools::FileExists(path))
     {
     program = path;
     args = "";
     return;
     }
-  kwsys_std::vector<kwsys_std::string> e;
-  kwsys_std::string findProg = SystemTools::FindProgram(path, e);
+  // Try to find the program in the path, note the program
+  // may have spaces in its name so we have to look for it 
+  kwsys_stl::vector<kwsys_stl::string> e;
+  kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
   if(findProg.size())
     {
     program = findProg;
     args = "";
     return;
     }
-  kwsys_std::string dir = path;
-  kwsys_std::string::size_type spacePos = dir.rfind(' ');
-  if(spacePos == kwsys_std::string::npos)
+
+  // Now try and peel off space separated chunks from the end of the string
+  // so the largest path possible is found allowing for spaces in the path
+  kwsys_stl::string dir = path;
+  kwsys_stl::string::size_type spacePos = dir.rfind(' ');
+  while(spacePos != kwsys_stl::string::npos)
     {
-    program = "";
-    args = "";
-    return;
-    }
-  while(spacePos != kwsys_std::string::npos)
-    {
-    kwsys_std::string tryProg = dir.substr(0, spacePos);
+    kwsys_stl::string tryProg = dir.substr(0, spacePos);
+    // See if the file exists
     if(SystemTools::FileExists(tryProg.c_str()))
       {
       program = tryProg;
+      // remove trailing spaces from program
+      kwsys_stl::string::size_type pos = program.size()-1;
+      while(program[pos] == ' ')
+        {
+        program.erase(pos);
+        pos--;
+        }
       args = dir.substr(spacePos, dir.size()-spacePos);
       return;
-      } 
+      }
+    // Now try and find the the program in the path 
     findProg = SystemTools::FindProgram(tryProg.c_str(), e);
     if(findProg.size())
       {
       program = findProg;
+      // remove trailing spaces from program
+      kwsys_stl::string::size_type pos = program.size()-1;
+      while(program[pos] == ' ')
+        {
+        program.erase(pos);
+        pos--;
+        }
       args = dir.substr(spacePos, dir.size()-spacePos);
       return;
       }
-    spacePos = dir.rfind(' ', spacePos--);
+    // move past the space for the next search
+    spacePos--;
+    spacePos = dir.rfind(' ', spacePos);
     }
+
   program = "";
   args = "";
 }
 
-kwsys_std::string SystemTools::GetCurrentDateTime(const char* format)
+kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
 {
   char buf[1024];
   time_t t;
   return buf;
 }
 
-kwsys_std::string SystemTools::MakeCindentifier(const char* s)
+kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
 {
-  kwsys_std::string str(s);
+  kwsys_stl::string str(s);
   if (str.find_first_of("0123456789") == 0)
     {
     str = "_" + str;
     }
 
-  kwsys_std::string permited_chars("_"
+  kwsys_stl::string permited_chars("_"
                              "abcdefghijklmnopqrstuvwxyz"
                              "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                              "0123456789");
-  kwsys_std::string::size_type pos = 0;
-  while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_std::string::npos)
+  kwsys_stl::string::size_type pos = 0;
+  while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
     {
     str[pos] = '_';
     }
 // Due to a buggy stream library on the HP and another on Mac OSX, we
 // need this very carefully written version of getline.  Returns true
 // if any data were read before the end-of-file was reached.
-bool SystemTools::GetLineFromStream(kwsys_std::istream& is, kwsys_std::string& line)
+bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, kwsys_stl::string& line,
+                                    bool *has_newline /* = 0 */)
 {
   const int bufferSize = 1024;
   char buffer[bufferSize];
   line = "";
   bool haveData = false;
+  if ( has_newline )
+    {
+    *has_newline = false;
+    }
 
   // If no characters are read from the stream, the end of file has
   // been reached.
     // reached.
     if(strlen(buffer) < static_cast<size_t>(is.gcount()))
       {
+      if ( has_newline )
+        {
+        *has_newline = true;
+        }
       break;
       }
 
     // The fail bit may be set.  Clear it.
-    is.clear(is.rdstate() & ~kwsys_std::ios::failbit);
+    is.clear(is.rdstate() & ~kwsys_ios::ios::failbit);
     }
   return haveData;
 }
 
+int SystemTools::GetTerminalWidth()
+{
+  int width = -1;
+#ifndef _WIN32
+  struct winsize ws;
+  char *columns; /* Unix98 environment variable */
+  if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
+    {
+    width = ws.ws_col;
+    }
+  if(!isatty(STDOUT_FILENO))
+    {
+    width = -1;
+    }
+  columns = getenv("COLUMNS");
+  if(columns && *columns)
+    {
+    long t;
+    char *endptr;
+    t = strtol(columns, &endptr, 0);
+    if(endptr && !*endptr && (t>0) && (t<1000))
+      {
+      width = (int)t;
+      }
+    }
+  if ( width < 9 )
+    {
+    width = -1;
+    }
+#endif
+  return width;
+}
+
+bool SystemTools::GetPermissions(const char* file, mode_t& mode)
+{
+  if ( !file )
+    {
+    return false;
+    }
+
+  struct stat st;
+  if ( stat(file, &st) < 0 )
+    {
+    return false;
+    }
+  mode = st.st_mode;
+  return true;
+}
+
+bool SystemTools::SetPermissions(const char* file, mode_t mode)
+{
+  if ( !file )
+    {
+    return false;
+    }
+  if ( !SystemTools::FileExists(file) )
+    {
+    return false;
+    }
+  if ( chmod(file, mode) < 0 )
+    {
+    return false;
+    }
+
+  return true;
+}
+
+kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
+{
+  if ( !fileOrDir || !*fileOrDir )
+    {
+    return "";
+    }
+  kwsys_stl::string res = fileOrDir;
+  SystemTools::ConvertToUnixSlashes(res);
+  kwsys_stl::string::size_type cc = res.size()-1;
+  if ( res[cc] == '/' )
+    {
+    cc --;
+    }
+  for ( ; cc > 0; cc -- )
+    {
+    if ( res[cc] == '/' )
+      {
+      break;
+      }
+    }
+  return res.substr(0, cc);
+}
+
+bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
+{
+  kwsys_stl::string subdir = cSubdir;
+  kwsys_stl::string dir = cDir;
+  SystemTools::ConvertToUnixSlashes(dir);
+  kwsys_stl::string path = subdir;
+  do
+    {
+    path = SystemTools::GetParentDirectory(path.c_str());
+    if ( dir == path )
+      {
+      return true;
+      }
+    }
+  while ( path.size() > dir.size() );
+  return false;
+}
+
+kwsys_stl::string SystemTools::FileExistsInParentDirectories(const char* fname,
+  const char* directory, const char* toplevel)
+{
+  kwsys_stl::string file = fname;
+  SystemTools::ConvertToUnixSlashes(file);
+  kwsys_stl::string dir = directory;
+  SystemTools::ConvertToUnixSlashes(dir);
+  while ( !dir.empty() )
+    {
+    kwsys_stl::string path = dir + "/" + file;
+    if ( SystemTools::FileExists(path.c_str()) )
+      {
+      return path;
+      }
+    if ( dir.size() < strlen(toplevel) )
+      {
+      break;
+      }
+    dir = SystemTools::GetParentDirectory(dir.c_str());
+    }
+  return "";
+}
+
+// These must NOT be initialized.  Default initialization to zero is
+// necessary.
+unsigned int SystemToolsManagerCount;
+SystemToolsTranslationMap *SystemTools::TranslationMap;
+
+// SystemToolsManager manages the SystemTools singleton.
+// SystemToolsManager should be included in any translation unit
+// that will use SystemTools or that implements the singleton
+// pattern. It makes sure that the SystemTools singleton is created
+// before and destroyed after all other singletons in CMake.
+
+SystemToolsManager::SystemToolsManager()
+{
+  if(++SystemToolsManagerCount == 1)
+    {
+    SystemTools::ClassInitialize();
+    }
+}
+
+SystemToolsManager::~SystemToolsManager()
+{
+  if(--SystemToolsManagerCount == 0)
+    {
+    SystemTools::ClassFinalize();
+    }
+}
+
+void SystemTools::ClassInitialize()
+{
+  SystemTools::TranslationMap = new SystemToolsTranslationMap;
+}
+
+void SystemTools::ClassFinalize()
+{
+  delete SystemTools::TranslationMap;
+}
+
+
+} // namespace KWSYS_NAMESPACE
+
 #if defined(_MSC_VER) && defined(_DEBUG)
 # include <crtdbg.h>
 # include <stdio.h>
 # include <stdlib.h>
+namespace KWSYS_NAMESPACE
+{
+
 static int SystemToolsDebugReport(int, char* message, int*)
 {
   fprintf(stderr, message);
   exit(1);
-  return 0;
 }
 void SystemTools::EnableMSVCDebugHook()
 {
     _CrtSetReportHook(SystemToolsDebugReport);
     }
 }
+
+} // namespace KWSYS_NAMESPACE
 #else
-void SystemTools::EnableMSVCDebugHook()
+namespace KWSYS_NAMESPACE
 {
-}
+void SystemTools::EnableMSVCDebugHook() {}
+} // namespace KWSYS_NAMESPACE
 #endif
 
-} // namespace KWSYS_NAMESPACE